KiCad PCB EDA Suite
Loading...
Searching...
No Matches
lib_table_base.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) 2010-2012 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
5 * Copyright (C) 2012 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 2012-2022 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, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26
27#include <wx/debug.h>
28#include <wx/filename.h>
29#include <set>
30#include <common.h>
31#include <kiface_base.h>
32#include <lib_table_base.h>
33#include <lib_table_lexer.h>
34#include <macros.h>
35#include <string_utils.h>
36
37#define OPT_SEP '|'
38
39
40using namespace LIB_TABLE_T;
41
42
43std::unique_ptr<LINE_READER> FILE_LIB_TABLE_IO::GetReader( const wxString& aURI ) const
44{
45 const wxFileName fn( aURI );
46
47 if( !fn.IsOk() || !fn.IsFileReadable() )
48 return nullptr;
49
50 return std::make_unique<FILE_LINE_READER>( aURI );
51}
52
53bool FILE_LIB_TABLE_IO::CanSaveToUri( const wxString& aURI ) const
54{
55 const wxFileName fn( aURI );
56
57 if( !fn.IsOk() )
58 return false;
59
60 return fn.IsFileWritable();
61}
62
63bool FILE_LIB_TABLE_IO::UrisAreEquivalent( const wxString& aURI1, const wxString& aURI2 ) const
64{
65 // Avoid comparing filenames as wxURIs
66 if( aURI1.Find( "://" ) != wxNOT_FOUND )
67 {
68 // found as full path
69 return aURI1 == aURI2;
70 }
71 else
72 {
73 const wxFileName fn1( aURI1 );
74 const wxFileName fn2( aURI2 );
75
76 // This will also test if the file is a symlink so if we are comparing
77 // a symlink to the same real file, the comparison will be true. See
78 // wxFileName::SameAs() in the wxWidgets source.
79
80 // found as full path and file name
81 return fn1 == fn2;
82 }
83}
84
85std::unique_ptr<OUTPUTFORMATTER> FILE_LIB_TABLE_IO::GetWriter( const wxString& aURI ) const
86{
87 const wxFileName fn( aURI );
88 return std::make_unique<FILE_OUTPUTFORMATTER>( aURI );
89}
90
91
93{
94 return aRow.clone();
95}
96
97
98void LIB_TABLE_ROW::setProperties( std::map<std::string, UTF8>* aProperties )
99{
100 properties.reset( aProperties );
101}
102
103
104void LIB_TABLE_ROW::SetFullURI( const wxString& aFullURI )
105{
106 uri_user = aFullURI;
107}
108
109
110const wxString LIB_TABLE_ROW::GetFullURI( bool aSubstituted ) const
111{
112 if( aSubstituted )
113 {
114 return ExpandEnvVarSubstitutions( uri_user, nullptr );
115 }
116
117 return uri_user;
118}
119
120
121void LIB_TABLE_ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const
122{
123 // In Kicad, we save path and file names using the Unix notation (separator = '/')
124 // So ensure separator is always '/' is saved URI string
125 wxString uri = GetFullURI();
126 uri.Replace( '\\', '/' );
127
128 wxString extraOptions;
129
130 if( !GetIsEnabled() )
131 extraOptions += "(disabled)";
132
133 if( !GetIsVisible() )
134 extraOptions += "(hidden)";
135
136 out->Print( nestLevel, "(lib (name %s)(type %s)(uri %s)(options %s)(descr %s)%s)\n",
137 out->Quotew( GetNickName() ).c_str(),
138 out->Quotew( GetType() ).c_str(),
139 out->Quotew( uri ).c_str(),
140 out->Quotew( GetOptions() ).c_str(),
141 out->Quotew( GetDescr() ).c_str(),
142 extraOptions.ToStdString().c_str() );
143}
144
145
147{
148 return nickName == r.nickName
149 && uri_user == r.uri_user
150 && options == r.options
152 && enabled == r.enabled
153 && visible == r.visible;
154}
155
156
157void LIB_TABLE_ROW::SetOptions( const wxString& aOptions )
158{
159 options = aOptions;
160
161 // set PROPERTIES* from options
163}
164
165
166LIB_TABLE::LIB_TABLE( LIB_TABLE* aFallBackTable, std::unique_ptr<LIB_TABLE_IO> aTableIo ) :
167 m_io( std::move( aTableIo ) ), m_fallBack( aFallBackTable ), m_version( 0 )
168{
169 // If not given, use the default file-based I/O.
170 if( !m_io )
171 {
172 m_io = std::make_unique<FILE_LIB_TABLE_IO>();
173 }
174
175 // not copying fall back, simply search aFallBackTable separately
176 // if "nickName not found".
177}
178
179
181{
182 // *fallBack is not owned here.
183}
184
185
187{
188 m_rows.clear();
189 m_rowsMap.clear();
190}
191
192
193bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
194{
195 if( !aIncludeFallback || !m_fallBack )
196 return m_rows.empty();
197
198 return m_rows.empty() && m_fallBack->IsEmpty( true );
199}
200
201
202const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
203{
204 // Use "no exception" form of find row and ignore disabled flag.
205 const LIB_TABLE_ROW* row = findRow( aNickname );
206
207 if( row )
208 return row->GetDescr();
209 else
210 return wxEmptyString;
211}
212
213
214bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
215{
216 const LIB_TABLE_ROW* row = findRow( aNickname, aCheckEnabled );
217
218 if( row == nullptr )
219 return false;
220
221 return true;
222}
223
224
225bool LIB_TABLE::HasLibraryWithPath( const wxString& aPath ) const
226{
227 for( const LIB_TABLE_ROW& row : m_rows )
228 {
229 if( row.GetFullURI() == aPath )
230 return true;
231 }
232
233 return false;
234}
235
236
237wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
238{
239 const LIB_TABLE_ROW* row = findRow( aNickname, true );
240
241 wxString retv;
242
243 if( row )
244 retv = row->GetFullURI( aExpandEnvVars );
245
246 return retv;
247}
248
249
250LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName, bool aCheckIfEnabled ) const
251{
252 LIB_TABLE_ROW* row = nullptr;
253 LIB_TABLE* cur = (LIB_TABLE*) this;
254
255 do
256 {
257 std::shared_lock<std::shared_mutex> lock( cur->m_mutex );
258
259 if( cur->m_rowsMap.count( aNickName ) )
260 row = &*cur->m_rowsMap.at( aNickName );
261
262 if( row )
263 {
264 if( !aCheckIfEnabled || row->GetIsEnabled() )
265 return row;
266 else
267 return nullptr; // We found it, but it's disabled
268 }
269
270 // Repeat, this time looking for names that were "fixed" by legacy versions because
271 // the old eeschema file format didn't support spaces in tokens.
272 for( const std::pair<const wxString, LIB_TABLE_ROWS_ITER>& entry : cur->m_rowsMap )
273 {
274 wxString legacyLibName = entry.first;
275 legacyLibName.Replace( " ", "_" );
276
277 if( legacyLibName == aNickName )
278 {
279 row = &*entry.second;
280
281 if( !aCheckIfEnabled || row->GetIsEnabled() )
282 return row;
283 }
284 }
285
286 // not found, search fall back table(s), if any
287 } while( ( cur = cur->m_fallBack ) != nullptr );
288
289 return nullptr; // not found
290}
291
292
293const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
294{
295 LIB_TABLE* cur = this;
296
297 do
298 {
299 for( unsigned i = 0; i < cur->m_rows.size(); i++ )
300 {
301 const wxString tmp = cur->m_rows[i].GetFullURI( true );
302
303 if( m_io->UrisAreEquivalent( tmp, aURI ) )
304 return &cur->m_rows[i];
305 }
306
307 // not found, search fall back table(s), if any
308 } while( ( cur = cur->m_fallBack ) != nullptr );
309
310 return nullptr; // not found
311}
312
313
314std::vector<wxString> LIB_TABLE::GetLogicalLibs()
315{
316 // Only return unique logical library names. Use std::set::insert() to quietly reject any
317 // duplicates (usually due to encountering a duplicate nickname in a fallback table).
318
319 std::set<wxString> unique;
320 std::vector<wxString> ret;
321 const LIB_TABLE* cur = this;
322
323 do
324 {
325 for( const LIB_TABLE_ROW& row : cur->m_rows )
326 {
327 if( row.GetIsEnabled() )
328 unique.insert( row.GetNickName() );
329 }
330
331 } while( ( cur = cur->m_fallBack ) != nullptr );
332
333 ret.reserve( unique.size() );
334
335 // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
336 for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
337 ret.push_back( *it );
338
339 // We want to allow case-sensitive duplicates but sort by case-insensitive ordering
340 std::sort( ret.begin(), ret.end(),
341 []( const wxString& lhs, const wxString& rhs )
342 {
343 return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
344 } );
345
346 return ret;
347}
348
349
350bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
351{
352 std::lock_guard<std::shared_mutex> lock( m_mutex );
353
354 doInsertRow( aRow, doReplace );
355 reindex();
356
357 return true;
358}
359
360
361bool LIB_TABLE::doInsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
362{
363 auto it = m_rowsMap.find( aRow->GetNickName() );
364
365 if( it != m_rowsMap.end() )
366 {
367 if( !doReplace )
368 return false;
369
370 m_rows.replace( it->second, aRow );
371 }
372 else
373 {
374 m_rows.push_back( aRow );
375 }
376
377 aRow->SetParent( this );
378 reindex();
379 return true;
380}
381
382
384{
385 std::lock_guard<std::shared_mutex> lock( m_mutex );
386
387 bool found = false;
388 auto it = m_rowsMap.find( aRow->GetNickName() );
389
390 if( it != m_rowsMap.end() )
391 {
392 if( &*it->second == aRow )
393 {
394 found = true;
395 m_rows.erase( it->second );
396 }
397 }
398
399 if( !found )
400 {
401 // Bookkeeping got messed up...
402 for( int i = (int)m_rows.size() - 1; i >= 0; --i )
403 {
404 if( &m_rows[i] == aRow )
405 {
406 m_rows.erase( m_rows.begin() + i );
407 found = true;
408 break;
409 }
410 }
411 }
412
413 if( found )
414 reindex();
415
416 return found;
417}
418
419
420bool LIB_TABLE::ReplaceRow( size_t aIndex, LIB_TABLE_ROW* aRow )
421{
422 std::lock_guard<std::shared_mutex> lock( m_mutex );
423
424 if( aIndex >= m_rows.size() )
425 return false;
426
427 m_rowsMap.erase( m_rows[aIndex].GetNickName() );
428
429 m_rows.replace( aIndex, aRow );
430 reindex();
431 return true;
432}
433
434
435bool LIB_TABLE::ChangeRowOrder( size_t aIndex, int aOffset )
436{
437 std::lock_guard<std::shared_mutex> lock( m_mutex );
438
439 if( aIndex >= m_rows.size() )
440 return false;
441
442 int newPos = static_cast<int>( aIndex ) + aOffset;
443
444 if( newPos < 0 || newPos > static_cast<int>( m_rows.size() ) - 1 )
445 return false;
446
447 auto element = m_rows.release( m_rows.begin() + aIndex );
448
449 m_rows.insert( m_rows.begin() + newPos, element.release() );
450 reindex();
451
452 return true;
453}
454
455
457{
458 std::lock_guard<std::shared_mutex> lock( m_mutex );
459
460 clear();
461 m_rows.transfer( m_rows.end(), aRowsList.begin(), aRowsList.end(), aRowsList );
462
463 reindex();
464}
465
466
468{
469 m_rowsMap.clear();
470
471 for( LIB_TABLE_ROWS_ITER it = m_rows.begin(); it != m_rows.end(); ++it )
472 {
473 it->SetParent( this );
474 m_rowsMap[it->GetNickName()] = it;
475 }
476}
477
478
480{
481 bool table_updated = false;
482
483 for( LIB_TABLE_ROW& row : m_rows )
484 {
485 bool row_updated = false;
486 wxString uri = row.GetFullURI( true );
487
488 // If the uri still has a variable in it, that means that the user does not have
489 // these vars defined. We update the old vars to the KICAD7 versions on load
490 row_updated |= ( uri.Replace( wxS( "${KICAD5_" ), wxS( "${KICAD7_" ), false ) > 0 );
491 row_updated |= ( uri.Replace( wxS( "${KICAD6_" ), wxS( "${KICAD7_" ), false ) > 0 );
492
493 if( row_updated )
494 {
495 row.SetFullURI( uri );
496 table_updated = true;
497 }
498 }
499
500 return table_updated;
501}
502
503
504void LIB_TABLE::Load( const wxString& aFileName )
505{
506 std::lock_guard<std::shared_mutex> lock( m_mutex );
507 clear();
508
509 std::unique_ptr<LINE_READER> reader = m_io->GetReader( aFileName );
510
511 // It's OK if footprint library tables are missing.
512 if( reader )
513 {
514 LIB_TABLE_LEXER lexer( reader.get() );
515
516 Parse( &lexer );
517
518 if( m_version != 7 && migrate() && m_io->CanSaveToUri( aFileName ) )
519 Save( aFileName );
520
521 reindex();
522 }
523}
524
525
526void LIB_TABLE::Save( const wxString& aFileName ) const
527{
528 std::unique_ptr<OUTPUTFORMATTER> sf = m_io->GetWriter( aFileName );
529
530 if( !sf )
531 {
532 THROW_IO_ERROR( wxString::Format( _( "Failed to get writer for %s" ), aFileName ) );
533 }
534
535 // Force the lib table version to 7 before saving
536 m_version = 7;
537 Format( sf.get(), 0 );
538}
539
540
541std::map<std::string, UTF8>* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
542{
543 if( aOptionsList.size() )
544 {
545 const char* cp = &aOptionsList[0];
546 const char* end = cp + aOptionsList.size();
547
548 std::map<std::string, UTF8> props;
549 std::string pair;
550
551 // Parse all name=value pairs
552 while( cp < end )
553 {
554 pair.clear();
555
556 // Skip leading white space.
557 while( cp < end && isspace( *cp ) )
558 ++cp;
559
560 // Find the end of pair/field
561 while( cp < end )
562 {
563 if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
564 {
565 ++cp; // skip the escape
566 pair += *cp++; // add the separator
567 }
568 else if( *cp == OPT_SEP )
569 {
570 ++cp; // skip the separator
571 break; // process the pair
572 }
573 else
574 {
575 pair += *cp++;
576 }
577 }
578
579 // stash the pair
580 if( pair.size() )
581 {
582 // first equals sign separates 'name' and 'value'.
583 size_t eqNdx = pair.find( '=' );
584
585 if( eqNdx != pair.npos )
586 {
587 std::string name = pair.substr( 0, eqNdx );
588 std::string value = pair.substr( eqNdx + 1 );
589 props[name] = value;
590 }
591 else
592 {
593 props[pair] = ""; // property is present, but with no value.
594 }
595 }
596 }
597
598 if( props.size() )
599 return new std::map<std::string, UTF8>( props );
600 }
601
602 return nullptr;
603}
604
605
606UTF8 LIB_TABLE::FormatOptions( const std::map<std::string, UTF8>* aProperties )
607{
608 UTF8 ret;
609
610 if( aProperties )
611 {
612 for( std::map<std::string, UTF8>::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
613 {
614 const std::string& name = it->first;
615
616 const UTF8& value = it->second;
617
618 if( ret.size() )
619 ret += OPT_SEP;
620
621 ret += name;
622
623 // the separation between name and value is '='
624 if( value.size() )
625 {
626 ret += '=';
627
628 for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
629 {
630 // escape any separator in the value.
631 if( *si == OPT_SEP )
632 ret += '\\';
633
634 ret += *si;
635 }
636 }
637 }
638 }
639
640 return ret;
641}
const char * name
Definition: DXF_plotter.cpp:57
bool CanSaveToUri(const wxString &aURI) const override
Check if the given URI is writable.
bool UrisAreEquivalent(const wxString &aURI1, const wxString &aURI2) const override
Compare two URIs for equivalence.
std::unique_ptr< LINE_READER > GetReader(const wxString &aURI) const override
Create a reader for the given URI.
std::unique_ptr< OUTPUTFORMATTER > GetWriter(const wxString &aURI) const override
Save the given table to the given URI.
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE.
void SetFullURI(const wxString &aFullURI)
Change the full URI for the library.
bool visible
Whether the LIB_TABLE_ROW is visible in choosers.
std::unique_ptr< std::map< std::string, UTF8 > > properties
const wxString & GetOptions() const
Return the options string, which may hold a password or anything else needed to instantiate the under...
wxString nickName
const wxString & GetDescr() const
Return the description of the library referenced by this row.
wxString options
wxString uri_user
what user entered from UI or loaded from disk
virtual const wxString GetType() const =0
Return the type of library represented by this row.
wxString description
void Format(OUTPUTFORMATTER *out, int nestLevel) const
Serialize this object as utf8 text to an OUTPUTFORMATTER, and tries to make it look good using multip...
bool enabled
Whether the LIB_TABLE_ROW is enabled.
void SetParent(LIB_TABLE *aParent)
const wxString & GetNickName() const
const wxString GetFullURI(bool aSubstituted=false) const
Return the full location specifying URI for the LIB, either in original UI form or in environment var...
LIB_TABLE_ROW * clone() const
bool operator==(const LIB_TABLE_ROW &r) const
bool GetIsEnabled() const
void SetOptions(const wxString &aOptions)
Change the library options strings.
void setProperties(std::map< std::string, UTF8 > *aProperties)
bool GetIsVisible() const
Manage LIB_TABLE_ROW records (rows), and can be searched based on library nickname.
bool ReplaceRow(size_t aIndex, LIB_TABLE_ROW *aRow)
Replaces the Nth row with the given new row.
std::shared_mutex m_mutex
Mutex to protect access to the rows vector.
const wxString GetDescription(const wxString &aNickname)
std::vector< wxString > GetLogicalLibs()
Return the logical library names, all of them that are pertinent to a look up done on this LIB_TABLE.
static std::map< std::string, UTF8 > * ParseOptions(const std::string &aOptionsList)
Parses aOptionsList and places the result into a #PROPERTIES object which is returned.
static UTF8 FormatOptions(const std::map< std::string, UTF8 > *aProperties)
Returns a list of options from the aProperties parameter.
std::map< wxString, LIB_TABLE_ROWS_ITER > m_rowsMap
this is a non-owning index into the LIB_TABLE_ROWS table
bool HasLibrary(const wxString &aNickname, bool aCheckEnabled=false) const
Test for the existence of aNickname in the library table.
int m_version
Versioning to handle importing old tables.
bool InsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Adds aRow if it does not already exist or if doReplace is true.
void TransferRows(LIB_TABLE_ROWS &aRowsList)
Takes ownership of another list of rows; the original list will be freed.
LIB_TABLE_ROWS m_rows
Owning set of rows.
virtual ~LIB_TABLE()
bool doInsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Performs the mechanics of inserting a row, but without locking or reindexing.
bool migrate()
Updates the env vars from older version of KiCad, provided they do not currently resolve to anything.
void Load(const wxString &aFileName)
Load the library table using the path defined by aFileName aFallBackTable.
bool HasLibraryWithPath(const wxString &aPath) const
Test for the existence of aPath in the library table.
virtual void Format(OUTPUTFORMATTER *aOutput, int aIndentLevel) const =0
Generate the table in s-expression format to aOutput with an indentation level of aIndentLevel.
bool RemoveRow(const LIB_TABLE_ROW *aRow)
Removes a row from the table and frees the pointer.
LIB_TABLE(LIB_TABLE *aFallBackTable=nullptr, std::unique_ptr< LIB_TABLE_IO > aTableIo=nullptr)
Build a library table by pre-pending this table fragment in front of aFallBackTable.
LIB_TABLE * m_fallBack
wxString GetFullURI(const wxString &aLibNickname, bool aExpandEnvVars=true) const
Return the full URI of the library mapped to aLibNickname.
bool IsEmpty(bool aIncludeFallback=true)
Return true if the table is empty.
virtual void Parse(LIB_TABLE_LEXER *aLexer)=0
Parse the #LIB_TABLE_LEXER s-expression library table format into the appropriate LIB_TABLE_ROW objec...
std::unique_ptr< LIB_TABLE_IO > m_io
const LIB_TABLE_ROW * FindRowByURI(const wxString &aURI)
bool ChangeRowOrder(size_t aIndex, int aOffset)
Moves a row within the table.
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
LIB_TABLE_ROW * findRow(const wxString &aNickname, bool aCheckIfEnabled=false) const
Return a LIB_TABLE_ROW if aNickname is found in this table or in any chained fallBack table fragment,...
An interface used to output 8 bit text in a convenient way.
Definition: richio.h:322
std::string Quotew(const wxString &aWrapee) const
Definition: richio.cpp:543
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:458
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition: utf8.h:72
std::string::const_iterator begin() const
Definition: utf8.h:197
std::string::size_type size() const
Definition: utf8.h:111
std::string::const_iterator end() const
Definition: utf8.h:198
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:348
The common library.
#define OPT_SEP
options separator character
#define _(s)
#define THROW_IO_ERROR(msg)
Definition: ki_exception.h:39
LIB_TABLE_ROW * new_clone(const LIB_TABLE_ROW &aRow)
Allows boost pointer containers to make clones of the data stored in them.
boost::ptr_vector< LIB_TABLE_ROW > LIB_TABLE_ROWS
LIB_TABLE_ROWS::iterator LIB_TABLE_ROWS_ITER
This file contains miscellaneous commonly used macros and functions.
STL namespace.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: string_utils.h:398