KiCad PCB EDA Suite
panel_sym_lib_table.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2017 Wayne Stambaugh <stambaughw@gmail.com>
5  * Copyright (C) 2021 CERN
6  * Copyright (C) 2017-2021 KiCad Developers, see AUTHORS.txt for contributors.
7  *
8  * This program is free software: you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by the
10  * Free Software Foundation, either version 3 of the License, or (at your
11  * option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program. If not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include <set>
23 #include <wx/regex.h>
24 
25 #include <project.h>
26 #include <panel_sym_lib_table.h>
27 #include <lib_id.h>
28 #include <symbol_lib_table.h>
29 #include <lib_table_lexer.h>
30 #include <grid_tricks.h>
31 #include <widgets/wx_grid.h>
32 #include <confirm.h>
33 #include <bitmaps.h>
34 #include <lib_table_grid.h>
36 #include <env_paths.h>
37 #include <eeschema_id.h>
38 #include <symbol_edit_frame.h>
39 #include <symbol_viewer_frame.h>
40 #include <sch_edit_frame.h>
41 #include <kiway.h>
42 #include <paths.h>
43 #include <pgm_base.h>
47 #include <sch_file_versions.h>
48 
49 
50 // clang-format off
51 
56 {
57  wxString m_Description;
58  wxString m_FileFilter;
60  bool m_IsFile;
61  SCH_IO_MGR::SCH_FILE_T m_Plugin;
62 };
63 
64 
68 enum {
71 };
72 
73 
78 {
79  friend class SYMBOL_GRID_TRICKS;
80 
81 protected:
82  LIB_TABLE_ROW* at( size_t aIndex ) override { return &rows.at( aIndex ); }
83 
84  size_t size() const override { return rows.size(); }
85 
87  {
88  return dynamic_cast< LIB_TABLE_ROW* >( new SYMBOL_LIB_TABLE_ROW );
89  }
90 
91  LIB_TABLE_ROWS_ITER begin() override { return rows.begin(); }
92 
94  {
95  return rows.insert( aIterator, aRow );
96  }
97 
98  void push_back( LIB_TABLE_ROW* aRow ) override { rows.push_back( aRow ); }
99 
101  {
102  return rows.erase( aFirst, aLast );
103  }
104 
105 public:
106 
108  {
109  rows = aTableToEdit.rows;
110  }
111 };
112 
113 
115 {
116 public:
118  GRID_TRICKS( aGrid ),
119  m_dialog( aParent )
120  {
121  }
122 
123 protected:
125 
128  virtual void paste_text( const wxString& cb_text ) override
129  {
130  SYMBOL_LIB_TABLE_GRID* tbl = (SYMBOL_LIB_TABLE_GRID*) m_grid->GetTable();
131  size_t ndx = cb_text.find( "(sym_lib_table" );
132 
133  if( ndx != std::string::npos )
134  {
135  // paste the SYMBOL_LIB_TABLE_ROWs of s-expression (sym_lib_table), starting
136  // at column 0 regardless of current cursor column.
137 
138  STRING_LINE_READER slr( TO_UTF8( cb_text ), "Clipboard" );
139  LIB_TABLE_LEXER lexer( &slr );
140  SYMBOL_LIB_TABLE tmp_tbl;
141  bool parsed = true;
142 
143  try
144  {
145  tmp_tbl.Parse( &lexer );
146  }
147  catch( PARSE_ERROR& pe )
148  {
149  DisplayError( m_dialog, pe.What() );
150  parsed = false;
151  }
152 
153  if( parsed )
154  {
155  // make sure the table is big enough...
156  if( tmp_tbl.GetCount() > (unsigned) tbl->GetNumberRows() )
157  tbl->AppendRows( tmp_tbl.GetCount() - tbl->GetNumberRows() );
158 
159  for( unsigned i = 0; i < tmp_tbl.GetCount(); ++i )
160  tbl->rows.replace( i, tmp_tbl.At( i ).clone() );
161  }
162 
163  m_grid->AutoSizeColumns( false );
164  }
165  else
166  {
167  // paste spreadsheet formatted text.
168  GRID_TRICKS::paste_text( cb_text );
169 
170  m_grid->AutoSizeColumns( false );
171  }
172  }
173 };
174 
175 
177  SYMBOL_LIB_TABLE* aGlobalTable,
178  const wxString& aGlobalTablePath,
179  SYMBOL_LIB_TABLE* aProjectTable,
180  const wxString& aProjectTablePath ) :
181  PANEL_SYM_LIB_TABLE_BASE( aParent ),
182  m_globalTable( aGlobalTable ),
183  m_projectTable( aProjectTable ),
184  m_project( aProject ),
185  m_parent( aParent )
186 {
187  // wxGrid only supports user owned tables if they exist past end of ~wxGrid(),
188  // so make it a grid owned table.
190 
191  wxArrayString pluginChoices;
192 
193  pluginChoices.Add( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD ) );
194  pluginChoices.Add( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY ) );
195 
196  EESCHEMA_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<EESCHEMA_SETTINGS>();
197 
198  if( cfg->m_lastSymbolLibDir.IsEmpty() )
200 
202 
203  auto setupGrid =
204  [&]( WX_GRID* aGrid )
205  {
206  // Give a bit more room for combobox editors
207  aGrid->SetDefaultRowSize( aGrid->GetDefaultRowSize() + 4 );
208 
209  // add Cut, Copy, and Paste to wxGrids
210  aGrid->PushEventHandler( new SYMBOL_GRID_TRICKS( m_parent, aGrid ) );
211 
212  aGrid->SetSelectionMode( wxGrid::wxGridSelectRows );
213  aGrid->AutoSizeColumns( false );
214 
215  // Set special attributes
216  wxGridCellAttr* attr;
217 
218  attr = new wxGridCellAttr;
219 
220  wxString wildcards = AllSymbolLibFilesWildcard()
222  + "|" + LegacySymbolLibFileWildcard();
223  attr->SetEditor( new GRID_CELL_PATH_EDITOR( m_parent, aGrid,
224  &cfg->m_lastSymbolLibDir, wildcards,
225  true, m_project->GetProjectPath() ) );
226  aGrid->SetColAttr( COL_URI, attr );
227 
228  attr = new wxGridCellAttr;
229  attr->SetEditor( new wxGridCellChoiceEditor( pluginChoices ) );
230  aGrid->SetColAttr( COL_TYPE, attr );
231 
232  attr = new wxGridCellAttr;
233  attr->SetRenderer( new wxGridCellBoolRenderer() );
234  attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
235  aGrid->SetColAttr( COL_ENABLED, attr );
236 
237  // all but COL_OPTIONS, which is edited with Option Editor anyways.
238  aGrid->AutoSizeColumn( COL_NICKNAME, false );
239  aGrid->AutoSizeColumn( COL_TYPE, false );
240  aGrid->AutoSizeColumn( COL_URI, false );
241  aGrid->AutoSizeColumn( COL_DESCR, false );
242  aGrid->AutoSizeColumn( COL_ENABLED, false );
243 
244  // would set this to width of title, if it was easily known.
245  aGrid->SetColSize( COL_OPTIONS, 80 );
246 
247  // Gives a selection to each grid, mainly for delete button. wxGrid's wake up with
248  // a currentCell which is sometimes not highlighted.
249  if( aGrid->GetNumberRows() > 0 )
250  aGrid->SelectRow( 0 );
251  };
252 
253  setupGrid( m_global_grid );
254 
255  if( m_projectTable )
256  {
258  setupGrid( m_project_grid );
259  }
260  else
261  {
262  m_pageNdx = 0;
263  m_notebook->DeletePage( 1 );
264  m_project_grid = nullptr;
265  }
266 
267  // add Cut, Copy, and Paste to wxGrids
268  m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
269 
271 
272  // select the last selected page
273  m_notebook->SetSelection( m_pageNdx );
275 
276  m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
277  m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
278 
279  // for ALT+A handling, we want the initial focus to be on the first selected grid.
281 
282  // Configure button logos
283  m_append_button->SetBitmap( KiBitmap( small_plus_xpm ) );
284  m_delete_button->SetBitmap( KiBitmap( small_trash_xpm ) );
285  m_move_up_button->SetBitmap( KiBitmap( small_up_xpm ) );
286  m_move_down_button->SetBitmap( KiBitmap( small_down_xpm ) );
287  m_browse_button->SetBitmap( KiBitmap( small_folder_xpm ) );
288 }
289 
290 
292 {
293  // When the dialog is closed it will hide the current notebook page first, which will
294  // in turn select the other one. We then end up saving its index as the "current page".
295  // So flip them back again:
296  m_pageNdx = m_pageNdx == 1 ? 0 : 1;
297 
298  // Delete the GRID_TRICKS.
299  // Any additional event handlers should be popped before the window is deleted.
300  m_global_grid->PopEventHandler( true );
301 
302  if( m_project_grid )
303  m_project_grid->PopEventHandler( true );
304 
305  m_path_subs_grid->PopEventHandler( true );
306 }
307 
308 
310 {
311  for( SYMBOL_LIB_TABLE_GRID* model : { global_model(), project_model() } )
312  {
313  if( !model )
314  continue;
315 
316  for( int r = 0; r < model->GetNumberRows(); )
317  {
318  wxString nick = model->GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
319  wxString uri = model->GetValue( r, COL_URI ).Trim( false ).Trim();
320  unsigned illegalCh = 0;
321 
322  if( !nick || !uri )
323  {
324  // Delete the "empty" row, where empty means missing nick or uri.
325  // This also updates the UI which could be slow, but there should only be a few
326  // rows to delete, unless the user fell asleep on the Add Row
327  // button.
328  model->DeleteRows( r, 1 );
329  }
330  else if( ( illegalCh = LIB_ID::FindIllegalLibraryNameChar( nick ) ) )
331  {
332  wxString msg = wxString::Format( _( "Illegal character '%c' in nickname '%s'" ),
333  illegalCh,
334  nick );
335 
336  // show the tabbed panel holding the grid we have flunked:
337  if( model != cur_model() )
338  m_notebook->SetSelection( model == global_model() ? 0 : 1 );
339 
340  m_cur_grid->MakeCellVisible( r, 0 );
341  m_cur_grid->SetGridCursor( r, 1 );
342 
343  wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
344  errdlg.ShowModal();
345  return false;
346  }
347  else
348  {
349  // set the trimmed values back into the table so they get saved to disk.
350  model->SetValue( r, COL_NICKNAME, nick );
351  model->SetValue( r, COL_URI, uri );
352  ++r; // this row was OK.
353  }
354  }
355  }
356 
357  // check for duplicate nickNames, separately in each table.
358  for( SYMBOL_LIB_TABLE_GRID* model : { global_model(), project_model() } )
359  {
360  if( !model )
361  continue;
362 
363  for( int r1 = 0; r1 < model->GetNumberRows() - 1; ++r1 )
364  {
365  wxString nick1 = model->GetValue( r1, COL_NICKNAME );
366 
367  for( int r2=r1+1; r2 < model->GetNumberRows(); ++r2 )
368  {
369  wxString nick2 = model->GetValue( r2, COL_NICKNAME );
370 
371  if( nick1 == nick2 )
372  {
373  wxString msg = wxString::Format( _( "Multiple libraries cannot share the same "
374  "nickname ('%s')." ),
375  nick1 );
376 
377  // show the tabbed panel holding the grid we have flunked:
378  if( model != cur_model() )
379  m_notebook->SetSelection( model == global_model() ? 0 : 1 );
380 
381  // go to the lower of the two rows, it is technically the duplicate:
382  m_cur_grid->MakeCellVisible( r2, 0 );
383  m_cur_grid->SetGridCursor( r2, 1 );
384 
385  wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
386  errdlg.ShowModal();
387 
388  return false;
389  }
390  }
391  }
392  }
393 
394  for( SYMBOL_LIB_TABLE* table : { global_model(), project_model() } )
395  {
396  if( !table )
397  continue;
398 
399  for( unsigned int r = 0; r < table->GetCount(); ++r )
400  {
401  SYMBOL_LIB_TABLE_ROW& row = dynamic_cast<SYMBOL_LIB_TABLE_ROW&>( table->At( r ) );
402 
403  if( !row.GetIsEnabled() )
404  continue;
405 
406  try
407  {
408  if( row.Refresh() )
409  {
410  if( table == global_model() )
412  else
414  }
415  }
416  catch( const IO_ERROR& ioe )
417  {
418  wxString msg = wxString::Format( _( "Symbol library \"%s\" failed to load.\n %s" ),
419  row.GetNickName(),
420  ioe.What() );
421 
422  wxMessageDialog errdlg( this, msg, _( "Error Loading Library" ) );
423  errdlg.ShowModal();
424 
425  return false;
426  }
427  }
428  }
429 
430  return true;
431 }
432 
433 
434 void PANEL_SYM_LIB_TABLE::OnUpdateUI( wxUpdateUIEvent& event )
435 {
436  m_pageNdx = (unsigned) std::max( 0, m_notebook->GetSelection() );
438 }
439 
440 
441 void PANEL_SYM_LIB_TABLE::browseLibrariesHandler( wxCommandEvent& event )
442 {
443  wxString wildcards = AllSymbolLibFilesWildcard()
445  + "|" + LegacySymbolLibFileWildcard();
446 
447  EESCHEMA_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<EESCHEMA_SETTINGS>();
448 
449  wxString openDir = cfg->m_lastSymbolLibDir;
450  if( m_cur_grid == m_project_grid )
451  {
452  openDir = m_lastProjectLibDir;
453  }
454 
455  wxFileDialog dlg( this, _( "Select Library" ),
456  openDir, wxEmptyString, wildcards,
457  wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
458 
459  if( dlg.ShowModal() == wxID_CANCEL )
460  return;
461 
462  if( m_cur_grid == m_global_grid )
463  {
464  cfg->m_lastSymbolLibDir = dlg.GetPath();
465  }
466  else
467  {
468  m_lastProjectLibDir = dlg.GetPath();
469  }
470 
471  const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
472  bool addDuplicates = false;
473  bool applyToAll = false;
474  wxString warning = _( "Warning: Duplicate Nickname" );
475  wxString msg = _( "A library nicknamed '%s' already exists." );
476  wxString detailedMsg = _( "One of the nicknames will need to be changed after "
477  "adding this library." );
478 
479  wxArrayString files;
480  dlg.GetFilenames( files );
481 
482  for( const wxString& file : files )
483  {
484  wxString filePath = dlg.GetDirectory() + wxFileName::GetPathSeparator() + file;
485  wxFileName fn( filePath );
486  wxString nickname = LIB_ID::FixIllegalChars( fn.GetName() );
487  bool doAdd = true;
488 
489  if( cur_model()->ContainsNickname( nickname ) )
490  {
491  if( !applyToAll )
492  {
493  // The cancel button adds the library to the table anyway
494  addDuplicates = OKOrCancelDialog( this, warning, wxString::Format( msg, nickname ),
495  detailedMsg, _( "Skip" ), _( "Add Anyway" ),
496  &applyToAll ) == wxID_CANCEL;
497  }
498 
499  doAdd = addDuplicates;
500  }
501 
502  if( doAdd && m_cur_grid->AppendRows( 1 ) )
503  {
504  int last_row = m_cur_grid->GetNumberRows() - 1;
505 
506  m_cur_grid->SetCellValue( last_row, COL_NICKNAME, nickname );
507 
508  // TODO the following code can detect only schematic types, not libs
509  // SCH_IO_MGR needs to provide file extension information for libraries too
510 
511  // auto detect the plugin type
512  for( SCH_IO_MGR::SCH_FILE_T piType : SCH_IO_MGR::SCH_FILE_T_vector )
513  {
514  if( SCH_IO_MGR::GetLibraryFileExtension( piType ).Lower() == fn.GetExt().Lower() )
515  {
516  m_cur_grid->SetCellValue( last_row, COL_TYPE, SCH_IO_MGR::ShowType( piType ) );
517  break;
518  }
519  }
520 
521  // try to use path normalized to an environmental variable or project path
522  wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
523 
524  // Do not use the project path in the global library table. This will almost
525  // assuredly be wrong for a different project.
526  if( path.IsEmpty() || (m_pageNdx == 0 && path.Contains( "${KIPRJMOD}" )) )
527  path = fn.GetFullPath();
528 
529  m_cur_grid->SetCellValue( last_row, COL_URI, path );
530  }
531  }
532 
533  if( !files.IsEmpty() )
534  {
535  m_cur_grid->MakeCellVisible( m_cur_grid->GetNumberRows() - 1, 0 );
536  m_cur_grid->SetGridCursor( m_cur_grid->GetNumberRows() - 1, 1 );
537  }
538 }
539 
540 
541 void PANEL_SYM_LIB_TABLE::appendRowHandler( wxCommandEvent& event )
542 {
544  return;
545 
546  if( m_cur_grid->AppendRows( 1 ) )
547  {
548  int row = m_cur_grid->GetNumberRows() - 1;
549 
550  // wx documentation is wrong, SetGridCursor does not make visible.
551  m_cur_grid->MakeCellVisible( row, 0 );
552  m_cur_grid->SetGridCursor( row, 1 );
553  m_cur_grid->EnableCellEditControl( true );
554  m_cur_grid->ShowCellEditControl();
555  }
556 }
557 
558 
559 void PANEL_SYM_LIB_TABLE::deleteRowHandler( wxCommandEvent& event )
560 {
562  return;
563 
564  int curRow = m_cur_grid->GetGridCursorRow();
565  int curCol = m_cur_grid->GetGridCursorCol();
566 
567  // In a wxGrid, collect rows that have a selected cell, or are selected
568  // It is not so easy: it depends on the way the selection was made.
569  // Here, we collect rows selected by clicking on a row label, and rows that contain
570  // previously-selected cells.
571  // If no candidate, just delete the row with the grid cursor.
572  wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
573  wxGridCellCoordsArray cells = m_cur_grid->GetSelectedCells();
574  wxGridCellCoordsArray blockTopLeft = m_cur_grid->GetSelectionBlockTopLeft();
575  wxGridCellCoordsArray blockBotRight = m_cur_grid->GetSelectionBlockBottomRight();
576 
577  // Add all row having cell selected to list:
578  for( unsigned ii = 0; ii < cells.GetCount(); ii++ )
579  selectedRows.Add( cells[ii].GetRow() );
580 
581  // Handle block selection
582  if( !blockTopLeft.IsEmpty() && !blockBotRight.IsEmpty() )
583  {
584  for( int i = blockTopLeft[0].GetRow(); i <= blockBotRight[0].GetRow(); ++i )
585  selectedRows.Add( i );
586  }
587 
588  // Use the row having the grid cursor only if we have no candidate:
589  if( selectedRows.size() == 0 && m_cur_grid->GetGridCursorRow() >= 0 )
590  selectedRows.Add( m_cur_grid->GetGridCursorRow() );
591 
592  if( selectedRows.size() == 0 )
593  {
594  wxBell();
595  return;
596  }
597 
598  std::sort( selectedRows.begin(), selectedRows.end() );
599 
600  // Remove selected rows (note: a row can be stored more than once in list)
601  int last_row = -1;
602 
603  for( int ii = selectedRows.GetCount()-1; ii >= 0; ii-- )
604  {
605  int row = selectedRows[ii];
606 
607  if( row != last_row )
608  {
609  last_row = row;
610  m_cur_grid->DeleteRows( row, 1 );
611  }
612  }
613 
614  if( m_cur_grid->GetNumberRows() > 0 && curRow >= 0 )
615  m_cur_grid->SetGridCursor( std::min( curRow, m_cur_grid->GetNumberRows() - 1 ), curCol );
616 }
617 
618 
619 void PANEL_SYM_LIB_TABLE::moveUpHandler( wxCommandEvent& event )
620 {
622  return;
623 
625  int curRow = m_cur_grid->GetGridCursorRow();
626 
627  // @todo: add multiple selection moves.
628  if( curRow >= 1 )
629  {
630  boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
631  tbl->rows.release( tbl->rows.begin() + curRow );
632 
633  --curRow;
634  tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
635 
636  if( tbl->GetView() )
637  {
638  // Update the wxGrid
639  wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow, 0 );
640  tbl->GetView()->ProcessTableMessage( msg );
641  }
642 
643  m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
644  m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
645  }
646 }
647 
648 
649 void PANEL_SYM_LIB_TABLE::moveDownHandler( wxCommandEvent& event )
650 {
652  return;
653 
655  int curRow = m_cur_grid->GetGridCursorRow();
656 
657  // @todo: add multiple selection moves.
658  if( unsigned( curRow + 1 ) < tbl->rows.size() )
659  {
660  boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
661  tbl->rows.release( tbl->rows.begin() + curRow );
662 
663  ++curRow;
664  tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
665 
666  if( tbl->GetView() )
667  {
668  // Update the wxGrid
669  wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow - 1, 0 );
670  tbl->GetView()->ProcessTableMessage( msg );
671  }
672 
673  m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
674  m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
675  }
676 }
677 
678 
680 {
682  return;
683 
684  wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
685 
686  if( selectedRows.empty() && m_cur_grid->GetGridCursorRow() >= 0 )
687  selectedRows.push_back( m_cur_grid->GetGridCursorRow() );
688 
689  wxArrayInt legacyRows;
690  wxString legacyType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY );
691  wxString kicadType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD );
692  wxString msg;
693 
694  for( int row : selectedRows )
695  {
696  if( m_cur_grid->GetCellValue( row, COL_TYPE ) == legacyType )
697  legacyRows.push_back( row );
698  }
699 
700  if( legacyRows.size() <= 0 )
701  {
702  wxMessageBox( _( "Select one or more table rows containing legacy libraries to save as "
703  "current format (*.kicad_sym)." ) );
704  return;
705  }
706  else
707  {
708  if( legacyRows.size() == 1 )
709  {
710  msg.Printf( _( "Save '%s' as current format (*.kicad_sym) and "
711  "replace legacy entry in table?" ),
712  m_cur_grid->GetCellValue( legacyRows[0], COL_NICKNAME ) );
713  }
714  else
715  {
716  msg.Printf( _( "Save %d legacy libraries as current format (*.kicad_sym) and "
717  "replace legacy entries in table?" ),
718  legacyRows.size() );
719  }
720 
721  if( !IsOK( m_parent, msg ) )
722  return;
723  }
724 
725  for( int row : legacyRows )
726  {
727  wxString libName = m_cur_grid->GetCellValue( row, COL_NICKNAME );
728  wxString relPath = m_cur_grid->GetCellValue( row, COL_URI );
729  wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
730  wxFileName legacyLib( resolvedPath );
731 
732  if( !legacyLib.Exists() )
733  {
734  msg.Printf( _( "Library '%s' not found." ), relPath );
735  DisplayErrorMessage( this, msg );
736  continue;
737  }
738 
739  wxFileName newLib( resolvedPath );
740  newLib.SetExt( "kicad_sym" );
741 
742  if( convertLibrary( libName, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
743  {
744  relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(),
745  m_project );
746 
747  // Do not use the project path in the global library table. This will almost
748  // assuredly be wrong for a different project.
749  if( relPath.IsEmpty() || (m_cur_grid == m_global_grid && relPath.Contains( "${KIPRJMOD}" ) ) )
750  relPath = newLib.GetFullPath();
751 
752  m_cur_grid->SetCellValue( row, COL_URI, relPath );
753  m_cur_grid->SetCellValue( row, COL_TYPE, kicadType );
754  }
755  else
756  {
757  msg.Printf( _( "Failed to save symbol library file '%s'." ), newLib.GetFullPath() );
758  DisplayErrorMessage( this, msg );
759  }
760  }
761 }
762 
763 
764 bool PANEL_SYM_LIB_TABLE::convertLibrary( const wxString& aLibrary, const wxString& legacyFilepath,
765  const wxString& newFilepath )
766 {
767  SCH_PLUGIN::SCH_PLUGIN_RELEASER legacyPI( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_LEGACY ) );
768  SCH_PLUGIN::SCH_PLUGIN_RELEASER kicadPI( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
769  std::vector<LIB_PART*> parts;
770  std::vector<LIB_PART*> newParts;
771  std::map<LIB_PART*, LIB_PART*> partMap;
772 
773  try
774  {
775  // Write a stub file; SaveSymbol() expects something to be there already.
776  FILE_OUTPUTFORMATTER* formatter = new FILE_OUTPUTFORMATTER( newFilepath );
777 
778  formatter->Print( 0, "(kicad_symbol_lib (version %d) (generator kicad_converter))",
780 
781  // This will write the file
782  delete formatter;
783 
784  legacyPI->EnumerateSymbolLib( parts, legacyFilepath );
785 
786  // Copy non-aliases first so we can build a map from parts to newParts
787  for( LIB_PART* part : parts )
788  {
789  if( part->IsAlias() )
790  continue;
791 
792  newParts.push_back( new LIB_PART( *part ) );
793  partMap[part] = newParts.back();
794  }
795 
796  // Now do the aliases using the map to hook them up to their newPart parents
797  for( LIB_PART* part : parts )
798  {
799  if( !part->IsAlias() )
800  continue;
801 
802  newParts.push_back( new LIB_PART( *part ) );
803  newParts.back()->SetParent( partMap[ part->GetParent().lock().get() ] );
804  }
805 
806  // Finally write out newParts
807  for( LIB_PART* part : newParts )
808  {
809  kicadPI->SaveSymbol( newFilepath, part );
810  }
811  }
812  catch( ... )
813  {
814  return false;
815  }
816 
817  return true;
818 }
819 
820 
822 {
824  return false;
825 
826  if( !verifyTables() )
827  return false;
828 
829  if( *global_model() != *m_globalTable )
830  {
832 
833  m_globalTable->Clear();
834  m_globalTable->rows.transfer( m_globalTable->rows.end(), global_model()->rows.begin(),
835  global_model()->rows.end(), global_model()->rows );
837  }
838 
839  if( project_model() && *project_model() != *m_projectTable )
840  {
842 
844  m_projectTable->rows.transfer( m_projectTable->rows.end(), project_model()->rows.begin(),
845  project_model()->rows.end(), project_model()->rows );
847  }
848 
849  return true;
850 }
851 
852 
854 {
855  wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
856  wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
857 
858  std::set< wxString > unique;
859 
860  // clear the table
861  m_path_subs_grid->DeleteRows( 0, m_path_subs_grid->GetNumberRows() );
862 
863  for( SYMBOL_LIB_TABLE_GRID* tbl : { global_model(), project_model() } )
864  {
865  if( !tbl )
866  continue;
867 
868  for( int row = 0; row < tbl->GetNumberRows(); ++row )
869  {
870  wxString uri = tbl->GetValue( row, COL_URI );
871 
872  while( re.Matches( uri ) )
873  {
874  wxString envvar = re.GetMatch( uri, 2 );
875 
876  // if not ${...} form then must be $(...)
877  if( envvar.IsEmpty() )
878  envvar = re.GetMatch( uri, 4 );
879 
880  // ignore duplicates
881  unique.insert( envvar );
882 
883  // delete the last match and search again
884  uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
885  }
886  }
887  }
888 
889  // Make sure this special environment variable shows up even if it was
890  // not used yet. It is automatically set by KiCad to the directory holding
891  // the current project.
892  unique.insert( PROJECT_VAR_NAME );
894 
895  for( const wxString& evName : unique )
896  {
897  int row = m_path_subs_grid->GetNumberRows();
898  m_path_subs_grid->AppendRows( 1 );
899 
900  m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
901  m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
902 
903  wxString evValue;
904  wxGetEnv( evName, &evValue );
905  m_path_subs_grid->SetCellValue( row, 1, evValue );
906  m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
907  }
908 
909  // No combobox editors here, but it looks better if its consistent with the other
910  // grids in the dialog.
911  m_path_subs_grid->SetDefaultRowSize( m_path_subs_grid->GetDefaultRowSize() + 2 );
912 
913  adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
914 }
915 
916 
918 {
919  // Account for scroll bars
920  aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
921 
922  m_path_subs_grid->AutoSizeColumn( 0 );
923 
924  int remaining_width = aWidth - m_path_subs_grid->GetColSize( 0 );
925 
926  if( remaining_width < 0 )
927  m_path_subs_grid->SetColSize( 1, -1 );
928  else
929  m_path_subs_grid->SetColSize( 1, remaining_width );
930 }
931 
932 
933 void PANEL_SYM_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
934 {
935  adjustPathSubsGridColumns( event.GetSize().GetX() );
936 
937  event.Skip();
938 }
939 
940 
942 {
943  return (SYMBOL_LIB_TABLE_GRID*) m_global_grid->GetTable();
944 }
945 
946 
948 {
949  return m_project_grid ? (SYMBOL_LIB_TABLE_GRID*) m_project_grid->GetTable() : nullptr;
950 }
951 
952 
954 {
955  return (SYMBOL_LIB_TABLE_GRID*) m_cur_grid->GetTable();
956 }
957 
958 
960 
961 
962 void InvokeSchEditSymbolLibTable( KIWAY* aKiway, wxWindow *aParent )
963 {
964  auto* schEditor = (SCH_EDIT_FRAME*) aKiway->Player( FRAME_SCH, false );
965  auto* symbolEditor = (SYMBOL_EDIT_FRAME*) aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
966  auto* symbolViewer = (SYMBOL_VIEWER_FRAME*) aKiway->Player( FRAME_SCH_VIEWER, false );
967 
969  wxString globalTablePath = SYMBOL_LIB_TABLE::GetGlobalTableFileName();
970  SYMBOL_LIB_TABLE* projectTable = nullptr;
971  wxString projectPath = aKiway->Prj().GetProjectPath();
972  wxFileName projectTableFn( projectPath, SYMBOL_LIB_TABLE::GetSymbolLibTableFileName() );
973  wxString msg;
974  wxString currentLib;
975 
976  // Don't allow editing project tables if no project is open
977  if( !aKiway->Prj().IsNullProject() )
978  projectTable = aKiway->Prj().SchSymbolLibTable();
979 
980  if( symbolEditor )
981  {
982  currentLib = symbolEditor->GetCurLib();
983 
984  // This prevents an ugly crash on OSX (https://bugs.launchpad.net/kicad/+bug/1765286)
985  symbolEditor->FreezeSearchTree();
986 
987  if( symbolEditor->HasLibModifications() )
988  {
989  msg = _( "Modifications have been made to one or more symbol libraries.\n"
990  "Changes must be saved or discarded before the symbol library "
991  "table can be modified." );
992 
993  switch( UnsavedChangesDialog( aParent, msg ) )
994  {
995  case wxID_YES: symbolEditor->SaveAll(); break;
996  case wxID_NO: symbolEditor->RevertAll(); break;
997  default:
998  case wxID_CANCEL: symbolEditor->ThawSearchTree(); return;
999  }
1000  }
1001  }
1002 
1003  DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Symbol Libraries" ) );
1004  dlg.SetKiway( &dlg, aKiway );
1005 
1006  dlg.InstallPanel( new PANEL_SYM_LIB_TABLE( &dlg, &aKiway->Prj(), globalTable, globalTablePath,
1007  projectTable, projectTableFn.GetFullPath() ) );
1008 
1009  if( dlg.ShowModal() == wxID_CANCEL )
1010  {
1011  if( symbolEditor )
1012  symbolEditor->ThawSearchTree();
1013 
1014  return;
1015  }
1016 
1017  if( dlg.m_GlobalTableChanged )
1018  {
1019  try
1020  {
1021  globalTable->Save( globalTablePath );
1022  }
1023  catch( const IO_ERROR& ioe )
1024  {
1025  msg.Printf( _( "Error saving global library table:\n\n%s" ), ioe.What() );
1026  wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
1027  }
1028  }
1029 
1030  if( projectTable && dlg.m_ProjectTableChanged )
1031  {
1032  try
1033  {
1034  projectTable->Save( projectTableFn.GetFullPath() );
1035  }
1036  catch( const IO_ERROR& ioe )
1037  {
1038  msg.Printf( _( "Error saving project-specific library table:\n\n%s" ), ioe.What() );
1039  wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
1040  }
1041  }
1042 
1043  if( schEditor )
1044  schEditor->SyncView();
1045 
1046  if( symbolEditor )
1047  {
1048  // Check if the currently selected symbol library been removed or disabled.
1049  if( !currentLib.empty() && projectTable && !projectTable->HasLibrary( currentLib, true ) )
1050  {
1051  symbolEditor->SetCurLib( wxEmptyString );
1052  symbolEditor->emptyScreen();
1053  }
1054 
1055  symbolEditor->SyncLibraries( true );
1056  symbolEditor->ThawSearchTree();
1057  }
1058 
1059  if( symbolViewer )
1060  symbolViewer->ReCreateLibList();
1061 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:253
static const wxString & GetSymbolLibTableFileName()
static SYMBOL_LIB_TABLE & GetGlobalLibTable()
virtual void paste_text(const wxString &cb_text) override
handle specialized clipboard text, with leading "(sym_lib_table" or spreadsheet formatted text.
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
It is only used for debugging, since "this" is not a wxWindow*.
wxString AllSymbolLibFilesWildcard()
void moveUpHandler(wxCommandEvent &event) override
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib=false)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition: lib_id.cpp:347
Hold a record identifying a symbol library accessed by the appropriate symbol library SCH_PLUGIN obje...
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE.
Container for project specific data.
Definition: project.h:62
Container that describes file type info for the add a library options.
void Clear()
Delete all rows.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:266
This file is part of the common library.
const BITMAP_OPAQUE small_folder_xpm[1]
void reindex()
bool ContainsNickname(const wxString &aNickname)
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition: kiway.cpp:174
unsigned GetCount() const
Get the number of rows contained in the table.
static const wxString ShowType(SCH_FILE_T aFileType)
Return a brief name for a plugin, given aFileType enum.
Definition: sch_io_mgr.cpp:87
LIB_TABLE_ROW * at(size_t aIndex) override
void OnUpdateUI(wxUpdateUIEvent &event) override
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition: project.h:38
void InvokeSchEditSymbolLibTable(KIWAY *aKiway, wxWindow *aParent)
WX_GRID * m_cur_grid
changed based on tab choice
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
Definition: grid_tricks.h:52
static const wxString GetLibraryFileExtension(SCH_FILE_T aFileType)
Return the symbol library file extension (if any) for aFileType.
Definition: sch_io_mgr.cpp:154
SYMBOL_LIB_TABLE_GRID * global_model() const
static const wxString GlobalPathEnvVariableName()
Return the name of the environment variable used to hold the directory of locally installed "KiCad sp...
static size_t m_pageNdx
Remember the last notebook page selected.
Symbol library viewer main window.
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition: kiway.cpp:345
Schematic editor (Eeschema) main window.
LIB_TABLE_ROWS rows
#define SEXPR_SYMBOL_LIB_FILE_VERSION
This file contains the file format version information for the s-expression schematic and symbol libr...
void SetTable(wxGridTableBase *table, bool aTakeOwnership=false)
Hide wxGrid's SetTable() method with one which doesn't mess up the grid column widths when setting th...
Definition: wx_grid.cpp:65
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:269
int GetNumberRows() override
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:106
SCH_IO_MGR::SCH_FILE_T m_Plugin
virtual const wxString GetProjectPath() const
Return the full path of the project.
void SetInitialFocus(wxWindow *aWindow)
Sets the window (usually a wxTextCtrl) that should be focused when the dialog is shown.
Definition: dialog_shim.h:98
void adjustPathSubsGridColumns(int aWidth)
This abstract base class mixes any object derived from LIB_TABLE into wxGridTableBase so the result c...
WX_GRID * m_grid
I don't own the grid, but he owns me.
Definition: grid_tricks.h:81
virtual void paste_text(const wxString &cb_text)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:96
wxBitmap KiBitmap(BITMAP_DEF aBitmap)
Construct a wxBitmap from a memory record, held in a BITMAP_DEF.
Definition: bitmap.cpp:82
void populateEnvironReadOnlyTable()
Populate the readonly environment variable table with names and values by examining all the full_uri ...
const wxString & GetNickName() const
LIB_TABLE_ROW * clone() const
Build a wxGridTableBase by wrapping an SYMBOL_LIB_TABLE object.
bool GetIsEnabled() const
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:29
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
Definition: pgm_base.h:113
SYMBOL_LIB_TABLE_GRID * cur_model() const
SYMBOL_LIB_TABLE * m_projectTable
bool Refresh()
Attempt to reload the library.
bool TransferDataFromWindow() override
bool convertLibrary(const wxString &aLibrary, const wxString &legacyFilepath, const wxString &newFilepath)
PANEL_SYM_LIB_TABLE(DIALOG_EDIT_LIBRARY_TABLES *aParent, PROJECT *m_project, SYMBOL_LIB_TABLE *aGlobal, const wxString &aGlobalTablePath, SYMBOL_LIB_TABLE *aProject, const wxString &aProjectTablePath)
const BITMAP_OPAQUE small_down_xpm[1]
Definition: small_down.cpp:23
Class PANEL_SYM_LIB_TABLE_BASE.
void onConvertLegacyLibraries(wxCommandEvent &event) override
Define a library symbol object.
Definition: lib_symbol.h:93
Definition of file extensions used in Kicad.
bool m_IsFile
Whether the library is a folder or a file.
DIALOG_EDIT_LIBRARY_TABLES * m_dialog
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition: kiway.h:260
void push_back(LIB_TABLE_ROW *aRow) override
wxString KiCadSymbolLibFileWildcard()
Editor for wxGrid cells that adds a file/folder browser to the grid input field.
Dialog to show and edit symbol library tables.
void deleteRowHandler(wxCommandEvent &event) override
bool CommitPendingChanges(bool aQuietMode=false)
Close any open cell edit controls.
Definition: wx_grid.cpp:182
bool AppendRows(size_t aNumRows=1) override
int UnsavedChangesDialog(wxWindow *parent, wxString aMessage, bool *aApplyToAll)
A specialized version of HandleUnsavedChanges which handles an apply-to-all checkbox.
Definition: confirm.cpp:155
wxString LegacySymbolLibFileWildcard()
void appendRowHandler(wxCommandEvent &event) override
const BITMAP_OPAQUE small_up_xpm[1]
Definition: small_up.cpp:23
SYMBOL_LIB_TABLE_GRID(const SYMBOL_LIB_TABLE &aTableToEdit)
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
const BITMAP_OPAQUE small_trash_xpm[1]
Definition: small_trash.cpp:23
DIALOG_EDIT_LIBRARY_TABLES * m_parent
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:200
Helper object to release a SCH_PLUGIN in the context of a potential thrown exception through its dest...
Definition: sch_io_mgr.h:470
wxString m_FolderSearchExtension
In case of folders it stands for extensions of files stored inside.
int OKOrCancelDialog(wxWindow *aParent, const wxString &aWarning, const wxString &aMessage, wxString aDetailedMessage, wxString aOKLabel, wxString aCancelLabel, bool *aApplyToAll)
Display a warning dialog with aMessage and returns the user response.
Definition: confirm.cpp:221
static wxString GetDefaultUserSymbolsPath()
Gets the default path we point users to create projects.
Definition: paths.cpp:96
SYMBOL_LIB_TABLE_GRID * project_model() const
A filename or source description, a problem input line, a line number, a byte offset,...
Definition: ki_exception.h:118
see class PGM_BASE
LIB_TABLE_ROW & At(unsigned aIndex)
Get the 'n'th LIB_TABLE_ROW object.
#define _(s)
Definition: 3d_actions.cpp:33
LIB_TABLE_ROWS_ITER erase(LIB_TABLE_ROWS_ITER aFirst, LIB_TABLE_ROWS_ITER aLast) override
virtual void Parse(LIB_TABLE_LEXER *aLexer) override
Parse the #LIB_TABLE_LEXER s-expression library table format into the appropriate LIB_TABLE_ROW objec...
LIB_TABLE_ROWS::iterator LIB_TABLE_ROWS_ITER
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
bool verifyTables()
Trim important fields, removes blank row entries, and checks for duplicates.
Used for text file output.
Definition: richio.h:453
void onSizeGrid(wxSizeEvent &event) override
LIB_TABLE_ROWS_ITER insert(LIB_TABLE_ROWS_ITER aIterator, LIB_TABLE_ROW *aRow) override
SYMBOL_LIB_TABLE * m_globalTable
wxString m_Description
Description shown in the file picker dialog.
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:408
wxString m_FileFilter
Filter used for file pickers if m_IsFile is true.
LIB_TABLE_ROW * makeNewRow() override
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition: richio.h:237
LIB_TABLE_ROWS_ITER begin() override
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
Definition: ki_exception.h:75
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition: confirm.cpp:297
static wxString GetGlobalTableFileName()
Fetch the global symbol library table file name.
size_t size() const override
const BITMAP_OPAQUE small_plus_xpm[1]
Definition: small_plus.cpp:18
void moveDownHandler(wxCommandEvent &event) override
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:67
SYMBOL_GRID_TRICKS(DIALOG_EDIT_LIBRARY_TABLES *aParent, WX_GRID *aGrid)
static unsigned FindIllegalLibraryNameChar(const UTF8 &aLibraryName)
Looks for characters that are illegal in library nicknames.
Definition: lib_id.cpp:398
The symbol library editor main window.
void browseLibrariesHandler(wxCommandEvent &event) override