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/* TODO:
26
27*) After any change to uri, reparse the environment variables.
28
29*/
30
31
32#include <set>
33#include <wx/dir.h>
34#include <wx/log.h>
35#include <wx/regex.h>
36#include <wx/grid.h>
37#include <wx/dirdlg.h>
38#include <wx/filedlg.h>
39#include <wx/msgdlg.h>
40
41#include <common.h>
42#include <project.h>
43#include <env_vars.h>
44#include <lib_id.h>
45#include <lib_table_base.h>
46#include <bitmaps.h>
48#include <widgets/wx_grid.h>
50#include <confirm.h>
51#include <lib_table_grid.h>
53#include <pgm_base.h>
54#include <env_paths.h>
59#include <kiway.h>
60#include <kiway_express.h>
65#include <paths.h>
66#include <macros.h>
68
69// clang-format off
70
83
84// clang-format on
85
90class LIBRARY_TRAVERSER : public wxDirTraverser
91{
92public:
93 LIBRARY_TRAVERSER( std::vector<std::string> aSearchExtensions, wxString aInitialDir ) :
94 m_searchExtensions( aSearchExtensions ), m_currentDir( aInitialDir )
95 {
96 }
97
98 virtual wxDirTraverseResult OnFile( const wxString& aFileName ) override
99 {
100 wxFileName file( aFileName );
101
102 for( const std::string& ext : m_searchExtensions )
103 {
104 if( file.GetExt().IsSameAs( ext, false ) )
105 m_foundDirs.insert( { m_currentDir, 1 } );
106 }
107
108 return wxDIR_CONTINUE;
109 }
110
111 virtual wxDirTraverseResult OnOpenError( const wxString& aOpenErrorName ) override
112 {
113 m_failedDirs.insert( { aOpenErrorName, 1 } );
114 return wxDIR_IGNORE;
115 }
116
117 bool HasDirectoryOpenFailures() { return m_failedDirs.size() > 0; }
118
119 virtual wxDirTraverseResult OnDir( const wxString& aDirName ) override
120 {
121 m_currentDir = aDirName;
122 return wxDIR_CONTINUE;
123 }
124
125 void GetPaths( wxArrayString& aPathArray )
126 {
127 for( std::pair<const wxString, int>& foundDirsPair : m_foundDirs )
128 aPathArray.Add( foundDirsPair.first );
129 }
130
131 void GetFailedPaths( wxArrayString& aPathArray )
132 {
133 for( std::pair<const wxString, int>& failedDirsPair : m_failedDirs )
134 aPathArray.Add( failedDirsPair.first );
135 }
136
137private:
138 std::vector<std::string> m_searchExtensions;
139 wxString m_currentDir;
140 std::unordered_map<wxString, int> m_foundDirs;
141 std::unordered_map<wxString, int> m_failedDirs;
142};
143
144
149{
152
153public:
155 LIB_TABLE_GRID( aTableToEdit )
156 {
157 }
158
159 void SetValue( int aRow, int aCol, const wxString& aValue ) override
160 {
161 wxCHECK( aRow < (int) size(), /* void */ );
162
163 LIB_TABLE_GRID::SetValue( aRow, aCol, aValue );
164
165 // If setting a filepath, attempt to auto-detect the format
166 if( aCol == COL_URI )
167 {
168 LIBRARY_TABLE_ROW& row = at( static_cast<size_t>( aRow ) );
169 wxString uri = LIBRARY_MANAGER::ExpandURI( row.URI(), Pgm().GetSettingsManager().Prj() );
170
173
174 if( pluginType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
176
177 SetValue( aRow, COL_TYPE, DESIGN_BLOCK_IO_MGR::ShowType( pluginType ) );
178 }
179 }
180};
181
182
184{
185public:
187 LIB_TABLE_GRID_TRICKS( aGrid ),
188 m_dialog( aParent )
189 {
190 }
191
192protected:
194
195 void optionsEditor( int aRow ) override
196 {
197 auto tbl = static_cast<DESIGN_BLOCK_LIB_TABLE_GRID*>( m_grid->GetTable() );
198
199 if( tbl->GetNumberRows() > aRow )
200 {
201 LIBRARY_TABLE_ROW& row = tbl->at( static_cast<size_t>( aRow ) );
202 const wxString& options = row.Options();
203 wxString result = options;
204 std::map<std::string, UTF8> choices;
205
208 pi->GetLibraryOptions( &choices );
209
210 DIALOG_PLUGIN_OPTIONS dlg( m_dialog, row.Nickname(), choices, options, &result );
211 dlg.ShowModal();
212
213 if( options != result )
214 {
215 row.SetOptions( result );
216 m_grid->Refresh();
217 }
218 }
219 }
220
223 void paste_text( const wxString& cb_text ) override
224 {
225 auto tbl = static_cast<DESIGN_BLOCK_LIB_TABLE_GRID*>( m_grid->GetTable() );
226 size_t ndx = cb_text.find( "(design_block_lib_table" );
227
228 if( ndx != std::string::npos )
229 {
230 // paste the DESIGN_BLOCK_LIB_TABLE_ROWs of s-expression (design_block_lib_table),
231 // starting at column 0 regardless of current cursor column.
232
233 if( LIBRARY_TABLE tempTable( cb_text, tbl->Table().Scope() ); tempTable.IsOk() )
234 {
235 std::ranges::copy( tempTable.Rows(),
236 std::inserter( tbl->Table().Rows(), tbl->Table().Rows().begin() ) );
237
238 if( tbl->GetView() )
239 {
240 wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, 0, 0 );
241 tbl->GetView()->ProcessTableMessage( msg );
242 m_grid->AutoSizeColumns( false );
243 }
244 }
245 else
246 {
247 DisplayError( m_dialog, tempTable.ErrorDescription() );
248 }
249 }
250 else
251 {
252 // paste spreadsheet formatted text.
253 GRID_TRICKS::paste_text( cb_text );
254
255 m_grid->AutoSizeColumns( false );
256 }
257 }
258};
259
260
262 PROJECT* aProject ) :
264 m_project( aProject ),
265 m_parent( aParent )
266{
267 std::optional<LIBRARY_TABLE*> table = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
269 wxASSERT( table );
270
271 m_global_grid->SetTable( new DESIGN_BLOCK_LIB_TABLE_GRID( *table.value() ), true );
272
273 // add Cut, Copy, and Paste to wxGrids
274 m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
275
277
278 wxArrayString choices;
279
280 // There aren't (yet) any legacy DesignBlock libraries to migrate
281 m_migrate_libs_button->Hide();
282
283 for( auto& [fileType, desc] : m_supportedDesignBlockFiles )
284 choices.Add( DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
285
287
288 if( cfg->m_lastDesignBlockLibDir.IsEmpty() )
290
291 m_lastProjectLibDir = m_project->GetProjectPath();
292
293 auto autoSizeCol =
294 [&]( WX_GRID* aGrid, int aCol )
295 {
296 int prevWidth = aGrid->GetColSize( aCol );
297
298 aGrid->AutoSizeColumn( aCol, false );
299 aGrid->SetColSize( aCol, std::max( prevWidth, aGrid->GetColSize( aCol ) ) );
300 };
301
302 auto setupGrid =
303 [&]( WX_GRID* aGrid )
304 {
305 // add Cut, Copy, and Paste to wxGrids
306 aGrid->PushEventHandler( new DESIGN_BLOCK_GRID_TRICKS( m_parent, aGrid ) );
307
308 aGrid->SetSelectionMode( wxGrid::wxGridSelectRows );
309
310 wxGridCellAttr* attr = new wxGridCellAttr;
311
312 if( cfg )
313 {
314 attr->SetEditor( new GRID_CELL_PATH_EDITOR(
315 m_parent, aGrid, &cfg->m_lastDesignBlockLibDir, true, m_project->GetProjectPath(),
316 [this]( WX_GRID* grid, int row ) -> wxString
317 {
318 auto* libTable = static_cast<DESIGN_BLOCK_LIB_TABLE_GRID*>( grid->GetTable() );
319 LIBRARY_TABLE_ROW& tableRow = libTable->at( row );
320 DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T fileType =
321 DESIGN_BLOCK_IO_MGR::EnumFromStr( tableRow.Type() );
322 const IO_BASE::IO_FILE_DESC& pluginDesc = m_supportedDesignBlockFiles.at( fileType );
323
324 if( pluginDesc.m_IsFile )
325 return pluginDesc.FileFilter();
326 else
327 return wxEmptyString;
328 } ) );
329 }
330
331 aGrid->SetColAttr( COL_URI, attr );
332
333 attr = new wxGridCellAttr;
334 attr->SetEditor( new wxGridCellChoiceEditor( choices ) );
335 aGrid->SetColAttr( COL_TYPE, attr );
336
337 attr = new wxGridCellAttr;
338 attr->SetRenderer( new wxGridCellBoolRenderer() );
339 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
340 aGrid->SetColAttr( COL_ENABLED, attr );
341
342 // No visibility control for design block libraries yet; this feature is primarily
343 // useful for database libraries and it's only implemented for schematic symbols
344 // at the moment.
345 aGrid->HideCol( COL_VISIBLE );
346
347 // all but COL_OPTIONS, which is edited with Option Editor anyways.
348 autoSizeCol( aGrid, COL_NICKNAME );
349 autoSizeCol( aGrid, COL_TYPE );
350 autoSizeCol( aGrid, COL_URI );
351 autoSizeCol( aGrid, COL_DESCR );
352
353 // Gives a selection to each grid, mainly for delete button. wxGrid's wake up with
354 // a currentCell which is sometimes not highlighted.
355 if( aGrid->GetNumberRows() > 0 )
356 aGrid->SelectRow( 0 );
357 };
358
359 setupGrid( m_global_grid );
360
362
363 std::optional<LIBRARY_TABLE*> projectTable = Pgm().GetLibraryManager().Table( LIBRARY_TABLE_TYPE::DESIGN_BLOCK,
365
366 if( projectTable )
367 {
368 m_project_grid->SetTable( new DESIGN_BLOCK_LIB_TABLE_GRID( *projectTable.value() ), true );
369 setupGrid( m_project_grid );
370 }
371 else
372 {
373 m_pageNdx = 0;
374 m_notebook->DeletePage( 1 );
375 m_project_grid = nullptr;
376 }
377
378 m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
379 m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
380
381 // select the last selected page
382 m_notebook->SetSelection( m_pageNdx );
384
385 // for ALT+A handling, we want the initial focus to be on the first selected grid.
386 m_parent->SetInitialFocus( m_cur_grid );
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 auto joinExts =
408 []( const std::vector<std::string>& aExts )
409 {
410 wxString joined;
411
412 for( const std::string& ext : aExts )
413 {
414 if( !joined.empty() )
415 joined << wxS( ", " );
416
417 joined << wxS( "*." ) << ext;
418 }
419
420 return joined;
421 };
422
423 for( auto& [type, desc] : m_supportedDesignBlockFiles )
424 {
425 wxString entryStr = DESIGN_BLOCK_IO_MGR::ShowType( type );
426
427 if( desc.m_IsFile && !desc.m_FileExtensions.empty() )
428 {
429 entryStr << wxString::Format( wxS( " (%s)" ), joinExts( desc.m_FileExtensions ) );
430 }
431 else if( !desc.m_IsFile && !desc.m_ExtensionsInDir.empty() )
432 {
433 wxString midPart = wxString::Format( _( "folder with %s files" ), joinExts( desc.m_ExtensionsInDir ) );
434
435 entryStr << wxString::Format( wxS( " (%s)" ), midPart );
436 }
437
438 browseMenu->Append( type, entryStr );
439
440 browseMenu->Bind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
441 this, type );
442 }
443
444 Layout();
445
446 // This is the button only press for the browse button instead of the menu
448}
449
450
452{
453 wxMenu* browseMenu = m_browseButton->GetSplitButtonMenu();
454
455 for( auto& [type, desc] : m_supportedDesignBlockFiles )
456 {
457 browseMenu->Unbind( wxEVT_COMMAND_MENU_SELECTED, &PANEL_DESIGN_BLOCK_LIB_TABLE::browseLibrariesHandler,
458 this, type );
459 }
460
462
463 // Delete the GRID_TRICKS.
464 // Any additional event handlers should be popped before the window is deleted.
465 m_global_grid->PopEventHandler( true );
466
467 if( m_project_grid )
468 m_project_grid->PopEventHandler( true );
469
470 m_path_subs_grid->PopEventHandler( true );
471}
472
473
475{
477 {
479
480 if( !pi )
481 continue;
482
483 if( const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryDesc() )
484 m_supportedDesignBlockFiles.emplace( type, desc );
485 }
486}
487
488
490{
491 wxString msg;
492
494 {
495 if( !model )
496 continue;
497
498 for( int r = 0; r < model->GetNumberRows(); )
499 {
500 wxString nick = model->GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
501 wxString uri = model->GetValue( r, COL_URI ).Trim( false ).Trim();
502 unsigned illegalCh = 0;
503
504 if( !nick || !uri )
505 {
506 if( !nick && !uri )
507 msg = _( "A library table row nickname and path cells are empty." );
508 else if( !nick )
509 msg = _( "A library table row nickname cell is empty." );
510 else
511 msg = _( "A library table row path cell is empty." );
512
513 wxWindow* topLevelParent = wxGetTopLevelParent( this );
514
515 wxMessageDialog badCellDlg( topLevelParent, msg, _( "Invalid Row Definition" ),
516 wxYES_NO | wxCENTER | wxICON_QUESTION | wxYES_DEFAULT );
517 badCellDlg.SetExtendedMessage( _( "Empty cells will result in all rows that are "
518 "invalid to be removed from the table." ) );
519 badCellDlg.SetYesNoLabels( wxMessageDialog::ButtonLabel( _( "Remove Invalid Cells" ) ),
520 wxMessageDialog::ButtonLabel( _( "Cancel Table Update" ) ) );
521
522 if( badCellDlg.ShowModal() == wxID_NO )
523 return false;
524
525 // Delete the "empty" row, where empty means missing nick or uri.
526 // This also updates the UI which could be slow, but there should only be a few
527 // rows to delete, unless the user fell asleep on the Add Row
528 // button.
529 model->GetView()->ClearSelection();
530 model->DeleteRows( r, 1 );
531 }
532 else if( ( illegalCh = LIB_ID::FindIllegalLibraryNameChar( nick ) ) )
533 {
534 msg = wxString::Format( _( "Illegal character '%c' in nickname '%s'." ), illegalCh, nick );
535
536 // show the tabbed panel holding the grid we have flunked:
537 if( model != cur_model() )
538 m_notebook->SetSelection( model == global_model() ? 0 : 1 );
539
540 model->GetView()->MakeCellVisible( r, 0 );
541 model->GetView()->SetGridCursor( r, 1 );
542
543 wxWindow* topLevelParent = wxGetTopLevelParent( this );
544
545 wxMessageDialog errdlg( topLevelParent, msg, _( "Library Nickname Error" ) );
546 errdlg.ShowModal();
547 return false;
548 }
549 else
550 {
551 // set the trimmed values back into the table so they get saved to disk.
552 model->SetValue( r, COL_NICKNAME, nick );
553 model->SetValue( r, COL_URI, uri );
554
555 // Make sure to not save a hidden flag
556 model->SetValue( r, COL_VISIBLE, wxS( "1" ) );
557
558 ++r; // this row was OK.
559 }
560 }
561 }
562
563 // check for duplicate nickNames, separately in each table.
565 {
566 if( !model )
567 continue;
568
569 for( int r1 = 0; r1 < model->GetNumberRows() - 1; ++r1 )
570 {
571 wxString nick1 = model->GetValue( r1, COL_NICKNAME );
572
573 for( int r2 = r1 + 1; r2 < model->GetNumberRows(); ++r2 )
574 {
575 wxString nick2 = model->GetValue( r2, COL_NICKNAME );
576
577 if( nick1 == nick2 )
578 {
579 msg = wxString::Format( _( "Multiple libraries cannot share the same nickname ('%s')." ),
580 nick1 );
581
582 // show the tabbed panel holding the grid we have flunked:
583 if( model != cur_model() )
584 m_notebook->SetSelection( model == global_model() ? 0 : 1 );
585
586 // go to the lower of the two rows, it is technically the duplicate:
587 m_cur_grid->MakeCellVisible( r2, 0 );
588 m_cur_grid->SetGridCursor( r2, 1 );
589
590 wxWindow* topLevelParent = wxGetTopLevelParent( this );
591
592 wxMessageDialog errdlg( topLevelParent, msg, _( "Library Nickname Error" ) );
593 errdlg.ShowModal();
594 return false;
595 }
596 }
597 }
598 }
599
600 return true;
601}
602
603
604void PANEL_DESIGN_BLOCK_LIB_TABLE::OnUpdateUI( wxUpdateUIEvent& event )
605{
606 m_pageNdx = (unsigned) std::max( 0, m_notebook->GetSelection() );
608}
609
610
612{
613 m_cur_grid->OnAddRow(
614 [&]() -> std::pair<int, int>
615 {
616 m_cur_grid->AppendRows( 1 );
617 return { m_cur_grid->GetNumberRows() - 1, COL_NICKNAME };
618 } );
619}
620
621
623{
624 if( !m_cur_grid->CommitPendingChanges() )
625 return;
626
627 wxGridUpdateLocker noUpdates( m_cur_grid );
628
629 int curRow = m_cur_grid->GetGridCursorRow();
630 int curCol = m_cur_grid->GetGridCursorCol();
631
632 // In a wxGrid, collect rows that have a selected cell, or are selected
633 // It is not so easy: it depends on the way the selection was made.
634 // Here, we collect rows selected by clicking on a row label, and rows that contain any
635 // previously-selected cells.
636 // If no candidate, just delete the row with the grid cursor.
637 wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
638 wxGridCellCoordsArray cells = m_cur_grid->GetSelectedCells();
639 wxGridCellCoordsArray blockTopLeft = m_cur_grid->GetSelectionBlockTopLeft();
640 wxGridCellCoordsArray blockBotRight = m_cur_grid->GetSelectionBlockBottomRight();
641
642 // Add all row having cell selected to list:
643 for( unsigned ii = 0; ii < cells.GetCount(); ii++ )
644 selectedRows.Add( cells[ii].GetRow() );
645
646 // Handle block selection
647 if( !blockTopLeft.IsEmpty() && !blockBotRight.IsEmpty() )
648 {
649 for( int i = blockTopLeft[0].GetRow(); i <= blockBotRight[0].GetRow(); ++i )
650 selectedRows.Add( i );
651 }
652
653 // Use the row having the grid cursor only if we have no candidate:
654 if( selectedRows.size() == 0 && m_cur_grid->GetGridCursorRow() >= 0 )
655 selectedRows.Add( m_cur_grid->GetGridCursorRow() );
656
657 if( selectedRows.size() == 0 )
658 {
659 wxBell();
660 return;
661 }
662
663 std::sort( selectedRows.begin(), selectedRows.end() );
664
665 // Remove selected rows (note: a row can be stored more than once in list)
666 int last_row = -1;
667
668 // Needed to avoid a wxWidgets alert if the row to delete is the last row
669 // at least on wxMSW 3.2
670 m_cur_grid->ClearSelection();
671
672 for( int ii = selectedRows.GetCount() - 1; ii >= 0; ii-- )
673 {
674 int row = selectedRows[ii];
675
676 if( row != last_row )
677 {
678 last_row = row;
679 m_cur_grid->DeleteRows( row, 1 );
680 }
681 }
682
683 if( m_cur_grid->GetNumberRows() > 0 && curRow >= 0 )
684 m_cur_grid->SetGridCursor( std::min( curRow, m_cur_grid->GetNumberRows() - 1 ), curCol );
685}
686
687
689{
690 m_cur_grid->OnMoveRowUp(
691 [&]( int row )
692 {
694 int curRow = m_cur_grid->GetGridCursorRow();
695
696 std::vector<LIBRARY_TABLE_ROW>& rows = tbl->Table().Rows();
697
698 auto current = rows.begin() + curRow;
699 auto prev = rows.begin() + curRow - 1;
700
701 std::iter_swap( current, prev );
702
703 // Update the wxGrid
704 wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, row - 1, 0 );
705 tbl->GetView()->ProcessTableMessage( msg );
706 } );
707}
708
709
711{
712 m_cur_grid->OnMoveRowDown(
713 [&]( int row )
714 {
716 int curRow = m_cur_grid->GetGridCursorRow();
717 std::vector<LIBRARY_TABLE_ROW>& rows = tbl->Table().Rows();
718
719 auto current = rows.begin() + curRow;
720 auto next = rows.begin() + curRow + 1;
721
722 std::iter_swap( current, next );
723
724 // Update the wxGrid
725 wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, row, 0 );
726 tbl->GetView()->ProcessTableMessage( msg );
727 } );
728}
729
730
731// @todo refactor this function into single location shared with PANEL_SYM_LIB_TABLE
733{
734 if( !m_cur_grid->CommitPendingChanges() )
735 return;
736
737 wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
738
739 if( selectedRows.empty() && m_cur_grid->GetGridCursorRow() >= 0 )
740 selectedRows.push_back( m_cur_grid->GetGridCursorRow() );
741
742 wxArrayInt rowsToMigrate;
744 wxString msg;
745
746 for( int row : selectedRows )
747 {
748 if( m_cur_grid->GetCellValue( row, COL_TYPE ) != kicadType )
749 rowsToMigrate.push_back( row );
750 }
751
752 if( rowsToMigrate.size() <= 0 )
753 {
754 wxMessageBox( wxString::Format( _( "Select one or more rows containing libraries "
755 "to save as current KiCad format." ) ) );
756 return;
757 }
758 else
759 {
760 if( rowsToMigrate.size() == 1 )
761 {
762 msg.Printf( _( "Save '%s' as current KiCad format and replace entry in table?" ),
763 m_cur_grid->GetCellValue( rowsToMigrate[0], COL_NICKNAME ) );
764 }
765 else
766 {
767 msg.Printf( _( "Save %d libraries as current KiCad format and replace entries in table?" ),
768 (int) rowsToMigrate.size() );
769 }
770
771 if( !IsOK( m_parent, msg ) )
772 return;
773 }
774
775 for( int row : rowsToMigrate )
776 {
777 wxString libName = m_cur_grid->GetCellValue( row, COL_NICKNAME );
778 wxString relPath = m_cur_grid->GetCellValue( row, COL_URI );
779 wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
780 wxFileName legacyLib( resolvedPath );
781
782 if( !legacyLib.Exists() )
783 {
784 msg.Printf( _( "Library '%s' not found." ), relPath );
785 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
786 continue;
787 }
788
789 wxFileName newLib( resolvedPath );
790 newLib.AppendDir( newLib.GetName() + "." + FILEEXT::KiCadDesignBlockLibPathExtension );
791 newLib.SetName( "" );
792 newLib.ClearExt();
793
794 if( newLib.DirExists() )
795 {
796 msg.Printf( _( "Folder '%s' already exists. Do you want overwrite any existing design "
797 "blocks?" ),
798 newLib.GetFullPath() );
799
800 switch( wxMessageBox( msg, _( "Migrate Library" ), wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
801 {
802 case wxYES: break;
803 case wxNO: continue;
804 case wxCANCEL: return;
805 }
806 }
807
808 wxString options = m_cur_grid->GetCellValue( row, COL_OPTIONS );
809 std::map<std::string, UTF8> props( LIB_TABLE::ParseOptions( options.ToStdString() ) );
810
811 if( DESIGN_BLOCK_IO_MGR::ConvertLibrary( &props, legacyLib.GetFullPath(),
812 newLib.GetFullPath() ) )
813 {
814 relPath =
815 NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(), m_project );
816
817 // Do not use the project path in the global library table. This will almost
818 // assuredly be wrong for a different project.
819 if( m_cur_grid == m_global_grid && relPath.Contains( "${KIPRJMOD}" ) )
820 relPath = newLib.GetFullPath();
821
822 m_cur_grid->SetCellValue( row, COL_URI, relPath );
823 m_cur_grid->SetCellValue( row, COL_TYPE, kicadType );
824 }
825 else
826 {
827 msg.Printf( _( "Failed to save design block library file '%s'." ), newLib.GetFullPath() );
828 DisplayErrorMessage( wxGetTopLevelParent( this ), msg );
829 }
830 }
831}
832
833
835{
836 if( !m_cur_grid->CommitPendingChanges() )
837 return;
838
840
841 // We are bound both to the menu and button with this one handler
842 // So we must set the file type based on it
843 if( event.GetEventType() == wxEVT_BUTTON )
844 {
845 // Let's default to adding a kicad design block file for just the design block
847 }
848 else
849 {
850 fileType = static_cast<DESIGN_BLOCK_IO_MGR::DESIGN_BLOCK_FILE_T>( event.GetId() );
851 }
852
854 {
855 wxLogWarning( wxT( "File type selection event received but could not find the file type in the table" ) );
856 return;
857 }
858
861
862 wxString title = wxString::Format( _( "Select %s Library" ), DESIGN_BLOCK_IO_MGR::ShowType( fileType ) );
863 wxString dummy;
864 wxString* lastDir;
865
867 lastDir = &m_lastProjectLibDir;
868 else
869 lastDir = cfg ? &cfg->m_lastDesignBlockLibDir : &dummy;
870
871 wxArrayString files;
872 wxWindow* topLevelParent = wxGetTopLevelParent( this );
873
874 if( fileDesc.m_IsFile )
875 {
876 wxFileDialog dlg( topLevelParent, title, *lastDir, wxEmptyString, fileDesc.FileFilter(),
877 wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
878
879 if( dlg.ShowModal() == wxID_CANCEL )
880 return;
881
882 dlg.GetPaths( files );
883 *lastDir = dlg.GetDirectory();
884 }
885 else
886 {
887 wxDirDialog dlg( topLevelParent, title, *lastDir,
888 wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST | wxDD_MULTIPLE );
889
890 if( dlg.ShowModal() == wxID_CANCEL )
891 return;
892
893 dlg.GetPaths( files );
894
895 if( !files.IsEmpty() )
896 {
897 wxFileName first( files.front() );
898 *lastDir = first.GetPath();
899 }
900 }
901
902 // Drop the last directory if the path is a .pretty folder
904 cfg->m_lastDesignBlockLibDir = cfg->m_lastDesignBlockLibDir.BeforeLast( wxFileName::GetPathSeparator() );
905
906 const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
907 bool addDuplicates = false;
908 bool applyToAll = false;
909 wxString warning = _( "Warning: Duplicate Nicknames" );
910 wxString msg = _( "A library nicknamed '%s' already exists." );
911 wxString detailedMsg = _( "One of the nicknames will need to be changed after "
912 "adding this library." );
913
914 for( const wxString& filePath : files )
915 {
916 wxFileName fn( filePath );
917 wxString nickname = LIB_ID::FixIllegalChars( fn.GetName(), true );
918 bool doAdd = true;
919
921 nickname = LIB_ID::FixIllegalChars( fn.GetFullName(), true ).wx_str();
922
923 if( cur_model()->ContainsNickname( nickname ) )
924 {
925 if( !applyToAll )
926 {
927 // The cancel button adds the library to the table anyway
928 addDuplicates = OKOrCancelDialog( wxGetTopLevelParent( this ), warning,
929 wxString::Format( msg, nickname ), detailedMsg,
930 _( "Skip" ), _( "Add Anyway" ), &applyToAll )
931 == wxID_CANCEL;
932 }
933
934 doAdd = addDuplicates;
935 }
936
937 if( doAdd && m_cur_grid->AppendRows( 1 ) )
938 {
939 int last_row = m_cur_grid->GetNumberRows() - 1;
940
941 m_cur_grid->SetCellValue( last_row, COL_NICKNAME, nickname );
942
943 m_cur_grid->SetCellValue( last_row, COL_TYPE,
945
946 // try to use path normalized to an environmental variable or project path
947 wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
948
949 // Do not use the project path in the global library table. This will almost
950 // assuredly be wrong for a different project.
951 if( m_pageNdx == 0 && path.Contains( wxT( "${KIPRJMOD}" ) ) )
952 path = fn.GetFullPath();
953
954 m_cur_grid->SetCellValue( last_row, COL_URI, path );
955 }
956 }
957
958 if( !files.IsEmpty() )
959 {
960 int new_row = m_cur_grid->GetNumberRows() - 1;
961 m_cur_grid->MakeCellVisible( new_row, m_cur_grid->GetGridCursorCol() );
962 m_cur_grid->SetGridCursor( new_row, m_cur_grid->GetGridCursorCol() );
963 }
964}
965
966
968{
969 // Account for scroll bars
970 aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
971
972 m_path_subs_grid->AutoSizeColumn( 0 );
973 m_path_subs_grid->SetColSize( 0, std::max( 72, m_path_subs_grid->GetColSize( 0 ) ) );
974 m_path_subs_grid->SetColSize( 1, std::max( 120, aWidth - m_path_subs_grid->GetColSize( 0 ) ) );
975}
976
977
979{
980 adjustPathSubsGridColumns( event.GetSize().GetX() );
981
982 event.Skip();
983}
984
985
987{
988 if( !m_cur_grid->CommitPendingChanges() )
989 return false;
990
991 if( !verifyTables() )
992 return false;
993
994 std::optional<LIBRARY_TABLE*> optTable =
996 wxCHECK( optTable, false );
997 LIBRARY_TABLE* globalTable = *optTable;
998
999 if( global_model()->Table() != *globalTable )
1000 {
1001 m_parent->m_GlobalTableChanged = true;
1002 *globalTable = global_model()->Table();
1003 }
1004
1006
1007 if( optTable && project_model() )
1008 {
1009 LIBRARY_TABLE* projectTable = *optTable;
1010
1011 if( project_model()->Table() != *projectTable )
1012 {
1013 m_parent->m_ProjectTableChanged = true;
1014 *projectTable = project_model()->Table();
1015 }
1016 }
1017
1018 return true;
1019}
1020
1021
1025{
1026 wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
1027 wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
1028
1029 std::set<wxString> unique;
1030
1031 // clear the table
1032 m_path_subs_grid->ClearRows();
1033
1035 {
1036 if( !tbl )
1037 continue;
1038
1039 for( int row = 0; row < tbl->GetNumberRows(); ++row )
1040 {
1041 wxString uri = tbl->GetValue( row, COL_URI );
1042
1043 while( re.Matches( uri ) )
1044 {
1045 wxString envvar = re.GetMatch( uri, 2 );
1046
1047 // if not ${...} form then must be $(...)
1048 if( envvar.IsEmpty() )
1049 envvar = re.GetMatch( uri, 4 );
1050
1051 // ignore duplicates
1052 unique.insert( envvar );
1053
1054 // delete the last match and search again
1055 uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
1056 }
1057 }
1058 }
1059
1060 // Make sure this special environment variable shows up even if it was
1061 // not used yet. It is automatically set by KiCad to the directory holding
1062 // the current project.
1063 unique.insert( PROJECT_VAR_NAME );
1065
1066 // This special environment variable is used to locate 3d shapes
1067 unique.insert( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
1068
1069 for( const wxString& evName : unique )
1070 {
1071 int row = m_path_subs_grid->GetNumberRows();
1072 m_path_subs_grid->AppendRows( 1 );
1073
1074 m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
1075 m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
1076
1077 wxString evValue;
1078 wxGetEnv( evName, &evValue );
1079 m_path_subs_grid->SetCellValue( row, 1, evValue );
1080 m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
1081 }
1082
1083 adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
1084}
1085
1086//-----</event handlers>---------------------------------
1087
1089
1090
1091void InvokeEditDesignBlockLibTable( KIWAY* aKiway, wxWindow *aParent )
1092{
1093 wxString projectTablePath = aKiway->Prj().DesignBlockLibTblName();
1094 wxString msg;
1095
1096 DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Design Block Libraries" ) );
1097
1098 dlg.InstallPanel( new PANEL_DESIGN_BLOCK_LIB_TABLE( &dlg, &aKiway->Prj() ) );
1099
1100 if( dlg.ShowModal() == wxID_CANCEL )
1101 return;
1102
1103 if( dlg.m_GlobalTableChanged )
1104 {
1105 std::optional<LIBRARY_TABLE*> optTable =
1107 wxCHECK( optTable, /* void */ );
1108 LIBRARY_TABLE* globalTable = *optTable;
1109
1110 globalTable->Save().map_error(
1111 []( const LIBRARY_ERROR& aError )
1112 {
1113 wxMessageBox( wxString::Format( _( "Error saving global library table:\n\n%s" ), aError.message ),
1114 _( "File Save Error" ), wxOK | wxICON_ERROR );
1115 } );
1116
1118 }
1119
1120 std::optional<LIBRARY_TABLE*> projectTable =
1122
1123 if( projectTable && dlg.m_ProjectTableChanged )
1124 {
1125 ( *projectTable )->Save().map_error(
1126 []( const LIBRARY_ERROR& aError )
1127 {
1128 wxMessageBox( wxString::Format( _( "Error saving project-specific library table:\n\n%s" ),
1129 aError.message ),
1130 _( "File Save Error" ), wxOK | wxICON_ERROR );
1131 } );
1132
1133 // Trigger a reload of the table and cancel an in-progress background load
1135 }
1136
1137 // Trigger a load of any new block libraries
1138 Pgm().PreloadDesignBlockLibraries( aKiway );
1139
1140 std::string payload = "";
1141 aKiway->ExpressMail( FRAME_SCH, MAIL_RELOAD_LIB, payload );
1142 aKiway->ExpressMail( FRAME_PCB_EDITOR, MAIL_RELOAD_LIB, payload );
1143
1144 return;
1145}
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:110
void paste_text(const wxString &cb_text) override
handle specialized clipboard text, with leading "(design_block_lib_table", OR spreadsheet formatted t...
DIALOG_EDIT_LIBRARY_TABLES * m_dialog
DESIGN_BLOCK_GRID_TRICKS(DIALOG_EDIT_LIBRARY_TABLES *aParent, WX_GRID *aGrid)
@ KICAD_SEXP
S-expression KiCad file format.
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.
DESIGN_BLOCK_LIB_TABLE_GRID(const LIBRARY_TABLE &aTableToEdit)
void SetValue(int aRow, int aCol, const wxString &aValue) override
An options editor in the form of a two column name/value spreadsheet like (table) UI.
int ShowModal() override
Editor for wxGrid cells that adds a file/folder browser to the grid input field.
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
Definition grid_tricks.h:61
virtual void paste_text(const wxString &cb_text)
WX_GRID * m_grid
I don't own the grid, but he owns me.
wxString m_lastDesignBlockLibDir
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:292
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
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
const wxString & URI() const
const wxString & Nickname() const
const wxString & Options() const
LIBRARY_RESULT< void > Save()
bool IsOk() const
const std::vector< LIBRARY_TABLE_ROW > & Rows() const
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 unsigned FindIllegalLibraryNameChar(const UTF8 &aLibraryName)
Looks for characters that are illegal in library nicknames.
Definition lib_id.cpp:241
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:192
LIB_TABLE_GRID_TRICKS(WX_GRID *aGrid)
LIBRARY_TABLE & Table()
LIB_TABLE_GRID(const LIBRARY_TABLE &aTableToEdit, LIBRARY_MANAGER_ADAPTER *aAdapter=nullptr)
void SetValue(int aRow, int aCol, const wxString &aValue) override
virtual size_t size() const
virtual LIBRARY_TABLE_ROW & at(size_t aIndex)
static std::map< std::string, UTF8 > ParseOptions(const std::string &aOptionsList)
Parses aOptionsList and places the result into a #PROPERTIES object which is returned.
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
DESIGN_BLOCK_LIB_TABLE_GRID * project_model() const
void browseLibrariesHandler(wxCommandEvent &event)
void populateEnvironReadOnlyTable()
Populate the readonly environment variable table with names and values by examining all the full_uri ...
DESIGN_BLOCK_LIB_TABLE_GRID * cur_model() const
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 OnUpdateUI(wxUpdateUIEvent &event) override
void appendRowHandler(wxCommandEvent &event) override
PANEL_DESIGN_BLOCK_LIB_TABLE(DIALOG_EDIT_LIBRARY_TABLES *aParent, PROJECT *aProject)
DESIGN_BLOCK_LIB_TABLE_GRID * global_model() const
void onSizeGrid(wxSizeEvent &event) override
void deleteRowHandler(wxCommandEvent &event) override
bool verifyTables()
Trim important fields, removes blank row entries, and checks for duplicates.
static wxString GetDefaultUserDesignBlocksPath()
Gets the default path we point users to create projects.
Definition paths.cpp:103
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
Definition pgm_base.cpp:871
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition pgm_base.cpp:783
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:130
Container for project specific data.
Definition project.h:66
virtual const wxString DesignBlockLibTblName() const
Return the path and file name of this projects design block library table.
Definition project.cpp:201
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:365
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
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:177
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
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:623
@ COL_DESCR
@ COL_NICKNAME
@ COL_OPTIONS
@ COL_ENABLED
@ COL_URI
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.
Definition pgm_base.cpp:946
see class PGM_BASE
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition project.h:41
CITER next(CITER it)
Definition ptree.cpp:124
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:45
bool m_IsFile
Whether the library is a folder or a file.
Definition io_base.h:53
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.
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.