KiCad PCB EDA Suite
Loading...
Searching...
No Matches
panel_fp_lib_table.cpp
Go to the documentation of this file.
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 <[email protected]>
5 * Copyright (C) 2013-2021 CERN
6 * Copyright The 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, see <https://www.gnu.org/licenses/>.
20 */
21
22
23#include <set>
24#include <wx/regex.h>
25#include <wx/dirdlg.h>
26#include <wx/filedlg.h>
27#include <wx/msgdlg.h>
28#include <functional>
29
30#include <project.h>
31#include <env_vars.h>
33#include <panel_fp_lib_table.h>
34#include <lib_id.h>
36#include <lib_table_lexer.h>
37#include <invoke_pcb_dialog.h>
38#include <bitmaps.h>
40#include <widgets/wx_grid.h>
45#include <confirm.h>
47#include <kiplatform/ui.h>
49#include <pgm_base.h>
50#include <pcb_edit_frame.h>
51#include <env_paths.h>
55#include <kiway.h>
56#include <kiway_mail.h>
57#include <pcbnew_id.h> // For ID_PCBNEW_END_LIST
59#include <paths.h>
60#include <macros.h>
61#include <project_pcb.h>
62#include <common.h>
66
67
72{
73public:
74 FP_LIB_TABLE_GRID_DATA_MODEL( DIALOG_SHIM* aParent, WX_GRID* aGrid, const LIBRARY_TABLE& aTableToEdit,
75 FOOTPRINT_LIBRARY_ADAPTER* aAdapter, const wxArrayString& aPluginChoices,
76 wxString* aMRUDirectory, const wxString& aProjectPath,
77 const std::map<PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC>& aSupportedFiles ) :
78 LIB_TABLE_GRID_DATA_MODEL( aParent, aGrid, aTableToEdit, aAdapter, aPluginChoices, aMRUDirectory,
79 aProjectPath ),
80 m_supportedFpFiles( aSupportedFiles )
81 {
82 }
83
84 void SetValue( int aRow, int aCol, const wxString &aValue ) override
85 {
86 wxCHECK( aRow < (int) size(), /* void */ );
87
88 LIB_TABLE_GRID_DATA_MODEL::SetValue( aRow, aCol, aValue );
89
90 // If setting a filepath, attempt to auto-detect the format
91 if( aCol == COL_URI )
92 {
93 LIBRARY_TABLE_ROW& row = at( (size_t) aRow );
94 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
96
97 if( pluginType != PCB_IO_MGR::FILE_TYPE_NONE )
98 SetValue( aRow, COL_TYPE, PCB_IO_MGR::ShowType( pluginType ) );
99 }
100 }
101
102protected:
103 wxString getFileTypes( WX_GRID* aGrid, int aRow ) override
104 {
105 FP_LIB_TABLE_GRID_DATA_MODEL* table = static_cast<FP_LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
106 LIBRARY_TABLE_ROW& tableRow = table->at( aRow );
107
108 if( tableRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
109 {
110 wxString filter = _( "Footprint Library Tables" );
111#ifndef __WXOSX__
112 filter << wxString::Format( _( " (%s)|%s" ), FILEEXT::FootprintLibraryTableFileName,
114#else
115 filter << wxString::Format( _( " (%s)|%s" ), wxFileSelectorDefaultWildcardStr,
116 wxFileSelectorDefaultWildcardStr );
117#endif
118 return filter;
119 }
120
122
124 return wxEmptyString;
125
126 const IO_BASE::IO_FILE_DESC& pluginDesc = m_supportedFpFiles.at( fileType );
127
128 if( pluginDesc.m_IsFile )
129 return pluginDesc.FileFilter();
130
131 return wxEmptyString;
132 }
133
134private:
135 const std::map<PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC>& m_supportedFpFiles;
136};
137
138
139
141{
142public:
143 FP_GRID_TRICKS( PANEL_FP_LIB_TABLE* aPanel, WX_GRID* aGrid, std::function<void( wxCommandEvent& )> aAddHandler ) :
144 LIB_TABLE_GRID_TRICKS( aGrid, aAddHandler ),
145 m_panel( aPanel )
146 {
148 }
149
151 {
152 return false;
153 }
154
155protected:
156 void optionsEditor( int aRow ) override
157 {
158 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
159
160 if( tbl->GetNumberRows() > aRow )
161 {
162 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
163 const wxString& options = row.Options();
164 wxString result = options;
165 std::map<std::string, UTF8> choices;
166
169 pi->GetLibraryOptions( &choices );
170
171 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
172 dlg.ShowModal();
173
174 if( options != result )
175 {
176 row.SetOptions( result );
177 m_grid->Refresh();
178 }
179 }
180 }
181
182 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
183 {
184 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
185 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL,
187
188 if( !child->IsOk() )
189 {
190 wxMessageBox( _( "Unable to load library table." ) );
191 }
192 else
193 {
195
196 m_panel->OpenTable( child, aRow.Nickname() );
197 }
198 }
199
200 wxString getTablePreamble() override
201 {
202 return wxT( "(fp_lib_table" );
203 }
204
209
210protected:
212};
213
214
215void PANEL_FP_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
216{
217 wxString tabTitle = aTitle;
218
219 if( aTable->IsReadOnly() )
220 tabTitle += wxS( " " ) + _( "(read-only)" );
221
222 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
223 {
224 wxString candidate = m_notebook->GetPageText( ii );
225
226 if( candidate.EndsWith( " *" ) )
227 candidate = candidate.Left( candidate.Length() - 2 );
228
229 if( candidate == tabTitle )
230 {
231 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
232 // results in a re-entrant call where the second call is one page behind.
233 for( int attempts = 0; attempts < 3; ++attempts )
234 m_notebook->ChangeSelection( ii );
235
236 return;
237 }
238 }
239
240 m_nestedTables.push_back( aTable );
241 AddTable( aTable.get(), tabTitle, true );
242
243 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
244 // results in a re-entrant call where the second call is one page behind.
245 for( int attempts = 0; attempts < 3; ++attempts )
246 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
247}
248
249
250void PANEL_FP_LIB_TABLE::AddTable( LIBRARY_TABLE* aTable, const wxString& aTitle, bool aClosable )
251{
253 wxString projectPath = m_project->GetProjectPath();
254
256
257 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
258
259 if( aTable->Path().StartsWith( projectPath ) )
260 {
261 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *aTable, adapter, m_pluginChoices,
263 true /* take ownership */ );
264 }
265 else
266 {
267 wxString* lastGlobalLibDir = nullptr;
268
269 if( PCBNEW_SETTINGS* cfg = GetAppSettings<PCBNEW_SETTINGS>( "pcbnew" ) )
270 {
271 if( cfg->m_LastFootprintLibDir.IsEmpty() )
272 cfg->m_LastFootprintLibDir = PATHS::GetDefaultUserFootprintsPath();
273
274 lastGlobalLibDir = &cfg->m_LastFootprintLibDir;
275 }
276
277 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *aTable, adapter, m_pluginChoices,
278 lastGlobalLibDir, wxEmptyString, m_supportedFpFiles ),
279 true /* take ownership */ );
280 }
281
282 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )->RecheckRows();
283
284 LIB_TABLE_NOTEBOOK_PANEL* notebookPanel =
285 static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( m_notebook->GetPageCount() - 1 ) );
286
287 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )->SetChangeCallback(
288 [notebookPanel]()
289 {
290 notebookPanel->MarkDirty();
291 } );
292
293 // add Cut, Copy, and Paste to wxGrids
294 grid->PushEventHandler( new FP_GRID_TRICKS( this, grid,
295 [this]( wxCommandEvent& event )
296 {
297 appendRowHandler( event );
298 } ) );
299
300 auto autoSizeCol =
301 [&]( int aCol )
302 {
303 int prevWidth = grid->GetColSize( aCol );
304
305 grid->AutoSizeColumn( aCol, false );
306 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
307 };
308
309 // all but COL_OPTIONS, which is edited with Option Editor anyways.
310 autoSizeCol( COL_NICKNAME );
311 autoSizeCol( COL_TYPE );
312 autoSizeCol( COL_URI );
313 autoSizeCol( COL_DESCR );
314
315 if( grid->GetNumberRows() > 0 )
316 {
317 grid->SetGridCursor( 0, COL_NICKNAME );
318 grid->SelectRow( 0 );
319 }
320}
321
322
324 PANEL_FP_LIB_TABLE_BASE( aParent ),
325 m_project( aProject ),
326 m_parent( aParent ),
328{
329 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
330
331 m_lastProjectLibDir = m_project->GetProjectPath();
332
334
335 for( auto& [fileType, desc] : m_supportedFpFiles )
337
338 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
340 wxASSERT( table.has_value() );
341
342 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
343
344 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
346
347 if( projectTable.has_value() )
348 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
349
350 // add Cut, Copy, and Paste to wxGrids
351 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
352
354
355 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
356 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
357
358 // Configure button logos
364
365 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
366 // manually (for instance m_append_button)
367 Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
368 // their bitmaps
369 wxSize buttonSize = m_append_button->GetSize();
370
371 m_browseButton->SetWidthPadding( 4 );
372 m_browseButton->SetMinSize( buttonSize );
373
374 // Populate the browse library options
375 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
376
377 for( auto& [type, desc] : m_supportedFpFiles )
378 {
379 wxString entryStr = PCB_IO_MGR::ShowType( type );
380 wxString midPart;
381
382 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
383 {
384 entryStr << wxString::Format( wxS( " (%s)" ), JoinExtensions( desc.m_FileExtensions ) );
385 }
386 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
387 {
388 midPart = wxString::Format( _( "folder with %s files" ), JoinExtensions( desc.m_ExtensionsInDir ) );
389 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
390 }
391
392 browseMenu->Append( type, entryStr );
393 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this, type );
394 }
395
396 Layout();
397
398 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_FP_LIB_TABLE::onNotebookPageCloseRequest, this );
399 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CHANGING, &PANEL_FP_LIB_TABLE::onNotebookPageChangeRequest, this );
400 // This is the button only press for the browse button instead of the menu
402}
403
404
406{
407 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
408
409 for( auto& [type, desc] : m_supportedFpFiles )
410 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this, type );
411
412 m_browseButton->Unbind( wxEVT_BUTTON, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this );
413
414 // Delete the GRID_TRICKS.
415 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
416 m_path_subs_grid->PopEventHandler( true );
417}
418
419
421{
422 return static_cast<FP_LIB_TABLE_GRID_DATA_MODEL*>( get_grid( aPage )->GetTable() );
423}
424
425
427{
428 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
429}
430
431
433{
434 // No visibility control for footprint libraries yet; this feature is primarily
435 // useful for database libraries and it's only implemented for schematic symbols
436 // at the moment.
437 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
438 {
439 WX_GRID* grid = get_grid( page );
440 grid->HideCol( COL_VISIBLE );
441 }
442
443 // for ALT+A handling, we want the initial focus to be on the first selected grid.
444 m_parent->SetInitialFocus( cur_grid() );
445
446 return true;
447}
448
449
451{
452 for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
453 {
454 IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
455
456 if( !pi )
457 continue;
458
459 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
460 m_supportedFpFiles.emplace( plugin.m_type, desc );
461 }
462
464 IO_BASE::IO_FILE_DESC( _( "Table (nested library table)" ), {} ) );
465}
466
467
469{
470 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
471 {
472 WX_GRID* grid = get_grid( page );
473
475 [&]( int aRow, int aCol )
476 {
477 // show the tabbed panel holding the grid we have flunked:
478 if( m_notebook->GetSelection() != page )
479 m_notebook->SetSelection( page );
480
481 grid->MakeCellVisible( aRow, 0 );
482 grid->SetGridCursor( aRow, aCol );
483 } ) )
484 {
485 return false;
486 }
487 }
488
489 return true;
490}
491
492
497
498
503
504
509
510
515
516
517// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
518void PANEL_FP_LIB_TABLE::onMigrateLibraries( wxCommandEvent& event )
519{
520 if( !cur_grid()->CommitPendingChanges() )
521 return;
522
523 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
524
525 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
526 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
527
528 wxArrayInt rowsToMigrate;
529 wxString kicadType = PCB_IO_MGR::ShowType( PCB_IO_MGR::KICAD_SEXP );
530 wxString nestedTableType = LIBRARY_TABLE_ROW::TABLE_TYPE_NAME;
531 wxString msg;
532 DIALOG_HTML_REPORTER errorReporter( this );
533
534 for( int row : selectedRows )
535 {
536 const wxString& type = cur_grid()->GetCellValue( row, COL_TYPE );
537
538 // Nested library tables are not footprint libraries and cannot be migrated.
539 if( type != kicadType && type != nestedTableType )
540 rowsToMigrate.push_back( row );
541 }
542
543 if( rowsToMigrate.size() <= 0 )
544 {
545 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
546 return;
547 }
548 else
549 {
550 if( rowsToMigrate.size() == 1 )
551 {
552 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
553 cur_grid()->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
554 }
555 else
556 {
557 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
558 (int) rowsToMigrate.size() );
559 }
560
561 if( !IsOK( m_parent, msg ) )
562 return;
563 }
564
565 for( int row : rowsToMigrate )
566 {
567 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
568 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
569 wxFileName legacyLib( resolvedPath );
570
571 if( !legacyLib.Exists() )
572 {
573 msg.Printf( _( "Library '%s' not found." ), relPath );
574 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
575 continue;
576 }
577
578 wxFileName newLib( resolvedPath );
579 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadFootprintLibPathExtension );
580 newLib.SetName( "" );
581 newLib.ClearExt();
582
583 if( newLib.DirExists() )
584 {
585 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing footprints?" ),
586 newLib.GetFullPath() );
587
588 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO|wxCANCEL|wxICON_QUESTION, m_parent ) )
589 {
590 case wxYES: break;
591 case wxNO: continue;
592 case wxCANCEL: return;
593 }
594 }
595
596 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
597 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
598
599 if( PCB_IO_MGR::ConvertLibrary( props, legacyLib.GetFullPath(), newLib.GetFullPath(),
600 errorReporter.m_Reporter ) )
601 {
602 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
603
604 cur_grid()->SetCellValue( row, COL_URI, relPath );
605 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
606 }
607 else
608 {
609 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save footprint library file '%s'." ),
610 newLib.GetFullPath() ) );
611 }
612 }
613
614 if( errorReporter.m_Reporter->HasMessage() )
615 {
616 errorReporter.m_Reporter->Flush(); // Build HTML messages
617 errorReporter.ShowModal();
618 }
619}
620
621
623{
624 if( !cur_grid()->CommitPendingChanges() )
625 return;
626
628
629 // We are bound both to the menu and button with this one handler
630 // So we must set the file type based on it
631 if( event.GetEventType() == wxEVT_BUTTON )
632 {
633 // Let's default to adding a kicad footprint file for just the footprint
635 }
636 else
637 {
638 fileType = static_cast<PCB_IO_MGR::PCB_FILE_T>( event.GetId() );
639 }
640
642 return;
643
644 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
645 const IO_BASE::IO_FILE_DESC& fileDesc = m_supportedFpFiles.at( fileType );
647
648 wxString title;
649 wxString dummy;
650 wxString* lastDir;
651
653 title = _( "Select Library Table" );
654 else
655 title = wxString::Format( _( "Select %s Library" ), PCB_IO_MGR::ShowType( fileType ) );
656
657 if( m_notebook->GetSelection() == 0 )
658 lastDir = cfg ? &cfg->m_LastFootprintLibDir : &dummy;
659 else
660 lastDir = &m_lastProjectLibDir;
661
662 wxArrayString files;
663
664 if( fileDesc.m_IsFile )
665 {
666 wxFileDialog dlg( m_parent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
667 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
668
670
671 if( dlg.ShowModal() == wxID_CANCEL )
672 return;
673
674 dlg.GetPaths( files );
675 *lastDir = dlg.GetDirectory();
676 }
677 else
678 {
679 wxDirDialog dlg( m_parent, title, *lastDir, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
680
681 if( dlg.ShowModal() == wxID_CANCEL )
682 return;
683
684 dlg.GetPaths( files );
685
686 if( !files.IsEmpty() )
687 {
688 wxFileName first( files.front() );
689 *lastDir = first.GetPath();
690 }
691 }
692
693 // Drop the last directory if the path is a .pretty folder
695 cfg->m_LastFootprintLibDir = cfg->m_LastFootprintLibDir.BeforeLast( wxFileName::GetPathSeparator() );
696
697
698 bool addDuplicates = false;
699 bool applyToAll = false;
700 wxString warning = _( "Warning: Duplicate Nicknames" );
701 wxString msg = _( "An item nicknamed '%s' already exists." );
702 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
703
704 for( const wxString& filePath : files )
705 {
706 wxFileName fn( filePath );
707 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
708 bool doAdd = true;
709
712 {
713 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
714 }
715
716 if( cur_model()->ContainsNickname( nickname ) )
717 {
718 if( !applyToAll )
719 {
720 // The cancel button adds the library to the table anyway
721 addDuplicates = OKOrCancelDialog( m_parent, warning, wxString::Format( msg, nickname ), detailedMsg,
722 _( "Skip" ), _( "Add Anyway" ), &applyToAll ) == wxID_CANCEL;
723 }
724
725 doAdd = addDuplicates;
726 }
727
728 if( doAdd && cur_grid()->AppendRows( 1 ) )
729 {
730 int last_row = cur_grid()->GetNumberRows() - 1;
731
732 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
733 cur_grid()->SetCellValue( last_row, COL_TYPE, PCB_IO_MGR::ShowType( fileType ) );
734
735 // try to use path normalized to an environmental variable or project path
736 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
737
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_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
741 path = fn.GetFullPath();
742
743 cur_grid()->SetCellValue( last_row, COL_URI, path );
744 }
745 }
746
747 if( !files.IsEmpty() )
748 {
749 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
750 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
751 }
752}
753
754
755void PANEL_FP_LIB_TABLE::onNotebookPageCloseRequest( wxAuiNotebookEvent& aEvent )
756{
757 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
758 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
759
760 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
761 {
762 if( panel->GetClosable() )
763 {
764 if( !panel->GetCanClose() )
765 aEvent.Veto();
766 }
767 else
768 {
769 aEvent.Veto();
770 }
771 }
772}
773
774
776{
777 // Account for scroll bars
778 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
779
780 m_path_subs_grid->AutoSizeColumn( 0 );
781 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
782 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
783}
784
785
786void PANEL_FP_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
787{
788 adjustPathSubsGridColumns( event.GetSize().GetX() );
789
790 event.Skip();
791}
792
793
794void PANEL_FP_LIB_TABLE::onReset( wxCommandEvent& event )
795{
796 if( !cur_grid()->CommitPendingChanges() )
797 return;
798
799 WX_GRID* grid = get_grid( 0 );
800
801 // No need to prompt to preserve an empty table
802 if( grid->GetNumberRows() > 0 && !IsOK( this, wxString::Format( _( "This action will reset your global library "
803 "table on disk and cannot be undone." ) ) ) )
804 {
805 return;
806 }
807
808 wxString* lastGlobalLibDir = nullptr;
809
810 if( PCBNEW_SETTINGS* cfg = GetAppSettings<PCBNEW_SETTINGS>( "pcbnew" ) )
811 {
812 if( cfg->m_LastFootprintLibDir.IsEmpty() )
813 cfg->m_LastFootprintLibDir = PATHS::GetDefaultUserFootprintsPath();
814
815 lastGlobalLibDir = &cfg->m_LastFootprintLibDir;
816 }
817
819
820 // Go ahead and reload here because this action takes place even if the dialog is canceled
822
823 if( KIFACE *face = m_parent->Kiway().KiFACE( KIWAY::FACE_PCB ) )
824 face->PreloadLibraries( &m_parent->Kiway() );
825
826 grid->Freeze();
827
828 wxGridTableBase* table = grid->GetTable();
829 grid->DestroyTable( table );
830
831 std::optional<LIBRARY_TABLE*> newTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
833 wxASSERT( newTable );
834
836
837 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *newTable.value(), adapter, m_pluginChoices,
838 lastGlobalLibDir, wxEmptyString, m_supportedFpFiles ),
839 true /* take ownership */ );
840
841 LIB_TABLE_NOTEBOOK_PANEL* panel0 = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( 0 ) );
842 panel0->ClearDirty();
843
844 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )->SetChangeCallback(
845 [panel0]()
846 {
847 panel0->MarkDirty();
848 } );
849
850 m_parent->m_GlobalTableChanged = true;
851
852 grid->Thaw();
853
854 if( grid->GetNumberRows() > 0 )
855 {
856 grid->SetGridCursor( 0, COL_NICKNAME );
857 grid->SelectRow( 0 );
858 }
859}
860
861
862void PANEL_FP_LIB_TABLE::onNotebookPageChangeRequest( wxAuiNotebookEvent& aEvent )
863{
865 aEvent.Veto();
866 else
867 aEvent.Skip();
868}
869
870
871void PANEL_FP_LIB_TABLE::onPageChange( wxAuiNotebookEvent& event )
872{
873 m_resetGlobal->Enable( m_notebook->GetSelection() == 0 );
874}
875
876
878{
879 if( !cur_grid()->CommitPendingChanges() )
880 return false;
881
882 if( !verifyTables() )
883 return false;
884
885 bool success = true;
887 int firstNestedTable = 1;
888 std::optional<LIBRARY_TABLE*> globalTable = manager.Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
890
891 if( globalTable.has_value() && get_model( 0 )->Table() != *globalTable.value() )
892 {
893 m_parent->m_GlobalTableChanged = true;
894 *globalTable.value() = get_model( 0 )->Table();
895
896 globalTable.value()->Save().map_error(
897 [&success]( const LIBRARY_ERROR& aError )
898 {
899 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
900 _( "File Save Error" ), wxOK | wxICON_ERROR );
901 success = false;
902 } );
903 }
904
905 std::optional<LIBRARY_TABLE*> projectTable = manager.Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
907
908 if( projectTable.has_value() && get_model( 1 )->Table().Path() == projectTable.value()->Path() )
909 {
910 firstNestedTable = 2;
911
912 if( get_model( 1 )->Table() != *projectTable.value() )
913 {
914 m_parent->m_ProjectTableChanged = true;
915 *projectTable.value() = get_model( 1 )->Table();
916
917 projectTable.value()->Save().map_error(
918 [&success]( const LIBRARY_ERROR& aError )
919 {
920 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
921 _( "File Save Error" ), wxOK | wxICON_ERROR );
922 success = false;
923 } );
924 }
925 }
926
927 for( int ii = firstNestedTable; ii < (int) m_notebook->GetPageCount(); ++ii )
928 {
929 LIB_TABLE_NOTEBOOK_PANEL* panel = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
930
931 if( panel->TableModified() )
932 success &= panel->SaveTable();
933 }
934
936 return success;
937}
938
939
943{
944 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
945 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
946
947 std::set< wxString > unique;
948
949 // clear the table
950 m_path_subs_grid->ClearRows();
951
952 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
953 {
955
956 for( int row = 0; row < model->GetNumberRows(); ++row )
957 {
958 wxString uri = model->GetValue( row, COL_URI );
959
960 while( re.Matches( uri ) )
961 {
962 wxString envvar = re.GetMatch( uri, 2 );
963
964 // if not ${...} form then must be $(...)
965 if( envvar.IsEmpty() )
966 envvar = re.GetMatch( uri, 4 );
967
968 // ignore duplicates
969 unique.insert( envvar );
970
971 // delete the last match and search again
972 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
973 }
974 }
975 }
976
977 // Make sure this special environment variable shows up even if it was not used yet. It is
978 // automatically set by KiCad to the directory holding the current project.
979 unique.insert( PROJECT_VAR_NAME );
980 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "FOOTPRINT_DIR" ) ) );
981
982 // This special environment variable is used to locate 3d shapes
983 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
984
985 for( const wxString& evName : unique )
986 {
987 int row = m_path_subs_grid->GetNumberRows();
988 m_path_subs_grid->AppendRows( 1 );
989
990 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
991 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
992
993 wxString evValue;
994 wxGetEnv( evName, &evValue );
995 m_path_subs_grid->SetCellValue( row, 1, evValue );
996 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
997 }
998
999 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
1000}
1001
1002
1003//-----</event handlers>---------------------------------
1004
1005
1006
1007void InvokePcbLibTableEditor( KIWAY* aKiway, wxWindow* aCaller )
1008{
1009 DIALOG_EDIT_LIBRARY_TABLES dlg( aCaller, _( "Footprint Libraries" ) );
1010 dlg.SetKiway( &dlg, aKiway );
1011
1012 PANEL_FP_LIB_TABLE* panel = new PANEL_FP_LIB_TABLE( &dlg, &aKiway->Prj() );
1013 dlg.InstallPanel( panel, panel->GetNotebook() );
1014
1015 // User can choose to save changes on a Cancel, so don't exit on wxID_CANCEL.
1016 dlg.ShowModal();
1017
1018 if( dlg.m_GlobalTableChanged )
1020
1021 if( dlg.m_ProjectTableChanged )
1022 {
1023 // Trigger a reload of the table and cancel an in-progress background load
1025 }
1026
1027 // Trigger a reload in case any libraries have been added or removed
1028 if( KIFACE *face = aKiway->KiFACE( KIWAY::FACE_PCB ) )
1029 face->PreloadLibraries( aKiway );
1030
1031 std::string payload = "";
1034 aKiway->ExpressMail( FRAME_CVPCB, MAIL_RELOAD_LIB, payload );
1035}
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:106
void InstallPanel(wxPanel *aPanel, wxAuiNotebook *aNotebook)
Class DIALOG_HTML_REPORTER.
WX_HTML_REPORT_BOX * m_Reporter
An options editor in the form of a two column name/value spreadsheet like (table) UI.
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
Definition dialog_shim.h:80
int ShowModal() override
An interface to the global shared library manager that is schematic-specific and linked to one projec...
void openTable(const LIBRARY_TABLE_ROW &aRow) override
FP_GRID_TRICKS(PANEL_FP_LIB_TABLE *aPanel, WX_GRID *aGrid, std::function< void(wxCommandEvent &)> aAddHandler)
static bool SupportsVisibilityColumn()
wxString getTablePreamble() override
void optionsEditor(int aRow) override
PANEL_FP_LIB_TABLE * m_panel
bool supportsVisibilityColumn() override
This class builds a wxGridTableBase by wrapping an #FP_LIB_TABLE object.
FP_LIB_TABLE_GRID_DATA_MODEL(DIALOG_SHIM *aParent, WX_GRID *aGrid, const LIBRARY_TABLE &aTableToEdit, FOOTPRINT_LIBRARY_ADAPTER *aAdapter, const wxArrayString &aPluginChoices, wxString *aMRUDirectory, const wxString &aProjectPath, const std::map< PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC > &aSupportedFiles)
wxString getFileTypes(WX_GRID *aGrid, int aRow) override
void SetValue(int aRow, int aCol, const wxString &aValue) override
const std::map< PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC > & m_supportedFpFiles
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
Definition grid_tricks.h:57
WX_GRID * m_grid
I don't own the grid, but he owns me.
void SetTooltipEnable(int aCol, bool aEnable=true)
Enable the tooltip for a column.
Definition grid_tricks.h:71
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
It is only used for debugging, since "this" is not a wxWindow*.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:340
virtual void ExpressMail(FRAME_T aDestination, MAIL_T aCommand, std::string &aPayload, wxWindow *aSource=nullptr, bool aFromOtherThread=false)
Send aPayload to aDestination from aSource.
Definition kiway.cpp:486
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:207
@ FACE_PCB
pcbnew DSO
Definition kiway.h:348
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:201
static wxString ExpandURI(const wxString &aShortURI, const PROJECT &aProject)
std::optional< LIBRARY_TABLE * > Table(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope)
Retrieves a given table; creating a new empty project table if a valid project is loaded and the give...
void ApplyLibOverrides(LIBRARY_TABLE &aTable)
Applies stored user overrides (disabled/hidden) to rows of a read-only table.
static bool CreateGlobalTable(LIBRARY_TABLE_TYPE aType, bool aPopulateDefaultLibraries)
void LoadGlobalTables(std::initializer_list< LIBRARY_TABLE_TYPE > aTablesToLoad={})
(Re)loads the global library tables in the given list, or all tables if no list is given
void ProjectChanged()
Notify all adapters that the project has changed.
void SetOptions(const wxString &aOptions)
const wxString & Type() const
static const wxString TABLE_TYPE_NAME
const wxString & URI() const
const wxString & Nickname() const
const wxString & Options() const
LIBRARY_RESULT< void > Save()
static std::map< std::string, UTF8 > ParseOptions(const std::string &aOptionsList)
const wxString & Path() const
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
This abstract base class mixes any object derived from #LIB_TABLE into wxGridTableBase so the result ...
virtual LIBRARY_TABLE_ROW & at(size_t aIndex)
void SetChangeCallback(std::function< void()> aCallback)
LIBRARY_TABLE_ROW & At(size_t aIndex)
void SetValue(int aRow, int aCol, const wxString &aValue) override
LIB_TABLE_GRID_DATA_MODEL(DIALOG_SHIM *aParent, WX_GRID *aGrid, const LIBRARY_TABLE &aTableToEdit, LIBRARY_MANAGER_ADAPTER *aAdapter, const wxArrayString &aPluginChoices, wxString *aMRUDirectory, const wxString &aProjectPath)
static void MoveUpHandler(WX_GRID *aGrid)
LIB_TABLE_GRID_TRICKS(WX_GRID *aGrid)
static void DeleteRowHandler(WX_GRID *aGrid)
static void AppendRowHandler(WX_GRID *aGrid, const wxString &aType)
static bool VerifyTable(WX_GRID *aGrid, bool aSupportsVisibilityColumn, std::function< void(int aRow, int aCol)> aErrorHandler)
static void MoveDownHandler(WX_GRID *aGrid)
static void AddTable(wxAuiNotebook *aNotebook, const wxString &aTitle, bool aClosable)
STD_BITMAP_BUTTON * m_move_up_button
STD_BITMAP_BUTTON * m_append_button
STD_BITMAP_BUTTON * m_move_down_button
STD_BITMAP_BUTTON * m_delete_button
PANEL_FP_LIB_TABLE_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
Dialog to show and edit symbol library tables.
void OpenTable(const std::shared_ptr< LIBRARY_TABLE > &table, const wxString &aTitle)
bool verifyTables()
Trim important fields, removes blank row entries, and checks for duplicates.
std::map< PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC > m_supportedFpFiles
void onSizeGrid(wxSizeEvent &event) override
void moveUpHandler(wxCommandEvent &event) override
bool TransferDataToWindow() override
WX_GRID * cur_grid() const
void adjustPathSubsGridColumns(int aWidth)
void moveDownHandler(wxCommandEvent &event) override
wxArrayString m_pluginChoices
PANEL_FP_LIB_TABLE(DIALOG_EDIT_LIBRARY_TABLES *aParent, PROJECT *aProject)
void populateEnvironReadOnlyTable()
Populate the readonly environment variable table with names and values by examining all the full_uri ...
void deleteRowHandler(wxCommandEvent &event) override
void onNotebookPageCloseRequest(wxAuiNotebookEvent &aEvent)
FP_LIB_TABLE_GRID_DATA_MODEL * get_model(int aPage) const
FP_LIB_TABLE_GRID_DATA_MODEL * cur_model() const
void onReset(wxCommandEvent &event) override
std::vector< std::shared_ptr< LIBRARY_TABLE > > m_nestedTables
void onMigrateLibraries(wxCommandEvent &event) override
void browseLibrariesHandler(wxCommandEvent &event)
void onPageChange(wxAuiNotebookEvent &event) override
bool TransferDataFromWindow() override
void AddTable(LIBRARY_TABLE *table, const wxString &aTitle, bool aClosable)
WX_GRID * get_grid(int aPage) const
void onNotebookPageChangeRequest(wxAuiNotebookEvent &aEvent)
DIALOG_EDIT_LIBRARY_TABLES * m_parent
void appendRowHandler(wxCommandEvent &event) override
wxAuiNotebook * GetNotebook() const
static wxString GetDefaultUserFootprintsPath()
Gets the default path we point users to create projects.
Definition paths.cpp:93
wxString m_LastFootprintLibDir
static PLUGIN_REGISTRY * Instance()
Definition pcb_io_mgr.h:98
static bool ConvertLibrary(const std::map< std::string, UTF8 > &aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilePath, REPORTER *aReporter)
Convert a schematic symbol library to the latest KiCad format.
static PCB_FILE_T EnumFromStr(const wxString &aFileType)
Return the PCB_FILE_T from the corresponding plugin type name: "kicad", "legacy", etc.
PCB_FILE_T
The set of file types that the PCB_IO_MGR knows about, and for which there has been a plugin written,...
Definition pcb_io_mgr.h:52
@ KICAD_SEXP
S-expression Pcbnew file format.
Definition pcb_io_mgr.h:54
@ PCB_FILE_UNKNOWN
0 is not a legal menu id on Mac
Definition pcb_io_mgr.h:53
static PCB_IO * FindPlugin(PCB_FILE_T aFileType)
Return a #PLUGIN which the caller can use to import, export, save, or load design documents.
static PCB_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a footprint library's libPath.
static const wxString ShowType(PCB_FILE_T aFileType)
Return a brief name for a plugin given aFileType enum.
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition pgm_base.cpp:792
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:125
static FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(PROJECT *aProject)
Container for project specific data.
Definition project.h:63
wxString wx_str() const
Definition utf8.cpp:41
void Flush()
Build the HTML messages page.
bool HasMessage() const override
Returns true if any messages were reported.
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:776
wxString JoinExtensions(const std::vector< std::string > &aExts)
Join a list of file extensions for use in a file dialog.
Definition common.cpp:867
int OKOrCancelDialog(wxWindow *aParent, const wxString &aWarning, const wxString &aMessage, const wxString &aDetailedMessage, const wxString &aOKLabel, const wxString &aCancelLabel, bool *aApplyToAll)
Display a warning dialog with aMessage and returns the user response.
Definition confirm.cpp:165
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define _(s)
Declaration of the eda_3d_viewer class.
wxString NormalizePath(const wxFileName &aFilePath, const ENV_VAR_MAP *aEnvVars, const wxString &aProjectPath)
Normalize a file path to an environmental variable, if possible.
Definition env_paths.cpp:73
Helper functions to substitute paths with environmental variables.
Functions related to environment variables, including help functions.
@ FRAME_FOOTPRINT_VIEWER
Definition frame_type.h:41
@ FRAME_FOOTPRINT_EDITOR
Definition frame_type.h:39
@ FRAME_CVPCB
Definition frame_type.h:48
static const std::string FootprintLibraryTableFileName
static const std::string KiCadFootprintLibPathExtension
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
PROJECT & Prj()
Definition kicad.cpp:727
This file contains miscellaneous commonly used macros and functions.
@ MAIL_RELOAD_LIB
Definition mail_type.h:53
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:78
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:521
void InvokePcbLibTableEditor(KIWAY *aKiway, wxWindow *aCaller)
Function InvokePcbLibTableEditor shows the modal DIALOG_FP_LIB_TABLE for purposes of editing the glob...
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition project.h:38
T * GetAppSettings(const char *aFilename)
std::vector< FAB_LAYER_COLOR > dummy
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
Container that describes file type info.
Definition io_base.h:43
bool m_IsFile
Whether the library is a folder or a file.
Definition io_base.h:51
wxString FileFilter() const
Definition io_base.cpp:40
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
wxString message
std::string path
KIBIS_MODEL * model
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.