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, 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
26
27#include <set>
28#include <wx/regex.h>
29#include <wx/dirdlg.h>
30#include <wx/filedlg.h>
31#include <wx/msgdlg.h>
32#include <functional>
33
34#include <project.h>
35#include <env_vars.h>
37#include <panel_fp_lib_table.h>
38#include <lib_id.h>
40#include <lib_table_lexer.h>
41#include <invoke_pcb_dialog.h>
42#include <bitmaps.h>
44#include <widgets/wx_grid.h>
49#include <confirm.h>
51#include <kiplatform/ui.h>
53#include <pgm_base.h>
54#include <pcb_edit_frame.h>
55#include <env_paths.h>
59#include <kiway.h>
60#include <kiway_mail.h>
61#include <pcbnew_id.h> // For ID_PCBNEW_END_LIST
63#include <paths.h>
64#include <macros.h>
65#include <project_pcb.h>
66#include <common.h>
70
71
76{
77public:
78 FP_LIB_TABLE_GRID_DATA_MODEL( DIALOG_SHIM* aParent, WX_GRID* aGrid, const LIBRARY_TABLE& aTableToEdit,
79 FOOTPRINT_LIBRARY_ADAPTER* aAdapter, const wxArrayString& aPluginChoices,
80 wxString* aMRUDirectory, const wxString& aProjectPath,
81 const std::map<PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC>& aSupportedFiles ) :
82 LIB_TABLE_GRID_DATA_MODEL( aParent, aGrid, aTableToEdit, aAdapter, aPluginChoices, aMRUDirectory,
83 aProjectPath ),
84 m_supportedFpFiles( aSupportedFiles )
85 {
86 }
87
88 void SetValue( int aRow, int aCol, const wxString &aValue ) override
89 {
90 wxCHECK( aRow < (int) size(), /* void */ );
91
92 LIB_TABLE_GRID_DATA_MODEL::SetValue( aRow, aCol, aValue );
93
94 // If setting a filepath, attempt to auto-detect the format
95 if( aCol == COL_URI )
96 {
97 LIBRARY_TABLE_ROW& row = at( (size_t) aRow );
98 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
100
101 if( pluginType != PCB_IO_MGR::FILE_TYPE_NONE )
102 SetValue( aRow, COL_TYPE, PCB_IO_MGR::ShowType( pluginType ) );
103 }
104 }
105
106protected:
107 wxString getFileTypes( WX_GRID* aGrid, int aRow ) override
108 {
109 FP_LIB_TABLE_GRID_DATA_MODEL* table = static_cast<FP_LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
110 LIBRARY_TABLE_ROW& tableRow = table->at( aRow );
111
112 if( tableRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
113 {
114 wxString filter = _( "Footprint Library Tables" );
115#ifndef __WXOSX__
116 filter << wxString::Format( _( " (%s)|%s" ), FILEEXT::FootprintLibraryTableFileName,
118#else
119 filter << wxString::Format( _( " (%s)|%s" ), wxFileSelectorDefaultWildcardStr,
120 wxFileSelectorDefaultWildcardStr );
121#endif
122 return filter;
123 }
124
126
128 return wxEmptyString;
129
130 const IO_BASE::IO_FILE_DESC& pluginDesc = m_supportedFpFiles.at( fileType );
131
132 if( pluginDesc.m_IsFile )
133 return pluginDesc.FileFilter();
134
135 return wxEmptyString;
136 }
137
138private:
139 const std::map<PCB_IO_MGR::PCB_FILE_T, IO_BASE::IO_FILE_DESC>& m_supportedFpFiles;
140};
141
142
143
145{
146public:
147 FP_GRID_TRICKS( PANEL_FP_LIB_TABLE* aPanel, WX_GRID* aGrid, std::function<void( wxCommandEvent& )> aAddHandler ) :
148 LIB_TABLE_GRID_TRICKS( aGrid, aAddHandler ),
149 m_panel( aPanel )
150 {
152 }
153
155 {
156 return false;
157 }
158
159protected:
160 void optionsEditor( int aRow ) override
161 {
162 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
163
164 if( tbl->GetNumberRows() > aRow )
165 {
166 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
167 const wxString& options = row.Options();
168 wxString result = options;
169 std::map<std::string, UTF8> choices;
170
173 pi->GetLibraryOptions( &choices );
174
175 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
176 dlg.ShowModal();
177
178 if( options != result )
179 {
180 row.SetOptions( result );
181 m_grid->Refresh();
182 }
183 }
184 }
185
186 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
187 {
188 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
189 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL, LIBRARY_TABLE_TYPE::FOOTPRINT );
190
191 m_panel->OpenTable( child, aRow.Nickname() );
192 }
193
194 wxString getTablePreamble() override
195 {
196 return wxT( "(fp_lib_table" );
197 }
198
203
204protected:
206};
207
208
209void PANEL_FP_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
210{
211 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
212 {
213 if( m_notebook->GetPageText( ii ) == aTitle )
214 {
215 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
216 // results in a re-entrant call where the second call is one page behind.
217 for( int attempts = 0; attempts < 3; ++attempts )
218 m_notebook->ChangeSelection( ii );
219
220 return;
221 }
222 }
223
224 m_nestedTables.push_back( aTable );
225 AddTable( aTable.get(), aTitle, true );
226
227 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
228 // results in a re-entrant call where the second call is one page behind.
229 for( int attempts = 0; attempts < 3; ++attempts )
230 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
231}
232
233
234void PANEL_FP_LIB_TABLE::AddTable( LIBRARY_TABLE* aTable, const wxString& aTitle, bool aClosable )
235{
237 wxString projectPath = m_project->GetProjectPath();
238
240
241 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
242
243 if( aTable->Path().StartsWith( projectPath ) )
244 {
245 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *aTable, adapter, m_pluginChoices,
247 true /* take ownership */ );
248 }
249 else
250 {
251 wxString* lastGlobalLibDir = nullptr;
252
253 if( PCBNEW_SETTINGS* cfg = GetAppSettings<PCBNEW_SETTINGS>( "pcbnew" ) )
254 {
255 if( cfg->m_LastFootprintLibDir.IsEmpty() )
256 cfg->m_LastFootprintLibDir = PATHS::GetDefaultUserFootprintsPath();
257
258 lastGlobalLibDir = &cfg->m_LastFootprintLibDir;
259 }
260
261 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *aTable, adapter, m_pluginChoices,
262 lastGlobalLibDir, wxEmptyString, m_supportedFpFiles ),
263 true /* take ownership */ );
264 }
265
266 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )->RecheckRows();
267
268 LIB_TABLE_NOTEBOOK_PANEL* notebookPanel =
269 static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( m_notebook->GetPageCount() - 1 ) );
270
271 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )
273 [notebookPanel]()
274 {
275 notebookPanel->MarkDirty();
276 } );
277
278 // add Cut, Copy, and Paste to wxGrids
279 grid->PushEventHandler( new FP_GRID_TRICKS( this, grid,
280 [this]( wxCommandEvent& event )
281 {
282 appendRowHandler( event );
283 } ) );
284
285 auto autoSizeCol =
286 [&]( int aCol )
287 {
288 int prevWidth = grid->GetColSize( aCol );
289
290 grid->AutoSizeColumn( aCol, false );
291 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
292 };
293
294 // all but COL_OPTIONS, which is edited with Option Editor anyways.
295 autoSizeCol( COL_NICKNAME );
296 autoSizeCol( COL_TYPE );
297 autoSizeCol( COL_URI );
298 autoSizeCol( COL_DESCR );
299
300 if( grid->GetNumberRows() > 0 )
301 {
302 grid->SetGridCursor( 0, COL_NICKNAME );
303 grid->SelectRow( 0 );
304 }
305}
306
307
309 PANEL_FP_LIB_TABLE_BASE( aParent ),
310 m_project( aProject ),
311 m_parent( aParent ),
313{
314 m_lastProjectLibDir = m_project->GetProjectPath();
315
317
318 for( auto& [fileType, desc] : m_supportedFpFiles )
320
321 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
323 wxASSERT( table.has_value() );
324
325 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
326
327 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
329
330 if( projectTable.has_value() )
331 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
332
333 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
334
335 // add Cut, Copy, and Paste to wxGrids
336 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
337
339
340 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
341 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
342
343 // Configure button logos
349
350 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
351 // manually (for instance m_append_button)
352 Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
353 // their bitmaps
354 wxSize buttonSize = m_append_button->GetSize();
355
356 m_browseButton->SetWidthPadding( 4 );
357 m_browseButton->SetMinSize( buttonSize );
358
359 // Populate the browse library options
360 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
361
362 for( auto& [type, desc] : m_supportedFpFiles )
363 {
364 wxString entryStr = PCB_IO_MGR::ShowType( type );
365 wxString midPart;
366
367 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
368 {
369 entryStr << wxString::Format( wxS( " (%s)" ), JoinExtensions( desc.m_FileExtensions ) );
370 }
371 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
372 {
373 midPart = wxString::Format( _( "folder with %s files" ), JoinExtensions( desc.m_ExtensionsInDir ) );
374 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
375 }
376
377 browseMenu->Append( type, entryStr );
378 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this, type );
379 }
380
381 Layout();
382
383 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_FP_LIB_TABLE::onNotebookPageCloseRequest, this );
384 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CHANGING, &PANEL_FP_LIB_TABLE::onNotebookPageChangeRequest, this );
385 // This is the button only press for the browse button instead of the menu
387
388 m_parent->SetCanCloseCheck(
389 [this]()
390 {
391 for( int ii = 0; ii < (int) m_notebook->GetPageCount(); ++ii )
392 {
394 static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
395
396 if( panel->GetClosable() )
397 {
398 bool wasDirty = panel->TableModified();
399
400 if( !panel->GetCanClose() )
401 return false;
402
403 if( wasDirty && !panel->TableModified() )
404 {
405 m_parent->m_GlobalTableChanged = true;
406 m_parent->m_ProjectTableChanged = true;
407 }
408 }
409 }
410
411 return true;
412 } );
413}
414
415
417{
418 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
419
420 for( auto& [type, desc] : m_supportedFpFiles )
421 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this, type );
422
423 m_browseButton->Unbind( wxEVT_BUTTON, &PANEL_FP_LIB_TABLE::browseLibrariesHandler, this );
424
425 // Delete the GRID_TRICKS.
426 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
427 m_path_subs_grid->PopEventHandler( true );
428}
429
430
432{
433 return static_cast<FP_LIB_TABLE_GRID_DATA_MODEL*>( get_grid( aPage )->GetTable() );
434}
435
436
438{
439 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
440}
441
442
444{
445 // No visibility control for footprint libraries yet; this feature is primarily
446 // useful for database libraries and it's only implemented for schematic symbols
447 // at the moment.
448 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
449 {
450 WX_GRID* grid = get_grid( page );
451 grid->HideCol( COL_VISIBLE );
452 }
453
454 // for ALT+A handling, we want the initial focus to be on the first selected grid.
455 m_parent->SetInitialFocus( cur_grid() );
456
457 return true;
458}
459
460
462{
463 for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
464 {
465 IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
466
467 if( !pi )
468 continue;
469
470 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
471 m_supportedFpFiles.emplace( plugin.m_type, desc );
472 }
473
475 IO_BASE::IO_FILE_DESC( _( "Table (nested library table)" ), {} ) );
476}
477
478
480{
481 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
482 {
483 WX_GRID* grid = get_grid( page );
484
486 [&]( int aRow, int aCol )
487 {
488 // show the tabbed panel holding the grid we have flunked:
489 if( m_notebook->GetSelection() != page )
490 m_notebook->SetSelection( page );
491
492 grid->MakeCellVisible( aRow, 0 );
493 grid->SetGridCursor( aRow, aCol );
494 } ) )
495 {
496 return false;
497 }
498 }
499
500 return true;
501}
502
503
508
509
514
515
520
521
526
527
528// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
529void PANEL_FP_LIB_TABLE::onMigrateLibraries( wxCommandEvent& event )
530{
531 if( !cur_grid()->CommitPendingChanges() )
532 return;
533
534 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
535
536 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
537 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
538
539 wxArrayInt rowsToMigrate;
540 wxString kicadType = PCB_IO_MGR::ShowType( PCB_IO_MGR::KICAD_SEXP );
541 wxString msg;
542 DIALOG_HTML_REPORTER errorReporter( this );
543
544 for( int row : selectedRows )
545 {
546 if( cur_grid()->GetCellValue( row, COL_TYPE ) != kicadType )
547 rowsToMigrate.push_back( row );
548 }
549
550 if( rowsToMigrate.size() <= 0 )
551 {
552 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
553 return;
554 }
555 else
556 {
557 if( rowsToMigrate.size() == 1 )
558 {
559 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
560 cur_grid()->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
561 }
562 else
563 {
564 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
565 (int) rowsToMigrate.size() );
566 }
567
568 if( !IsOK( m_parent, msg ) )
569 return;
570 }
571
572 for( int row : rowsToMigrate )
573 {
574 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
575 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
576 wxFileName legacyLib( resolvedPath );
577
578 if( !legacyLib.Exists() )
579 {
580 msg.Printf( _( "Library '%s' not found." ), relPath );
581 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
582 continue;
583 }
584
585 wxFileName newLib( resolvedPath );
586 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadFootprintLibPathExtension );
587 newLib.SetName( "" );
588 newLib.ClearExt();
589
590 if( newLib.DirExists() )
591 {
592 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing footprints?" ),
593 newLib.GetFullPath() );
594
595 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO|wxCANCEL|wxICON_QUESTION, m_parent ) )
596 {
597 case wxYES: break;
598 case wxNO: continue;
599 case wxCANCEL: return;
600 }
601 }
602
603 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
604 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
605
606 if( PCB_IO_MGR::ConvertLibrary( props, legacyLib.GetFullPath(), newLib.GetFullPath(),
607 errorReporter.m_Reporter ) )
608 {
609 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
610
611 cur_grid()->SetCellValue( row, COL_URI, relPath );
612 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
613 }
614 else
615 {
616 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save footprint library file '%s'." ),
617 newLib.GetFullPath() ) );
618 }
619 }
620
621 if( errorReporter.m_Reporter->HasMessage() )
622 {
623 errorReporter.m_Reporter->Flush(); // Build HTML messages
624 errorReporter.ShowModal();
625 }
626}
627
628
630{
631 if( !cur_grid()->CommitPendingChanges() )
632 return;
633
635
636 // We are bound both to the menu and button with this one handler
637 // So we must set the file type based on it
638 if( event.GetEventType() == wxEVT_BUTTON )
639 {
640 // Let's default to adding a kicad footprint file for just the footprint
642 }
643 else
644 {
645 fileType = static_cast<PCB_IO_MGR::PCB_FILE_T>( event.GetId() );
646 }
647
649 return;
650
651 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
652 const IO_BASE::IO_FILE_DESC& fileDesc = m_supportedFpFiles.at( fileType );
654
655 wxString title;
656 wxString dummy;
657 wxString* lastDir;
658
660 title = _( "Select Library Table" );
661 else
662 title = wxString::Format( _( "Select %s Library" ), PCB_IO_MGR::ShowType( fileType ) );
663
664 if( m_notebook->GetSelection() == 0 )
665 lastDir = cfg ? &cfg->m_LastFootprintLibDir : &dummy;
666 else
667 lastDir = &m_lastProjectLibDir;
668
669 wxArrayString files;
670
671 if( fileDesc.m_IsFile )
672 {
673 wxFileDialog dlg( m_parent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
674 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
675
677
678 if( dlg.ShowModal() == wxID_CANCEL )
679 return;
680
681 dlg.GetPaths( files );
682 *lastDir = dlg.GetDirectory();
683 }
684 else
685 {
686 wxDirDialog dlg( m_parent, title, *lastDir, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
687
688 if( dlg.ShowModal() == wxID_CANCEL )
689 return;
690
691 dlg.GetPaths( files );
692
693 if( !files.IsEmpty() )
694 {
695 wxFileName first( files.front() );
696 *lastDir = first.GetPath();
697 }
698 }
699
700 // Drop the last directory if the path is a .pretty folder
702 cfg->m_LastFootprintLibDir = cfg->m_LastFootprintLibDir.BeforeLast( wxFileName::GetPathSeparator() );
703
704
705 bool addDuplicates = false;
706 bool applyToAll = false;
707 wxString warning = _( "Warning: Duplicate Nicknames" );
708 wxString msg = _( "An item nicknamed '%s' already exists." );
709 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
710
711 for( const wxString& filePath : files )
712 {
713 wxFileName fn( filePath );
714 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
715 bool doAdd = true;
716
719 {
720 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
721 }
722
723 if( cur_model()->ContainsNickname( nickname ) )
724 {
725 if( !applyToAll )
726 {
727 // The cancel button adds the library to the table anyway
728 addDuplicates = OKOrCancelDialog( m_parent, warning, wxString::Format( msg, nickname ), detailedMsg,
729 _( "Skip" ), _( "Add Anyway" ), &applyToAll ) == wxID_CANCEL;
730 }
731
732 doAdd = addDuplicates;
733 }
734
735 if( doAdd && cur_grid()->AppendRows( 1 ) )
736 {
737 int last_row = cur_grid()->GetNumberRows() - 1;
738
739 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
740 cur_grid()->SetCellValue( last_row, COL_TYPE, PCB_IO_MGR::ShowType( fileType ) );
741
742 // try to use path normalized to an environmental variable or project path
743 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
744
745 // Do not use the project path in the global library table. This will almost
746 // assuredly be wrong for a different project.
747 if( m_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
748 path = fn.GetFullPath();
749
750 cur_grid()->SetCellValue( last_row, COL_URI, path );
751 }
752 }
753
754 if( !files.IsEmpty() )
755 {
756 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
757 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
758 }
759}
760
761
762void PANEL_FP_LIB_TABLE::onNotebookPageCloseRequest( wxAuiNotebookEvent& aEvent )
763{
764 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
765 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
766
767 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
768 {
769 if( panel->GetClosable() )
770 {
771 if( !panel->GetCanClose() )
772 aEvent.Veto();
773 }
774 else
775 {
776 aEvent.Veto();
777 }
778 }
779}
780
781
783{
784 // Account for scroll bars
785 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
786
787 m_path_subs_grid->AutoSizeColumn( 0 );
788 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
789 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
790}
791
792
793void PANEL_FP_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
794{
795 adjustPathSubsGridColumns( event.GetSize().GetX() );
796
797 event.Skip();
798}
799
800
801void PANEL_FP_LIB_TABLE::onReset( wxCommandEvent& event )
802{
803 if( !cur_grid()->CommitPendingChanges() )
804 return;
805
806 WX_GRID* grid = get_grid( 0 );
807
808 // No need to prompt to preserve an empty table
809 if( grid->GetNumberRows() > 0 && !IsOK( this, wxString::Format( _( "This action will reset your global library "
810 "table on disk and cannot be undone." ) ) ) )
811 {
812 return;
813 }
814
815 wxString* lastGlobalLibDir = nullptr;
816
817 if( PCBNEW_SETTINGS* cfg = GetAppSettings<PCBNEW_SETTINGS>( "pcbnew" ) )
818 {
819 if( cfg->m_LastFootprintLibDir.IsEmpty() )
820 cfg->m_LastFootprintLibDir = PATHS::GetDefaultUserFootprintsPath();
821
822 lastGlobalLibDir = &cfg->m_LastFootprintLibDir;
823 }
824
826
827 // Go ahead and reload here because this action takes place even if the dialog is canceled
829
830 if( KIFACE *face = m_parent->Kiway().KiFACE( KIWAY::FACE_PCB ) )
831 face->PreloadLibraries( &m_parent->Kiway() );
832
833 grid->Freeze();
834
835 wxGridTableBase* table = grid->GetTable();
836 grid->DestroyTable( table );
837
838 std::optional<LIBRARY_TABLE*> newTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
840 wxASSERT( newTable );
841
843
844 grid->SetTable( new FP_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *newTable.value(), adapter, m_pluginChoices,
845 lastGlobalLibDir, wxEmptyString, m_supportedFpFiles ),
846 true /* take ownership */ );
847
848 m_parent->m_GlobalTableChanged = true;
849
850 grid->Thaw();
851
852 if( grid->GetNumberRows() > 0 )
853 {
854 grid->SetGridCursor( 0, COL_NICKNAME );
855 grid->SelectRow( 0 );
856 }
857}
858
859
860void PANEL_FP_LIB_TABLE::onNotebookPageChangeRequest( wxAuiNotebookEvent& aEvent )
861{
863 aEvent.Veto();
864 else
865 aEvent.Skip();
866}
867
868
869void PANEL_FP_LIB_TABLE::onPageChange( wxAuiNotebookEvent& event )
870{
871 m_resetGlobal->Enable( m_notebook->GetSelection() == 0 );
872}
873
874
876{
877 if( !cur_grid()->CommitPendingChanges() )
878 return false;
879
880 if( !verifyTables() )
881 return false;
882
883 std::optional<LIBRARY_TABLE*> optTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::FOOTPRINT,
885 wxCHECK( optTable, false );
886 LIBRARY_TABLE* globalTable = *optTable;
887
888 if( get_model( 0 )->Table() != *globalTable )
889 {
890 m_parent->m_GlobalTableChanged = true;
891 *globalTable = get_model( 0 )->Table();
892
893 globalTable->Save().map_error(
894 []( const LIBRARY_ERROR& aError )
895 {
896 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
897 _( "File Save Error" ), wxOK | wxICON_ERROR );
898 } );
899 }
900
902
903 if( optTable.has_value() && get_model( 1 )->Table().Path() == optTable.value()->Path() )
904 {
905 LIBRARY_TABLE* projectTable = *optTable;
906
907 if( get_model( 1 )->Table() != *projectTable )
908 {
909 m_parent->m_ProjectTableChanged = true;
910 *projectTable = get_model( 1 )->Table();
911
912 projectTable->Save().map_error(
913 []( const LIBRARY_ERROR& aError )
914 {
915 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
916 _( "File Save Error" ), wxOK | wxICON_ERROR );
917 } );
918 }
919 }
920
922 return true;
923}
924
925
929{
930 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
931 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
932
933 std::set< wxString > unique;
934
935 // clear the table
936 m_path_subs_grid->ClearRows();
937
938 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
939 {
941
942 for( int row = 0; row < model->GetNumberRows(); ++row )
943 {
944 wxString uri = model->GetValue( row, COL_URI );
945
946 while( re.Matches( uri ) )
947 {
948 wxString envvar = re.GetMatch( uri, 2 );
949
950 // if not ${...} form then must be $(...)
951 if( envvar.IsEmpty() )
952 envvar = re.GetMatch( uri, 4 );
953
954 // ignore duplicates
955 unique.insert( envvar );
956
957 // delete the last match and search again
958 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
959 }
960 }
961 }
962
963 // Make sure this special environment variable shows up even if it was not used yet. It is
964 // automatically set by KiCad to the directory holding the current project.
965 unique.insert( PROJECT_VAR_NAME );
966 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "FOOTPRINT_DIR" ) ) );
967
968 // This special environment variable is used to locate 3d shapes
969 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
970
971 for( const wxString& evName : unique )
972 {
973 int row = m_path_subs_grid->GetNumberRows();
974 m_path_subs_grid->AppendRows( 1 );
975
976 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
977 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
978
979 wxString evValue;
980 wxGetEnv( evName, &evValue );
981 m_path_subs_grid->SetCellValue( row, 1, evValue );
982 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
983 }
984
985 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
986}
987
988
989//-----</event handlers>---------------------------------
990
991
992
993void InvokePcbLibTableEditor( KIWAY* aKiway, wxWindow* aCaller )
994{
995 DIALOG_EDIT_LIBRARY_TABLES dlg( aCaller, _( "Footprint Libraries" ) );
996 dlg.SetKiway( &dlg, aKiway );
997
998 dlg.InstallPanel( new PANEL_FP_LIB_TABLE( &dlg, &aKiway->Prj() ) );
999
1000 if( dlg.ShowModal() == wxID_CANCEL )
1001 return;
1002
1003 if( dlg.m_GlobalTableChanged )
1005
1006 if( dlg.m_ProjectTableChanged )
1007 {
1008 // Trigger a reload of the table and cancel an in-progress background load
1010 }
1011
1012 // Trigger a reload in case any libraries have been added or removed
1013 if( KIFACE *face = aKiway->KiFACE( KIWAY::FACE_PCB ) )
1014 face->PreloadLibraries( aKiway );
1015
1016 std::string payload = "";
1019 aKiway->ExpressMail( FRAME_CVPCB, MAIL_RELOAD_LIB, payload );
1020}
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:110
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:68
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:61
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:75
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:315
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:500
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:211
@ FACE_PCB
pcbnew DSO
Definition kiway.h:323
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:205
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...
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:192
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)
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
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:56
@ KICAD_SEXP
S-expression Pcbnew file format.
Definition pcb_io_mgr.h:58
@ PCB_FILE_UNKNOWN
0 is not a legal menu id on Mac
Definition pcb_io_mgr.h:57
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:787
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:132
static FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(PROJECT *aProject)
Container for project specific data.
Definition project.h:66
wxString wx_str() const
Definition utf8.cpp:45
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:708
wxString JoinExtensions(const std::vector< std::string > &aExts)
Join a list of file extensions for use in a file dialog.
Definition common.cpp:798
The common library.
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:169
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:278
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:221
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:45
@ FRAME_FOOTPRINT_EDITOR
Definition frame_type.h:43
@ FRAME_CVPCB
Definition frame_type.h:52
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:655
This file contains miscellaneous commonly used macros and functions.
@ MAIL_RELOAD_LIB
Definition mail_type.h:57
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:77
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:435
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:41
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:156
wxString message
std::string path
KIBIS_MODEL * model
std::vector< std::vector< std::string > > table
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.