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