KiCad PCB EDA Suite
Loading...
Searching...
No Matches
panel_design_block_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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24
25#include <set>
26#include <wx/dir.h>
27#include <wx/regex.h>
28#include <wx/dirdlg.h>
29#include <wx/filedlg.h>
30#include <wx/msgdlg.h>
31
32#include <common.h>
33#include <project.h>
34#include <env_vars.h>
35#include <lib_id.h>
36#include <bitmaps.h>
38#include <widgets/wx_grid.h>
41#include <confirm.h>
44#include <pgm_base.h>
45#include <env_paths.h>
50#include <kiway.h>
51#include <kiway_express.h>
54#include <paths.h>
55#include <macros.h>
59
72
73
78class LIBRARY_TRAVERSER : public wxDirTraverser
79{
80public:
81 LIBRARY_TRAVERSER( std::vector<std::string> aSearchExtensions, wxString aInitialDir ) :
82 m_searchExtensions( aSearchExtensions ), m_currentDir( aInitialDir )
83 {
84 }
85
86 virtual wxDirTraverseResult OnFile( const wxString& aFileName ) override
87 {
88 wxFileName file( aFileName );
89
90 for( const std::string& ext : m_searchExtensions )
91 {
92 if( file.GetExt().IsSameAs( ext, false ) )
93 m_foundDirs.insert( { m_currentDir, 1 } );
94 }
95
96 return wxDIR_CONTINUE;
97 }
98
99 virtual wxDirTraverseResult OnOpenError( const wxString& aOpenErrorName ) override
100 {
101 m_failedDirs.insert( { aOpenErrorName, 1 } );
102 return wxDIR_IGNORE;
103 }
104
105 bool HasDirectoryOpenFailures() { return m_failedDirs.size() > 0; }
106
107 virtual wxDirTraverseResult OnDir( const wxString& aDirName ) override
108 {
109 m_currentDir = aDirName;
110 return wxDIR_CONTINUE;
111 }
112
113 void GetPaths( wxArrayString& aPathArray )
114 {
115 for( std::pair<const wxString, int>& foundDirsPair : m_foundDirs )
116 aPathArray.Add( foundDirsPair.first );
117 }
118
119 void GetFailedPaths( wxArrayString& aPathArray )
120 {
121 for( std::pair<const wxString, int>& failedDirsPair : m_failedDirs )
122 aPathArray.Add( failedDirsPair.first );
123 }
124
125private:
126 std::vector<std::string> m_searchExtensions;
127 wxString m_currentDir;
128 std::unordered_map<wxString, int> m_foundDirs;
129 std::unordered_map<wxString, int> m_failedDirs;
130};
131
132
137{
138public:
140 LIBRARY_MANAGER_ADAPTER* aAdapter, const wxArrayString& aPluginChoices,
141 wxString* aMRUDirectory, const wxString& aProjectPath,
143 IO_BASE::IO_FILE_DESC>& aSupportedFiles ) :
144 LIB_TABLE_GRID_DATA_MODEL( aParent, aGrid, aTableToEdit, aAdapter, aPluginChoices, aMRUDirectory,
145 aProjectPath ),
146 m_supportedDesignBlockFiles( aSupportedFiles )
147 {
148 }
149
150 void SetValue( int aRow, int aCol, const wxString& aValue ) override
151 {
152 wxCHECK( aRow < (int) size(), /* void */ );
153
154 LIB_TABLE_GRID_DATA_MODEL::SetValue( aRow, aCol, aValue );
155
156 // If setting a filepath, attempt to auto-detect the format
157 if( aCol == COL_URI )
158 {
159 LIBRARY_TABLE_ROW& row = at( static_cast<size_t>( aRow ) );
160 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
161
164
165 if( pluginType != DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
166 SetValue( aRow, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( pluginType ) );
167 }
168 }
169
170protected:
171 wxString getFileTypes( WX_GRID* aGrid, int aRow ) override
172 {
173 auto* table = static_cast<DESIGN_BLOCK_LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
174 LIBRARY_TABLE_ROW& tableRow = table->at( aRow );
175
176 if( tableRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
177 {
178 wxString filter = _( "Design Block Library Tables" );
179#ifndef __WXOSX__
180 filter << wxString::Format( _( " (%s)|%s" ), FILEEXT::DesignBlockLibraryTableFileName,
182#else
183 filter << wxString::Format( _( " (%s)|%s" ), wxFileSelectorDefaultWildcardStr,
184 wxFileSelectorDefaultWildcardStr );
185#endif
186 return filter;
187 }
188
189 if( tableRow.Type().IsEmpty() )
190 return wxEmptyString;
191
194 return wxEmptyString;
195
197
198 if( pluginDesc.m_IsFile )
199 return pluginDesc.FileFilter();
200
201 return wxEmptyString;
202 }
203
204private:
205 const std::map<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T, IO_BASE::IO_FILE_DESC>& m_supportedDesignBlockFiles;
206};
207
208
210{
211public:
218
219protected:
220 void optionsEditor( int aRow ) override
221 {
222 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
223
224 if( tbl->GetNumberRows() > aRow )
225 {
226 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
227 const wxString& options = row.Options();
228 wxString result = options;
229 std::map<std::string, UTF8> choices;
230
233 pi->GetLibraryOptions( &choices );
234
235 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
236 dlg.ShowModal();
237
238 if( options != result )
239 {
240 row.SetOptions( result );
241 m_grid->Refresh();
242 }
243 }
244 }
245
246 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
247 {
248 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
249 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL );
250
251 m_panel->OpenTable( child, aRow.Nickname() );
252 }
253
254 wxString getTablePreamble() override
255 {
256 return wxT( "(design_block_lib_table" );
257 }
258
259protected:
261};
262
263
264void PANEL_DESIGN_BLOCK_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
265{
266 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
267 {
268 if( m_notebook->GetPageText( ii ) == aTitle )
269 {
270 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
271 // results in a re-entrant call where the second call is one page behind.
272 for( int attempts = 0; attempts < 3; ++attempts )
273 m_notebook->ChangeSelection( ii );
274
275 return;
276 }
277 }
278
279 m_nestedTables.push_back( aTable );
280 AddTable( aTable.get(), aTitle, true );
281
282 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
283 // results in a re-entrant call where the second call is one page behind.
284 for( int attempts = 0; attempts < 3; ++attempts )
285 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
286}
287
288
289void PANEL_DESIGN_BLOCK_LIB_TABLE::AddTable( LIBRARY_TABLE* table, const wxString& aTitle, bool aClosable )
290{
291 DESIGN_BLOCK_LIBRARY_ADAPTER* adapter = m_project->DesignBlockLibs();
292 wxString projectPath = m_project->GetProjectPath();
293
295
296 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
297
298 if( table->Path().StartsWith( projectPath ) )
299 {
301 &m_lastProjectLibDir, projectPath,
303 true /* take ownership */ );
304 }
305 else
306 {
307 wxString* lastGlobalLibDir = nullptr;
308
309 if( KICAD_SETTINGS* cfg = GetAppSettings<KICAD_SETTINGS>( "kicad" ) )
310 {
311 if( cfg->m_lastDesignBlockLibDir.IsEmpty() )
312 cfg->m_lastDesignBlockLibDir = PATHS::GetDefaultUserDesignBlocksPath();
313
314 lastGlobalLibDir = &cfg->m_lastDesignBlockLibDir;
315 }
316
318 lastGlobalLibDir, wxEmptyString,
320 true /* take ownership */ );
321 }
322
323 // add Cut, Copy, and Paste to wxGrids
324 grid->PushEventHandler( new DESIGN_BLOCK_GRID_TRICKS( this, grid ) );
325
326 auto autoSizeCol =
327 [&]( int aCol )
328 {
329 int prevWidth = grid->GetColSize( aCol );
330
331 grid->AutoSizeColumn( aCol, false );
332 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
333 };
334
335 // all but COL_OPTIONS, which is edited with Option Editor anyways.
336 autoSizeCol( COL_NICKNAME );
337 autoSizeCol( COL_TYPE );
338 autoSizeCol( COL_URI );
339 autoSizeCol( COL_DESCR );
340
341 if( grid->GetNumberRows() > 0 )
342 {
343 grid->SetGridCursor( 0, COL_NICKNAME );
344 grid->SelectRow( 0 );
345 }
346}
347
348
350 PROJECT* aProject ) :
352 m_project( aProject ),
353 m_parent( aParent )
354{
355 m_lastProjectLibDir = m_project->GetProjectPath();
356
358
359 for( auto& [fileType, desc] : m_supportedDesignBlockFiles )
361
362 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
364 wxASSERT( table.has_value() );
365
366 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
367
368 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
370
371 if( projectTable.has_value() )
372 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
373
374 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
375
376 // There aren't (yet) any legacy DesignBlock libraries to migrate
377 m_migrate_libs_button->Hide();
378
379 // add Cut, Copy, and Paste to wxGrids
380 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
381
383
384 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
385 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
386
387 // Configure button logos
393
394 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
395 // manually (for instance m_append_button)
396 Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
397 // their bitmaps
398 wxSize buttonSize = m_append_button->GetSize();
399
400 m_browseButton->SetWidthPadding( 4 );
401 m_browseButton->SetMinSize( buttonSize );
402
403 // Populate the browse library options
404 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
405
406 for( auto& [type, desc] : m_supportedDesignBlockFiles )
407 {
408 wxString entryStr = DESIGN_BLOCK_IO_MGR::ShowType( type );
409 wxString midPart;
410
411 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
412 {
413 entryStr << wxString::Format( wxS( " (%s)" ), JoinExtensions( desc.m_FileExtensions ) );
414 }
415 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
416 {
417 midPart = wxString::Format( _( "folder with %s files" ), JoinExtensions( desc.m_ExtensionsInDir ) );
418 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
419 }
420
421 browseMenu->Append( type, entryStr );
422 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
423 this, type );
424 }
425
426 Layout();
427
428 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_DESIGN_BLOCK_LIB_TABLE::onNotebookPageCloseRequest, this );
429 // This is the button only press for the browse button instead of the menu
431}
432
433
435{
436 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
437
438 for( auto& [type, desc] : m_supportedDesignBlockFiles )
439 {
440 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
441 this, type );
442 }
443
445
446 // Delete the GRID_TRICKS.
447 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
448 m_path_subs_grid->PopEventHandler( true );
449}
450
451
453{
455 {
457 {
459 continue;
460 }
461
463
464 if( !pi )
465 continue;
466
467 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
468 m_supportedDesignBlockFiles.emplace( type, desc );
469 }
470}
471
472
477
478
480{
481 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
482}
483
484
486{
487 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
488 {
489 WX_GRID* grid = get_grid( page );
490
492 [&]( int aRow, int aCol )
493 {
494 // show the tabbed panel holding the grid we have flunked:
495 if( m_notebook->GetSelection() != page )
496 m_notebook->SetSelection( page );
497
498 grid->MakeCellVisible( aRow, 0 );
499 grid->SetGridCursor( aRow, aCol );
500 } ) )
501 {
502 return false;
503 }
504 }
505
506 return true;
507}
508
509
514
515
520
521
526
527
532
533
535{
536 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
537 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
538
539 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
540 {
541 if( panel->GetClosable() )
542 {
543 if( !panel->GetCanClose() )
544 aEvent.Veto();
545 }
546 else
547 {
548 aEvent.Veto();
549 }
550 }
551}
552
553
554// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
556{
557 if( !cur_grid()->CommitPendingChanges() )
558 return;
559
560 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
561
562 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
563 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
564
565 wxArrayInt rowsToMigrate;
567 wxString msg;
568
569 for( int row : selectedRows )
570 {
571 if( cur_grid()->GetCellValue( row, COL_TYPE ) != kicadType )
572 rowsToMigrate.push_back( row );
573 }
574
575 if( rowsToMigrate.size() <= 0 )
576 {
577 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
578 return;
579 }
580 else
581 {
582 if( rowsToMigrate.size() == 1 )
583 {
584 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
585 cur_grid()->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
586 }
587 else
588 {
589 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
590 (int) rowsToMigrate.size() );
591 }
592
593 if( !IsOK( m_parent, msg ) )
594 return;
595 }
596
597 for( int row : rowsToMigrate )
598 {
599 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
600 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
601 wxFileName legacyLib( resolvedPath );
602
603 if( !legacyLib.Exists() )
604 {
605 msg.Printf( _( "Library '%s' not found." ), relPath );
606 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
607 continue;
608 }
609
610 wxFileName newLib( resolvedPath );
611 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadDesignBlockLibPathExtension );
612 newLib.SetName( "" );
613 newLib.ClearExt();
614
615 if( newLib.DirExists() )
616 {
617 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing design blocks?" ),
618 newLib.GetFullPath() );
619
620 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
621 {
622 case wxYES: break;
623 case wxNO: continue;
624 case wxCANCEL: return;
625 }
626 }
627
628 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
629 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
630
631 if( DESIGN_BLOCK_IO_MGR::ConvertLibrary( &props, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
632 {
633 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
634
635 cur_grid()->SetCellValue( row, COL_URI, relPath );
636 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
637 }
638 else
639 {
640 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save design block library file '%s'." ),
641 newLib.GetFullPath() ) );
642 }
643 }
644}
645
646
648{
649 if( !cur_grid()->CommitPendingChanges() )
650 return;
651
653
654 // We are bound both to the menu and button with this one handler
655 // So we must set the file type based on it
656 if( event.GetEventType() == wxEVT_BUTTON )
657 {
658 // Let's default to adding a kicad design block file for just the design block
660 }
661 else
662 {
663 fileType = static_cast<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T>( event.GetId() );
664 }
665
667 return;
668
671
672 wxString title = wxString::Format( _( "Select %s Library" ), DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
673 wxString dummy;
674 wxString* lastDir;
675
676 if( m_notebook->GetSelection() == 0 )
677 lastDir = cfg ? &cfg->m_lastDesignBlockLibDir : &dummy;
678 else
679 lastDir = &m_lastProjectLibDir;
680
681 wxArrayString files;
682 wxWindow* topLevelParent = wxGetTopLevelParent( this );
683
684 if( fileDesc.m_IsFile )
685 {
686 wxFileDialog dlg( topLevelParent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
687 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
688
689 if( dlg.ShowModal() == wxID_CANCEL )
690 return;
691
692 dlg.GetPaths( files );
693 *lastDir = dlg.GetDirectory();
694 }
695 else
696 {
697 wxDirDialog dlg( topLevelParent, title, *lastDir,
698 wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
699
700 if( dlg.ShowModal() == wxID_CANCEL )
701 return;
702
703 dlg.GetPaths( files );
704
705 if( !files.IsEmpty() )
706 {
707 wxFileName first( files.front() );
708 *lastDir = first.GetPath();
709 }
710 }
711
712 // Drop the last directory if the path is a .pretty folder
714 cfg->m_lastDesignBlockLibDir = cfg->m_lastDesignBlockLibDir.BeforeLast( wxFileName::GetPathSeparator() );
715
716 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
717 bool addDuplicates = false;
718 bool applyToAll = false;
719 wxString warning = _( "Warning: Duplicate Nicknames" );
720 wxString msg = _( "An item nicknamed '%s' already exists." );
721 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
722
723 for( const wxString& filePath : files )
724 {
725 wxFileName fn( filePath );
726 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
727 bool doAdd = true;
728
730 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
731
732 if( cur_model()->ContainsNickname( nickname ) )
733 {
734 if( !applyToAll )
735 {
736 // The cancel button adds the library to the table anyway
737 addDuplicates = OKOrCancelDialog( m_parent, warning, wxString::Format( msg, nickname ), detailedMsg,
738 _( "Skip" ), _( "Add Anyway" ), &applyToAll ) == wxID_CANCEL;
739 }
740
741 doAdd = addDuplicates;
742 }
743
744 if( doAdd && cur_grid()->AppendRows( 1 ) )
745 {
746 int last_row = cur_grid()->GetNumberRows() - 1;
747
748 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
749 cur_grid()->SetCellValue( last_row, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
750
751 // try to use path normalized to an environmental variable or project path
752 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
753
754 // Do not use the project path in the global library table. This will almost
755 // assuredly be wrong for a different project.
756 if( m_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
757 path = fn.GetFullPath();
758
759 cur_grid()->SetCellValue( last_row, COL_URI, path );
760 }
761 }
762
763 if( !files.IsEmpty() )
764 {
765 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
766 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
767 }
768}
769
770
772{
773 // Account for scroll bars
774 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
775
776 m_path_subs_grid->AutoSizeColumn( 0 );
777 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
778 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
779}
780
781
783{
784 adjustPathSubsGridColumns( event.GetSize().GetX() );
785
786 event.Skip();
787}
788
789
791{
792 if( !cur_grid()->CommitPendingChanges() )
793 return false;
794
795 if( !verifyTables() )
796 return false;
797
799
800 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
802 wxCHECK( optTable.has_value(), false );
803 LIBRARY_TABLE* globalTable = optTable.value();
804
805 if( get_model( 0 )->Table() != *globalTable )
806 {
807 m_parent->m_GlobalTableChanged = true;
808 *globalTable = get_model( 0 )->Table();
809
810 globalTable->Save().map_error(
811 []( const LIBRARY_ERROR& aError )
812 {
813 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
814 _( "File Save Error" ), wxOK | wxICON_ERROR );
815 } );
816 }
817
819
820 if( optTable.has_value() && get_model( 1 )->Table().Path() == optTable.value()->Path() )
821 {
822 LIBRARY_TABLE* projectTable = optTable.value();
823
824 if( get_model( 1 )->Table() != *projectTable )
825 {
826 m_parent->m_ProjectTableChanged = true;
827 *projectTable = get_model( 1 )->Table();
828
829 projectTable->Save().map_error(
830 []( const LIBRARY_ERROR& aError )
831 {
832 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
833 _( "File Save Error" ), wxOK | wxICON_ERROR );
834 } );
835 }
836 }
837
838 for( int ii = 0; ii < (int) m_notebook->GetPageCount(); ++ii )
839 {
840 LIB_TABLE_NOTEBOOK_PANEL* panel = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
841
842 if( panel->GetClosable() && panel->TableModified() )
843 {
844 panel->SaveTable();
845 m_parent->m_GlobalTableChanged = true;
846 m_parent->m_ProjectTableChanged = true;
847 }
848 }
849
850 return true;
851}
852
853
857{
858 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
859 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
860
861 std::set<wxString> unique;
862
863 // clear the table
864 m_path_subs_grid->ClearRows();
865
866 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
867 {
869
870 for( int row = 0; row < model->GetNumberRows(); ++row )
871 {
872 wxString uri = model->GetValue( row, COL_URI );
873
874 while( re.Matches( uri ) )
875 {
876 wxString envvar = re.GetMatch( uri, 2 );
877
878 // if not ${...} form then must be $(...)
879 if( envvar.IsEmpty() )
880 envvar = re.GetMatch( uri, 4 );
881
882 // ignore duplicates
883 unique.insert( envvar );
884
885 // delete the last match and search again
886 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
887 }
888 }
889 }
890
891 // Make sure this special environment variable shows up even if it was
892 // not used yet. It is automatically set by KiCad to the directory holding
893 // the current project.
894 unique.insert( PROJECT_VAR_NAME );
896
897 // This special environment variable is used to locate 3d shapes
898 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
899
900 for( const wxString& evName : unique )
901 {
902 int row = m_path_subs_grid->GetNumberRows();
903 m_path_subs_grid->AppendRows( 1 );
904
905 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
906 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
907
908 wxString evValue;
909 wxGetEnv( evName, &evValue );
910 m_path_subs_grid->SetCellValue( row, 1, evValue );
911 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
912 }
913
914 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
915}
916
917//-----</event handlers>---------------------------------
918
919void InvokeEditDesignBlockLibTable( KIWAY* aKiway, wxWindow *aParent )
920{
921 DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Design Block Libraries" ) );
922
923 dlg.InstallPanel( new PANEL_DESIGN_BLOCK_LIB_TABLE( &dlg, &aKiway->Prj() ) );
924
925 if( dlg.ShowModal() == wxID_CANCEL )
926 return;
927
928 if( dlg.m_GlobalTableChanged )
930
931 if( dlg.m_ProjectTableChanged )
932 {
933 // Trigger a reload of the table and cancel an in-progress background load
935 }
936
937 // Trigger a load of any new block libraries
939
940 std::string payload = "";
941 aKiway->ExpressMail( FRAME_SCH, MAIL_RELOAD_LIB, payload );
942 aKiway->ExpressMail( FRAME_PCB_EDITOR, MAIL_RELOAD_LIB, payload );
943
944 return;
945}
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:110
void openTable(const LIBRARY_TABLE_ROW &aRow) override
DESIGN_BLOCK_GRID_TRICKS(PANEL_DESIGN_BLOCK_LIB_TABLE *aPanel, WX_GRID *aGrid)
PANEL_DESIGN_BLOCK_LIB_TABLE * m_panel
@ KICAD_SEXP
S-expression KiCad file format.
@ DESIGN_BLOCK_FILE_UNKNOWN
0 is not a legal menu id on Mac
static const wxString ShowType(DESIGN_BLOCK_FILE_T aFileType)
static DESIGN_BLOCK_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
static DESIGN_BLOCK_FILE_T EnumFromStr(const wxString &aFileType)
static bool ConvertLibrary(std::map< std::string, UTF8 > *aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilePath)
Convert a design block library to the latest KiCad format.
static DESIGN_BLOCK_IO * FindPlugin(DESIGN_BLOCK_FILE_T aFileType)
This class builds a wxGridTableBase by wrapping an #DESIGN_BLOCK_LIB_TABLE object.
void SetValue(int aRow, int aCol, const wxString &aValue) override
wxString getFileTypes(WX_GRID *aGrid, int aRow) override
const std::map< DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T, IO_BASE::IO_FILE_DESC > & m_supportedDesignBlockFiles
DESIGN_BLOCK_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, const std::map< DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T, IO_BASE::IO_FILE_DESC > &aSupportedFiles)
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
wxString m_lastDesignBlockLibDir
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 PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:200
The interface used by the classes that actually can load IO plugins for the different parts of KiCad ...
static wxString ExpandURI(const wxString &aShortURI, const PROJECT &aProject)
std::optional< LIBRARY_TABLE * > Table(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope)
Retrieves a given table; creating a new empty project table if a valid project is loaded and the give...
void 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)
void GetPaths(wxArrayString &aPathArray)
virtual wxDirTraverseResult OnOpenError(const wxString &aOpenErrorName) override
std::unordered_map< wxString, int > m_failedDirs
std::vector< std::string > m_searchExtensions
void GetFailedPaths(wxArrayString &aPathArray)
LIBRARY_TRAVERSER(std::vector< std::string > aSearchExtensions, wxString aInitialDir)
std::unordered_map< wxString, int > m_foundDirs
virtual wxDirTraverseResult OnDir(const wxString &aDirName) override
virtual wxDirTraverseResult OnFile(const wxString &aFileName) override
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_DESIGN_BLOCK_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 moveUpHandler(wxCommandEvent &event) override
void onMigrateLibraries(wxCommandEvent &event) override
void onNotebookPageCloseRequest(wxAuiNotebookEvent &aEvent)
std::vector< std::shared_ptr< LIBRARY_TABLE > > m_nestedTables
void browseLibrariesHandler(wxCommandEvent &event)
void populateEnvironReadOnlyTable()
Populate the readonly environment variable table with names and values by examining all the full_uri ...
std::map< DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T, IO_BASE::IO_FILE_DESC > m_supportedDesignBlockFiles
void moveDownHandler(wxCommandEvent &event) override
DIALOG_EDIT_LIBRARY_TABLES * m_parent
DESIGN_BLOCK_LIB_TABLE_GRID_DATA_MODEL * get_model(int aPage) const
void appendRowHandler(wxCommandEvent &event) override
PANEL_DESIGN_BLOCK_LIB_TABLE(DIALOG_EDIT_LIBRARY_TABLES *aParent, PROJECT *aProject)
void onSizeGrid(wxSizeEvent &event) override
void deleteRowHandler(wxCommandEvent &event) override
void AddTable(LIBRARY_TABLE *table, const wxString &aTitle, bool aClosable)
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.
DESIGN_BLOCK_LIB_TABLE_GRID_DATA_MODEL * cur_model() const
static wxString GetDefaultUserDesignBlocksPath()
Gets the default path we point users to create projects.
Definition paths.cpp:104
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
Definition pgm_base.cpp:881
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition pgm_base.cpp:781
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:134
Container for project specific data.
Definition project.h:65
wxString wx_str() const
Definition utf8.cpp:45
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)
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_PCB_EDITOR
Definition frame_type.h:42
@ FRAME_SCH
Definition frame_type.h:34
static const std::string KiCadDesignBlockLibPathExtension
static const std::string DesignBlockLibraryTableFileName
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 InvokeEditDesignBlockLibTable(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
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.