KiCad PCB EDA Suite
Loading...
Searching...
No Matches
symbol_library_manager.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 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Maciej Suminski <[email protected]>
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 3
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
23
25#include <symbol_edit_frame.h>
26#include <env_paths.h>
27#include <pgm_base.h>
28#include <project_sch.h>
29#include <kiway.h>
30#include <core/profile.h>
31#include <core/wx_stl_compat.h>
32#include <unordered_map>
33#include <wx_filename.h>
35#include <progress_reporter.h>
36#include <algorithm>
37#include <list>
38#include <locale_io.h>
39#include <confirm.h>
40#include <string_utils.h>
42#include <kiplatform/io.h>
45
46#include "lib_logger.h"
47
48
54
55
60
61
63{
64 for( const auto& [name, buffer] : m_libs )
65 {
66 if( buffer.IsModified() )
67 return true;
68 }
69
70 return false;
71}
72
73
75{
77 return adapter->GetModifyHash();
78}
79
80
81int SYMBOL_LIBRARY_MANAGER::GetLibraryHash( const wxString& aLibrary ) const
82{
83 if( const auto libBufIt = m_libs.find( aLibrary ); libBufIt != m_libs.end() )
84 return libBufIt->second.GetHash();
85
87
88 if( std::optional<wxString> uri = manager.GetFullURI( LIBRARY_TABLE_TYPE::SYMBOL, aLibrary, true ); uri )
89 {
90 // Mix a file modification timestamp into the hash so that external changes (e.g. a git
91 // branch switch) are detected by the library tree synchronizer without a restart.
92 wxFileName fn( *uri );
93 long long mtime = 0;
94
95 wxLogNull silence;
96
97 fn.Normalize( FN_NORMALIZE_FLAGS );
98
99 if( fn.DirExists() )
100 {
101 mtime = KIPLATFORM::IO::TimestampDir( fn.GetFullPath(),
102 wxS( "*." ) + wxString( FILEEXT::KiCadSymbolLibFileExtension ) );
103 }
104 else if( fn.IsFileReadable() )
105 {
106 mtime = fn.GetModificationTime().GetValue().GetValue();
107 }
108
109 size_t base = std::hash<std::string>{}( aLibrary.ToStdString() + uri->ToStdString() );
110 return static_cast<int>( base ^ static_cast<size_t>( mtime ) );
111 }
112
113 return -1;
114}
115
116
118{
119 wxArrayString res;
120
122
123 for( const LIBRARY_TABLE_ROW* row : manager.Rows( LIBRARY_TABLE_TYPE::SYMBOL ) )
124 {
125 // Database libraries are hidden from the symbol editor at the moment
126 if( row->Type() == SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_DATABASE ) )
127 continue;
128
129 res.Add( row->Nickname() );
130 }
131
132 res.Sort( []( const wxString& lhs, const wxString& rhs ) -> int
133 {
134 return StrNumCmp( lhs, rhs, CMP_T::IGNORE_CASE );
135 } );
136
137 return res;
138}
139
140
141bool SYMBOL_LIBRARY_MANAGER::SaveLibrary( const wxString& aLibrary, const wxString& aFileName,
142 SCH_IO_MGR::SCH_FILE_T aFileType )
143{
144 wxCHECK( aFileType != SCH_IO_MGR::SCH_FILE_T::SCH_LEGACY, false );
145
146 wxFileName fn( aFileName );
147
148 if( fn.FileExists() && !fn.IsFileWritable() )
149 return false;
150
151 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( aFileType ) );
152 bool res = true; // assume all libraries are successfully saved
153 std::map<std::string, UTF8> properties;
154
155 properties.emplace( SCH_IO_KICAD_LEGACY::PropBuffering, "" );
156
157 auto it = m_libs.find( aLibrary );
158
159 if( it != m_libs.end() )
160 {
161 // Handle buffered library
162 LIB_BUFFER& libBuf = it->second;
163
164 const std::deque<std::shared_ptr<SYMBOL_BUFFER>>& symbolBuffers = libBuf.GetBuffers();
165
166 wxFileName original, destination( aFileName );
168
169 if( std::optional<wxString> uri = manager.GetFullURI( LIBRARY_TABLE_TYPE::SYMBOL, aLibrary, true ); uri )
170 {
171 original = *uri;
172 original.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
173 }
174
175 destination.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
176
177 bool toOriginal = original == destination;
178
179 if( toOriginal )
180 {
181 res = libBuf.SaveModifiedBuffers( aFileName, &*pi );
182 }
183 else
184 {
185 for( const std::shared_ptr<SYMBOL_BUFFER>& symbolBuf : symbolBuffers )
186 {
187 wxCHECK2( symbolBuf, continue );
188
189 if( !libBuf.SaveBuffer( *symbolBuf, aFileName, &*pi, true ) )
190 {
191 // Something went wrong, but try to save other symbols
192 res = false;
193 }
194 }
195 }
196
197 // clear the deleted symbols buffer only if data is saved to the original file
198 if( res && toOriginal )
199 {
200 // Delete symbols that were removed from the buffer before clearing the deleted list
201 for( const std::shared_ptr<SYMBOL_BUFFER>& deletedBuf : libBuf.GetDeletedBuffers() )
202 {
203 wxCHECK2( deletedBuf, continue );
204
205 const wxString& originalName = deletedBuf->GetOriginal().GetName();
206
207 try
208 {
209 if( pi->LoadSymbol( aFileName, originalName ) )
210 pi->DeleteSymbol( aFileName, originalName, &properties );
211 }
212 catch( const IO_ERROR& ioe )
213 {
214 wxLogError( _( "Error deleting symbol %s from library '%s'." ) + wxS( "\n%s" ),
215 UnescapeString( originalName ),
216 aFileName,
217 ioe.What() );
218 res = false;
219 }
220 }
221
223 }
224 }
225 else
226 {
227 // Handle original library
228 for( LIB_SYMBOL* symbol : getOriginalSymbols( aLibrary ) )
229 {
230 try
231 {
232 if( symbol->IsDerived() )
233 {
234 std::shared_ptr< LIB_SYMBOL > oldParent = symbol->GetParent().lock();
235
236 wxCHECK_MSG( oldParent, false,
237 wxString::Format( wxT( "Derived symbol '%s' found with undefined parent." ),
238 symbol->GetName() ) );
239
240 LIB_SYMBOL* libParent = pi->LoadSymbol( aFileName, oldParent->GetName(), &properties );
241
242 if( !libParent )
243 {
244 std::unique_ptr<LIB_SYMBOL> newParent = std::make_unique<LIB_SYMBOL>( *oldParent );
245 pi->SaveSymbol( aFileName, std::move( newParent ), &properties );
246
247 // We cannot use the old parent after handing it to the plugin, we
248 // must borrow a new copy from the plugin cache to reparent the derived symbol.
249 libParent = pi->LoadSymbol( aFileName, oldParent->GetName(), &properties );
250 }
251 else
252 {
253 // Copy embedded files from the in-memory parent to the loaded parent
254 // This ensures that any embedded files added to the parent are preserved
255 //
256 // We do this manually rather than using the assignment operator to avoid
257 // potential ABI issues where the size of EMBEDDED_FILES differs between
258 // compilation units, potentially causing the assignment to overwrite
259 // members of LIB_SYMBOL (like m_me) that follow the EMBEDDED_FILES base.
260 libParent->ClearEmbeddedFiles();
261
262 for( const auto& [name, file] : oldParent->EmbeddedFileMap() )
263 libParent->AddFile( new EMBEDDED_FILES::EMBEDDED_FILE( *file ) );
264
265 libParent->SetAreFontsEmbedded( oldParent->GetAreFontsEmbedded() );
266 libParent->SetFileAddedCallback( oldParent->GetFileAddedCallback() );
267 }
268
269 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( *symbol );
270 newSymbol->SetParent( libParent );
271 pi->SaveSymbol( aFileName, std::move( newSymbol ), &properties );
272 }
273 else if( !pi->LoadSymbol( aFileName, symbol->GetName(), &properties ) )
274 {
275 pi->SaveSymbol( aFileName, std::make_unique<LIB_SYMBOL>( *symbol ), &properties );
276 }
277 }
278 catch( ... )
279 {
280 res = false;
281 break;
282 }
283 }
284 }
285
286 try
287 {
288 pi->SaveLibrary( aFileName );
289 }
290 catch( ... )
291 {
292 // return false because something happens.
293 // The library is not successfully saved
294 res = false;
295 }
296
297 return res;
298}
299
300
301bool SYMBOL_LIBRARY_MANAGER::IsLibraryModified( const wxString& aLibrary ) const
302{
303 auto it = m_libs.find( aLibrary );
304 return it != m_libs.end() ? it->second.IsModified() : false;
305}
306
307
308bool SYMBOL_LIBRARY_MANAGER::IsSymbolModified( const wxString& aSymbolName, const wxString& aLibrary ) const
309{
310 auto libIt = m_libs.find( aLibrary );
311
312 if( libIt == m_libs.end() )
313 return false;
314
315 const LIB_BUFFER& buf = libIt->second;
316 const std::shared_ptr<SYMBOL_BUFFER> symbolBuf = buf.GetBuffer( aSymbolName );
317
318 return symbolBuf ? symbolBuf->IsModified() : false;
319}
320
321
322void SYMBOL_LIBRARY_MANAGER::SetSymbolModified( const wxString& aSymbolName, const wxString& aLibrary )
323{
324 auto libIt = m_libs.find( aLibrary );
325
326 if( libIt == m_libs.end() )
327 return;
328
329 const LIB_BUFFER& buf = libIt->second;
330 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = buf.GetBuffer( aSymbolName );
331
332 wxCHECK( symbolBuf, /* void */ );
333
334 symbolBuf->GetScreen()->SetContentModified();
335}
336
337
338bool SYMBOL_LIBRARY_MANAGER::ClearLibraryModified( const wxString& aLibrary ) const
339{
340 auto libIt = m_libs.find( aLibrary );
341
342 if( libIt == m_libs.end() )
343 return false;
344
345 for( const std::shared_ptr<SYMBOL_BUFFER>& symbolBuf : libIt->second.GetBuffers() )
346 {
347 SCH_SCREEN* screen = symbolBuf->GetScreen();
348
349 if( screen )
350 screen->SetContentModified( false );
351 }
352
353 return true;
354}
355
356
357bool SYMBOL_LIBRARY_MANAGER::IsLibraryReadOnly( const wxString& aLibrary ) const
358{
360 return !adapter->IsSymbolLibWritable( aLibrary );
361}
362
363
364bool SYMBOL_LIBRARY_MANAGER::IsLibraryLoaded( const wxString& aLibrary ) const
365{
367 return adapter->IsLibraryLoaded( aLibrary );
368}
369
370
371std::list<LIB_SYMBOL*> SYMBOL_LIBRARY_MANAGER::EnumerateSymbols( const wxString& aLibrary ) const
372{
373 std::list<LIB_SYMBOL*> ret;
374 auto libIt = m_libs.find( aLibrary );
375
376 if( libIt != m_libs.end() )
377 {
378 for( const std::shared_ptr<SYMBOL_BUFFER>& symbolBuf : libIt->second.GetBuffers() )
379 ret.push_back( &symbolBuf->GetSymbol() );
380 }
381 else
382 {
384 std::vector<LIB_SYMBOL*> symbols = adapter->GetSymbols( aLibrary );
385
386 std::copy( symbols.begin(), symbols.end(), std::back_inserter( ret ) );
387 }
388
389 return ret;
390}
391
392
393LIB_SYMBOL* SYMBOL_LIBRARY_MANAGER::GetBufferedSymbol( const wxString& aSymbolName, const wxString& aLibrary )
394{
395 // try the library buffers first
396 LIB_BUFFER& libBuf = getLibraryBuffer( aLibrary );
397 LIB_SYMBOL* bufferedSymbol = libBuf.GetSymbol( aSymbolName );
398
399 if( !bufferedSymbol ) // no buffer symbol found
400 {
402
403 // create a copy of the symbol
404 try
405 {
406 LIB_SYMBOL* symbol = adapter->LoadSymbol( aLibrary, aSymbolName );
407
408 if( symbol == nullptr )
409 THROW_IO_ERROR( _( "Symbol not found." ) );
410
411 LIB_SYMBOL* bufferedParent = nullptr;
412
413 // Create parent symbols on demand so parent symbol can be set.
414 if( symbol->IsDerived() )
415 {
416 std::shared_ptr<LIB_SYMBOL> parent = symbol->GetParent().lock();
417 wxCHECK_MSG( parent, nullptr, wxString::Format( "Derived symbol '%s' found with undefined parent.",
418 symbol->GetName() ) );
419
420 // Check if the parent symbol buffer has already be created.
421 bufferedParent = libBuf.GetSymbol( parent->GetName() );
422
423 if( !bufferedParent )
424 {
425 std::unique_ptr<LIB_SYMBOL> newParent = std::make_unique<LIB_SYMBOL>( *parent );
426 bufferedParent = newParent.get();
427 libBuf.CreateBuffer( std::move( newParent ), std::make_unique<SCH_SCREEN>() );
428 }
429 }
430
431 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( *symbol );
432 bufferedSymbol = newSymbol.get();
433
434 if( bufferedParent )
435 newSymbol->SetParent( bufferedParent );
436
437 libBuf.CreateBuffer( std::move( newSymbol ), std::make_unique<SCH_SCREEN>() );
438 }
439 catch( const IO_ERROR& e )
440 {
441 wxString msg;
442
443 msg.Printf( _( "Error loading symbol %s from library '%s'." ),
444 aSymbolName,
445 aLibrary );
446 DisplayErrorMessage( &m_frame, msg, e.What() );
447 bufferedSymbol = nullptr;
448 }
449 }
450
451 return bufferedSymbol;
452}
453
454
455SCH_SCREEN* SYMBOL_LIBRARY_MANAGER::GetScreen( const wxString& aSymbolName, const wxString& aLibrary )
456{
457 auto it = m_libs.find( aLibrary );
458 wxCHECK( it != m_libs.end(), nullptr );
459
460 LIB_BUFFER& buf = it->second;
461 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = buf.GetBuffer( aSymbolName );
462
463 return symbolBuf ? symbolBuf->GetScreen() : nullptr;
464}
465
466
467SYMBOL_BUFFER* SYMBOL_LIBRARY_MANAGER::GetBuffer( const wxString& aSymbolName, const wxString& aLibrary )
468{
469 if( !LibraryExists( aLibrary ) )
470 return nullptr;
471
472 LIB_BUFFER& libBuf = getLibraryBuffer( aLibrary );
473
474 // Buffers live as long as the manager, so the raw pointer dangles only if a caller outlives it.
475 return libBuf.GetBuffer( aSymbolName ).get();
476}
477
478
479bool SYMBOL_LIBRARY_MANAGER::UpdateSymbol( LIB_SYMBOL* aSymbol, const wxString& aLibrary )
480{
481 LIB_BUFFER& libBuf = getLibraryBuffer( aLibrary );
482 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = libBuf.GetBuffer( aSymbol->GetName() );
483
484 if( symbolBuf ) // Existing symbol.
485 {
486 LIB_SYMBOL& bufferedSymbol = symbolBuf->GetSymbol();
487
488 // If we are coming from a different library, the library ID needs to be preserved
489 const LIB_ID libId = bufferedSymbol.GetLibId();
490 bufferedSymbol = *aSymbol;
491 bufferedSymbol.SetLibId( libId );
492
493 symbolBuf->GetScreen()->SetContentModified();
494 }
495 else // New symbol
496 {
497 std::unique_ptr<LIB_SYMBOL> symbolCopy = std::make_unique<LIB_SYMBOL>( *aSymbol, nullptr );
498
499 symbolCopy->SetLibId( LIB_ID( aLibrary, aSymbol->GetLibId().GetLibItemName() ) );
500
501 std::unique_ptr<SCH_SCREEN> newScreen = std::make_unique<SCH_SCREEN>();
502 newScreen->SetContentModified();
503
504 libBuf.CreateBuffer( std::move( symbolCopy ), std::move( newScreen ), true );
505 }
506
507 return true;
508}
509
510
511bool SYMBOL_LIBRARY_MANAGER::UpdateSymbolAfterRename( LIB_SYMBOL* aSymbol, const wxString& aOldName,
512 const wxString& aLibrary )
513{
514 LIB_BUFFER& libBuf = getLibraryBuffer( aLibrary );
515 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = libBuf.GetBuffer( aOldName );
516
517 wxCHECK( symbolBuf && aSymbol, false );
518
519 libBuf.UpdateBuffer( *symbolBuf, *aSymbol );
521
522 return true;
523}
524
525
527{
528 auto it = m_libs.find( aIdToRevert.GetLibNickname() );
529
530 if( it == m_libs.end() ) // no items to flush
531 return aIdToRevert;
532
533 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = it->second.GetBuffer( aIdToRevert.GetLibItemName() );
534 wxCHECK( symbolBuf, aIdToRevert );
535 LIB_SYMBOL original( symbolBuf->GetOriginal() );
536
537 if( original.GetName() != aIdToRevert.GetLibItemName().wx_str() )
538 {
539 UpdateSymbolAfterRename( &original, aIdToRevert.GetLibItemName(), aIdToRevert.GetLibNickname() );
540 }
541 else
542 {
543 // copy the initial data to the current symbol to restore
544 symbolBuf->GetSymbol() = original;
546 }
547
548 symbolBuf->GetScreen()->SetContentModified( false );
549
550 return LIB_ID( aIdToRevert.GetLibNickname(), original.GetName() );
551}
552
553
554bool SYMBOL_LIBRARY_MANAGER::RevertLibrary( const wxString& aLibrary )
555{
556 auto it = m_libs.find( aLibrary );
557
558 if( it == m_libs.end() ) // nothing to reverse
559 return false;
560
561 m_libs.erase( it );
563
564 return true;
565}
566
567
569{
570 bool retv = true;
571
572 // Nothing to revert.
573 if( GetHash() == 0 )
574 return true;
575
576 for( auto& [libName, libBuffer] : m_libs )
577 {
578 if( !libBuffer.IsModified() )
579 continue;
580
581 // A buffer could be modified and then deleted, so make sure it's replaced on the
582 // active list first, and any previous changes can then be reverted below.
583 libBuffer.RevertDeletedBuffers();
584
585 for( const std::shared_ptr<SYMBOL_BUFFER>& buffer : libBuffer.GetBuffers() )
586 {
587 if( !buffer->IsModified() )
588 continue;
589
590 // Restore the buffer itself, since renames can pass its name to another buffer
591 libBuffer.UpdateBuffer( *buffer, buffer->GetOriginal() );
592 buffer->GetScreen()->SetContentModified( false );
593 }
594
595 libBuffer.RevertAddedBuffers();
596 }
597
599 return retv;
600}
601
602
603bool SYMBOL_LIBRARY_MANAGER::RemoveSymbol( const wxString& aSymbolName, const wxString& aLibrary )
604{
605 LIB_BUFFER& libBuf = getLibraryBuffer( aLibrary );
606 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = libBuf.GetBuffer( aSymbolName );
607 wxCHECK( symbolBuf, false );
608
609 bool retv = true;
610
611 retv &= libBuf.DeleteBuffer( *symbolBuf );
613
614 return retv;
615}
616
617
618LIB_SYMBOL* SYMBOL_LIBRARY_MANAGER::GetSymbol( const wxString& aSymbolName, const wxString& aLibrary ) const
619{
620 // Try the library buffers first
621 auto libIt = m_libs.find( aLibrary );
622
623 if( libIt != m_libs.end() )
624 {
625 LIB_SYMBOL* symbol = libIt->second.GetSymbol( aSymbolName );
626
627 if( symbol )
628 return symbol;
629 }
630
631 // Get the original symbol
633 LIB_SYMBOL* symbol = nullptr;
634
635 try
636 {
637 symbol = adapter->LoadSymbol( aLibrary, aSymbolName );
638 }
639 catch( const IO_ERROR& e )
640 {
641 wxString msg;
642
643 msg.Printf( _( "Cannot load symbol '%s' from library '%s'." ),
644 aSymbolName,
645 aLibrary );
646 DisplayErrorMessage( &m_frame, msg, e.What() );
647 }
648
649 return symbol;
650}
651
652
653bool SYMBOL_LIBRARY_MANAGER::SymbolExists( const wxString& aSymbolName, const wxString& aLibrary ) const
654{
655 auto libBufIt = m_libs.find( aLibrary );
656 LIB_SYMBOL* symbol = nullptr;
657
658 if( libBufIt != m_libs.end() )
659 return libBufIt->second.GetBuffer( aSymbolName ) != nullptr;
660
662
663 try
664 {
665 symbol = adapter->LoadSymbol( aLibrary, aSymbolName );
666 }
667 catch( IO_ERROR& )
668 {
669 // checking if certain symbol exists, so its absence is perfectly fine
670 }
671
672 return symbol != nullptr;
673}
674
675
676bool SYMBOL_LIBRARY_MANAGER::SymbolNameInUse( const wxString& aName, const wxString& aLibrary )
677{
678 wxArrayString existing;
679
680 // NB: GetSymbolNames() is mostly used for GUI stuff, so it returns unescaped names
681 GetSymbolNames( aLibrary, existing );
682
683 wxString unescapedName = UnescapeString( aName );
684
685 for( wxString& candidate : existing )
686 {
687 if( candidate.CmpNoCase( unescapedName ) == 0 )
688 return true;
689 }
690
691 return false;
692}
693
694
695bool SYMBOL_LIBRARY_MANAGER::LibraryExists( const wxString& aLibrary, bool aCheckEnabled ) const
696{
697 if( aLibrary.IsEmpty() )
698 return false;
699
700 if( m_libs.count( aLibrary ) > 0 )
701 return true;
702
704
705 return adapter->HasLibrary( aLibrary, aCheckEnabled );
706}
707
708
710{
711 wxString name = "New_Library";
712
713 if( !LibraryExists( name ) )
714 return name;
715
716 name += "_";
717
718 for( unsigned int i = 0; i < std::numeric_limits<unsigned int>::max(); ++i )
719 {
720 if( !LibraryExists( name + wxString::Format( "%u", i ) ) )
721 return name + wxString::Format( "%u", i );
722 }
723
724 wxFAIL;
725 return wxEmptyString;
726}
727
728
729void SYMBOL_LIBRARY_MANAGER::GetSymbolNames( const wxString& aLibraryName, wxArrayString& aSymbolNames,
730 SYMBOL_NAME_FILTER aFilter )
731{
732 LIB_BUFFER& libBuf = getLibraryBuffer( aLibraryName );
733
734 libBuf.GetSymbolNames( aSymbolNames, aFilter );
735}
736
737
738size_t SYMBOL_LIBRARY_MANAGER::GetDerivedSymbolNames( const wxString& aSymbolName, const wxString& aLibraryName,
739 wxArrayString& aList )
740{
741 LIB_BUFFER& libBuf = getLibraryBuffer( aLibraryName );
742
743 return libBuf.GetDerivedSymbolNames( aSymbolName, aList );
744}
745
746
747bool SYMBOL_LIBRARY_MANAGER::HasDerivedSymbols( const wxString& aSymbolName, const wxString& aLibraryName )
748{
749 LIB_BUFFER& libBuf = getLibraryBuffer( aLibraryName );
750
751 return libBuf.HasDerivedSymbols( aSymbolName );
752}
753
754
756{
758 return adapter->GetLibraryNames().size();
759}
760
761
762wxString SYMBOL_LIBRARY_MANAGER::getLibraryName( const wxString& aFilePath )
763{
764 wxFileName fn( aFilePath );
765 return fn.GetName();
766}
767
768
769bool SYMBOL_LIBRARY_MANAGER::addLibrary( const wxString& aFilePath, bool aCreate, LIBRARY_TABLE_SCOPE aScope )
770{
771 wxString libName = getLibraryName( aFilePath );
772 wxCHECK( !LibraryExists( libName ), false ); // either create or add an existing one
773
774 // try to use path normalized to an environmental variable or project path
775 wxString relPath = NormalizePath( aFilePath, &Pgm().GetLocalEnvVariables(), &m_frame.Prj() );
776
777 SCH_IO_MGR::SCH_FILE_T schFileType = SCH_IO_MGR::GuessPluginTypeFromLibPath( aFilePath, aCreate ? KICTL_CREATE
778 : 0 );
779
780 if( schFileType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
781 schFileType = SCH_IO_MGR::SCH_LEGACY;
782
785 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::SYMBOL, aScope );
786
787 wxCHECK( optTable, false );
788 LIBRARY_TABLE* table = optTable.value();
789
790 try
791 {
792 bool success = true;
793 LIBRARY_TABLE_ROW& row = table->InsertRow();
794
795 row.SetNickname( libName );
796 row.SetURI( relPath );
797 row.SetType( SCH_IO_MGR::ShowType( schFileType ) );
798
799 table->Save().map_error(
800 [&]( const LIBRARY_ERROR& aError )
801 {
802 wxMessageBox( _( "Error saving library table:\n\n" ) + aError.message,
803 _( "File Save Error" ), wxOK | wxICON_ERROR );
804 success = false;
805 } );
806
807 if( !success )
808 return false;
809
810 if( aCreate )
811 {
812 wxCHECK( schFileType != SCH_IO_MGR::SCH_FILE_T::SCH_LEGACY, false );
813
814 if( !adapter->CreateLibrary( libName ) )
815 {
816 table->Rows().erase( table->Rows().end() - 1 );
817
818 table->Save().map_error(
819 [&]( const LIBRARY_ERROR& aError )
820 {
821 wxMessageBox( _( "Error saving library table:\n\n" ) + aError.message,
822 _( "File Save Error" ), wxOK | wxICON_ERROR );
823 } );
824
825 return false;
826 }
827 }
828
829 adapter->LoadOne( libName );
831 }
832 catch( const IO_ERROR& ioe )
833 {
834 DisplayError( nullptr, ioe.What() );
835 return false;
836 }
837
838 return true;
839}
840
841
842std::set<LIB_SYMBOL*> SYMBOL_LIBRARY_MANAGER::getOriginalSymbols( const wxString& aLibrary )
843{
844 std::set<LIB_SYMBOL*> symbols;
845 wxCHECK( LibraryExists( aLibrary ), symbols );
846
848
849 for( LIB_SYMBOL* symbol : adapter->GetSymbols( aLibrary ) )
850 symbols.insert( symbol );
851
852 return symbols;
853}
854
855
857{
858 auto it = m_libs.find( aLibrary );
859
860 if( it != m_libs.end() )
861 return it->second;
862
863 // The requested buffer does not exist yet, so create one
864 auto ret = m_libs.emplace( aLibrary, LIB_BUFFER( aLibrary ) );
865 LIB_BUFFER& buf = ret.first->second;
866
867 for( LIB_SYMBOL* symbol : getOriginalSymbols( aLibrary ) )
868 {
869 if( symbol->IsDerived() )
870 {
871 std::shared_ptr<LIB_SYMBOL> oldParent = symbol->GetParent().lock();
872
873 wxCHECK_MSG( oldParent, buf, wxString::Format( "Derived symbol '%s' found with undefined parent.",
874 symbol->GetName() ) );
875
876 LIB_SYMBOL* libParent = buf.GetSymbol( oldParent->GetName() );
877
878 if( !libParent )
879 {
880 std::unique_ptr<LIB_SYMBOL> newParent = std::make_unique<LIB_SYMBOL>( *oldParent.get() );
881 libParent = newParent.get();
882 buf.CreateBuffer( std::move( newParent ), std::make_unique<SCH_SCREEN>() );
883 }
884
885 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( *symbol );
886 newSymbol->SetParent( libParent );
887 buf.CreateBuffer( std::move( newSymbol ), std::make_unique<SCH_SCREEN>() );
888 }
889 else if( !buf.GetSymbol( symbol->GetName() ) )
890 {
891 buf.CreateBuffer( std::make_unique<LIB_SYMBOL>( *symbol ), std::make_unique<SCH_SCREEN>() );
892 }
893 }
894
895 return buf;
896}
897
898
899bool SYMBOL_LIBRARY_MANAGER::UpdateLibraryBuffer( const wxString& aLibrary )
900{
901 try
902 {
903 m_libs.erase( aLibrary );
904 getLibraryBuffer( aLibrary );
905 }
906 catch( const std::exception& e )
907 {
908 wxLogError( _( "Error updating library buffer: %s" ), e.what() );
909 return false;
910 }
911 catch(...)
912 {
913 wxLogError( _( "Error updating library buffer." ) );
914 return false;
915 }
916
917 getLibraryBuffer( aLibrary );
918
919 return true;
920}
921
922
923std::vector<wxString> SYMBOL_LIBRARY_MANAGER::DropUnmodifiedBuffers( const std::set<wxString>& aKeep )
924{
925 std::vector<wxString> dropped;
926
927 for( auto it = m_libs.begin(); it != m_libs.end(); )
928 {
929 if( it->second.IsModified() || aKeep.contains( it->first ) )
930 {
931 ++it;
932 continue;
933 }
934
935 dropped.push_back( it->first );
936 it = m_libs.erase( it );
937 }
938
939 return dropped;
940}
941
942
943SYMBOL_BUFFER::SYMBOL_BUFFER( std::unique_ptr<LIB_SYMBOL> aSymbol, std::unique_ptr<SCH_SCREEN> aScreen ) :
944 m_screen( std::move( aScreen ) ),
945 m_symbol( std::move( aSymbol ) )
946{
947 wxASSERT( m_symbol );
948 m_original = std::make_unique<LIB_SYMBOL>( *m_symbol );
949 wxASSERT( m_original );
950}
951
952
956
957
958void SYMBOL_BUFFER::SetSymbol( std::unique_ptr<LIB_SYMBOL> aSymbol )
959{
960 wxCHECK( m_symbol != aSymbol, /* void */ );
961 wxASSERT( aSymbol );
962 m_symbol = std::move( aSymbol );
963
964 // If the symbol moves libraries then the original moves with it
965 if( m_original->GetLibId().GetLibNickname() != m_symbol->GetLibId().GetLibNickname() )
966 {
967 m_original->SetLibId( LIB_ID( m_symbol->GetLibId().GetLibNickname(),
968 m_original->GetLibId().GetLibItemName() ) );
969 }
970}
971
972
973void SYMBOL_BUFFER::SetOriginal( std::unique_ptr<LIB_SYMBOL> aSymbol )
974{
975 wxCHECK( m_original != aSymbol, /* void */ );
976 wxASSERT( aSymbol );
977 m_original = std::move( aSymbol );
978
979 // The original is not allowed to have a different library than its symbol
980 if( m_original->GetLibId().GetLibNickname() != m_symbol->GetLibId().GetLibNickname() )
981 {
982 m_original->SetLibId( LIB_ID( m_symbol->GetLibId().GetLibNickname(),
983 m_original->GetLibId().GetLibItemName() ) );
984 }
985}
986
987
989{
990 return m_screen && m_screen->IsContentModified();
991}
992
993
994LIB_SYMBOL* LIB_BUFFER::GetSymbol( const wxString& aAlias ) const
995{
996 std::shared_ptr<SYMBOL_BUFFER> buf = GetBuffer( aAlias );
997
998 if( !buf )
999 return nullptr;
1000
1001 return &buf->GetSymbol();
1002}
1003
1004
1005bool LIB_BUFFER::CreateBuffer( std::unique_ptr<LIB_SYMBOL> aCopy, std::unique_ptr<SCH_SCREEN> aScreen, bool aNew )
1006{
1007 wxASSERT( aCopy );
1008 wxASSERT( aCopy->GetLib() == nullptr );
1009
1010 // Set the parent library name,
1011 // otherwise it is empty as no library has been given as the owner during object construction
1012 LIB_ID libId = aCopy->GetLibId();
1013 libId.SetLibNickname( m_libName );
1014 aCopy->SetLibId( libId );
1015
1016 std::shared_ptr<SYMBOL_BUFFER> symbolBuf = std::make_shared<SYMBOL_BUFFER>( std::move( aCopy ),
1017 std::move( aScreen ) );
1018 m_symbols.push_back( std::move( symbolBuf ) );
1019
1020 if( aNew )
1021 m_added.push_back( m_symbols.back() );
1022
1023 ++m_hash;
1024
1025 return true;
1026}
1027
1028
1029bool LIB_BUFFER::UpdateBuffer( SYMBOL_BUFFER& aSymbolBuf, const LIB_SYMBOL& aCopy )
1030{
1031 LIB_SYMBOL& bufferedSymbol = aSymbolBuf.GetSymbol();
1032
1033 bufferedSymbol = aCopy;
1034 ++m_hash;
1035
1036 return true;
1037}
1038
1039
1041{
1042 const auto sameBufferPredicate =
1043 [&]( const std::shared_ptr<SYMBOL_BUFFER>& aBuf )
1044 {
1045 return aBuf.get() == &aSymbolBuf;
1046 };
1047
1048 wxCHECK( std::any_of( m_symbols.begin(), m_symbols.end(), sameBufferPredicate ), false );
1049
1050 bool retv = true;
1051
1052 // Remove all derived symbols to prevent broken inheritance.
1053 if( HasDerivedSymbols( aSymbolBuf.GetSymbol().GetName() )
1054 && ( removeChildSymbols( aSymbolBuf ) == 0 ) )
1055 {
1056 retv = false;
1057 }
1058
1059 // Erasing the children invalidated any earlier iterator into the deque
1060 auto symbolBufIt = std::find_if( m_symbols.begin(), m_symbols.end(), sameBufferPredicate );
1061 wxCHECK( symbolBufIt != m_symbols.end(), false );
1062
1063 m_deleted.emplace_back( *symbolBufIt );
1064 m_symbols.erase( symbolBufIt );
1065 ++m_hash;
1066
1067 return retv;
1068}
1069
1070
1072{
1073 for( std::shared_ptr<SYMBOL_BUFFER>& buffer : m_deleted )
1074 m_symbols.emplace_back( buffer );
1075
1076 m_deleted.clear();
1077 ++m_hash;
1078}
1079
1080
1082{
1083 std::erase_if( m_symbols,
1084 [&]( const std::shared_ptr<SYMBOL_BUFFER>& item )
1085 {
1086 for( const std::shared_ptr<SYMBOL_BUFFER>& added : m_added )
1087 {
1088 if( added.get() == item.get() )
1089 return true;
1090 }
1091
1092 return false;
1093 } );
1094
1095 m_added.clear();
1096 ++m_hash;
1097}
1098
1099
1101static wxString getParentName( const SYMBOL_BUFFER& aSymbolBuf )
1102{
1103 std::shared_ptr<LIB_SYMBOL> parent = aSymbolBuf.GetSymbol().GetParent().lock();
1104
1105 return parent ? parent->GetName() : wxString();
1106}
1107
1108
1109bool LIB_BUFFER::SaveModifiedBuffers( const wxString& aFileName, SCH_IO* aPlugin )
1110{
1111 // Skipped symbols rely on the plugin cache holding the file, and an empty cache would be saved over it
1112 if( wxFileName::FileExists( aFileName ) || wxFileName::DirExists( aFileName ) )
1113 {
1114 wxArrayString names;
1115
1116 try
1117 {
1118 aPlugin->EnumerateSymbolLib( names, aFileName );
1119 }
1120 catch( const IO_ERROR& ioe )
1121 {
1122 wxLogError( _( "Error loading library '%s'." ) + wxS( "\n%s" ), aFileName, ioe.What() );
1123 return false;
1124 }
1125 }
1126
1127 bool res = true;
1128
1129 for( const std::shared_ptr<SYMBOL_BUFFER>& symbolBuf : m_symbols )
1130 {
1131 wxCHECK2( symbolBuf, continue );
1132
1133 if( symbolBuf->IsModified() && !SaveBuffer( *symbolBuf, aFileName, aPlugin, true ) )
1134 res = false;
1135 }
1136
1137 return res;
1138}
1139
1140
1141bool LIB_BUFFER::SaveBuffer( SYMBOL_BUFFER& aSymbolBuf, const wxString& aFileName, SCH_IO* aPlugin,
1142 bool aBuffer )
1143{
1144 wxCHECK( !aFileName.IsEmpty(), false );
1145
1146 wxString errorMsg = _( "Error saving symbol %s to library '%s'." ) + wxS( "\n%s" );
1147
1148 // Set properties to prevent saving the file on every symbol save.
1149 std::map<std::string, UTF8> properties;
1150 properties.emplace( SCH_IO_KICAD_LEGACY::PropBuffering, "" );
1151
1152 LIB_SYMBOL& libSymbol = aSymbolBuf.GetSymbol();
1153
1154 // Collect symbols that are *directly* derived from this symbol before renaming it
1155 wxArrayString derivedSymbols;
1156
1157 for( const std::shared_ptr<SYMBOL_BUFFER>& buf : m_symbols )
1158 {
1159 if( getParentName( *buf ) == libSymbol.GetName() )
1160 derivedSymbols.push_back( buf->GetSymbol().GetName() );
1161 }
1162
1163 {
1164 LIB_SYMBOL& originalSymbol = aSymbolBuf.GetOriginal();
1165 const wxString originalName = originalSymbol.GetName();
1166
1167 // Delete the original symbol if the symbol name has been changed.
1168 if( libSymbol.GetName() != originalSymbol.GetName() )
1169 {
1170 const bool nameTaken = std::any_of( m_symbols.begin(), m_symbols.end(),
1171 [&]( const std::shared_ptr<SYMBOL_BUFFER>& aBuf )
1172 {
1173 return aBuf->GetSymbol().GetName() == originalName;
1174 } );
1175
1176 try
1177 {
1178 if( !nameTaken && aPlugin->LoadSymbol( aFileName, originalName ) )
1179 aPlugin->DeleteSymbol( aFileName, originalName, &properties );
1180 }
1181 catch( const IO_ERROR& ioe )
1182 {
1183 wxLogError( errorMsg, UnescapeString( originalName ), aFileName, ioe.What() );
1184 return false;
1185 }
1186 }
1187 }
1188
1189 if( libSymbol.IsDerived() )
1190 {
1191 std::unique_ptr<LIB_SYMBOL> newCachedSymbol = std::make_unique<LIB_SYMBOL>( libSymbol );
1192 std::shared_ptr<LIB_SYMBOL> bufferedParent = libSymbol.GetParent().lock();
1193
1194 wxCHECK( bufferedParent, false );
1195
1196 // A borrowed pointer to the cached parent symbol in the library.
1197 LIB_SYMBOL* cachedParent = nullptr;
1198
1199 try
1200 {
1201 cachedParent = aPlugin->LoadSymbol( aFileName, bufferedParent->GetName() );
1202 }
1203 catch( const IO_ERROR& )
1204 {
1205 return false;
1206 }
1207
1208 if( !cachedParent )
1209 {
1210 // The parent symbol does not exist in the library, so we need to save it first.
1211
1212 std::unique_ptr<LIB_SYMBOL> newParent = std::make_unique<LIB_SYMBOL>( *bufferedParent );
1213 newCachedSymbol->SetParent( newParent.get() );
1214
1215 const wxString cachedParentName = newParent->GetName();
1216
1217 try
1218 {
1219 aPlugin->SaveSymbol( aFileName, std::move( newParent ), aBuffer ? &properties : nullptr );
1220 }
1221 catch( const IO_ERROR& ioe )
1222 {
1223 wxLogError( errorMsg, UnescapeString( cachedParentName ), aFileName, ioe.What() );
1224 return false;
1225 }
1226
1227 const wxString newCachedSymbolName = newCachedSymbol->GetName();
1228
1229 try
1230 {
1231 aPlugin->SaveSymbol( aFileName, std::move( newCachedSymbol ), aBuffer ? &properties : nullptr );
1232 }
1233 catch( const IO_ERROR& ioe )
1234 {
1235 wxLogError( errorMsg, UnescapeString( newCachedSymbolName ), aFileName, ioe.What() );
1236 return false;
1237 }
1238
1239 std::unique_ptr<LIB_SYMBOL> originalParent = std::make_unique<LIB_SYMBOL>( *bufferedParent );
1240 LIB_SYMBOL& parentRef = *originalParent;
1241 aSymbolBuf.SetOriginal( std::move( originalParent ) );
1242
1243 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( libSymbol );
1244 newSymbol->SetParent( &parentRef );
1245 aSymbolBuf.SetOriginal( std::move( newSymbol ) );
1246 }
1247 else
1248 {
1249 // Copy embedded files from the buffered parent to the cached parent
1250 // This ensures that any embedded files added to the parent are preserved
1251 //
1252 // We do this manually rather than using the assignment operator to avoid
1253 // potential ABI issues where the size of EMBEDDED_FILES differs between
1254 // compilation units, potentially causing the assignment to overwrite
1255 // members of LIB_SYMBOL (like m_me) that follow the EMBEDDED_FILES base.
1256 cachedParent->ClearEmbeddedFiles();
1257
1258 for( const auto& [name, file] : bufferedParent->EmbeddedFileMap() )
1259 cachedParent->AddFile( new EMBEDDED_FILES::EMBEDDED_FILE( *file ) );
1260
1261 cachedParent->SetAreFontsEmbedded( bufferedParent->GetAreFontsEmbedded() );
1262 cachedParent->SetFileAddedCallback( bufferedParent->GetFileAddedCallback() );
1263
1264 newCachedSymbol->SetParent( cachedParent );
1265
1266 const wxString newCachedSymbolName = newCachedSymbol->GetName();
1267
1268 try
1269 {
1270 aPlugin->SaveSymbol( aFileName, std::move( newCachedSymbol ), aBuffer ? &properties : nullptr );
1271 }
1272 catch( const IO_ERROR& ioe )
1273 {
1274 wxLogError( errorMsg, UnescapeString( newCachedSymbolName ), aFileName, ioe.What() );
1275 return false;
1276 }
1277
1278 std::shared_ptr<SYMBOL_BUFFER> originalBufferedParent = GetBuffer( bufferedParent->GetName() );
1279 wxCHECK( originalBufferedParent, false );
1280
1281 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( libSymbol );
1282 newSymbol->SetParent( &originalBufferedParent->GetSymbol() );
1283 aSymbolBuf.SetOriginal( std::move( newSymbol ) );
1284 }
1285 }
1286 else
1287 {
1288 std::unique_ptr<LIB_SYMBOL> newSymbol = std::make_unique<LIB_SYMBOL>( libSymbol );
1289
1290 try
1291 {
1292 aPlugin->SaveSymbol( aFileName, std::move( newSymbol ), aBuffer ? &properties : nullptr );
1293 }
1294 catch( const IO_ERROR& ioe )
1295 {
1296 wxLogError( errorMsg, UnescapeString( libSymbol.GetName() ), aFileName, ioe.What() );
1297 return false;
1298 }
1299
1300 aSymbolBuf.SetOriginal( std::make_unique<LIB_SYMBOL>( libSymbol ) );
1301 }
1302
1303 bool res = true;
1304
1305 // Reparent all symbols derived from the saved symbol.
1306 if( !derivedSymbols.IsEmpty() )
1307 {
1308 // The saved copy is owned by the plugin cache. Borrow it back to reparent the
1309 // derived symbols. The lookup cannot normally fail since it was just added.
1310 LIB_SYMBOL* parentSymbol = aPlugin->LoadSymbol( aFileName, libSymbol.GetName(), aBuffer ? &properties
1311 : nullptr );
1312
1313 wxCHECK_MSG( parentSymbol, false, wxS( "Failed to borrow the saved symbol back from the plugin cache." ) );
1314
1315 // Save the derived symbols.
1316 for( const wxString& entry : derivedSymbols )
1317 {
1318 std::shared_ptr<SYMBOL_BUFFER> symbol = GetBuffer( entry );
1319
1320 wxCHECK2( symbol, continue );
1321
1322 std::unique_ptr<LIB_SYMBOL> derivedSymbol = std::make_unique<LIB_SYMBOL>( symbol->GetSymbol() );
1323
1324 derivedSymbol->SetParent( parentSymbol );
1325
1326 const wxString derivedSymbolName = derivedSymbol->GetName();
1327
1328 try
1329 {
1330 aPlugin->SaveSymbol( aFileName, std::move( derivedSymbol ), aBuffer ? &properties : nullptr );
1331 }
1332 catch( const IO_ERROR& ioe )
1333 {
1334 wxLogError( errorMsg, UnescapeString( derivedSymbolName ), aFileName, ioe.What() );
1335
1336 // Something went wrong, but try to save other derived symbols
1337 res = false;
1338 }
1339 }
1340 }
1341
1342 ++m_hash;
1343 return res;
1344}
1345
1346
1347std::shared_ptr<SYMBOL_BUFFER> LIB_BUFFER::GetBuffer( const wxString& aSymbolName ) const
1348{
1349 for( std::shared_ptr<SYMBOL_BUFFER> entry : m_symbols )
1350 {
1351 if( entry->GetSymbol().GetName() == aSymbolName )
1352 return entry;
1353 }
1354
1355 return std::shared_ptr<SYMBOL_BUFFER>( nullptr );
1356}
1357
1358
1359bool LIB_BUFFER::HasDerivedSymbols( const wxString& aParentName ) const
1360{
1361 wxCHECK( !aParentName.IsEmpty(), false );
1362
1363 for( const std::shared_ptr<SYMBOL_BUFFER>& entry : m_symbols )
1364 {
1365 if( getParentName( *entry ) == aParentName )
1366 return true;
1367 }
1368
1369 return false;
1370}
1371
1372
1373void LIB_BUFFER::GetSymbolNames( wxArrayString& aSymbolNames, SYMBOL_NAME_FILTER aFilter )
1374{
1375 for( std::shared_ptr<SYMBOL_BUFFER>& entry : m_symbols )
1376 {
1377 const LIB_SYMBOL& symbol = entry->GetSymbol();
1378
1379 if( ( symbol.IsDerived() && ( aFilter == SYMBOL_NAME_FILTER::ROOT_ONLY ) )
1380 || ( symbol.IsRoot() && ( aFilter == SYMBOL_NAME_FILTER::DERIVED_ONLY ) ) )
1381 {
1382 continue;
1383 }
1384
1385 aSymbolNames.Add( UnescapeString( symbol.GetName() ) );
1386 }
1387}
1388
1389
1390size_t LIB_BUFFER::GetDerivedSymbolNames( const wxString& aSymbolName, wxArrayString& aList ) const
1391{
1392 wxCHECK( !aSymbolName.IsEmpty(), 0 );
1393
1394 // Links resolve by parent name rather than by parent object, because a buffered child can
1395 // still point at an unbuffered copy of its parent
1396 std::unordered_map<wxString, std::vector<wxString>> derivedMap;
1397
1398 // Resolve every parent link up front so the walk below is only map lookups
1399 for( const std::shared_ptr<SYMBOL_BUFFER>& entry : m_symbols )
1400 {
1401 const wxString parentName = getParentName( *entry );
1402
1403 if( !parentName.IsEmpty() )
1404 derivedMap[parentName].emplace_back( entry->GetSymbol().GetName() );
1405 }
1406
1407 // Seeded with the query so that a name cycle in a corrupt library neither recurses forever nor
1408 // reports the root as its own descendant, which would have removeChildSymbols() delete it
1409 std::set<wxString> visited{ aSymbolName };
1410
1411 // Assign to std::function to allow recursion
1412 const std::function<void( const wxString& )> getDerived =
1413 [&]( const wxString& aParentName )
1414 {
1415 auto it = derivedMap.find( aParentName );
1416
1417 if( it != derivedMap.end() )
1418 {
1419 for( const wxString& derivedName : it->second )
1420 {
1421 if( !visited.insert( derivedName ).second )
1422 continue;
1423
1424 aList.Add( derivedName );
1425
1426 // Recurse to get symbols derived from this one
1427 getDerived( derivedName );
1428 }
1429 }
1430 };
1431
1432 // A name that is not buffered simply has no children here
1433 getDerived( aSymbolName );
1434
1435 return aList.GetCount();
1436}
1437
1438
1440{
1441 int cnt = 0;
1442 wxArrayString derivedSymbolNames;
1443 std::deque<std::shared_ptr<SYMBOL_BUFFER>>::iterator it;
1444
1445 if( GetDerivedSymbolNames( aSymbolBuf.GetSymbol().GetName(), derivedSymbolNames ) )
1446 {
1447 for( const wxString& symbolName : derivedSymbolNames )
1448 {
1449 it = std::find_if( m_symbols.begin(), m_symbols.end(),
1450 [symbolName]( std::shared_ptr<SYMBOL_BUFFER>& buf )
1451 {
1452 return buf->GetSymbol().GetName() == symbolName;
1453 } );
1454
1455 wxCHECK2( it != m_symbols.end(), continue );
1456
1457 m_deleted.emplace_back( *it );
1458 m_symbols.erase( it );
1459 cnt += 1;
1460 }
1461 }
1462
1463 return cnt;
1464}
const char * name
void SetContentModified(bool aModified=true)
Definition base_screen.h:55
void SetFileAddedCallback(FILE_ADDED_CALLBACK callback)
void ClearEmbeddedFiles(bool aDeleteFiles=true)
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
const std::map< wxString, std::shared_ptr< EMBEDDED_FILE > > & EmbeddedFileMap() const
Provide an iterable view of the file collection.
void SetAreFontsEmbedded(bool aEmbedFonts)
FILE_ADDED_CALLBACK GetFileAddedCallback() const
bool GetAreFontsEmbedded() const
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()
bool IsLibraryLoaded(const wxString &aNickname)
bool HasLibrary(const wxString &aNickname, bool aCheckEnabled=false) const
Test for the existence of aNickname in the library tables.
std::vector< wxString > GetLibraryNames() const
Returns a list of library nicknames that are available (skips any that failed to load)
bool CreateLibrary(const wxString &aNickname)
Creates the library (i.e. saves to disk) for the given row if it exists.
std::optional< LIBRARY_TABLE * > Table(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope)
Retrieves a given table; creating a new empty project table if a valid project is loaded and the give...
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::vector< LIBRARY_TABLE_ROW * > Rows(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH, bool aIncludeInvalid=false) const
Returns a flattened list of libraries of the given type.
void SetNickname(const wxString &aNickname)
void SetType(const wxString &aType)
void SetURI(const wxString &aUri)
Store a working copy of a library.
void ClearAddedAndDeletedBufferLists()
void RevertDeletedBuffers()
Move symbol buffers on the library's deleted list back to its main list.
bool CreateBuffer(std::unique_ptr< LIB_SYMBOL > aCopy, std::unique_ptr< SCH_SCREEN > aScreen, bool aNew=false)
Create a new buffer to store a symbol. LIB_BUFFER takes ownership of aCopy.
std::deque< std::shared_ptr< SYMBOL_BUFFER > > m_added
Buffer for added synbols until lib is saved.
bool DeleteBuffer(const SYMBOL_BUFFER &aSymbolBuf)
Delete the given symbol buffer from the library buffer.
bool SaveModifiedBuffers(const wxString &aFileName, SCH_IO *aPlugin)
Save the modified symbols back to the library's own file aFileName.
void GetSymbolNames(wxArrayString &aSymbolNames, SYMBOL_NAME_FILTER aFilter=SYMBOL_NAME_FILTER::ALL)
Fetch a list of root symbols names from the library buffer.
const std::deque< std::shared_ptr< SYMBOL_BUFFER > > & GetDeletedBuffers() const
Return the deleted symbol buffers that need to be removed from the library file.
size_t GetDerivedSymbolNames(const wxString &aSymbolName, wxArrayString &aList) const
Fetch all of the symbols derived from a aSymbolName into aList.
std::deque< std::shared_ptr< SYMBOL_BUFFER > > m_symbols
std::deque< std::shared_ptr< SYMBOL_BUFFER > > m_deleted
Buffer for deleted symbols until lib is saved.
bool SaveBuffer(SYMBOL_BUFFER &aSymbolBuf, const wxString &aFileName, SCH_IO *aPlugin, bool aBuffer)
Save stored modifications using a plugin.
const std::deque< std::shared_ptr< SYMBOL_BUFFER > > & GetBuffers() const
Return all buffered symbols.
std::shared_ptr< SYMBOL_BUFFER > GetBuffer(const wxString &aAlias) const
Return a symbol buffer with LIB_SYMBOL holding a symbolic alias.
LIB_SYMBOL * GetSymbol(const wxString &aAlias) const
Return the working copy of a LIB_SYMBOL root object with specified alias.
int removeChildSymbols(const SYMBOL_BUFFER &aSymbolBuf)
Remove all symbols derived from aSymbolBuf from the library buffer.
bool HasDerivedSymbols(const wxString &aParentName) const
Check to see any symbols in the buffer are derived from a parent named aParentName.
bool UpdateBuffer(SYMBOL_BUFFER &aSymbolBuf, const LIB_SYMBOL &aCopy)
Update the buffered symbol with the contents of aCopy.
const wxString m_libName
Buffered library name.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int SetLibNickname(const UTF8 &aLibNickname)
Override the logical library name portion of the LIB_ID to aLibNickname.
Definition lib_id.cpp:113
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
Define a library symbol object.
Definition lib_symbol.h:114
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:190
std::weak_ptr< LIB_SYMBOL > & GetParent()
Definition lib_symbol.h:152
bool IsRoot() const override
For symbols derived from other symbols, IsRoot() indicates no derivation.
Definition lib_symbol.h:240
bool IsDerived() const
Definition lib_symbol.h:241
wxString GetName() const override
Definition lib_symbol.h:183
void SetLibId(const LIB_ID &aLibId)
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:126
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
A shim class between EDA_DRAW_FRAME and several derived classes: SYMBOL_EDIT_FRAME,...
static const char * PropBuffering
The property used internally by the plugin to enable cache buffering which prevents the library file ...
static const wxString ShowType(SCH_FILE_T aFileType)
Return a brief name for a plugin, given aFileType enum.
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.
Base class that schematic file and library loading and saving plugins should derive from.
Definition sch_io.h:60
virtual void EnumerateSymbolLib(wxArrayString &aSymbolNameList, const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr)
Populate a list of LIB_SYMBOL alias names contained within the library aLibraryPath.
Definition sch_io.cpp:90
virtual void DeleteSymbol(const wxString &aLibraryPath, const wxString &aSymbolName, const std::map< std::string, UTF8 > *aProperties=nullptr)
Delete the entire LIB_SYMBOL associated with aAliasName from the library aLibraryPath.
Definition sch_io.cpp:132
virtual LIB_SYMBOL * LoadSymbol(const wxString &aLibraryPath, const wxString &aPartName, const std::map< std::string, UTF8 > *aProperties=nullptr)
Load a LIB_SYMBOL object having aPartName from the aLibraryPath containing a library format that this...
Definition sch_io.cpp:116
virtual void SaveSymbol(const wxString &aLibraryPath, std::unique_ptr< LIB_SYMBOL > aSymbol, const std::map< std::string, UTF8 > *aProperties=nullptr)
Write aSymbol to an existing library located at aLibraryPath.
Definition sch_io.cpp:124
std::unique_ptr< LIB_SYMBOL > m_symbol
std::unique_ptr< SCH_SCREEN > m_screen
void SetSymbol(std::unique_ptr< LIB_SYMBOL > aSymbol)
LIB_SYMBOL & GetSymbol() const
SYMBOL_BUFFER(std::unique_ptr< LIB_SYMBOL > aSymbol=nullptr, std::unique_ptr< SCH_SCREEN > aScreen=nullptr)
std::unique_ptr< LIB_SYMBOL > m_original
LIB_SYMBOL & GetOriginal() const
void SetOriginal(std::unique_ptr< LIB_SYMBOL > aSymbol)
An interface to the global shared library manager that is schematic-specific and linked to one projec...
std::optional< LIB_STATUS > LoadOne(LIB_DATA *aLib) override
Loads or reloads the given library, if it exists.
LIB_SYMBOL * LoadSymbol(const wxString &aNickname, const wxString &aName)
Load a LIB_SYMBOL having aName from the library given by aNickname.
std::vector< LIB_SYMBOL * > GetSymbols(const wxString &aNickname, SYMBOL_TYPE aType=SYMBOL_TYPE::ALL_SYMBOLS)
bool IsSymbolLibWritable(const wxString &aNickname)
Return true if the library given by aNickname is writable.
bool IsLibraryReadOnly(const wxString &aLibrary) const
Return true if the library is stored in a read-only file.
SYMBOL_BUFFER * GetBuffer(const wxString &aSymbolName, const wxString &aLibrary)
Return the working buffer holding the symbol/screen pair, or nullptr when none exists.
bool LibraryExists(const wxString &aLibrary, bool aCheckEnabled=false) const
Return true if library exists.
bool ClearLibraryModified(const wxString &aLibrary) const
Clear the modified flag for all symbols in a library.
LIB_SYMBOL * GetBufferedSymbol(const wxString &aSymbolName, const wxString &aLibrary)
Return the symbol copy from the buffer.
bool addLibrary(const wxString &aFilePath, bool aCreate, LIBRARY_TABLE_SCOPE aScope)
Helper function to add either existing or create new library.
SCH_SCREEN * GetScreen(const wxString &aSymbolName, const wxString &aLibrary)
Return the screen used to edit a specific symbol.
bool SymbolNameInUse(const wxString &aName, const wxString &aLibrary)
Return true if the symbol name is already in use in the specified library.
bool IsLibraryModified(const wxString &aLibrary) const
Return true if library has unsaved modifications.
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...
bool RemoveSymbol(const wxString &aSymbolName, const wxString &aLibrary)
Remove the symbol from the symbol buffer.
wxArrayString GetLibraryNames() const
Return the array of library names.
LIB_BUFFER & getLibraryBuffer(const wxString &aLibrary)
Return an existing library buffer or creates one to using symbol library table to get the original da...
std::vector< wxString > DropUnmodifiedBuffers(const std::set< wxString > &aKeep={})
Forget the buffers of libraries with no unsaved changes, except those in aKeep, so they are read agai...
wxString GetUniqueLibraryName() const
Return a library name that is not currently in use.
static wxString getLibraryName(const wxString &aFilePath)
Extract library name basing on the file name.
bool UpdateSymbolAfterRename(LIB_SYMBOL *aSymbol, const wxString &aOldSymbolName, const wxString &aLibrary)
Update the symbol buffer with a new version of the symbol when the name has changed.
bool IsSymbolModified(const wxString &aSymbolName, const wxString &aLibrary) const
Return true if symbol has unsaved modifications.
virtual void OnDataChanged() const
bool IsLibraryLoaded(const wxString &aLibrary) const
Return true if the library was successfully loaded.
void SetSymbolModified(const wxString &aSymbolName, const wxString &aLibrary)
bool RevertLibrary(const wxString &aLibrary)
Revert unsaved changes for a symbol library.
void GetSymbolNames(const wxString &aLibName, wxArrayString &aSymbolNames, SYMBOL_NAME_FILTER aFilter=SYMBOL_NAME_FILTER::ALL)
std::set< LIB_SYMBOL * > getOriginalSymbols(const wxString &aLibrary)
Return a set of LIB_SYMBOL objects belonging to the original library.
int GetLibraryHash(const wxString &aLibrary) const
Return a library hash value to determine if it has changed.
LIB_ID RevertSymbol(const LIB_ID &aIdToRevert)
Revert unsaved changes for a symbol and clear its modified flag.
size_t GetDerivedSymbolNames(const wxString &aSymbolName, const wxString &aLibraryName, wxArrayString &aList)
Fetch all of the symbols derived from a aSymbolName into aList.
bool RevertAll()
Revert all pending changes.
SYMBOL_LIBRARY_MANAGER(SCH_BASE_FRAME &aFrame)
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).
SCH_BASE_FRAME & m_frame
Parent frame.
std::list< LIB_SYMBOL * > EnumerateSymbols(const wxString &aLibrary) const
bool UpdateSymbol(LIB_SYMBOL *aSymbol, const wxString &aLibrary)
Update the symbol buffer with a new version of the symbol.
bool SaveLibrary(const wxString &aLibrary, const wxString &aFileName, SCH_IO_MGR::SCH_FILE_T aFileType=SCH_IO_MGR::SCH_FILE_T::SCH_LEGACY)
Save library to a file, including unsaved changes.
bool HasDerivedSymbols(const wxString &aSymbolName, const wxString &aLibraryName)
Check whether any symbol inherits from aSymbolName, without building the list of names.
std::map< wxString, LIB_BUFFER > m_libs
The library buffers.
bool UpdateLibraryBuffer(const wxString &aLibrary)
Update the library buffer with a new version of the library.
wxString wx_str() const
Definition utf8.cpp:41
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)
wxString NormalizePath(const wxFileName &aFilePath, const ENV_VAR_MAP *aEnvVars, const wxString &aProjectPath)
Normalize a file path to an environmental variable, if possible.
Definition env_paths.cpp:73
Helper functions to substitute paths with environmental variables.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
static const std::string KiCadSymbolLibFileExtension
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
#define KICTL_CREATE
caller thinks requested project files may not exist.
LIBRARY_TABLE_SCOPE
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
STL namespace.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
int StrNumCmp(const wxString &aString1, const wxString &aString2, CMP_T aCaseSensitivity)
Compare two strings with alphanumerical content.
wxString UnescapeString(const wxString &aSource)
@ IGNORE_CASE
wxString message
static wxString getParentName(const SYMBOL_BUFFER &aSymbolBuf)
Name of the parent a buffered symbol inherits from, or empty if it is a root symbol.
const std::string table
nanodbc::result res
Definition of file extensions used in Kicad.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:35