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.

679 lines
21 KiB

* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
3 years ago
3 years ago
3 years ago
3 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
3 years ago
3 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2010-2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  5. * Copyright (C) 2012 Wayne Stambaugh <stambaughw@gmail.com>
  6. * Copyright (C) 2012-2024 KiCad Developers, see AUTHORS.txt for contributors.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 2
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #include <kiface_base.h>
  26. #include <env_vars.h>
  27. #include <footprint_info.h>
  28. #include <lib_id.h>
  29. #include <lib_table_lexer.h>
  30. #include <paths.h>
  31. #include <pgm_base.h>
  32. #include <search_stack.h>
  33. #include <settings/kicad_settings.h>
  34. #include <settings/settings_manager.h>
  35. #include <systemdirsappend.h>
  36. #include <fp_lib_table.h>
  37. #include <footprint.h>
  38. #include <wx/dir.h>
  39. #include <wx/hash.h>
  40. #define OPT_SEP '|' ///< options separator character
  41. using namespace LIB_TABLE_T;
  42. static const wxChar global_tbl_name[] = wxT( "fp-lib-table" );
  43. bool FP_LIB_TABLE_ROW::operator==( const FP_LIB_TABLE_ROW& aRow ) const
  44. {
  45. return LIB_TABLE_ROW::operator == ( aRow ) && type == aRow.type;
  46. }
  47. void FP_LIB_TABLE_ROW::SetType( const wxString& aType )
  48. {
  49. type = PCB_IO_MGR::EnumFromStr( aType );
  50. if( PCB_IO_MGR::PCB_FILE_T( -1 ) == type )
  51. type = PCB_IO_MGR::KICAD_SEXP;
  52. plugin.reset();
  53. }
  54. FP_LIB_TABLE::FP_LIB_TABLE( FP_LIB_TABLE* aFallBackTable ) :
  55. LIB_TABLE( aFallBackTable )
  56. {
  57. // not copying fall back, simply search aFallBackTable separately
  58. // if "nickName not found".
  59. }
  60. void FP_LIB_TABLE::Parse( LIB_TABLE_LEXER* in )
  61. {
  62. T tok;
  63. wxString errMsg; // to collect error messages
  64. // This table may be nested within a larger s-expression, or not.
  65. // Allow for parser of that optional containing s-epression to have looked ahead.
  66. if( in->CurTok() != T_fp_lib_table )
  67. {
  68. in->NeedLEFT();
  69. if( ( tok = in->NextTok() ) != T_fp_lib_table )
  70. in->Expecting( T_fp_lib_table );
  71. }
  72. while( ( tok = in->NextTok() ) != T_RIGHT )
  73. {
  74. std::unique_ptr<FP_LIB_TABLE_ROW> row = std::make_unique<FP_LIB_TABLE_ROW>();
  75. if( tok == T_EOF )
  76. in->Expecting( T_RIGHT );
  77. if( tok != T_LEFT )
  78. in->Expecting( T_LEFT );
  79. // in case there is a "row integrity" error, tell where later.
  80. int lineNum = in->CurLineNumber();
  81. tok = in->NextTok();
  82. // Optionally parse the current version number
  83. if( tok == T_version )
  84. {
  85. in->NeedNUMBER( "version" );
  86. m_version = std::stoi( in->CurText() );
  87. in->NeedRIGHT();
  88. continue;
  89. }
  90. if( tok != T_lib )
  91. in->Expecting( T_lib );
  92. // (name NICKNAME)
  93. in->NeedLEFT();
  94. if( ( tok = in->NextTok() ) != T_name )
  95. in->Expecting( T_name );
  96. in->NeedSYMBOLorNUMBER();
  97. row->SetNickName( in->FromUTF8() );
  98. in->NeedRIGHT();
  99. // After (name), remaining (lib) elements are order independent, and in
  100. // some cases optional.
  101. bool sawType = false;
  102. bool sawOpts = false;
  103. bool sawDesc = false;
  104. bool sawUri = false;
  105. bool sawDisabled = false;
  106. while( ( tok = in->NextTok() ) != T_RIGHT )
  107. {
  108. if( tok == T_EOF )
  109. in->Unexpected( T_EOF );
  110. if( tok != T_LEFT )
  111. in->Expecting( T_LEFT );
  112. tok = in->NeedSYMBOLorNUMBER();
  113. switch( tok )
  114. {
  115. case T_uri:
  116. if( sawUri )
  117. in->Duplicate( tok );
  118. sawUri = true;
  119. in->NeedSYMBOLorNUMBER();
  120. row->SetFullURI( in->FromUTF8() );
  121. break;
  122. case T_type:
  123. if( sawType )
  124. in->Duplicate( tok );
  125. sawType = true;
  126. in->NeedSYMBOLorNUMBER();
  127. row->SetType( in->FromUTF8() );
  128. break;
  129. case T_options:
  130. if( sawOpts )
  131. in->Duplicate( tok );
  132. sawOpts = true;
  133. in->NeedSYMBOLorNUMBER();
  134. row->SetOptions( in->FromUTF8() );
  135. break;
  136. case T_descr:
  137. if( sawDesc )
  138. in->Duplicate( tok );
  139. sawDesc = true;
  140. in->NeedSYMBOLorNUMBER();
  141. row->SetDescr( in->FromUTF8() );
  142. break;
  143. case T_disabled:
  144. if( sawDisabled )
  145. in->Duplicate( tok );
  146. sawDisabled = true;
  147. row->SetEnabled( false );
  148. break;
  149. case T_hidden:
  150. // Hiding footprint libraries is not yet supported. Unclear what path can set this
  151. // attribute, but clear it on load.
  152. row->SetVisible();
  153. break;
  154. default:
  155. in->Unexpected( tok );
  156. }
  157. in->NeedRIGHT();
  158. }
  159. if( !sawType )
  160. in->Expecting( T_type );
  161. if( !sawUri )
  162. in->Expecting( T_uri );
  163. // All nickNames within this table fragment must be unique, so we do not use doReplace
  164. // in doInsertRow(). (However a fallBack table can have a conflicting nickName and ours
  165. // will supercede that one since in FindLib() we search this table before any fall back.)
  166. wxString nickname = row->GetNickName(); // store it to be able to used it
  167. // after row deletion if an error occurs
  168. bool doReplace = false;
  169. LIB_TABLE_ROW* tmp = row.release();
  170. if( !doInsertRow( tmp, doReplace ) )
  171. {
  172. delete tmp; // The table did not take ownership of the row.
  173. wxString msg = wxString::Format( _( "Duplicate library nickname '%s' found in "
  174. "footprint library table file line %d." ),
  175. nickname,
  176. lineNum );
  177. if( !errMsg.IsEmpty() )
  178. errMsg << '\n';
  179. errMsg << msg;
  180. }
  181. }
  182. if( !errMsg.IsEmpty() )
  183. THROW_IO_ERROR( errMsg );
  184. }
  185. bool FP_LIB_TABLE::operator==( const FP_LIB_TABLE& aFpTable ) const
  186. {
  187. if( m_rows.size() == aFpTable.m_rows.size() )
  188. {
  189. for( unsigned i = 0; i < m_rows.size(); ++i )
  190. {
  191. if( (FP_LIB_TABLE_ROW&)m_rows[i] != (FP_LIB_TABLE_ROW&)aFpTable.m_rows[i] )
  192. return false;
  193. }
  194. return true;
  195. }
  196. return false;
  197. }
  198. void FP_LIB_TABLE::Format( OUTPUTFORMATTER* aOutput, int aIndentLevel ) const
  199. {
  200. aOutput->Print( aIndentLevel, "(fp_lib_table\n" );
  201. aOutput->Print( aIndentLevel + 1, "(version %d)\n", m_version );
  202. for( LIB_TABLE_ROWS_CITER it = m_rows.begin(); it != m_rows.end(); ++it )
  203. it->Format( aOutput, aIndentLevel+1 );
  204. aOutput->Print( aIndentLevel, ")\n" );
  205. }
  206. long long FP_LIB_TABLE::GenerateTimestamp( const wxString* aNickname )
  207. {
  208. long long hash = 0;
  209. if( aNickname )
  210. {
  211. const FP_LIB_TABLE_ROW* row = FindRow( *aNickname, true );
  212. wxCHECK( row && row->plugin, hash );
  213. return row->plugin->GetLibraryTimestamp( row->GetFullURI( true ) ) +
  214. wxHashTable::MakeKey( *aNickname );
  215. }
  216. for( const wxString& nickname : GetLogicalLibs() )
  217. {
  218. const FP_LIB_TABLE_ROW* row = nullptr;
  219. try
  220. {
  221. row = FindRow( nickname, true );
  222. }
  223. catch( ... )
  224. {
  225. // Do nothing if not found: just skip.
  226. }
  227. wxCHECK2( row && row->plugin, continue );
  228. hash += row->plugin->GetLibraryTimestamp( row->GetFullURI( true ) ) +
  229. wxHashTable::MakeKey( nickname );
  230. }
  231. return hash;
  232. }
  233. void FP_LIB_TABLE::FootprintEnumerate( wxArrayString& aFootprintNames, const wxString& aNickname,
  234. bool aBestEfforts )
  235. {
  236. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  237. wxASSERT( row->plugin );
  238. row->plugin->FootprintEnumerate( aFootprintNames, row->GetFullURI( true ), aBestEfforts,
  239. row->GetProperties() );
  240. }
  241. void FP_LIB_TABLE::PrefetchLib( const wxString& aNickname )
  242. {
  243. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  244. wxASSERT( row->plugin );
  245. row->plugin->PrefetchLib( row->GetFullURI( true ), row->GetProperties() );
  246. }
  247. const FP_LIB_TABLE_ROW* FP_LIB_TABLE::FindRow( const wxString& aNickname, bool aCheckIfEnabled )
  248. {
  249. FP_LIB_TABLE_ROW* row = static_cast<FP_LIB_TABLE_ROW*>( findRow( aNickname, aCheckIfEnabled ) );
  250. if( !row )
  251. {
  252. // We don't generally show this string to the user (who is unlikely to know what
  253. // "fp-lib-table" means), and translating it may produce Sentry KICAD-YP.
  254. wxString msg = wxString::Format( wxS( "'%s' not found in fp-lib-table." ), aNickname );
  255. THROW_IO_ERROR( msg );
  256. }
  257. // We've been 'lazy' up until now, but it cannot be deferred any longer; instantiate a
  258. // PCB_IO of the proper kind if it is not already in this FP_LIB_TABLE_ROW.
  259. if( !row->plugin )
  260. row->setPlugin( PCB_IO_MGR::PluginFind( row->type ) );
  261. return row;
  262. }
  263. static void setLibNickname( FOOTPRINT* aModule, const wxString& aNickname,
  264. const wxString& aFootprintName )
  265. {
  266. // The library cannot know its own name, because it might have been renamed or moved.
  267. // Therefore footprints cannot know their own library nickname when residing in
  268. // a footprint library.
  269. // Only at this API layer can we tell the footprint about its actual library nickname.
  270. if( aModule )
  271. {
  272. // remove "const"-ness, I really do want to set nickname without
  273. // having to copy the LIB_ID and its two strings, twice each.
  274. LIB_ID& fpid = (LIB_ID&) aModule->GetFPID();
  275. // Catch any misbehaving plugin, which should be setting internal footprint name properly:
  276. wxASSERT( aFootprintName == fpid.GetLibItemName().wx_str() );
  277. // and clearing nickname
  278. wxASSERT( !fpid.GetLibNickname().size() );
  279. fpid.SetLibNickname( aNickname );
  280. }
  281. }
  282. const FOOTPRINT* FP_LIB_TABLE::GetEnumeratedFootprint( const wxString& aNickname,
  283. const wxString& aFootprintName )
  284. {
  285. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  286. wxASSERT( row->plugin );
  287. return row->plugin->GetEnumeratedFootprint( row->GetFullURI( true ), aFootprintName,
  288. row->GetProperties() );
  289. }
  290. bool FP_LIB_TABLE::FootprintExists( const wxString& aNickname, const wxString& aFootprintName )
  291. {
  292. try
  293. {
  294. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  295. wxASSERT( row->plugin );
  296. return row->plugin->FootprintExists( row->GetFullURI( true ), aFootprintName,
  297. row->GetProperties() );
  298. }
  299. catch( ... )
  300. {
  301. return false;
  302. }
  303. }
  304. FOOTPRINT* FP_LIB_TABLE::FootprintLoad( const wxString& aNickname,
  305. const wxString& aFootprintName, bool aKeepUUID )
  306. {
  307. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  308. wxASSERT( row->plugin );
  309. FOOTPRINT* ret = row->plugin->FootprintLoad( row->GetFullURI( true ), aFootprintName,
  310. aKeepUUID, row->GetProperties() );
  311. setLibNickname( ret, row->GetNickName(), aFootprintName );
  312. return ret;
  313. }
  314. FP_LIB_TABLE::SAVE_T FP_LIB_TABLE::FootprintSave( const wxString& aNickname,
  315. const FOOTPRINT* aFootprint, bool aOverwrite )
  316. {
  317. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  318. wxASSERT( row->plugin );
  319. if( !aOverwrite )
  320. {
  321. // Try loading the footprint to see if it already exists, caller wants overwrite
  322. // protection, which is atypical, not the default.
  323. wxString fpname = aFootprint->GetFPID().GetLibItemName();
  324. std::unique_ptr<FOOTPRINT> footprint( row->plugin->FootprintLoad( row->GetFullURI( true ),
  325. fpname,
  326. row->GetProperties() ) );
  327. if( footprint.get() )
  328. return SAVE_SKIPPED;
  329. }
  330. row->plugin->FootprintSave( row->GetFullURI( true ), aFootprint, row->GetProperties() );
  331. return SAVE_OK;
  332. }
  333. void FP_LIB_TABLE::FootprintDelete( const wxString& aNickname, const wxString& aFootprintName )
  334. {
  335. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  336. wxASSERT( row->plugin );
  337. return row->plugin->FootprintDelete( row->GetFullURI( true ), aFootprintName,
  338. row->GetProperties() );
  339. }
  340. bool FP_LIB_TABLE::IsFootprintLibWritable( const wxString& aNickname )
  341. {
  342. try
  343. {
  344. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  345. if( !row || !row->plugin )
  346. return false;
  347. return row->plugin->IsLibraryWritable( row->GetFullURI( true ) );
  348. }
  349. catch( ... )
  350. {
  351. }
  352. // aNickname not found, so the library is not writable
  353. return false;
  354. }
  355. void FP_LIB_TABLE::FootprintLibDelete( const wxString& aNickname )
  356. {
  357. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  358. wxASSERT( row->plugin );
  359. row->plugin->DeleteLibrary( row->GetFullURI( true ), row->GetProperties() );
  360. }
  361. void FP_LIB_TABLE::FootprintLibCreate( const wxString& aNickname )
  362. {
  363. const FP_LIB_TABLE_ROW* row = FindRow( aNickname, true );
  364. wxASSERT( row->plugin );
  365. row->plugin->CreateLibrary( row->GetFullURI( true ), row->GetProperties() );
  366. }
  367. FOOTPRINT* FP_LIB_TABLE::FootprintLoadWithOptionalNickname( const LIB_ID& aFootprintId,
  368. bool aKeepUUID )
  369. {
  370. wxString nickname = aFootprintId.GetLibNickname();
  371. wxString fpname = aFootprintId.GetLibItemName();
  372. if( nickname.size() )
  373. {
  374. return FootprintLoad( nickname, fpname, aKeepUUID );
  375. }
  376. // nickname is empty, sequentially search (alphabetically) all libs/nicks for first match:
  377. else
  378. {
  379. std::vector<wxString> nicks = GetLogicalLibs();
  380. // Search each library going through libraries alphabetically.
  381. for( unsigned i = 0; i < nicks.size(); ++i )
  382. {
  383. // FootprintLoad() returns NULL on not found, does not throw exception
  384. // unless there's an IO_ERROR.
  385. FOOTPRINT* ret = FootprintLoad( nicks[i], fpname, aKeepUUID );
  386. if( ret )
  387. return ret;
  388. }
  389. return nullptr;
  390. }
  391. }
  392. const wxString FP_LIB_TABLE::GlobalPathEnvVariableName()
  393. {
  394. return ENV_VAR::GetVersionedEnvVarName( wxS( "FOOTPRINT_DIR" ) );
  395. }
  396. class PCM_FP_LIB_TRAVERSER final : public wxDirTraverser
  397. {
  398. public:
  399. explicit PCM_FP_LIB_TRAVERSER( const wxString& aPath, FP_LIB_TABLE& aTable,
  400. const wxString& aPrefix ) :
  401. m_lib_table( aTable ),
  402. m_path_prefix( aPath ),
  403. m_lib_prefix( aPrefix )
  404. {
  405. wxFileName f( aPath, wxS( "" ) );
  406. m_prefix_dir_count = f.GetDirCount();
  407. }
  408. wxDirTraverseResult OnFile( const wxString& aFilePath ) override { return wxDIR_CONTINUE; }
  409. wxDirTraverseResult OnDir( const wxString& dirPath ) override
  410. {
  411. wxFileName dir = wxFileName::DirName( dirPath );
  412. // consider a directory to be a lib if it's name ends with .pretty and
  413. // it is under $KICADn_3RD_PARTY/footprints/<pkgid>/ i.e. has nested level of at least +3
  414. if( dirPath.EndsWith( wxS( ".pretty" ) ) && dir.GetDirCount() >= m_prefix_dir_count + 3 )
  415. {
  416. wxString versionedPath = wxString::Format( wxS( "${%s}" ),
  417. ENV_VAR::GetVersionedEnvVarName( wxS( "3RD_PARTY" ) ) );
  418. wxArrayString parts = dir.GetDirs();
  419. parts.RemoveAt( 0, m_prefix_dir_count );
  420. parts.Insert( versionedPath, 0 );
  421. wxString libPath = wxJoin( parts, '/' );
  422. if( !m_lib_table.HasLibraryWithPath( libPath ) )
  423. {
  424. wxString name = parts.Last().substr( 0, parts.Last().length() - 7 );
  425. wxString nickname = wxString::Format( wxS( "%s%s" ), m_lib_prefix, name );
  426. if( m_lib_table.HasLibrary( nickname ) )
  427. {
  428. int increment = 1;
  429. do
  430. {
  431. nickname = wxString::Format( wxS( "%s%s_%d" ), m_lib_prefix, name, increment );
  432. increment++;
  433. } while( m_lib_table.HasLibrary( nickname ) );
  434. }
  435. m_lib_table.InsertRow(
  436. new FP_LIB_TABLE_ROW( nickname, libPath, wxT( "KiCad" ), wxEmptyString,
  437. _( "Added by Plugin and Content Manager" ) ) );
  438. }
  439. }
  440. return wxDIR_CONTINUE;
  441. }
  442. private:
  443. FP_LIB_TABLE& m_lib_table;
  444. wxString m_path_prefix;
  445. wxString m_lib_prefix;
  446. size_t m_prefix_dir_count;
  447. };
  448. bool FP_LIB_TABLE::LoadGlobalTable( FP_LIB_TABLE& aTable )
  449. {
  450. bool tableExists = true;
  451. wxFileName fn = GetGlobalTableFileName();
  452. if( !fn.FileExists() )
  453. {
  454. tableExists = false;
  455. if( !fn.DirExists() && !fn.Mkdir( 0x777, wxPATH_MKDIR_FULL ) )
  456. {
  457. THROW_IO_ERROR( wxString::Format( _( "Cannot create global library table path '%s'." ),
  458. fn.GetPath() ) );
  459. }
  460. // Attempt to copy the default global file table from the KiCad
  461. // template folder to the user's home configuration path.
  462. SEARCH_STACK ss;
  463. SystemDirsAppend( &ss );
  464. const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
  465. std::optional<wxString> v = ENV_VAR::GetVersionedEnvVarValue( envVars,
  466. wxT( "TEMPLATE_DIR" ) );
  467. if( v && !v->IsEmpty() )
  468. ss.AddPaths( *v, 0 );
  469. wxString fileName = ss.FindValidPath( global_tbl_name );
  470. // The fallback is to create an empty global footprint table for the user to populate.
  471. if( fileName.IsEmpty() || !::wxCopyFile( fileName, fn.GetFullPath(), false ) )
  472. {
  473. FP_LIB_TABLE emptyTable;
  474. emptyTable.Save( fn.GetFullPath() );
  475. }
  476. }
  477. aTable.Load( fn.GetFullPath() );
  478. SETTINGS_MANAGER& mgr = Pgm().GetSettingsManager();
  479. KICAD_SETTINGS* settings = mgr.GetAppSettings<KICAD_SETTINGS>( "kicad" );
  480. const ENV_VAR_MAP& env = Pgm().GetLocalEnvVariables();
  481. wxString packagesPath;
  482. if( std::optional<wxString> v = ENV_VAR::GetVersionedEnvVarValue( env, wxT( "3RD_PARTY" ) ) )
  483. packagesPath = *v;
  484. if( settings->m_PcmLibAutoAdd )
  485. {
  486. // Scan for libraries in PCM packages directory
  487. wxFileName d( packagesPath, wxS( "" ) );
  488. d.AppendDir( wxS( "footprints" ) );
  489. if( d.DirExists() )
  490. {
  491. PCM_FP_LIB_TRAVERSER traverser( packagesPath, aTable, settings->m_PcmLibPrefix );
  492. wxDir dir( d.GetPath() );
  493. dir.Traverse( traverser );
  494. }
  495. }
  496. if( settings->m_PcmLibAutoRemove )
  497. {
  498. // Remove PCM libraries that no longer exist
  499. std::vector<wxString> to_remove;
  500. for( size_t i = 0; i < aTable.GetCount(); i++ )
  501. {
  502. LIB_TABLE_ROW& row = aTable.At( i );
  503. wxString path = row.GetFullURI( true );
  504. if( path.StartsWith( packagesPath ) && !wxDir::Exists( path ) )
  505. to_remove.push_back( row.GetNickName() );
  506. }
  507. for( const wxString& nickName : to_remove )
  508. aTable.RemoveRow( aTable.FindRow( nickName ) );
  509. }
  510. return tableExists;
  511. }
  512. wxString FP_LIB_TABLE::GetGlobalTableFileName()
  513. {
  514. wxFileName fn;
  515. fn.SetPath( PATHS::GetUserSettingsPath() );
  516. fn.SetName( global_tbl_name );
  517. return fn.GetFullPath();
  518. }