KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_import_symbol_select.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 modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * 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, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <bitmaps.h>
23#include <confirm.h>
24#include <kidialog.h>
25#include <kiway.h>
26#include <lib_symbol.h>
28#include <symbol_edit_frame.h>
30#include <wx/filename.h>
31#include <wx/msgdlg.h>
32#include <wx/dataview.h>
33
34
35namespace
36{
37
39constexpr wxUIntPtr ROW_DATA_DERIVED = 1;
40
42constexpr unsigned int SYMBOL_COLUMN = 1;
43
44
52class IMPORT_SYMBOL_LIST_STORE : public wxDataViewListStore
53{
54public:
55 bool GetAttrByRow( unsigned int aRow, unsigned int aCol,
56 wxDataViewItemAttr& aAttr ) const override
57 {
58 if( aCol == SYMBOL_COLUMN && GetItemData( GetItem( aRow ) ) == ROW_DATA_DERIVED )
59 {
60 aAttr.SetItalic( true );
61 return true;
62 }
63
64 return false;
65 }
66};
67
68} // namespace
69
70
72 const wxString& aFilePath,
73 const wxString& aDestLibrary,
74 SCH_IO_MGR::SCH_FILE_T aPluginType ) :
76 m_frame( aParent ),
77 m_filePath( aFilePath ),
78 m_destLibrary( aDestLibrary ),
79 m_plugin( SCH_IO_MGR::FindPlugin( aPluginType ) ),
80 m_preview( nullptr )
81{
82 wxFileName fn( aFilePath );
83 SetTitle( wxString::Format( _( "Import Symbols from %s" ), fn.GetFullName() ) );
84
85 // Replace the default store with our italicizing variant before adding columns
86 // so the columns are bound to the new model.
87 IMPORT_SYMBOL_LIST_STORE* store = new IMPORT_SYMBOL_LIST_STORE();
88 m_symbolList->AssociateModel( store );
89 store->DecRef();
90
91 m_symbolList->AppendToggleColumn( wxEmptyString, wxDATAVIEW_CELL_ACTIVATABLE, 30 );
92 m_symbolList->AppendIconTextColumn( _( "Symbol" ), wxDATAVIEW_CELL_INERT, 250 );
93
94 m_symbolList->Connect( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED,
95 wxDataViewEventHandler( DIALOG_IMPORT_SYMBOL_SELECT::onItemChecked ),
96 nullptr, this );
97
100 m_previewSizer->Add( m_preview, 1, wxEXPAND, 0 );
101 m_previewPanel->Layout();
102 m_unitChoice->Enable( false );
103
104 SetupStandardButtons( { { wxID_OK, _( "Import" ) } } );
105 m_sdbSizerOK->Disable();
106
109}
110
111
113{
114 m_symbolList->Disconnect( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED,
115 wxDataViewEventHandler( DIALOG_IMPORT_SYMBOL_SELECT::onItemChecked ),
116 nullptr, this );
117}
118
119
121{
122 if( !loadSymbols() )
123 return false;
124
125 m_manager.BuildDependencyMaps();
126 refreshList();
128
129 return true;
130}
131
132
137
138
140{
141 if( !m_plugin )
142 {
143 DisplayError( this, _( "Unable to find a plugin to read this library." ) );
144 return false;
145 }
146
147 wxArrayString symbolNames;
148
149 try
150 {
151 m_plugin->EnumerateSymbolLib( symbolNames, m_filePath );
152 }
153 catch( const IO_ERROR& ioe )
154 {
156 wxString::Format( _( "Cannot read symbol library '%s'." ), m_filePath ),
157 ioe.What() );
158 return false;
159 }
160
161 if( symbolNames.empty() )
162 {
163 DisplayError( this, wxString::Format( _( "Symbol library '%s' is empty." ), m_filePath ) );
164 return false;
165 }
166
167 // Get the library manager to check for existing symbols
168 LIB_SYMBOL_LIBRARY_MANAGER& libMgr = m_frame->GetLibManager();
169 m_manager.Clear();
170
171 for( const wxString& name : symbolNames )
172 {
173 wxString parentName;
174 bool isPower = false;
175 LIB_SYMBOL* sym = nullptr;
176
177 try
178 {
179 sym = m_plugin->LoadSymbol( m_filePath, name );
180
181 if( sym )
182 {
183 parentName = sym->GetParentName();
184 isPower = sym->IsPower();
185 }
186 }
187 catch( const IO_ERROR& )
188 {
189 // Symbol failed to load - still add it to list but without full info
190 }
191
192 // Add to manager - don't pass the symbol pointer since LoadSymbol returns
193 // a cached pointer owned by the plugin, not a new allocation
194 m_manager.AddSymbol( name, parentName, isPower, nullptr );
195 }
196
197 m_manager.CheckExistingSymbols(
198 [&libMgr, this]( const wxString& name ) {
199 return libMgr.SymbolExists( name, m_destLibrary );
200 } );
201
202 return true;
203}
204
205
207{
208 m_symbolList->DeleteAllItems();
209 m_listIndices.clear();
210
211 int index = 0;
212
213 for( const wxString& name : m_manager.GetSymbolNames() )
214 {
215 if( !matchesFilter( name ) )
216 {
217 m_listIndices[name] = -1;
218 continue;
219 }
220
222
223 const SYMBOL_IMPORT_INFO* info = m_manager.GetSymbolInfo( name );
224
225 if( !info )
226 continue;
227
228 wxVector<wxVariant> data;
229 wxIcon icon;
230
231 // Checkbox column - show checked for both manual and auto-selected
232 bool isChecked = info->m_checked || info->m_autoSelected;
233 data.push_back( wxVariant( isChecked ) );
234
235 if( info->m_isPower )
236 {
237 wxBitmap bmp = KiBitmap( BITMAPS::add_power );
238 icon.CopyFromBitmap( bmp );
239 }
240 else if( info->m_existsInDest )
241 {
242 wxBitmap bmp = KiBitmap( BITMAPS::small_warning );
243 icon.CopyFromBitmap( bmp );
244 }
245 // Derived (non-root) symbols are indicated by italic text via the custom
246 // store's GetAttrByRow override, matching the symbol library tree.
247
248 wxDataViewIconText iconText( name, icon );
249 data.push_back( wxVariant( iconText ) );
250
251 // Tag derived (non-root) rows so the store italicizes them, matching the
252 // convention used by the symbol library tree.
253 wxUIntPtr rowData = info->m_parentName.IsEmpty() ? 0 : ROW_DATA_DERIVED;
254 m_symbolList->AppendItem( data, rowData );
255 index++;
256 }
257
259}
260
261
263{
264 if( m_selectedSymbol.IsEmpty() )
265 {
266 m_preview->DisplayPart( nullptr, 0 );
267 m_unitChoice->Clear();
268 m_unitChoice->Enable( false );
269 return;
270 }
271
272 // Load symbol from plugin for preview (returns cached pointer)
273 LIB_SYMBOL* sym = nullptr;
274
275 try
276 {
277 sym = m_plugin->LoadSymbol( m_filePath, m_selectedSymbol );
278 }
279 catch( const IO_ERROR& )
280 {
281 m_preview->DisplayPart( nullptr, 0 );
282 return;
283 }
284
285 if( !sym )
286 {
287 m_preview->DisplayPart( nullptr, 0 );
288 return;
289 }
290
291 int unitCount = std::max( sym->GetUnitCount(), 1 );
292
293 // Update unit choice if count changed
294 m_unitChoice->Enable( unitCount > 1 );
295 m_unitChoice->Clear();
296
297 if( unitCount > 1 )
298 {
299 for( int ii = 0; ii < unitCount; ii++ )
300 m_unitChoice->Append( sym->GetUnitDisplayName( ii + 1, true ) );
301
302 m_unitChoice->SetSelection( 0 );
303 }
304
305 int selectedUnit = ( m_unitChoice->GetSelection() != wxNOT_FOUND )
306 ? m_unitChoice->GetSelection() + 1
307 : 1;
308
309 // For derived symbols, we need to flatten to show properly
310 std::unique_ptr<LIB_SYMBOL> flattenedSym;
311
312 if( sym->IsDerived() || !sym->GetParentName().IsEmpty() )
313 {
314 try
315 {
316 flattenedSym = sym->Flatten();
317 m_preview->DisplayPart( flattenedSym.get(), selectedUnit );
318 }
319 catch( const IO_ERROR& )
320 {
321 // show unflattened symbol as fallback
322 m_preview->DisplayPart( sym, selectedUnit );
323 }
324 }
325 else
326 {
327 m_preview->DisplayPart( sym, selectedUnit );
328 }
329}
330
331
333{
334 int manualCount = m_manager.GetManualSelectionCount();
335 int autoCount = m_manager.GetAutoSelectionCount();
336
337 wxString status;
338
339 if( autoCount > 0 )
340 {
341 status = wxString::Format( _( "%d symbols selected, %d parents auto-included" ),
342 manualCount, autoCount );
343 }
344 else
345 {
346 status = wxString::Format( _( "%d symbols selected" ), manualCount );
347 }
348
349 m_statusLine->SetLabel( status );
350}
351
352
354{
355 bool hasSelection = !m_manager.GetSymbolsToImport().empty();
356 m_sdbSizerOK->Enable( hasSelection );
357}
358
359
361{
362 m_filterString = m_searchCtrl->GetValue().Lower();
363 refreshList();
364}
365
366
368{
369 int row = m_symbolList->GetSelectedRow();
370
371 if( row == wxNOT_FOUND )
372 {
373 m_selectedSymbol.clear();
375 return;
376 }
377
378 for( const auto& [name, listIndex] : m_listIndices )
379 {
380 if( listIndex == row )
381 {
384 return;
385 }
386 }
387}
388
389
390void DIALOG_IMPORT_SYMBOL_SELECT::onItemChecked( wxDataViewEvent& event )
391{
392 if( event.GetColumn() != COL_CHECKBOX )
393 return;
394
395 int row = m_symbolList->ItemToRow( event.GetItem() );
396
397 if( row == wxNOT_FOUND )
398 return;
399
400 for( const auto& [name, listIndex] : m_listIndices )
401 {
402 if( listIndex == row )
403 {
404 wxVariant value;
405 m_symbolList->GetValue( value, row, COL_CHECKBOX );
406 bool newState = value.GetBool();
407
408 toggleSymbolSelection( name, newState );
409 return;
410 }
411 }
412}
413
414
415bool DIALOG_IMPORT_SYMBOL_SELECT::toggleSymbolSelection( const wxString& aSymbolName, bool aChecked )
416{
417 if( aChecked )
418 {
419 std::vector<wxString> changed = m_manager.SetSymbolSelected( aSymbolName, true );
420
421 for( const wxString& changedName : changed )
422 {
423 auto it = m_listIndices.find( changedName );
424
425 if( it != m_listIndices.end() && it->second >= 0 )
426 {
427 m_symbolList->GetStore()->SetValueByRow( true, it->second, COL_CHECKBOX );
428 }
429 }
430 }
431 else
432 {
433 m_manager.DeselectWithDescendants( aSymbolName );
434
435 for( const wxString& name : m_manager.GetSymbolNames() )
436 {
437 auto it = m_listIndices.find( name );
438
439 if( it != m_listIndices.end() && it->second >= 0 )
440 {
441 const SYMBOL_IMPORT_INFO* info = m_manager.GetSymbolInfo( name );
442
443 if( info )
444 {
445 bool shouldBeChecked = info->m_checked || info->m_autoSelected;
446 m_symbolList->GetStore()->SetValueByRow( shouldBeChecked, it->second, COL_CHECKBOX );
447 }
448 }
449 }
450 }
451
454 return true;
455}
456
457
458bool DIALOG_IMPORT_SYMBOL_SELECT::matchesFilter( const wxString& aSymbolName ) const
459{
461}
462
463
464void DIALOG_IMPORT_SYMBOL_SELECT::OnSelectAll( wxCommandEvent& event )
465{
466 m_manager.SelectAll( [this]( const wxString& name ) { return matchesFilter( name ); } );
467
468 refreshList();
471}
472
473
474void DIALOG_IMPORT_SYMBOL_SELECT::OnSelectNone( wxCommandEvent& event )
475{
476 m_manager.DeselectAll( [this]( const wxString& name ) { return matchesFilter( name ); } );
477
478 refreshList();
481}
482
483
485{
486 if( m_selectedSymbol.IsEmpty() )
487 return;
488
489 int selectedUnit = ( m_unitChoice->GetSelection() != wxNOT_FOUND )
490 ? m_unitChoice->GetSelection() + 1
491 : 1;
492
493 // Load symbol from plugin for preview (returns cached pointer)
494 LIB_SYMBOL* sym = nullptr;
495
496 try
497 {
498 sym = m_plugin->LoadSymbol( m_filePath, m_selectedSymbol );
499 }
500 catch( const IO_ERROR& )
501 {
502 return;
503 }
504
505 if( !sym )
506 return;
507
508 // For derived symbols, we need to flatten to show properly
509 std::unique_ptr<LIB_SYMBOL> flattenedSym;
510
511 if( sym->IsDerived() || !sym->GetParentName().IsEmpty() )
512 {
513 try
514 {
515 flattenedSym = sym->Flatten();
516 m_preview->DisplayPart( flattenedSym.get(), selectedUnit );
517 }
518 catch( const IO_ERROR& )
519 {
520 m_preview->DisplayPart( sym, selectedUnit );
521 }
522 }
523 else
524 {
525 m_preview->DisplayPart( sym, selectedUnit );
526 }
527}
528
529
531{
532 return m_manager.GetSymbolsToImport();
533}
534
535
537{
538 m_conflictResolutions.clear();
539
540 std::vector<wxString> conflicts = m_manager.GetConflicts();
541
542 if( conflicts.empty() )
543 return true;
544
545 wxDialog dlg( this, wxID_ANY, _( "Resolve Import Conflicts" ),
546 wxDefaultPosition, wxSize( 500, 400 ),
547 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER );
548
549 wxBoxSizer* mainSizer = new wxBoxSizer( wxVERTICAL );
550
551 wxStaticText* label = new wxStaticText( &dlg, wxID_ANY,
552 _( "The following symbols already exist in the destination library. "
553 "Choose how to handle each conflict:" ) );
554 label->Wrap( 450 );
555 mainSizer->Add( label, 0, wxALL | wxEXPAND, 10 );
556
557 wxDataViewListCtrl* conflictList = new wxDataViewListCtrl( &dlg, wxID_ANY );
558 conflictList->AppendTextColumn( _( "Symbol" ), wxDATAVIEW_CELL_INERT, 200 );
559 conflictList->AppendTextColumn( _( "Action" ), wxDATAVIEW_CELL_EDITABLE, 100 );
560
561 for( const wxString& name : conflicts )
562 {
563 wxVector<wxVariant> data;
564 data.push_back( wxVariant( name ) );
565 data.push_back( wxVariant( _( "Overwrite" ) ) );
566 conflictList->AppendItem( data );
567
569 }
570
571 mainSizer->Add( conflictList, 1, wxALL | wxEXPAND, 10 );
572
573 wxBoxSizer* actionSizer = new wxBoxSizer( wxHORIZONTAL );
574 wxButton* skipAllBtn = new wxButton( &dlg, wxID_ANY, _( "Skip All" ) );
575 wxButton* overwriteAllBtn = new wxButton( &dlg, wxID_ANY, _( "Overwrite All" ) );
576 actionSizer->Add( skipAllBtn, 0, wxRIGHT, 5 );
577 actionSizer->Add( overwriteAllBtn, 0 );
578 mainSizer->Add( actionSizer, 0, wxLEFT | wxRIGHT | wxBOTTOM, 10 );
579
580 wxStdDialogButtonSizer* btnSizer = new wxStdDialogButtonSizer();
581 btnSizer->AddButton( new wxButton( &dlg, wxID_OK, _( "Import" ) ) );
582 btnSizer->AddButton( new wxButton( &dlg, wxID_CANCEL ) );
583 btnSizer->Realize();
584 mainSizer->Add( btnSizer, 0, wxALL | wxEXPAND, 10 );
585
586 dlg.SetSizer( mainSizer );
587
588 skipAllBtn->Bind( wxEVT_BUTTON, [&]( wxCommandEvent& ) {
589 for( size_t i = 0; i < conflicts.size(); i++ )
590 {
591 conflictList->SetTextValue( _( "Skip" ), i, 1 );
593 }
594 } );
595
596 overwriteAllBtn->Bind( wxEVT_BUTTON, [&]( wxCommandEvent& ) {
597 for( size_t i = 0; i < conflicts.size(); i++ )
598 {
599 conflictList->SetTextValue( _( "Overwrite" ), i, 1 );
601 }
602 } );
603
604 conflictList->Bind( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [&]( wxDataViewEvent& evt ) {
605 int row = conflictList->ItemToRow( evt.GetItem() );
606
607 if( row >= 0 && row < (int) conflicts.size() )
608 {
609 wxString action = conflictList->GetTextValue( row, 1 );
610 m_conflictResolutions[conflicts[row]] =
611 ( action == _( "Skip" ) ) ? CONFLICT_RESOLUTION::SKIP
613 }
614 } );
615
616 return dlg.ShowModal() == wxID_OK;
617}
int index
const char * name
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:100
DIALOG_IMPORT_SYMBOL_SELECT_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Import Symbols from %s"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(900, 650), long style=wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
bool loadSymbols()
Load symbols from the source file and populate the manager.
SYMBOL_IMPORT_MANAGER m_manager
Manager for symbol selection logic.
void refreshList()
Refresh the list control based on current filter and selections.
std::vector< wxString > GetSelectedSymbols() const
Get the list of symbols selected for import.
bool toggleSymbolSelection(const wxString &aSymbolName, bool aChecked)
Toggle selection state for a symbol.
wxString m_filterString
Current filter string.
wxString m_selectedSymbol
Currently selected symbol for preview.
bool matchesFilter(const wxString &aSymbolName) const
Check if a symbol matches the current filter.
std::map< wxString, CONFLICT_RESOLUTION > m_conflictResolutions
Conflict resolutions chosen by user.
void OnSymbolSelected(wxDataViewEvent &event) override
bool resolveConflicts()
Show conflict resolution dialog.
void updateImportButton()
Update import button enabled state based on selection.
void updateStatusLine()
Update the status line with selection counts.
void OnFilterTextChanged(wxCommandEvent &event) override
void OnSelectAll(wxCommandEvent &event) override
std::map< wxString, int > m_listIndices
Map from symbol name to list index (UI-only, -1 if filtered out)
void OnSelectNone(wxCommandEvent &event) override
void onItemChecked(wxDataViewEvent &event)
Handle checkbox toggle in the list.
void OnUnitChanged(wxCommandEvent &event) override
DIALOG_IMPORT_SYMBOL_SELECT(SYMBOL_EDIT_FRAME *aParent, const wxString &aFilePath, const wxString &aDestLibrary, SCH_IO_MGR::SCH_FILE_T aPluginType)
void updatePreview()
Update the preview for the currently selected symbol.
IO_RELEASER< SCH_IO > m_plugin
Plugin kept alive for symbol access during dialog lifetime.
void SetInitialFocus(wxWindow *aWindow)
Sets the window (usually a wxTextCtrl) that should be focused when the dialog is shown.
Definition dialog_shim.h:79
void SetupStandardButtons(std::map< int, wxString > aLabels={})
void finishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
@ GAL_TYPE_OPENGL
OpenGL implementation.
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
KIWAY & Kiway() const
Return a reference to the KIWAY that this object has an opportunity to participate in.
Symbol library management helper that is specific to the symbol library editor frame.
Define a library symbol object.
Definition lib_symbol.h:80
bool IsPower() const override
bool IsDerived() const
Definition lib_symbol.h:197
const wxString & GetParentName() const
Definition lib_symbol.h:903
int GetUnitCount() const override
std::unique_ptr< LIB_SYMBOL > Flatten() const
Return a flattened symbol inheritance to the caller.
wxString GetUnitDisplayName(int aUnit, bool aLabel) const override
Return the user-defined display name for aUnit for symbols with units.
A factory which returns an instance of a SCH_IO.
Definition sch_io_mgr.h:50
The symbol library editor main window.
static bool MatchesFilter(const wxString &aSymbolName, const wxString &aFilter)
Check if a symbol name matches a filter string (case-insensitive contains).
bool SymbolExists(const wxString &aSymbolName, const wxString &aLibrary) const
Return true if symbol with a specific alias exists in library (either original one or buffered).
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:192
This file is part of the common library.
#define _(s)
Information about a symbol available for import.
@ OVERWRITE
Overwrite existing symbol.
@ SKIP
Don't import this symbol.