KiCad PCB EDA Suite
Loading...
Searching...
No Matches
legacy_symbol_library.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) 2004-2016 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 2022 CERN
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23#include <algorithm>
24#include <kiface_base.h>
25#include <eda_base_frame.h>
26#include <string_utils.h>
27#include <macros.h>
28#include <richio.h>
31#include <project_rescue.h>
32#include <project_sch.h>
34
37
38#include <wx/log.h>
39#include <wx/progdlg.h>
40#include <wx/tokenzr.h>
41#include <sim/sim_model.h>
42
43LEGACY_SYMBOL_LIB::LEGACY_SYMBOL_LIB( SCH_LIB_TYPE aType, const wxString& aFileName,
44 SCH_IO_MGR::SCH_FILE_T aPluginType ) :
45 m_pluginType( aPluginType )
46{
47 type = aType;
48 isModified = false;
49 timeStamp = 0;
50 timeStamp = wxDateTime::Now();
51 versionMajor = 0; // Will be updated after reading the lib file
52 versionMinor = 0; // Will be updated after reading the lib file
53
54 fileName = aFileName;
55
56 if( !fileName.IsOk() )
57 fileName = "unnamed.lib";
58
59 m_plugin.reset( SCH_IO_MGR::FindPlugin( m_pluginType ) );
60 m_properties = std::make_unique<std::map<std::string, UTF8>>();
61 m_mod_hash = 0;
62}
63
64
68
69
70void LEGACY_SYMBOL_LIB::Save( bool aSaveDocFile )
71{
72 wxCHECK_RET( m_plugin != nullptr,
73 wxString::Format( wxT( "no plugin defined for library `%s`." ),
74 fileName.GetFullPath() ) );
75
76 std::map<std::string, UTF8> props;
77
78 if( !aSaveDocFile )
80
81 m_plugin->SaveLibrary( fileName.GetFullPath(), &props );
82 isModified = false;
83}
84
85
86void LEGACY_SYMBOL_LIB::Create( const wxString& aFileName )
87{
88 wxString tmpFileName = fileName.GetFullPath();
89
90 if( !aFileName.IsEmpty() )
91 tmpFileName = aFileName;
92
93 m_plugin->CreateLibrary( tmpFileName, m_properties.get() );
94}
95
96
97void LEGACY_SYMBOL_LIB::SetPluginType( SCH_IO_MGR::SCH_FILE_T aPluginType )
98{
99 if( m_pluginType != aPluginType )
100 {
101 m_pluginType = aPluginType;
102 m_plugin.reset( SCH_IO_MGR::FindPlugin( m_pluginType ) );
103 }
104}
105
106
108{
110}
111
112
114{
115 (*m_properties)[ SCH_IO_KICAD_LEGACY::PropNoDocFile ] = "";
116}
117
118
123
124
126{
127 if( aEnable )
128 (*m_properties)[ SCH_IO_KICAD_LEGACY::PropBuffering ] = "";
129 else
131}
132
133
134void LEGACY_SYMBOL_LIB::GetSymbolNames( wxArrayString& aNames ) const
135{
136 m_plugin->EnumerateSymbolLib( aNames, fileName.GetFullPath(), m_properties.get() );
137
138 aNames.Sort();
139}
140
141
142void LEGACY_SYMBOL_LIB::GetSymbols( std::vector<LIB_SYMBOL*>& aSymbols ) const
143{
144 m_plugin->EnumerateSymbolLib( aSymbols, fileName.GetFullPath(), m_properties.get() );
145
146 std::sort( aSymbols.begin(), aSymbols.end(),
147 [](LIB_SYMBOL *lhs, LIB_SYMBOL *rhs) -> bool
148 {
149 return lhs->GetName() < rhs->GetName();
150 } );
151}
152
153
154LIB_SYMBOL* LEGACY_SYMBOL_LIB::FindSymbol( const wxString& aName ) const
155{
156 LIB_SYMBOL* symbol = m_plugin->LoadSymbol( fileName.GetFullPath(), aName, m_properties.get() );
157
158 if( symbol )
159 {
160 // Set the library to this even though technically the legacy cache plugin owns the
161 // symbols. This allows the symbol library table conversion tool to determine the
162 // correct library where the symbol was found.
163 if( !symbol->GetLib() )
164 symbol->SetLib( const_cast<LEGACY_SYMBOL_LIB*>( this ) );
165
166 SIM_MODEL::MigrateSimModel<LIB_SYMBOL>( *symbol, nullptr );
167 }
168
169 return symbol;
170}
171
172
174{
175 return FindSymbol( aLibId.Format().wx_str() );
176}
177
178
180{
181 // add a clone, not the caller's copy, the plugin take ownership of the new symbol.
182 std::unique_ptr<LIB_SYMBOL> clonedSymbol = std::make_unique<LIB_SYMBOL>( *aSymbol->SharedPtr().get(), this );
183 m_plugin->SaveSymbol( fileName.GetFullPath(),
184 std::move( clonedSymbol ),
185 m_properties.get() );
186
187 // If we are not buffering, the library file is updated immediately when the plugin
188 // SaveSymbol() function is called.
189 if( IsBuffering() )
190 isModified = true;
191
192 ++m_mod_hash;
193}
194
195
197{
198 wxCHECK_MSG( aEntry != nullptr, nullptr, "NULL pointer cannot be removed from library." );
199
200 m_plugin->DeleteSymbol( fileName.GetFullPath(), aEntry->GetName(), m_properties.get() );
201
202 // If we are not buffering, the library file is updated immediately when the plugin
203 // SaveSymbol() function is called.
204 if( IsBuffering() )
205 isModified = true;
206
207 ++m_mod_hash;
208 return nullptr;
209}
210
211
213{
214 std::unique_ptr<LEGACY_SYMBOL_LIB> lib = std::make_unique<LEGACY_SYMBOL_LIB>( SCH_LIB_TYPE::LT_EESCHEMA,
215 aFileName );
216
217 std::vector<LIB_SYMBOL*> parts;
218 // This loads the library.
219 lib->GetSymbols( parts );
220
221 // Now, set the LIB_SYMBOL m_library member but it will only be used
222 // when loading legacy libraries in the future. Once the symbols in the
223 // schematic have a full #LIB_ID, this will not get called.
224 for( size_t ii = 0; ii < parts.size(); ii++ )
225 {
226 LIB_SYMBOL* part = parts[ii];
227
228 part->SetLib( lib.get() );
229 }
230
231 LEGACY_SYMBOL_LIB* ret = lib.release();
232 return ret;
233}
234
235
237{
239
240 wxFileName fn = aFileName;
241 // Don't reload the library if it is already loaded.
242 lib = FindLibrary( fn.GetName() );
243
244 if( lib )
245 return lib;
246
247 try
248 {
249 lib = LEGACY_SYMBOL_LIB::LoadSymbolLibrary( aFileName );
250 push_back( lib );
251
252 return lib;
253 }
254 catch( ... )
255 {
256 return nullptr;
257 }
258}
259
260
261LEGACY_SYMBOL_LIB* LEGACY_SYMBOL_LIBS::AddLibrary( const wxString& aFileName, LEGACY_SYMBOL_LIBS::iterator& aIterator )
262{
263 // Don't reload the library if it is already loaded.
264 wxFileName fn( aFileName );
265 LEGACY_SYMBOL_LIB* lib = FindLibrary( fn.GetName() );
266
267 if( lib )
268 return lib;
269
270 try
271 {
272 lib = LEGACY_SYMBOL_LIB::LoadSymbolLibrary( aFileName );
273
274 if( aIterator >= begin() && aIterator < end() )
275 insert( aIterator, lib );
276 else
277 push_back( lib );
278
279 return lib;
280 }
281 catch( ... )
282 {
283 return nullptr;
284 }
285}
286
287
288bool LEGACY_SYMBOL_LIBS::ReloadLibrary( const wxString &aFileName )
289{
290 wxFileName fn = aFileName;
291 LEGACY_SYMBOL_LIB* lib = FindLibrary( fn.GetName() );
292
293 // Check if the library already exists.
294 if( !lib )
295 return false;
296
297 // Create a clone of the library pointer in case we need to re-add it
298 LEGACY_SYMBOL_LIB *cloneLib = lib;
299
300 // Try to find the iterator of the library
301 for( auto it = begin(); it != end(); ++it )
302 {
303 if( it->GetName() == fn.GetName() )
304 {
305 // Remove the old library and keep the pointer
306 lib = &*it;
307 release( it );
308 break;
309 }
310 }
311
312 // Try to reload the library
313 try
314 {
315 lib = LEGACY_SYMBOL_LIB::LoadSymbolLibrary( aFileName );
316
317 // If the library is successfully reloaded, add it back to the set.
318 push_back( lib );
319 return true;
320 }
321 catch( ... )
322 {
323 // If an exception occurs, ensure that the SYMBOL_LIBS remains unchanged
324 // by re-adding the old library back to the set.
325 push_back( cloneLib );
326 return false;
327 }
328}
329
330
332{
333 for( LEGACY_SYMBOL_LIBS::iterator it = begin(); it!=end(); ++it )
334 {
335 if( it->GetName() == aName )
336 return &*it;
337 }
338
339 return nullptr;
340}
341
342
344{
345 for( LEGACY_SYMBOL_LIBS::iterator it = begin(); it!=end(); ++it )
346 {
347 if( it->IsCache() )
348 return &*it;
349 }
350
351 return nullptr;
352}
353
354
356{
357 for( LEGACY_SYMBOL_LIBS::iterator it = begin(); it!=end(); ++it )
358 {
359 if( it->GetFullFileName() == aFullFileName )
360 return &*it;
361 }
362
363 return nullptr;
364}
365
366
367wxArrayString LEGACY_SYMBOL_LIBS::GetLibraryNames( bool aSorted )
368{
369 wxArrayString cacheNames;
370 wxArrayString names;
371
372 for( LEGACY_SYMBOL_LIB& lib : *this )
373 {
374 if( lib.IsCache() && aSorted )
375 cacheNames.Add( lib.GetName() );
376 else
377 names.Add( lib.GetName() );
378 }
379
380 // Even sorted, the cache library is always at the end of the list.
381 if( aSorted )
382 names.Sort();
383
384 for( unsigned int i = 0; i<cacheNames.Count(); i++ )
385 names.Add( cacheNames.Item( i ) );
386
387 return names;
388}
389
390
391LIB_SYMBOL* LEGACY_SYMBOL_LIBS::FindLibSymbol( const LIB_ID& aLibId, const wxString& aLibraryName )
392{
393 LIB_SYMBOL* part = nullptr;
394
395 for( LEGACY_SYMBOL_LIB& lib : *this )
396 {
397 if( !aLibraryName.IsEmpty() && lib.GetName() != aLibraryName )
398 continue;
399
400 part = lib.FindSymbol( aLibId.GetLibItemName().wx_str() );
401
402 if( part )
403 break;
404 }
405
406 return part;
407}
408
409
410void LEGACY_SYMBOL_LIBS::FindLibraryNearEntries( std::vector<LIB_SYMBOL*>& aCandidates,
411 const wxString& aEntryName,
412 const wxString& aLibraryName )
413{
414 for( LEGACY_SYMBOL_LIB& lib : *this )
415 {
416 if( !aLibraryName.IsEmpty() && lib.GetName() != aLibraryName )
417 continue;
418
419 wxArrayString partNames;
420
421 lib.GetSymbolNames( partNames );
422
423 if( partNames.IsEmpty() )
424 continue;
425
426 for( size_t i = 0; i < partNames.size(); i++ )
427 {
428 if( partNames[i].CmpNoCase( aEntryName ) == 0 )
429 aCandidates.push_back( lib.FindSymbol( partNames[i] ) );
430 }
431 }
432}
433
434
435void LEGACY_SYMBOL_LIBS::GetLibNamesAndPaths( PROJECT* aProject, wxString* aPaths, wxArrayString* aNames )
436{
437 wxCHECK_RET( aProject, "Null PROJECT in GetLibNamesAndPaths" );
438
439 PROJECT_FILE& project = aProject->GetProjectFile();
440
441 if( aPaths )
442 *aPaths = project.m_LegacyLibDir;
443
444 if( aNames )
445 *aNames = project.m_LegacyLibNames;
446}
447
448
449void LEGACY_SYMBOL_LIBS::SetLibNamesAndPaths( PROJECT* aProject, const wxString& aPaths,
450 const wxArrayString& aNames )
451{
452 wxCHECK_RET( aProject, "Null PROJECT in SetLibNamesAndPaths" );
453
454 PROJECT_FILE& project = aProject->GetProjectFile();
455
456 project.m_LegacyLibDir = aPaths;
457 project.m_LegacyLibNames = aNames;
458}
459
460
461const wxString LEGACY_SYMBOL_LIBS::CacheName( const wxString& aFullProjectFilename )
462{
463 wxFileName filename( aFullProjectFilename );
464 wxString name = filename.GetName();
465
466 filename.SetName( name + "-cache" );
467 filename.SetExt( FILEEXT::LegacySymbolLibFileExtension );
468
469 if( filename.FileExists() )
470 return filename.GetFullPath();
471
472 // Try the old (2007) cache name
473 filename.SetName( name + ".cache" );
474
475 if( filename.FileExists() )
476 return filename.GetFullPath();
477
478 return wxEmptyString;
479}
480
481
482void LEGACY_SYMBOL_LIBS::LoadAllLibraries( PROJECT* aProject, bool aShowProgress )
483{
484 wxString filename;
485 wxString libs_not_found;
486 SEARCH_STACK* lib_search = PROJECT_SCH::SchSearchS( aProject );
487
488#if defined(DEBUG) && 0
489 lib_search->Show( __func__ );
490#endif
491
492 wxArrayString lib_names;
493
494 GetLibNamesAndPaths( aProject, nullptr, &lib_names );
495
496 // Post symbol library table, this should be empty. Only the cache library should get loaded.
497 if( !lib_names.empty() )
498 {
499 APP_PROGRESS_DIALOG lib_dialog( _( "Loading Symbol Libraries" ),
500 wxEmptyString,
501 lib_names.GetCount(),
502 nullptr,
503 false,
504 wxPD_APP_MODAL );
505
506 if( aShowProgress )
507 {
508 lib_dialog.Show();
509 }
510
511 for( unsigned i = 0; i < lib_names.GetCount(); ++i )
512 {
513 if( aShowProgress )
514 {
515 lib_dialog.Update( i, wxString::Format( _( "Loading %s..." ), lib_names[i] ) );
516 }
517
518 // lib_names[] does not store the file extension. Set it.
519 // Remember lib_names[i] can contain a '.' in name, so using a wxFileName
520 // before adding the extension can create incorrect full filename
521 wxString fullname = lib_names[i] + "." + FILEEXT::LegacySymbolLibFileExtension;
522
523 // Now the full name is set, we can use a wxFileName.
524 wxFileName fn( fullname );
525
526 // Skip if the file name is not valid..
527 if( !fn.IsOk() )
528 continue;
529
530 if( !fn.FileExists() )
531 {
532 filename = lib_search->FindValidPath( fn.GetFullPath() );
533
534 if( !filename )
535 {
536 libs_not_found += fn.GetFullPath();
537 libs_not_found += '\n';
538 continue;
539 }
540 }
541 else
542 { // ensure the lib filename has a absolute path.
543 // If the lib has no absolute path, and is found in the cwd by fn.FileExists(),
544 // make a full absolute path, to avoid issues with load library functions which
545 // expects an absolute path.
546 if( !fn.IsAbsolute() )
547 fn.MakeAbsolute();
548
549 filename = fn.GetFullPath();
550 }
551
552 try
553 {
554 AddLibrary( filename );
555 }
556 catch( const IO_ERROR& ioe )
557 {
558 wxString msg;
559 msg.Printf( _( "Symbol library '%s' failed to load." ), filename );
560
561 wxLogError( msg + wxS( "\n" ) + ioe.What() );
562 }
563 }
564 }
565
566 // add the special cache library.
567 wxString cache_name = CacheName( aProject->GetProjectFullName() );
568 LEGACY_SYMBOL_LIB* cache_lib;
569
570 if( !aProject->IsNullProject() && !cache_name.IsEmpty() )
571 {
572 try
573 {
574 cache_lib = AddLibrary( cache_name );
575
576 if( cache_lib )
577 cache_lib->SetCache();
578 }
579 catch( const IO_ERROR& ioe )
580 {
581 THROW_IO_ERRORF( _( "Error loading symbol library '%s'." ) + wxS( "\n%s" ),
582 cache_name, ioe.What() );
583 }
584 }
585
586 // Print the libraries not found
587 if( !libs_not_found.IsEmpty() )
588 {
589 // Use a different exception type so catch()er can route to proper use
590 // of the HTML_MESSAGE_BOX.
591 THROW_PARSE_ERROR( wxEmptyString, __func__, TO_UTF8( libs_not_found ), 0, 0 );
592 }
593}
const char * name
wxProgressDialog with the option to also update the application progress on the taskbar
virtual bool Update(int aValue, const wxString &aNewMsg=wxEmptyString, bool *aSkip=nullptr) override
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()
LEGACY_SYMBOL_LIB * GetCacheLibrary()
wxArrayString GetLibraryNames(bool aSorted=true)
Return the list of symbol library file names without path and extension.
void FindLibraryNearEntries(std::vector< LIB_SYMBOL * > &aCandidates, const wxString &aEntryName, const wxString &aLibraryName=wxEmptyString)
Search all libraries in the list for a LIB_SYMBOL using a case insensitive comparison.
LEGACY_SYMBOL_LIB * FindLibraryByFullFileName(const wxString &aFullFileName)
static void GetLibNamesAndPaths(PROJECT *aProject, wxString *aPaths, wxArrayString *aNames=nullptr)
void LoadAllLibraries(PROJECT *aProject, bool aShowProgress=true)
Load all of the project's libraries into this container, which should be cleared before calling it.
static void SetLibNamesAndPaths(PROJECT *aProject, const wxString &aPaths, const wxArrayString &aNames)
LEGACY_SYMBOL_LIB * FindLibrary(const wxString &aName)
Find a symbol library by aName.
LIB_SYMBOL * FindLibSymbol(const LIB_ID &aLibId, const wxString &aLibraryName=wxEmptyString)
Search all libraries in the list for a symbol.
LEGACY_SYMBOL_LIB * AddLibrary(const wxString &aFileName)
Allocate and adds a symbol library to the library list.
bool ReloadLibrary(const wxString &aFileName)
Refreshes the library from the (possibly updated) contents on disk.
static const wxString CacheName(const wxString &aFullProjectFilename)
Return the name of the cache library after potentially fixing it from an older naming scheme.
Object used to load, save, search, and otherwise manipulate symbol library files.
static LEGACY_SYMBOL_LIB * LoadSymbolLibrary(const wxString &aFileName)
Allocate and load a symbol library file.
wxFileName fileName
Library file name.
int versionMajor
Library major version number.
std::unique_ptr< std::map< std::string, UTF8 > > m_properties
Library properties.
void EnableBuffering(bool aEnable=true)
wxDateTime timeStamp
Library save time and date.
std::unique_ptr< SCH_IO > m_plugin
SCH_IO_MGR::SCH_FILE_T m_pluginType
LIB_SYMBOL * FindSymbol(const wxString &aName) const
Find LIB_SYMBOL by aName.
LIB_SYMBOL * RemoveSymbol(LIB_SYMBOL *aEntry)
Safely remove aEntry from the library and return the next entry.
void Create(const wxString &aFileName=wxEmptyString)
int m_mod_hash
incremented each time library is changed.
LEGACY_SYMBOL_LIB(SCH_LIB_TYPE aType, const wxString &aFileName, SCH_IO_MGR::SCH_FILE_T aPluginType=SCH_IO_MGR::SCH_LEGACY)
void GetSymbolNames(wxArrayString &aNames) const
Load a string array with the names of all the entries in this library.
void AddSymbol(LIB_SYMBOL *aSymbol)
Add aSymbol entry to library.
const wxString GetName() const
Return the file name without path or extension.
void Save(bool aSaveDocFile=true)
bool isModified
Library modification status.
void GetSymbols(std::vector< LIB_SYMBOL * > &aSymbols) const
Load a vector with all the entries in this library.
int versionMinor
Library minor version number.
void SetPluginType(SCH_IO_MGR::SCH_FILE_T aPluginType)
SCH_LIB_TYPE type
Library type indicator.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
UTF8 Format() const
Definition lib_id.cpp:132
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
Define a library symbol object.
Definition lib_symbol.h:119
void SetLib(LEGACY_SYMBOL_LIB *aLibrary)
LEGACY_SYMBOL_LIB * GetLib() const
Definition lib_symbol.h:240
wxString GetName() const override
Definition lib_symbol.h:181
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:128
The backing store for a PROJECT, in JSON format.
static SEARCH_STACK * SchSearchS(PROJECT *aProject)
Accessor for Eeschema search stack.
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:177
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition project.cpp:201
static const char * PropBuffering
The property used internally by the plugin to enable cache buffering which prevents the library file ...
static const char * PropNoDocFile
The property used internally by the plugin to disable writing the library documentation (....
Look for files in a number of paths.
static void MigrateSimModel(T &aSymbol, const PROJECT *aProject)
wxString wx_str() const
Definition utf8.cpp:41
#define _(s)
Base window classes and related definitions.
static const std::string LegacySymbolLibFileExtension
#define THROW_IO_ERRORF(msg,...)
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
This file contains miscellaneous commonly used macros and functions.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
VECTOR2I end
Definition of file extensions used in Kicad.