KiCad PCB EDA Suite
Loading...
Searching...
No Matches
symbol_editor.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) 2019 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <pgm_base.h>
23#include <clipboard.h>
24#include <confirm.h>
25#include <kidialog.h>
26#include <kiway.h>
27#include <tool/tool_manager.h>
28#include <tool/actions.h>
29#include <widgets/wx_infobar.h>
30#include <sch_edit_frame.h>
31#include <symbol_edit_frame.h>
34#include <template_fieldnames.h>
37#include <symbol_tree_pane.h>
39#include <richio.h>
40#include <widgets/lib_tree.h>
44#include <eda_list_dialog.h>
45#include <set>
46#include <wx/clipbrd.h>
47#include <wx/dirdlg.h>
48#include <wx/filedlg.h>
49#include <wx/log.h>
50#include <project_sch.h>
51#include <kiplatform/io.h>
52#include <kiplatform/ui.h>
53#include <string_utils.h>
54#include "symbol_saveas_type.h"
58
59
61{
62 SetTitle( _( "Symbol Editor" ) );
63}
64
65
67{
68 if( GetCurSymbol() )
69 {
71 {
72 SCH_EDIT_FRAME* schframe = (SCH_EDIT_FRAME*) Kiway().Player( FRAME_SCH, false );
73
74 if( !schframe ) // happens when the schematic editor has been closed
75 {
76 DisplayErrorMessage( this, _( "No schematic currently open." ) );
77 return false;
78 }
79 else
80 {
82 GetScreen()->SetContentModified( false );
83 return true;
84 }
85 }
86 else
87 {
88 const wxString& libName = GetCurSymbol()->GetLibId().GetLibNickname();
89
90 // A brand-new symbol has no library home yet, so its first save asks for one and
91 // promotes the unsaved tab to a library tab.
92 if( libName.IsEmpty() )
93 {
94 saveSymbolCopyAs( false );
95 return !GetScreen()->IsContentModified();
96 }
97
98 if( m_libMgr->IsLibraryReadOnly( libName ) )
99 {
100 wxString msg = wxString::Format( _( "Symbol library '%s' is not writable." ),
101 libName );
102 wxString msg2 = _( "You must save to a different location." );
103
104 if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) == wxID_OK )
105 return saveLibrary( libName, SAVE_LIBRARY_AS::NEW );
106 }
107 else
108 {
109 return saveLibrary( libName, SAVE_LIBRARY_AS::ORIGINAL );
110 }
111 }
112 }
113
114 return false;
115}
116
117
118bool SYMBOL_EDIT_FRAME::LoadSymbol( const LIB_ID& aLibId, int aUnit, int aBodyStyle )
119{
120 LIB_ID libId = aLibId;
123
124 // Some libraries can't be edited, so load the underlying chosen symbol
125 if( auto optRow = manager.GetRow( LIBRARY_TABLE_TYPE::SYMBOL, aLibId.GetLibNickname() ); optRow.has_value() )
126 {
127 const LIBRARY_TABLE_ROW* row = *optRow;
128 SCH_IO_MGR::SCH_FILE_T type = SCH_IO_MGR::EnumFromStr( row->Type() );
129
130 if( type == SCH_IO_MGR::SCH_DATABASE
131 || type == SCH_IO_MGR::SCH_CADSTAR_ARCHIVE
132 || type == SCH_IO_MGR::SCH_HTTP )
133 {
134 try
135 {
136 LIB_SYMBOL* readOnlySym = adapter->LoadSymbol( aLibId );
137
138 if( readOnlySym && readOnlySym->GetSourceLibId().IsValid() )
139 libId = readOnlySym->GetSourceLibId();
140 }
141 catch( const IO_ERROR& ioe )
142 {
143 wxString msg;
144
145 msg.Printf( _( "Error loading symbol %s from library '%s'." ),
146 aLibId.GetUniStringLibId(),
147 aLibId.GetUniStringLibItemName() );
148 DisplayErrorMessage( this, msg, ioe.What() );
149 return false;
150 }
151 }
152 }
153
154 if( GetCurSymbol()
156 && GetCurSymbol()->GetLibId() == libId
157 && GetUnit() == aUnit
158 && GetBodyStyle() == aBodyStyle )
159 {
160 return true;
161 }
162
164 {
165 if( !HandleUnsavedChanges( this, _( "The current symbol has been modified. Save changes?" ),
166 [&]() -> bool
167 {
168 return saveCurrentSymbol();
169 } ) )
170 {
171 return false;
172 }
173 }
174
175 if( LoadSymbolFromLib( libId.GetLibNickname(), libId.GetLibItemName(), aUnit, aBodyStyle ) )
176 {
177 m_treePane->GetLibTree()->SelectLibId( libId );
178 m_treePane->GetLibTree()->ExpandLibId( libId );
179
180 m_centerItemOnIdle = libId;
181 Bind( wxEVT_IDLE, &SYMBOL_EDIT_FRAME::centerItemIdleHandler, this );
182 setSymWatcher( &libId );
183
184 return true;
185 }
186
187 return false;
188}
189
190
192{
193 m_treePane->GetLibTree()->CenterLibId( m_centerItemOnIdle );
194 Unbind( wxEVT_IDLE, &SYMBOL_EDIT_FRAME::centerItemIdleHandler, this );
195}
196
197
198bool SYMBOL_EDIT_FRAME::LoadSymbolFromLib( const wxString& aLibName, const wxString& aSymbolName, int aUnit,
199 int aBodyStyle )
200{
201 LIB_SYMBOL* symbol = nullptr;
202
203 try
204 {
205 symbol = PROJECT_SCH::SymbolLibAdapter( &Prj() )->LoadSymbol( aLibName, aSymbolName );
206 }
207 catch( const IO_ERROR& ioe )
208 {
209 wxString msg;
210
211 msg.Printf( _( "Error loading symbol %s from library '%s'." ),
212 UnescapeString( aSymbolName ),
213 UnescapeString( aLibName ) );
214 DisplayErrorMessage( this, msg, ioe.What() );
215 return false;
216 }
217
218 if( !symbol || !LoadOneLibrarySymbol( symbol, aLibName, aUnit, aBodyStyle ) )
219 return false;
220
222
224
225 return true;
226}
227
228
229bool SYMBOL_EDIT_FRAME::LoadOneLibrarySymbol( LIB_SYMBOL* aEntry, const wxString& aLibrary, int aUnit, int aBodyStyle )
230{
231 bool rebuildMenuAndToolbar = false;
232
233 if( !aEntry || aLibrary.empty() )
234 return false;
235
236 if( aEntry->GetName().IsEmpty() )
237 {
238 wxLogWarning( "Symbol in library '%s' has empty name field.", aLibrary );
239 return false;
240 }
241
243
244 // Switching away from a schematic-instance tab changes the available menu/toolbar actions. The
245 // instance tab keeps owning its working objects, so nothing is deleted here.
247 rebuildMenuAndToolbar = true;
248
249 LIB_SYMBOL* lib_symbol = m_libMgr->GetBufferedSymbol( aEntry->GetName(), aLibrary );
250 wxCHECK( lib_symbol, false );
251
252 // Activating the tab installs these, the outgoing tab must first save the frame's own
253 const int unit = aUnit > 0 ? aUnit : 1;
254 const int bodyStyle = aBodyStyle > 0 ? aBodyStyle : 1;
255
256 // Open as a preview tab that the next library-open reuses until the symbol is edited.
257 bool wasCreated = false;
258 SYMBOL_EDITOR_TAB_CONTEXT* ctx = findOrCreateSymbolTab( aLibrary, lib_symbol->GetName(),
259 unit, bodyStyle, true,
260 &wasCreated );
261 wxCHECK( ctx, false );
262
263 if( rebuildMenuAndToolbar )
264 {
267 GetInfoBar()->Dismiss();
268 }
269
271
272 // Only a freshly-created tab gets a clean undo history; re-focusing preserves the live stack.
273 if( wasCreated )
275
276 if( !IsSymbolFromSchematic() )
277 {
278 LIB_ID libId = GetCurSymbol()->GetLibId();
279 setSymWatcher( &libId );
280 }
281
284
285 // Display the document information based on the entry selected just in
286 // case the entry is an alias.
288 Refresh();
289
290 return true;
291}
292
293
295{
296 saveAllLibraries( false );
297 m_treePane->GetLibTree()->RefreshLibTree();
298}
299
300
301void SYMBOL_EDIT_FRAME::CreateNewSymbol( const wxString& aInheritFrom )
302{
304
305 wxString lib = getTargetLib();
306
307 wxArrayString symbolNamesInLib;
308 wxArrayString derivedSymbols;
309
310 // With no target library there are no names to list or style; querying would create a bogus
311 // empty library buffer keyed by an empty nickname.
312 if( !lib.empty() )
313 {
314 m_libMgr->GetSymbolNames( lib, symbolNamesInLib, SYMBOL_NAME_FILTER::ALL );
315 m_libMgr->GetSymbolNames( lib, derivedSymbols, SYMBOL_NAME_FILTER::DERIVED_ONLY );
316 }
317
318 const auto validator =
319 [&]( wxString newName ) -> bool
320 {
321 if( newName.IsEmpty() )
322 {
323 wxMessageBox( _( "Symbol must have a name." ) );
324 return false;
325 }
326
327 if( !lib.empty() && m_libMgr->SymbolNameInUse( newName, lib ) )
328 {
329 wxString msg;
330
331 msg.Printf( _( "Symbol '%s' already exists in library '%s'." ),
332 UnescapeString( newName ),
333 lib );
334
335 KIDIALOG errorDlg( this, msg, _( "Confirmation" ),
336 wxOK | wxCANCEL | wxICON_WARNING );
337
338 errorDlg.SetOKLabel( _( "Overwrite" ) );
339
340 return errorDlg.ShowModal() == wxID_OK;
341 }
342
343 return true;
344 };
345
346 const auto styler =
347 [&]( const wxString& aItem ) -> int
348 {
349 for( wxString& candidate : derivedSymbols )
350 {
351 if( candidate.CmpNoCase( aItem ) == 0 )
352 return ITALIC;
353 }
354
355 return 0;
356 };
357
358 DIALOG_LIB_NEW_SYMBOL dlg( this, symbolNamesInLib, styler, aInheritFrom, validator );
359
360 dlg.SetMinSize( dlg.GetSize() );
361
362 if( dlg.ShowModal() == wxID_CANCEL )
363 return;
364
366
367 props.name = dlg.GetName();
369 props.reference = dlg.GetReference();
370 props.unitCount = dlg.GetUnitCount();
371 props.pinNameInside = dlg.GetPinNameInside();
373 props.powerSymbol = dlg.GetPowerSymbol();
374 props.showPinNumber = dlg.GetShowPinNumber();
375 props.showPinName = dlg.GetShowPinName();
377 props.includeInBom = dlg.GetIncludeInBom();
378 props.includeOnBoard = dlg.GetIncludeOnBoard();
380 props.keepFootprint = dlg.GetKeepFootprint();
381 props.keepDatasheet = dlg.GetKeepDatasheet();
384
385 if( lib.empty() )
386 {
387 // No library home yet: edit the new symbol in an unsaved tab and let the first save
388 // (which asks for a library) promote the tab. With no target library there is no source
389 // for a parent symbol, so the dialog's inheritance combo is empty and the symbol is a root.
390 std::unique_ptr<LIB_SYMBOL> newSymbol = LIB_SYMBOL_LIBRARY_MANAGER::CreateSymbol( props, nullptr );
391
392 SCH_SCREEN* screen = new SCH_SCREEN();
393 CreateUnsavedSymbolTab( newSymbol.release(), screen );
394
397 OnModify();
398 return;
399 }
400
401 m_libMgr->CreateNewSymbol( lib, props );
402 SyncLibraries( false );
403 LoadSymbol( props.name, lib, 1 );
404}
405
406
408{
409 wxString libName;
410
411 if( m_activeTab && m_activeTab->IsUnsaved() )
412 {
414 }
415 else
416 {
417 if( IsLibraryTreeShown() )
419
420 if( libName.empty() )
421 {
423 }
424 else if( m_libMgr->IsLibraryReadOnly( libName ) )
425 {
426 wxString msg = wxString::Format( _( "Symbol library '%s' is not writable." ),
427 libName );
428 wxString msg2 = _( "You must save to a different location." );
429
430 if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) == wxID_OK )
432 }
433 else
434 {
436 }
437 }
438
439 if( IsLibraryTreeShown() )
440 m_treePane->GetLibTree()->RefreshLibTree();
441}
442
443
445{
446 const wxString& libName = GetTargetLibId().GetLibNickname();
447
448 if( !libName.IsEmpty() )
449 {
450 saveLibrary( libName, aSaveAsType );
451 m_treePane->GetLibTree()->RefreshLibTree();
452 }
453}
454
455
457{
458 saveSymbolCopyAs( aOpenCopy );
459
460 m_treePane->GetLibTree()->RefreshLibTree();
461}
462
463
473static std::vector<std::shared_ptr<LIB_SYMBOL>> GetParentChain( const LIB_SYMBOL& aSymbol, bool aIncludeLeaf = true )
474{
475 std::vector<std::shared_ptr<LIB_SYMBOL>> chain;
476 std::shared_ptr<LIB_SYMBOL> sym = aSymbol.SharedPtr();
477
478 if( aIncludeLeaf )
479 chain.push_back( sym );
480
481 while( sym->IsDerived() )
482 {
483 std::shared_ptr<LIB_SYMBOL> parent = sym->GetParent().lock();
484
485 // A symbol can report itself as derived while its parent pointer has already expired.
486 // Stop walking rather than push a null entry and dereference it on the next iteration.
487 if( !parent )
488 break;
489
490 chain.push_back( parent );
491 sym = parent;
492 }
493
494 return chain;
495}
496
497
507static std::pair<bool, bool> CheckSavingIntoOwnInheritance( LIB_SYMBOL_LIBRARY_MANAGER& aLibMgr,
508 LIB_SYMBOL& aSymbol,
509 const wxString& aNewSymbolName,
510 const wxString& aNewLibraryName )
511{
512 const wxString& oldLibraryName = aSymbol.GetLibId().GetLibNickname();
513
514 // Cannot be intersecting if in different libs
515 if( aNewLibraryName != oldLibraryName )
516 return { false, false };
517
518 // Or if the target symbol doesn't exist
519 if( !aLibMgr.SymbolNameInUse( aNewSymbolName, aNewLibraryName ) )
520 return { false, false };
521
522 bool inAncestry = false;
523 bool inDescendents = false;
524
525 {
526 const std::vector<std::shared_ptr<LIB_SYMBOL>> parentChainFromUs = GetParentChain( aSymbol, true );
527
528 // Ignore the leaf symbol (0) - that must match
529 for( size_t i = 1; i < parentChainFromUs.size(); ++i )
530 {
531 // Attempting to overwrite a symbol in the parental chain
532 if( parentChainFromUs[i]->GetName() == aNewSymbolName )
533 {
534 inAncestry = true;
535 break;
536 }
537 }
538 }
539
540 {
541 LIB_SYMBOL* targetSymbol = aLibMgr.GetSymbol( aNewSymbolName, aNewLibraryName );
542 const std::vector<std::shared_ptr<LIB_SYMBOL>> parentChainFromTarget = GetParentChain( *targetSymbol, true );
543 const wxString oldSymbolName = aSymbol.GetName();
544
545 // Ignore the leaf symbol - it'll match if we're saving the symbol
546 // to the same name, and that would be OK
547 for( size_t i = 1; i < parentChainFromTarget.size(); ++i )
548 {
549 if( parentChainFromTarget[i]->GetName() == oldSymbolName )
550 {
551 inDescendents = true;
552 break;
553 }
554 }
555 }
556
557 return { inAncestry, inDescendents };
558}
559
560
568static std::vector<wxString> CheckForParentalChainConflicts( LIB_SYMBOL_LIBRARY_MANAGER& aLibMgr,
569 LIB_SYMBOL& aSymbol,
570 bool aFlattenSymbol,
571 const wxString& newSymbolName,
572 const wxString& newLibraryName )
573{
574 std::vector<wxString> conflicts;
575 const wxString& oldLibraryName = aSymbol.GetLibId().GetLibNickname();
576
577 if( newLibraryName == oldLibraryName || aFlattenSymbol )
578 {
579 // Saving into the same library - the only conflict could be the symbol itself
580 // Different library and flattening - ditto
581 if( aLibMgr.SymbolNameInUse( newSymbolName, newLibraryName ) )
582 conflicts.push_back( newSymbolName );
583 }
584 else
585 {
586 // In a different library with parents - check the whole chain
587 const std::vector<std::shared_ptr<LIB_SYMBOL>> parentChain = GetParentChain( aSymbol, true );
588
589 for( size_t i = 0; i < parentChain.size(); ++i )
590 {
591 if( i == 0 )
592 {
593 // This is the leaf symbol which the user actually named
594 if( aLibMgr.SymbolNameInUse( newSymbolName, newLibraryName ) )
595 conflicts.push_back( newSymbolName );
596 }
597 else
598 {
599 std::shared_ptr<LIB_SYMBOL> chainSymbol = parentChain[i];
600
601 if( aLibMgr.SymbolNameInUse( chainSymbol->GetName(), newLibraryName ) )
602 conflicts.push_back( chainSymbol->GetName() );
603 }
604 }
605 }
606
607 return conflicts;
608}
609
610
618{
619public:
621 {
622 // Just overwrite any existing symbols in the target library
624 // Add a suffix until we find a name that doesn't conflict
626 // Could have a mode that asks for every one, be then we'll need a fancier
627 // SAVE_SYMBOL_AS_DIALOG subdialog with Overwrite/Rename/Prompt/Cancel
628 // PROMPT
629 };
630
631 SYMBOL_SAVE_AS_HANDLER( LIB_SYMBOL_LIBRARY_MANAGER& aLibMgr, CONFLICT_STRATEGY aStrategy, bool aValueFollowsName ) :
632 m_libMgr( aLibMgr ),
633 m_strategy( aStrategy ),
634 m_valueFollowsName( aValueFollowsName )
635 {
636 }
637
638 bool DoSave( LIB_SYMBOL& symbol, const wxString& aNewSymName, const wxString& aNewLibName, bool aFlattenSymbol )
639 {
640 std::unique_ptr<LIB_SYMBOL> flattenedSymbol; // for ownership
641 std::vector<std::shared_ptr<LIB_SYMBOL>> parentChain;
642
643 const bool sameLib = aNewLibName == symbol.GetLibId().GetLibNickname().wx_str();
644
645 if( aFlattenSymbol )
646 {
647 // If we're not copying parent symbols, we need to flatten the symbol
648 // and only save that.
649 flattenedSymbol = symbol.Flatten();
650 wxCHECK( flattenedSymbol, false );
651
652 parentChain.push_back( flattenedSymbol->SharedPtr() );
653 }
654 else if( sameLib )
655 {
656 // If we're saving into the same library, we don't need to check the parental chain
657 // because we can just keep the same parent symbol
658 parentChain.push_back( symbol.SharedPtr() );
659 }
660 else
661 {
662 // Need to copy all parent symbols
663 parentChain = GetParentChain( symbol, true );
664 }
665
666 std::vector<wxString> newNames;
667
668 // Iterate backwards (i.e. from the root down)
669 for( int i = (int) parentChain.size() - 1; i >= 0; --i )
670 {
671 std::shared_ptr<LIB_SYMBOL>& oldSymbol = parentChain[i];
672 LIB_SYMBOL new_symbol( *oldSymbol );
673
674 wxString newName;
675 if( i == 0 )
676 {
677 // This is the leaf symbol which the user actually named
678 newName = aNewSymName;
679 }
680 else
681 {
682 // Somewhere in the inheritance chain, use the conflict resolution strategy
683 newName = oldSymbol->GetName();
684 }
685
686 newName = resolveConflict( newName, aNewLibName );
687 new_symbol.SetName( newName );
688
690 new_symbol.GetValueField().SetText( newName );
691
692 if( i == (int) parentChain.size() - 1 )
693 {
694 // This is the root symbol
695 // Nothing extra to do, it's just a simple symbol with no parents
696 }
697 else
698 {
699 // Get the buffered new copy in the new library (with the name we gave it)
700 LIB_SYMBOL* newParent = m_libMgr.GetSymbol( newNames.back(), aNewLibName );
701
702 // We should have stored this already, why didn't we get it back?
703 wxASSERT( newParent );
704 new_symbol.SetParent( newParent );
705
706 // Keep the recorded parent name in sync with the (possibly renamed) buffered
707 // parent so serialization has a valid fallback if the live pointer is lost.
708 if( newParent )
709 new_symbol.SetParentName( newParent->GetName() );
710 }
711
712 newNames.push_back( newName );
713 m_libMgr.UpdateSymbol( &new_symbol, aNewLibName );
714 }
715
716 return true;
717 }
718
719private:
720 wxString resolveConflict( const wxString& proposed, const wxString& aNewLibName ) const
721 {
722 switch( m_strategy )
723 {
725 {
726 // In an overwrite strategy, we don't care about conflicts
727 return proposed;
728 }
730 {
731 // In a rename strategy, we need to find a name that doesn't conflict
732 int suffix = 1;
733
734 while( true )
735 {
736 wxString newName = wxString::Format( "%s_%d", proposed, suffix );
737
738 if( !m_libMgr.SymbolNameInUse( newName, aNewLibName ) )
739 return newName;
740
741 ++suffix;
742 }
743 break;
744 }
745 // No default
746 }
747
748 wxFAIL_MSG( "Invalid conflict strategy" );
749 return "";
750 }
751
755};
756
757
764
765
767{
768public:
769 using SymLibNameValidator = std::function<int( const wxString& libName, const wxString& symbolName )>;
770
778
780 PARAMS& aParams,
781 SymLibNameValidator aValidator,
782 const std::vector<wxString>& aParentSymbolNames ) :
783 EDA_LIST_DIALOG( aParent, _( "Save Symbol As" ), false ),
784 m_validator( std::move( aValidator ) ),
785 m_params( aParams )
786 {
787 wxArrayString headers;
788 std::vector<wxArrayString> itemsToDisplay;
789
790 if( aParentSymbolNames.size() )
791 {
792 // This is a little trick to word - when saving to another library, "copy parents" makes sense,
793 // but when in the same library, the parents will be untouched in any case.
794 const wxString aParentNames = AccumulateDescriptions( aParentSymbolNames );
795 AddExtraCheckbox(
796 wxString::Format( "Flatten/remove symbol inheritance (current parent symbols: %s)", aParentNames ),
797 &m_params.m_FlattenSymbol );
798 }
799
800 aParent->GetLibraryItemsForListDialog( headers, itemsToDisplay );
801 initDialog( headers, itemsToDisplay, m_params.m_LibraryName );
802
803 SetListLabel( _( "Save in library:" ) );
804 SetOKLabel( _( "Save" ) );
805
806 wxBoxSizer* bNameSizer = new wxBoxSizer( wxHORIZONTAL );
807
808 wxStaticText* label = new wxStaticText( this, wxID_ANY, _( "Name:" ) );
809 bNameSizer->Add( label, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
810
811 m_symbolNameCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString );
812 bNameSizer->Add( m_symbolNameCtrl, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
813
814 wxButton* newLibraryButton = new wxButton( this, ID_MAKE_NEW_LIBRARY, _( "New Library..." ) );
815 m_ButtonsSizer->Prepend( 80, 20 );
816 m_ButtonsSizer->Prepend( newLibraryButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 10 );
817
818 GetSizer()->Prepend( bNameSizer, 0, wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5 );
819
820 Bind( wxEVT_BUTTON,
821 [this]( wxCommandEvent& )
822 {
823 EndModal( ID_MAKE_NEW_LIBRARY );
825
826 // Move nameTextCtrl to the head of the tab-order
827 if( GetChildren().DeleteObject( m_symbolNameCtrl ) )
828 GetChildren().Insert( m_symbolNameCtrl );
829
831
833
834 Layout();
835 GetSizer()->Fit( this );
836
837 Centre();
838 }
839
840protected:
841 wxString getSymbolName() const
842 {
843 wxString symbolName = m_symbolNameCtrl->GetValue();
844 symbolName.Trim( true );
845 symbolName.Trim( false );
846 symbolName.Replace( " ", "_" );
847 return EscapeString( symbolName, CTX_LIBID );
848 }
849
850 bool TransferDataToWindow() override
851 {
852 m_symbolNameCtrl->SetValue( UnescapeString( m_params.m_SymbolName ) );
853 return true;
854 }
855
857 {
858 // This updates m_params.m_FlattenSymbol
859 // Do this now, so the validator can use it
861
862 m_params.m_SymbolName = getSymbolName();
863 m_params.m_LibraryName = GetTextSelection();
864
865 int ret = m_validator( m_params.m_LibraryName, m_params.m_SymbolName );
866
867 if( ret == wxID_CANCEL )
868 return false;
869
870 if( ret == ID_OVERWRITE_CONFLICTS )
872 else if( ret == ID_RENAME_CONFLICTS )
874
875 return true;
876 }
877
878private:
879 wxTextCtrl* m_symbolNameCtrl;
882};
883
884
886{
887 LIB_SYMBOL* symbol = getTargetSymbol();
888
889 if( !symbol )
890 return;
891
892 const bool savingUnsavedTab = m_activeTab && m_activeTab->IsUnsaved() && symbol == m_symbol;
893
894 LIB_ID old_lib_id = symbol->GetLibId();
895 wxString symbolName = old_lib_id.GetLibItemName();
896 wxString libraryName = old_lib_id.GetLibNickname();
897 bool valueFollowsName = symbol->GetValueField().GetText() == symbolName;
898 wxString msg;
899 bool done = false;
900 bool flattenSymbol = false;
901
902 // This is the function that will be called when the user clicks OK in the dialog and checks
903 // if the proposed name has problems, and asks for clarification.
904 const auto dialogValidatorFunc =
905 [&]( const wxString& newLib, const wxString& newName ) -> int
906 {
907 if( newLib.IsEmpty() )
908 {
909 wxMessageBox( _( "A library must be specified." ) );
910 return wxID_CANCEL;
911 }
912
913 if( newName.IsEmpty() )
914 {
915 wxMessageBox( _( "Symbol must have a name." ) );
916 return wxID_CANCEL;
917 }
918
919 if( m_libMgr->IsLibraryReadOnly( newLib ) )
920 {
921 msg = wxString::Format( _( "Library '%s' is read-only. Choose a "
922 "different library to save the symbol '%s' to." ),
923 newLib,
924 UnescapeString( newName ) );
925 wxMessageBox( msg );
926 return wxID_CANCEL;
927 }
928
933 const auto& [inAncestry, inDescendents] = CheckSavingIntoOwnInheritance( *m_libMgr, *symbol,
934 newName, newLib );
935
936 if( inAncestry )
937 {
938 msg = wxString::Format( _( "Symbol '%s' cannot replace another symbol '%s' "
939 "that it descends from" ),
940 symbolName,
941 UnescapeString( newName ) );
942 wxMessageBox( msg );
943 return wxID_CANCEL;
944 }
945
946 if( inDescendents )
947 {
948 msg = wxString::Format( _( "Symbol '%s' cannot replace another symbol '%s' "
949 "that is a descendent of it." ),
950 symbolName,
951 UnescapeString( newName ) );
952 wxMessageBox( msg );
953 return wxID_CANCEL;
954 }
955
956 const std::vector<wxString> conflicts =
957 CheckForParentalChainConflicts( *m_libMgr, *symbol, flattenSymbol, newName, newLib );
958
959 if( conflicts.size() == 1 && conflicts.front() == newName )
960 {
961 // The simplest case is when the symbol itself has a conflict
962 msg = wxString::Format( _( "Symbol '%s' already exists in library '%s'. "
963 "Do you want to overwrite it?" ),
964 UnescapeString( newName ),
965 newLib );
966
967 KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
968 errorDlg.SetOKLabel( _( "Overwrite" ) );
969
970 return errorDlg.ShowModal() == wxID_OK ? ID_OVERWRITE_CONFLICTS : (int) wxID_CANCEL;
971 }
972 else if( !conflicts.empty() )
973 {
974 // If there are conflicts in the parental chain, we need to ask the user
975 // if they want to overwrite all of them.
976 // A more complex UI might allow the user to re-parent the symbol to an
977 // existing symbol in the target lib, or rename all the parents somehow.
978 msg = wxString::Format( _( "The following symbols in the inheritance chain of "
979 "'%s' already exist in library '%s':\n" ),
980 UnescapeString( symbolName ),
981 newLib );
982
983 for( const wxString& conflict : conflicts )
984 msg += wxString::Format( " %s\n", conflict );
985
986 msg += _( "\nDo you want to overwrite all of them, or rename the new symbols?" );
987
988 KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxYES_NO | wxCANCEL | wxICON_WARNING );
989 errorDlg.SetYesNoCancelLabels( _( "Overwrite All" ), _( "Rename All" ), _( "Cancel" ) );
990
991 switch( errorDlg.ShowModal() )
992 {
993 case wxID_YES: return ID_OVERWRITE_CONFLICTS;
994 case wxID_NO: return ID_RENAME_CONFLICTS;
995 default: return wxID_CANCEL;
996 }
997 }
998
999 return wxID_OK;
1000 };
1001
1003
1004 std::vector<wxString> parentSymbolNames;
1005
1006 if( symbol->IsDerived() )
1007 {
1008 // The parents are everything but the leaf symbol
1009 std::vector<std::shared_ptr<LIB_SYMBOL>> parentChain = GetParentChain( *symbol, false );
1010
1011 for( const std::shared_ptr<LIB_SYMBOL>& parent : parentChain )
1012 parentSymbolNames.push_back( parent->GetName() );
1013 }
1014
1016 symbolName,
1017 libraryName,
1018 flattenSymbol,
1019 strategy,
1020 };
1021
1022 // Keep asking the user for a new name until they give a valid one or cancel the operation
1023 while( !done )
1024 {
1025 SAVE_SYMBOL_AS_DIALOG dlg( this, params, dialogValidatorFunc, parentSymbolNames );
1026
1027 int ret = dlg.ShowModal();
1028
1029 switch( ret )
1030 {
1031 case wxID_CANCEL:
1032 // A cancelled save leaves the unsaved tab dirty so the user is re-prompted later.
1033 return;
1034
1035 case wxID_OK: // No conflicts
1038 {
1039 done = true;
1040 break;
1041 }
1043 {
1044 wxFileName newLibrary( AddLibraryFile( true ) );
1045 params.m_LibraryName = newLibrary.GetName();
1046
1047 // Go round again to ask for the symbol name
1048 break;
1049 }
1050
1051 default:
1052 break;
1053 }
1054 }
1055
1056 SYMBOL_SAVE_AS_HANDLER saver( *m_libMgr, params.m_ConflictStrategy, valueFollowsName );
1057
1058 saver.DoSave( *symbol, params.m_SymbolName, params.m_LibraryName, params.m_FlattenSymbol );
1059
1060 SyncLibraries( false );
1061
1062 if( savingUnsavedTab )
1063 {
1064 symbol->SetLibId( LIB_ID( params.m_LibraryName, params.m_SymbolName ) );
1065
1066 RenameSymbolTab( LIB_ID( wxEmptyString, symbolName ), LIB_ID( params.m_LibraryName, params.m_SymbolName ) );
1067
1068 GetScreen()->SetContentModified( false );
1069
1070 if( int idx = m_tabsPanel->FindTab( m_activeTab->GetTabKey() ); idx >= 0 )
1071 m_tabsPanel->MarkModified( idx, false );
1072 }
1073 else
1074 {
1075 RenameSymbolTab( LIB_ID( libraryName, symbolName ), LIB_ID( params.m_LibraryName, params.m_SymbolName ) );
1076 }
1077
1078 if( aOpenCopy )
1079 LoadSymbol( params.m_SymbolName, params.m_LibraryName, 1 );
1080}
1081
1082
1084{
1085 wxString msg;
1086 LIB_SYMBOL* symbol = getTargetSymbol();
1087
1088 if( !symbol )
1089 {
1090 ShowInfoBarError( _( "There is no symbol selected to save." ) );
1091 return;
1092 }
1093
1094 wxFileName fn;
1095
1096 fn.SetName( symbol->GetName().Lower() );
1098
1099 wxFileDialog dlg( this, _( "Export Symbol" ), m_mruPath, fn.GetFullName(),
1101
1103
1104 if( dlg.ShowModal() == wxID_CANCEL )
1105 return;
1106
1108
1109 fn = dlg.GetPath();
1110 fn.MakeAbsolute();
1111
1112 LIBRARY_MANAGER& manager = Pgm().GetLibraryManager();
1113
1114 wxString libraryName;
1115 std::unique_ptr<LIB_SYMBOL> flattenedSymbol = symbol->Flatten();
1116
1117 for( const wxString& candidate : m_libMgr->GetLibraryNames() )
1118 {
1119 if( auto uri = manager.GetFullURI( LIBRARY_TABLE_TYPE::SYMBOL, candidate, true ); uri )
1120 {
1121 if( *uri == fn.GetFullPath() )
1122 libraryName = candidate;
1123 }
1124 }
1125
1126 if( !libraryName.IsEmpty() )
1127 {
1128 SYMBOL_SAVE_AS_HANDLER saver( *m_libMgr, strategy, false );
1129
1130 if( m_libMgr->IsLibraryReadOnly( libraryName ) )
1131 {
1132 msg = wxString::Format( _( "Library '%s' is read-only." ), libraryName );
1133 DisplayError( this, msg );
1134 return;
1135 }
1136
1137 if( m_libMgr->SymbolNameInUse( symbol->GetName(), libraryName ) )
1138 {
1139 msg = wxString::Format( _( "Symbol '%s' already exists in library '%s'." ),
1140 symbol->GetName(), libraryName );
1141
1142 KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
1143 errorDlg.SetOKLabel( _( "Overwrite" ) );
1144 errorDlg.DoNotShowCheckbox( __FILE__, __LINE__ );
1145
1146 if( errorDlg.ShowModal() == wxID_CANCEL )
1147 return;
1148 }
1149
1150 saver.DoSave( *flattenedSymbol, symbol->GetName(), libraryName, false );
1151
1152 SyncLibraries( false );
1153 return;
1154 }
1155
1156 LIB_SYMBOL* old_symbol = nullptr;
1157 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::GuessPluginTypeFromLibPath( fn.GetFullPath() );
1158
1159 if( pluginType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
1160 pluginType = SCH_IO_MGR::SCH_KICAD;
1161
1162 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pluginType ) );
1163
1164 if( fn.FileExists() )
1165 {
1166 try
1167 {
1168 old_symbol = pi->LoadSymbol( fn.GetFullPath(), symbol->GetName() );
1169 }
1170 catch( const IO_ERROR& ioe )
1171 {
1172 msg.Printf( _( "Error occurred attempting to load symbol library file '%s'." ),
1173 fn.GetFullPath() );
1174 DisplayErrorMessage( this, msg, ioe.What() );
1175 return;
1176 }
1177
1178 if( old_symbol )
1179 {
1180 msg.Printf( _( "Symbol %s already exists in library '%s'." ),
1181 UnescapeString( symbol->GetName() ),
1182 fn.GetFullName() );
1183
1184 KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
1185 errorDlg.SetOKLabel( _( "Overwrite" ) );
1186 errorDlg.DoNotShowCheckbox( __FILE__, __LINE__ );
1187
1188 if( errorDlg.ShowModal() == wxID_CANCEL )
1189 return;
1190 }
1191 }
1192
1193 if( !fn.IsDirWritable() )
1194 {
1195 msg.Printf( _( "Insufficient permissions to save library '%s'." ), fn.GetFullPath() );
1196 DisplayError( this, msg );
1197 return;
1198 }
1199
1200 try
1201 {
1202 if( !fn.FileExists() )
1203 pi->CreateLibrary( fn.GetFullPath() );
1204
1205 // The flattened symbol is most likely what the user would want. As some point in
1206 // the future as more of the symbol library inheritance is implemented, this may have
1207 // to be changes to save symbols of inherited symbols.
1208 pi->SaveSymbol( fn.GetFullPath(), std::move( flattenedSymbol ) );
1209 }
1210 catch( const IO_ERROR& ioe )
1211 {
1212 msg.Printf( _( "Failed to create symbol library file '%s'." ), fn.GetFullPath() );
1213 DisplayErrorMessage( this, msg, ioe.What() );
1214 msg.Printf( _( "Error creating symbol library '%s'." ), fn.GetFullName() );
1215 SetStatusText( msg );
1216 return;
1217 }
1218
1219 m_mruPath = fn.GetPath();
1220
1221 msg.Printf( _( "Symbol %s saved to library '%s'." ),
1222 UnescapeString( symbol->GetName() ),
1223 fn.GetFullPath() );
1224 SetStatusText( msg );
1225}
1226
1227
1229{
1230 wxCHECK( m_symbol, /* void */ );
1231
1232 wxString lib;
1233
1234 if( !IsSymbolFromSchematic() )
1235 lib = m_symbol->GetLibNickname();
1236
1237 if( !lib.IsEmpty() && aOldName && *aOldName != m_symbol->GetName() )
1238 {
1239 // Test the current library for name conflicts
1240 if( m_libMgr->SymbolNameInUse( m_symbol->GetName(), lib ) )
1241 {
1242 wxString msg = wxString::Format( _( "Symbol name '%s' already in use." ),
1243 UnescapeString( m_symbol->GetName() ) );
1244
1245 DisplayErrorMessage( this, msg );
1246 m_symbol->SetName( *aOldName );
1247 }
1248 else
1249 {
1250 m_libMgr->UpdateSymbolAfterRename( m_symbol, *aOldName, lib );
1251 }
1252
1253 // Reselect the renamed symbol
1254 m_treePane->GetLibTree()->SelectLibId( LIB_ID( lib, m_symbol->GetName() ) );
1255 }
1256
1257 wxDataViewItem treeItem = m_libMgr->GetAdapter()->FindItem( LIB_ID( lib, m_symbol->GetName() ) );
1258
1259 if( treeItem.IsOk() )
1260 UpdateLibraryTree( treeItem, m_symbol );
1261
1263
1264 if( aOldName )
1265 RenameSymbolTab( LIB_ID( lib, *aOldName ), m_symbol->GetLibId() );
1266
1267 // N.B. The view needs to be rebuilt first as the Symbol Properties change may invalidate
1268 // the view pointers by rebuilting the field table
1269 RebuildView();
1271
1272 OnModify();
1273}
1274
1275
1277{
1278 std::vector<LIB_ID> toDelete = GetSelectedLibIds();
1279
1280 if( toDelete.empty() )
1281 toDelete.emplace_back( GetTargetLibId() );
1282
1283 // A derived symbol selected together with its base is already gone once the base is removed
1284 std::set<LIB_ID> removedWithBase;
1285
1286 for( LIB_ID& libId : toDelete )
1287 {
1288 if( removedWithBase.count( libId ) )
1289 continue;
1290
1291 if( m_libMgr->IsSymbolModified( libId.GetLibItemName(), libId.GetLibNickname() )
1292 && !IsOK( this, wxString::Format( _( "The symbol '%s' has been modified.\n"
1293 "Do you want to remove it from the library?" ),
1294 libId.GetUniStringLibItemName() ) ) )
1295 {
1296 continue;
1297 }
1298
1299 wxArrayString derived;
1300
1301 if( m_libMgr->GetDerivedSymbolNames( libId.GetLibItemName(), libId.GetLibNickname(), derived ) > 0 )
1302 {
1303 wxString msg = _( "Deleting a base symbol will delete all symbols derived from it.\n\n" );
1304
1305 msg += libId.GetLibItemName().wx_str() + _( " (base)\n" );
1306
1307 for( const wxString& name : derived )
1308 msg += name + wxT( "\n" );
1309
1310 KICAD_MESSAGE_DIALOG dlg( this, msg, _( "Warning" ), wxYES_NO | wxICON_WARNING | wxCENTER );
1311 dlg.SetExtendedMessage( wxT( " " ) );
1312 dlg.SetYesNoLabels( _( "Delete All Listed Symbols" ), _( "Cancel" ) );
1313
1314 if( dlg.ShowModal() == wxID_NO )
1315 continue;
1316 }
1317
1318 // Close only the tabs for the symbol being deleted and the symbols derived from it,
1319 // which are removed along with it. The other open tabs stay put.
1320 closeSymbolTab( libId );
1321
1322 for( const wxString& derivedName : derived )
1323 closeSymbolTab( LIB_ID( libId.GetLibNickname().wx_str(), derivedName ) );
1324
1325 m_libMgr->RemoveSymbol( libId.GetLibItemName(), libId.GetLibNickname() );
1326
1327 for( const wxString& derivedName : derived )
1328 removedWithBase.emplace( libId.GetLibNickname().wx_str(), derivedName );
1329 }
1330
1331 m_treePane->GetLibTree()->RefreshLibTree();
1332}
1333
1334
1336{
1337 std::vector<LIB_ID> symbols;
1338
1339 if( GetTreeLIBIDs( symbols ) == 0 )
1340 return;
1341
1342 STRING_FORMATTER formatter;
1343
1344 for( LIB_ID& libId : symbols )
1345 {
1346 LIB_SYMBOL* symbol = m_libMgr->GetBufferedSymbol( libId.GetLibItemName(),
1347 libId.GetLibNickname() );
1348
1349 if( !symbol )
1350 continue;
1351
1352 std::unique_ptr<LIB_SYMBOL> tmp = symbol->Flatten();
1353 SCH_IO_KICAD_SEXPR::FormatLibSymbol( tmp.get(), formatter );
1354 }
1355
1356 std::string prettyData = formatter.GetString();
1357 KICAD_FORMAT::Prettify( prettyData, KICAD_FORMAT::FORMAT_MODE::COMPACT_TEXT_PROPERTIES );
1358
1359 wxLogNull doNotLog; // disable logging of failed clipboard actions
1360
1361 auto clipboard = wxTheClipboard;
1362 wxClipboardLocker clipboardLock( clipboard );
1363
1364 if( !clipboardLock || !clipboard->IsOpened() )
1365 return;
1366
1367 auto data = new wxTextDataObject( wxString( prettyData.c_str(), wxConvUTF8 ) );
1368 clipboard->SetData( data );
1369
1370 clipboard->Flush();
1371}
1372
1373
1374void SYMBOL_EDIT_FRAME::DuplicateSymbol( bool aFromClipboard )
1375{
1376 LIB_ID libId = GetTargetLibId();
1377 wxString lib = libId.GetLibNickname();
1378
1379 if( !m_libMgr->LibraryExists( lib ) )
1380 return;
1381
1382 std::vector<LIB_SYMBOL*> newSymbols;
1383
1384 if( aFromClipboard )
1385 {
1386 std::string clipboardData = GetClipboardUTF8();
1387
1388 try
1389 {
1390 newSymbols = SCH_IO_KICAD_SEXPR::ParseLibSymbols( clipboardData, "Clipboard" );
1391 }
1392 catch( IO_ERROR& e )
1393 {
1394 wxLogMessage( wxS( "Can not paste: %s" ), e.Problem() );
1395 }
1396 }
1397 else if( LIB_SYMBOL* srcSymbol = m_libMgr->GetBufferedSymbol( libId.GetLibItemName(), lib ) )
1398 {
1399 newSymbols.emplace_back( new LIB_SYMBOL( *srcSymbol ) );
1400
1401 // Derive from same parent.
1402 if( srcSymbol->IsDerived() )
1403 {
1404 if( std::shared_ptr<LIB_SYMBOL> srcParent = srcSymbol->GetParent().lock() )
1405 newSymbols.back()->SetParent( srcParent.get() );
1406 }
1407 }
1408
1409 if( newSymbols.empty() )
1410 return;
1411
1412 for( LIB_SYMBOL* symbol : newSymbols )
1413 {
1414 ensureUniqueName( symbol, lib );
1415 m_libMgr->UpdateSymbol( symbol, lib );
1416
1417 LoadOneLibrarySymbol( symbol, lib, GetUnit(), GetBodyStyle() );
1418 }
1419
1420 SyncLibraries( false );
1421 m_treePane->GetLibTree()->SelectLibId( LIB_ID( lib, newSymbols[0]->GetName() ) );
1422
1423 for( LIB_SYMBOL* symbol : newSymbols )
1424 delete symbol;
1425}
1426
1427
1428void SYMBOL_EDIT_FRAME::ensureUniqueName( LIB_SYMBOL* aSymbol, const wxString& aLibrary )
1429{
1430 if( aSymbol )
1431 {
1432 int i = 1;
1433 wxString newName = aSymbol->GetName();
1434
1435 // Append a number to the name until the name is unique in the library.
1436 while( m_libMgr->SymbolNameInUse( newName, aLibrary ) )
1437 newName.Printf( "%s_%d", aSymbol->GetName(), i++ );
1438
1439 aSymbol->SetName( newName );
1440 }
1441}
1442
1443
1444void SYMBOL_EDIT_FRAME::Revert( LIB_ID& aTarget, bool aConfirm )
1445{
1446 const wxString& libName = aTarget.GetLibNickname();
1447
1448 // Empty if this is the library itself that is selected.
1449 const wxString& symbolName = aTarget.GetLibItemName();
1450
1451 if( libName.IsEmpty() )
1452 return;
1453
1454 wxString msg = wxString::Format( _( "Revert '%s' to last version saved?" ),
1455 symbolName.IsEmpty() ? libName : symbolName );
1456
1457 if( aConfirm && !ConfirmRevertDialog( this, msg ) )
1458 return;
1459
1460 // Other tabs may hold unsaved edits, so close only the reverted ones
1461 int unit = m_unit;
1462 const LIB_ID active = closeLibraryTabs( libName, symbolName );
1463
1464 if( symbolName.IsEmpty() )
1465 {
1466 m_libMgr->RevertLibrary( libName );
1467 }
1468 else
1469 {
1470 aTarget = m_libMgr->RevertSymbol( aTarget );
1471
1472 m_treePane->GetLibTree()->SelectLibId( aTarget );
1473 }
1474
1475 // A derived symbol still shown draws its parent's items, which the revert just replaced
1476 if( m_symbol && m_symbol->IsDerived() )
1477 {
1478 m_symbol->ClearCaches();
1480 RebuildView();
1481 }
1482
1483 // A reverted rename brings the symbol back under its old name
1484 const wxString reload = symbolName.IsEmpty() ? active.GetUniStringLibItemName()
1485 : aTarget.GetUniStringLibItemName();
1486
1487 if( !active.GetLibItemName().empty() && m_libMgr->SymbolExists( reload, libName ) )
1488 LoadSymbol( reload, libName, unit );
1489
1490 m_treePane->Refresh();
1491}
1492
1493
1495{
1496 wxCHECK_RET( m_libMgr, "Library manager object not created." );
1497
1498 // Every library buffer is restored in place, so no library tab may keep its working copy
1499 int unit = m_unit;
1500 const LIB_ID active = closeLibraryTabs( wxEmptyString, wxEmptyString );
1501
1502 LIB_ID target = GetTargetLibId();
1503 Revert( target, false );
1504 m_libMgr->RevertAll();
1505
1506 if( m_libMgr->SymbolExists( active.GetUniStringLibItemName(), active.GetUniStringLibNickname() ) )
1508}
1509
1510
1511LIB_ID SYMBOL_EDIT_FRAME::closeLibraryTabs( const wxString& aLibrary, const wxString& aSymbol )
1512{
1513 const wxString activeKey = m_activeTab ? m_activeTab->GetTabKey() : wxString();
1514 std::vector<LIB_ID> tabs;
1515
1516 // Reactivating a tab restores its stored unit and body style, which lag the frame's
1517 if( m_activeTab )
1518 {
1519 m_activeTab->SetUnit( m_unit );
1520 m_activeTab->SetBodyStyle( m_bodyStyle );
1521 }
1522 LIB_ID active;
1523
1524 for( const std::unique_ptr<SYMBOL_EDITOR_TAB_CONTEXT>& ctx : m_tabContexts )
1525 {
1526 if( ctx->IsTransient() )
1527 continue;
1528
1529 if( !aLibrary.IsEmpty() && ctx->GetLibrary() != aLibrary )
1530 continue;
1531
1532 if( !aSymbol.IsEmpty() && ctx->GetName() != aSymbol )
1533 continue;
1534
1535 tabs.emplace_back( ctx->GetLibrary(), ctx->GetName() );
1536
1537 if( ctx.get() == m_activeTab )
1538 active = tabs.back();
1539 }
1540
1541 for( const LIB_ID& tab : tabs )
1542 closeSymbolTab( tab );
1543
1544 // Closing an inactive tab selects its neighbour, so return to the tab that was active
1545 if( int activeIdx = m_tabsPanel->FindTab( activeKey ); activeIdx >= 0 )
1546 m_tabsPanel->SelectTab( activeIdx );
1547
1548 return active;
1549}
1550
1551
1552void SYMBOL_EDIT_FRAME::LoadSymbol( const wxString& aAlias, const wxString& aLibrary, int aUnit )
1553{
1555 {
1556 if( !HandleUnsavedChanges( this, _( "The current symbol has been modified. Save changes?" ),
1557 [&]() -> bool
1558 {
1559 return saveCurrentSymbol();
1560 } ) )
1561 {
1562 return;
1563 }
1564 }
1565
1566 LIB_SYMBOL* symbol = m_libMgr->GetBufferedSymbol( aAlias, aLibrary );
1567
1568 if( !symbol )
1569 {
1570 DisplayError( this, wxString::Format( _( "Symbol %s not found in library '%s'." ),
1571 aAlias,
1572 aLibrary ) );
1573 m_treePane->GetLibTree()->RefreshLibTree();
1574 return;
1575 }
1576
1577 // Optimize default edit options for this symbol
1578 // Usually if units are locked, graphic items are specific to each unit
1579 // and if units are interchangeable, graphic items are common to units
1580 SetDrawSpecificUnit( symbol->UnitsLocked() );
1581
1582 LoadOneLibrarySymbol( symbol, aLibrary, aUnit, 0 );
1583}
1584
1585
1586bool SYMBOL_EDIT_FRAME::saveLibrary( const wxString& aLibrary, SAVE_LIBRARY_AS aSaveType )
1587{
1588 wxFileName fn;
1589 wxString msg;
1591 SCH_IO_MGR::SCH_FILE_T fileType = SCH_IO_MGR::SCH_FILE_T::SCH_KICAD;
1592 PROJECT& prj = Prj();
1593
1595
1597
1598 wxCHECK( adapter, false );
1599
1600 if( ( aSaveType == SAVE_LIBRARY_AS::ORIGINAL ) && ( aLibrary.empty() || !adapter->HasLibrary( aLibrary ) ) )
1601 {
1602 ShowInfoBarError( _( "No library specified." ) );
1603 return false;
1604 }
1605
1606 bool newPackedLibrary = ( ( aSaveType == SAVE_LIBRARY_AS::ORIGINAL ) && wxFileName::FileExists( aLibrary ) ) ||
1607 ( aSaveType == SAVE_LIBRARY_AS::PACKED );
1608
1609 bool newUnpackedLibrary = ( ( aSaveType == SAVE_LIBRARY_AS::ORIGINAL ) && wxFileName::DirExists( aLibrary ) ) ||
1610 ( aSaveType == SAVE_LIBRARY_AS::UNPACKED );
1611
1612 if( newPackedLibrary )
1613 {
1614 SEARCH_STACK* search = PROJECT_SCH::SchSearchS( &prj );
1615
1616 // Get a new name for the library
1617 wxString default_path = prj.GetRString( PROJECT::SCH_LIB_PATH );
1618
1619 if( !default_path )
1620 default_path = search->LastVisitedPath();
1621
1622 fn.SetName( aLibrary );
1624
1625 wxString wildcards = FILEEXT::KiCadSymbolLibFileWildcard();
1626 wxString dlgPrompt;
1627
1628 if( aSaveType == SAVE_LIBRARY_AS::ORIGINAL )
1629 dlgPrompt.Printf( _( "Save Library '%s' As..." ), aLibrary );
1630 else
1631 dlgPrompt.Printf( _( "Save Library '%s' As Packed Library..." ), aLibrary );
1632
1633 wxFileDialog dlg( this, dlgPrompt, default_path, fn.GetFullName(), wildcards,
1634 wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
1635
1636 SYMBOL_LIBRARY_SAVE_AS_FILEDLG_HOOK saveAsHook( type );
1637 dlg.SetCustomizeHook( saveAsHook );
1638
1640
1641 if( dlg.ShowModal() == wxID_CANCEL )
1642 return false;
1643
1644 fn = dlg.GetPath();
1645
1646 prj.SetRString( PROJECT::SCH_LIB_PATH, fn.GetPath() );
1647
1648 if( fn.GetExt().IsEmpty() )
1650
1651 type = saveAsHook.GetOption();
1652 }
1653 else if( newUnpackedLibrary )
1654 {
1655 SEARCH_STACK* search = PROJECT_SCH::SchSearchS( &prj );
1656
1657 // Get a new name for the library
1658 wxString default_path = prj.GetRString( PROJECT::SCH_LIB_PATH );
1659
1660 if( !default_path )
1661 default_path = search->LastVisitedPath();
1662
1663 wxString dlgPrompt;
1664
1665 if( aSaveType == SAVE_LIBRARY_AS::ORIGINAL )
1666 dlgPrompt.Printf( _( "Save Library '%s' As..." ), aLibrary );
1667 else
1668 dlgPrompt.Printf( _( "Save Library '%s' As Unpacked Library..." ), aLibrary );
1669
1670 wxDirDialog dlg( this, dlgPrompt, default_path );
1671
1673
1674 if( dlg.ShowModal() == wxID_CANCEL )
1675 return false;
1676
1677 fn.SetPath( dlg.GetPath() );
1678 }
1679 else
1680 {
1681 std::optional<LIBRARY_TABLE_ROW*> optRow = adapter->GetRow( aLibrary );
1682 wxCHECK( optRow, false );
1683
1684 wxString libFileName = LIBRARY_MANAGER::GetFullURI( *optRow, true );
1685
1686 // wxFileName will parse any string with a dot(.) followed by any characters as a file extension.
1687 // By default KiCad uses paths suffixed with .kicad_symdir which is interpreted as a file rather
1688 // than a path. Checking if the library is a file (packed) or a folder (unpacked) is required to
1689 // ensure the correct save type is used.
1690 if( wxFileName::DirExists( libFileName ) )
1691 fn.SetPath( libFileName );
1692 else
1693 fn = libFileName;
1694
1696
1697 if( fileType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
1698 fileType = SCH_IO_MGR::SCH_KICAD;
1699 }
1700
1701 // Verify the user has write privileges before attempting to save the library file.
1702 if( ( aSaveType == SAVE_LIBRARY_AS::ORIGINAL ) && m_libMgr->IsLibraryReadOnly( aLibrary ) )
1703 return false;
1704
1705 ClearMsgPanel();
1706
1707 // Only make a backup when saving to the original library.
1708 if( aSaveType == SAVE_LIBRARY_AS::ORIGINAL )
1709 {
1710 wxString errMsg;
1711
1712 // Copy .kicad_symb file to .bak.
1713 if( !backupLibrary( fn, errMsg ) )
1714 {
1715 return false;
1716 }
1717 }
1718
1719 if( !m_libMgr->SaveLibrary( aLibrary, fn.GetFullPath(), fileType ) )
1720 {
1721 msg.Printf( _( "Failed to save changes to symbol library file '%s'." ),
1722 fn.GetFullPath() );
1723 DisplayErrorMessage( this, _( "Error Saving Library" ), msg );
1724 return false;
1725 }
1726
1727 if( aSaveType == SAVE_LIBRARY_AS::ORIGINAL )
1728 {
1729 m_libMgr->ClearLibraryModified( aLibrary );
1730
1732
1733 // Update the library modification time so that we don't reload based on the watcher
1734 if( aLibrary == getTargetLib() )
1735 {
1736 if( wxFileName::DirExists( fn.GetFullPath() ) )
1737 {
1739 fn.GetFullPath(),
1740 wxS( "*." ) + wxString( FILEEXT::KiCadSymbolLibFileExtension ) ) );
1741 }
1742 else if( fn.FileExists() )
1743 {
1744 wxLogNull silence;
1745 SetSymModificationTime( fn.GetModificationTime().GetValue().GetValue() );
1746 }
1747 }
1748 }
1749 else
1750 {
1751 bool resyncLibTree = false;
1752 wxString originalLibNickname = getTargetLib();
1753 wxString forceRefresh;
1754
1755 switch( type )
1756 {
1758 resyncLibTree = replaceLibTableEntry( originalLibNickname, fn.GetFullPath() );
1759 forceRefresh = originalLibNickname;
1760 break;
1761
1763 resyncLibTree = addLibTableEntry( fn.GetFullPath() );
1764 break;
1765
1767 resyncLibTree = addLibTableEntry( fn.GetFullPath(), LIBRARY_TABLE_SCOPE::PROJECT );
1768 break;
1769
1770 default:
1771 break;
1772 }
1773
1774 if( resyncLibTree )
1775 {
1776 m_treePane->Freeze();
1777 SyncLibraries( true, false, forceRefresh );
1778 m_treePane->Thaw();
1779 }
1780 }
1781
1782 ClearMsgPanel();
1783 msg.Printf( _( "Symbol library file '%s' saved." ), fn.GetFullPath() );
1785
1786 return true;
1787}
1788
1789
1790bool SYMBOL_EDIT_FRAME::SaveLibraryHeadless( const wxString& aLibrary )
1791{
1792 return saveLibrary( aLibrary, SAVE_LIBRARY_AS::ORIGINAL );
1793}
1794
1795
1796bool SYMBOL_EDIT_FRAME::saveAllLibraries( bool aRequireConfirmation )
1797{
1798 wxString msg, msg2;
1799 bool doSave = true;
1800 int dirtyCount = 0;
1801 bool applyToAll = false;
1802 bool retv = true;
1803
1804 for( const wxString& libNickname : m_libMgr->GetLibraryNames() )
1805 {
1806 if( m_libMgr->IsLibraryModified( libNickname ) )
1807 dirtyCount++;
1808 }
1809
1810 for( const wxString& libNickname : m_libMgr->GetLibraryNames() )
1811 {
1812 if( m_libMgr->IsLibraryModified( libNickname ) )
1813 {
1814 if( aRequireConfirmation && !applyToAll )
1815 {
1816 msg.Printf( _( "Save changes to '%s' before closing?" ), libNickname );
1817
1818 switch( UnsavedChangesDialog( this, msg, dirtyCount > 1 ? &applyToAll : nullptr ) )
1819 {
1820 case wxID_YES: doSave = true; break;
1821 case wxID_NO: doSave = false; break;
1822 default:
1823 case wxID_CANCEL: return false;
1824 }
1825 }
1826
1827 if( doSave )
1828 {
1829 // If saving under existing name fails then do a Save As..., and if that
1830 // fails then cancel close action.
1831 if( m_libMgr->IsLibraryReadOnly( libNickname ) )
1832 {
1833 msg.Printf( _( "Symbol library '%s' is not writable." ), libNickname );
1834 msg2 = _( "You must save to a different location." );
1835
1836 if( dirtyCount == 1 )
1837 {
1838 if( OKOrCancelDialog( this, _( "Warning" ), msg, msg2 ) != wxID_OK )
1839 {
1840 retv = false;
1841 continue;
1842 }
1843 }
1844 else
1845 {
1846 m_infoBar->Dismiss();
1847 m_infoBar->ShowMessageFor( msg + wxS( " " ) + msg2, 5000, wxICON_EXCLAMATION );
1848
1849 while( m_infoBar->IsShownOnScreen() )
1850 wxSafeYield();
1851
1852 retv = false;
1853 continue;
1854 }
1855 }
1856 else if( saveLibrary( libNickname, SAVE_LIBRARY_AS::ORIGINAL ) )
1857 {
1858 continue;
1859 }
1860
1861 if( !saveLibrary( libNickname, SAVE_LIBRARY_AS::NEW ) )
1862 retv = false;
1863 }
1864 }
1865 }
1866
1867 return retv;
1868}
1869
1870
1872{
1874
1875 if( !m_symbol )
1876 return;
1877
1878 wxString msg = m_symbol->GetName();
1879
1880 AppendMsgPanel( _( "Name" ), UnescapeString( msg ), 8 );
1881
1882 if( m_symbol->IsDerived() )
1883 {
1884 std::shared_ptr<LIB_SYMBOL> parent = m_symbol->GetParent().lock();
1885
1886 msg = parent ? parent->GetName() : _( "Undefined!" );
1887 AppendMsgPanel( _( "Parent" ), UnescapeString( msg ), 8 );
1888 }
1889
1890 if( m_symbol->IsGlobalPower() )
1891 msg = _( "Power Symbol" );
1892 else if( m_symbol->IsLocalPower() )
1893 msg = _( "Power Symbol (Local)" );
1894 else
1895 msg = _( "Symbol" );
1896
1897 AppendMsgPanel( _( "Type" ), msg, 8 );
1898 AppendMsgPanel( _( "Description" ), m_symbol->GetDescription(), 8 );
1899 AppendMsgPanel( _( "Keywords" ), m_symbol->GetKeyWords() );
1900 AppendMsgPanel( _( "Datasheet" ), m_symbol->GetDatasheetField().GetText() );
1901}
const char * name
static TOOL_ACTION cancelInteractive
Definition actions.h:69
static TOOL_ACTION zoomFitScreen
Definition actions.h:139
bool IsContentModified() const
Definition base_screen.h:56
void SetContentModified(bool aModified=true)
Definition base_screen.h:55
wxString GetParentSymbolName() const
wxString GetName() const override
void SetInitialFocus(wxWindow *aWindow)
Sets the window (usually a wxTextCtrl) that should be focused when the dialog is shown.
Definition dialog_shim.h:95
void SetupStandardButtons(std::map< int, wxString > aLabels={})
int ShowModal() override
virtual void ClearUndoRedoList()
Clear the undo and redo list using ClearUndoORRedoList()
WX_INFOBAR * m_infoBar
void ShowInfoBarError(const wxString &aErrorMsg, bool aShowCloseButton=false, INFOBAR_MESSAGE_TYPE aType=INFOBAR_MESSAGE_TYPE::GENERIC)
Show the WX_INFOBAR displayed on the top of the canvas with a message and an error icon on the left o...
virtual void RecreateToolbars()
void ReCreateMenuBar()
Recreate the menu bar.
WX_INFOBAR * GetInfoBar()
virtual void ClearMsgPanel()
Clear all messages from the message panel.
void AppendMsgPanel(const wxString &aTextUpper, const wxString &aTextLower, int aPadding=6)
Append a message to the message panel.
void SetOKLabel(const wxString &aLabel)
void initDialog(const wxArrayString &aItemHeaders, const std::vector< wxArrayString > &aItemList, const wxString &aPreselectText)
wxString GetTextSelection(int aColumn=0)
Return the selected text from aColumn in the wxListCtrl in the dialog.
void SetListLabel(const wxString &aLabel)
void GetExtraCheckboxValues()
Fills in the value pointers from the checkboxes after the dialog has run.
EDA_LIST_DIALOG(wxWindow *aParent, const wxString &aTitle, const wxArrayString &aItemHeaders, const std::vector< wxArrayString > &aItemList, const wxString &aPreselectText=wxEmptyString, bool aSortList=true)
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()
virtual const wxString Problem() const
what was the problem?
Helper class to create more flexible dialogs, including 'do not show again' checkbox handling.
Definition kidialog.h:38
void DoNotShowCheckbox(wxString file, int line)
Shows the 'do not show again' checkbox.
Definition kidialog.cpp:51
int ShowModal() override
Definition kidialog.cpp:89
void UpdateAllItems(int aUpdateFlags)
Update all items in the view according to the given flags.
Definition view.cpp:2474
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:407
bool HasLibrary(const wxString &aNickname, bool aCheckEnabled=false) const
Test for the existence of aNickname in the library tables.
std::optional< LIBRARY_TABLE_ROW * > GetRow(const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH) const
Like LIBRARY_MANAGER::GetRow but filtered to the LIBRARY_TABLE_TYPE of this adapter.
std::optional< wxString > GetFullURI(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, bool aSubstituted=false)
Return the full location specifying URI for the LIB, either in original UI form or in environment var...
std::optional< LIBRARY_TABLE_ROW * > GetRow(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH)
const wxString & Type() const
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
wxString GetUniStringLibId() const
Definition lib_id.h:144
const wxString GetUniStringLibItemName() const
Get strings for display messages in dialogs.
Definition lib_id.h:108
const wxString GetUniStringLibNickname() const
Definition lib_id.h:84
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
Symbol library management helper that is specific to the symbol library editor frame.
static std::unique_ptr< LIB_SYMBOL > CreateSymbol(const NEW_SYMBOL_PROPERTIES &aProps, LIB_SYMBOL *aParent)
Define a library symbol object.
Definition lib_symbol.h:114
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:190
bool UnitsLocked() const
Check whether symbol units are interchangeable.
bool IsDerived() const
Definition lib_symbol.h:241
LIB_ID GetSourceLibId() const
Definition lib_symbol.h:193
void SetParent(LIB_SYMBOL *aParent=nullptr)
wxString GetName() const override
Definition lib_symbol.h:183
SCH_FIELD & GetValueField()
Definition lib_symbol.h:449
std::shared_ptr< LIB_SYMBOL > SharedPtr() const
http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/sp_techniques.html#weak_without_shared.
Definition lib_symbol.h:125
std::unique_ptr< LIB_SYMBOL > Flatten() const
Return a flattened symbol inheritance to the caller.
void SetParentName(const wxString &aParentName)
Definition lib_symbol.h:996
void SetLibId(const LIB_ID &aLibId)
virtual void SetName(const wxString &aName)
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:126
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
static SEARCH_STACK * SchSearchS(PROJECT *aProject)
Accessor for Eeschema search stack.
Container for project specific data.
Definition project.h:63
@ SCH_LIB_PATH
Definition project.h:235
virtual void SetRString(RSTRING_T aStringId, const wxString &aString)
Store a "retained string", which is any session and project specific string identified in enum RSTRIN...
Definition project.cpp:449
virtual const wxString & GetRString(RSTRING_T aStringId)
Return a "retained string", which is any session and project specific string identified in enum RSTRI...
Definition project.cpp:460
bool TransferDataFromWindow() override
std::function< int(const wxString &libName, const wxString &symbolName)> SymLibNameValidator
bool TransferDataToWindow() override
SymLibNameValidator m_validator
SAVE_SYMBOL_AS_DIALOG(SYMBOL_EDIT_FRAME *aParent, PARAMS &aParams, SymLibNameValidator aValidator, const std::vector< wxString > &aParentSymbolNames)
wxString getSymbolName() const
wxTextCtrl * m_symbolNameCtrl
SCH_SCREEN * GetScreen() const override
Return a pointer to a BASE_SCREEN or one of its derivatives.
SCH_DRAW_PANEL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
void GetLibraryItemsForListDialog(wxArrayString &aHeaders, std::vector< wxArrayString > &aItemsToDisplay)
void setSymWatcher(const LIB_ID *aSymbol)
Creates (or removes) a watcher on the specified symbol library.
void SetSymModificationTime(long long aTimestamp)
Set the modification timestamp of the watched symbol library.
KIGFX::SCH_VIEW * GetView() const override
Return a pointer to the KIGFX::VIEW instance used in the panel.
Schematic editor (Eeschema) main window.
bool SaveSymbolToSchematic(const LIB_SYMBOL &aSymbol, const KIID &aSchematicSymbolUUID)
Update a schematic symbol from a LIB_SYMBOL.
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
void SetText(const wxString &aText) override
static void FormatLibSymbol(LIB_SYMBOL *aPart, OUTPUTFORMATTER &aFormatter)
static std::vector< LIB_SYMBOL * > ParseLibSymbols(std::string &aSymbolText, std::string aSource, int aFileVersion=SEXPR_SCHEMATIC_FILE_VERSION)
static SCH_FILE_T EnumFromStr(const wxString &aFileType)
Return the file type from the corresponding plugin type name: "kicad", "legacy", etc.
static SCH_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a symbol library using the file extension of aLibPath.
Look for files in a number of paths.
const wxString LastVisitedPath(const wxString &aSubPathToSearch=wxEmptyString)
A quirky function inherited from old code that seems to serve particular needs in the UI.
Implement an OUTPUTFORMATTER to a memory buffer.
Definition richio.h:430
const std::string & GetString()
Definition richio.h:453
One open symbol tab owning a working LIB_SYMBOL and screen lent to the frame while active.
The symbol library editor main window.
std::vector< std::unique_ptr< SYMBOL_EDITOR_TAB_CONTEXT > > m_tabContexts
bool SaveLibraryHeadless(const wxString &aLibrary)
Save the given library (including buffered changes) without user interaction.
void ClearMsgPanel() override
Clear all messages from the message panel.
void UpdateAfterSymbolProperties(wxString *aOldName=nullptr)
void SaveAll()
Save all modified symbols and libraries.
bool IsLibraryTreeShown() const override
void RenameSymbolTab(const LIB_ID &aOldId, const LIB_ID &aNewId)
Update the open tab for aOldId, if any, to the renamed symbol aNewId so its label and key track the r...
wxString getTargetLib() const
Return either the library selected in the symbol tree, if context menu is active or the library that ...
bool LoadSymbolFromLib(const wxString &aLibName, const wxString &aSymbolName, int aUnit=0, int aBodyStyle=0)
Load a symbol from a library, optionally setting the selected unit and body style.
bool backupLibrary(const wxFileName &aOriginalFile, wxString &aErrorMsg)
Create a backup copy of a symbol library.
EDITOR_TABS_PANEL * m_tabsPanel
bool saveLibrary(const wxString &aLibrary, SAVE_LIBRARY_AS aSaveType=SAVE_LIBRARY_AS::ORIGINAL)
Save the changes to the current library.
void RebuildSymbolUnitAndBodyStyleLists()
int GetTreeLIBIDs(std::vector< LIB_ID > &aSelection) const
LIB_ID GetTreeLIBID(int *aUnit=nullptr) const
Return the LIB_ID of the library or symbol selected in the symbol tree.
LIB_SYMBOL_LIBRARY_MANAGER * m_libMgr
void SaveLibraryAs(SAVE_LIBRARY_AS aSaveType=SAVE_LIBRARY_AS::NEW)
Save the currently selected library to a new file.
void Save()
Save the selected symbol or library.
void LoadSymbol(const wxString &aLibrary, const wxString &aSymbol, int Unit)
bool addLibTableEntry(const wxString &aLibFile, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::GLOBAL)
Add aLibFile to the symbol library table defined by aScope.
int m_unit
The unit number to edit and show.
bool LoadOneLibrarySymbol(LIB_SYMBOL *aLibEntry, const wxString &aLibrary, int aUnit, int aBodyStyle)
Create a copy of aLibEntry into memory.
void centerItemIdleHandler(wxIdleEvent &aEvent)
bool replaceLibTableEntry(const wxString &aLibNickname, const wxString &aLibFile)
Replace the file path of the symbol library table entry aLibNickname with aLibFile.
bool IsSymbolFromSchematic() const
LIB_ID closeLibraryTabs(const wxString &aLibrary, const wxString &aSymbol)
Close the library tabs of aLibrary, or of every library when it is empty, limited to aSymbol when giv...
SYMBOL_EDITOR_TAB_CONTEXT * m_activeTab
void DuplicateSymbol(bool aFromClipboard)
Insert a duplicate symbol.
void saveSymbolCopyAs(bool aOpenCopy)
std::vector< LIB_ID > GetSelectedLibIds() const
void SyncLibraries(bool aShowProgress, bool aPreloadCancelled=false, const wxString &aForceRefresh=wxEmptyString)
Synchronize the library manager to the symbol library table, and then the symbol tree to the library ...
SYMBOL_EDITOR_TAB_CONTEXT * findOrCreateSymbolTab(const wxString &aLib, const wxString &aName, int aUnit, int aBodyStyle, bool aAsPreview, bool *aWasCreated=nullptr)
Open aName from aLib in a tab, creating it when absent, and return the activated context.
LIB_SYMBOL * GetCurSymbol() const
Return the current symbol being edited or NULL if none selected.
void UpdateSymbolMsgPanelInfo()
Display the documentation of the selected symbol.
LIB_ID GetTargetLibId() const override
Return either the symbol selected in the symbol tree (if context menu is active) or the symbol on the...
int m_bodyStyle
Show the normal shape (m_bodyStyle <= 1) or the DeMorgan converted shape (m_bodyStyle > 1)
bool saveAllLibraries(bool aRequireConfirmation)
Return true when the operation has succeeded (all requested libraries have been saved or none was sel...
void UpdateMsgPanel() override
Redraw the message panel.
void CreateNewSymbol(const wxString &newName=wxEmptyString)
Create a new symbol in the selected library.
void UpdateTitle()
Update the main window title bar with the current library name and read only status of the library.
SYMBOL_EDITOR_TAB_CONTEXT * CreateUnsavedSymbolTab(LIB_SYMBOL *aSymbol, SCH_SCREEN *aScreen)
Open a new tab over a transient working symbol and screen and make it active.
SYMBOL_TREE_PANE * m_treePane
void SetDrawSpecificUnit(bool aSpecific)
void closeSymbolTab(const LIB_ID &aLibId)
Close the open tab for aLibId, if any, without prompting and leaving the other tabs open.
bool saveCurrentSymbol()
Save the current symbol.
void SaveSymbolCopyAs(bool aOpenCopy)
Save the currently selected symbol to a new name and/or location.
void clearSymbolTabsModifiedForLibrary(const wxString &aLibrary)
Clear the unsaved-edits flag on every tab in a saved library so its dirty indicator clears.
wxString AddLibraryFile(bool aCreateNew)
Create or add an existing library to the symbol library table.
void Revert(LIB_ID &aTarget, bool aConfirm=true)
Revert unsaved changes in a symbol, restoring to the last saved state.
void ensureUniqueName(LIB_SYMBOL *aSymbol, const wxString &aLibrary)
Rename LIB_SYMBOL aliases to avoid conflicts before adding a symbol to a library.
void UpdateLibraryTree(const wxDataViewItem &aTreeItem, LIB_SYMBOL *aSymbol)
Update a symbol node in the library tree.
void OnModify() override
Must be called after a schematic change in order to set the "modify" flag of the current symbol.
bool IsContentModified() const override
Get if any symbols or libraries have been modified but not saved.
LIB_SYMBOL * getTargetSymbol() const
Return currently edited symbol.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
LIB_SYMBOL * LoadSymbol(const wxString &aNickname, const wxString &aName)
Load a LIB_SYMBOL having aName from the library given by aNickname.
bool SymbolNameInUse(const wxString &aName, const wxString &aLibrary)
Return true if the symbol name is already in use in the specified library.
LIB_SYMBOL * GetSymbol(const wxString &aSymbolName, const wxString &aLibrary) const
Return either an alias of a working LIB_SYMBOL copy, or alias of the original symbol if there is no w...
This is a class that handles state involved in saving a symbol copy as a new symbol.
CONFLICT_STRATEGY m_strategy
wxString resolveConflict(const wxString &proposed, const wxString &aNewLibName) const
SYMBOL_SAVE_AS_HANDLER(LIB_SYMBOL_LIBRARY_MANAGER &aLibMgr, CONFLICT_STRATEGY aStrategy, bool aValueFollowsName)
LIB_SYMBOL_LIBRARY_MANAGER & m_libMgr
bool DoSave(LIB_SYMBOL &symbol, const wxString &aNewSymName, const wxString &aNewLibName, bool aFlattenSymbol)
TOOL_MANAGER * m_toolManager
bool empty() const
Definition utf8.h:105
wxString wx_str() const
Definition utf8.cpp:41
void Dismiss() override
Dismisses the infobar and updates the containing layout and AUI manager (if one is provided).
std::string GetClipboardUTF8()
Return the information currently stored in the system clipboard.
int OKOrCancelDialog(wxWindow *aParent, const wxString &aWarning, const wxString &aMessage, const wxString &aDetailedMessage, const wxString &aOKLabel, const wxString &aCancelLabel, bool *aApplyToAll)
Display a warning dialog with aMessage and returns the user response.
Definition confirm.cpp:165
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
bool HandleUnsavedChanges(wxWindow *aParent, const wxString &aMessage, const std::function< bool()> &aSaveFunction)
Display a dialog with Save, Cancel and Discard Changes buttons.
Definition confirm.cpp:146
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
int UnsavedChangesDialog(wxWindow *parent, const wxString &aMessage, bool *aApplyToAll)
A specialized version of HandleUnsavedChanges which handles an apply-to-all checkbox.
Definition confirm.cpp:60
bool ConfirmRevertDialog(wxWindow *parent, const wxString &aMessage)
Display a confirmation dialog for a revert action.
Definition confirm.cpp:133
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 KICAD_MESSAGE_DIALOG
Definition confirm.h:48
#define _(s)
@ ITALIC
Definition font.h:44
@ FRAME_SCH
Definition frame_type.h:30
static const std::string KiCadSymbolLibFileExtension
static wxString KiCadSymbolLibFileWildcard()
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
PROJECT & Prj()
Definition kicad.cpp:730
void Prettify(std::string &aSource, FORMAT_MODE aMode)
Pretty-prints s-expression text according to KiCad format rules.
@ ALL
All except INITIAL_ADD.
Definition view_item.h:55
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
Computes a hash of modification times and sizes for files matching a pattern.
Definition unix/io.cpp:123
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:741
STL namespace.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
KIWAY Kiway(KFCTL_STANDALONE)
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
wxString UnescapeString(const wxString &aSource)
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_LIBID
SYMBOL_SAVE_AS_HANDLER::CONFLICT_STRATEGY m_ConflictStrategy
SAVE_LIBRARY_AS
Types of KiCad symbol library save actions.
@ NEW
Save to a new library in the original symbol library format.
@ UNPACKED
Save a packed symbol library to the unpacked format.
@ PACKED
Save an unpacked symbol library to the packed format.
@ ORIGINAL
Save to the original symbol library format.
SAVE_AS_IDS
@ ID_OVERWRITE_CONFLICTS
@ ID_RENAME_CONFLICTS
@ ID_MAKE_NEW_LIBRARY
static std::vector< wxString > CheckForParentalChainConflicts(LIB_SYMBOL_LIBRARY_MANAGER &aLibMgr, LIB_SYMBOL &aSymbol, bool aFlattenSymbol, const wxString &newSymbolName, const wxString &newLibraryName)
Get a list of all the symbols in the parental chain of a symbol that have conflicts when transposed t...
static std::vector< std::shared_ptr< LIB_SYMBOL > > GetParentChain(const LIB_SYMBOL &aSymbol, bool aIncludeLeaf=true)
Get a list of all the symbols in the parental chain of a symbol, with the "leaf" symbol at the start ...
static std::pair< bool, bool > CheckSavingIntoOwnInheritance(LIB_SYMBOL_LIBRARY_MANAGER &aLibMgr, LIB_SYMBOL &aSymbol, const wxString &aNewSymbolName, const wxString &aNewLibraryName)
Check if a planned overwrite would put a symbol into it's own inheritance chain.
SYMBOL_SAVEAS_TYPE
JSON_SCHEMA_VALIDATOR validator(schema)
const SHAPE_LINE_CHAIN chain
Definition of file extensions used in Kicad.