You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2450 lines
84 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2012 CERN
  5. * Copyright (C) 1992-2020 KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. #include <fctsys.h>
  25. #include <kicad_string.h>
  26. #include <common.h>
  27. #include <build_version.h> // LEGACY_BOARD_FILE_VERSION
  28. #include <macros.h>
  29. #include <wildcards_and_files_ext.h>
  30. #include <base_units.h>
  31. #include <trace_helpers.h>
  32. #include <class_board.h>
  33. #include <class_module.h>
  34. #include <class_pcb_text.h>
  35. #include <class_dimension.h>
  36. #include <class_track.h>
  37. #include <class_zone.h>
  38. #include <class_drawsegment.h>
  39. #include <class_pcb_target.h>
  40. #include <class_edge_mod.h>
  41. #include <pcb_plot_params.h>
  42. #include <zones.h>
  43. #include <kicad_plugin.h>
  44. #include <pcb_parser.h>
  45. #include <pcbnew_settings.h>
  46. #include <wx/dir.h>
  47. #include <wx/filename.h>
  48. #include <wx/wfstream.h>
  49. #include <boost/ptr_container/ptr_map.hpp>
  50. #include <memory.h>
  51. #include <connectivity/connectivity_data.h>
  52. #include <convert_basic_shapes_to_polygon.h> // for enum RECT_CHAMFER_POSITIONS definition
  53. #include <kiface_i.h>
  54. #include <advanced_config.h> // for pad pin function and pad property feature management
  55. using namespace PCB_KEYS_T;
  56. ///> Removes empty nets (i.e. with node count equal zero) from net classes
  57. void filterNetClass( const BOARD& aBoard, NETCLASS& aNetClass )
  58. {
  59. auto connectivity = aBoard.GetConnectivity();
  60. for( NETCLASS::iterator it = aNetClass.begin(); it != aNetClass.end(); )
  61. {
  62. NETINFO_ITEM* netinfo = aBoard.FindNet( *it );
  63. if( netinfo && connectivity->GetNodeCount( netinfo->GetNet() ) <= 0 ) // hopefully there are no nets with negative
  64. aNetClass.Remove( it++ ); // node count, but you never know..
  65. else
  66. ++it;
  67. }
  68. }
  69. /**
  70. * FP_CACHE_ITEM
  71. * is helper class for creating a footprint library cache.
  72. *
  73. * The new footprint library design is a file path of individual module files
  74. * that contain a single module per file. This class is a helper only for the
  75. * footprint portion of the PLUGIN API, and only for the #PCB_IO plugin. It is
  76. * private to this implementation file so it is not placed into a header.
  77. */
  78. class FP_CACHE_ITEM
  79. {
  80. WX_FILENAME m_filename;
  81. std::unique_ptr<MODULE> m_module;
  82. public:
  83. FP_CACHE_ITEM( MODULE* aModule, const WX_FILENAME& aFileName );
  84. const WX_FILENAME& GetFileName() const { return m_filename; }
  85. const MODULE* GetModule() const { return m_module.get(); }
  86. };
  87. FP_CACHE_ITEM::FP_CACHE_ITEM( MODULE* aModule, const WX_FILENAME& aFileName ) :
  88. m_filename( aFileName ),
  89. m_module( aModule )
  90. { }
  91. typedef boost::ptr_map< wxString, FP_CACHE_ITEM > MODULE_MAP;
  92. typedef MODULE_MAP::iterator MODULE_ITER;
  93. typedef MODULE_MAP::const_iterator MODULE_CITER;
  94. class FP_CACHE
  95. {
  96. PCB_IO* m_owner; // Plugin object that owns the cache.
  97. wxFileName m_lib_path; // The path of the library.
  98. wxString m_lib_raw_path; // For quick comparisons.
  99. MODULE_MAP m_modules; // Map of footprint file name per MODULE*.
  100. bool m_cache_dirty; // Stored separately because it's expensive to check
  101. // m_cache_timestamp against all the files.
  102. long long m_cache_timestamp; // A hash of the timestamps for all the footprint
  103. // files.
  104. public:
  105. FP_CACHE( PCB_IO* aOwner, const wxString& aLibraryPath );
  106. wxString GetPath() const { return m_lib_raw_path; }
  107. bool IsWritable() const { return m_lib_path.IsOk() && m_lib_path.IsDirWritable(); }
  108. bool Exists() const { return m_lib_path.IsOk() && m_lib_path.DirExists(); }
  109. MODULE_MAP& GetModules() { return m_modules; }
  110. // Most all functions in this class throw IO_ERROR exceptions. There are no
  111. // error codes nor user interface calls from here, nor in any PLUGIN.
  112. // Catch these exceptions higher up please.
  113. /**
  114. * Function Save
  115. * Save the footprint cache or a single module from it to disk
  116. *
  117. * @param aModule if set, save only this module, otherwise, save the full library
  118. */
  119. void Save( MODULE* aModule = NULL );
  120. void Load();
  121. void Remove( const wxString& aFootprintName );
  122. /**
  123. * Function GetTimestamp
  124. * Generate a timestamp representing all source files in the cache (including the
  125. * parent directory).
  126. * Timestamps should not be considered ordered. They either match or they don't.
  127. */
  128. static long long GetTimestamp( const wxString& aLibPath );
  129. /**
  130. * Function IsModified
  131. * Return true if the cache is not up-to-date.
  132. */
  133. bool IsModified();
  134. /**
  135. * Function IsPath
  136. * checks if \a aPath is the same as the current cache path.
  137. *
  138. * This tests paths by converting \a aPath using the native separators. Internally
  139. * #FP_CACHE stores the current path using native separators. This prevents path
  140. * miscompares on Windows due to the fact that paths can be stored with / instead of \\
  141. * in the footprint library table.
  142. *
  143. * @param aPath is the library path to test against.
  144. * @return true if \a aPath is the same as the cache path.
  145. */
  146. bool IsPath( const wxString& aPath ) const;
  147. };
  148. FP_CACHE::FP_CACHE( PCB_IO* aOwner, const wxString& aLibraryPath )
  149. {
  150. m_owner = aOwner;
  151. m_lib_raw_path = aLibraryPath;
  152. m_lib_path.SetPath( aLibraryPath );
  153. m_cache_timestamp = 0;
  154. m_cache_dirty = true;
  155. }
  156. void FP_CACHE::Save( MODULE* aModule )
  157. {
  158. m_cache_timestamp = 0;
  159. if( !m_lib_path.DirExists() && !m_lib_path.Mkdir() )
  160. {
  161. THROW_IO_ERROR( wxString::Format( _( "Cannot create footprint library path \"%s\"" ),
  162. m_lib_raw_path ) );
  163. }
  164. if( !m_lib_path.IsDirWritable() )
  165. {
  166. THROW_IO_ERROR( wxString::Format( _( "Footprint library path \"%s\" is read only" ),
  167. m_lib_raw_path ) );
  168. }
  169. for( MODULE_ITER it = m_modules.begin(); it != m_modules.end(); ++it )
  170. {
  171. if( aModule && aModule != it->second->GetModule() )
  172. continue;
  173. WX_FILENAME fn = it->second->GetFileName();
  174. wxString tempFileName =
  175. #ifdef USE_TMP_FILE
  176. wxFileName::CreateTempFileName( fn.GetPath() );
  177. #else
  178. fn.GetFullPath();
  179. #endif
  180. // Allow file output stream to go out of scope to close the file stream before
  181. // renaming the file.
  182. {
  183. wxLogTrace( traceKicadPcbPlugin, wxT( "Creating temporary library file %s" ),
  184. GetChars( tempFileName ) );
  185. FILE_OUTPUTFORMATTER formatter( tempFileName );
  186. m_owner->SetOutputFormatter( &formatter );
  187. m_owner->Format( (BOARD_ITEM*) it->second->GetModule() );
  188. }
  189. #ifdef USE_TMP_FILE
  190. wxRemove( fn.GetFullPath() ); // it is not an error if this does not exist
  191. // Even on linux you can see an _intermittent_ error when calling wxRename(),
  192. // and it is fully inexplicable. See if this dodges the error.
  193. wxMilliSleep( 250L );
  194. if( !wxRenameFile( tempFileName, fn.GetFullPath() ) )
  195. {
  196. wxString msg = wxString::Format(
  197. _( "Cannot rename temporary file \"%s\" to footprint library file \"%s\"" ),
  198. GetChars( tempFileName ),
  199. GetChars( fn.GetFullPath() )
  200. );
  201. THROW_IO_ERROR( msg );
  202. }
  203. #endif
  204. m_cache_timestamp += fn.GetTimestamp();
  205. }
  206. m_cache_timestamp += m_lib_path.GetModificationTime().GetValue().GetValue();
  207. // If we've saved the full cache, we clear the dirty flag.
  208. if( !aModule )
  209. m_cache_dirty = false;
  210. }
  211. void FP_CACHE::Load()
  212. {
  213. m_cache_dirty = false;
  214. m_cache_timestamp = 0;
  215. wxDir dir( m_lib_raw_path );
  216. if( !dir.IsOpened() )
  217. {
  218. wxString msg = wxString::Format( _( "Footprint library path '%s' does not exist "
  219. "(or is not a directory)." ),
  220. m_lib_raw_path );
  221. THROW_IO_ERROR( msg );
  222. }
  223. wxString fullName;
  224. wxString fileSpec = wxT( "*." ) + KiCadFootprintFileExtension;
  225. // wxFileName construction is egregiously slow. Construct it once and just swap out
  226. // the filename thereafter.
  227. WX_FILENAME fn( m_lib_raw_path, wxT( "dummyName" ) );
  228. if( dir.GetFirst( &fullName, fileSpec ) )
  229. {
  230. wxString cacheError;
  231. do
  232. {
  233. fn.SetFullName( fullName );
  234. // Queue I/O errors so only files that fail to parse don't get loaded.
  235. try
  236. {
  237. FILE_LINE_READER reader( fn.GetFullPath() );
  238. m_owner->m_parser->SetLineReader( &reader );
  239. MODULE* footprint = (MODULE*) m_owner->m_parser->Parse();
  240. wxString fpName = fn.GetName();
  241. footprint->SetFPID( LIB_ID( wxEmptyString, fpName ) );
  242. m_modules.insert( fpName, new FP_CACHE_ITEM( footprint, fn ) );
  243. m_cache_timestamp += fn.GetTimestamp();
  244. }
  245. catch( const IO_ERROR& ioe )
  246. {
  247. if( !cacheError.IsEmpty() )
  248. cacheError += "\n\n";
  249. cacheError += ioe.What();
  250. }
  251. } while( dir.GetNext( &fullName ) );
  252. if( !cacheError.IsEmpty() )
  253. THROW_IO_ERROR( cacheError );
  254. }
  255. }
  256. void FP_CACHE::Remove( const wxString& aFootprintName )
  257. {
  258. MODULE_CITER it = m_modules.find( aFootprintName );
  259. if( it == m_modules.end() )
  260. {
  261. wxString msg = wxString::Format( _( "library \"%s\" has no footprint \"%s\" to delete" ),
  262. m_lib_raw_path,
  263. aFootprintName );
  264. THROW_IO_ERROR( msg );
  265. }
  266. // Remove the module from the cache and delete the module file from the library.
  267. wxString fullPath = it->second->GetFileName().GetFullPath();
  268. m_modules.erase( aFootprintName );
  269. wxRemoveFile( fullPath );
  270. }
  271. bool FP_CACHE::IsPath( const wxString& aPath ) const
  272. {
  273. return aPath == m_lib_raw_path;
  274. }
  275. bool FP_CACHE::IsModified()
  276. {
  277. m_cache_dirty = m_cache_dirty || GetTimestamp( m_lib_path.GetFullPath() ) != m_cache_timestamp;
  278. return m_cache_dirty;
  279. }
  280. long long FP_CACHE::GetTimestamp( const wxString& aLibPath )
  281. {
  282. wxString fileSpec = wxT( "*." ) + KiCadFootprintFileExtension;
  283. return TimestampDir( aLibPath, fileSpec );
  284. }
  285. void PCB_IO::Save( const wxString& aFileName, BOARD* aBoard, const PROPERTIES* aProperties )
  286. {
  287. LOCALE_IO toggle; // toggles on, then off, the C locale.
  288. init( aProperties );
  289. m_board = aBoard; // after init()
  290. // Prepare net mapping that assures that net codes saved in a file are consecutive integers
  291. m_mapping->SetBoard( aBoard );
  292. FILE_OUTPUTFORMATTER formatter( aFileName );
  293. m_out = &formatter; // no ownership
  294. m_out->Print( 0, "(kicad_pcb (version %d) (host pcbnew %s)\n", SEXPR_BOARD_FILE_VERSION,
  295. formatter.Quotew( GetBuildVersion() ).c_str() );
  296. Format( aBoard, 1 );
  297. m_out->Print( 0, ")\n" );
  298. }
  299. BOARD_ITEM* PCB_IO::Parse( const wxString& aClipboardSourceInput )
  300. {
  301. std::string input = TO_UTF8( aClipboardSourceInput );
  302. STRING_LINE_READER reader( input, wxT( "clipboard" ) );
  303. m_parser->SetLineReader( &reader );
  304. try
  305. {
  306. return m_parser->Parse();
  307. }
  308. catch( const PARSE_ERROR& parse_error )
  309. {
  310. if( m_parser->IsTooRecent() )
  311. throw FUTURE_FORMAT_ERROR( parse_error, m_parser->GetRequiredVersion() );
  312. else
  313. throw;
  314. }
  315. }
  316. void PCB_IO::Format( BOARD_ITEM* aItem, int aNestLevel ) const
  317. {
  318. LOCALE_IO toggle; // public API function, perform anything convenient for caller
  319. switch( aItem->Type() )
  320. {
  321. case PCB_T:
  322. format( static_cast<BOARD*>( aItem ), aNestLevel );
  323. break;
  324. case PCB_DIMENSION_T:
  325. format( static_cast<DIMENSION*>( aItem ), aNestLevel );
  326. break;
  327. case PCB_LINE_T:
  328. format( static_cast<DRAWSEGMENT*>( aItem ), aNestLevel );
  329. break;
  330. case PCB_MODULE_EDGE_T:
  331. format( static_cast<EDGE_MODULE*>( aItem ), aNestLevel );
  332. break;
  333. case PCB_TARGET_T:
  334. format( static_cast<PCB_TARGET*>( aItem ), aNestLevel );
  335. break;
  336. case PCB_MODULE_T:
  337. format( static_cast<MODULE*>( aItem ), aNestLevel );
  338. break;
  339. case PCB_PAD_T:
  340. format( static_cast<D_PAD*>( aItem ), aNestLevel );
  341. break;
  342. case PCB_TEXT_T:
  343. format( static_cast<TEXTE_PCB*>( aItem ), aNestLevel );
  344. break;
  345. case PCB_MODULE_TEXT_T:
  346. format( static_cast<TEXTE_MODULE*>( aItem ), aNestLevel );
  347. break;
  348. case PCB_TRACE_T:
  349. case PCB_ARC_T:
  350. case PCB_VIA_T:
  351. format( static_cast<TRACK*>( aItem ), aNestLevel );
  352. break;
  353. case PCB_MODULE_ZONE_AREA_T:
  354. case PCB_ZONE_AREA_T:
  355. format( static_cast<ZONE_CONTAINER*>( aItem ), aNestLevel );
  356. break;
  357. default:
  358. wxFAIL_MSG( wxT( "Cannot format item " ) + aItem->GetClass() );
  359. }
  360. }
  361. void PCB_IO::formatLayer( const BOARD_ITEM* aItem ) const
  362. {
  363. if( m_ctl & CTL_STD_LAYER_NAMES )
  364. {
  365. PCB_LAYER_ID layer = aItem->GetLayer();
  366. // English layer names should never need quoting.
  367. m_out->Print( 0, " (layer %s)", TO_UTF8( BOARD::GetStandardLayerName( layer ) ) );
  368. }
  369. else
  370. m_out->Print( 0, " (layer %s)", m_out->Quotew( aItem->GetLayerName() ).c_str() );
  371. }
  372. void PCB_IO::formatSetup( BOARD* aBoard, int aNestLevel ) const
  373. {
  374. const BOARD_DESIGN_SETTINGS& dsnSettings = aBoard->GetDesignSettings();
  375. // Setup
  376. m_out->Print( aNestLevel, "(setup\n" );
  377. // Save the board physical stackup structure
  378. BOARD_STACKUP& stackup = aBoard->GetDesignSettings().GetStackupDescriptor();
  379. if( aBoard->GetDesignSettings().m_HasStackup )
  380. stackup.FormatBoardStackup( m_out,aBoard, aNestLevel+1 );
  381. // Save current default track width, for compatibility with older Pcbnew version;
  382. m_out->Print( aNestLevel+1, "(last_trace_width %s)\n",
  383. FormatInternalUnits( dsnSettings.GetCurrentTrackWidth() ).c_str() );
  384. // Save custom track widths list (the first is not saved here: it's the netclass value)
  385. for( unsigned ii = 1; ii < dsnSettings.m_TrackWidthList.size(); ii++ )
  386. {
  387. m_out->Print( aNestLevel+1, "(user_trace_width %s)\n",
  388. FormatInternalUnits( dsnSettings.m_TrackWidthList[ii] ).c_str() );
  389. }
  390. m_out->Print( aNestLevel+1, "(trace_clearance %s)\n",
  391. FormatInternalUnits( dsnSettings.GetDefault()->GetClearance() ).c_str() );
  392. // ZONE_SETTINGS
  393. m_out->Print( aNestLevel+1, "(zone_clearance %s)\n",
  394. FormatInternalUnits( aBoard->GetZoneSettings().m_ZoneClearance ).c_str() );
  395. m_out->Print( aNestLevel+1, "(zone_45_only %s)\n",
  396. aBoard->GetZoneSettings().m_Zone_45_Only ? "yes" : "no" );
  397. m_out->Print( aNestLevel+1, "(trace_min %s)\n",
  398. FormatInternalUnits( dsnSettings.m_TrackMinWidth ).c_str() );
  399. m_out->Print( aNestLevel+1, "(clearance_min %s)\n",
  400. FormatInternalUnits( dsnSettings.m_MinClearance ).c_str() );
  401. m_out->Print( aNestLevel+1, "(via_min_annulus %s)\n",
  402. FormatInternalUnits( dsnSettings.m_ViasMinAnnulus ).c_str() );
  403. m_out->Print( aNestLevel+1, "(via_min_size %s)\n",
  404. FormatInternalUnits( dsnSettings.m_ViasMinSize ).c_str() );
  405. m_out->Print( aNestLevel+1, "(through_hole_min %s)\n",
  406. FormatInternalUnits( dsnSettings.m_MinThroughDrill ).c_str() );
  407. m_out->Print( aNestLevel+1, "(hole_to_hole_min %s)\n",
  408. FormatInternalUnits( dsnSettings.m_HoleToHoleMin ).c_str() );
  409. // Save current default via size, for compatibility with older Pcbnew version;
  410. m_out->Print( aNestLevel+1, "(via_size %s)\n",
  411. FormatInternalUnits( dsnSettings.GetDefault()->GetViaDiameter() ).c_str() );
  412. m_out->Print( aNestLevel+1, "(via_drill %s)\n",
  413. FormatInternalUnits( dsnSettings.GetDefault()->GetViaDrill() ).c_str() );
  414. // Save custom via dimensions list (the first is not saved here: it's the netclass value)
  415. for( unsigned ii = 1; ii < dsnSettings.m_ViasDimensionsList.size(); ii++ )
  416. m_out->Print( aNestLevel+1, "(user_via %s %s)\n",
  417. FormatInternalUnits( dsnSettings.m_ViasDimensionsList[ii].m_Diameter ).c_str(),
  418. FormatInternalUnits( dsnSettings.m_ViasDimensionsList[ii].m_Drill ).c_str() );
  419. // Save custom diff-pair dimensions (the first is not saved here: it's the netclass value)
  420. for( unsigned ii = 1; ii < dsnSettings.m_DiffPairDimensionsList.size(); ii++ )
  421. {
  422. m_out->Print( aNestLevel+1, "(user_diff_pair %s %s %s)\n",
  423. FormatInternalUnits( dsnSettings.m_DiffPairDimensionsList[ii].m_Width ).c_str(),
  424. FormatInternalUnits( dsnSettings.m_DiffPairDimensionsList[ii].m_Gap ).c_str(),
  425. FormatInternalUnits( dsnSettings.m_DiffPairDimensionsList[ii].m_ViaGap ).c_str() );
  426. }
  427. // for old versions compatibility:
  428. if( dsnSettings.m_BlindBuriedViaAllowed )
  429. m_out->Print( aNestLevel+1, "(blind_buried_vias_allowed yes)\n" );
  430. m_out->Print( aNestLevel+1, "(uvia_size %s)\n",
  431. FormatInternalUnits( dsnSettings.GetDefault()->GetuViaDiameter() ).c_str() );
  432. m_out->Print( aNestLevel+1, "(uvia_drill %s)\n",
  433. FormatInternalUnits( dsnSettings.GetDefault()->GetuViaDrill() ).c_str() );
  434. m_out->Print( aNestLevel+1, "(uvias_allowed %s)\n",
  435. ( dsnSettings.m_MicroViasAllowed ) ? "yes" : "no" );
  436. m_out->Print( aNestLevel+1, "(uvia_min_size %s)\n",
  437. FormatInternalUnits( dsnSettings.m_MicroViasMinSize ).c_str() );
  438. m_out->Print( aNestLevel+1, "(uvia_min_drill %s)\n",
  439. FormatInternalUnits( dsnSettings.m_MicroViasMinDrill ).c_str() );
  440. m_out->Print( aNestLevel+1, "(max_error %s)\n",
  441. FormatInternalUnits( dsnSettings.m_MaxError ).c_str() );
  442. // Store this option only if it is not the legacy option:
  443. if( dsnSettings.m_ZoneUseNoOutlineInFill )
  444. m_out->Print( aNestLevel+1, "(filled_areas_thickness no)\n" );
  445. formatDefaults( dsnSettings, aNestLevel+1 );
  446. m_out->Print( aNestLevel+1, "(pad_size %s %s)\n",
  447. FormatInternalUnits( dsnSettings.m_Pad_Master.GetSize().x ).c_str(),
  448. FormatInternalUnits( dsnSettings.m_Pad_Master.GetSize().y ).c_str() );
  449. m_out->Print( aNestLevel+1, "(pad_drill %s)\n",
  450. FormatInternalUnits( dsnSettings.m_Pad_Master.GetDrillSize().x ).c_str() );
  451. m_out->Print( aNestLevel+1, "(pad_to_mask_clearance %s)\n",
  452. FormatInternalUnits( dsnSettings.m_SolderMaskMargin ).c_str() );
  453. if( dsnSettings.m_SolderMaskMinWidth )
  454. m_out->Print( aNestLevel+1, "(solder_mask_min_width %s)\n",
  455. FormatInternalUnits( dsnSettings.m_SolderMaskMinWidth ).c_str() );
  456. if( dsnSettings.m_SolderPasteMargin != 0 )
  457. m_out->Print( aNestLevel+1, "(pad_to_paste_clearance %s)\n",
  458. FormatInternalUnits( dsnSettings.m_SolderPasteMargin ).c_str() );
  459. if( dsnSettings.m_SolderPasteMarginRatio != 0 )
  460. m_out->Print( aNestLevel+1, "(pad_to_paste_clearance_ratio %s)\n",
  461. Double2Str( dsnSettings.m_SolderPasteMarginRatio ).c_str() );
  462. m_out->Print( aNestLevel+1, "(aux_axis_origin %s %s)\n",
  463. FormatInternalUnits( aBoard->GetAuxOrigin().x ).c_str(),
  464. FormatInternalUnits( aBoard->GetAuxOrigin().y ).c_str() );
  465. if( aBoard->GetGridOrigin().x || aBoard->GetGridOrigin().y )
  466. m_out->Print( aNestLevel+1, "(grid_origin %s %s)\n",
  467. FormatInternalUnits( aBoard->GetGridOrigin().x ).c_str(),
  468. FormatInternalUnits( aBoard->GetGridOrigin().y ).c_str() );
  469. m_out->Print( aNestLevel+1, "(visible_elements %X)\n",
  470. dsnSettings.GetVisibleElements() );
  471. aBoard->GetPlotOptions().Format( m_out, aNestLevel+1 );
  472. m_out->Print( aNestLevel, ")\n\n" );
  473. }
  474. void PCB_IO::formatDefaults( const BOARD_DESIGN_SETTINGS& aSettings, int aNestLevel ) const
  475. {
  476. m_out->Print( aNestLevel, "(defaults\n" );
  477. m_out->Print( aNestLevel+1, "(edge_clearance %s)\n",
  478. FormatInternalUnits( aSettings.m_CopperEdgeClearance ).c_str() );
  479. m_out->Print( aNestLevel+1, "(edge_cuts_line_width %s)\n",
  480. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_EDGES ] ).c_str() );
  481. m_out->Print( aNestLevel+1, "(courtyard_line_width %s)\n",
  482. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_COURTYARD ] ).c_str() );
  483. m_out->Print( aNestLevel+1, "(copper_line_width %s)\n",
  484. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_COPPER ] ).c_str() );
  485. m_out->Print( aNestLevel+1, "(copper_text_dims (size %s %s) (thickness %s)%s%s)\n",
  486. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_COPPER ].x ).c_str(),
  487. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_COPPER ].y ).c_str(),
  488. FormatInternalUnits( aSettings.m_TextThickness[ LAYER_CLASS_COPPER ] ).c_str(),
  489. aSettings.m_TextItalic[ LAYER_CLASS_COPPER ] ? " italic" : "",
  490. aSettings.m_TextUpright[ LAYER_CLASS_COPPER ] ? " keep_upright" : "" );
  491. m_out->Print( aNestLevel+1, "(silk_line_width %s)\n",
  492. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_SILK ] ).c_str() );
  493. m_out->Print( aNestLevel+1, "(silk_text_dims (size %s %s) (thickness %s)%s%s)\n",
  494. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_SILK ].x ).c_str(),
  495. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_SILK ].y ).c_str(),
  496. FormatInternalUnits( aSettings.m_TextThickness[ LAYER_CLASS_SILK ] ).c_str(),
  497. aSettings.m_TextItalic[ LAYER_CLASS_SILK ] ? " italic" : "",
  498. aSettings.m_TextUpright[ LAYER_CLASS_SILK ] ? " keep_upright" : "" );
  499. m_out->Print( aNestLevel+1, "(fab_layers_line_width %s)\n",
  500. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_FAB ] ).c_str() );
  501. m_out->Print( aNestLevel+1, "(fab_layers_text_dims (size %s %s) (thickness %s)%s%s)\n",
  502. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_FAB ].x ).c_str(),
  503. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_FAB ].y ).c_str(),
  504. FormatInternalUnits( aSettings.m_TextThickness[ LAYER_CLASS_FAB ] ).c_str(),
  505. aSettings.m_TextItalic[ LAYER_CLASS_OTHERS ] ? " italic" : "",
  506. aSettings.m_TextUpright[ LAYER_CLASS_OTHERS ] ? " keep_upright" : "" );
  507. m_out->Print( aNestLevel+1, "(other_layers_line_width %s)\n",
  508. FormatInternalUnits( aSettings.m_LineThickness[ LAYER_CLASS_OTHERS ] ).c_str() );
  509. m_out->Print( aNestLevel+1, "(other_layers_text_dims (size %s %s) (thickness %s)%s%s)\n",
  510. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_OTHERS ].x ).c_str(),
  511. FormatInternalUnits( aSettings.m_TextSize[ LAYER_CLASS_OTHERS ].y ).c_str(),
  512. FormatInternalUnits( aSettings.m_TextThickness[ LAYER_CLASS_OTHERS ] ).c_str(),
  513. aSettings.m_TextItalic[ LAYER_CLASS_OTHERS ] ? " italic" : "",
  514. aSettings.m_TextUpright[ LAYER_CLASS_OTHERS ] ? " keep_upright" : "" );
  515. m_out->Print( aNestLevel+1, "(dimension_units %d)\n", aSettings.m_DimensionUnits );
  516. m_out->Print( aNestLevel+1, "(dimension_precision %d)\n", aSettings.m_DimensionPrecision );
  517. m_out->Print( aNestLevel, ")\n" );
  518. }
  519. void PCB_IO::formatGeneral( BOARD* aBoard, int aNestLevel ) const
  520. {
  521. const BOARD_DESIGN_SETTINGS& dsnSettings = aBoard->GetDesignSettings();
  522. m_out->Print( 0, "\n" );
  523. m_out->Print( aNestLevel, "(general\n" );
  524. // Write Bounding box info
  525. m_out->Print( aNestLevel+1, "(thickness %s)\n",
  526. FormatInternalUnits( dsnSettings.GetBoardThickness() ).c_str() );
  527. m_out->Print( aNestLevel+1, "(drawings %u)\n", (unsigned)aBoard->Drawings().size() );
  528. m_out->Print( aNestLevel + 1, "(tracks %u)\n", (unsigned)aBoard->Tracks().size() );
  529. m_out->Print( aNestLevel + 1, "(modules %u)\n", (unsigned)aBoard->Modules().size() );
  530. m_out->Print( aNestLevel+1, "(nets %d)\n", m_mapping->GetSize() );
  531. m_out->Print( aNestLevel, ")\n\n" );
  532. aBoard->GetPageSettings().Format( m_out, aNestLevel, m_ctl );
  533. aBoard->GetTitleBlock().Format( m_out, aNestLevel, m_ctl );
  534. }
  535. void PCB_IO::formatBoardLayers( BOARD* aBoard, int aNestLevel ) const
  536. {
  537. m_out->Print( aNestLevel, "(layers\n" );
  538. // Save only the used copper layers from front to back.
  539. LSET visible_layers = aBoard->GetVisibleLayers();
  540. for( LSEQ cu = aBoard->GetEnabledLayers().CuStack(); cu; ++cu )
  541. {
  542. PCB_LAYER_ID layer = *cu;
  543. m_out->Print( aNestLevel+1, "(%d %s %s", layer,
  544. m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str(),
  545. LAYER::ShowType( aBoard->GetLayerType( layer ) ) );
  546. if( !visible_layers[layer] )
  547. m_out->Print( 0, " hide" );
  548. m_out->Print( 0, ")\n" );
  549. }
  550. // Save used non-copper layers in the order they are defined.
  551. // desired sequence for non Cu BOARD layers.
  552. static const PCB_LAYER_ID non_cu[] =
  553. {
  554. B_Adhes, // 32
  555. F_Adhes,
  556. B_Paste,
  557. F_Paste,
  558. B_SilkS,
  559. F_SilkS,
  560. B_Mask,
  561. F_Mask,
  562. Dwgs_User,
  563. Cmts_User,
  564. Eco1_User,
  565. Eco2_User,
  566. Edge_Cuts,
  567. Margin,
  568. B_CrtYd,
  569. F_CrtYd,
  570. B_Fab,
  571. F_Fab
  572. };
  573. for( LSEQ seq = aBoard->GetEnabledLayers().Seq( non_cu, arrayDim( non_cu ) ); seq; ++seq )
  574. {
  575. PCB_LAYER_ID layer = *seq;
  576. m_out->Print( aNestLevel+1, "(%d %s user", layer,
  577. m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str() );
  578. if( !visible_layers[layer] )
  579. m_out->Print( 0, " hide" );
  580. m_out->Print( 0, ")\n" );
  581. }
  582. m_out->Print( aNestLevel, ")\n\n" );
  583. }
  584. void PCB_IO::formatNetInformation( BOARD* aBoard, int aNestLevel ) const
  585. {
  586. const BOARD_DESIGN_SETTINGS& dsnSettings = aBoard->GetDesignSettings();
  587. for( NETINFO_ITEM* net : *m_mapping )
  588. {
  589. m_out->Print( aNestLevel, "(net %d %s)\n",
  590. m_mapping->Translate( net->GetNet() ),
  591. m_out->Quotew( net->GetNetname() ).c_str() );
  592. }
  593. m_out->Print( 0, "\n" );
  594. // Save the default net class first.
  595. NETCLASS defaultNC = *dsnSettings.GetDefault();
  596. filterNetClass( *aBoard, defaultNC ); // Remove empty nets (from a copy of a netclass)
  597. defaultNC.Format( m_out, aNestLevel, m_ctl );
  598. // Save the rest of the net classes alphabetically.
  599. for( const auto& it : dsnSettings.m_NetClasses )
  600. {
  601. NETCLASS netclass = *it.second;
  602. filterNetClass( *aBoard, netclass ); // Remove empty nets (from a copy of a netclass)
  603. netclass.Format( m_out, aNestLevel, m_ctl );
  604. }
  605. }
  606. void PCB_IO::formatHeader( BOARD* aBoard, int aNestLevel ) const
  607. {
  608. formatGeneral( aBoard, aNestLevel );
  609. // Layers list.
  610. formatBoardLayers( aBoard, aNestLevel );
  611. // Setup
  612. formatSetup( aBoard, aNestLevel );
  613. // Save net codes and names
  614. formatNetInformation( aBoard, aNestLevel );
  615. }
  616. void PCB_IO::format( BOARD* aBoard, int aNestLevel ) const
  617. {
  618. formatHeader( aBoard, aNestLevel );
  619. // Save the modules.
  620. for( auto module : aBoard->Modules() )
  621. {
  622. Format( module, aNestLevel );
  623. m_out->Print( 0, "\n" );
  624. }
  625. // Save the graphical items on the board (not owned by a module)
  626. for( auto item : aBoard->Drawings() )
  627. Format( item, aNestLevel );
  628. if( aBoard->Drawings().size() )
  629. m_out->Print( 0, "\n" );
  630. // Do not save MARKER_PCBs, they can be regenerated easily.
  631. // Save the tracks and vias.
  632. for( auto track : aBoard->Tracks() )
  633. Format( track, aNestLevel );
  634. if( aBoard->Tracks().size() )
  635. m_out->Print( 0, "\n" );
  636. // Save the polygon (which are the newer technology) zones.
  637. for( int i = 0; i < aBoard->GetAreaCount(); ++i )
  638. Format( aBoard->GetArea( i ), aNestLevel );
  639. }
  640. void PCB_IO::format( DIMENSION* aDimension, int aNestLevel ) const
  641. {
  642. m_out->Print( aNestLevel, "(dimension %s (width %s)",
  643. FormatInternalUnits( aDimension->GetValue() ).c_str(),
  644. FormatInternalUnits( aDimension->GetWidth() ).c_str() );
  645. formatLayer( aDimension );
  646. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aDimension->m_Uuid.AsString() ) );
  647. m_out->Print( 0, "\n" );
  648. Format( &aDimension->Text(), aNestLevel+1 );
  649. m_out->Print( aNestLevel+1, "(feature1 (pts (xy %s %s) (xy %s %s)))\n",
  650. FormatInternalUnits( aDimension->m_featureLineDO.x ).c_str(),
  651. FormatInternalUnits( aDimension->m_featureLineDO.y ).c_str(),
  652. FormatInternalUnits( aDimension->m_featureLineDF.x ).c_str(),
  653. FormatInternalUnits( aDimension->m_featureLineDF.y ).c_str() );
  654. m_out->Print( aNestLevel+1, "(feature2 (pts (xy %s %s) (xy %s %s)))\n",
  655. FormatInternalUnits( aDimension->m_featureLineGO.x ).c_str(),
  656. FormatInternalUnits( aDimension->m_featureLineGO.y ).c_str(),
  657. FormatInternalUnits( aDimension->m_featureLineGF.x ).c_str(),
  658. FormatInternalUnits( aDimension->m_featureLineGF.y ).c_str() );
  659. m_out->Print( aNestLevel+1, "(crossbar (pts (xy %s %s) (xy %s %s)))\n",
  660. FormatInternalUnits( aDimension->m_crossBarO.x ).c_str(),
  661. FormatInternalUnits( aDimension->m_crossBarO.y ).c_str(),
  662. FormatInternalUnits( aDimension->m_crossBarF.x ).c_str(),
  663. FormatInternalUnits( aDimension->m_crossBarF.y ).c_str() );
  664. m_out->Print( aNestLevel+1, "(arrow1a (pts (xy %s %s) (xy %s %s)))\n",
  665. FormatInternalUnits( aDimension->m_crossBarF.x ).c_str(),
  666. FormatInternalUnits( aDimension->m_crossBarF.y ).c_str(),
  667. FormatInternalUnits( aDimension->m_arrowD1F.x ).c_str(),
  668. FormatInternalUnits( aDimension->m_arrowD1F.y ).c_str() );
  669. m_out->Print( aNestLevel+1, "(arrow1b (pts (xy %s %s) (xy %s %s)))\n",
  670. FormatInternalUnits( aDimension->m_crossBarF.x ).c_str(),
  671. FormatInternalUnits( aDimension->m_crossBarF.y ).c_str(),
  672. FormatInternalUnits( aDimension->m_arrowD2F.x ).c_str(),
  673. FormatInternalUnits( aDimension->m_arrowD2F.y ).c_str() );
  674. m_out->Print( aNestLevel+1, "(arrow2a (pts (xy %s %s) (xy %s %s)))\n",
  675. FormatInternalUnits( aDimension->m_crossBarO.x ).c_str(),
  676. FormatInternalUnits( aDimension->m_crossBarO.y ).c_str(),
  677. FormatInternalUnits( aDimension->m_arrowG1F.x ).c_str(),
  678. FormatInternalUnits( aDimension->m_arrowG1F.y ).c_str() );
  679. m_out->Print( aNestLevel+1, "(arrow2b (pts (xy %s %s) (xy %s %s)))\n",
  680. FormatInternalUnits( aDimension->m_crossBarO.x ).c_str(),
  681. FormatInternalUnits( aDimension->m_crossBarO.y ).c_str(),
  682. FormatInternalUnits( aDimension->m_arrowG2F.x ).c_str(),
  683. FormatInternalUnits( aDimension->m_arrowG2F.y ).c_str() );
  684. m_out->Print( aNestLevel, ")\n" );
  685. }
  686. void PCB_IO::format( DRAWSEGMENT* aSegment, int aNestLevel ) const
  687. {
  688. switch( aSegment->GetShape() )
  689. {
  690. case S_SEGMENT: // Line
  691. m_out->Print( aNestLevel, "(gr_line (start %s) (end %s)",
  692. FormatInternalUnits( aSegment->GetStart() ).c_str(),
  693. FormatInternalUnits( aSegment->GetEnd() ).c_str() );
  694. if( aSegment->GetAngle() != 0.0 )
  695. m_out->Print( 0, " (angle %s)", FormatAngle( aSegment->GetAngle() ).c_str() );
  696. break;
  697. case S_CIRCLE: // Circle
  698. m_out->Print( aNestLevel, "(gr_circle (center %s) (end %s)",
  699. FormatInternalUnits( aSegment->GetStart() ).c_str(),
  700. FormatInternalUnits( aSegment->GetEnd() ).c_str() );
  701. break;
  702. case S_ARC: // Arc
  703. m_out->Print( aNestLevel, "(gr_arc (start %s) (end %s) (angle %s)",
  704. FormatInternalUnits( aSegment->GetStart() ).c_str(),
  705. FormatInternalUnits( aSegment->GetEnd() ).c_str(),
  706. FormatAngle( aSegment->GetAngle() ).c_str() );
  707. break;
  708. case S_POLYGON: // Polygon
  709. if( aSegment->IsPolyShapeValid() )
  710. {
  711. SHAPE_POLY_SET& poly = aSegment->GetPolyShape();
  712. SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
  713. int pointsCount = outline.PointCount();
  714. m_out->Print( aNestLevel, "(gr_poly (pts" );
  715. for( int ii = 0; ii < pointsCount; ++ii )
  716. {
  717. m_out->Print( 0, " (xy %s)", FormatInternalUnits( outline.CPoint( ii ) ).c_str() );
  718. }
  719. m_out->Print( 0, ")" );
  720. }
  721. else
  722. {
  723. wxFAIL_MSG( wxT( "Cannot format invalid polygon." ) );
  724. return;
  725. }
  726. break;
  727. case S_CURVE: // Bezier curve
  728. m_out->Print( aNestLevel, "(gr_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
  729. FormatInternalUnits( aSegment->GetStart() ).c_str(),
  730. FormatInternalUnits( aSegment->GetBezControl1() ).c_str(),
  731. FormatInternalUnits( aSegment->GetBezControl2() ).c_str(),
  732. FormatInternalUnits( aSegment->GetEnd() ).c_str() );
  733. break;
  734. default:
  735. wxFAIL_MSG( wxT( "Cannot format invalid DRAWSEGMENT type." ) );
  736. return;
  737. };
  738. formatLayer( aSegment );
  739. m_out->Print( 0, " (width %s)", FormatInternalUnits( aSegment->GetWidth() ).c_str() );
  740. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aSegment->m_Uuid.AsString() ) );
  741. if( aSegment->GetStatus() )
  742. m_out->Print( 0, " (status %X)", aSegment->GetStatus() );
  743. m_out->Print( 0, ")\n" );
  744. }
  745. void PCB_IO::format( EDGE_MODULE* aModuleDrawing, int aNestLevel ) const
  746. {
  747. switch( aModuleDrawing->GetShape() )
  748. {
  749. case S_SEGMENT: // Line
  750. m_out->Print( aNestLevel, "(fp_line (start %s) (end %s)",
  751. FormatInternalUnits( aModuleDrawing->GetStart0() ).c_str(),
  752. FormatInternalUnits( aModuleDrawing->GetEnd0() ).c_str() );
  753. break;
  754. case S_CIRCLE: // Circle
  755. m_out->Print( aNestLevel, "(fp_circle (center %s) (end %s)",
  756. FormatInternalUnits( aModuleDrawing->GetStart0() ).c_str(),
  757. FormatInternalUnits( aModuleDrawing->GetEnd0() ).c_str() );
  758. break;
  759. case S_ARC: // Arc
  760. m_out->Print( aNestLevel, "(fp_arc (start %s) (end %s) (angle %s)",
  761. FormatInternalUnits( aModuleDrawing->GetStart0() ).c_str(),
  762. FormatInternalUnits( aModuleDrawing->GetEnd0() ).c_str(),
  763. FormatAngle( aModuleDrawing->GetAngle() ).c_str() );
  764. break;
  765. case S_POLYGON: // Polygonal segment
  766. if( aModuleDrawing->IsPolyShapeValid() )
  767. {
  768. SHAPE_POLY_SET& poly = aModuleDrawing->GetPolyShape();
  769. SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
  770. int pointsCount = outline.PointCount();
  771. m_out->Print( aNestLevel, "(fp_poly (pts" );
  772. for( int ii = 0; ii < pointsCount; ++ii )
  773. {
  774. int nestLevel = 0;
  775. if( ii && !( ii%4 ) ) // newline every 4 pts
  776. {
  777. nestLevel = aNestLevel + 1;
  778. m_out->Print( 0, "\n" );
  779. }
  780. m_out->Print( nestLevel, "%s(xy %s)",
  781. nestLevel ? "" : " ", FormatInternalUnits( outline.CPoint( ii ) ).c_str() );
  782. }
  783. m_out->Print( 0, ")" );
  784. }
  785. else
  786. {
  787. wxFAIL_MSG( wxT( "Cannot format invalid polygon." ) );
  788. return;
  789. }
  790. break;
  791. case S_CURVE: // Bezier curve
  792. m_out->Print( aNestLevel, "(fp_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
  793. FormatInternalUnits( aModuleDrawing->GetStart0() ).c_str(),
  794. FormatInternalUnits( aModuleDrawing->GetBezier0_C1() ).c_str(),
  795. FormatInternalUnits( aModuleDrawing->GetBezier0_C2() ).c_str(),
  796. FormatInternalUnits( aModuleDrawing->GetEnd0() ).c_str() );
  797. break;
  798. default:
  799. wxFAIL_MSG( wxT( "Cannot format invalid DRAWSEGMENT type." ) );
  800. return;
  801. };
  802. formatLayer( aModuleDrawing );
  803. m_out->Print( 0, " (width %s)", FormatInternalUnits( aModuleDrawing->GetWidth() ).c_str() );
  804. m_out->Print( 0, ")\n" );
  805. }
  806. void PCB_IO::format( PCB_TARGET* aTarget, int aNestLevel ) const
  807. {
  808. m_out->Print( aNestLevel, "(target %s (at %s) (size %s)",
  809. ( aTarget->GetShape() ) ? "x" : "plus",
  810. FormatInternalUnits( aTarget->GetPosition() ).c_str(),
  811. FormatInternalUnits( aTarget->GetSize() ).c_str() );
  812. if( aTarget->GetWidth() != 0 )
  813. m_out->Print( 0, " (width %s)", FormatInternalUnits( aTarget->GetWidth() ).c_str() );
  814. formatLayer( aTarget );
  815. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aTarget->m_Uuid.AsString() ) );
  816. m_out->Print( 0, ")\n" );
  817. }
  818. void PCB_IO::format( MODULE* aModule, int aNestLevel ) const
  819. {
  820. if( !( m_ctl & CTL_OMIT_INITIAL_COMMENTS ) )
  821. {
  822. const wxArrayString* initial_comments = aModule->GetInitialComments();
  823. if( initial_comments )
  824. {
  825. for( unsigned i=0; i<initial_comments->GetCount(); ++i )
  826. m_out->Print( aNestLevel, "%s\n", TO_UTF8( (*initial_comments)[i] ) );
  827. m_out->Print( 0, "\n" ); // improve readability?
  828. }
  829. }
  830. m_out->Print( aNestLevel, "(module %s",
  831. m_out->Quotes( aModule->GetFPID().Format() ).c_str() );
  832. if( aModule->IsLocked() )
  833. m_out->Print( 0, " locked" );
  834. if( aModule->IsPlaced() )
  835. m_out->Print( 0, " placed" );
  836. formatLayer( aModule );
  837. m_out->Print( 0, " (tedit %lX)", (unsigned long)aModule->GetLastEditTime() );
  838. if( !( m_ctl & CTL_OMIT_TSTAMPS ) )
  839. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aModule->m_Uuid.AsString() ) );
  840. m_out->Print( 0, "\n" );
  841. if( !( m_ctl & CTL_OMIT_AT ) )
  842. {
  843. m_out->Print( aNestLevel+1, "(at %s", FormatInternalUnits( aModule->GetPosition() ).c_str() );
  844. if( aModule->GetOrientation() != 0.0 )
  845. m_out->Print( 0, " %s", FormatAngle( aModule->GetOrientation() ).c_str() );
  846. m_out->Print( 0, ")\n" );
  847. }
  848. if( !aModule->GetDescription().IsEmpty() )
  849. m_out->Print( aNestLevel+1, "(descr %s)\n",
  850. m_out->Quotew( aModule->GetDescription() ).c_str() );
  851. if( !aModule->GetKeywords().IsEmpty() )
  852. m_out->Print( aNestLevel+1, "(tags %s)\n",
  853. m_out->Quotew( aModule->GetKeywords() ).c_str() );
  854. if( !( m_ctl & CTL_OMIT_PATH ) && !aModule->GetPath().empty() )
  855. m_out->Print( aNestLevel+1, "(path %s)\n",
  856. m_out->Quotew( aModule->GetPath().AsString() ).c_str() );
  857. if( aModule->GetPlacementCost90() != 0 )
  858. m_out->Print( aNestLevel+1, "(autoplace_cost90 %d)\n", aModule->GetPlacementCost90() );
  859. if( aModule->GetPlacementCost180() != 0 )
  860. m_out->Print( aNestLevel+1, "(autoplace_cost180 %d)\n", aModule->GetPlacementCost180() );
  861. if( aModule->GetLocalSolderMaskMargin() != 0 )
  862. m_out->Print( aNestLevel+1, "(solder_mask_margin %s)\n",
  863. FormatInternalUnits( aModule->GetLocalSolderMaskMargin() ).c_str() );
  864. if( aModule->GetLocalSolderPasteMargin() != 0 )
  865. m_out->Print( aNestLevel+1, "(solder_paste_margin %s)\n",
  866. FormatInternalUnits( aModule->GetLocalSolderPasteMargin() ).c_str() );
  867. if( aModule->GetLocalSolderPasteMarginRatio() != 0 )
  868. m_out->Print( aNestLevel+1, "(solder_paste_ratio %s)\n",
  869. Double2Str( aModule->GetLocalSolderPasteMarginRatio() ).c_str() );
  870. if( aModule->GetLocalClearance() != 0 )
  871. m_out->Print( aNestLevel+1, "(clearance %s)\n",
  872. FormatInternalUnits( aModule->GetLocalClearance() ).c_str() );
  873. if( aModule->GetZoneConnection() != ZONE_CONNECTION::INHERITED )
  874. m_out->Print( aNestLevel+1, "(zone_connect %d)\n",
  875. static_cast<int>( aModule->GetZoneConnection() ) );
  876. if( aModule->GetThermalWidth() != 0 )
  877. m_out->Print( aNestLevel+1, "(thermal_width %s)\n",
  878. FormatInternalUnits( aModule->GetThermalWidth() ).c_str() );
  879. if( aModule->GetThermalGap() != 0 )
  880. m_out->Print( aNestLevel+1, "(thermal_gap %s)\n",
  881. FormatInternalUnits( aModule->GetThermalGap() ).c_str() );
  882. // Attributes
  883. if( aModule->GetAttributes() != MOD_DEFAULT )
  884. {
  885. m_out->Print( aNestLevel+1, "(attr" );
  886. if( aModule->GetAttributes() & MOD_CMS )
  887. m_out->Print( 0, " smd" );
  888. if( aModule->GetAttributes() & MOD_VIRTUAL )
  889. m_out->Print( 0, " virtual" );
  890. m_out->Print( 0, ")\n" );
  891. }
  892. Format( (BOARD_ITEM*) &aModule->Reference(), aNestLevel+1 );
  893. Format( (BOARD_ITEM*) &aModule->Value(), aNestLevel+1 );
  894. // Save drawing elements.
  895. for( auto gr : aModule->GraphicalItems() )
  896. Format( gr, aNestLevel+1 );
  897. // Save pads.
  898. for( auto pad : aModule->Pads() )
  899. format( pad, aNestLevel+1 );
  900. // Save zones.
  901. for( auto zone : aModule->Zones() )
  902. format( zone, aNestLevel + 1 );
  903. // Save 3D info.
  904. auto bs3D = aModule->Models().begin();
  905. auto es3D = aModule->Models().end();
  906. while( bs3D != es3D )
  907. {
  908. if( !bs3D->m_Filename.IsEmpty() )
  909. {
  910. m_out->Print( aNestLevel+1, "(model %s%s\n",
  911. m_out->Quotew( bs3D->m_Filename ).c_str(),
  912. bs3D->m_Show ? "" : " hide" );
  913. if( bs3D->m_Opacity != 1.0 )
  914. m_out->Print( aNestLevel+2, "(opacity %0.4f)", bs3D->m_Opacity );
  915. /* Write 3D model offset in mm
  916. * 4.0.x wrote "at" which was actually in inches
  917. * 5.0.x onwards, 3D model offset is written using "offset"
  918. *
  919. * If the offset is all zero, write "at" (fewer file changes)
  920. * Otherwise, write "offset"
  921. */
  922. wxString offsetTag = "offset";
  923. if( bs3D->m_Offset.x == 0 &&
  924. bs3D->m_Offset.y == 0 &&
  925. bs3D->m_Offset.z == 0 )
  926. {
  927. offsetTag = "at";
  928. }
  929. m_out->Print( aNestLevel+2, "(%s (xyz %s %s %s))\n",
  930. offsetTag.ToStdString().c_str(),
  931. Double2Str( bs3D->m_Offset.x ).c_str(),
  932. Double2Str( bs3D->m_Offset.y ).c_str(),
  933. Double2Str( bs3D->m_Offset.z ).c_str() );
  934. m_out->Print( aNestLevel+2, "(scale (xyz %s %s %s))\n",
  935. Double2Str( bs3D->m_Scale.x ).c_str(),
  936. Double2Str( bs3D->m_Scale.y ).c_str(),
  937. Double2Str( bs3D->m_Scale.z ).c_str() );
  938. m_out->Print( aNestLevel+2, "(rotate (xyz %s %s %s))\n",
  939. Double2Str( bs3D->m_Rotation.x ).c_str(),
  940. Double2Str( bs3D->m_Rotation.y ).c_str(),
  941. Double2Str( bs3D->m_Rotation.z ).c_str() );
  942. m_out->Print( aNestLevel+1, ")\n" );
  943. }
  944. ++bs3D;
  945. }
  946. m_out->Print( aNestLevel, ")\n" );
  947. }
  948. void PCB_IO::formatLayers( LSET aLayerMask, int aNestLevel ) const
  949. {
  950. std::string output;
  951. if( aNestLevel == 0 )
  952. output += ' ';
  953. output += "(layers";
  954. static const LSET cu_all( LSET::AllCuMask() );
  955. static const LSET fr_bk( 2, B_Cu, F_Cu );
  956. static const LSET adhes( 2, B_Adhes, F_Adhes );
  957. static const LSET paste( 2, B_Paste, F_Paste );
  958. static const LSET silks( 2, B_SilkS, F_SilkS );
  959. static const LSET mask( 2, B_Mask, F_Mask );
  960. static const LSET crt_yd(2, B_CrtYd, F_CrtYd );
  961. static const LSET fab( 2, B_Fab, F_Fab );
  962. LSET cu_mask = cu_all;
  963. // output copper layers first, then non copper
  964. if( ( aLayerMask & cu_mask ) == cu_mask )
  965. {
  966. output += " *.Cu";
  967. aLayerMask &= ~cu_all; // clear bits, so they are not output again below
  968. }
  969. else if( ( aLayerMask & cu_mask ) == fr_bk )
  970. {
  971. output += " F&B.Cu";
  972. aLayerMask &= ~fr_bk;
  973. }
  974. if( ( aLayerMask & adhes ) == adhes )
  975. {
  976. output += " *.Adhes";
  977. aLayerMask &= ~adhes;
  978. }
  979. if( ( aLayerMask & paste ) == paste )
  980. {
  981. output += " *.Paste";
  982. aLayerMask &= ~paste;
  983. }
  984. if( ( aLayerMask & silks ) == silks )
  985. {
  986. output += " *.SilkS";
  987. aLayerMask &= ~silks;
  988. }
  989. if( ( aLayerMask & mask ) == mask )
  990. {
  991. output += " *.Mask";
  992. aLayerMask &= ~mask;
  993. }
  994. if( ( aLayerMask & crt_yd ) == crt_yd )
  995. {
  996. output += " *.CrtYd";
  997. aLayerMask &= ~crt_yd;
  998. }
  999. if( ( aLayerMask & fab ) == fab )
  1000. {
  1001. output += " *.Fab";
  1002. aLayerMask &= ~fab;
  1003. }
  1004. // output any individual layers not handled in wildcard combos above
  1005. wxString layerName;
  1006. for( LAYER_NUM layer = 0; layer < PCB_LAYER_ID_COUNT; ++layer )
  1007. {
  1008. if( aLayerMask[layer] )
  1009. {
  1010. if( m_board && !( m_ctl & CTL_STD_LAYER_NAMES ) )
  1011. layerName = m_board->GetLayerName( PCB_LAYER_ID( layer ) );
  1012. else // I am being called from FootprintSave()
  1013. layerName = BOARD::GetStandardLayerName( PCB_LAYER_ID( layer ) );
  1014. output += ' ';
  1015. output += m_out->Quotew( layerName );
  1016. }
  1017. }
  1018. m_out->Print( aNestLevel, "%s)", output.c_str() );
  1019. }
  1020. void PCB_IO::format( D_PAD* aPad, int aNestLevel ) const
  1021. {
  1022. const char* shape;
  1023. switch( aPad->GetShape() )
  1024. {
  1025. case PAD_SHAPE_CIRCLE: shape = "circle"; break;
  1026. case PAD_SHAPE_RECT: shape = "rect"; break;
  1027. case PAD_SHAPE_OVAL: shape = "oval"; break;
  1028. case PAD_SHAPE_TRAPEZOID: shape = "trapezoid"; break;
  1029. case PAD_SHAPE_CHAMFERED_RECT:
  1030. case PAD_SHAPE_ROUNDRECT: shape = "roundrect"; break;
  1031. case PAD_SHAPE_CUSTOM: shape = "custom"; break;
  1032. default:
  1033. THROW_IO_ERROR( wxString::Format( _( "unknown pad type: %d"), aPad->GetShape() ) );
  1034. }
  1035. const char* type;
  1036. switch( aPad->GetAttribute() )
  1037. {
  1038. case PAD_ATTRIB_STANDARD: type = "thru_hole"; break;
  1039. case PAD_ATTRIB_SMD: type = "smd"; break;
  1040. case PAD_ATTRIB_CONN: type = "connect"; break;
  1041. case PAD_ATTRIB_HOLE_NOT_PLATED: type = "np_thru_hole"; break;
  1042. default:
  1043. THROW_IO_ERROR( wxString::Format( "unknown pad attribute: %d", aPad->GetAttribute() ) );
  1044. }
  1045. const char* property = nullptr;
  1046. switch( aPad->GetProperty() )
  1047. {
  1048. case PAD_PROP_NONE: break;
  1049. case PAD_PROP_BGA: property = "pad_prop_bga"; break;
  1050. case PAD_PROP_FIDUCIAL_GLBL: property = "pad_prop_fiducial_glob"; break;
  1051. case PAD_PROP_FIDUCIAL_LOCAL: property = "pad_prop_fiducial_loc"; break;
  1052. case PAD_PROP_TESTPOINT: property = "pad_prop_testpoint"; break;
  1053. case PAD_PROP_HEATSINK: property = "pad_prop_heatsink"; break;
  1054. case PAD_PROP_CASTELLATED: property = "pad_prop_castellated"; break;
  1055. default:
  1056. THROW_IO_ERROR( wxString::Format( "unknown pad property: %d", aPad->GetProperty() ) );
  1057. }
  1058. m_out->Print( aNestLevel, "(pad %s %s %s",
  1059. m_out->Quotew( aPad->GetName() ).c_str(),
  1060. type, shape );
  1061. m_out->Print( 0, " (at %s", FormatInternalUnits( aPad->GetPos0() ).c_str() );
  1062. if( aPad->GetOrientation() != 0.0 )
  1063. m_out->Print( 0, " %s", FormatAngle( aPad->GetOrientation() ).c_str() );
  1064. m_out->Print( 0, ")" );
  1065. m_out->Print( 0, " (size %s)", FormatInternalUnits( aPad->GetSize() ).c_str() );
  1066. if( (aPad->GetDelta().GetWidth()) != 0 || (aPad->GetDelta().GetHeight() != 0 ) )
  1067. m_out->Print( 0, " (rect_delta %s )", FormatInternalUnits( aPad->GetDelta() ).c_str() );
  1068. wxSize sz = aPad->GetDrillSize();
  1069. wxPoint shapeoffset = aPad->GetOffset();
  1070. if( (sz.GetWidth() > 0) || (sz.GetHeight() > 0) ||
  1071. (shapeoffset.x != 0) || (shapeoffset.y != 0) )
  1072. {
  1073. m_out->Print( 0, " (drill" );
  1074. if( aPad->GetDrillShape() == PAD_DRILL_SHAPE_OBLONG )
  1075. m_out->Print( 0, " oval" );
  1076. if( sz.GetWidth() > 0 )
  1077. m_out->Print( 0, " %s", FormatInternalUnits( sz.GetWidth() ).c_str() );
  1078. if( sz.GetHeight() > 0 && sz.GetWidth() != sz.GetHeight() )
  1079. m_out->Print( 0, " %s", FormatInternalUnits( sz.GetHeight() ).c_str() );
  1080. if( (shapeoffset.x != 0) || (shapeoffset.y != 0) )
  1081. m_out->Print( 0, " (offset %s)", FormatInternalUnits( aPad->GetOffset() ).c_str() );
  1082. m_out->Print( 0, ")" );
  1083. }
  1084. if( property && ADVANCED_CFG::GetCfg().m_EnableUsePadProperty )
  1085. {
  1086. // Add pad property, if exists.
  1087. m_out->Print( 0, " (property %s)", property );
  1088. }
  1089. formatLayers( aPad->GetLayerSet() );
  1090. // Output the radius ratio for rounded and chamfered rect pads
  1091. if( aPad->GetShape() == PAD_SHAPE_ROUNDRECT || aPad->GetShape() == PAD_SHAPE_CHAMFERED_RECT)
  1092. {
  1093. m_out->Print( 0, " (roundrect_rratio %s)",
  1094. Double2Str( aPad->GetRoundRectRadiusRatio() ).c_str() );
  1095. }
  1096. // Output the chamfer corners for chamfered rect pads
  1097. if( aPad->GetShape() == PAD_SHAPE_CHAMFERED_RECT)
  1098. {
  1099. m_out->Print( 0, "\n" );
  1100. m_out->Print( aNestLevel+1, "(chamfer_ratio %s)",
  1101. Double2Str( aPad->GetChamferRectRatio() ).c_str() );
  1102. m_out->Print( 0, " (chamfer" );
  1103. if( ( aPad->GetChamferPositions() & RECT_CHAMFER_TOP_LEFT ) )
  1104. m_out->Print( 0, " top_left" );
  1105. if( ( aPad->GetChamferPositions() & RECT_CHAMFER_TOP_RIGHT ) )
  1106. m_out->Print( 0, " top_right" );
  1107. if( ( aPad->GetChamferPositions() & RECT_CHAMFER_BOTTOM_LEFT ) )
  1108. m_out->Print( 0, " bottom_left" );
  1109. if( ( aPad->GetChamferPositions() & RECT_CHAMFER_BOTTOM_RIGHT ) )
  1110. m_out->Print( 0, " bottom_right" );
  1111. m_out->Print( 0, ")" );
  1112. }
  1113. std::string output;
  1114. // Unconnected pad is default net so don't save it.
  1115. if( !( m_ctl & CTL_OMIT_NETS ) && aPad->GetNetCode() != NETINFO_LIST::UNCONNECTED )
  1116. StrPrintf( &output, " (net %d %s)", m_mapping->Translate( aPad->GetNetCode() ),
  1117. m_out->Quotew( aPad->GetNetname() ).c_str() );
  1118. // Add pinfunction, if exists.
  1119. // Pin function is closely related to nets, so if CTL_OMIT_NETS is set,
  1120. // omit also pin function (for instance when saved from library editor)
  1121. if( !(m_ctl & CTL_OMIT_NETS) && !aPad->GetPinFunction().IsEmpty() )
  1122. StrPrintf( &output, " (pinfunction %s)",
  1123. m_out->Quotew( aPad->GetPinFunction() ).c_str() );
  1124. if( aPad->GetPadToDieLength() != 0 )
  1125. StrPrintf( &output, " (die_length %s)",
  1126. FormatInternalUnits( aPad->GetPadToDieLength() ).c_str() );
  1127. if( aPad->GetLocalSolderMaskMargin() != 0 )
  1128. StrPrintf( &output, " (solder_mask_margin %s)",
  1129. FormatInternalUnits( aPad->GetLocalSolderMaskMargin() ).c_str() );
  1130. if( aPad->GetLocalSolderPasteMargin() != 0 )
  1131. StrPrintf( &output, " (solder_paste_margin %s)",
  1132. FormatInternalUnits( aPad->GetLocalSolderPasteMargin() ).c_str() );
  1133. if( aPad->GetLocalSolderPasteMarginRatio() != 0 )
  1134. StrPrintf( &output, " (solder_paste_margin_ratio %s)",
  1135. Double2Str( aPad->GetLocalSolderPasteMarginRatio() ).c_str() );
  1136. if( aPad->GetLocalClearance() != 0 )
  1137. StrPrintf( &output, " (clearance %s)", FormatInternalUnits( aPad->GetLocalClearance() ).c_str() );
  1138. if( aPad->GetZoneConnection() != ZONE_CONNECTION::INHERITED )
  1139. StrPrintf( &output, " (zone_connect %d)", static_cast<int>( aPad->GetZoneConnection() ) );
  1140. if( aPad->GetThermalWidth() != 0 )
  1141. StrPrintf( &output, " (thermal_width %s)", FormatInternalUnits( aPad->GetThermalWidth() ).c_str() );
  1142. if( aPad->GetThermalGap() != 0 )
  1143. StrPrintf( &output, " (thermal_gap %s)", FormatInternalUnits( aPad->GetThermalGap() ).c_str() );
  1144. if( output.size() )
  1145. {
  1146. m_out->Print( 0, "\n" );
  1147. m_out->Print( aNestLevel+1, "%s", output.c_str()+1 ); // +1 skips 1st space on 1st element
  1148. }
  1149. if( aPad->GetShape() == PAD_SHAPE_CUSTOM )
  1150. {
  1151. m_out->Print( 0, "\n");
  1152. m_out->Print( aNestLevel+1, "(options" );
  1153. if( aPad->GetCustomShapeInZoneOpt() == CUST_PAD_SHAPE_IN_ZONE_CONVEXHULL )
  1154. m_out->Print( 0, " (clearance convexhull)" );
  1155. #if 1 // Set to 1 to output the default option
  1156. else
  1157. m_out->Print( 0, " (clearance outline)" );
  1158. #endif
  1159. // Output the anchor pad shape (circle/rect)
  1160. if( aPad->GetAnchorPadShape() == PAD_SHAPE_RECT )
  1161. shape = "rect";
  1162. else
  1163. shape = "circle";
  1164. m_out->Print( 0, " (anchor %s)", shape );
  1165. m_out->Print( 0, ")"); // end of (options ...
  1166. // Output graphic primitive of the pad shape
  1167. m_out->Print( 0, "\n");
  1168. m_out->Print( aNestLevel+1, "(primitives" );
  1169. int nested_level = aNestLevel+2;
  1170. // Output all basic shapes
  1171. for( unsigned icnt = 0; icnt < aPad->GetPrimitives().size(); ++icnt )
  1172. {
  1173. m_out->Print( 0, "\n");
  1174. const PAD_CS_PRIMITIVE& primitive = aPad->GetPrimitives()[icnt];
  1175. switch( primitive.m_Shape )
  1176. {
  1177. case S_SEGMENT: // usual segment : line with rounded ends
  1178. m_out->Print( nested_level, "(gr_line (start %s) (end %s) (width %s))",
  1179. FormatInternalUnits( primitive.m_Start ).c_str(),
  1180. FormatInternalUnits( primitive.m_End ).c_str(),
  1181. FormatInternalUnits( primitive.m_Thickness ).c_str() );
  1182. break;
  1183. case S_ARC: // Arc with rounded ends
  1184. m_out->Print( nested_level, "(gr_arc (start %s) (end %s) (angle %s) (width %s))",
  1185. FormatInternalUnits( primitive.m_Start ).c_str(),
  1186. FormatInternalUnits( primitive.m_End ).c_str(),
  1187. FormatAngle( primitive.m_ArcAngle ).c_str(),
  1188. FormatInternalUnits( primitive.m_Thickness ).c_str() );
  1189. break;
  1190. case S_CIRCLE: // ring or circle (circle if width == 0
  1191. m_out->Print( nested_level, "(gr_circle (center %s) (end %s %s) (width %s))",
  1192. FormatInternalUnits( primitive.m_Start ).c_str(),
  1193. FormatInternalUnits( primitive.m_Start.x + primitive.m_Radius ).c_str(),
  1194. FormatInternalUnits( primitive.m_Start.y ).c_str(),
  1195. FormatInternalUnits( primitive.m_Thickness ).c_str() );
  1196. break;
  1197. case S_CURVE: // Bezier Curve
  1198. m_out->Print( aNestLevel, "(gr_curve (pts (xy %s) (xy %s) (xy %s) (xy %s)) (width %s))",
  1199. FormatInternalUnits( primitive.m_Start ).c_str(),
  1200. FormatInternalUnits( primitive.m_Ctrl1 ).c_str(),
  1201. FormatInternalUnits( primitive.m_Ctrl2 ).c_str(),
  1202. FormatInternalUnits( primitive.m_End ).c_str(),
  1203. FormatInternalUnits( primitive.m_Thickness ).c_str() );
  1204. break;
  1205. case S_POLYGON: // polygon
  1206. if( primitive.m_Poly.size() < 2 )
  1207. break; // Malformed polygon.
  1208. {
  1209. m_out->Print( nested_level, "(gr_poly (pts\n");
  1210. // Write the polygon corners coordinates:
  1211. const std::vector< wxPoint>& poly = primitive.m_Poly;
  1212. int newLine = 0;
  1213. for( unsigned ii = 0; ii < poly.size(); ii++ )
  1214. {
  1215. if( newLine == 0 )
  1216. m_out->Print( nested_level+1, " (xy %s)",
  1217. FormatInternalUnits( wxPoint( poly[ii].x, poly[ii].y ) ).c_str() );
  1218. else
  1219. m_out->Print( 0, " (xy %s)",
  1220. FormatInternalUnits( wxPoint( poly[ii].x, poly[ii].y ) ).c_str() );
  1221. if( ++newLine > 4 )
  1222. {
  1223. newLine = 0;
  1224. m_out->Print( 0, "\n" );
  1225. }
  1226. }
  1227. m_out->Print( 0, ") (width %s))", FormatInternalUnits( primitive.m_Thickness ).c_str() );
  1228. }
  1229. break;
  1230. default:
  1231. break;
  1232. }
  1233. }
  1234. m_out->Print( 0, "\n");
  1235. m_out->Print( aNestLevel+1, ")" ); // end of (basic_shapes
  1236. }
  1237. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aPad->m_Uuid.AsString() ) );
  1238. m_out->Print( 0, ")\n" );
  1239. }
  1240. void PCB_IO::format( TEXTE_PCB* aText, int aNestLevel ) const
  1241. {
  1242. m_out->Print( aNestLevel, "(gr_text %s (at %s",
  1243. m_out->Quotew( aText->GetText() ).c_str(),
  1244. FormatInternalUnits( aText->GetTextPos() ).c_str() );
  1245. if( aText->GetTextAngle() != 0.0 )
  1246. m_out->Print( 0, " %s", FormatAngle( aText->GetTextAngle() ).c_str() );
  1247. m_out->Print( 0, ")" );
  1248. formatLayer( aText );
  1249. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aText->m_Uuid.AsString() ) );
  1250. m_out->Print( 0, "\n" );
  1251. aText->EDA_TEXT::Format( m_out, aNestLevel, m_ctl );
  1252. m_out->Print( aNestLevel, ")\n" );
  1253. }
  1254. void PCB_IO::format( TEXTE_MODULE* aText, int aNestLevel ) const
  1255. {
  1256. std::string type;
  1257. switch( aText->GetType() )
  1258. {
  1259. case TEXTE_MODULE::TEXT_is_REFERENCE: type = "reference"; break;
  1260. case TEXTE_MODULE::TEXT_is_VALUE: type = "value"; break;
  1261. case TEXTE_MODULE::TEXT_is_DIVERS: type = "user";
  1262. }
  1263. m_out->Print( aNestLevel, "(fp_text %s %s (at %s",
  1264. type.c_str(),
  1265. m_out->Quotew( aText->GetText() ).c_str(),
  1266. FormatInternalUnits( aText->GetPos0() ).c_str() );
  1267. // Due to Pcbnew history, fp_text angle is saved as an absolute on screen angle,
  1268. // but internally the angle is held relative to its parent footprint. parent
  1269. // may be NULL when saving a footprint outside a BOARD.
  1270. double orient = aText->GetTextAngle();
  1271. MODULE* parent = (MODULE*) aText->GetParent();
  1272. if( parent )
  1273. {
  1274. // GetTextAngle() is always in -360..+360 range because of
  1275. // TEXTE_MODULE::SetTextAngle(), but summing that angle with an
  1276. // additional board angle could kick sum up >= 360 or <= -360, so to have
  1277. // consistent results, normalize again for the BOARD save. A footprint
  1278. // save does not use this code path since parent is NULL.
  1279. #if 0
  1280. // This one could be considered reasonable if you like positive angles
  1281. // in your board text.
  1282. orient = NormalizeAnglePos( orient + parent->GetOrientation() );
  1283. #else
  1284. // Choose compatibility for now, even though this is only a 720 degree clamp
  1285. // with two possible values for every angle.
  1286. orient = NormalizeAngle360Min( orient + parent->GetOrientation() );
  1287. #endif
  1288. }
  1289. if( orient != 0.0 )
  1290. m_out->Print( 0, " %s", FormatAngle( orient ).c_str() );
  1291. if( !aText->IsKeepUpright() )
  1292. m_out->Print( 0, " unlocked" );
  1293. m_out->Print( 0, ")" );
  1294. formatLayer( aText );
  1295. if( !aText->IsVisible() )
  1296. m_out->Print( 0, " hide" );
  1297. m_out->Print( 0, "\n" );
  1298. aText->EDA_TEXT::Format( m_out, aNestLevel, m_ctl | CTL_OMIT_HIDE );
  1299. m_out->Print( aNestLevel, ")\n" );
  1300. }
  1301. void PCB_IO::format( TRACK* aTrack, int aNestLevel ) const
  1302. {
  1303. if( aTrack->Type() == PCB_VIA_T )
  1304. {
  1305. PCB_LAYER_ID layer1, layer2;
  1306. const VIA* via = static_cast<const VIA*>( aTrack );
  1307. BOARD* board = (BOARD*) via->GetParent();
  1308. wxCHECK_RET( board != 0, wxT( "Via " ) + via->GetSelectMenuText( EDA_UNITS::MILLIMETRES )
  1309. + wxT( " has no parent." ) );
  1310. m_out->Print( aNestLevel, "(via" );
  1311. via->LayerPair( &layer1, &layer2 );
  1312. switch( via->GetViaType() )
  1313. {
  1314. case VIATYPE::THROUGH: // Default shape not saved.
  1315. break;
  1316. case VIATYPE::BLIND_BURIED:
  1317. m_out->Print( 0, " blind" );
  1318. break;
  1319. case VIATYPE::MICROVIA:
  1320. m_out->Print( 0, " micro" );
  1321. break;
  1322. default:
  1323. THROW_IO_ERROR( wxString::Format( _( "unknown via type %d" ), via->GetViaType() ) );
  1324. }
  1325. m_out->Print( 0, " (at %s) (size %s)",
  1326. FormatInternalUnits( aTrack->GetStart() ).c_str(),
  1327. FormatInternalUnits( aTrack->GetWidth() ).c_str() );
  1328. if( via->GetDrill() != UNDEFINED_DRILL_DIAMETER )
  1329. m_out->Print( 0, " (drill %s)", FormatInternalUnits( via->GetDrill() ).c_str() );
  1330. m_out->Print( 0, " (layers %s %s)",
  1331. m_out->Quotew( m_board->GetLayerName( layer1 ) ).c_str(),
  1332. m_out->Quotew( m_board->GetLayerName( layer2 ) ).c_str() );
  1333. }
  1334. else if( aTrack->Type() == PCB_ARC_T )
  1335. {
  1336. const ARC* arc = static_cast<const ARC*>( aTrack );
  1337. m_out->Print( aNestLevel, "(arc (start %s) (mid %s) (end %s) (width %s)",
  1338. FormatInternalUnits( arc->GetStart() ).c_str(),
  1339. FormatInternalUnits( arc->GetMid() ).c_str(),
  1340. FormatInternalUnits( arc->GetEnd() ).c_str(),
  1341. FormatInternalUnits( arc->GetWidth() ).c_str() );
  1342. m_out->Print( 0, " (layer %s)", m_out->Quotew( aTrack->GetLayerName() ).c_str() );
  1343. }
  1344. else
  1345. {
  1346. m_out->Print( aNestLevel, "(segment (start %s) (end %s) (width %s)",
  1347. FormatInternalUnits( aTrack->GetStart() ).c_str(), FormatInternalUnits( aTrack->GetEnd() ).c_str(),
  1348. FormatInternalUnits( aTrack->GetWidth() ).c_str() );
  1349. m_out->Print( 0, " (layer %s)", m_out->Quotew( aTrack->GetLayerName() ).c_str() );
  1350. }
  1351. m_out->Print( 0, " (net %d)", m_mapping->Translate( aTrack->GetNetCode() ) );
  1352. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aTrack->m_Uuid.AsString() ) );
  1353. if( aTrack->GetStatus() != 0 )
  1354. m_out->Print( 0, " (status %X)", aTrack->GetStatus() );
  1355. m_out->Print( 0, ")\n" );
  1356. }
  1357. void PCB_IO::format( ZONE_CONTAINER* aZone, int aNestLevel ) const
  1358. {
  1359. // Save the NET info; For keepout zones, net code and net name are irrelevant
  1360. // so be sure a dummy value is stored, just for ZONE_CONTAINER compatibility
  1361. // (perhaps netcode and netname should be not stored)
  1362. m_out->Print( aNestLevel, "(zone (net %d) (net_name %s)",
  1363. aZone->GetIsKeepout() ? 0 : m_mapping->Translate( aZone->GetNetCode() ),
  1364. m_out->Quotew( aZone->GetIsKeepout() ? wxT("") : aZone->GetNetname() ).c_str() );
  1365. // If a zone exists on multiple layers, format accordingly
  1366. if( aZone->GetLayerSet().count() > 1 )
  1367. {
  1368. formatLayers( aZone->GetLayerSet() );
  1369. }
  1370. else
  1371. {
  1372. formatLayer( aZone );
  1373. }
  1374. m_out->Print( 0, " (tstamp %s)", TO_UTF8( aZone->m_Uuid.AsString() ) );
  1375. // Save the outline aux info
  1376. std::string hatch;
  1377. switch( aZone->GetHatchStyle() )
  1378. {
  1379. default:
  1380. case ZONE_HATCH_STYLE::NO_HATCH:
  1381. hatch = "none";
  1382. break;
  1383. case ZONE_HATCH_STYLE::DIAGONAL_EDGE:
  1384. hatch = "edge";
  1385. break;
  1386. case ZONE_HATCH_STYLE::DIAGONAL_FULL:
  1387. hatch = "full";
  1388. break;
  1389. }
  1390. m_out->Print( 0, " (hatch %s %s)\n", hatch.c_str(),
  1391. FormatInternalUnits( aZone->GetHatchPitch() ).c_str() );
  1392. if( aZone->GetPriority() > 0 )
  1393. m_out->Print( aNestLevel+1, "(priority %d)\n", aZone->GetPriority() );
  1394. m_out->Print( aNestLevel+1, "(connect_pads" );
  1395. switch( aZone->GetPadConnection() )
  1396. {
  1397. default:
  1398. case ZONE_CONNECTION::THERMAL: // Default option not saved or loaded.
  1399. break;
  1400. case ZONE_CONNECTION::THT_THERMAL:
  1401. m_out->Print( 0, " thru_hole_only" );
  1402. break;
  1403. case ZONE_CONNECTION::FULL:
  1404. m_out->Print( 0, " yes" );
  1405. break;
  1406. case ZONE_CONNECTION::NONE:
  1407. m_out->Print( 0, " no" );
  1408. break;
  1409. }
  1410. m_out->Print( 0, " (clearance %s))\n",
  1411. FormatInternalUnits( aZone->GetZoneClearance() ).c_str() );
  1412. m_out->Print( aNestLevel+1, "(min_thickness %s)",
  1413. FormatInternalUnits( aZone->GetMinThickness() ).c_str() );
  1414. // write it only if V 6.O version option is not used (i.e. do not write if the
  1415. // "legacy" algorithm is used)
  1416. if( !aZone->GetFilledPolysUseThickness() )
  1417. m_out->Print( 0, " (filled_areas_thickness no)" );
  1418. m_out->Print( 0, "\n" );
  1419. if( aZone->GetIsKeepout() )
  1420. {
  1421. m_out->Print( aNestLevel+1, "(keepout (tracks %s) (vias %s) (pads %s ) (copperpour %s) (footprints %s))\n",
  1422. aZone->GetDoNotAllowTracks() ? "not_allowed" : "allowed",
  1423. aZone->GetDoNotAllowVias() ? "not_allowed" : "allowed",
  1424. aZone->GetDoNotAllowPads() ? "not_allowed" : "allowed",
  1425. aZone->GetDoNotAllowCopperPour() ? "not_allowed" : "allowed",
  1426. aZone->GetDoNotAllowFootprints() ? "not_allowed" : "allowed" );
  1427. }
  1428. m_out->Print( aNestLevel+1, "(fill" );
  1429. // Default is not filled.
  1430. if( aZone->IsFilled() )
  1431. m_out->Print( 0, " yes" );
  1432. // Default is polygon filled.
  1433. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1434. m_out->Print( 0, " (mode hatch)" );
  1435. m_out->Print( 0, " (thermal_gap %s) (thermal_bridge_width %s)",
  1436. FormatInternalUnits( aZone->GetThermalReliefGap() ).c_str(),
  1437. FormatInternalUnits( aZone->GetThermalReliefCopperBridge() ).c_str() );
  1438. if( aZone->GetCornerSmoothingType() != ZONE_SETTINGS::SMOOTHING_NONE )
  1439. {
  1440. m_out->Print( 0, " (smoothing" );
  1441. switch( aZone->GetCornerSmoothingType() )
  1442. {
  1443. case ZONE_SETTINGS::SMOOTHING_CHAMFER:
  1444. m_out->Print( 0, " chamfer" );
  1445. break;
  1446. case ZONE_SETTINGS::SMOOTHING_FILLET:
  1447. m_out->Print( 0, " fillet" );
  1448. break;
  1449. default:
  1450. THROW_IO_ERROR( wxString::Format( _( "unknown zone corner smoothing type %d" ),
  1451. aZone->GetCornerSmoothingType() ) );
  1452. }
  1453. m_out->Print( 0, ")" );
  1454. if( aZone->GetCornerRadius() != 0 )
  1455. m_out->Print( 0, " (radius %s)",
  1456. FormatInternalUnits( aZone->GetCornerRadius() ).c_str() );
  1457. }
  1458. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1459. {
  1460. m_out->Print( 0, "\n" );
  1461. m_out->Print( aNestLevel+2, "(hatch_thickness %s) (hatch_gap %s) (hatch_orientation %s)",
  1462. FormatInternalUnits( aZone->GetHatchFillTypeThickness() ).c_str(),
  1463. FormatInternalUnits( aZone->GetHatchFillTypeGap() ).c_str(),
  1464. Double2Str( aZone->GetHatchFillTypeOrientation() ).c_str() );
  1465. if( aZone->GetHatchFillTypeSmoothingLevel() > 0 )
  1466. {
  1467. m_out->Print( 0, "\n" );
  1468. m_out->Print( aNestLevel+2, "(hatch_smoothing_level %d) (hatch_smoothing_value %s)",
  1469. aZone->GetHatchFillTypeSmoothingLevel(),
  1470. Double2Str( aZone->GetHatchFillTypeSmoothingValue() ).c_str() );
  1471. }
  1472. }
  1473. m_out->Print( 0, ")\n" );
  1474. int newLine = 0;
  1475. if( aZone->GetNumCorners() )
  1476. {
  1477. bool new_polygon = true;
  1478. bool is_closed = false;
  1479. for( auto iterator = aZone->IterateWithHoles(); iterator; iterator++ )
  1480. {
  1481. if( new_polygon )
  1482. {
  1483. newLine = 0;
  1484. m_out->Print( aNestLevel+1, "(polygon\n" );
  1485. m_out->Print( aNestLevel+2, "(pts\n" );
  1486. new_polygon = false;
  1487. is_closed = false;
  1488. }
  1489. if( newLine == 0 )
  1490. m_out->Print( aNestLevel+3, "(xy %s %s)",
  1491. FormatInternalUnits( iterator->x ).c_str(),
  1492. FormatInternalUnits( iterator->y ).c_str() );
  1493. else
  1494. m_out->Print( 0, " (xy %s %s)",
  1495. FormatInternalUnits( iterator->x ).c_str(),
  1496. FormatInternalUnits( iterator->y ).c_str() );
  1497. if( newLine < 4 )
  1498. {
  1499. newLine += 1;
  1500. }
  1501. else
  1502. {
  1503. newLine = 0;
  1504. m_out->Print( 0, "\n" );
  1505. }
  1506. if( iterator.IsEndContour() )
  1507. {
  1508. is_closed = true;
  1509. if( newLine != 0 )
  1510. m_out->Print( 0, "\n" );
  1511. m_out->Print( aNestLevel+2, ")\n" );
  1512. m_out->Print( aNestLevel+1, ")\n" );
  1513. new_polygon = true;
  1514. }
  1515. }
  1516. if( !is_closed ) // Should not happen, but...
  1517. {
  1518. if( newLine != 0 )
  1519. m_out->Print( 0, "\n" );
  1520. m_out->Print( aNestLevel+2, ")\n" );
  1521. m_out->Print( aNestLevel+1, ")\n" );
  1522. }
  1523. }
  1524. // Save the PolysList (filled areas)
  1525. const SHAPE_POLY_SET& fv = aZone->GetFilledPolysList();
  1526. newLine = 0;
  1527. if( !fv.IsEmpty() )
  1528. {
  1529. bool new_polygon = true;
  1530. bool is_closed = false;
  1531. for( auto it = fv.CIterate(); it; ++it )
  1532. {
  1533. if( new_polygon )
  1534. {
  1535. newLine = 0;
  1536. m_out->Print( aNestLevel+1, "(filled_polygon\n" );
  1537. m_out->Print( aNestLevel+2, "(pts\n" );
  1538. new_polygon = false;
  1539. is_closed = false;
  1540. }
  1541. if( newLine == 0 )
  1542. m_out->Print( aNestLevel+3, "(xy %s %s)",
  1543. FormatInternalUnits( it->x ).c_str(),
  1544. FormatInternalUnits( it->y ).c_str() );
  1545. else
  1546. m_out->Print( 0, " (xy %s %s)",
  1547. FormatInternalUnits( it->x ) .c_str(),
  1548. FormatInternalUnits( it->y ).c_str() );
  1549. if( newLine < 4 )
  1550. {
  1551. newLine += 1;
  1552. }
  1553. else
  1554. {
  1555. newLine = 0;
  1556. m_out->Print( 0, "\n" );
  1557. }
  1558. if( it.IsEndContour() )
  1559. {
  1560. is_closed = true;
  1561. if( newLine != 0 )
  1562. m_out->Print( 0, "\n" );
  1563. m_out->Print( aNestLevel+2, ")\n" );
  1564. m_out->Print( aNestLevel+1, ")\n" );
  1565. new_polygon = true;
  1566. }
  1567. }
  1568. if( !is_closed ) // Should not happen, but...
  1569. m_out->Print( aNestLevel+1, ")\n" );
  1570. }
  1571. // Save the filling segments list
  1572. const auto& segs = aZone->FillSegments();
  1573. if( segs.size() )
  1574. {
  1575. m_out->Print( aNestLevel+1, "(fill_segments\n" );
  1576. for( ZONE_SEGMENT_FILL::const_iterator it = segs.begin(); it != segs.end(); ++it )
  1577. {
  1578. m_out->Print( aNestLevel+2, "(pts (xy %s) (xy %s))\n",
  1579. FormatInternalUnits( wxPoint( it->A ) ).c_str(),
  1580. FormatInternalUnits( wxPoint( it->B ) ).c_str() );
  1581. }
  1582. m_out->Print( aNestLevel+1, ")\n" );
  1583. }
  1584. m_out->Print( aNestLevel, ")\n" );
  1585. }
  1586. PCB_IO::PCB_IO( int aControlFlags ) :
  1587. m_cache( 0 ),
  1588. m_ctl( aControlFlags ),
  1589. m_parser( new PCB_PARSER() ),
  1590. m_mapping( new NETINFO_MAPPING() )
  1591. {
  1592. init( 0 );
  1593. m_out = &m_sf;
  1594. }
  1595. PCB_IO::~PCB_IO()
  1596. {
  1597. delete m_cache;
  1598. delete m_parser;
  1599. delete m_mapping;
  1600. }
  1601. BOARD* PCB_IO::Load( const wxString& aFileName, BOARD* aAppendToMe, const PROPERTIES* aProperties )
  1602. {
  1603. FILE_LINE_READER reader( aFileName );
  1604. init( aProperties );
  1605. m_parser->SetLineReader( &reader );
  1606. m_parser->SetBoard( aAppendToMe );
  1607. BOARD* board;
  1608. try
  1609. {
  1610. board = dynamic_cast<BOARD*>( m_parser->Parse() );
  1611. }
  1612. catch( const FUTURE_FORMAT_ERROR& )
  1613. {
  1614. // Don't wrap a FUTURE_FORMAT_ERROR in another
  1615. throw;
  1616. }
  1617. catch( const PARSE_ERROR& parse_error )
  1618. {
  1619. if( m_parser->IsTooRecent() )
  1620. throw FUTURE_FORMAT_ERROR( parse_error, m_parser->GetRequiredVersion() );
  1621. else
  1622. throw;
  1623. }
  1624. if( !board )
  1625. {
  1626. // The parser loaded something that was valid, but wasn't a board.
  1627. THROW_PARSE_ERROR( _( "this file does not contain a PCB" ),
  1628. m_parser->CurSource(), m_parser->CurLine(),
  1629. m_parser->CurLineNumber(), m_parser->CurOffset() );
  1630. }
  1631. // Give the filename to the board if it's new
  1632. if( !aAppendToMe )
  1633. board->SetFileName( aFileName );
  1634. return board;
  1635. }
  1636. void PCB_IO::init( const PROPERTIES* aProperties )
  1637. {
  1638. m_board = NULL;
  1639. m_reader = NULL;
  1640. m_loading_format_version = SEXPR_BOARD_FILE_VERSION;
  1641. m_props = aProperties;
  1642. }
  1643. void PCB_IO::validateCache( const wxString& aLibraryPath, bool checkModified )
  1644. {
  1645. if( !m_cache || !m_cache->IsPath( aLibraryPath ) || ( checkModified && m_cache->IsModified() ) )
  1646. {
  1647. // a spectacular episode in memory management:
  1648. delete m_cache;
  1649. m_cache = new FP_CACHE( this, aLibraryPath );
  1650. m_cache->Load();
  1651. }
  1652. }
  1653. void PCB_IO::FootprintEnumerate( wxArrayString& aFootprintNames, const wxString& aLibPath,
  1654. bool aBestEfforts, const PROPERTIES* aProperties )
  1655. {
  1656. LOCALE_IO toggle; // toggles on, then off, the C locale.
  1657. wxDir dir( aLibPath );
  1658. wxString errorMsg;
  1659. init( aProperties );
  1660. try
  1661. {
  1662. validateCache( aLibPath );
  1663. }
  1664. catch( const IO_ERROR& ioe )
  1665. {
  1666. errorMsg = ioe.What();
  1667. }
  1668. // Some of the files may have been parsed correctly so we want to add the valid files to
  1669. // the library.
  1670. for( MODULE_CITER it = m_cache->GetModules().begin(); it != m_cache->GetModules().end(); ++it )
  1671. aFootprintNames.Add( it->first );
  1672. if( !errorMsg.IsEmpty() && !aBestEfforts )
  1673. THROW_IO_ERROR( errorMsg );
  1674. }
  1675. const MODULE* PCB_IO::getFootprint( const wxString& aLibraryPath,
  1676. const wxString& aFootprintName,
  1677. const PROPERTIES* aProperties,
  1678. bool checkModified )
  1679. {
  1680. LOCALE_IO toggle; // toggles on, then off, the C locale.
  1681. init( aProperties );
  1682. try
  1683. {
  1684. validateCache( aLibraryPath, checkModified );
  1685. }
  1686. catch( const IO_ERROR& )
  1687. {
  1688. // do nothing with the error
  1689. }
  1690. const MODULE_MAP& mods = m_cache->GetModules();
  1691. MODULE_CITER it = mods.find( aFootprintName );
  1692. if( it == mods.end() )
  1693. return nullptr;
  1694. return it->second->GetModule();
  1695. }
  1696. const MODULE* PCB_IO::GetEnumeratedFootprint( const wxString& aLibraryPath,
  1697. const wxString& aFootprintName,
  1698. const PROPERTIES* aProperties )
  1699. {
  1700. return getFootprint( aLibraryPath, aFootprintName, aProperties, false );
  1701. }
  1702. bool PCB_IO::FootprintExists( const wxString& aLibraryPath, const wxString& aFootprintName,
  1703. const PROPERTIES* aProperties )
  1704. {
  1705. // Note: checking the cache sounds like a good idea, but won't catch files which differ
  1706. // only in case.
  1707. //
  1708. // Since this goes out to the native filesystem, we get platform differences (ie: MSW's
  1709. // case-insensitive filesystem) handled "for free".
  1710. // Warning: footprint names frequently contain a point. So be careful when initializing
  1711. // wxFileName, and use a CTOR with extension specified
  1712. wxFileName footprintFile( aLibraryPath, aFootprintName, KiCadFootprintFileExtension );
  1713. return footprintFile.Exists();
  1714. }
  1715. MODULE* PCB_IO::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
  1716. const PROPERTIES* aProperties )
  1717. {
  1718. const MODULE* footprint = getFootprint( aLibraryPath, aFootprintName, aProperties, true );
  1719. return footprint ? (MODULE*) footprint->Duplicate() : nullptr;
  1720. }
  1721. void PCB_IO::FootprintSave( const wxString& aLibraryPath, const MODULE* aFootprint,
  1722. const PROPERTIES* aProperties )
  1723. {
  1724. LOCALE_IO toggle; // toggles on, then off, the C locale.
  1725. init( aProperties );
  1726. // In this public PLUGIN API function, we can safely assume it was
  1727. // called for saving into a library path.
  1728. m_ctl = CTL_FOR_LIBRARY;
  1729. validateCache( aLibraryPath );
  1730. if( !m_cache->IsWritable() )
  1731. {
  1732. if( !m_cache->Exists() )
  1733. {
  1734. const wxString msg = wxString::Format( _( "Library \"%s\" does not exist.\n"
  1735. "Would you like to create it?"),
  1736. GetChars( aLibraryPath ) );
  1737. if( wxMessageBox( msg, _( "Library Not Found"), wxYES_NO | wxICON_QUESTION ) != wxYES )
  1738. return;
  1739. // Save throws its own IO_ERROR on failure, so no need to recreate here
  1740. m_cache->Save( NULL );
  1741. }
  1742. else
  1743. {
  1744. wxString msg = wxString::Format( _( "Library \"%s\" is read only" ), aLibraryPath );
  1745. THROW_IO_ERROR( msg );
  1746. }
  1747. }
  1748. wxString footprintName = aFootprint->GetFPID().GetLibItemName();
  1749. MODULE_MAP& mods = m_cache->GetModules();
  1750. // Quietly overwrite module and delete module file from path for any by same name.
  1751. wxFileName fn( aLibraryPath, aFootprint->GetFPID().GetLibItemName(),
  1752. KiCadFootprintFileExtension );
  1753. #ifndef __WINDOWS__
  1754. // Write through symlinks, don't replace them
  1755. if( fn.Exists( wxFILE_EXISTS_SYMLINK ) )
  1756. {
  1757. char buffer[ PATH_MAX + 1 ];
  1758. ssize_t pathLen = readlink( TO_UTF8( fn.GetFullPath() ), buffer, PATH_MAX );
  1759. if( pathLen > 0 )
  1760. {
  1761. buffer[ pathLen ] = '\0';
  1762. fn.Assign( fn.GetPath() + wxT( "/" ) + wxString::FromUTF8( buffer ) );
  1763. fn.Normalize();
  1764. }
  1765. }
  1766. #endif
  1767. if( !fn.IsOk() )
  1768. {
  1769. THROW_IO_ERROR( wxString::Format( _( "Footprint file name \"%s\" is not valid." ),
  1770. fn.GetFullPath() ) );
  1771. }
  1772. if( fn.FileExists() && !fn.IsFileWritable() )
  1773. {
  1774. THROW_IO_ERROR( wxString::Format( _( "No write permissions to delete file \"%s\"" ),
  1775. fn.GetFullPath() ) );
  1776. }
  1777. wxString fullPath = fn.GetFullPath();
  1778. wxString fullName = fn.GetFullName();
  1779. MODULE_CITER it = mods.find( footprintName );
  1780. if( it != mods.end() )
  1781. {
  1782. wxLogTrace( traceKicadPcbPlugin, wxT( "Removing footprint file '%s'." ), fullPath );
  1783. mods.erase( footprintName );
  1784. wxRemoveFile( fullPath );
  1785. }
  1786. // I need my own copy for the cache
  1787. MODULE* module = static_cast<MODULE*>( aFootprint->Duplicate() );
  1788. // It should have no parent, orientation should be zero, and it should be on the front layer.
  1789. module->SetParent( nullptr );
  1790. module->SetOrientation( 0 );
  1791. if( module->GetLayer() != F_Cu )
  1792. {
  1793. auto cfg = dynamic_cast<PCBNEW_SETTINGS*>( Kiface().KifaceSettings() );
  1794. if( cfg )
  1795. module->Flip( module->GetPosition(), cfg->m_FlipLeftRight );
  1796. else
  1797. module->Flip( module->GetPosition(), false );
  1798. }
  1799. wxLogTrace( traceKicadPcbPlugin, wxT( "Creating s-expr footprint file '%s'." ), fullPath );
  1800. mods.insert( footprintName, new FP_CACHE_ITEM( module, WX_FILENAME( fn.GetPath(), fullName ) ) );
  1801. m_cache->Save( module );
  1802. }
  1803. void PCB_IO::FootprintDelete( const wxString& aLibraryPath, const wxString& aFootprintName,
  1804. const PROPERTIES* aProperties )
  1805. {
  1806. LOCALE_IO toggle; // toggles on, then off, the C locale.
  1807. init( aProperties );
  1808. validateCache( aLibraryPath );
  1809. if( !m_cache->IsWritable() )
  1810. {
  1811. THROW_IO_ERROR( wxString::Format( _( "Library \"%s\" is read only." ),
  1812. aLibraryPath.GetData() ) );
  1813. }
  1814. m_cache->Remove( aFootprintName );
  1815. }
  1816. long long PCB_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
  1817. {
  1818. return FP_CACHE::GetTimestamp( aLibraryPath );
  1819. }
  1820. void PCB_IO::FootprintLibCreate( const wxString& aLibraryPath, const PROPERTIES* aProperties )
  1821. {
  1822. if( wxDir::Exists( aLibraryPath ) )
  1823. {
  1824. THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path \"%s\"." ),
  1825. aLibraryPath.GetData() ) );
  1826. }
  1827. LOCALE_IO toggle;
  1828. init( aProperties );
  1829. delete m_cache;
  1830. m_cache = new FP_CACHE( this, aLibraryPath );
  1831. m_cache->Save();
  1832. }
  1833. bool PCB_IO::FootprintLibDelete( const wxString& aLibraryPath, const PROPERTIES* aProperties )
  1834. {
  1835. wxFileName fn;
  1836. fn.SetPath( aLibraryPath );
  1837. // Return if there is no library path to delete.
  1838. if( !fn.DirExists() )
  1839. return false;
  1840. if( !fn.IsDirWritable() )
  1841. {
  1842. THROW_IO_ERROR( wxString::Format( _( "User does not have permission to delete directory \"%s\"." ),
  1843. aLibraryPath.GetData() ) );
  1844. }
  1845. wxDir dir( aLibraryPath );
  1846. if( dir.HasSubDirs() )
  1847. {
  1848. THROW_IO_ERROR( wxString::Format( _( "Library directory \"%s\" has unexpected sub-directories." ),
  1849. aLibraryPath.GetData() ) );
  1850. }
  1851. // All the footprint files must be deleted before the directory can be deleted.
  1852. if( dir.HasFiles() )
  1853. {
  1854. unsigned i;
  1855. wxFileName tmp;
  1856. wxArrayString files;
  1857. wxDir::GetAllFiles( aLibraryPath, &files );
  1858. for( i = 0; i < files.GetCount(); i++ )
  1859. {
  1860. tmp = files[i];
  1861. if( tmp.GetExt() != KiCadFootprintFileExtension )
  1862. {
  1863. THROW_IO_ERROR( wxString::Format( _( "Unexpected file \"%s\" was found in library path \"%s\"." ),
  1864. files[i].GetData(), aLibraryPath.GetData() ) );
  1865. }
  1866. }
  1867. for( i = 0; i < files.GetCount(); i++ )
  1868. wxRemoveFile( files[i] );
  1869. }
  1870. wxLogTrace( traceKicadPcbPlugin, wxT( "Removing footprint library \"%s\"." ),
  1871. aLibraryPath.GetData() );
  1872. // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
  1873. // we don't want that. we want bare metal portability with no UI here.
  1874. if( !wxRmdir( aLibraryPath ) )
  1875. {
  1876. THROW_IO_ERROR( wxString::Format( _( "Footprint library \"%s\" cannot be deleted." ),
  1877. aLibraryPath.GetData() ) );
  1878. }
  1879. // For some reason removing a directory in Windows is not immediately updated. This delay
  1880. // prevents an error when attempting to immediately recreate the same directory when over
  1881. // writing an existing library.
  1882. #ifdef __WINDOWS__
  1883. wxMilliSleep( 250L );
  1884. #endif
  1885. if( m_cache && !m_cache->IsPath( aLibraryPath ) )
  1886. {
  1887. delete m_cache;
  1888. m_cache = NULL;
  1889. }
  1890. return true;
  1891. }
  1892. bool PCB_IO::IsFootprintLibWritable( const wxString& aLibraryPath )
  1893. {
  1894. LOCALE_IO toggle;
  1895. init( NULL );
  1896. validateCache( aLibraryPath );
  1897. return m_cache->IsWritable();
  1898. }