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_mail.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
221 {
222 return false;
223 }
224
225protected:
226 void optionsEditor( int aRow ) override
227 {
228 LIB_TABLE_GRID_DATA_MODEL* tbl = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
229
230 if( tbl->GetNumberRows() > aRow )
231 {
232 LIBRARY_TABLE_ROW& row = tbl->At( static_cast<size_t>( aRow ) );
233 const wxString& options = row.Options();
234 wxString result = options;
235 std::map<std::string, UTF8> choices;
236
239 pi->GetLibraryOptions( &choices );
240
241 DIALOG_PLUGIN_OPTIONS dlg( wxGetTopLevelParent( m_grid ), row.Nickname(), choices, options, &result );
242 dlg.ShowModal();
243
244 if( options != result )
245 {
246 row.SetOptions( result );
247 m_grid->Refresh();
248 }
249 }
250 }
251
252 void openTable( const LIBRARY_TABLE_ROW& aRow ) override
253 {
254 wxFileName fn( LIBRARY_MANAGER::ExpandURI( aRow.URI(), Pgm().GetSettingsManager().Prj() ) );
255 std::shared_ptr<LIBRARY_TABLE> child = std::make_shared<LIBRARY_TABLE>( fn, LIBRARY_TABLE_SCOPE::GLOBAL );
256
257 m_panel->OpenTable( child, aRow.Nickname() );
258 }
259
260 wxString getTablePreamble() override
261 {
262 return wxT( "(design_block_lib_table" );
263 }
264
269
270protected:
272};
273
274
275void PANEL_DESIGN_BLOCK_LIB_TABLE::OpenTable( const std::shared_ptr<LIBRARY_TABLE>& aTable, const wxString& aTitle )
276{
277 for( int ii = 2; ii < (int) m_notebook->GetPageCount(); ++ii )
278 {
279 if( m_notebook->GetPageText( ii ) == aTitle )
280 {
281 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
282 // results in a re-entrant call where the second call is one page behind.
283 for( int attempts = 0; attempts < 3; ++attempts )
284 m_notebook->ChangeSelection( ii );
285
286 return;
287 }
288 }
289
290 m_nestedTables.push_back( aTable );
291 AddTable( aTable.get(), aTitle, true );
292
293 // Something is pretty fishy with wxAuiNotebook::ChangeSelection(); on Mac at least it
294 // results in a re-entrant call where the second call is one page behind.
295 for( int attempts = 0; attempts < 3; ++attempts )
296 m_notebook->ChangeSelection( m_notebook->GetPageCount() - 1 );
297}
298
299
300void PANEL_DESIGN_BLOCK_LIB_TABLE::AddTable( LIBRARY_TABLE* table, const wxString& aTitle, bool aClosable )
301{
302 DESIGN_BLOCK_LIBRARY_ADAPTER* adapter = m_project->DesignBlockLibs();
303 wxString projectPath = m_project->GetProjectPath();
304
306
307 WX_GRID* grid = get_grid( (int) m_notebook->GetPageCount() - 1 );
308
309 if( table->Path().StartsWith( projectPath ) )
310 {
312 &m_lastProjectLibDir, projectPath,
314 true /* take ownership */ );
315 }
316 else
317 {
318 wxString* lastGlobalLibDir = nullptr;
319
320 if( KICAD_SETTINGS* cfg = GetAppSettings<KICAD_SETTINGS>( "kicad" ) )
321 {
322 if( cfg->m_lastDesignBlockLibDir.IsEmpty() )
323 cfg->m_lastDesignBlockLibDir = PATHS::GetDefaultUserDesignBlocksPath();
324
325 lastGlobalLibDir = &cfg->m_lastDesignBlockLibDir;
326 }
327
329 lastGlobalLibDir, wxEmptyString,
331 true /* take ownership */ );
332 }
333
334 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( grid->GetTable() )->RecheckRows();
335
336 // add Cut, Copy, and Paste to wxGrids
337 grid->PushEventHandler( new DESIGN_BLOCK_GRID_TRICKS( this, grid ) );
338
339 auto autoSizeCol =
340 [&]( int aCol )
341 {
342 int prevWidth = grid->GetColSize( aCol );
343
344 grid->AutoSizeColumn( aCol, false );
345 grid->SetColSize( aCol, std::max( prevWidth, grid->GetColSize( aCol ) ) );
346 };
347
348 // all but COL_OPTIONS, which is edited with Option Editor anyways.
349 autoSizeCol( COL_NICKNAME );
350 autoSizeCol( COL_TYPE );
351 autoSizeCol( COL_URI );
352 autoSizeCol( COL_DESCR );
353
354 if( grid->GetNumberRows() > 0 )
355 {
356 grid->SetGridCursor( 0, COL_NICKNAME );
357 grid->SelectRow( 0 );
358 }
359}
360
361
363 PROJECT* aProject ) :
365 m_project( aProject ),
366 m_parent( aParent ),
368{
369 m_lastProjectLibDir = m_project->GetProjectPath();
370
372
373 for( auto& [fileType, desc] : m_supportedDesignBlockFiles )
375
376 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
378 wxASSERT( table.has_value() );
379
380 AddTable( table.value(), _( "Global Libraries" ), false /* closable */ );
381
382 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
384
385 if( projectTable.has_value() )
386 AddTable( projectTable.value(), _( "Project Specific Libraries" ), false /* closable */ );
387
388 m_notebook->SetArtProvider( new WX_AUI_TAB_ART() );
389
390 // There aren't (yet) any legacy DesignBlock libraries to migrate
391 m_migrate_libs_button->Hide();
392
393 // add Cut, Copy, and Paste to wxGrids
394 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
395
397
398 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
399 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
400
401 // Configure button logos
407
408 // For aesthetic reasons, we must set the size of m_browseButton to match the other bitmaps
409 // manually (for instance m_append_button)
410 Layout(); // Needed at least on MSW to compute the actual buttons sizes, after initializing
411 // their bitmaps
412 wxSize buttonSize = m_append_button->GetSize();
413
414 m_browseButton->SetWidthPadding( 4 );
415 m_browseButton->SetMinSize( buttonSize );
416
417 // Populate the browse library options
418 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
419
420 for( auto& [type, desc] : m_supportedDesignBlockFiles )
421 {
422 wxString entryStr = DESIGN_BLOCK_IO_MGR::ShowType( type );
423 wxString midPart;
424
425 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
426 {
427 entryStr << wxString::Format( wxS( " (%s)" ), JoinExtensions( desc.m_FileExtensions ) );
428 }
429 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
430 {
431 midPart = wxString::Format( _( "folder with %s files" ), JoinExtensions( desc.m_ExtensionsInDir ) );
432 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
433 }
434
435 browseMenu->Append( type, entryStr );
436 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
437 this, type );
438 }
439
440 Layout();
441
442 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CLOSE, &PANEL_DESIGN_BLOCK_LIB_TABLE::onNotebookPageCloseRequest, this );
443 m_notebook->Bind( wxEVT_AUINOTEBOOK_PAGE_CHANGING, &PANEL_DESIGN_BLOCK_LIB_TABLE::onNotebookPageChangeRequest, this );
444 // This is the button only press for the browse button instead of the menu
446}
447
448
450{
451 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
452
453 for( auto& [type, desc] : m_supportedDesignBlockFiles )
454 {
455 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
456 this, type );
457 }
458
460
461 // Delete the GRID_TRICKS.
462 // (Notebook page GRID_TRICKS are deleted by LIB_TABLE_NOTEBOOK_PANEL.)
463 m_path_subs_grid->PopEventHandler( true );
464}
465
466
468{
470 {
472 {
474 continue;
475 }
476
478
479 if( !pi )
480 continue;
481
482 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
483 m_supportedDesignBlockFiles.emplace( type, desc );
484 }
485}
486
487
492
493
495{
496 return static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( aPage ) )->GetGrid();
497}
498
499
501{
502 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
503 {
504 WX_GRID* grid = get_grid( page );
505
507 [&]( int aRow, int aCol )
508 {
509 // show the tabbed panel holding the grid we have flunked:
510 if( m_notebook->GetSelection() != page )
511 m_notebook->SetSelection( page );
512
513 grid->MakeCellVisible( aRow, 0 );
514 grid->SetGridCursor( aRow, aCol );
515 } ) )
516 {
517 return false;
518 }
519 }
520
521 return true;
522}
523
524
529
530
535
536
541
542
547
548
550{
552 aEvent.Veto();
553 else
554 aEvent.Skip();
555}
556
557
559{
560 wxAuiNotebook* notebook = (wxAuiNotebook*) aEvent.GetEventObject();
561 wxWindow* page = notebook->GetPage( aEvent.GetSelection() );
562
563 if( LIB_TABLE_NOTEBOOK_PANEL* panel = dynamic_cast<LIB_TABLE_NOTEBOOK_PANEL*>( page ) )
564 {
565 if( panel->GetClosable() )
566 {
567 if( !panel->GetCanClose() )
568 aEvent.Veto();
569 }
570 else
571 {
572 aEvent.Veto();
573 }
574 }
575}
576
577
578// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
580{
581 if( !cur_grid()->CommitPendingChanges() )
582 return;
583
584 wxArrayInt selectedRows = cur_grid()->GetSelectedRows();
585
586 if( selectedRows.empty() && cur_grid()->GetGridCursorRow() >= 0 )
587 selectedRows.push_back( cur_grid()->GetGridCursorRow() );
588
589 wxArrayInt rowsToMigrate;
591 wxString msg;
592
593 for( int row : selectedRows )
594 {
595 if( cur_grid()->GetCellValue( row, COL_TYPE ) != kicadType )
596 rowsToMigrate.push_back( row );
597 }
598
599 if( rowsToMigrate.size() <= 0 )
600 {
601 wxMessageBox( _( "Select one or more rows containing libraries to save as current KiCad format." ) );
602 return;
603 }
604 else
605 {
606 if( rowsToMigrate.size() == 1 )
607 {
608 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
609 cur_grid()->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
610 }
611 else
612 {
613 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
614 (int) rowsToMigrate.size() );
615 }
616
617 if( !IsOK( m_parent, msg ) )
618 return;
619 }
620
621 for( int row : rowsToMigrate )
622 {
623 wxString relPath = cur_grid()->GetCellValue( row, COL_URI );
624 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
625 wxFileName legacyLib( resolvedPath );
626
627 if( !legacyLib.Exists() )
628 {
629 msg.Printf( _( "Library '%s' not found." ), relPath );
630 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
631 continue;
632 }
633
634 wxFileName newLib( resolvedPath );
635 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadDesignBlockLibPathExtension );
636 newLib.SetName( "" );
637 newLib.ClearExt();
638
639 if( newLib.DirExists() )
640 {
641 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing design blocks?" ),
642 newLib.GetFullPath() );
643
644 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
645 {
646 case wxYES: break;
647 case wxNO: continue;
648 case wxCANCEL: return;
649 }
650 }
651
652 wxString options = cur_grid()->GetCellValue( row, COL_OPTIONS );
653 std::map<std::string, UTF8> props( LIBRARY_TABLE::ParseOptions( options.ToStdString() ) );
654
655 if( DESIGN_BLOCK_IO_MGR::ConvertLibrary( &props, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
656 {
657 relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
658
659 cur_grid()->SetCellValue( row, COL_URI, relPath );
660 cur_grid()->SetCellValue( row, COL_TYPE, kicadType );
661 }
662 else
663 {
664 DisplayErrorMessage( m_parent, wxString::Format( _( "Failed to save design block library file '%s'." ),
665 newLib.GetFullPath() ) );
666 }
667 }
668}
669
670
672{
673 if( !cur_grid()->CommitPendingChanges() )
674 return;
675
677
678 // We are bound both to the menu and button with this one handler
679 // So we must set the file type based on it
680 if( event.GetEventType() == wxEVT_BUTTON )
681 {
682 // Let's default to adding a kicad design block file for just the design block
684 }
685 else
686 {
687 fileType = static_cast<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T>( event.GetId() );
688 }
689
691 return;
692
695
696 wxString title = wxString::Format( _( "Select %s Library" ), DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
697 wxString dummy;
698 wxString* lastDir;
699
700 if( m_notebook->GetSelection() == 0 )
701 lastDir = cfg ? &cfg->m_lastDesignBlockLibDir : &dummy;
702 else
703 lastDir = &m_lastProjectLibDir;
704
705 wxArrayString files;
706 wxWindow* topLevelParent = wxGetTopLevelParent( this );
707
708 if( fileDesc.m_IsFile )
709 {
710 wxFileDialog dlg( topLevelParent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
711 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
712
714
715 if( dlg.ShowModal() == wxID_CANCEL )
716 return;
717
718 dlg.GetPaths( files );
719 *lastDir = dlg.GetDirectory();
720 }
721 else
722 {
723 wxDirDialog dlg( topLevelParent, title, *lastDir,
724 wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
725
726 if( dlg.ShowModal() == wxID_CANCEL )
727 return;
728
729 dlg.GetPaths( files );
730
731 if( !files.IsEmpty() )
732 {
733 wxFileName first( files.front() );
734 *lastDir = first.GetPath();
735 }
736 }
737
738 // Drop the last directory if the path is a .pretty folder
740 cfg->m_lastDesignBlockLibDir = cfg->m_lastDesignBlockLibDir.BeforeLast( wxFileName::GetPathSeparator() );
741
742 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
743 bool addDuplicates = false;
744 bool applyToAll = false;
745 wxString warning = _( "Warning: Duplicate Nicknames" );
746 wxString msg = _( "An item nicknamed '%s' already exists." );
747 wxString detailedMsg = _( "One of the nicknames will need to be changed." );
748
749 for( const wxString& filePath : files )
750 {
751 wxFileName fn( filePath );
752 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
753 bool doAdd = true;
754
756 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
757
758 if( cur_model()->ContainsNickname( nickname ) )
759 {
760 if( !applyToAll )
761 {
762 // The cancel button adds the library to the table anyway
763 addDuplicates = OKOrCancelDialog( m_parent, warning, wxString::Format( msg, nickname ), detailedMsg,
764 _( "Skip" ), _( "Add Anyway" ), &applyToAll ) == wxID_CANCEL;
765 }
766
767 doAdd = addDuplicates;
768 }
769
770 if( doAdd && cur_grid()->AppendRows( 1 ) )
771 {
772 int last_row = cur_grid()->GetNumberRows() - 1;
773
774 cur_grid()->SetCellValue( last_row, COL_NICKNAME, nickname );
775 cur_grid()->SetCellValue( last_row, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
776
777 // try to use path normalized to an environmental variable or project path
778 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
779
780 // Do not use the project path in the global library table. This will almost
781 // assuredly be wrong for a different project.
782 if( m_notebook->GetSelection() == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
783 path = fn.GetFullPath();
784
785 cur_grid()->SetCellValue( last_row, COL_URI, path );
786 }
787 }
788
789 if( !files.IsEmpty() )
790 {
791 cur_grid()->MakeCellVisible( cur_grid()->GetNumberRows() - 1, COL_ENABLED );
792 cur_grid()->SetGridCursor( cur_grid()->GetNumberRows() - 1, COL_NICKNAME );
793 }
794}
795
796
798{
799 // Account for scroll bars
800 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
801
802 m_path_subs_grid->AutoSizeColumn( 0 );
803 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
804 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
805}
806
807
809{
810 adjustPathSubsGridColumns( event.GetSize().GetX() );
811
812 event.Skip();
813}
814
815
817{
818 if( !cur_grid()->CommitPendingChanges() )
819 return false;
820
821 if( !verifyTables() )
822 return false;
823
825
826 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
828 wxCHECK( optTable.has_value(), false );
829 LIBRARY_TABLE* globalTable = optTable.value();
830
831 if( get_model( 0 )->Table() != *globalTable )
832 {
833 m_parent->m_GlobalTableChanged = true;
834 *globalTable = get_model( 0 )->Table();
835
836 globalTable->Save().map_error(
837 []( const LIBRARY_ERROR& aError )
838 {
839 wxMessageBox( _( "Error saving global library table:\n\n" ) + aError.message,
840 _( "File Save Error" ), wxOK | wxICON_ERROR );
841 } );
842 }
843
845
846 if( optTable.has_value() && get_model( 1 )->Table().Path() == optTable.value()->Path() )
847 {
848 LIBRARY_TABLE* projectTable = optTable.value();
849
850 if( get_model( 1 )->Table() != *projectTable )
851 {
852 m_parent->m_ProjectTableChanged = true;
853 *projectTable = get_model( 1 )->Table();
854
855 projectTable->Save().map_error(
856 []( const LIBRARY_ERROR& aError )
857 {
858 wxMessageBox( _( "Error saving project library table:\n\n" ) + aError.message,
859 _( "File Save Error" ), wxOK | wxICON_ERROR );
860 } );
861 }
862 }
863
864 for( int ii = 0; ii < (int) m_notebook->GetPageCount(); ++ii )
865 {
866 LIB_TABLE_NOTEBOOK_PANEL* panel = static_cast<LIB_TABLE_NOTEBOOK_PANEL*>( m_notebook->GetPage( ii ) );
867
868 if( panel->GetClosable() && panel->TableModified() )
869 {
870 panel->SaveTable();
871 m_parent->m_GlobalTableChanged = true;
872 m_parent->m_ProjectTableChanged = true;
873 }
874 }
875
877 return true;
878}
879
880
884{
885 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
886 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
887
888 std::set<wxString> unique;
889
890 // clear the table
891 m_path_subs_grid->ClearRows();
892
893 for( int page = 0 ; page < (int) m_notebook->GetPageCount(); ++page )
894 {
896
897 for( int row = 0; row < model->GetNumberRows(); ++row )
898 {
899 wxString uri = model->GetValue( row, COL_URI );
900
901 while( re.Matches( uri ) )
902 {
903 wxString envvar = re.GetMatch( uri, 2 );
904
905 // if not ${...} form then must be $(...)
906 if( envvar.IsEmpty() )
907 envvar = re.GetMatch( uri, 4 );
908
909 // ignore duplicates
910 unique.insert( envvar );
911
912 // delete the last match and search again
913 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
914 }
915 }
916 }
917
918 // Make sure this special environment variable shows up even if it was
919 // not used yet. It is automatically set by KiCad to the directory holding
920 // the current project.
921 unique.insert( PROJECT_VAR_NAME );
923
924 // This special environment variable is used to locate 3d shapes
925 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_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//-----</event handlers>---------------------------------
945
946void InvokeEditDesignBlockLibTable( KIWAY* aKiway, wxWindow *aParent )
947{
948 DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Design Block Libraries" ) );
949
950 dlg.InstallPanel( new PANEL_DESIGN_BLOCK_LIB_TABLE( &dlg, &aKiway->Prj() ) );
951
952 if( dlg.ShowModal() == wxID_CANCEL )
953 return;
954
955 if( dlg.m_GlobalTableChanged )
957
958 if( dlg.m_ProjectTableChanged )
959 {
960 // Trigger a reload of the table and cancel an in-progress background load
962 }
963
964 // Trigger a load of any new block libraries
966
967 std::string payload = "";
968 aKiway->ExpressMail( FRAME_SCH, MAIL_RELOAD_LIB, payload );
969 aKiway->ExpressMail( FRAME_PCB_EDITOR, MAIL_RELOAD_LIB, payload );
970
971 return;
972}
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:315
virtual void ExpressMail(FRAME_T aDestination, MAIL_T aCommand, std::string &aPayload, wxWindow *aSource=nullptr, bool aFromOtherThread=false)
Send aPayload to aDestination from aSource.
Definition kiway.cpp:500
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:205
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 void AppendRowHandler(WX_GRID *aGrid)
static bool VerifyTable(WX_GRID *aGrid, bool aSupportsVisibilityColumn, std::function< void(int aRow, int aCol)> aErrorHandler)
static void MoveDownHandler(WX_GRID *aGrid)
static void AddTable(wxAuiNotebook *aNotebook, const wxString &aTitle, bool aClosable)
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
void onNotebookPageChangeRequest(wxAuiNotebookEvent &aEvent)
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:887
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition pgm_base.cpp:787
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:132
Container for project specific data.
Definition project.h:66
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:644
This file contains miscellaneous commonly used macros and functions.
@ MAIL_RELOAD_LIB
Definition mail_type.h:57
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:77
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:435
void InvokeEditDesignBlockLibTable(KIWAY *aKiway, wxWindow *aParent)
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
std::vector< std::vector< std::string > > table
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.