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/filename.h>
28#include <set>
29#include <common.h>
30#include <kiface_base.h>
31#include <lib_table_base.h>
32#include <lib_table_lexer.h>
33#include <macros.h>
34#include <string_utils.h>
35
36#define OPT_SEP '|'
37
38
39using namespace LIB_TABLE_T;
40
41
43{
44 return aRow.clone();
45}
46
47
49{
50 properties.reset( aProperties );
51}
52
53
54void LIB_TABLE_ROW::SetFullURI( const wxString& aFullURI )
55{
56 uri_user = aFullURI;
57}
58
59
60const wxString LIB_TABLE_ROW::GetFullURI( bool aSubstituted ) const
61{
62 if( aSubstituted )
63 {
64 return ExpandEnvVarSubstitutions( uri_user, nullptr );
65 }
66
67 return uri_user;
68}
69
70
71void LIB_TABLE_ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const
72{
73 // In Kicad, we save path and file names using the Unix notation (separator = '/')
74 // So ensure separator is always '/' is saved URI string
75 wxString uri = GetFullURI();
76 uri.Replace( '\\', '/' );
77
78 wxString extraOptions;
79
80 if( !GetIsEnabled() )
81 extraOptions += "(disabled)";
82
83 if( !GetIsVisible() )
84 extraOptions += "(hidden)";
85
86 out->Print( nestLevel, "(lib (name %s)(type %s)(uri %s)(options %s)(descr %s)%s)\n",
87 out->Quotew( GetNickName() ).c_str(),
88 out->Quotew( GetType() ).c_str(),
89 out->Quotew( uri ).c_str(),
90 out->Quotew( GetOptions() ).c_str(),
91 out->Quotew( GetDescr() ).c_str(),
92 extraOptions.ToStdString().c_str() );
93}
94
95
97{
98 return nickName == r.nickName
99 && uri_user == r.uri_user
100 && options == r.options
102 && enabled == r.enabled
103 && visible == r.visible;
104}
105
106
107void LIB_TABLE_ROW::SetOptions( const wxString& aOptions )
108{
109 options = aOptions;
110
111 // set PROPERTIES* from options
113}
114
115
116LIB_TABLE::LIB_TABLE( LIB_TABLE* aFallBackTable ) :
117 m_fallBack( aFallBackTable ), m_version( 0 )
118{
119 // not copying fall back, simply search aFallBackTable separately
120 // if "nickName not found".
121}
122
123
125{
126 // *fallBack is not owned here.
127}
128
129
131{
132 m_rows.clear();
133 m_rowsMap.clear();
134}
135
136
137bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
138{
139 if( !aIncludeFallback || !m_fallBack )
140 return m_rows.empty();
141
142 return m_rows.empty() && m_fallBack->IsEmpty( true );
143}
144
145
146const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
147{
148 // Use "no exception" form of find row and ignore disabled flag.
149 const LIB_TABLE_ROW* row = findRow( aNickname );
150
151 if( row )
152 return row->GetDescr();
153 else
154 return wxEmptyString;
155}
156
157
158bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
159{
160 const LIB_TABLE_ROW* row = findRow( aNickname, aCheckEnabled );
161
162 if( row == nullptr )
163 return false;
164
165 return true;
166}
167
168
169bool LIB_TABLE::HasLibraryWithPath( const wxString& aPath ) const
170{
171 for( const LIB_TABLE_ROW& row : m_rows )
172 {
173 if( row.GetFullURI() == aPath )
174 return true;
175 }
176
177 return false;
178}
179
180
181wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
182{
183 const LIB_TABLE_ROW* row = findRow( aNickname, true );
184
185 wxString retv;
186
187 if( row )
188 retv = row->GetFullURI( aExpandEnvVars );
189
190 return retv;
191}
192
193
194LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName, bool aCheckIfEnabled ) const
195{
196 LIB_TABLE_ROW* row = nullptr;
197 LIB_TABLE* cur = (LIB_TABLE*) this;
198
199 do
200 {
201 std::shared_lock<std::shared_mutex> lock( cur->m_mutex );
202
203 if( cur->m_rowsMap.count( aNickName ) )
204 row = &*cur->m_rowsMap.at( aNickName );
205
206 if( row )
207 {
208 if( !aCheckIfEnabled || row->GetIsEnabled() )
209 return row;
210 else
211 return nullptr; // We found it, but it's disabled
212 }
213
214 // Repeat, this time looking for names that were "fixed" by legacy versions because
215 // the old eeschema file format didn't support spaces in tokens.
216 for( const std::pair<const wxString, LIB_TABLE_ROWS_ITER>& entry : cur->m_rowsMap )
217 {
218 wxString legacyLibName = entry.first;
219 legacyLibName.Replace( " ", "_" );
220
221 if( legacyLibName == aNickName )
222 {
223 row = &*entry.second;
224
225 if( !aCheckIfEnabled || row->GetIsEnabled() )
226 return row;
227 }
228 }
229
230 // not found, search fall back table(s), if any
231 } while( ( cur = cur->m_fallBack ) != nullptr );
232
233 return nullptr; // not found
234}
235
236
237const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
238{
239 LIB_TABLE* cur = this;
240
241 do
242 {
243 for( unsigned i = 0; i < cur->m_rows.size(); i++ )
244 {
245 wxString tmp = cur->m_rows[i].GetFullURI( true );
246
247 if( tmp.Find( "://" ) != wxNOT_FOUND )
248 {
249 if( tmp == aURI )
250 return &cur->m_rows[i]; // found as URI
251 }
252 else
253 {
254 wxFileName fn = aURI;
255
256 // This will also test if the file is a symlink so if we are comparing
257 // a symlink to the same real file, the comparison will be true. See
258 // wxFileName::SameAs() in the wxWidgets source.
259 if( fn == wxFileName( tmp ) )
260 return &cur->m_rows[i]; // found as full path and file name
261 }
262 }
263
264 // not found, search fall back table(s), if any
265 } while( ( cur = cur->m_fallBack ) != nullptr );
266
267 return nullptr; // not found
268}
269
270
271std::vector<wxString> LIB_TABLE::GetLogicalLibs()
272{
273 // Only return unique logical library names. Use std::set::insert() to quietly reject any
274 // duplicates (usually due to encountering a duplicate nickname in a fallback table).
275
276 std::set<wxString> unique;
277 std::vector<wxString> ret;
278 const LIB_TABLE* cur = this;
279
280 do
281 {
282 for( const LIB_TABLE_ROW& row : cur->m_rows )
283 {
284 if( row.GetIsEnabled() )
285 unique.insert( row.GetNickName() );
286 }
287
288 } while( ( cur = cur->m_fallBack ) != nullptr );
289
290 ret.reserve( unique.size() );
291
292 // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
293 for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
294 ret.push_back( *it );
295
296 // We want to allow case-sensitive duplicates but sort by case-insensitive ordering
297 std::sort( ret.begin(), ret.end(),
298 []( const wxString& lhs, const wxString& rhs )
299 {
300 return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
301 } );
302
303 return ret;
304}
305
306
307bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
308{
309 std::lock_guard<std::shared_mutex> lock( m_mutex );
310
311 auto it = m_rowsMap.find( aRow->GetNickName() );
312
313 if( it != m_rowsMap.end() )
314 {
315 if( !doReplace )
316 return false;
317
318 m_rows.replace( it->second, aRow );
319 }
320 else
321 {
322 m_rows.push_back( aRow );
323 }
324
325 aRow->SetParent( this );
326 reindex();
327 return true;
328}
329
330
332{
333 std::lock_guard<std::shared_mutex> lock( m_mutex );
334
335 bool found = false;
336 auto it = m_rowsMap.find( aRow->GetNickName() );
337
338 if( it != m_rowsMap.end() )
339 {
340 if( &*it->second == aRow )
341 {
342 found = true;
343 m_rows.erase( it->second );
344 }
345 }
346
347 if( !found )
348 {
349 // Bookkeeping got messed up...
350 for( int i = (int)m_rows.size() - 1; i >= 0; --i )
351 {
352 if( &m_rows[i] == aRow )
353 {
354 m_rows.erase( m_rows.begin() + i );
355 found = true;
356 break;
357 }
358 }
359 }
360
361 if( found )
362 reindex();
363
364 return found;
365}
366
367
368bool LIB_TABLE::ReplaceRow( size_t aIndex, LIB_TABLE_ROW* aRow )
369{
370 std::lock_guard<std::shared_mutex> lock( m_mutex );
371
372 if( aIndex >= m_rows.size() )
373 return false;
374
375 m_rowsMap.erase( m_rows[aIndex].GetNickName() );
376
377 m_rows.replace( aIndex, aRow );
378 reindex();
379 return true;
380}
381
382
383bool LIB_TABLE::ChangeRowOrder( size_t aIndex, int aOffset )
384{
385 std::lock_guard<std::shared_mutex> lock( m_mutex );
386
387 if( aIndex >= m_rows.size() )
388 return false;
389
390 int newPos = static_cast<int>( aIndex ) + aOffset;
391
392 if( newPos < 0 || newPos > static_cast<int>( m_rows.size() ) - 1 )
393 return false;
394
395 auto element = m_rows.release( m_rows.begin() + aIndex );
396
397 m_rows.insert( m_rows.begin() + newPos, element.release() );
398 reindex();
399
400 return true;
401}
402
403
405{
406 std::lock_guard<std::shared_mutex> lock( m_mutex );
407
408 m_rows.transfer( m_rows.end(), aRowsList.begin(), aRowsList.end(), aRowsList );
409
410 reindex();
411}
412
413
415{
416 m_rowsMap.clear();
417
418 for( LIB_TABLE_ROWS_ITER it = m_rows.begin(); it != m_rows.end(); ++it )
419 {
420 it->SetParent( this );
421 m_rowsMap[it->GetNickName()] = it;
422 }
423}
424
425
427{
428 bool table_updated = false;
429
430 for( LIB_TABLE_ROW& row : m_rows )
431 {
432 bool row_updated = false;
433 wxString uri = row.GetFullURI( true );
434
435 // If the uri still has a variable in it, that means that the user does not have
436 // these vars defined. We update the old vars to the KICAD7 versions on load
437 row_updated |= ( uri.Replace( wxS( "${KICAD5_" ), wxS( "${KICAD7_" ), false ) > 0 );
438 row_updated |= ( uri.Replace( wxS( "${KICAD6_" ), wxS( "${KICAD7_" ), false ) > 0 );
439
440 if( row_updated )
441 {
442 row.SetFullURI( uri );
443 table_updated = true;
444 }
445 }
446
447 return table_updated;
448}
449
450
451void LIB_TABLE::Load( const wxString& aFileName )
452{
453 // It's OK if footprint library tables are missing.
454 if( wxFileName::IsFileReadable( aFileName ) )
455 {
456 FILE_LINE_READER reader( aFileName );
457 LIB_TABLE_LEXER lexer( &reader );
458
459 Parse( &lexer );
460
461 if( m_version != 7 && migrate() && wxFileName::IsFileWritable( aFileName ) )
462 Save( aFileName );
463 }
464}
465
466
467void LIB_TABLE::Save( const wxString& aFileName ) const
468{
469 FILE_OUTPUTFORMATTER sf( aFileName );
470
471 // Force the lib table version to 7 before saving
472 m_version = 7;
473 Format( &sf, 0 );
474}
475
476
477STRING_UTF8_MAP* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
478{
479 if( aOptionsList.size() )
480 {
481 const char* cp = &aOptionsList[0];
482 const char* end = cp + aOptionsList.size();
483
484 STRING_UTF8_MAP props;
485 std::string pair;
486
487 // Parse all name=value pairs
488 while( cp < end )
489 {
490 pair.clear();
491
492 // Skip leading white space.
493 while( cp < end && isspace( *cp ) )
494 ++cp;
495
496 // Find the end of pair/field
497 while( cp < end )
498 {
499 if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
500 {
501 ++cp; // skip the escape
502 pair += *cp++; // add the separator
503 }
504 else if( *cp == OPT_SEP )
505 {
506 ++cp; // skip the separator
507 break; // process the pair
508 }
509 else
510 {
511 pair += *cp++;
512 }
513 }
514
515 // stash the pair
516 if( pair.size() )
517 {
518 // first equals sign separates 'name' and 'value'.
519 size_t eqNdx = pair.find( '=' );
520
521 if( eqNdx != pair.npos )
522 {
523 std::string name = pair.substr( 0, eqNdx );
524 std::string value = pair.substr( eqNdx + 1 );
525 props[name] = value;
526 }
527 else
528 {
529 props[pair] = ""; // property is present, but with no value.
530 }
531 }
532 }
533
534 if( props.size() )
535 return new STRING_UTF8_MAP( props );
536 }
537
538 return nullptr;
539}
540
541
543{
544 UTF8 ret;
545
546 if( aProperties )
547 {
548 for( STRING_UTF8_MAP::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
549 {
550 const std::string& name = it->first;
551
552 const UTF8& value = it->second;
553
554 if( ret.size() )
555 ret += OPT_SEP;
556
557 ret += name;
558
559 // the separation between name and value is '='
560 if( value.size() )
561 {
562 ret += '=';
563
564 for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
565 {
566 // escape any separator in the value.
567 if( *si == OPT_SEP )
568 ret += '\\';
569
570 ret += *si;
571 }
572 }
573 }
574 }
575
576 return ret;
577}
const char * name
Definition: DXF_plotter.cpp:57
A LINE_READER that reads from an open file.
Definition: richio.h:185
Used for text file output.
Definition: richio.h:475
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.
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.
std::unique_ptr< STRING_UTF8_MAP > properties
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)
void setProperties(STRING_UTF8_MAP *aProperties)
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.
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.
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 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.
void Clear()
Delete all rows.
LIB_TABLE * m_fallBack
wxString GetFullURI(const wxString &aLibNickname, bool aExpandEnvVars=true) const
Return the full URI of the library mapped to aLibNickname.
LIB_TABLE(LIB_TABLE *aFallBackTable=nullptr)
Build a library table by pre-pending this table fragment in front of aFallBackTable.
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...
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.
static STRING_UTF8_MAP * ParseOptions(const std::string &aOptionsList)
Parses aOptionsList and places the result into a #PROPERTIES object which is returned.
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,...
static UTF8 FormatOptions(const STRING_UTF8_MAP *aProperties)
Returns a list of options from the aProperties parameter.
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:526
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:458
A name/value tuple with unique names and optional values.
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition: utf8.h:71
std::string::const_iterator begin() const
Definition: utf8.h:192
std::string::size_type size() const
Definition: utf8.h:110
std::string::const_iterator end() const
Definition: utf8.h:193
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:334
The common library.
#define OPT_SEP
options separator character
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.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: string_utils.h:391