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 <common.h> // For ExpandEnvVarSubstitutions
26 #include <project.h>
27 #include <panel_sym_lib_table.h>
28 #include <lib_id.h>
29 #include <symbol_lib_table.h>
30 #include <lib_table_lexer.h>
31 #include <grid_tricks.h>
32 #include <widgets/wx_grid.h>
33 #include <confirm.h>
34 #include <bitmaps.h>
35 #include <lib_table_grid.h>
37 #include <env_paths.h>
38 #include <eeschema_id.h>
39 #include <symbol_edit_frame.h>
40 #include <symbol_viewer_frame.h>
41 #include <sch_edit_frame.h>
42 #include <kiway.h>
43 #include <paths.h>
44 #include <pgm_base.h>
48 #include <sch_file_versions.h>
49 #include <wx/filedlg.h>
50 
51 
52 
53 // clang-format off
54 
59 {
60  wxString m_Description;
61  wxString m_FileFilter;
63  bool m_IsFile;
64  SCH_IO_MGR::SCH_FILE_T m_Plugin;
65 };
66 
67 
71 enum {
74 };
75 
76 
81 {
82  friend class SYMBOL_GRID_TRICKS;
83 
84 protected:
85  LIB_TABLE_ROW* at( size_t aIndex ) override { return &rows.at( aIndex ); }
86 
87  size_t size() const override { return rows.size(); }
88 
90  {
91  return dynamic_cast< LIB_TABLE_ROW* >( new SYMBOL_LIB_TABLE_ROW );
92  }
93 
94  LIB_TABLE_ROWS_ITER begin() override { return rows.begin(); }
95 
97  {
98  return rows.insert( aIterator, aRow );
99  }
100 
101  void push_back( LIB_TABLE_ROW* aRow ) override { rows.push_back( aRow ); }
102 
104  {
105  return rows.erase( aFirst, aLast );
106  }
107 
108 public:
109 
111  {
112  rows = aTableToEdit.rows;
113  }
114 };
115 
116 
118 {
119 public:
121  GRID_TRICKS( aGrid ),
122  m_dialog( aParent )
123  {
124  }
125 
126 protected:
128 
131  virtual void paste_text( const wxString& cb_text ) override
132  {
133  SYMBOL_LIB_TABLE_GRID* tbl = (SYMBOL_LIB_TABLE_GRID*) m_grid->GetTable();
134  size_t ndx = cb_text.find( "(sym_lib_table" );
135 
136  if( ndx != std::string::npos )
137  {
138  // paste the SYMBOL_LIB_TABLE_ROWs of s-expression (sym_lib_table), starting
139  // at column 0 regardless of current cursor column.
140 
141  STRING_LINE_READER slr( TO_UTF8( cb_text ), "Clipboard" );
142  LIB_TABLE_LEXER lexer( &slr );
143  SYMBOL_LIB_TABLE tmp_tbl;
144  bool parsed = true;
145 
146  try
147  {
148  tmp_tbl.Parse( &lexer );
149  }
150  catch( PARSE_ERROR& pe )
151  {
152  DisplayError( m_dialog, pe.What() );
153  parsed = false;
154  }
155 
156  if( parsed )
157  {
158  // make sure the table is big enough...
159  if( tmp_tbl.GetCount() > (unsigned) tbl->GetNumberRows() )
160  tbl->AppendRows( tmp_tbl.GetCount() - tbl->GetNumberRows() );
161 
162  for( unsigned i = 0; i < tmp_tbl.GetCount(); ++i )
163  tbl->rows.replace( i, tmp_tbl.At( i ).clone() );
164  }
165 
166  m_grid->AutoSizeColumns( false );
167  }
168  else
169  {
170  // paste spreadsheet formatted text.
171  GRID_TRICKS::paste_text( cb_text );
172 
173  m_grid->AutoSizeColumns( false );
174  }
175  }
176 };
177 
178 
180  SYMBOL_LIB_TABLE* aGlobalTable,
181  const wxString& aGlobalTablePath,
182  SYMBOL_LIB_TABLE* aProjectTable,
183  const wxString& aProjectTablePath ) :
184  PANEL_SYM_LIB_TABLE_BASE( aParent ),
185  m_globalTable( aGlobalTable ),
186  m_projectTable( aProjectTable ),
187  m_project( aProject ),
188  m_parent( aParent )
189 {
190  // wxGrid only supports user owned tables if they exist past end of ~wxGrid(),
191  // so make it a grid owned table.
193 
194  wxArrayString pluginChoices;
195 
196  pluginChoices.Add( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD ) );
197  pluginChoices.Add( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY ) );
198 
199  EESCHEMA_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<EESCHEMA_SETTINGS>();
200 
201  if( cfg->m_lastSymbolLibDir.IsEmpty() )
203 
205 
206  auto setupGrid =
207  [&]( WX_GRID* aGrid )
208  {
209  // Give a bit more room for combobox editors
210  aGrid->SetDefaultRowSize( aGrid->GetDefaultRowSize() + 4 );
211 
212  // add Cut, Copy, and Paste to wxGrids
213  aGrid->PushEventHandler( new SYMBOL_GRID_TRICKS( m_parent, aGrid ) );
214 
215  aGrid->SetSelectionMode( wxGrid::wxGridSelectRows );
216  aGrid->AutoSizeColumns( false );
217 
218  // Set special attributes
219  wxGridCellAttr* attr;
220 
221  attr = new wxGridCellAttr;
222 
223  wxString wildcards = AllSymbolLibFilesWildcard()
225  + "|" + LegacySymbolLibFileWildcard();
226  attr->SetEditor( new GRID_CELL_PATH_EDITOR( m_parent, aGrid,
227  &cfg->m_lastSymbolLibDir, wildcards,
228  true, m_project->GetProjectPath() ) );
229  aGrid->SetColAttr( COL_URI, attr );
230 
231  attr = new wxGridCellAttr;
232  attr->SetEditor( new wxGridCellChoiceEditor( pluginChoices ) );
233  aGrid->SetColAttr( COL_TYPE, attr );
234 
235  attr = new wxGridCellAttr;
236  attr->SetRenderer( new wxGridCellBoolRenderer() );
237  attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
238  aGrid->SetColAttr( COL_ENABLED, attr );
239 
240  // all but COL_OPTIONS, which is edited with Option Editor anyways.
241  aGrid->AutoSizeColumn( COL_NICKNAME, false );
242  aGrid->AutoSizeColumn( COL_TYPE, false );
243  aGrid->AutoSizeColumn( COL_URI, false );
244  aGrid->AutoSizeColumn( COL_DESCR, false );
245  aGrid->AutoSizeColumn( COL_ENABLED, false );
246 
247  // would set this to width of title, if it was easily known.
248  aGrid->SetColSize( COL_OPTIONS, 80 );
249 
250  // Gives a selection to each grid, mainly for delete button. wxGrid's wake up with
251  // a currentCell which is sometimes not highlighted.
252  if( aGrid->GetNumberRows() > 0 )
253  aGrid->SelectRow( 0 );
254  };
255 
256  setupGrid( m_global_grid );
257 
258  if( m_projectTable )
259  {
261  setupGrid( m_project_grid );
262  }
263  else
264  {
265  m_pageNdx = 0;
266  m_notebook->DeletePage( 1 );
267  m_project_grid = nullptr;
268  }
269 
270  // add Cut, Copy, and Paste to wxGrids
271  m_path_subs_grid->PushEventHandler( new GRID_TRICKS( m_path_subs_grid ) );
272 
274 
275  // select the last selected page
276  m_notebook->SetSelection( m_pageNdx );
278 
279  m_path_subs_grid->SetColLabelValue( 0, _( "Name" ) );
280  m_path_subs_grid->SetColLabelValue( 1, _( "Value" ) );
281 
282  // for ALT+A handling, we want the initial focus to be on the first selected grid.
284 
285  // Configure button logos
291 }
292 
293 
295 {
296  // When the dialog is closed it will hide the current notebook page first, which will
297  // in turn select the other one. We then end up saving its index as the "current page".
298  // So flip them back again:
299  m_pageNdx = m_pageNdx == 1 ? 0 : 1;
300 
301  // Delete the GRID_TRICKS.
302  // Any additional event handlers should be popped before the window is deleted.
303  m_global_grid->PopEventHandler( true );
304 
305  if( m_project_grid )
306  m_project_grid->PopEventHandler( true );
307 
308  m_path_subs_grid->PopEventHandler( true );
309 }
310 
311 
313 {
314  wxString msg;
315 
316  for( SYMBOL_LIB_TABLE_GRID* model : { global_model(), project_model() } )
317  {
318  if( !model )
319  continue;
320 
321  for( int r = 0; r < model->GetNumberRows(); )
322  {
323  wxString nick = model->GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
324  wxString uri = model->GetValue( r, COL_URI ).Trim( false ).Trim();
325  unsigned illegalCh = 0;
326 
327  if( !nick || !uri )
328  {
329  if( !nick && !uri )
330  msg = _( "A library table row nickname and path cells are empty." );
331  else if( !nick )
332  msg = _( "A library table row nickname cell is empty." );
333  else
334  msg = _( "A library table row path cell is empty." );
335 
336  wxMessageDialog badCellDlg( this, msg, _( "Invalid Row Definition" ),
337  wxYES_NO | wxCENTER | wxICON_QUESTION | wxYES_DEFAULT );
338  badCellDlg.SetExtendedMessage( _( "Empty cells will result in all rows that are "
339  "invalid to be removed from the table." ) );
340  badCellDlg.SetYesNoLabels( wxMessageDialog::ButtonLabel( "Remove Invalid Cells" ),
341  wxMessageDialog::ButtonLabel( "Cancel Table Update" ) );
342 
343  if( badCellDlg.ShowModal() == wxID_NO )
344  return false;
345 
346  // Delete the "empty" row, where empty means missing nick or uri.
347  // This also updates the UI which could be slow, but there should only be a few
348  // rows to delete, unless the user fell asleep on the Add Row
349  // button.
350  model->DeleteRows( r, 1 );
351  }
352  else if( ( illegalCh = LIB_ID::FindIllegalLibraryNameChar( nick ) ) )
353  {
354  msg = wxString::Format( _( "Illegal character '%c' in nickname '%s'" ),
355  illegalCh,
356  nick );
357 
358  // show the tabbed panel holding the grid we have flunked:
359  if( model != cur_model() )
360  m_notebook->SetSelection( model == global_model() ? 0 : 1 );
361 
362  m_cur_grid->MakeCellVisible( r, 0 );
363  m_cur_grid->SetGridCursor( r, 1 );
364 
365  wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
366  errdlg.ShowModal();
367  return false;
368  }
369  else
370  {
371  // set the trimmed values back into the table so they get saved to disk.
372  model->SetValue( r, COL_NICKNAME, nick );
373  model->SetValue( r, COL_URI, uri );
374  ++r; // this row was OK.
375  }
376  }
377  }
378 
379  // check for duplicate nickNames, separately in each table.
380  for( SYMBOL_LIB_TABLE_GRID* model : { global_model(), project_model() } )
381  {
382  if( !model )
383  continue;
384 
385  for( int r1 = 0; r1 < model->GetNumberRows() - 1; ++r1 )
386  {
387  wxString nick1 = model->GetValue( r1, COL_NICKNAME );
388 
389  for( int r2=r1+1; r2 < model->GetNumberRows(); ++r2 )
390  {
391  wxString nick2 = model->GetValue( r2, COL_NICKNAME );
392 
393  if( nick1 == nick2 )
394  {
395  msg = wxString::Format( _( "Multiple libraries cannot share the same "
396  "nickname ('%s')." ), nick1 );
397 
398  // show the tabbed panel holding the grid we have flunked:
399  if( model != cur_model() )
400  m_notebook->SetSelection( model == global_model() ? 0 : 1 );
401 
402  // go to the lower of the two rows, it is technically the duplicate:
403  m_cur_grid->MakeCellVisible( r2, 0 );
404  m_cur_grid->SetGridCursor( r2, 1 );
405 
406  wxMessageDialog errdlg( this, msg, _( "Library Nickname Error" ) );
407  errdlg.ShowModal();
408 
409  return false;
410  }
411  }
412  }
413  }
414 
415  for( SYMBOL_LIB_TABLE* table : { global_model(), project_model() } )
416  {
417  if( !table )
418  continue;
419 
420  for( unsigned int r = 0; r < table->GetCount(); ++r )
421  {
422  SYMBOL_LIB_TABLE_ROW& row = dynamic_cast<SYMBOL_LIB_TABLE_ROW&>( table->At( r ) );
423 
424  if( !row.GetIsEnabled() )
425  continue;
426 
427  try
428  {
429  if( row.Refresh() )
430  {
431  if( table == global_model() )
433  else
435  }
436  }
437  catch( const IO_ERROR& ioe )
438  {
439  msg = wxString::Format( _( "Symbol library \"%s\" failed to load.\n %s" ),
440  row.GetNickName(),
441  ioe.What() );
442 
443  wxMessageDialog errdlg( this, msg, _( "Error Loading Library" ) );
444  errdlg.ShowModal();
445 
446  return false;
447  }
448  }
449  }
450 
451  return true;
452 }
453 
454 
455 void PANEL_SYM_LIB_TABLE::OnUpdateUI( wxUpdateUIEvent& event )
456 {
457  m_pageNdx = (unsigned) std::max( 0, m_notebook->GetSelection() );
459 }
460 
461 
462 void PANEL_SYM_LIB_TABLE::browseLibrariesHandler( wxCommandEvent& event )
463 {
464  wxString wildcards = AllSymbolLibFilesWildcard()
466  + "|" + LegacySymbolLibFileWildcard();
467 
468  EESCHEMA_SETTINGS* cfg = Pgm().GetSettingsManager().GetAppSettings<EESCHEMA_SETTINGS>();
469 
470  wxString openDir = cfg->m_lastSymbolLibDir;
471  if( m_cur_grid == m_project_grid )
472  {
473  openDir = m_lastProjectLibDir;
474  }
475 
476  wxFileDialog dlg( this, _( "Select Library" ),
477  openDir, wxEmptyString, wildcards,
478  wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE );
479 
480  if( dlg.ShowModal() == wxID_CANCEL )
481  return;
482 
483  if( m_cur_grid == m_global_grid )
484  {
485  cfg->m_lastSymbolLibDir = dlg.GetPath();
486  }
487  else
488  {
489  m_lastProjectLibDir = dlg.GetPath();
490  }
491 
492  const ENV_VAR_MAP& envVars = Pgm().GetLocalEnvVariables();
493  bool addDuplicates = false;
494  bool applyToAll = false;
495  wxString warning = _( "Warning: Duplicate Nickname" );
496  wxString msg = _( "A library nicknamed '%s' already exists." );
497  wxString detailedMsg = _( "One of the nicknames will need to be changed after "
498  "adding this library." );
499 
500  wxArrayString files;
501  dlg.GetFilenames( files );
502 
503  for( const wxString& file : files )
504  {
505  wxString filePath = dlg.GetDirectory() + wxFileName::GetPathSeparator() + file;
506  wxFileName fn( filePath );
507  wxString nickname = LIB_ID::FixIllegalChars( fn.GetName() );
508  bool doAdd = true;
509 
510  if( cur_model()->ContainsNickname( nickname ) )
511  {
512  if( !applyToAll )
513  {
514  // The cancel button adds the library to the table anyway
515  addDuplicates = OKOrCancelDialog( this, warning, wxString::Format( msg, nickname ),
516  detailedMsg, _( "Skip" ), _( "Add Anyway" ),
517  &applyToAll ) == wxID_CANCEL;
518  }
519 
520  doAdd = addDuplicates;
521  }
522 
523  if( doAdd && m_cur_grid->AppendRows( 1 ) )
524  {
525  int last_row = m_cur_grid->GetNumberRows() - 1;
526 
527  m_cur_grid->SetCellValue( last_row, COL_NICKNAME, nickname );
528 
529  // TODO the following code can detect only schematic types, not libs
530  // SCH_IO_MGR needs to provide file extension information for libraries too
531 
532  // auto detect the plugin type
533  for( SCH_IO_MGR::SCH_FILE_T piType : SCH_IO_MGR::SCH_FILE_T_vector )
534  {
535  if( SCH_IO_MGR::GetLibraryFileExtension( piType ).Lower() == fn.GetExt().Lower() )
536  {
537  m_cur_grid->SetCellValue( last_row, COL_TYPE, SCH_IO_MGR::ShowType( piType ) );
538  break;
539  }
540  }
541 
542  // try to use path normalized to an environmental variable or project path
543  wxString path = NormalizePath( filePath, &envVars, m_project->GetProjectPath() );
544 
545  // Do not use the project path in the global library table. This will almost
546  // assuredly be wrong for a different project.
547  if( path.IsEmpty() || (m_pageNdx == 0 && path.Contains( "${KIPRJMOD}" )) )
548  path = fn.GetFullPath();
549 
550  m_cur_grid->SetCellValue( last_row, COL_URI, path );
551  }
552  }
553 
554  if( !files.IsEmpty() )
555  {
556  m_cur_grid->MakeCellVisible( m_cur_grid->GetNumberRows() - 1, 0 );
557  m_cur_grid->SetGridCursor( m_cur_grid->GetNumberRows() - 1, 1 );
558  }
559 }
560 
561 
562 void PANEL_SYM_LIB_TABLE::appendRowHandler( wxCommandEvent& event )
563 {
565  return;
566 
567  if( m_cur_grid->AppendRows( 1 ) )
568  {
569  int row = m_cur_grid->GetNumberRows() - 1;
570 
571  // wx documentation is wrong, SetGridCursor does not make visible.
572  m_cur_grid->MakeCellVisible( row, 0 );
573  m_cur_grid->SetGridCursor( row, 1 );
574  m_cur_grid->EnableCellEditControl( true );
575  m_cur_grid->ShowCellEditControl();
576  }
577 }
578 
579 
580 void PANEL_SYM_LIB_TABLE::deleteRowHandler( wxCommandEvent& event )
581 {
583  return;
584 
585  int curRow = m_cur_grid->GetGridCursorRow();
586  int curCol = m_cur_grid->GetGridCursorCol();
587 
588  // In a wxGrid, collect rows that have a selected cell, or are selected
589  // It is not so easy: it depends on the way the selection was made.
590  // Here, we collect rows selected by clicking on a row label, and rows that contain
591  // previously-selected cells.
592  // If no candidate, just delete the row with the grid cursor.
593  wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
594  wxGridCellCoordsArray cells = m_cur_grid->GetSelectedCells();
595  wxGridCellCoordsArray blockTopLeft = m_cur_grid->GetSelectionBlockTopLeft();
596  wxGridCellCoordsArray blockBotRight = m_cur_grid->GetSelectionBlockBottomRight();
597 
598  // Add all row having cell selected to list:
599  for( unsigned ii = 0; ii < cells.GetCount(); ii++ )
600  selectedRows.Add( cells[ii].GetRow() );
601 
602  // Handle block selection
603  if( !blockTopLeft.IsEmpty() && !blockBotRight.IsEmpty() )
604  {
605  for( int i = blockTopLeft[0].GetRow(); i <= blockBotRight[0].GetRow(); ++i )
606  selectedRows.Add( i );
607  }
608 
609  // Use the row having the grid cursor only if we have no candidate:
610  if( selectedRows.size() == 0 && m_cur_grid->GetGridCursorRow() >= 0 )
611  selectedRows.Add( m_cur_grid->GetGridCursorRow() );
612 
613  if( selectedRows.size() == 0 )
614  {
615  wxBell();
616  return;
617  }
618 
619  std::sort( selectedRows.begin(), selectedRows.end() );
620 
621  // Remove selected rows (note: a row can be stored more than once in list)
622  int last_row = -1;
623 
624  for( int ii = selectedRows.GetCount()-1; ii >= 0; ii-- )
625  {
626  int row = selectedRows[ii];
627 
628  if( row != last_row )
629  {
630  last_row = row;
631  m_cur_grid->DeleteRows( row, 1 );
632  }
633  }
634 
635  if( m_cur_grid->GetNumberRows() > 0 && curRow >= 0 )
636  m_cur_grid->SetGridCursor( std::min( curRow, m_cur_grid->GetNumberRows() - 1 ), curCol );
637 }
638 
639 
640 void PANEL_SYM_LIB_TABLE::moveUpHandler( wxCommandEvent& event )
641 {
643  return;
644 
646  int curRow = m_cur_grid->GetGridCursorRow();
647 
648  // @todo: add multiple selection moves.
649  if( curRow >= 1 )
650  {
651  boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
652  tbl->rows.release( tbl->rows.begin() + curRow );
653 
654  --curRow;
655  tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
656 
657  if( tbl->GetView() )
658  {
659  // Update the wxGrid
660  wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow, 0 );
661  tbl->GetView()->ProcessTableMessage( msg );
662  }
663 
664  m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
665  m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
666  }
667 }
668 
669 
670 void PANEL_SYM_LIB_TABLE::moveDownHandler( wxCommandEvent& event )
671 {
673  return;
674 
676  int curRow = m_cur_grid->GetGridCursorRow();
677 
678  // @todo: add multiple selection moves.
679  if( unsigned( curRow + 1 ) < tbl->rows.size() )
680  {
681  boost::ptr_vector< LIB_TABLE_ROW >::auto_type move_me =
682  tbl->rows.release( tbl->rows.begin() + curRow );
683 
684  ++curRow;
685  tbl->rows.insert( tbl->rows.begin() + curRow, move_me.release() );
686 
687  if( tbl->GetView() )
688  {
689  // Update the wxGrid
690  wxGridTableMessage msg( tbl, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, curRow - 1, 0 );
691  tbl->GetView()->ProcessTableMessage( msg );
692  }
693 
694  m_cur_grid->MakeCellVisible( curRow, m_cur_grid->GetGridCursorCol() );
695  m_cur_grid->SetGridCursor( curRow, m_cur_grid->GetGridCursorCol() );
696  }
697 }
698 
699 
701 {
703  return;
704 
705  wxArrayInt selectedRows = m_cur_grid->GetSelectedRows();
706 
707  if( selectedRows.empty() && m_cur_grid->GetGridCursorRow() >= 0 )
708  selectedRows.push_back( m_cur_grid->GetGridCursorRow() );
709 
710  wxArrayInt legacyRows;
711  wxString legacyType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY );
712  wxString kicadType = SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_KICAD );
713  wxString msg;
714 
715  for( int row : selectedRows )
716  {
717  if( m_cur_grid->GetCellValue( row, COL_TYPE ) == legacyType )
718  legacyRows.push_back( row );
719  }
720 
721  if( legacyRows.size() <= 0 )
722  {
723  wxMessageBox( _( "Select one or more table rows containing legacy libraries to save as "
724  "current format (*.kicad_sym)." ) );
725  return;
726  }
727  else
728  {
729  if( legacyRows.size() == 1 )
730  {
731  msg.Printf( _( "Save '%s' as current format (*.kicad_sym) and "
732  "replace legacy entry in table?" ),
733  m_cur_grid->GetCellValue( legacyRows[0], COL_NICKNAME ) );
734  }
735  else
736  {
737  msg.Printf( _( "Save %d legacy libraries as current format (*.kicad_sym) and "
738  "replace legacy entries in table?" ),
739  (int) legacyRows.size() );
740  }
741 
742  if( !IsOK( m_parent, msg ) )
743  return;
744  }
745 
746  for( int row : legacyRows )
747  {
748  wxString libName = m_cur_grid->GetCellValue( row, COL_NICKNAME );
749  wxString relPath = m_cur_grid->GetCellValue( row, COL_URI );
750  wxString resolvedPath = ExpandEnvVarSubstitutions( relPath, m_project );
751  wxFileName legacyLib( resolvedPath );
752 
753  if( !legacyLib.Exists() )
754  {
755  msg.Printf( _( "Library '%s' not found." ), relPath );
756  DisplayErrorMessage( this, msg );
757  continue;
758  }
759 
760  wxFileName newLib( resolvedPath );
761  newLib.SetExt( "kicad_sym" );
762 
763  if( newLib.Exists() )
764  {
765  msg.Printf( _( "File '%s' already exists. Do you want overwrite this file?" ),
766  newLib.GetFullPath() );
767 
768  switch( wxMessageBox( msg, _( "Migrate Library" ),
769  wxYES_NO | wxCANCEL | wxICON_QUESTION, m_parent ) )
770  {
771  case wxYES: break;
772  case wxNO: continue;
773  case wxCANCEL: return;
774  }
775  }
776 
777  if( convertLibrary( libName, legacyLib.GetFullPath(), newLib.GetFullPath() ) )
778  {
779  relPath = NormalizePath( newLib.GetFullPath(), &Pgm().GetLocalEnvVariables(),
780  m_project );
781 
782  // Do not use the project path in the global library table. This will almost
783  // assuredly be wrong for a different project.
784  if( relPath.IsEmpty() || (m_cur_grid == m_global_grid && relPath.Contains( "${KIPRJMOD}" ) ) )
785  relPath = newLib.GetFullPath();
786 
787  m_cur_grid->SetCellValue( row, COL_URI, relPath );
788  m_cur_grid->SetCellValue( row, COL_TYPE, kicadType );
789  }
790  else
791  {
792  msg.Printf( _( "Failed to save symbol library file '%s'." ), newLib.GetFullPath() );
793  DisplayErrorMessage( this, msg );
794  }
795  }
796 }
797 
798 
799 bool PANEL_SYM_LIB_TABLE::convertLibrary( const wxString& aLibrary, const wxString& legacyFilepath,
800  const wxString& newFilepath )
801 {
802  SCH_PLUGIN::SCH_PLUGIN_RELEASER legacyPI( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_LEGACY ) );
803  SCH_PLUGIN::SCH_PLUGIN_RELEASER kicadPI( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
804  std::vector<LIB_PART*> parts;
805  std::vector<LIB_PART*> newParts;
806  std::map<LIB_PART*, LIB_PART*> partMap;
807 
808  try
809  {
810  // Write a stub file; SaveSymbol() expects something to be there already.
811  FILE_OUTPUTFORMATTER* formatter = new FILE_OUTPUTFORMATTER( newFilepath );
812 
813  formatter->Print( 0, "(kicad_symbol_lib (version %d) (generator kicad_converter))",
815 
816  // This will write the file
817  delete formatter;
818 
819  legacyPI->EnumerateSymbolLib( parts, legacyFilepath );
820 
821  // Copy non-aliases first so we can build a map from parts to newParts
822  for( LIB_PART* part : parts )
823  {
824  if( part->IsAlias() )
825  continue;
826 
827  newParts.push_back( new LIB_PART( *part ) );
828  partMap[part] = newParts.back();
829  }
830 
831  // Now do the aliases using the map to hook them up to their newPart parents
832  for( LIB_PART* part : parts )
833  {
834  if( !part->IsAlias() )
835  continue;
836 
837  newParts.push_back( new LIB_PART( *part ) );
838  newParts.back()->SetParent( partMap[ part->GetParent().lock().get() ] );
839  }
840 
841  // Finally write out newParts
842  for( LIB_PART* part : newParts )
843  {
844  kicadPI->SaveSymbol( newFilepath, part );
845  }
846  }
847  catch( ... )
848  {
849  return false;
850  }
851 
852  return true;
853 }
854 
855 
857 {
859  return false;
860 
861  if( !verifyTables() )
862  return false;
863 
864  if( *global_model() != *m_globalTable )
865  {
867 
868  m_globalTable->Clear();
869  m_globalTable->rows.transfer( m_globalTable->rows.end(), global_model()->rows.begin(),
870  global_model()->rows.end(), global_model()->rows );
872  }
873 
874  if( project_model() && *project_model() != *m_projectTable )
875  {
877 
879  m_projectTable->rows.transfer( m_projectTable->rows.end(), project_model()->rows.begin(),
880  project_model()->rows.end(), project_model()->rows );
882  }
883 
884  return true;
885 }
886 
887 
889 {
890  wxRegEx re( ".*?(\\$\\{(.+?)\\})|(\\$\\((.+?)\\)).*?", wxRE_ADVANCED );
891  wxASSERT( re.IsValid() ); // wxRE_ADVANCED is required.
892 
893  std::set< wxString > unique;
894 
895  // clear the table
896  m_path_subs_grid->DeleteRows( 0, m_path_subs_grid->GetNumberRows() );
897 
898  for( SYMBOL_LIB_TABLE_GRID* tbl : { global_model(), project_model() } )
899  {
900  if( !tbl )
901  continue;
902 
903  for( int row = 0; row < tbl->GetNumberRows(); ++row )
904  {
905  wxString uri = tbl->GetValue( row, COL_URI );
906 
907  while( re.Matches( uri ) )
908  {
909  wxString envvar = re.GetMatch( uri, 2 );
910 
911  // if not ${...} form then must be $(...)
912  if( envvar.IsEmpty() )
913  envvar = re.GetMatch( uri, 4 );
914 
915  // ignore duplicates
916  unique.insert( envvar );
917 
918  // delete the last match and search again
919  uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
920  }
921  }
922  }
923 
924  // Make sure this special environment variable shows up even if it was
925  // not used yet. It is automatically set by KiCad to the directory holding
926  // the current project.
927  unique.insert( PROJECT_VAR_NAME );
929 
930  for( const wxString& evName : unique )
931  {
932  int row = m_path_subs_grid->GetNumberRows();
933  m_path_subs_grid->AppendRows( 1 );
934 
935  m_path_subs_grid->SetCellValue( row, 0, wxT( "${" ) + evName + wxT( "}" ) );
936  m_path_subs_grid->SetCellEditor( row, 0, new GRID_CELL_READONLY_TEXT_EDITOR() );
937 
938  wxString evValue;
939  wxGetEnv( evName, &evValue );
940  m_path_subs_grid->SetCellValue( row, 1, evValue );
941  m_path_subs_grid->SetCellEditor( row, 1, new GRID_CELL_READONLY_TEXT_EDITOR() );
942  }
943 
944  // No combobox editors here, but it looks better if its consistent with the other
945  // grids in the dialog.
946  m_path_subs_grid->SetDefaultRowSize( m_path_subs_grid->GetDefaultRowSize() + 2 );
947 
948  adjustPathSubsGridColumns( m_path_subs_grid->GetRect().GetWidth() );
949 }
950 
951 
953 {
954  // Account for scroll bars
955  aWidth -= ( m_path_subs_grid->GetSize().x - m_path_subs_grid->GetClientSize().x );
956 
957  m_path_subs_grid->AutoSizeColumn( 0 );
958 
959  int remaining_width = aWidth - m_path_subs_grid->GetColSize( 0 );
960 
961  if( remaining_width < 0 )
962  m_path_subs_grid->SetColSize( 1, -1 );
963  else
964  m_path_subs_grid->SetColSize( 1, remaining_width );
965 }
966 
967 
968 void PANEL_SYM_LIB_TABLE::onSizeGrid( wxSizeEvent& event )
969 {
970  adjustPathSubsGridColumns( event.GetSize().GetX() );
971 
972  event.Skip();
973 }
974 
975 
977 {
978  return (SYMBOL_LIB_TABLE_GRID*) m_global_grid->GetTable();
979 }
980 
981 
983 {
984  return m_project_grid ? (SYMBOL_LIB_TABLE_GRID*) m_project_grid->GetTable() : nullptr;
985 }
986 
987 
989 {
990  return (SYMBOL_LIB_TABLE_GRID*) m_cur_grid->GetTable();
991 }
992 
993 
995 
996 
997 void InvokeSchEditSymbolLibTable( KIWAY* aKiway, wxWindow *aParent )
998 {
999  auto* schEditor = (SCH_EDIT_FRAME*) aKiway->Player( FRAME_SCH, false );
1000  auto* symbolEditor = (SYMBOL_EDIT_FRAME*) aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
1001  auto* symbolViewer = (SYMBOL_VIEWER_FRAME*) aKiway->Player( FRAME_SCH_VIEWER, false );
1002 
1004  wxString globalTablePath = SYMBOL_LIB_TABLE::GetGlobalTableFileName();
1005  SYMBOL_LIB_TABLE* projectTable = nullptr;
1006  wxString projectPath = aKiway->Prj().GetProjectPath();
1007  wxFileName projectTableFn( projectPath, SYMBOL_LIB_TABLE::GetSymbolLibTableFileName() );
1008  wxString msg;
1009  wxString currentLib;
1010 
1011  // Don't allow editing project tables if no project is open
1012  if( !aKiway->Prj().IsNullProject() )
1013  projectTable = aKiway->Prj().SchSymbolLibTable();
1014 
1015  if( symbolEditor )
1016  {
1017  currentLib = symbolEditor->GetCurLib();
1018 
1019  // This prevents an ugly crash on OSX (https://bugs.launchpad.net/kicad/+bug/1765286)
1020  symbolEditor->FreezeLibraryTree();
1021 
1022  if( symbolEditor->HasLibModifications() )
1023  {
1024  msg = _( "Modifications have been made to one or more symbol libraries.\n"
1025  "Changes must be saved or discarded before the symbol library "
1026  "table can be modified." );
1027 
1028  switch( UnsavedChangesDialog( aParent, msg ) )
1029  {
1030  case wxID_YES: symbolEditor->SaveAll(); break;
1031  case wxID_NO: symbolEditor->RevertAll(); break;
1032  default:
1033  case wxID_CANCEL: symbolEditor->ThawLibraryTree(); return;
1034  }
1035  }
1036  }
1037 
1038  DIALOG_EDIT_LIBRARY_TABLES dlg( aParent, _( "Symbol Libraries" ) );
1039  dlg.SetKiway( &dlg, aKiway );
1040 
1041  dlg.InstallPanel( new PANEL_SYM_LIB_TABLE( &dlg, &aKiway->Prj(), globalTable, globalTablePath,
1042  projectTable, projectTableFn.GetFullPath() ) );
1043 
1044  if( dlg.ShowModal() == wxID_CANCEL )
1045  {
1046  if( symbolEditor )
1047  symbolEditor->ThawLibraryTree();
1048 
1049  return;
1050  }
1051 
1052  if( dlg.m_GlobalTableChanged )
1053  {
1054  try
1055  {
1056  globalTable->Save( globalTablePath );
1057  }
1058  catch( const IO_ERROR& ioe )
1059  {
1060  msg.Printf( _( "Error saving global library table:\n\n%s" ), ioe.What() );
1061  wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
1062  }
1063  }
1064 
1065  if( projectTable && dlg.m_ProjectTableChanged )
1066  {
1067  try
1068  {
1069  projectTable->Save( projectTableFn.GetFullPath() );
1070  }
1071  catch( const IO_ERROR& ioe )
1072  {
1073  msg.Printf( _( "Error saving project-specific library table:\n\n%s" ), ioe.What() );
1074  wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
1075  }
1076  }
1077 
1078  if( schEditor )
1079  schEditor->SyncView();
1080 
1081  if( symbolEditor )
1082  {
1083  // Check if the currently selected symbol library been removed or disabled.
1084  if( !currentLib.empty() && projectTable && !projectTable->HasLibrary( currentLib, true ) )
1085  {
1086  symbolEditor->SetCurLib( wxEmptyString );
1087  symbolEditor->emptyScreen();
1088  }
1089 
1090  symbolEditor->SyncLibraries( true );
1091  symbolEditor->ThawLibraryTree();
1092  symbolEditor->RefreshLibraryTree();
1093  }
1094 
1095  if( symbolViewer )
1096  symbolViewer->ReCreateLibList();
1097 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:252
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:265
This file is part of the common library.
void reindex()
bool ContainsNickname(const wxString &aNickname)
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition: kiway.cpp:184
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:79
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:136
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:368
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:273
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.
Definition: project.cpp:123
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
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
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)
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:154
wxString LegacySymbolLibFileWildcard()
void appendRowHandler(wxCommandEvent &event) override
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
Definition: bitmap.cpp:104
SYMBOL_LIB_TABLE_GRID(const SYMBOL_LIB_TABLE &aTableToEdit)
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition: project.cpp:135
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:473
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:220
static wxString GetDefaultUserSymbolsPath()
Gets the default path we point users to create projects.
Definition: paths.cpp:97
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
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
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.
The common library.
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:296
static wxString GetGlobalTableFileName()
Fetch the global symbol library table file name.
size_t size() const override
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