KiCad PCB EDA Suite
Loading...
Searching...
No Matches
panel_sym_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) 2017 Wayne Stambaugh <[email protected]>
5 * Copyright (C) 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 modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <set>
23#include <wx/regex.h>
24
25#include <build_version.h>
26#include <common.h> // For ExpandEnvVarSubstitutions
28#include <project.h>
29#include <panel_sym_lib_table.h>
30#include <lib_id.h>
34#include <widgets/wx_grid.h>
38#include <confirm.h>
39#include <bitmaps.h>
42#include <env_paths.h>
43#include <functional>
44#include <eeschema_id.h>
45#include <env_vars.h>
46#include <sch_io/sch_io.h>
47#include <symbol_edit_frame.h>
48#include <sch_edit_frame.h>
49#include <kiway.h>
50#include <paths.h>
51#include <kiplatform/ui.h>
52#include <pgm_base.h>
54#include <wx/dir.h>
55#include <wx/dirdlg.h>
56#include <wx/filedlg.h>
57#include <wx/msgdlg.h>
58#include <project_sch.h>
62
67{
68 wxString m_Description;
69 wxString m_FileFilter;
70
73 bool m_IsFile;
74 SCH_IO_MGR::SCH_FILE_T m_Plugin;
75};
76
77
82static constexpr int FIRST_MENU_ID = 1000;
83// This must not collide with any SCH_FILE_T enum values so we offset it below.
85
86
88{
89public:
90 SYMBOL_LIB_TABLE_GRID_DATA_MODEL( DIALOG_SHIM* aParent, WX_GRID* aGrid, const LIBRARY_TABLE& aTableToEdit,
91 SYMBOL_LIBRARY_ADAPTER* aAdapter, const wxArrayString& aPluginChoices,
92 wxString* aMRUDirectory, const wxString& aProjectPath ) :
93 LIB_TABLE_GRID_DATA_MODEL( aParent, aGrid, aTableToEdit, aAdapter, aPluginChoices, aMRUDirectory,
94 aProjectPath )
95 {
96 }
97
98 void SetValue( int aRow, int aCol, const wxString &aValue ) override
99 {
100 wxCHECK( aRow < (int) size(), /* void */ );
101
102 LIB_TABLE_GRID_DATA_MODEL::SetValue( aRow, aCol, aValue );
103
104 // If setting a filepath, attempt to auto-detect the format
105 if( aCol == COL_URI )
106 {
107 LIBRARY_TABLE_ROW& row = at( static_cast<size_t>( aRow ) );
108 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
109 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::GuessPluginTypeFromLibPath( uri );
110
111 if( pluginType != SCH_IO_MGR::SCH_FILE_UNKNOWN )
112 SetValue( aRow, COL_TYPE, SCH_IO_MGR::ShowType( pluginType ) );
113 }
114 }
115
116protected:
117 wxString getFileTypes( WX_GRID* aGrid, int aRow ) override
118 {
119 LIB_TABLE_GRID_DATA_MODEL* table = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
120 LIBRARY_TABLE_ROW& tableRow = table->At( aRow );
121
122 if( tableRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
123 {
124 wxString filter = _( "Symbol Library Tables" );
125#ifndef __WXOSX__
126 filter << wxString::Format( _( " (%s)|%s" ), FILEEXT::SymbolLibraryTableFileName,
128#else
129 filter << wxString::Format( _( " (%s)|%s" ), wxFileSelectorDefaultWildcardStr,
130 wxFileSelectorDefaultWildcardStr );
131#endif
132 return filter;
133 }
134
135 SCH_IO_MGR::SCH_FILE_T pi_type = SCH_IO_MGR::EnumFromStr( tableRow.Type() );
136 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pi_type ) );
137
138 if( pi )
139 {
140 const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc();
141
142 if( desc.m_IsFile )
143 return desc.FileFilter();
144 }
145
146 return wxEmptyString;
147 }
148};
149
150
152{
153public:
155 std::function<void( wxCommandEvent& )> aAddHandler ) :
156 LIB_TABLE_GRID_TRICKS( aGrid, aAddHandler ),
157 m_panel( aPanel )
158 {
160 }
161
162protected:
163 void optionsEditor( int aRow ) override
164 {
165 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
166
167 if( tbl->GetNumberRows() > aRow )
168 {
169 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
170 const wxString& options = row.Options();
171 wxString result = options;
172 std::map<std::string, UTF8> choices;
173
174 SCH_IO_MGR::SCH_FILE_T pi_type = SCH_IO_MGR::EnumFromStr( row.Type() );
175 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pi_type ) );
176 pi->GetLibraryOptions( &choices );
177
178 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
179 dlg.ShowModal();
180
181 if( options != result )
182 {
183 row.SetOptions( result );
184 m_grid->Refresh();
185 }
186 }
187 }
188
189 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
190 {
191 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
192 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL );
193
194 m_panel->OpenTable( child, aRow.Nickname() );
195 }
196
197 wxString getTablePreamble() override
198 {
199 return wxT( "(sym_lib_table" );
200 }
201
203 {
204 return true;
205 }
206
207protected:
209};
210
211
212void PANEL_SYM_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
213{
214 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
215 {
216 if( m_notebook->GetPageText( ii ) == aTitle )
217 {
218 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
219 // results in a re-entrant call where the second call is one page behind.
220 for( int attempts = 0; attempts < 3; ++attempts )
221 m_notebook->ChangeSelection( ii );
222
223 return;
224 }
225 }
226
227 m_nestedTables.push_back( aTable );
228 AddTable( aTable.get(), aTitle, true );
229
230 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
231 // results in a re-entrant call where the second call is one page behind.
232 for( int attempts = 0; attempts < 3; ++attempts )
233 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
234}
235
236
237void PANEL_SYM_LIB_TABLE::AddTable( LIBRARY_TABLE* table, const wxString& aTitle, bool aClosable )
238{
240 wxString projectPath = m_project->GetProjectPath();
241
243
244 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
245
246 if( table->Path().StartsWith( projectPath ) )
247 {
249 &m_lastProjectLibDir, projectPath ),
250 true /* take ownership */ );
251 }
252 else
253 {
254 wxString* lastGlobalLibDir = nullptr;
255
257 {
258 if( cfg->m_lastSymbolLibDir.IsEmpty() )
259 cfg->m_lastSymbolLibDir = PATHS::GetDefaultUserSymbolsPath();
260
261 lastGlobalLibDir = &cfg->m_lastSymbolLibDir;
262 }
263
265 lastGlobalLibDir, wxEmptyString ),
266 true /* take ownership */ );
267 }
268
269 // add Cut, Copy, and Paste to wxGrids
270 grid->PushEventHandler( new SYMBOL_GRID_TRICKS( this, grid,
271 [this]( wxCommandEvent& event )
272 {
273 appendRowHandler( event );
274 } ) );
275
276 auto autoSizeCol =
277 [&]( int aCol )
278 {
279 int prevWidth = grid->GetColSize( aCol );
280
281 grid->AutoSizeColumn( aCol, false );
282 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
283 };
284
285 // all but COL_OPTIONS, which is edited with Option Editor anyways.
286 autoSizeCol( COL_NICKNAME );
287 autoSizeCol( COL_TYPE );
288 autoSizeCol( COL_URI );
289 autoSizeCol( COL_DESCR );
290
291 if( grid->GetNumberRows() > 0 )
292 {
293 grid->SetGridCursor( 0, COL_NICKNAME );
294 grid->SelectRow( 0 );
295 }
296}
297
298
300 PANEL_SYM_LIB_TABLE_BASE( aParent ),
301 m_project( aProject ),
302 m_parent( aParent )
303{
304 m_lastProjectLibDir = m_project->GetProjectPath();
305
307
308 for( const SCH_IO_MGR::SCH_FILE_T& type : SCH_IO_MGR::SCH_FILE_T_vector )
309 {
310 if( type == SCH_IO_MGR::SCH_NESTED_TABLE )
311 {
313 continue;
314 }
315
316 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( type ) );
317
318 if( pi )
320 }
321
322 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::SYMBOL,
324 wxASSERT( table.has_value() );
325
326 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
327
328 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::SYMBOL,
330
331 if( projectTable.has_value() )
332 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
333
334 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
335
336 // add Cut, Copy, and Paste to wxGrids
337 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
338
340
341 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
342 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
343
344 // Configure button logos
350
351 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
352 Layout();
353 wxSize buttonSize = m_append_button->GetSize();
354
355 m_browseButton->SetWidthPadding( 4 );
356 m_browseButton->SetMinSize( buttonSize );
357
358 // Populate the browse library options
359 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
360
361 auto joinExtensions =
362 []( const std::vector<std::string>& aExts ) -> wxString
363 {
364 wxString result;
365
366 for( const std::string& ext : aExts )
367 {
368 if( !result.IsEmpty() )
369 result << wxT( ", " );
370
371 result << wxT( "." ) << ext;
372 }
373
374 return result;
375 };
376
377 for( auto& [type, desc] : m_supportedSymFiles )
378 {
379 wxString entryStr = SCH_IO_MGR::ShowType( type );
380
381 if( !desc.m_FileExtensions.empty() )
382 entryStr << wxString::Format( wxS( " (%s)" ), joinExtensions( desc.m_FileExtensions ) );
383
384 browseMenu->Append( type + FIRST_MENU_ID, entryStr );
385 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_SYM_LIB_TABLE::browseLibrariesHandler, this,
386 type + FIRST_MENU_ID );
387
388 // Add folder-based entry right after KiCad file-based entry
389 if( type == SCH_IO_MGR::SCH_KICAD )
390 {
391 wxString folderEntry = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD );
392 folderEntry << wxString::Format( wxS( " (%s)" ), _( "folder with .kicad_sym files" ) );
393 browseMenu->Append( ID_PANEL_SYM_LIB_KICAD_FOLDER, folderEntry );
394 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_SYM_LIB_TABLE::browseLibrariesHandler, this,
396 }
397 }
398
399 Layout();
400
401 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_SYM_LIB_TABLE::onNotebookPageCloseRequest, this );
403}
404
405
407{
408 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
409
410 for( auto& [type, desc] : m_supportedSymFiles )
411 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_SYM_LIB_TABLE::browseLibrariesHandler, this, type );
412
413 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_SYM_LIB_TABLE::browseLibrariesHandler,
415 m_browseButton->Unbind( wxEVT_BUTTON, &PANEL_SYM_LIB_TABLE::browseLibrariesHandler, this );
416
417 // Delete the GRID_TRICKS.
418 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
419 m_path_subs_grid->PopEventHandler( true );
420}
421
422
424{
425 for( const SCH_IO_MGR::SCH_FILE_T& type : SCH_IO_MGR::SCH_FILE_T_vector )
426 {
427 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( type ) );
428
429 if( !pi )
430 continue;
431
432 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
433 {
434 if( !desc.m_FileExtensions.empty() )
435 m_supportedSymFiles.emplace( type, desc );
436 }
437 }
438
439 m_supportedSymFiles.emplace( SCH_IO_MGR::SCH_NESTED_TABLE,
440 IO_BASE::IO_FILE_DESC( _( "Table (nested library table)" ), {} ) );
441}
442
443
445{
446 return static_cast<SYMBOL_LIB_TABLE_GRID_DATA_MODEL*>( get_grid( aPage )->GetTable() );
447}
448
449
451{
452 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
453}
454
455
457{
458 // for ALT+A handling, we want the initial focus to be on the first selected grid.
459 m_parent->SetInitialFocus( cur_grid() );
460
461 return true;
462}
463
464
466{
467 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
468 {
469 WX_GRID* grid = get_grid( page );
470
472 [&]( int aRow, int aCol )
473 {
474 // show the tabbed panel holding the grid we have flunked:
475 if( m_notebook->GetSelection() != page )
476 m_notebook->SetSelection( page );
477
478 grid->MakeCellVisible( aRow, 0 );
479 grid->SetGridCursor( aRow, aCol );
480 } ) )
481 {
482 return false;
483 }
484 }
485
486 return true;
487}
488
489
491{
492 if( !cur_grid()->CommitPendingChanges() )
493 return;
494
495 SCH_IO_MGR::SCH_FILE_T fileType = SCH_IO_MGR::SCH_FILE_UNKNOWN;
496 bool selectingFolder = false;
497
498 // We are bound both to the menu and button with this one handler
499 if( event.GetEventType() == wxEVT_BUTTON )
500 {
501 // Default to KiCad file format when clicking the button directly
502 fileType = SCH_IO_MGR::SCH_KICAD;
503 }
504 else if( event.GetId() == ID_PANEL_SYM_LIB_KICAD_FOLDER )
505 {
506 // Special case for folder-based KiCad library
507 fileType = SCH_IO_MGR::SCH_KICAD;
508 selectingFolder = true;
509 }
510 else
511 {
512 fileType = static_cast<SCH_IO_MGR::SCH_FILE_T>( event.GetId() - FIRST_MENU_ID );
513 }
514
515 if( fileType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
516 return;
517
518 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
519
521 wxString dummy;
522 wxString* lastDir;
523
524 if( m_notebook->GetSelection() == 0 )
525 lastDir = cfg ? &cfg->m_lastSymbolLibDir : &dummy;
526 else
527 lastDir = &m_lastProjectLibDir;
528
529 wxString title = wxString::Format( _( "Select %s Library" ), SCH_IO_MGR::ShowType( fileType ) );
530 wxWindow* topLevelParent = wxGetTopLevelParent( this );
531 wxArrayString files;
532
533 if( selectingFolder )
534 {
535 wxDirDialog dlg( topLevelParent, title, *lastDir, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
536
537 if( dlg.ShowModal() == wxID_CANCEL )
538 return;
539
540 dlg.GetPaths( files );
541
542 if( !files.IsEmpty() )
543 {
544 wxFileName first( files.front() );
545 *lastDir = first.GetPath();
546 }
547 }
548 else
549 {
550 auto it = m_supportedSymFiles.find( fileType );
551
552 if( it == m_supportedSymFiles.end() )
553 return;
554
555 const IO_BASE::IO_FILE_DESC& fileDesc = it->second;
556
557 wxFileDialog dlg( topLevelParent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
558 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
559
561
562 if( dlg.ShowModal() == wxID_CANCEL )
563 return;
564
565 dlg.GetPaths( files );
566 *lastDir = dlg.GetDirectory();
567 }
568
569 bool addDuplicates = false;
570 bool applyToAll = false;
571 wxString warning = _( "Warning: Duplicate Nicknames" );
572 wxString msg = _( "An item nicknamed '%s' already exists." );
573 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
574
575 for( const wxString& filePath : files )
576 {
577 wxFileName fn( filePath );
578 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
579 bool doAdd = true;
580
581 if( cur_model()->ContainsNickname( nickname ) )
582 {
583 if( !applyToAll )
584 {
585 addDuplicates = OKOrCancelDialog( topLevelParent, warning,
586 wxString::Format( msg, nickname ), detailedMsg,
587 _( "Skip" ), _( "Add Anyway" ),
588 &applyToAll ) == wxID_CANCEL;
589 }
590
591 doAdd = addDuplicates;
592 }
593
594 if( doAdd && cur_grid()->AppendRows( 1 ) )
595 {
596 int last_row = cur_grid()->GetNumberRows() - 1;
597
598 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
599 cur_grid()->SetCellValue( last_row, COL_TYPE, SCH_IO_MGR::ShowType( fileType ) );
600
601 // try to use path normalized to an environmental variable or project path
602 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
603
604 // Do not use the project path in the global library table. This will almost
605 // assuredly be wrong for a different project.
606 if( m_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
607 path = fn.GetFullPath();
608
609 cur_grid()->SetCellValue( last_row, COL_URI, path );
610 }
611 }
612
613 if( !files.IsEmpty() )
614 {
615 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
616 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
617 }
618}
619
620
625
626
631
632
637
638
643
644
645void PANEL_SYM_LIB_TABLE::onReset( wxCommandEvent& event )
646{
647 if( !cur_grid()->CommitPendingChanges() )
648 return;
649
650 WX_GRID* grid = get_grid( 0 );
651
652 // No need to prompt to preserve an empty table
653 if( grid->GetNumberRows() > 0 && !IsOK( this, wxString::Format( _( "This action will reset your global library "
654 "table on disk and cannot be undone." ) ) ) )
655 {
656 return;
657 }
658
659 wxString* lastGlobalLibDir = nullptr;
660
662 {
663 if( cfg->m_lastSymbolLibDir.IsEmpty() )
664 cfg->m_lastSymbolLibDir = PATHS::GetDefaultUserSymbolsPath();
665
666 lastGlobalLibDir = &cfg->m_lastSymbolLibDir;
667 }
668
670
671 // Go ahead and reload here because this action takes place even if the dialog is canceled
673
674 if( KIFACE *schface = m_parent->Kiway().KiFACE( KIWAY::FACE_SCH ) )
675 schface->PreloadLibraries( &m_parent->Kiway() );
676
677 grid->Freeze();
678
679 wxGridTableBase* table = grid->GetTable();
680 grid->DestroyTable( table );
681
682 std::optional<LIBRARY_TABLE*> newTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::SYMBOL,
684 wxASSERT( newTable );
685
687
688 grid->SetTable( new SYMBOL_LIB_TABLE_GRID_DATA_MODEL( m_parent, grid, *newTable.value(), adapter, m_pluginChoices,
689 lastGlobalLibDir, wxEmptyString ),
690 true /* take ownership */ );
691
692 m_parent->m_GlobalTableChanged = true;
693
694 grid->Thaw();
695
696 if( grid->GetNumberRows() > 0 )
697 {
698 grid->SetGridCursor( 0, COL_NICKNAME );
699 grid->SelectRow( 0 );
700 }
701}
702
703
704void PANEL_SYM_LIB_TABLE::onPageChange( wxAuiNotebookEvent& event )
705{
706 m_resetGlobal->Enable( m_notebook->GetSelection() == 0 );
707}
708
709
710void PANEL_SYM_LIB_TABLE::onNotebookPageCloseRequest( wxAuiNotebookEvent& aEvent )
711{
712 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
713 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
714
715 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
716 {
717 if( panel->GetClosable() )
718 {
719 if( !panel->GetCanClose() )
720 aEvent.Veto();
721 }
722 else
723 {
724 aEvent.Veto();
725 }
726 }
727}
728
729
731{
732 if( !cur_grid()->CommitPendingChanges() )
733 return;
734
735 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
736
737 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
738 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
739
740 wxArrayInt legacyRows;
741 wxString databaseType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_DATABASE );
742 wxString kicadType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD );
743 wxString msg;
744
745 for( int row : selectedRows )
746 {
747 if( cur_grid()->GetCellValue( row, COL_TYPE ) != databaseType
748 && cur_grid()->GetCellValue( row, COL_TYPE ) != kicadType )
749 {
750 legacyRows.push_back( row );
751 }
752 }
753
754 if( legacyRows.size() <= 0 )
755 {
756 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
757 return;
758 }
759 else
760 {
761 if( legacyRows.size() == 1 )
762 {
763 msg.Printf( _( "Save '%s' as current KiCad format (*.kicad_sym) and replace legacy entry in table?" ),
764 cur_grid()->GetCellValue( legacyRows[0], COL_NICKNAME ) );
765 }
766 else
767 {
768 msg.Printf( _( "Save %d libraries as current KiCad format (*.kicad_sym) and replace legacy entries "
769 "in table?" ),
770 (int) legacyRows.size() );
771 }
772
773 if( !IsOK( m_parent, msg ) )
774 return;
775 }
776
777 for( int row : legacyRows )
778 {
779 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
780 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
781 wxFileName legacyLib( resolvedPath );
782
783 if( !legacyLib.Exists() )
784 {
785 DisplayErrorMessage( m_parent, wxString::Format( _( "Library '%s' not found." ), relPath ) );
786 continue;
787 }
788
789 wxFileName newLib( resolvedPath );
790 newLib.SetExt( "kicad_sym" );
791
792 if( newLib.Exists() )
793 {
794 msg.Printf( _( "File '%s' already exists. Do you want overwrite this file?" ), newLib.GetFullPath() );
795
796 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
797 {
798 case wxYES: break;
799 case wxNO: continue;
800 case wxCANCEL: return;
801 }
802 }
803
804 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
805 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
806
807 if( SCH_IO_MGR::ConvertLibrary( &props, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
808 {
809 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
810
811 cur_grid()->SetCellValue( row, COL_URI, relPath );
812 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
813 cur_grid()->SetCellValue( row, COL_OPTIONS, wxEmptyString );
814 }
815 else
816 {
817 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save symbol library file '%s'." ),
818 newLib.GetFullPath() ) );
819 }
820 }
821}
822
823
825{
826 if( !cur_grid()->CommitPendingChanges() )
827 return false;
828
829 if( !verifyTables() )
830 return false;
831
833 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::SYMBOL, LIBRARY_TABLE_SCOPE::GLOBAL );
834 wxCHECK( optTable, false );
835 LIBRARY_TABLE* globalTable = *optTable;
836
837 if( get_model( 0 )->Table() != *globalTable )
838 {
839 m_parent->m_GlobalTableChanged = true;
840 *globalTable = get_model( 0 )->Table();
841
842 globalTable->Save().map_error(
843 []( const LIBRARY_ERROR& aError )
844 {
845 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
846 _( "File Save Error" ), wxOK | wxICON_ERROR );
847 } );
848 }
849
851
852 if( optTable.has_value() && get_model( 1 )->Table().Path() == optTable.value()->Path() )
853 {
854 LIBRARY_TABLE* projectTable = *optTable;
855
856 if( get_model( 1 )->Table() != *projectTable )
857 {
858 m_parent->m_ProjectTableChanged = true;
859 *projectTable = get_model( 1 )->Table();
860
861 projectTable->Save().map_error(
862 []( const LIBRARY_ERROR& aError )
863 {
864 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
865 _( "File Save Error" ), wxOK | wxICON_ERROR );
866 } );
867 }
868 }
869
870 for( int ii = 0; ii < (int) m_notebook->GetPageCount(); ++ii )
871 {
872 LIB_TABLE_NOTEBOOK_PANEL* panel = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
873
874 if( panel->GetClosable() && panel->TableModified() )
875 {
876 panel->SaveTable();
877 m_parent->m_GlobalTableChanged = true;
878 m_parent->m_ProjectTableChanged = true;
879 }
880 }
881
882 return true;
883}
884
885
887{
888 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
889 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
890
891 std::set< wxString > unique;
892
893 // clear the table
894 m_path_subs_grid->ClearRows();
895
896 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
897 {
899
900 for( int row = 0; row < model->GetNumberRows(); ++row )
901 {
902 wxString uri = model->GetValue( row, COL_URI );
903
904 while( re.Matches( uri ) )
905 {
906 wxString envvar = re.GetMatch( uri, 2 );
907
908 // if not ${...} form then must be $(...)
909 if( envvar.IsEmpty() )
910 envvar = re.GetMatch( uri, 4 );
911
912 // ignore duplicates
913 unique.insert( envvar );
914
915 // delete the last match and search again
916 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
917 }
918 }
919 }
920
921 // Make sure this special environment variable shows up even if it was
922 // not used yet. It is automatically set by KiCad to the directory holding
923 // the current project.
924 unique.insert( PROJECT_VAR_NAME );
925 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "SYMBOL_DIR" ) ) );
926
927 for( const wxString& evName : unique )
928 {
929 int row = m_path_subs_grid->GetNumberRows();
930 m_path_subs_grid->AppendRows( 1 );
931
932 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
933 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
934
935 wxString evValue;
936 wxGetEnv( evName, &evValue );
937 m_path_subs_grid->SetCellValue( row, 1, evValue );
938 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
939 }
940
941 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
942}
943
944
946{
947 // Account for scroll bars
948 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
949
950 m_path_subs_grid->AutoSizeColumn( 0 );
951 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
952 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
953}
954
955
956void PANEL_SYM_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
957{
958 adjustPathSubsGridColumns( event.GetSize().GetX() );
959
960 event.Skip();
961}
962
963
964void InvokeSchEditSymbolLibTable( KIWAY* aKiway, wxWindow *aParent )
965{
966 auto symbolEditor = static_cast<SYMBOL_EDIT_FRAME*>( aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false ) );
967 wxString msg;
968
969 if( symbolEditor )
970 {
971 // This prevents an ugly crash on OSX (https://bugs.launchpad.net/kicad/+bug/1765286)
972 symbolEditor->FreezeLibraryTree();
973
974 if( symbolEditor->HasLibModifications() )
975 {
976 msg = _( "Modifications have been made to one or more symbol libraries.\n"
977 "Changes must be saved or discarded before the symbol library table can be modified." );
978
979 switch( UnsavedChangesDialog( aParent, msg ) )
980 {
981 case wxID_YES: symbolEditor->SaveAll(); break;
982 case wxID_NO: symbolEditor->RevertAll(); break;
983 default:
984 case wxID_CANCEL: symbolEditor->ThawLibraryTree(); return;
985 }
986 }
987 }
988
989 DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Symbol Libraries" ) );
990 dlg.SetKiway( &dlg, aKiway );
991
992 dlg.InstallPanel( new PANEL_SYM_LIB_TABLE( &dlg, &aKiway->Prj() ) );
993
994 if( dlg.ShowModal() == wxID_CANCEL )
995 {
996 if( symbolEditor )
997 symbolEditor->ThawLibraryTree();
998
999 return;
1000 }
1001
1002 if( dlg.m_GlobalTableChanged )
1004
1005 if( dlg.m_ProjectTableChanged )
1006 {
1007 // Trigger a reload of the table and cancel an in-progress background load
1009 }
1010
1011 // Trigger a reload in case any libraries have been added or removed
1012 if( KIFACE *schface = aKiway->KiFACE( KIWAY::FACE_SCH ) )
1013 schface->PreloadLibraries( aKiway );
1014
1015 if( symbolEditor )
1016 symbolEditor->ThawLibraryTree();
1017}
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:110
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
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 KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:403
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:206
@ FACE_SCH
eeschema DSO
Definition kiway.h:301
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)
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)
PANEL_SYM_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)
STD_BITMAP_BUTTON * m_move_down_button
Dialog to show and edit symbol library tables.
void moveUpHandler(wxCommandEvent &event) override
SYMBOL_LIB_TABLE_GRID_DATA_MODEL * get_model(int aPage) const
void onReset(wxCommandEvent &event) override
void deleteRowHandler(wxCommandEvent &event) override
WX_GRID * get_grid(int aPage) const
void onNotebookPageCloseRequest(wxAuiNotebookEvent &aEvent)
void onPageChange(wxAuiNotebookEvent &event) override
void browseLibrariesHandler(wxCommandEvent &event) override
void AddTable(LIBRARY_TABLE *table, const wxString &aTitle, bool aClosable)
bool verifyTables()
Trim important fields, removes blank row entries, and checks for duplicates.
void adjustPathSubsGridColumns(int aWidth)
void OpenTable(const std::shared_ptr< LIBRARY_TABLE > &table, const wxString &aTitle)
void onSizeGrid(wxSizeEvent &event) override
std::vector< std::shared_ptr< LIBRARY_TABLE > > m_nestedTables
void onConvertLegacyLibraries(wxCommandEvent &event) override
std::map< SCH_IO_MGR::SCH_FILE_T, IO_BASE::IO_FILE_DESC > m_supportedSymFiles
bool TransferDataToWindow() override
wxArrayString m_pluginChoices
void moveDownHandler(wxCommandEvent &event) override
PANEL_SYM_LIB_TABLE(DIALOG_EDIT_LIBRARY_TABLES *aParent, PROJECT *m_project)
SYMBOL_LIB_TABLE_GRID_DATA_MODEL * cur_model() const
void populateEnvironReadOnlyTable()
Populate the readonly environment variable table with names and values by examining all the full_uri ...
WX_GRID * cur_grid() const
DIALOG_EDIT_LIBRARY_TABLES * m_parent
bool TransferDataFromWindow() override
void appendRowHandler(wxCommandEvent &event) override
static wxString GetDefaultUserSymbolsPath()
Gets the default path we point users to create projects.
Definition paths.cpp:82
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition pgm_base.cpp:781
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:134
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Container for project specific data.
Definition project.h:65
static bool ConvertLibrary(std::map< std::string, UTF8 > *aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilepath)
Convert a schematic symbol library to the latest KiCad format.
static SCH_FILE_T EnumFromStr(const wxString &aFileType)
Return the #SCH_FILE_T from the corresponding plugin type name: "kicad", "legacy",...
static const wxString ShowType(SCH_FILE_T aFileType)
Return a brief name for a plugin, given aFileType enum.
static SCH_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a symbol library using the file extension of aLibPath.
The symbol library editor main window.
SYMBOL_GRID_TRICKS(PANEL_SYM_LIB_TABLE *aPanel, WX_GRID *aGrid, std::function< void(wxCommandEvent &)> aAddHandler)
bool supportsVisibilityColumn() override
wxString getTablePreamble() override
PANEL_SYM_LIB_TABLE * m_panel
void openTable(const LIBRARY_TABLE_ROW &aRow) override
void optionsEditor(int aRow) override
An interface to the global shared library manager that is schematic-specific and linked to one projec...
SYMBOL_LIB_TABLE_GRID_DATA_MODEL(DIALOG_SHIM *aParent, WX_GRID *aGrid, const LIBRARY_TABLE &aTableToEdit, SYMBOL_LIBRARY_ADAPTER *aAdapter, const wxArrayString &aPluginChoices, wxString *aMRUDirectory, const wxString &aProjectPath)
void SetValue(int aRow, int aCol, const wxString &aValue) override
wxString getFileTypes(WX_GRID *aGrid, int aRow) override
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:558
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
int UnsavedChangesDialog(wxWindow *parent, const wxString &aMessage, bool *aApplyToAll)
A specialized version of HandleUnsavedChanges which handles an apply-to-all checkbox.
Definition confirm.cpp:64
This file is part of the common library.
#define _(s)
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_SCH_SYMBOL_EDITOR
Definition frame_type.h:35
static const std::string SymbolLibraryTableFileName
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
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:717
static constexpr int FIRST_MENU_ID
Special menu ID for folder-based KiCad symbol library format.
static constexpr int ID_PANEL_SYM_LIB_KICAD_FOLDER
void InvokeSchEditSymbolLibTable(KIWAY *aKiway, wxWindow *aParent)
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
Container that describes file type info for the add a library options.
bool m_IsFile
Whether the library is a folder or a file.
wxString m_Description
Description shown in the file picker dialog.
wxString m_FileFilter
Filter used for file pickers if m_IsFile is true.
DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T m_Plugin
wxString m_FolderSearchExtension
In case of folders it stands for extensions of files stored inside.
std::string path
KIBIS_MODEL * model
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.