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 <kiplatform/ui.h>
52#include <kiway_express.h>
55#include <paths.h>
56#include <macros.h>
60
73
74
79class LIBRARY_TRAVERSER : public wxDirTraverser
80{
81public:
82 LIBRARY_TRAVERSER( std::vector<std::string> aSearchExtensions, wxString aInitialDir ) :
83 m_searchExtensions( aSearchExtensions ), m_currentDir( aInitialDir )
84 {
85 }
86
87 virtual wxDirTraverseResult OnFile( const wxString& aFileName ) override
88 {
89 wxFileName file( aFileName );
90
91 for( const std::string& ext : m_searchExtensions )
92 {
93 if( file.GetExt().IsSameAs( ext, false ) )
94 m_foundDirs.insert( { m_currentDir, 1 } );
95 }
96
97 return wxDIR_CONTINUE;
98 }
99
100 virtual wxDirTraverseResult OnOpenError( const wxString& aOpenErrorName ) override
101 {
102 m_failedDirs.insert( { aOpenErrorName, 1 } );
103 return wxDIR_IGNORE;
104 }
105
106 bool HasDirectoryOpenFailures() { return m_failedDirs.size() > 0; }
107
108 virtual wxDirTraverseResult OnDir( const wxString& aDirName ) override
109 {
110 m_currentDir = aDirName;
111 return wxDIR_CONTINUE;
112 }
113
114 void GetPaths( wxArrayString& aPathArray )
115 {
116 for( std::pair<const wxString, int>& foundDirsPair : m_foundDirs )
117 aPathArray.Add( foundDirsPair.first );
118 }
119
120 void GetFailedPaths( wxArrayString& aPathArray )
121 {
122 for( std::pair<const wxString, int>& failedDirsPair : m_failedDirs )
123 aPathArray.Add( failedDirsPair.first );
124 }
125
126private:
127 std::vector<std::string> m_searchExtensions;
128 wxString m_currentDir;
129 std::unordered_map<wxString, int> m_foundDirs;
130 std::unordered_map<wxString, int> m_failedDirs;
131};
132
133
138{
139public:
141 LIBRARY_MANAGER_ADAPTER* aAdapter, const wxArrayString& aPluginChoices,
142 wxString* aMRUDirectory, const wxString& aProjectPath,
144 IO_BASE::IO_FILE_DESC>& aSupportedFiles ) :
145 LIB_TABLE_GRID_DATA_MODEL( aParent, aGrid, aTableToEdit, aAdapter, aPluginChoices, aMRUDirectory,
146 aProjectPath ),
147 m_supportedDesignBlockFiles( aSupportedFiles )
148 {
149 }
150
151 void SetValue( int aRow, int aCol, const wxString& aValue ) override
152 {
153 wxCHECK( aRow < (int) size(), /* void */ );
154
155 LIB_TABLE_GRID_DATA_MODEL::SetValue( aRow, aCol, aValue );
156
157 // If setting a filepath, attempt to auto-detect the format
158 if( aCol == COL_URI )
159 {
160 LIBRARY_TABLE_ROW& row = at( static_cast<size_t>( aRow ) );
161 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
162
165
166 if( pluginType != DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
167 SetValue( aRow, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( pluginType ) );
168 }
169 }
170
171protected:
172 wxString getFileTypes( WX_GRID* aGrid, int aRow ) override
173 {
174 auto* table = static_cast<DESIGN_BLOCK_LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
175 LIBRARY_TABLE_ROW& tableRow = table->at( aRow );
176
177 if( tableRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
178 {
179 wxString filter = _( "Design Block Library Tables" );
180#ifndef __WXOSX__
181 filter << wxString::Format( _( " (%s)|%s" ), FILEEXT::DesignBlockLibraryTableFileName,
183#else
184 filter << wxString::Format( _( " (%s)|%s" ), wxFileSelectorDefaultWildcardStr,
185 wxFileSelectorDefaultWildcardStr );
186#endif
187 return filter;
188 }
189
190 if( tableRow.Type().IsEmpty() )
191 return wxEmptyString;
192
195 return wxEmptyString;
196
198
199 if( pluginDesc.m_IsFile )
200 return pluginDesc.FileFilter();
201
202 return wxEmptyString;
203 }
204
205private:
206 const std::map<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T, IO_BASE::IO_FILE_DESC>& m_supportedDesignBlockFiles;
207};
208
209
211{
212public:
219
220protected:
221 void optionsEditor( int aRow ) override
222 {
223 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
224
225 if( tbl->GetNumberRows() > aRow )
226 {
227 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
228 const wxString& options = row.Options();
229 wxString result = options;
230 std::map<std::string, UTF8> choices;
231
234 pi->GetLibraryOptions( &choices );
235
236 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
237 dlg.ShowModal();
238
239 if( options != result )
240 {
241 row.SetOptions( result );
242 m_grid->Refresh();
243 }
244 }
245 }
246
247 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
248 {
249 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
250 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL );
251
252 m_panel->OpenTable( child, aRow.Nickname() );
253 }
254
255 wxString getTablePreamble() override
256 {
257 return wxT( "(design_block_lib_table" );
258 }
259
260protected:
262};
263
264
265void PANEL_DESIGN_BLOCK_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
266{
267 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
268 {
269 if( m_notebook->GetPageText( ii ) == aTitle )
270 {
271 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
272 // results in a re-entrant call where the second call is one page behind.
273 for( int attempts = 0; attempts < 3; ++attempts )
274 m_notebook->ChangeSelection( ii );
275
276 return;
277 }
278 }
279
280 m_nestedTables.push_back( aTable );
281 AddTable( aTable.get(), aTitle, true );
282
283 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
284 // results in a re-entrant call where the second call is one page behind.
285 for( int attempts = 0; attempts < 3; ++attempts )
286 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
287}
288
289
290void PANEL_DESIGN_BLOCK_LIB_TABLE::AddTable( LIBRARY_TABLE* table, const wxString& aTitle, bool aClosable )
291{
292 DESIGN_BLOCK_LIBRARY_ADAPTER* adapter = m_project->DesignBlockLibs();
293 wxString projectPath = m_project->GetProjectPath();
294
296
297 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
298
299 if( table->Path().StartsWith( projectPath ) )
300 {
302 &m_lastProjectLibDir, projectPath,
304 true /* take ownership */ );
305 }
306 else
307 {
308 wxString* lastGlobalLibDir = nullptr;
309
310 if( KICAD_SETTINGS* cfg = GetAppSettings<KICAD_SETTINGS>( "kicad" ) )
311 {
312 if( cfg->m_lastDesignBlockLibDir.IsEmpty() )
313 cfg->m_lastDesignBlockLibDir = PATHS::GetDefaultUserDesignBlocksPath();
314
315 lastGlobalLibDir = &cfg->m_lastDesignBlockLibDir;
316 }
317
319 lastGlobalLibDir, wxEmptyString,
321 true /* take ownership */ );
322 }
323
324 // add Cut, Copy, and Paste to wxGrids
325 grid->PushEventHandler( new DESIGN_BLOCK_GRID_TRICKS( this, grid ) );
326
327 auto autoSizeCol =
328 [&]( int aCol )
329 {
330 int prevWidth = grid->GetColSize( aCol );
331
332 grid->AutoSizeColumn( aCol, false );
333 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
334 };
335
336 // all but COL_OPTIONS, which is edited with Option Editor anyways.
337 autoSizeCol( COL_NICKNAME );
338 autoSizeCol( COL_TYPE );
339 autoSizeCol( COL_URI );
340 autoSizeCol( COL_DESCR );
341
342 if( grid->GetNumberRows() > 0 )
343 {
344 grid->SetGridCursor( 0, COL_NICKNAME );
345 grid->SelectRow( 0 );
346 }
347}
348
349
351 PROJECT* aProject ) :
353 m_project( aProject ),
354 m_parent( aParent )
355{
356 m_lastProjectLibDir = m_project->GetProjectPath();
357
359
360 for( auto& [fileType, desc] : m_supportedDesignBlockFiles )
362
363 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
365 wxASSERT( table.has_value() );
366
367 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
368
369 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
371
372 if( projectTable.has_value() )
373 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
374
375 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
376
377 // There aren't (yet) any legacy DesignBlock libraries to migrate
378 m_migrate_libs_button->Hide();
379
380 // add Cut, Copy, and Paste to wxGrids
381 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
382
384
385 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
386 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
387
388 // Configure button logos
394
395 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
396 // manually (for instance m_append_button)
397 Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
398 // their bitmaps
399 wxSize buttonSize = m_append_button->GetSize();
400
401 m_browseButton->SetWidthPadding( 4 );
402 m_browseButton->SetMinSize( buttonSize );
403
404 // Populate the browse library options
405 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
406
407 for( auto& [type, desc] : m_supportedDesignBlockFiles )
408 {
409 wxString entryStr = DESIGN_BLOCK_IO_MGR::ShowType( type );
410 wxString midPart;
411
412 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
413 {
414 entryStr << wxString::Format( wxS( " (%s)" ), JoinExtensions( desc.m_FileExtensions ) );
415 }
416 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
417 {
418 midPart = wxString::Format( _( "folder with %s files" ), JoinExtensions( desc.m_ExtensionsInDir ) );
419 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
420 }
421
422 browseMenu->Append( type, entryStr );
423 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
424 this, type );
425 }
426
427 Layout();
428
429 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_DESIGN_BLOCK_LIB_TABLE::onNotebookPageCloseRequest, this );
430 // This is the button only press for the browse button instead of the menu
432}
433
434
436{
437 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
438
439 for( auto& [type, desc] : m_supportedDesignBlockFiles )
440 {
441 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
442 this, type );
443 }
444
446
447 // Delete the GRID_TRICKS.
448 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
449 m_path_subs_grid->PopEventHandler( true );
450}
451
452
454{
456 {
458 {
460 continue;
461 }
462
464
465 if( !pi )
466 continue;
467
468 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
469 m_supportedDesignBlockFiles.emplace( type, desc );
470 }
471}
472
473
478
479
481{
482 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
483}
484
485
487{
488 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
489 {
490 WX_GRID* grid = get_grid( page );
491
493 [&]( int aRow, int aCol )
494 {
495 // show the tabbed panel holding the grid we have flunked:
496 if( m_notebook->GetSelection() != page )
497 m_notebook->SetSelection( page );
498
499 grid->MakeCellVisible( aRow, 0 );
500 grid->SetGridCursor( aRow, aCol );
501 } ) )
502 {
503 return false;
504 }
505 }
506
507 return true;
508}
509
510
515
516
521
522
527
528
533
534
536{
537 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
538 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
539
540 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
541 {
542 if( panel->GetClosable() )
543 {
544 if( !panel->GetCanClose() )
545 aEvent.Veto();
546 }
547 else
548 {
549 aEvent.Veto();
550 }
551 }
552}
553
554
555// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
557{
558 if( !cur_grid()->CommitPendingChanges() )
559 return;
560
561 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
562
563 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
564 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
565
566 wxArrayInt rowsToMigrate;
568 wxString msg;
569
570 for( int row : selectedRows )
571 {
572 if( cur_grid()->GetCellValue( row, COL_TYPE ) != kicadType )
573 rowsToMigrate.push_back( row );
574 }
575
576 if( rowsToMigrate.size() <= 0 )
577 {
578 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
579 return;
580 }
581 else
582 {
583 if( rowsToMigrate.size() == 1 )
584 {
585 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
586 cur_grid()->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
587 }
588 else
589 {
590 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
591 (int) rowsToMigrate.size() );
592 }
593
594 if( !IsOK( m_parent, msg ) )
595 return;
596 }
597
598 for( int row : rowsToMigrate )
599 {
600 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
601 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
602 wxFileName legacyLib( resolvedPath );
603
604 if( !legacyLib.Exists() )
605 {
606 msg.Printf( _( "Library '%s' not found." ), relPath );
607 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
608 continue;
609 }
610
611 wxFileName newLib( resolvedPath );
612 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadDesignBlockLibPathExtension );
613 newLib.SetName( "" );
614 newLib.ClearExt();
615
616 if( newLib.DirExists() )
617 {
618 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing design blocks?" ),
619 newLib.GetFullPath() );
620
621 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
622 {
623 case wxYES: break;
624 case wxNO: continue;
625 case wxCANCEL: return;
626 }
627 }
628
629 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
630 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
631
632 if( DESIGN_BLOCK_IO_MGR::ConvertLibrary( &props, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
633 {
634 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
635
636 cur_grid()->SetCellValue( row, COL_URI, relPath );
637 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
638 }
639 else
640 {
641 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save design block library file '%s'." ),
642 newLib.GetFullPath() ) );
643 }
644 }
645}
646
647
649{
650 if( !cur_grid()->CommitPendingChanges() )
651 return;
652
654
655 // We are bound both to the menu and button with this one handler
656 // So we must set the file type based on it
657 if( event.GetEventType() == wxEVT_BUTTON )
658 {
659 // Let's default to adding a kicad design block file for just the design block
661 }
662 else
663 {
664 fileType = static_cast<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T>( event.GetId() );
665 }
666
668 return;
669
672
673 wxString title = wxString::Format( _( "Select %s Library" ), DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
674 wxString dummy;
675 wxString* lastDir;
676
677 if( m_notebook->GetSelection() == 0 )
678 lastDir = cfg ? &cfg->m_lastDesignBlockLibDir : &dummy;
679 else
680 lastDir = &m_lastProjectLibDir;
681
682 wxArrayString files;
683 wxWindow* topLevelParent = wxGetTopLevelParent( this );
684
685 if( fileDesc.m_IsFile )
686 {
687 wxFileDialog dlg( topLevelParent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
688 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
689
691
692 if( dlg.ShowModal() == wxID_CANCEL )
693 return;
694
695 dlg.GetPaths( files );
696 *lastDir = dlg.GetDirectory();
697 }
698 else
699 {
700 wxDirDialog dlg( topLevelParent, title, *lastDir,
701 wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
702
703 if( dlg.ShowModal() == wxID_CANCEL )
704 return;
705
706 dlg.GetPaths( files );
707
708 if( !files.IsEmpty() )
709 {
710 wxFileName first( files.front() );
711 *lastDir = first.GetPath();
712 }
713 }
714
715 // Drop the last directory if the path is a .pretty folder
717 cfg->m_lastDesignBlockLibDir = cfg->m_lastDesignBlockLibDir.BeforeLast( wxFileName::GetPathSeparator() );
718
719 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
720 bool addDuplicates = false;
721 bool applyToAll = false;
722 wxString warning = _( "Warning: Duplicate Nicknames" );
723 wxString msg = _( "An item nicknamed '%s' already exists." );
724 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
725
726 for( const wxString& filePath : files )
727 {
728 wxFileName fn( filePath );
729 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
730 bool doAdd = true;
731
733 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
734
735 if( cur_model()->ContainsNickname( nickname ) )
736 {
737 if( !applyToAll )
738 {
739 // The cancel button adds the library to the table anyway
740 addDuplicates = OKOrCancelDialog( m_parent, warning, wxString::Format( msg, nickname ), detailedMsg,
741 _( "Skip" ), _( "Add Anyway" ), &applyToAll ) == wxID_CANCEL;
742 }
743
744 doAdd = addDuplicates;
745 }
746
747 if( doAdd && cur_grid()->AppendRows( 1 ) )
748 {
749 int last_row = cur_grid()->GetNumberRows() - 1;
750
751 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
752 cur_grid()->SetCellValue( last_row, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
753
754 // try to use path normalized to an environmental variable or project path
755 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
756
757 // Do not use the project path in the global library table. This will almost
758 // assuredly be wrong for a different project.
759 if( m_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
760 path = fn.GetFullPath();
761
762 cur_grid()->SetCellValue( last_row, COL_URI, path );
763 }
764 }
765
766 if( !files.IsEmpty() )
767 {
768 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
769 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
770 }
771}
772
773
775{
776 // Account for scroll bars
777 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
778
779 m_path_subs_grid->AutoSizeColumn( 0 );
780 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
781 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
782}
783
784
786{
787 adjustPathSubsGridColumns( event.GetSize().GetX() );
788
789 event.Skip();
790}
791
792
794{
795 if( !cur_grid()->CommitPendingChanges() )
796 return false;
797
798 if( !verifyTables() )
799 return false;
800
802
803 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
805 wxCHECK( optTable.has_value(), false );
806 LIBRARY_TABLE* globalTable = optTable.value();
807
808 if( get_model( 0 )->Table() != *globalTable )
809 {
810 m_parent->m_GlobalTableChanged = true;
811 *globalTable = get_model( 0 )->Table();
812
813 globalTable->Save().map_error(
814 []( const LIBRARY_ERROR& aError )
815 {
816 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
817 _( "File Save Error" ), wxOK | wxICON_ERROR );
818 } );
819 }
820
822
823 if( optTable.has_value() && get_model( 1 )->Table().Path() == optTable.value()->Path() )
824 {
825 LIBRARY_TABLE* projectTable = optTable.value();
826
827 if( get_model( 1 )->Table() != *projectTable )
828 {
829 m_parent->m_ProjectTableChanged = true;
830 *projectTable = get_model( 1 )->Table();
831
832 projectTable->Save().map_error(
833 []( const LIBRARY_ERROR& aError )
834 {
835 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
836 _( "File Save Error" ), wxOK | wxICON_ERROR );
837 } );
838 }
839 }
840
841 for( int ii = 0; ii < (int) m_notebook->GetPageCount(); ++ii )
842 {
843 LIB_TABLE_NOTEBOOK_PANEL* panel = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
844
845 if( panel->GetClosable() && panel->TableModified() )
846 {
847 panel->SaveTable();
848 m_parent->m_GlobalTableChanged = true;
849 m_parent->m_ProjectTableChanged = true;
850 }
851 }
852
853 return true;
854}
855
856
860{
861 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
862 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
863
864 std::set<wxString> unique;
865
866 // clear the table
867 m_path_subs_grid->ClearRows();
868
869 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
870 {
872
873 for( int row = 0; row < model->GetNumberRows(); ++row )
874 {
875 wxString uri = model->GetValue( row, COL_URI );
876
877 while( re.Matches( uri ) )
878 {
879 wxString envvar = re.GetMatch( uri, 2 );
880
881 // if not ${...} form then must be $(...)
882 if( envvar.IsEmpty() )
883 envvar = re.GetMatch( uri, 4 );
884
885 // ignore duplicates
886 unique.insert( envvar );
887
888 // delete the last match and search again
889 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
890 }
891 }
892 }
893
894 // Make sure this special environment variable shows up even if it was
895 // not used yet. It is automatically set by KiCad to the directory holding
896 // the current project.
897 unique.insert( PROJECT_VAR_NAME );
899
900 // This special environment variable is used to locate 3d shapes
901 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
902
903 for( const wxString& evName : unique )
904 {
905 int row = m_path_subs_grid->GetNumberRows();
906 m_path_subs_grid->AppendRows( 1 );
907
908 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
909 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
910
911 wxString evValue;
912 wxGetEnv( evName, &evValue );
913 m_path_subs_grid->SetCellValue( row, 1, evValue );
914 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
915 }
916
917 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
918}
919
920//-----</event handlers>---------------------------------
921
922void InvokeEditDesignBlockLibTable( KIWAY* aKiway, wxWindow *aParent )
923{
924 DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Design Block Libraries" ) );
925
926 dlg.InstallPanel( new PANEL_DESIGN_BLOCK_LIB_TABLE( &dlg, &aKiway->Prj() ) );
927
928 if( dlg.ShowModal() == wxID_CANCEL )
929 return;
930
931 if( dlg.m_GlobalTableChanged )
933
934 if( dlg.m_ProjectTableChanged )
935 {
936 // Trigger a reload of the table and cancel an in-progress background load
938 }
939
940 // Trigger a load of any new block libraries
942
943 std::string payload = "";
944 aKiway->ExpressMail( FRAME_SCH, MAIL_RELOAD_LIB, payload );
945 aKiway->ExpressMail( FRAME_PCB_EDITOR, MAIL_RELOAD_LIB, payload );
946
947 return;
948}
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:558
wxString JoinExtensions(const std::vector< std::string > &aExts)
Join a list of file extensions for use in a file dialog.
Definition common.cpp:648
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 AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:717
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.