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.

1131 lines
37 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
5 years ago
5 years ago
5 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  5. * Copyright (C) 2013-2021 CERN
  6. * Copyright (C) 2012-2021 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. /* TODO:
  26. *) After any change to uri, reparse the environment variables.
  27. */
  28. #include <set>
  29. #include <wx/dir.h>
  30. #include <wx/regex.h>
  31. #include <wx/grid.h>
  32. #include <wx/dirdlg.h>
  33. #include <wx/filedlg.h>
  34. #include <project.h>
  35. #include <3d_viewer/eda_3d_viewer_frame.h> // for KICAD6_3DMODEL_DIR
  36. #include <panel_fp_lib_table.h>
  37. #include <lib_id.h>
  38. #include <fp_lib_table.h>
  39. #include <lib_table_lexer.h>
  40. #include <invoke_pcb_dialog.h>
  41. #include <bitmaps.h>
  42. #include <grid_tricks.h>
  43. #include <widgets/wx_grid.h>
  44. #include <confirm.h>
  45. #include <lib_table_grid.h>
  46. #include <wildcards_and_files_ext.h>
  47. #include <pgm_base.h>
  48. #include <pcb_edit_frame.h>
  49. #include <env_paths.h>
  50. #include <dialogs/dialog_edit_library_tables.h>
  51. #include <footprint_viewer_frame.h>
  52. #include <footprint_edit_frame.h>
  53. #include <kiway.h>
  54. #include <widgets/grid_readonly_text_helpers.h>
  55. #include <widgets/grid_text_button_helpers.h>
  56. #include <pcbnew_id.h> // For ID_PCBNEW_END_LIST
  57. #include <settings/settings_manager.h>
  58. #include <paths.h>
  59. #include <macros.h>
  60. // clang-format off
  61. /**
  62. * Container that describes file type info for the add a library options
  63. */
  64. struct SUPPORTED_FILE_TYPE
  65. {
  66. wxString m_Description; ///< Description shown in the file picker dialog
  67. wxString m_FileFilter; ///< Filter used for file pickers if m_IsFile is true
  68. wxString m_FolderSearchExtension; ///< In case of folders it stands for extensions of files stored inside
  69. bool m_IsFile; ///< Whether the library is a folder or a file
  70. IO_MGR::PCB_FILE_T m_Plugin;
  71. };
  72. /**
  73. * Event IDs for the menu items in the split button menu for add a library
  74. */
  75. enum {
  76. ID_PANEL_FPLIB_ADD_KICADMOD = ID_PCBNEW_END_LIST,
  77. ID_PANEL_FPLIB_ADD_EAGLE6,
  78. ID_PANEL_FPLIB_ADD_KICADLEGACY,
  79. ID_PANEL_FPLIB_ADD_GEDA,
  80. };
  81. /**
  82. * Map with event id as the key to supported file types that will be listed for the add a
  83. * library option.
  84. *
  85. */
  86. static const std::map<int, SUPPORTED_FILE_TYPE>& fileTypes()
  87. {
  88. /*
  89. * TODO(C++20): Clean this up
  90. * This is wrapped inside a function to prevent a static initialization order fiasco
  91. * with the file extension variables. Once C++20 is allowed in KiCad code, those file
  92. * extensions can be made constexpr and this can be removed from a function call and
  93. * placed in the file normally.
  94. */
  95. static const std::map<int, SUPPORTED_FILE_TYPE> fileTypes =
  96. {
  97. { ID_PANEL_FPLIB_ADD_KICADMOD,
  98. {
  99. "KiCad (folder with .kicad_mod files)", "", KiCadFootprintFileExtension,
  100. false, IO_MGR::KICAD_SEXP
  101. }
  102. },
  103. { ID_PANEL_FPLIB_ADD_EAGLE6,
  104. {
  105. "Eagle 6.x (*.lbr)", EagleFootprintLibPathWildcard(), "", true, IO_MGR::EAGLE
  106. }
  107. },
  108. { ID_PANEL_FPLIB_ADD_KICADLEGACY,
  109. {
  110. "KiCad legacy (*.mod)", LegacyFootprintLibPathWildcard(), "", true, IO_MGR::LEGACY
  111. }
  112. },
  113. { ID_PANEL_FPLIB_ADD_GEDA,
  114. {
  115. "Geda (folder with *.fp files)", "", GedaPcbFootprintLibFileExtension, false,
  116. IO_MGR::GEDA_PCB
  117. }
  118. },
  119. };
  120. return fileTypes;
  121. }
  122. // clang-format on
  123. /**
  124. * Traverser implementation that looks to find any and all "folder" libraries by looking for files
  125. * with a specific extension inside folders
  126. */
  127. class LIBRARY_TRAVERSER : public wxDirTraverser
  128. {
  129. public:
  130. LIBRARY_TRAVERSER( wxString aSearchExtension, wxString aInitialDir )
  131. : m_searchExtension( aSearchExtension ),
  132. m_currentDir( aInitialDir )
  133. {
  134. }
  135. virtual wxDirTraverseResult OnFile( const wxString& aFileName ) override
  136. {
  137. wxFileName file( aFileName );
  138. if( m_searchExtension.IsSameAs( file.GetExt(), false ) )
  139. m_foundDirs.insert( { m_currentDir, 1 } );
  140. return wxDIR_CONTINUE;
  141. }
  142. virtual wxDirTraverseResult OnOpenError( const wxString& aOpenErrorName ) override
  143. {
  144. m_failedDirs.insert( { aOpenErrorName, 1 } );
  145. return wxDIR_IGNORE;
  146. }
  147. bool HasDirectoryOpenFailures()
  148. {
  149. return m_failedDirs.size() > 0;
  150. }
  151. virtual wxDirTraverseResult OnDir( const wxString& aDirName ) override
  152. {
  153. m_currentDir = aDirName;
  154. return wxDIR_CONTINUE;
  155. }
  156. void GetPaths( wxArrayString& aPathArray )
  157. {
  158. for( std::pair<const wxString, int>& foundDirsPair : m_foundDirs )
  159. aPathArray.Add( foundDirsPair.first );
  160. }
  161. void GetFailedPaths( wxArrayString& aPathArray )
  162. {
  163. for( std::pair<const wxString, int>& failedDirsPair : m_failedDirs )
  164. aPathArray.Add( failedDirsPair.first );
  165. }
  166. private:
  167. wxString m_searchExtension;
  168. wxString m_currentDir;
  169. std::unordered_map<wxString, int> m_foundDirs;
  170. std::unordered_map<wxString, int> m_failedDirs;
  171. };
  172. /**
  173. * This class builds a wxGridTableBase by wrapping an #FP_LIB_TABLE object.
  174. */
  175. class FP_LIB_TABLE_GRID : public LIB_TABLE_GRID, public FP_LIB_TABLE
  176. {
  177. friend class PANEL_FP_LIB_TABLE;
  178. friend class FP_GRID_TRICKS;
  179. protected:
  180. LIB_TABLE_ROW* at( size_t aIndex ) override { return &rows.at( aIndex ); }
  181. size_t size() const override { return rows.size(); }
  182. LIB_TABLE_ROW* makeNewRow() override
  183. {
  184. return dynamic_cast< LIB_TABLE_ROW* >( new FP_LIB_TABLE_ROW );
  185. }
  186. LIB_TABLE_ROWS_ITER begin() override { return rows.begin(); }
  187. LIB_TABLE_ROWS_ITER insert( LIB_TABLE_ROWS_ITER aIterator, LIB_TABLE_ROW* aRow ) override
  188. {
  189. return rows.insert( aIterator, aRow );
  190. }
  191. void push_back( LIB_TABLE_ROW* aRow ) override { rows.push_back( aRow ); }
  192. LIB_TABLE_ROWS_ITER erase( LIB_TABLE_ROWS_ITER aFirst, LIB_TABLE_ROWS_ITER aLast ) override
  193. {
  194. return rows.erase( aFirst, aLast );
  195. }
  196. public:
  197. FP_LIB_TABLE_GRID( const FP_LIB_TABLE& aTableToEdit )
  198. {
  199. rows = aTableToEdit.rows;
  200. }
  201. };
  202. #define MYID_OPTIONS_EDITOR 15151
  203. class FP_GRID_TRICKS : public GRID_TRICKS
  204. {
  205. public:
  206. FP_GRID_TRICKS( DIALOG_EDIT_LIBRARY_TABLES* aParent, WX_GRID* aGrid ) :
  207. GRID_TRICKS( aGrid ),
  208. m_dialog( aParent )
  209. { }
  210. protected:
  211. DIALOG_EDIT_LIBRARY_TABLES* m_dialog;
  212. void optionsEditor( int aRow )
  213. {
  214. FP_LIB_TABLE_GRID* tbl = (FP_LIB_TABLE_GRID*) m_grid->GetTable();
  215. if( tbl->GetNumberRows() > aRow )
  216. {
  217. LIB_TABLE_ROW* row = tbl->at( (size_t) aRow );
  218. const wxString& options = row->GetOptions();
  219. wxString result = options;
  220. InvokePluginOptionsEditor( m_dialog, row->GetNickName(), row->GetType(), options,
  221. &result );
  222. if( options != result )
  223. {
  224. row->SetOptions( result );
  225. m_grid->Refresh();
  226. }
  227. }
  228. }
  229. bool handleDoubleClick( wxGridEvent& aEvent ) override
  230. {
  231. if( aEvent.GetCol() == COL_OPTIONS )
  232. {
  233. optionsEditor( aEvent.GetRow() );
  234. return true;
  235. }
  236. return false;
  237. }
  238. void showPopupMenu( wxMenu& menu ) override
  239. {
  240. if( m_grid->GetGridCursorCol() == COL_OPTIONS )
  241. {
  242. menu.Append( MYID_OPTIONS_EDITOR, _( "Options Editor..." ), _( "Edit options" ) );
  243. menu.AppendSeparator();
  244. }
  245. GRID_TRICKS::showPopupMenu( menu );
  246. }
  247. void doPopupSelection( wxCommandEvent& event ) override
  248. {
  249. if( event.GetId() == MYID_OPTIONS_EDITOR )
  250. optionsEditor( m_grid->GetGridCursorRow() );
  251. else
  252. GRID_TRICKS::doPopupSelection( event );
  253. }
  254. /// handle specialized clipboard text, with leading "(fp_lib_table", OR
  255. /// spreadsheet formatted text.
  256. void paste_text( const wxString& cb_text ) override
  257. {
  258. FP_LIB_TABLE_GRID* tbl = (FP_LIB_TABLE_GRID*) m_grid->GetTable();
  259. size_t ndx = cb_text.find( "(fp_lib_table" );
  260. if( ndx != std::string::npos )
  261. {
  262. // paste the FP_LIB_TABLE_ROWs of s-expression (fp_lib_table), starting
  263. // at column 0 regardless of current cursor column.
  264. STRING_LINE_READER slr( TO_UTF8( cb_text ), "Clipboard" );
  265. LIB_TABLE_LEXER lexer( &slr );
  266. FP_LIB_TABLE tmp_tbl;
  267. bool parsed = true;
  268. try
  269. {
  270. tmp_tbl.Parse( &lexer );
  271. }
  272. catch( PARSE_ERROR& pe )
  273. {
  274. DisplayError( m_dialog, pe.What() );
  275. parsed = false;
  276. }
  277. if( parsed )
  278. {
  279. // make sure the table is big enough...
  280. if( tmp_tbl.GetCount() > (unsigned) tbl->GetNumberRows() )
  281. tbl->AppendRows( tmp_tbl.GetCount() - tbl->GetNumberRows() );
  282. for( unsigned i = 0; i < tmp_tbl.GetCount(); ++i )
  283. tbl->rows.replace( i, tmp_tbl.At( i ).clone() );
  284. }
  285. m_grid->AutoSizeColumns( false );
  286. }
  287. else
  288. {
  289. // paste spreadsheet formatted text.
  290. GRID_TRICKS::paste_text( cb_text );
  291. m_grid->AutoSizeColumns( false );
  292. }
  293. }
  294. };
  295. PANEL_FP_LIB_TABLE::PANEL_FP_LIB_TABLE( DIALOG_EDIT_LIBRARY_TABLES* aParent,
  296. FP_LIB_TABLE* aGlobal, const wxString& aGlobalTblPath,
  297. FP_LIB_TABLE* aProject, const wxString& aProjectTblPath,
  298. const wxString& aProjectBasePath ) :
  299. PANEL_FP_LIB_TABLE_BASE( aParent ),
  300. m_global( aGlobal ),
  301. m_project( aProject ),
  302. m_projectBasePath( aProjectBasePath ),
  303. m_parent( aParent )
  304. {
  305. m_global_grid->SetTable( new FP_LIB_TABLE_GRID( *aGlobal ), true );
  306. // add Cut, Copy, and Paste to wxGrids
  307. m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
  308. wxArrayString choices;
  309. choices.Add( IO_MGR::ShowType( IO_MGR::KICAD_SEXP ) );
  310. choices.Add( IO_MGR::ShowType( IO_MGR::LEGACY ) );
  311. choices.Add( IO_MGR::ShowType( IO_MGR::EAGLE ) );
  312. choices.Add( IO_MGR::ShowType( IO_MGR::GEDA_PCB ) );
  313. /* PCAD_PLUGIN does not support Footprint*() functions
  314. choices.Add( IO_MGR::ShowType( IO_MGR::PCAD ) );
  315. */
  316. PCBNEW_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<PCBNEW_SETTINGS>();
  317. if( cfg->m_lastFootprintLibDir.IsEmpty() )
  318. cfg->m_lastFootprintLibDir = PATHS::GetDefaultUserFootprintsPath();
  319. m_lastProjectLibDir = m_projectBasePath;
  320. auto setupGrid =
  321. [&]( WX_GRID* aGrid )
  322. {
  323. // Give a bit more room for wxChoice editors
  324. aGrid->SetDefaultRowSize( aGrid->GetDefaultRowSize() + 4 );
  325. // add Cut, Copy, and Paste to wxGrids
  326. aGrid->PushEventHandler( new FP_GRID_TRICKS( m_parent, aGrid ) );
  327. aGrid->SetSelectionMode( wxGrid::wxGridSelectRows );
  328. aGrid->AutoSizeColumns( false );
  329. wxGridCellAttr* attr;
  330. attr = new wxGridCellAttr;
  331. attr->SetEditor( new GRID_CELL_PATH_EDITOR( m_parent, aGrid,
  332. &cfg->m_lastFootprintLibDir,
  333. wxEmptyString, true,
  334. m_projectBasePath ) );
  335. aGrid->SetColAttr( COL_URI, attr );
  336. attr = new wxGridCellAttr;
  337. attr->SetEditor( new wxGridCellChoiceEditor( choices ) );
  338. aGrid->SetColAttr( COL_TYPE, attr );
  339. attr = new wxGridCellAttr;
  340. attr->SetRenderer( new wxGridCellBoolRenderer() );
  341. attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
  342. aGrid->SetColAttr( COL_ENABLED, attr );
  343. // all but COL_OPTIONS, which is edited with Option Editor anyways.
  344. aGrid->AutoSizeColumn( COL_NICKNAME, false );
  345. aGrid->AutoSizeColumn( COL_TYPE, false );
  346. aGrid->AutoSizeColumn( COL_URI, false );
  347. aGrid->AutoSizeColumn( COL_DESCR, false );
  348. // would set this to width of title, if it was easily known.
  349. aGrid->SetColSize( COL_OPTIONS, 80 );
  350. // Gives a selection to each grid, mainly for delete button. wxGrid's wake up with
  351. // a currentCell which is sometimes not highlighted.
  352. if( aGrid->GetNumberRows() > 0 )
  353. aGrid->SelectRow( 0 );
  354. };
  355. setupGrid( m_global_grid );
  356. populateEnvironReadOnlyTable();
  357. if( aProject )
  358. {
  359. m_project_grid->SetTable( new FP_LIB_TABLE_GRID( *aProject ), true );
  360. setupGrid( m_project_grid );
  361. }
  362. else
  363. {
  364. m_pageNdx = 0;
  365. m_notebook->DeletePage( 1 );
  366. m_project_grid = nullptr;
  367. }
  368. m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
  369. m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
  370. // select the last selected page
  371. m_notebook->SetSelection( m_pageNdx );
  372. m_cur_grid = ( m_pageNdx == 0 ) ? m_global_grid : m_project_grid;
  373. // for ALT+A handling, we want the initial focus to be on the first selected grid.
  374. m_parent->SetInitialFocus( m_cur_grid );
  375. // Configure button logos
  376. m_append_button->SetBitmap( KiBitmap( BITMAPS::small_plus ) );
  377. m_delete_button->SetBitmap( KiBitmap( BITMAPS::small_trash ) );
  378. m_move_up_button->SetBitmap( KiBitmap( BITMAPS::small_up ) );
  379. m_move_down_button->SetBitmap( KiBitmap( BITMAPS::small_down ) );
  380. m_browseButton->SetBitmap( KiBitmap( BITMAPS::small_folder ) );
  381. // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
  382. // manually (for instance m_append_button)
  383. Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
  384. // their bitmaps
  385. wxSize buttonSize = m_append_button->GetSize();
  386. m_browseButton->SetWidthPadding( 4 );
  387. m_browseButton->SetMinSize( buttonSize );
  388. // Populate the browse library options
  389. wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
  390. for( const std::pair<const int, SUPPORTED_FILE_TYPE>& fileType : fileTypes() )
  391. {
  392. browseMenu->Append( fileType.first, fileType.second.m_Description );
  393. browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_FP_LIB_TABLE::browseLibrariesHandler,
  394. this, fileType.first );
  395. }
  396. Layout();
  397. // Hack to make buttons lay out correctly the first time on Mac
  398. wxSize hackSize = m_buttonsPanel->GetSize();
  399. m_buttonsPanel->SetSize( wxSize( hackSize.x - 5, hackSize.y ) );
  400. Layout();
  401. // This is the button only press for the browse button instead of the menu
  402. m_browseButton->Bind( wxEVT_BUTTON, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this );
  403. }
  404. PANEL_FP_LIB_TABLE::~PANEL_FP_LIB_TABLE()
  405. {
  406. // When the dialog is closed it will hide the current notebook page first, which will
  407. // in turn select the other one. We then end up saving its index as the "current page".
  408. // So flip them back again:
  409. m_pageNdx = m_pageNdx == 1 ? 0 : 1;
  410. // Delete the GRID_TRICKS.
  411. // Any additional event handlers should be popped before the window is deleted.
  412. m_global_grid->PopEventHandler( true );
  413. if( m_project_grid )
  414. m_project_grid->PopEventHandler( true );
  415. m_path_subs_grid->PopEventHandler( true );
  416. }
  417. bool PANEL_FP_LIB_TABLE::verifyTables()
  418. {
  419. wxString msg;
  420. for( FP_LIB_TABLE_GRID* model : { global_model(), project_model() } )
  421. {
  422. if( !model )
  423. continue;
  424. for( int r = 0; r < model->GetNumberRows(); )
  425. {
  426. wxString nick = model->GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
  427. wxString uri = model->GetValue( r, COL_URI ).Trim( false ).Trim();
  428. unsigned illegalCh = 0;
  429. if( !nick || !uri )
  430. {
  431. if( !nick && !uri )
  432. msg = _( "A library table row nickname and path cells are empty." );
  433. else if( !nick )
  434. msg = _( "A library table row nickname cell is empty." );
  435. else
  436. msg = _( "A library table row path cell is empty." );
  437. wxMessageDialog badCellDlg( this, msg, _( "Invalid Row Definition" ),
  438. wxYES_NO | wxCENTER | wxICON_QUESTION | wxYES_DEFAULT );
  439. badCellDlg.SetExtendedMessage( _( "Empty cells will result in all rows that are "
  440. "invalid to be removed from the table." ) );
  441. badCellDlg.SetYesNoLabels( wxMessageDialog::ButtonLabel( "Remove Invalid Cells" ),
  442. wxMessageDialog::ButtonLabel( "Cancel Table Update" ) );
  443. if( badCellDlg.ShowModal() == wxID_NO )
  444. return false;
  445. // Delete the "empty" row, where empty means missing nick or uri.
  446. // This also updates the UI which could be slow, but there should only be a few
  447. // rows to delete, unless the user fell asleep on the Add Row
  448. // button.
  449. model->DeleteRows( r, 1 );
  450. }
  451. else if( ( illegalCh = LIB_ID::FindIllegalLibraryNameChar( nick ) ) )
  452. {
  453. msg = wxString::Format( _( "Illegal character '%c' in nickname '%s'." ),
  454. illegalCh,
  455. nick );
  456. // show the tabbed panel holding the grid we have flunked:
  457. if( model != cur_model() )
  458. m_notebook->SetSelection( model == global_model() ? 0 : 1 );
  459. m_cur_grid->MakeCellVisible( r, 0 );
  460. m_cur_grid->SetGridCursor( r, 1 );
  461. wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
  462. errdlg.ShowModal();
  463. return false;
  464. }
  465. else
  466. {
  467. // set the trimmed values back into the table so they get saved to disk.
  468. model->SetValue( r, COL_NICKNAME, nick );
  469. model->SetValue( r, COL_URI, uri );
  470. ++r; // this row was OK.
  471. }
  472. }
  473. }
  474. // check for duplicate nickNames, separately in each table.
  475. for( FP_LIB_TABLE_GRID* model : { global_model(), project_model() } )
  476. {
  477. if( !model )
  478. continue;
  479. for( int r1 = 0; r1 < model->GetNumberRows() - 1; ++r1 )
  480. {
  481. wxString nick1 = model->GetValue( r1, COL_NICKNAME );
  482. for( int r2 = r1 + 1; r2 < model->GetNumberRows(); ++r2 )
  483. {
  484. wxString nick2 = model->GetValue( r2, COL_NICKNAME );
  485. if( nick1 == nick2 )
  486. {
  487. msg = wxString::Format( _( "Multiple libraries cannot share the same "
  488. "nickname ('%s')." ),
  489. nick1 );
  490. // show the tabbed panel holding the grid we have flunked:
  491. if( model != cur_model() )
  492. m_notebook->SetSelection( model == global_model() ? 0 : 1 );
  493. // go to the lower of the two rows, it is technically the duplicate:
  494. m_cur_grid->MakeCellVisible( r2, 0 );
  495. m_cur_grid->SetGridCursor( r2, 1 );
  496. wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
  497. errdlg.ShowModal();
  498. return false;
  499. }
  500. }
  501. }
  502. }
  503. return true;
  504. }
  505. void PANEL_FP_LIB_TABLE::OnUpdateUI( wxUpdateUIEvent& event )
  506. {
  507. m_pageNdx = (unsigned) std::max( 0, m_notebook->GetSelection() );
  508. m_cur_grid = m_pageNdx == 0 ? m_global_grid : m_project_grid;
  509. }
  510. void PANEL_FP_LIB_TABLE::appendRowHandler( wxCommandEvent& event )
  511. {
  512. if( !m_cur_grid->CommitPendingChanges() )
  513. return;
  514. if( m_cur_grid->AppendRows( 1 ) )
  515. {
  516. int last_row = m_cur_grid->GetNumberRows() - 1;
  517. // wx documentation is wrong, SetGridCursor does not make visible.
  518. m_cur_grid->MakeCellVisible( last_row, 0 );
  519. m_cur_grid->SetGridCursor( last_row, 1 );
  520. m_cur_grid->EnableCellEditControl( true );
  521. m_cur_grid->ShowCellEditControl();
  522. }
  523. }
  524. void PANEL_FP_LIB_TABLE::deleteRowHandler( wxCommandEvent& event )
  525. {
  526. if( !m_cur_grid->CommitPendingChanges() )
  527. return;
  528. int curRow = m_cur_grid->GetGridCursorRow();
  529. int curCol = m_cur_grid->GetGridCursorCol();
  530. // In a wxGrid, collect rows that have a selected cell, or are selected
  531. // It is not so easy: it depends on the way the selection was made.
  532. // Here, we collect rows selected by clicking on a row label, and rows that contain any
  533. // previously-selected cells.
  534. // If no candidate, just delete the row with the grid cursor.
  535. wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
  536. wxGridCellCoordsArray cells = m_cur_grid->GetSelectedCells();
  537. wxGridCellCoordsArray blockTopLeft = m_cur_grid->GetSelectionBlockTopLeft();
  538. wxGridCellCoordsArray blockBotRight = m_cur_grid->GetSelectionBlockBottomRight();
  539. // Add all row having cell selected to list:
  540. for( unsigned ii = 0; ii < cells.GetCount(); ii++ )
  541. selectedRows.Add( cells[ii].GetRow() );
  542. // Handle block selection
  543. if( !blockTopLeft.IsEmpty() && !blockBotRight.IsEmpty() )
  544. {
  545. for( int i = blockTopLeft[0].GetRow(); i <= blockBotRight[0].GetRow(); ++i )
  546. selectedRows.Add( i );
  547. }
  548. // Use the row having the grid cursor only if we have no candidate:
  549. if( selectedRows.size() == 0 && m_cur_grid->GetGridCursorRow() >= 0 )
  550. selectedRows.Add( m_cur_grid->GetGridCursorRow() );
  551. if( selectedRows.size() == 0 )
  552. {
  553. wxBell();
  554. return;
  555. }
  556. std::sort( selectedRows.begin(), selectedRows.end() );
  557. // Remove selected rows (note: a row can be stored more than once in list)
  558. int last_row = -1;
  559. for( int ii = selectedRows.GetCount()-1; ii >= 0; ii-- )
  560. {
  561. int row = selectedRows[ii];
  562. if( row != last_row )
  563. {
  564. last_row = row;
  565. m_cur_grid->DeleteRows( row, 1 );
  566. }
  567. }
  568. if( m_cur_grid->GetNumberRows() > 0 && curRow >= 0 )
  569. m_cur_grid->SetGridCursor( std::min( curRow, m_cur_grid->GetNumberRows() - 1 ), curCol );
  570. }
  571. void PANEL_FP_LIB_TABLE::moveUpHandler( wxCommandEvent& event )
  572. {
  573. if( !m_cur_grid->CommitPendingChanges() )
  574. return;
  575. FP_LIB_TABLE_GRID* tbl = cur_model();
  576. int curRow = m_cur_grid->GetGridCursorRow();
  577. // @todo: add multiple selection moves.
  578. if( curRow >= 1 )
  579. {
  580. boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
  581. tbl->rows.release( tbl->rows.begin() + curRow );
  582. --curRow;
  583. tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
  584. if( tbl->GetView() )
  585. {
  586. // Update the wxGrid
  587. wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow, 0 );
  588. tbl->GetView()->ProcessTableMessage( msg );
  589. }
  590. m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
  591. m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
  592. }
  593. }
  594. void PANEL_FP_LIB_TABLE::moveDownHandler( wxCommandEvent& event )
  595. {
  596. if( !m_cur_grid->CommitPendingChanges() )
  597. return;
  598. FP_LIB_TABLE_GRID* tbl = cur_model();
  599. int curRow = m_cur_grid->GetGridCursorRow();
  600. // @todo: add multiple selection moves.
  601. if( unsigned( curRow + 1 ) < tbl->rows.size() )
  602. {
  603. boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
  604. tbl->rows.release( tbl->rows.begin() + curRow );
  605. ++curRow;
  606. tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
  607. if( tbl->GetView() )
  608. {
  609. // Update the wxGrid
  610. wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow - 1, 0 );
  611. tbl->GetView()->ProcessTableMessage( msg );
  612. }
  613. m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
  614. m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
  615. }
  616. }
  617. void PANEL_FP_LIB_TABLE::browseLibrariesHandler( wxCommandEvent& event )
  618. {
  619. if( !m_cur_grid->CommitPendingChanges() )
  620. return;
  621. std::map<int, SUPPORTED_FILE_TYPE>::const_iterator fileTypeIt;
  622. // We are bound both to the menu and button with this one handler
  623. // So we must set the file type based on it
  624. if( event.GetEventType() == wxEVT_BUTTON )
  625. {
  626. // Let's default to adding a kicad footprint file for just the footprint
  627. fileTypeIt = fileTypes().find( ID_PANEL_FPLIB_ADD_KICADMOD );
  628. }
  629. else
  630. {
  631. fileTypeIt = fileTypes().find( event.GetId() );
  632. }
  633. if( fileTypeIt == fileTypes().end() )
  634. {
  635. wxLogWarning( "File type selection event received but could not find the file type in the table" );
  636. return;
  637. }
  638. SUPPORTED_FILE_TYPE fileType = fileTypeIt->second;
  639. PCBNEW_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<PCBNEW_SETTINGS>();
  640. wxArrayString files;
  641. wxString title;
  642. title.Printf( _( "Select %s Library" ), fileType.m_Description );
  643. wxString openDir = cfg->m_lastFootprintLibDir;
  644. if( m_cur_grid == m_project_grid )
  645. openDir = m_lastProjectLibDir;
  646. if( fileType.m_IsFile )
  647. {
  648. wxFileDialog dlg( this, title, openDir, wxEmptyString, fileType.m_FileFilter,
  649. wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
  650. int result = dlg.ShowModal();
  651. if( result == wxID_CANCEL )
  652. return;
  653. dlg.GetPaths( files );
  654. if( m_cur_grid == m_global_grid )
  655. cfg->m_lastFootprintLibDir = dlg.GetDirectory();
  656. else
  657. m_lastProjectLibDir = dlg.GetDirectory();
  658. }
  659. else
  660. {
  661. #if wxCHECK_VERSION( 3, 1, 4 ) // 3.1.4 required for wxDD_MULTIPLE
  662. wxDirDialog dlg( nullptr, title, openDir,
  663. wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
  664. int result = dlg.ShowModal();
  665. if( result == wxID_CANCEL )
  666. return;
  667. dlg.GetPaths( files );
  668. #else
  669. wxDirDialog dlg( nullptr, title, openDir, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST );
  670. int result = dlg.ShowModal();
  671. if( result == wxID_CANCEL )
  672. return;
  673. // is there a file extension configured to hunt out their containing folders?
  674. if( fileType.m_FolderSearchExtension != "" )
  675. {
  676. wxDir rootDir( dlg.GetPath() );
  677. LIBRARY_TRAVERSER traverser( fileType.m_FolderSearchExtension, rootDir.GetName() );
  678. rootDir.Traverse( traverser );
  679. traverser.GetPaths( files );
  680. if( traverser.HasDirectoryOpenFailures() )
  681. {
  682. wxArrayString failedDirs;
  683. traverser.GetPaths( failedDirs );
  684. wxString detailedMsg = _( "The following directories could not be opened: \n" );
  685. for( const wxString& path : failedDirs )
  686. detailedMsg << path << "\n";
  687. DisplayErrorMessage( this, _( "Failed to open directories to look for libraries" ),
  688. detailedMsg );
  689. }
  690. }
  691. else
  692. {
  693. files.Add( dlg.GetPath() );
  694. }
  695. #endif
  696. if( !files.IsEmpty() )
  697. {
  698. wxFileName first( files.front() );
  699. if( m_cur_grid == m_global_grid )
  700. cfg->m_lastFootprintLibDir = first.GetPath();
  701. else
  702. m_lastProjectLibDir = first.GetPath();
  703. }
  704. }
  705. // Drop the last directory if the path is a .pretty folder
  706. if( cfg->m_lastFootprintLibDir.EndsWith( KiCadFootprintLibPathExtension ) )
  707. cfg->m_lastFootprintLibDir = cfg->m_lastFootprintLibDir.BeforeLast( wxFileName::GetPathSeparator() );
  708. const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
  709. bool addDuplicates = false;
  710. bool applyToAll = false;
  711. wxString warning = _( "Warning: Duplicate Nicknames" );
  712. wxString msg = _( "A library nicknamed '%s' already exists." );
  713. wxString detailedMsg = _( "One of the nicknames will need to be changed after "
  714. "adding this library." );
  715. for( const wxString& filePath : files )
  716. {
  717. wxFileName fn( filePath );
  718. wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
  719. bool doAdd = true;
  720. if( cur_model()->ContainsNickname( nickname ) )
  721. {
  722. if( !applyToAll )
  723. {
  724. // The cancel button adds the library to the table anyway
  725. addDuplicates = OKOrCancelDialog( this, warning, wxString::Format( msg, nickname ),
  726. detailedMsg, _( "Skip" ), _( "Add Anyway" ),
  727. &applyToAll ) == wxID_CANCEL;
  728. }
  729. doAdd = addDuplicates;
  730. }
  731. if( doAdd && m_cur_grid->AppendRows( 1 ) )
  732. {
  733. int last_row = m_cur_grid->GetNumberRows() - 1;
  734. m_cur_grid->SetCellValue( last_row, COL_NICKNAME, nickname );
  735. m_cur_grid->SetCellValue( last_row, COL_TYPE, IO_MGR::ShowType( fileType.m_Plugin ) );
  736. // try to use path normalized to an environmental variable or project path
  737. wxString path = NormalizePath( filePath, &envVars, m_projectBasePath );
  738. // Do not use the project path in the global library table. This will almost
  739. // assuredly be wrong for a different project.
  740. if( m_pageNdx == 0 && path.Contains( "${KIPRJMOD}" ) )
  741. path = fn.GetFullPath();
  742. m_cur_grid->SetCellValue( last_row, COL_URI, path );
  743. }
  744. }
  745. if( !files.IsEmpty() )
  746. {
  747. int new_row = m_cur_grid->GetNumberRows() - 1;
  748. m_cur_grid->MakeCellVisible( new_row, m_cur_grid->GetGridCursorCol() );
  749. m_cur_grid->SetGridCursor( new_row, m_cur_grid->GetGridCursorCol() );
  750. }
  751. }
  752. void PANEL_FP_LIB_TABLE::adjustPathSubsGridColumns( int aWidth )
  753. {
  754. // Account for scroll bars
  755. aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
  756. m_path_subs_grid->AutoSizeColumn( 0 );
  757. if( aWidth - m_path_subs_grid->GetColSize( 0 ) < 60 )
  758. m_path_subs_grid->SetColSize( 0, aWidth / 2 );
  759. m_path_subs_grid->SetColSize( 1, aWidth - m_path_subs_grid->GetColSize( 0 ) );
  760. }
  761. void PANEL_FP_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
  762. {
  763. adjustPathSubsGridColumns( event.GetSize().GetX() );
  764. event.Skip();
  765. }
  766. bool PANEL_FP_LIB_TABLE::TransferDataFromWindow()
  767. {
  768. if( !m_cur_grid->CommitPendingChanges() )
  769. return false;
  770. if( verifyTables() )
  771. {
  772. if( *global_model() != *m_global )
  773. {
  774. m_parent->m_GlobalTableChanged = true;
  775. m_global->Clear();
  776. m_global->rows.transfer( m_global->rows.end(), global_model()->rows.begin(),
  777. global_model()->rows.end(), global_model()->rows );
  778. m_global->reindex();
  779. }
  780. if( project_model() && *project_model() != *m_project )
  781. {
  782. m_parent->m_ProjectTableChanged = true;
  783. m_project->Clear();
  784. m_project->rows.transfer( m_project->rows.end(), project_model()->rows.begin(),
  785. project_model()->rows.end(), project_model()->rows );
  786. m_project->reindex();
  787. }
  788. return true;
  789. }
  790. return false;
  791. }
  792. /// Populate the readonly environment variable table with names and values
  793. /// by examining all the full_uri columns.
  794. void PANEL_FP_LIB_TABLE::populateEnvironReadOnlyTable()
  795. {
  796. wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
  797. wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
  798. std::set< wxString > unique;
  799. // clear the table
  800. m_path_subs_grid->ClearRows();
  801. for( FP_LIB_TABLE_GRID* tbl : { global_model(), project_model() } )
  802. {
  803. if( !tbl )
  804. continue;
  805. for( int row = 0; row < tbl->GetNumberRows(); ++row )
  806. {
  807. wxString uri = tbl->GetValue( row, COL_URI );
  808. while( re.Matches( uri ) )
  809. {
  810. wxString envvar = re.GetMatch( uri, 2 );
  811. // if not ${...} form then must be $(...)
  812. if( envvar.IsEmpty() )
  813. envvar = re.GetMatch( uri, 4 );
  814. // ignore duplicates
  815. unique.insert( envvar );
  816. // delete the last match and search again
  817. uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
  818. }
  819. }
  820. }
  821. // Make sure this special environment variable shows up even if it was
  822. // not used yet. It is automatically set by KiCad to the directory holding
  823. // the current project.
  824. unique.insert( PROJECT_VAR_NAME );
  825. unique.insert( FP_LIB_TABLE::GlobalPathEnvVariableName() );
  826. // This special environment variable is used to locate 3d shapes
  827. unique.insert( KICAD6_3DMODEL_DIR );
  828. for( const wxString& evName : unique )
  829. {
  830. int row = m_path_subs_grid->GetNumberRows();
  831. m_path_subs_grid->AppendRows( 1 );
  832. m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
  833. m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
  834. wxString evValue;
  835. wxGetEnv( evName, &evValue );
  836. m_path_subs_grid->SetCellValue( row, 1, evValue );
  837. m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
  838. }
  839. // No combobox editors here, but it looks better if its consistent with the other
  840. // grids in the dialog.
  841. m_path_subs_grid->SetDefaultRowSize( m_path_subs_grid->GetDefaultRowSize() + 2 );
  842. adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
  843. }
  844. //-----</event handlers>---------------------------------
  845. size_t PANEL_FP_LIB_TABLE::m_pageNdx = 0;
  846. void InvokePcbLibTableEditor( KIWAY* aKiway, wxWindow* aCaller )
  847. {
  848. FP_LIB_TABLE* globalTable = &GFootprintTable;
  849. wxString globalTablePath = FP_LIB_TABLE::GetGlobalTableFileName();
  850. FP_LIB_TABLE* projectTable = aKiway->Prj().PcbFootprintLibs();
  851. wxString projectTablePath = aKiway->Prj().FootprintLibTblName();
  852. wxString msg;
  853. DIALOG_EDIT_LIBRARY_TABLES dlg( aCaller, _( "Footprint Libraries" ) );
  854. dlg.SetKiway( &dlg, aKiway );
  855. if( aKiway->Prj().IsNullProject() )
  856. projectTable = nullptr;
  857. dlg.InstallPanel( new PANEL_FP_LIB_TABLE( &dlg, globalTable, globalTablePath,
  858. projectTable, projectTablePath,
  859. aKiway->Prj().GetProjectPath() ) );
  860. if( dlg.ShowModal() == wxID_CANCEL )
  861. return;
  862. if( dlg.m_GlobalTableChanged )
  863. {
  864. try
  865. {
  866. globalTable->Save( globalTablePath );
  867. }
  868. catch( const IO_ERROR& ioe )
  869. {
  870. msg.Printf( _( "Error saving global library table:\n\n%s" ), ioe.What() );
  871. wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
  872. }
  873. }
  874. if( projectTable && dlg.m_ProjectTableChanged )
  875. {
  876. try
  877. {
  878. projectTable->Save( projectTablePath );
  879. }
  880. catch( const IO_ERROR& ioe )
  881. {
  882. msg.Printf( _( "Error saving project-specific library table:\n\n%s" ), ioe.What() );
  883. wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
  884. }
  885. }
  886. auto editor = (FOOTPRINT_EDIT_FRAME*) aKiway->Player( FRAME_FOOTPRINT_EDITOR, false );
  887. if( editor )
  888. {
  889. editor->SyncLibraryTree( true );
  890. editor->RefreshLibraryTree();
  891. }
  892. auto viewer = (FOOTPRINT_VIEWER_FRAME*) aKiway->Player( FRAME_FOOTPRINT_VIEWER, false );
  893. if( viewer )
  894. viewer->ReCreateLibraryList();
  895. }