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.

1395 lines
44 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
18 years ago
18 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
15 years ago
15 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
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 1992-2023 KiCad Developers, see AUTHORS.txt for contributors.
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, you may find one here:
  18. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  19. * or you may search the http://www.gnu.org website for the version 2 license,
  20. * or you may write to the Free Software Foundation, Inc.,
  21. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  22. */
  23. #include <wx/ffile.h>
  24. #include <pgm_base.h>
  25. #include <kiface_base.h>
  26. #include <confirm.h>
  27. #include <string_utils.h>
  28. #include <macros.h>
  29. #include <pcb_edit_frame.h>
  30. #include <eda_list_dialog.h>
  31. #include <filter_reader.h>
  32. #include <fp_lib_table.h>
  33. #include <validators.h>
  34. #include <dialogs/dialog_text_entry.h>
  35. #include <tool/tool_manager.h>
  36. #include <tools/pcb_actions.h>
  37. #include <tools/board_editor_control.h>
  38. #include <tools/pad_tool.h>
  39. #include <footprint.h>
  40. #include <pcb_group.h>
  41. #include <board_commit.h>
  42. #include <footprint_edit_frame.h>
  43. #include <wildcards_and_files_ext.h>
  44. #include <pcb_io/kicad_legacy/pcb_io_kicad_legacy.h>
  45. #include <pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.h>
  46. #include <env_paths.h>
  47. #include <paths.h>
  48. #include <settings/settings_manager.h>
  49. #include <project_pcb.h>
  50. #include <project/project_file.h>
  51. #include <footprint_editor_settings.h>
  52. #include <footprint_viewer_frame.h>
  53. #include <wx/choicdlg.h>
  54. #include <wx/filedlg.h>
  55. #include <wx/fswatcher.h>
  56. // unique, "file local" translations:
  57. static const wxString INFO_LEGACY_LIB_WARN_EDIT(
  58. _( "Writing/modifying legacy libraries (.mod files) is not allowed\n"\
  59. "Please save the current library to the new .pretty format\n"\
  60. "and update your footprint lib table\n"\
  61. "to save your footprint (a .kicad_mod file) in the .pretty library folder" ) );
  62. static const wxString INFO_LEGACY_LIB_WARN_DELETE(
  63. _( "Modifying legacy libraries (.mod files) is not allowed\n"\
  64. "Please save the current library under the new .pretty format\n"\
  65. "and update your footprint lib table\n"\
  66. "before deleting a footprint" ) );
  67. FOOTPRINT* FOOTPRINT_EDIT_FRAME::ImportFootprint( const wxString& aName )
  68. {
  69. wxFileName fn;
  70. if( !aName.empty() )
  71. {
  72. fn = aName;
  73. }
  74. else
  75. {
  76. // Prompt the user for a footprint file to open.
  77. static int lastFilterIndex = 0; // To store the last choice during a session.
  78. wxString fileFiltersStr;
  79. std::vector<std::string> allExtensions;
  80. std::set<wxString> allWildcardsSet;
  81. for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
  82. {
  83. IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
  84. if( !pi )
  85. continue;
  86. const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryFileDesc();
  87. if( !desc )
  88. continue;
  89. if( !fileFiltersStr.IsEmpty() )
  90. fileFiltersStr += wxChar( '|' );
  91. fileFiltersStr += desc.FileFilter();
  92. for( const std::string& ext : desc.m_FileExtensions )
  93. {
  94. allExtensions.emplace_back( ext );
  95. allWildcardsSet.insert( wxT( "*." ) + formatWildcardExt( ext ) + wxT( ";" ) );
  96. }
  97. }
  98. wxString allWildcardsStr;
  99. for( const wxString& wildcard : allWildcardsSet )
  100. allWildcardsStr << wildcard;
  101. fileFiltersStr = _( "All supported formats" ) + wxT( "|" ) + allWildcardsStr + wxT( "|" )
  102. + fileFiltersStr;
  103. wxFileDialog dlg( this, _( "Import Footprint" ), m_mruPath, wxEmptyString, fileFiltersStr,
  104. wxFD_OPEN | wxFD_FILE_MUST_EXIST );
  105. dlg.SetFilterIndex( lastFilterIndex );
  106. if( dlg.ShowModal() == wxID_CANCEL )
  107. return nullptr;
  108. lastFilterIndex = dlg.GetFilterIndex();
  109. fn = dlg.GetPath();
  110. }
  111. if( !fn.IsOk() )
  112. return nullptr;
  113. if( !wxFileExists( fn.GetFullPath() ) )
  114. {
  115. wxString msg = wxString::Format( _( "File '%s' not found." ), fn.GetFullPath() );
  116. DisplayError( this, msg );
  117. return nullptr;
  118. }
  119. m_mruPath = fn.GetPath();
  120. PCB_IO_MGR::PCB_FILE_T fileType = PCB_IO_MGR::FILE_TYPE_NONE;
  121. for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
  122. {
  123. IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
  124. if( !pi )
  125. continue;
  126. if( pi->GetLibraryFileDesc().m_FileExtensions.empty() )
  127. continue;
  128. if( pi->CanReadFootprint( fn.GetFullPath() ) )
  129. {
  130. fileType = plugin.m_type;
  131. break;
  132. }
  133. }
  134. if( fileType == PCB_IO_MGR::FILE_TYPE_NONE )
  135. {
  136. DisplayError( this, _( "Not a footprint file." ) );
  137. return nullptr;
  138. }
  139. FOOTPRINT* footprint = nullptr;
  140. wxString footprintName;
  141. try
  142. {
  143. IO_RELEASER<PCB_IO> pi( PCB_IO_MGR::PluginFind( fileType ) );
  144. footprint = pi->ImportFootprint( fn.GetFullPath(), footprintName);
  145. if( !footprint )
  146. {
  147. wxString msg = wxString::Format( _( "Unable to load footprint '%s' from '%s'" ),
  148. footprintName, fn.GetFullPath() );
  149. DisplayError( this, msg );
  150. return nullptr;
  151. }
  152. }
  153. catch( const IO_ERROR& ioe )
  154. {
  155. DisplayError( this, ioe.What() );
  156. // if the footprint is not loaded, exit.
  157. // However, even if an error happens, it can be loaded, because in KICAD and GPCB format,
  158. // a fp library is a set of separate files, and the error(s) are not necessary when
  159. // reading the selected file
  160. if( !footprint )
  161. return nullptr;
  162. }
  163. footprint->SetFPID( LIB_ID( wxEmptyString, footprintName ) );
  164. // Insert footprint in list
  165. AddFootprintToBoard( footprint );
  166. // Display info :
  167. SetMsgPanel( footprint );
  168. PlaceFootprint( footprint );
  169. footprint->SetPosition( VECTOR2I( 0, 0 ) );
  170. GetBoard()->BuildListOfNets();
  171. UpdateView();
  172. return footprint;
  173. }
  174. void FOOTPRINT_EDIT_FRAME::ExportFootprint( FOOTPRINT* aFootprint )
  175. {
  176. wxFileName fn;
  177. FOOTPRINT_EDITOR_SETTINGS* cfg = GetSettings();
  178. if( !aFootprint )
  179. return;
  180. fn.SetName( aFootprint->GetFPID().GetLibItemName() );
  181. wxString wildcard = FILEEXT::KiCadFootprintLibFileWildcard();
  182. fn.SetExt( FILEEXT::KiCadFootprintFileExtension );
  183. if( !cfg->m_LastExportPath.empty() )
  184. fn.SetPath( cfg->m_LastExportPath );
  185. else
  186. fn.SetPath( m_mruPath );
  187. wxFileDialog dlg( this, _( "Export Footprint" ), fn.GetPath(), fn.GetFullName(),
  188. wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
  189. if( dlg.ShowModal() == wxID_CANCEL )
  190. return;
  191. fn = EnsureFileExtension( dlg.GetPath(), FILEEXT::KiCadFootprintFileExtension );
  192. cfg->m_LastExportPath = fn.GetPath();
  193. try
  194. {
  195. // Export as *.kicad_pcb format, using a strategy which is specifically chosen
  196. // as an example on how it could also be used to send it to the system clipboard.
  197. PCB_IO_KICAD_SEXPR pcb_io(CTL_FOR_LIBRARY );
  198. /* This footprint should *already* be "normalized" in a way such that
  199. orientation is zero, etc., since it came from the Footprint Editor.
  200. aFootprint->SetParent( 0 );
  201. aFootprint->SetOrientation( 0 );
  202. */
  203. pcb_io.Format( aFootprint );
  204. FILE* fp = wxFopen( dlg.GetPath(), wxT( "wt" ) );
  205. if( fp == nullptr )
  206. {
  207. DisplayErrorMessage( this, wxString::Format( _( "Insufficient permissions to write file '%s'." ),
  208. dlg.GetPath() ) );
  209. return;
  210. }
  211. fprintf( fp, "%s", pcb_io.GetStringOutput( false ).c_str() );
  212. fclose( fp );
  213. }
  214. catch( const IO_ERROR& ioe )
  215. {
  216. DisplayError( this, ioe.What() );
  217. return;
  218. }
  219. wxString msg = wxString::Format( _( "Footprint exported to file '%s'." ), dlg.GetPath() );
  220. DisplayInfoMessage( this, msg );
  221. }
  222. wxString PCB_BASE_EDIT_FRAME::CreateNewProjectLibrary( const wxString& aLibName,
  223. const wxString& aProposedName )
  224. {
  225. return createNewLibrary( aLibName, aProposedName, PROJECT_PCB::PcbFootprintLibs( &Prj() ) );
  226. }
  227. wxString PCB_BASE_EDIT_FRAME::CreateNewLibrary( const wxString& aLibName,
  228. const wxString& aProposedName )
  229. {
  230. FP_LIB_TABLE* table = selectLibTable();
  231. return createNewLibrary( aLibName, aProposedName, table );
  232. }
  233. wxString PCB_BASE_EDIT_FRAME::createNewLibrary( const wxString& aLibName,
  234. const wxString& aProposedName,
  235. FP_LIB_TABLE* aTable )
  236. {
  237. // Kicad cannot write legacy format libraries, only .pretty new format because the legacy
  238. // format cannot handle current features.
  239. // The footprint library is actually a directory.
  240. if( aTable == nullptr )
  241. return wxEmptyString;
  242. wxString initialPath = aProposedName.IsEmpty() ? Prj().GetProjectPath() : aProposedName;
  243. wxFileName fn;
  244. bool doAdd = false;
  245. bool isGlobal = ( aTable == &GFootprintTable );
  246. if( aLibName.IsEmpty() )
  247. {
  248. fn = initialPath;
  249. if( !LibraryFileBrowser( false, fn, FILEEXT::KiCadFootprintLibPathWildcard(),
  250. FILEEXT::KiCadFootprintLibPathExtension, false, isGlobal,
  251. PATHS::GetDefaultUserFootprintsPath() ) )
  252. {
  253. return wxEmptyString;
  254. }
  255. doAdd = true;
  256. }
  257. else
  258. {
  259. fn = EnsureFileExtension( aLibName, FILEEXT::KiCadFootprintLibPathExtension );
  260. if( !fn.IsAbsolute() )
  261. {
  262. fn.SetName( aLibName );
  263. fn.MakeAbsolute( initialPath );
  264. }
  265. }
  266. // We can save fp libs only using PCB_IO_MGR::KICAD_SEXP format (.pretty libraries)
  267. PCB_IO_MGR::PCB_FILE_T piType = PCB_IO_MGR::KICAD_SEXP;
  268. wxString libPath = fn.GetFullPath();
  269. try
  270. {
  271. IO_RELEASER<PCB_IO> pi( PCB_IO_MGR::PluginFind( piType ) );
  272. bool writable = false;
  273. bool exists = false;
  274. try
  275. {
  276. writable = pi->IsLibraryWritable( libPath );
  277. exists = true; // no exception was thrown, lib must exist.
  278. }
  279. catch( const IO_ERROR& )
  280. {
  281. // best efforts....
  282. }
  283. if( exists )
  284. {
  285. if( !writable )
  286. {
  287. wxString msg = wxString::Format( _( "Library %s is read only." ), libPath );
  288. ShowInfoBarError( msg );
  289. return wxEmptyString;
  290. }
  291. else
  292. {
  293. wxString msg = wxString::Format( _( "Library %s already exists." ), libPath );
  294. KIDIALOG dlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
  295. dlg.SetOKLabel( _( "Overwrite" ) );
  296. dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
  297. if( dlg.ShowModal() == wxID_CANCEL )
  298. return wxEmptyString;
  299. pi->DeleteLibrary( libPath );
  300. }
  301. }
  302. pi->CreateLibrary( libPath );
  303. }
  304. catch( const IO_ERROR& ioe )
  305. {
  306. DisplayError( this, ioe.What() );
  307. return wxEmptyString;
  308. }
  309. if( doAdd )
  310. AddLibrary( libPath, aTable );
  311. return libPath;
  312. }
  313. FP_LIB_TABLE* PCB_BASE_EDIT_FRAME::selectLibTable( bool aOptional )
  314. {
  315. // If no project is loaded, always work with the global table
  316. if( Prj().IsNullProject() )
  317. {
  318. FP_LIB_TABLE* ret = &GFootprintTable;
  319. if( aOptional )
  320. {
  321. wxMessageDialog dlg( this, _( "Add the library to the global library table?" ),
  322. _( "Add To Global Library Table" ), wxYES_NO );
  323. if( dlg.ShowModal() != wxID_OK )
  324. ret = nullptr;
  325. }
  326. return ret;
  327. }
  328. wxArrayString libTableNames;
  329. libTableNames.Add( _( "Global" ) );
  330. libTableNames.Add( _( "Project" ) );
  331. wxSingleChoiceDialog dlg( this, _( "Choose the Library Table to add the library to:" ),
  332. _( "Add To Library Table" ), libTableNames );
  333. if( aOptional )
  334. {
  335. dlg.FindWindow( wxID_CANCEL )->SetLabel( _( "Skip" ) );
  336. dlg.FindWindow( wxID_OK )->SetLabel( _( "Add" ) );
  337. }
  338. if( dlg.ShowModal() != wxID_OK )
  339. return nullptr;
  340. switch( dlg.GetSelection() )
  341. {
  342. case 0: return &GFootprintTable;
  343. case 1: return PROJECT_PCB::PcbFootprintLibs( &Prj() );
  344. default: return nullptr;
  345. }
  346. }
  347. bool PCB_BASE_EDIT_FRAME::AddLibrary( const wxString& aFilename, FP_LIB_TABLE* aTable )
  348. {
  349. if( aTable == nullptr )
  350. aTable = selectLibTable();
  351. if( aTable == nullptr )
  352. return wxEmptyString;
  353. bool isGlobal = ( aTable == &GFootprintTable );
  354. wxFileName fn( aFilename );
  355. if( aFilename.IsEmpty() )
  356. {
  357. if( !LibraryFileBrowser( true, fn, FILEEXT::KiCadFootprintLibPathWildcard(),
  358. FILEEXT::KiCadFootprintLibPathExtension, true, isGlobal,
  359. PATHS::GetDefaultUserFootprintsPath() ) )
  360. {
  361. return false;
  362. }
  363. }
  364. wxString libPath = fn.GetFullPath();
  365. wxString libName = fn.GetName();
  366. if( libName.IsEmpty() )
  367. return false;
  368. PCB_IO_MGR::PCB_FILE_T lib_type = PCB_IO_MGR::GuessPluginTypeFromLibPath( libPath );
  369. if( lib_type == PCB_IO_MGR::FILE_TYPE_NONE )
  370. lib_type = PCB_IO_MGR::KICAD_SEXP;
  371. wxString type = PCB_IO_MGR::ShowType( lib_type );
  372. // KiCad lib is our default guess. So it might not have the .pretty extension
  373. // In this case, the extension is part of the library name
  374. if( lib_type == PCB_IO_MGR::KICAD_SEXP
  375. && fn.GetExt() != FILEEXT::KiCadFootprintLibPathExtension )
  376. libName = fn.GetFullName();
  377. // try to use path normalized to an environmental variable or project path
  378. wxString normalizedPath = NormalizePath( libPath, &Pgm().GetLocalEnvVariables(), &Prj() );
  379. try
  380. {
  381. FP_LIB_TABLE_ROW* row = new FP_LIB_TABLE_ROW( libName, normalizedPath, type, wxEmptyString );
  382. aTable->InsertRow( row );
  383. if( isGlobal )
  384. GFootprintTable.Save( FP_LIB_TABLE::GetGlobalTableFileName() );
  385. else
  386. PROJECT_PCB::PcbFootprintLibs( &Prj() )->Save( Prj().FootprintLibTblName() );
  387. }
  388. catch( const IO_ERROR& ioe )
  389. {
  390. DisplayError( this, ioe.What() );
  391. return false;
  392. }
  393. auto editor = (FOOTPRINT_EDIT_FRAME*) Kiway().Player( FRAME_FOOTPRINT_EDITOR, false );
  394. if( editor )
  395. {
  396. LIB_ID libID( libName, wxEmptyString );
  397. editor->SyncLibraryTree( true );
  398. editor->FocusOnLibID( libID );
  399. }
  400. auto viewer = (FOOTPRINT_VIEWER_FRAME*) Kiway().Player( FRAME_FOOTPRINT_VIEWER, false );
  401. if( viewer )
  402. viewer->ReCreateLibraryList();
  403. return true;
  404. }
  405. bool FOOTPRINT_EDIT_FRAME::DeleteFootprintFromLibrary( const LIB_ID& aFPID, bool aConfirm )
  406. {
  407. if( !aFPID.IsValid() )
  408. return false;
  409. wxString nickname = aFPID.GetLibNickname();
  410. wxString fpname = aFPID.GetLibItemName();
  411. // Legacy libraries are readable, but modifying legacy format is not allowed
  412. // So prompt the user if he try to delete a footprint from a legacy lib
  413. wxString libfullname = PROJECT_PCB::PcbFootprintLibs( &Prj() )->FindRow( nickname )->GetFullURI();
  414. if( PCB_IO_MGR::GuessPluginTypeFromLibPath( libfullname ) == PCB_IO_MGR::LEGACY )
  415. {
  416. DisplayInfoMessage( this, INFO_LEGACY_LIB_WARN_DELETE );
  417. return false;
  418. }
  419. if( !PROJECT_PCB::PcbFootprintLibs( &Prj() )->IsFootprintLibWritable( nickname ) )
  420. {
  421. wxString msg = wxString::Format( _( "Library '%s' is read only." ), nickname );
  422. ShowInfoBarError( msg );
  423. return false;
  424. }
  425. // Confirmation
  426. wxString msg = wxString::Format( _( "Delete footprint '%s' from library '%s'?" ),
  427. fpname.GetData(),
  428. nickname.GetData() );
  429. if( aConfirm && !IsOK( this, msg ) )
  430. return false;
  431. try
  432. {
  433. PROJECT_PCB::PcbFootprintLibs( &Prj() )->FootprintDelete( nickname, fpname );
  434. }
  435. catch( const IO_ERROR& ioe )
  436. {
  437. DisplayError( this, ioe.What() );
  438. return false;
  439. }
  440. msg.Printf( _( "Footprint '%s' deleted from library '%s'" ),
  441. fpname.GetData(),
  442. nickname.GetData() );
  443. SetStatusText( msg );
  444. return true;
  445. }
  446. void PCB_EDIT_FRAME::ExportFootprintsToLibrary( bool aStoreInNewLib, const wxString& aLibName,
  447. wxString* aLibPath )
  448. {
  449. if( GetBoard()->GetFirstFootprint() == nullptr )
  450. {
  451. DisplayInfoMessage( this, _( "No footprints to export!" ) );
  452. return;
  453. }
  454. wxString footprintName;
  455. auto resetReference =
  456. []( FOOTPRINT* aFootprint )
  457. {
  458. aFootprint->SetReference( "REF**" );
  459. };
  460. auto resetGroup =
  461. []( FOOTPRINT* aFootprint )
  462. {
  463. if( PCB_GROUP* parentGroup = aFootprint->GetParentGroup() )
  464. parentGroup->RemoveItem( aFootprint );
  465. };
  466. if( !aStoreInNewLib )
  467. {
  468. // The footprints are saved in an existing .pretty library in the fp lib table
  469. PROJECT& prj = Prj();
  470. wxString last_nickname = prj.GetRString( PROJECT::PCB_LIB_NICKNAME );
  471. wxString nickname = SelectLibrary( last_nickname );
  472. if( !nickname ) // Aborted
  473. return;
  474. bool map = IsOK( this, wxString::Format( _( "Update footprints on board to refer to %s?" ),
  475. nickname ) );
  476. prj.SetRString( PROJECT::PCB_LIB_NICKNAME, nickname );
  477. for( FOOTPRINT* footprint : GetBoard()->Footprints() )
  478. {
  479. try
  480. {
  481. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &prj );
  482. if( !footprint->GetFPID().GetLibItemName().empty() ) // Handle old boards.
  483. {
  484. FOOTPRINT* fpCopy = static_cast<FOOTPRINT*>( footprint->Duplicate() );
  485. // Reset reference designator and group membership before saving
  486. resetReference( fpCopy );
  487. resetGroup( fpCopy );
  488. tbl->FootprintSave( nickname, fpCopy, true );
  489. delete fpCopy;
  490. }
  491. }
  492. catch( const IO_ERROR& ioe )
  493. {
  494. DisplayError( this, ioe.What() );
  495. }
  496. if( map )
  497. {
  498. LIB_ID id = footprint->GetFPID();
  499. id.SetLibNickname( nickname );
  500. footprint->SetFPID( id );
  501. }
  502. }
  503. }
  504. else
  505. {
  506. // The footprints are saved in a new .pretty library.
  507. // If this library already exists, all previous footprints will be deleted
  508. wxString libPath = CreateNewLibrary( aLibName );
  509. if( libPath.IsEmpty() ) // Aborted
  510. return;
  511. if( aLibPath )
  512. *aLibPath = libPath;
  513. wxString libNickname;
  514. bool map = IsOK( this, _( "Update footprints on board to refer to new library?" ) );
  515. if( map )
  516. {
  517. const LIB_TABLE_ROW* row = PROJECT_PCB::PcbFootprintLibs( &Prj() )->FindRowByURI( libPath );
  518. if( row )
  519. libNickname = row->GetNickName();
  520. }
  521. PCB_IO_MGR::PCB_FILE_T piType = PCB_IO_MGR::KICAD_SEXP;
  522. IO_RELEASER<PCB_IO> pi( PCB_IO_MGR::PluginFind( piType ) );
  523. for( FOOTPRINT* footprint : GetBoard()->Footprints() )
  524. {
  525. try
  526. {
  527. if( !footprint->GetFPID().GetLibItemName().empty() ) // Handle old boards.
  528. {
  529. FOOTPRINT* fpCopy = static_cast<FOOTPRINT*>( footprint->Duplicate() );
  530. // Reset reference designator and group membership before saving
  531. resetReference( fpCopy );
  532. resetGroup( fpCopy );
  533. pi->FootprintSave( libPath, fpCopy );
  534. delete fpCopy;
  535. }
  536. }
  537. catch( const IO_ERROR& ioe )
  538. {
  539. DisplayError( this, ioe.What() );
  540. }
  541. if( map )
  542. {
  543. LIB_ID id = footprint->GetFPID();
  544. id.SetLibNickname( libNickname );
  545. footprint->SetFPID( id );
  546. }
  547. }
  548. }
  549. }
  550. bool FOOTPRINT_EDIT_FRAME::SaveFootprint( FOOTPRINT* aFootprint )
  551. {
  552. if( !aFootprint ) // Happen if no footprint loaded
  553. return false;
  554. PAD_TOOL* padTool = m_toolManager->GetTool<PAD_TOOL>();
  555. if( padTool->InPadEditMode() )
  556. m_toolManager->RunAction( PCB_ACTIONS::recombinePad );
  557. wxString libraryName = aFootprint->GetFPID().GetLibNickname();
  558. wxString footprintName = aFootprint->GetFPID().GetLibItemName();
  559. bool nameChanged = m_footprintNameWhenLoaded != footprintName;
  560. if( aFootprint->GetLink() != niluuid )
  561. {
  562. if( SaveFootprintToBoard( false ) )
  563. {
  564. m_footprintNameWhenLoaded = footprintName;
  565. return true;
  566. }
  567. else
  568. {
  569. return false;
  570. }
  571. }
  572. else if( libraryName.IsEmpty() || footprintName.IsEmpty() )
  573. {
  574. if( SaveFootprintAs( aFootprint ) )
  575. {
  576. m_footprintNameWhenLoaded = footprintName;
  577. SyncLibraryTree( true );
  578. return true;
  579. }
  580. else
  581. {
  582. return false;
  583. }
  584. }
  585. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &Prj() );
  586. // Legacy libraries are readable, but modifying legacy format is not allowed
  587. // So prompt the user if he try to add/replace a footprint in a legacy lib
  588. wxString libfullname;
  589. try
  590. {
  591. libfullname = tbl->FindRow( libraryName )->GetFullURI();
  592. }
  593. catch( IO_ERROR& error )
  594. {
  595. DisplayInfoMessage( this, error.What() );
  596. return false;
  597. }
  598. if( PCB_IO_MGR::GuessPluginTypeFromLibPath( libfullname ) == PCB_IO_MGR::LEGACY )
  599. {
  600. DisplayInfoMessage( this, INFO_LEGACY_LIB_WARN_EDIT );
  601. return false;
  602. }
  603. if( nameChanged )
  604. {
  605. LIB_ID oldFPID( libraryName, m_footprintNameWhenLoaded );
  606. DeleteFootprintFromLibrary( oldFPID, false );
  607. }
  608. if( !SaveFootprintInLibrary( aFootprint, libraryName ) )
  609. return false;
  610. if( nameChanged )
  611. {
  612. m_footprintNameWhenLoaded = footprintName;
  613. SyncLibraryTree( true );
  614. }
  615. return true;
  616. }
  617. bool FOOTPRINT_EDIT_FRAME::DuplicateFootprint( FOOTPRINT* aFootprint )
  618. {
  619. LIB_ID fpID = aFootprint->GetFPID();
  620. wxString libraryName = fpID.GetLibNickname();
  621. wxString footprintName = fpID.GetLibItemName();
  622. // Legacy libraries are readable, but modifying legacy format is not allowed
  623. // So prompt the user if he try to add/replace a footprint in a legacy lib
  624. wxString libFullName = PROJECT_PCB::PcbFootprintLibs( &Prj() )->FindRow( libraryName )->GetFullURI();
  625. if( PCB_IO_MGR::GuessPluginTypeFromLibPath( libFullName ) == PCB_IO_MGR::LEGACY )
  626. {
  627. DisplayInfoMessage( this, INFO_LEGACY_LIB_WARN_EDIT );
  628. return false;
  629. }
  630. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &Prj() );
  631. int i = 1;
  632. wxString newName = footprintName;
  633. // Append a number to the name until the name is unique in the library.
  634. while( tbl->FootprintExists( libraryName, newName ) )
  635. newName.Printf( "%s_%d", footprintName, i++ );
  636. aFootprint->SetFPID( LIB_ID( libraryName, newName ) );
  637. if( aFootprint->GetValue() == footprintName )
  638. aFootprint->SetValue( newName );
  639. return SaveFootprintInLibrary( aFootprint, libraryName );
  640. }
  641. bool FOOTPRINT_EDIT_FRAME::SaveFootprintInLibrary( FOOTPRINT* aFootprint,
  642. const wxString& aLibraryName )
  643. {
  644. try
  645. {
  646. aFootprint->SetFPID( LIB_ID( wxEmptyString, aFootprint->GetFPID().GetLibItemName() ) );
  647. PROJECT_PCB::PcbFootprintLibs( &Prj() )->FootprintSave( aLibraryName, aFootprint );
  648. aFootprint->SetFPID( LIB_ID( aLibraryName, aFootprint->GetFPID().GetLibItemName() ) );
  649. if( aFootprint == GetBoard()->GetFirstFootprint() )
  650. setFPWatcher( aFootprint );
  651. return true;
  652. }
  653. catch( const IO_ERROR& ioe )
  654. {
  655. DisplayError( this, ioe.What() );
  656. aFootprint->SetFPID( LIB_ID( aLibraryName, aFootprint->GetFPID().GetLibItemName() ) );
  657. return false;
  658. }
  659. }
  660. bool FOOTPRINT_EDIT_FRAME::SaveFootprintToBoard( bool aAddNew )
  661. {
  662. // update footprint in the current board,
  663. // not just add it to the board with total disregard for the netlist...
  664. PCB_EDIT_FRAME* pcbframe = (PCB_EDIT_FRAME*) Kiway().Player( FRAME_PCB_EDITOR, false );
  665. if( pcbframe == nullptr ) // happens when the board editor is not active (or closed)
  666. {
  667. ShowInfoBarError( _( "No board currently open." ) );
  668. return false;
  669. }
  670. BOARD* mainpcb = pcbframe->GetBoard();
  671. FOOTPRINT* sourceFootprint = nullptr;
  672. FOOTPRINT* editorFootprint = GetBoard()->GetFirstFootprint();
  673. // Search the old footprint (source) if exists
  674. // Because this source could be deleted when editing the main board...
  675. if( editorFootprint->GetLink() != niluuid ) // this is not a new footprint ...
  676. {
  677. sourceFootprint = nullptr;
  678. for( FOOTPRINT* candidate : mainpcb->Footprints() )
  679. {
  680. if( editorFootprint->GetLink() == candidate->m_Uuid )
  681. {
  682. sourceFootprint = candidate;
  683. break;
  684. }
  685. }
  686. }
  687. if( !aAddNew && sourceFootprint == nullptr ) // source not found
  688. {
  689. DisplayError( this, _( "Unable to find the footprint on the main board.\nCannot save." ) );
  690. return false;
  691. }
  692. TOOL_MANAGER* pcb_ToolManager = pcbframe->GetToolManager();
  693. if( aAddNew && pcb_ToolManager->GetTool<BOARD_EDITOR_CONTROL>()->PlacingFootprint() )
  694. {
  695. DisplayError( this, _( "Previous footprint placement still in progress." ) );
  696. return false;
  697. }
  698. m_toolManager->RunAction( PCB_ACTIONS::selectionClear );
  699. BOARD_COMMIT commit( pcbframe );
  700. // Create a copy for the board, first using Clone() to keep existing Uuids, and then either
  701. // resetting the uuids to the board values or assigning new Uuids.
  702. FOOTPRINT* newFootprint = static_cast<FOOTPRINT*>( editorFootprint->Clone() );
  703. newFootprint->SetParent( mainpcb );
  704. newFootprint->SetLink( niluuid );
  705. auto fixUuid =
  706. [&]( KIID& aUuid )
  707. {
  708. if( editorFootprint->GetLink() != niluuid && m_boardFootprintUuids.count( aUuid ) )
  709. aUuid = m_boardFootprintUuids[ aUuid ];
  710. else
  711. aUuid = KIID();
  712. };
  713. fixUuid( const_cast<KIID&>( newFootprint->m_Uuid ) );
  714. newFootprint->RunOnDescendants(
  715. [&]( BOARD_ITEM* aChild )
  716. {
  717. fixUuid( const_cast<KIID&>( aChild->m_Uuid ) );
  718. } );
  719. BOARD_DESIGN_SETTINGS& bds = m_pcb->GetDesignSettings();
  720. newFootprint->ApplyDefaultSettings( *m_pcb, bds.m_StyleFPFields, bds.m_StyleFPText,
  721. bds.m_StyleFPShapes );
  722. if( sourceFootprint ) // this is an update command
  723. {
  724. // In the main board the new footprint replaces the old one (pos, orient, ref, value,
  725. // connections and properties are kept) and the sourceFootprint (old footprint) is
  726. // deleted
  727. pcbframe->ExchangeFootprint( sourceFootprint, newFootprint, commit );
  728. commit.Push( _( "Update Footprint" ) );
  729. }
  730. else // This is an insert command
  731. {
  732. KIGFX::VIEW_CONTROLS* viewControls = pcbframe->GetCanvas()->GetViewControls();
  733. VECTOR2D cursorPos = viewControls->GetCursorPosition();
  734. commit.Add( newFootprint );
  735. viewControls->SetCrossHairCursorPosition( VECTOR2D( 0, 0 ), false );
  736. pcbframe->PlaceFootprint( newFootprint );
  737. newFootprint->SetPosition( VECTOR2I( 0, 0 ) );
  738. viewControls->SetCrossHairCursorPosition( cursorPos, false );
  739. const_cast<KIID&>( newFootprint->m_Uuid ) = KIID();
  740. commit.Push( _( "Insert Footprint" ) );
  741. pcbframe->Raise();
  742. pcb_ToolManager->RunAction( PCB_ACTIONS::placeFootprint, newFootprint );
  743. }
  744. newFootprint->ClearFlags();
  745. return true;
  746. }
  747. static int ID_MAKE_NEW_LIBRARY = 4173;
  748. class SAVE_AS_DIALOG : public EDA_LIST_DIALOG
  749. {
  750. public:
  751. SAVE_AS_DIALOG( FOOTPRINT_EDIT_FRAME* aParent, const wxString& aFootprintName,
  752. const wxString& aLibraryPreselect,
  753. std::function<bool( wxString libName, wxString fpName )> aValidator ) :
  754. EDA_LIST_DIALOG( aParent, _( "Save Footprint As" ), false ),
  755. m_validator( std::move( aValidator ) )
  756. {
  757. COMMON_SETTINGS* cfg = Pgm().GetCommonSettings();
  758. PROJECT_FILE& project = aParent->Prj().GetProjectFile();
  759. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &aParent->Prj() );
  760. std::vector<wxString> nicknames = tbl->GetLogicalLibs();
  761. wxArrayString headers;
  762. std::vector<wxArrayString> itemsToDisplay;
  763. headers.Add( _( "Nickname" ) );
  764. headers.Add( _( "Description" ) );
  765. for( const wxString& nickname : nicknames )
  766. {
  767. if( alg::contains( project.m_PinnedFootprintLibs, nickname )
  768. || alg::contains( cfg->m_Session.pinned_fp_libs, nickname ) )
  769. {
  770. wxArrayString item;
  771. item.Add( LIB_TREE_MODEL_ADAPTER::GetPinningSymbol() + nickname );
  772. item.Add( tbl->GetDescription( nickname ) );
  773. itemsToDisplay.push_back( item );
  774. }
  775. }
  776. for( const wxString& nickname : nicknames )
  777. {
  778. if( !alg::contains( project.m_PinnedFootprintLibs, nickname )
  779. && !alg::contains( cfg->m_Session.pinned_fp_libs, nickname ) )
  780. {
  781. wxArrayString item;
  782. item.Add( nickname );
  783. item.Add( tbl->GetDescription( nickname ) );
  784. itemsToDisplay.push_back( item );
  785. }
  786. }
  787. initDialog( headers, itemsToDisplay, aLibraryPreselect );
  788. SetListLabel( _( "Save in library:" ) );
  789. SetOKLabel( _( "Save" ) );
  790. wxBoxSizer* bNameSizer = new wxBoxSizer( wxHORIZONTAL );
  791. wxStaticText* label = new wxStaticText( this, wxID_ANY, _( "Name:" ) );
  792. bNameSizer->Add( label, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
  793. m_fpNameCtrl = new wxTextCtrl( this, wxID_ANY, aFootprintName );
  794. bNameSizer->Add( m_fpNameCtrl, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
  795. wxTextValidator nameValidator( wxFILTER_EXCLUDE_CHAR_LIST );
  796. nameValidator.SetCharExcludes( FOOTPRINT::StringLibNameInvalidChars( false ) );
  797. m_fpNameCtrl->SetValidator( nameValidator );
  798. wxButton* newLibraryButton = new wxButton( this, ID_MAKE_NEW_LIBRARY, _( "New Library..." ) );
  799. m_ButtonsSizer->Prepend( 80, 20 );
  800. m_ButtonsSizer->Prepend( newLibraryButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 10 );
  801. GetSizer()->Prepend( bNameSizer, 0, wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5 );
  802. Bind( wxEVT_BUTTON,
  803. [this]( wxCommandEvent& )
  804. {
  805. EndModal( ID_MAKE_NEW_LIBRARY );
  806. }, ID_MAKE_NEW_LIBRARY );
  807. // Move nameTextCtrl to the head of the tab-order
  808. if( GetChildren().DeleteObject( m_fpNameCtrl ) )
  809. GetChildren().Insert( m_fpNameCtrl );
  810. SetInitialFocus( m_fpNameCtrl );
  811. SetupStandardButtons();
  812. Layout();
  813. GetSizer()->Fit( this );
  814. Centre();
  815. }
  816. wxString GetFPName()
  817. {
  818. wxString footprintName = m_fpNameCtrl->GetValue();
  819. footprintName.Trim( true );
  820. footprintName.Trim( false );
  821. return footprintName;
  822. }
  823. protected:
  824. bool TransferDataFromWindow() override
  825. {
  826. return m_validator( GetTextSelection(), GetFPName() );
  827. }
  828. private:
  829. wxTextCtrl* m_fpNameCtrl;
  830. std::function<bool( wxString libName, wxString fpName )> m_validator;
  831. };
  832. bool FOOTPRINT_EDIT_FRAME::SaveFootprintAs( FOOTPRINT* aFootprint )
  833. {
  834. if( aFootprint == nullptr )
  835. return false;
  836. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &Prj() );
  837. SetMsgPanel( aFootprint );
  838. wxString libraryName = aFootprint->GetFPID().GetLibNickname();
  839. wxString footprintName = aFootprint->GetFPID().GetLibItemName();
  840. bool updateValue = aFootprint->GetValue() == footprintName;
  841. bool done = false;
  842. bool footprintExists = false;
  843. while( !done )
  844. {
  845. SAVE_AS_DIALOG dlg( this, footprintName, libraryName,
  846. [&]( const wxString& newLib, const wxString& newName )
  847. {
  848. if( newLib.IsEmpty() )
  849. {
  850. wxMessageBox( _( "A library must be specified." ) );
  851. return false;
  852. }
  853. if( newName.IsEmpty() )
  854. {
  855. wxMessageBox( _( "Footprint must have a name." ) );
  856. return false;
  857. }
  858. // Legacy libraries are readable, but modifying legacy format is not allowed
  859. // So prompt the user if he try to add/replace a footprint in a legacy lib
  860. const FP_LIB_TABLE_ROW* row = PROJECT_PCB::PcbFootprintLibs( &Prj() )->FindRow( newLib );
  861. wxString libPath = row->GetFullURI();
  862. PCB_IO_MGR::PCB_FILE_T piType = PCB_IO_MGR::GuessPluginTypeFromLibPath( libPath );
  863. if( piType == PCB_IO_MGR::LEGACY )
  864. {
  865. DisplayInfoMessage( this, INFO_LEGACY_LIB_WARN_EDIT );
  866. return false;
  867. }
  868. footprintExists = tbl->FootprintExists( newLib, newName );
  869. if( footprintExists )
  870. {
  871. wxString msg = wxString::Format( _( "Footprint %s already exists in %s." ),
  872. newName,
  873. newLib );
  874. KIDIALOG errorDlg( this, msg, _( "Confirmation" ),
  875. wxOK | wxCANCEL | wxICON_WARNING );
  876. errorDlg.SetOKLabel( _( "Overwrite" ) );
  877. return errorDlg.ShowModal() == wxID_OK;
  878. }
  879. return true;
  880. } );
  881. int ret = dlg.ShowModal();
  882. if( ret == wxID_CANCEL )
  883. {
  884. return false;
  885. }
  886. else if( ret == wxID_OK )
  887. {
  888. footprintName = dlg.GetFPName();
  889. libraryName = dlg.GetTextSelection();
  890. done = true;
  891. }
  892. else if( ret == ID_MAKE_NEW_LIBRARY )
  893. {
  894. wxFileName newLibrary( CreateNewLibrary() );
  895. libraryName = newLibrary.GetName();
  896. }
  897. }
  898. aFootprint->SetFPID( LIB_ID( libraryName, footprintName ) );
  899. if( updateValue )
  900. aFootprint->SetValue( footprintName );
  901. if( !SaveFootprintInLibrary( aFootprint, libraryName ) )
  902. return false;
  903. // Once saved-as a board footprint is no longer a board footprint
  904. aFootprint->SetLink( niluuid );
  905. wxString fmt = footprintExists ? _( "Footprint '%s' replaced in '%s'" )
  906. : _( "Footprint '%s' added to '%s'" );
  907. wxString msg = wxString::Format( fmt, footprintName.GetData(), libraryName.GetData() );
  908. SetStatusText( msg );
  909. UpdateTitle();
  910. ReCreateHToolbar();
  911. return true;
  912. }
  913. bool FOOTPRINT_EDIT_FRAME::RevertFootprint()
  914. {
  915. if( GetScreen()->IsContentModified() && m_originalFootprintCopy )
  916. {
  917. wxString msg = wxString::Format( _( "Revert '%s' to last version saved?" ),
  918. GetLoadedFPID().GetLibItemName().wx_str() );
  919. if( ConfirmRevertDialog( this, msg ) )
  920. {
  921. Clear_Pcb( false );
  922. AddFootprintToBoard( static_cast<FOOTPRINT*>( m_originalFootprintCopy->Clone() ) );
  923. Zoom_Automatique( false );
  924. Update3DView( true, true );
  925. ClearUndoRedoList();
  926. GetScreen()->SetContentModified( false );
  927. UpdateView();
  928. GetCanvas()->Refresh();
  929. return true;
  930. }
  931. }
  932. return false;
  933. }
  934. class NEW_FP_DIALOG : public WX_TEXT_ENTRY_DIALOG
  935. {
  936. public:
  937. NEW_FP_DIALOG( PCB_BASE_FRAME* aParent, const wxString& aName, int aFootprintType,
  938. std::function<bool( wxString newName )> aValidator ) :
  939. WX_TEXT_ENTRY_DIALOG( aParent, _( "Enter footprint name:" ), _( "New Footprint" ),
  940. aName, _( "Footprint type:" ),
  941. { _( "Through hole" ), _( "SMD" ), _( "Other" ) },
  942. aFootprintType ),
  943. m_validator( std::move( aValidator ) )
  944. { }
  945. wxString GetFPName()
  946. {
  947. wxString name = m_textCtrl->GetValue();
  948. name.Trim( true ).Trim( false );
  949. return name;
  950. }
  951. protected:
  952. bool TransferDataFromWindow() override
  953. {
  954. return m_validator( GetFPName() );
  955. }
  956. private:
  957. std::function<bool( wxString newName )> m_validator;
  958. };
  959. FOOTPRINT* PCB_BASE_FRAME::CreateNewFootprint( const wxString& aFootprintName,
  960. const wxString& aLibName, bool aQuiet )
  961. {
  962. FP_LIB_TABLE* tbl = PROJECT_PCB::PcbFootprintLibs( &Prj() );
  963. wxString footprintName = aFootprintName;
  964. wxString msg;
  965. // Static to store user preference for a session
  966. static int footprintType = 1;
  967. int footprintTranslated = FP_SMD;
  968. // Ask for the new footprint name
  969. if( footprintName.IsEmpty() && !aQuiet )
  970. {
  971. NEW_FP_DIALOG dlg( this, footprintName, footprintType,
  972. [&]( wxString newName )
  973. {
  974. if( newName.IsEmpty() )
  975. {
  976. wxMessageBox( _( "Footprint must have a name." ) );
  977. return false;
  978. }
  979. if( !aLibName.IsEmpty() && tbl->FootprintExists( aLibName, newName ) )
  980. {
  981. msg = wxString::Format( _( "Footprint '%s' already exists in library '%s'." ),
  982. newName, aLibName );
  983. KIDIALOG errorDlg( this, msg, _( "Confirmation" ),
  984. wxOK | wxCANCEL | wxICON_WARNING );
  985. errorDlg.SetOKLabel( _( "Overwrite" ) );
  986. return errorDlg.ShowModal() == wxID_OK;
  987. }
  988. return true;
  989. } );
  990. dlg.SetTextValidator( FOOTPRINT_NAME_VALIDATOR( &footprintName ) );
  991. if( dlg.ShowModal() != wxID_OK )
  992. return nullptr; //Aborted by user
  993. footprintName = dlg.GetFPName();
  994. footprintType = dlg.GetChoice();
  995. switch( footprintType )
  996. {
  997. case 0: footprintTranslated = FP_THROUGH_HOLE; break;
  998. case 1: footprintTranslated = FP_SMD; break;
  999. default: footprintTranslated = 0; break;
  1000. }
  1001. }
  1002. // Creates the new footprint and add it to the head of the linked list of footprints
  1003. FOOTPRINT* footprint = new FOOTPRINT( GetBoard() );
  1004. // Update its name in lib
  1005. footprint->SetFPID( LIB_ID( wxEmptyString, footprintName ) );
  1006. footprint->SetAttributes( footprintTranslated );
  1007. PCB_LAYER_ID txt_layer;
  1008. VECTOR2I default_pos;
  1009. BOARD_DESIGN_SETTINGS& settings = GetDesignSettings();
  1010. footprint->Reference().SetText( settings.m_DefaultFPTextItems[0].m_Text );
  1011. footprint->Reference().SetVisible( settings.m_DefaultFPTextItems[0].m_Visible );
  1012. txt_layer = (PCB_LAYER_ID) settings.m_DefaultFPTextItems[0].m_Layer;
  1013. footprint->Reference().SetLayer( txt_layer );
  1014. default_pos.y -= settings.GetTextSize( txt_layer ).y / 2;
  1015. footprint->Reference().SetPosition( default_pos );
  1016. default_pos.y += settings.GetTextSize( txt_layer ).y;
  1017. footprint->Value().SetText( settings.m_DefaultFPTextItems[1].m_Text );
  1018. footprint->Value().SetVisible( settings.m_DefaultFPTextItems[1].m_Visible );
  1019. txt_layer = (PCB_LAYER_ID) settings.m_DefaultFPTextItems[1].m_Layer;
  1020. footprint->Value().SetLayer( txt_layer );
  1021. default_pos.y += settings.GetTextSize( txt_layer ).y / 2;
  1022. footprint->Value().SetPosition( default_pos );
  1023. default_pos.y += settings.GetTextSize( txt_layer ).y;
  1024. for( size_t i = 2; i < settings.m_DefaultFPTextItems.size(); ++i )
  1025. {
  1026. PCB_TEXT* textItem = new PCB_TEXT( footprint );
  1027. textItem->SetText( settings.m_DefaultFPTextItems[i].m_Text );
  1028. textItem->SetVisible( settings.m_DefaultFPTextItems[i].m_Visible );
  1029. txt_layer = (PCB_LAYER_ID) settings.m_DefaultFPTextItems[i].m_Layer;
  1030. textItem->SetLayer( txt_layer );
  1031. default_pos.y += settings.GetTextSize( txt_layer ).y / 2;
  1032. textItem->SetPosition( default_pos );
  1033. default_pos.y += settings.GetTextSize( txt_layer ).y;
  1034. footprint->GraphicalItems().push_back( textItem );
  1035. }
  1036. if( footprint->GetReference().IsEmpty() )
  1037. footprint->SetReference( footprintName );
  1038. if( footprint->GetValue().IsEmpty() )
  1039. footprint->SetValue( footprintName );
  1040. footprint->RunOnDescendants(
  1041. [&]( BOARD_ITEM* aChild )
  1042. {
  1043. if( aChild->Type() == PCB_FIELD_T || aChild->Type() == PCB_TEXT_T )
  1044. {
  1045. PCB_TEXT* textItem = static_cast<PCB_TEXT*>( aChild );
  1046. PCB_LAYER_ID layer = textItem->GetLayer();
  1047. textItem->SetTextThickness( settings.GetTextThickness( layer ) );
  1048. textItem->SetTextSize( settings.GetTextSize( layer ) );
  1049. textItem->SetItalic( settings.GetTextItalic( layer ) );
  1050. textItem->SetKeepUpright( settings.GetTextUpright( layer ) );
  1051. }
  1052. } );
  1053. SetMsgPanel( footprint );
  1054. return footprint;
  1055. }
  1056. wxString PCB_BASE_FRAME::SelectLibrary( const wxString& aNicknameExisting )
  1057. {
  1058. wxArrayString headers;
  1059. headers.Add( _( "Nickname" ) );
  1060. headers.Add( _( "Description" ) );
  1061. COMMON_SETTINGS* cfg = Pgm().GetCommonSettings();
  1062. PROJECT_FILE& project = Kiway().Prj().GetProjectFile();
  1063. FP_LIB_TABLE* fptbl = PROJECT_PCB::PcbFootprintLibs( &Prj() );
  1064. std::vector< wxArrayString > itemsToDisplay;
  1065. std::vector< wxString > nicknames = fptbl->GetLogicalLibs();
  1066. for( const wxString& nickname : nicknames )
  1067. {
  1068. if( alg::contains( project.m_PinnedFootprintLibs, nickname )
  1069. || alg::contains( cfg->m_Session.pinned_fp_libs, nickname ) )
  1070. {
  1071. wxArrayString item;
  1072. item.Add( LIB_TREE_MODEL_ADAPTER::GetPinningSymbol() + nickname );
  1073. item.Add( fptbl->GetDescription( nickname ) );
  1074. itemsToDisplay.push_back( item );
  1075. }
  1076. }
  1077. for( const wxString& nickname : nicknames )
  1078. {
  1079. if( !alg::contains( project.m_PinnedFootprintLibs, nickname )
  1080. && !alg::contains( cfg->m_Session.pinned_fp_libs, nickname ) )
  1081. {
  1082. wxArrayString item;
  1083. item.Add( nickname );
  1084. item.Add( fptbl->GetDescription( nickname ) );
  1085. itemsToDisplay.push_back( item );
  1086. }
  1087. }
  1088. EDA_LIST_DIALOG dlg( this, _( "Select Library" ), headers, itemsToDisplay, aNicknameExisting,
  1089. false );
  1090. if( dlg.ShowModal() != wxID_OK )
  1091. return wxEmptyString;
  1092. return dlg.GetTextSelection();
  1093. }