KiCad PCB EDA Suite
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
130bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
131{
132 if( !aIncludeFallback || !m_fallBack )
133 return m_rows.empty();
134
135 return m_rows.empty() && m_fallBack->IsEmpty( true );
136}
137
138
139const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
140{
141 // Use "no exception" form of find row and ignore disabled flag.
142 const LIB_TABLE_ROW* row = findRow( aNickname );
143
144 if( row )
145 return row->GetDescr();
146 else
147 return wxEmptyString;
148}
149
150
151bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
152{
153 const LIB_TABLE_ROW* row = findRow( aNickname, aCheckEnabled );
154
155 if( row == nullptr )
156 return false;
157
158 return true;
159}
160
161
162bool LIB_TABLE::HasLibraryWithPath( const wxString& aPath ) const
163{
164 for( const LIB_TABLE_ROW& row : m_rows )
165 {
166 if( row.GetFullURI() == aPath )
167 return true;
168 }
169
170 return false;
171}
172
173
174wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
175{
176 const LIB_TABLE_ROW* row = findRow( aNickname, true );
177
178 wxString retv;
179
180 if( row )
181 retv = row->GetFullURI( aExpandEnvVars );
182
183 return retv;
184}
185
186
187LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName, bool aCheckIfEnabled ) const
188{
189 LIB_TABLE_ROW* row = nullptr;
190 LIB_TABLE* cur = (LIB_TABLE*) this;
191
192 do
193 {
194 cur->ensureIndex();
195
196 std::shared_lock<std::shared_mutex> lock( cur->m_nickIndexMutex );
197
198 for( const std::pair<const wxString, int>& entry : cur->m_nickIndex )
199 {
200 if( entry.first == aNickName )
201 {
202 row = &cur->m_rows[entry.second];
203
204 if( !aCheckIfEnabled || row->GetIsEnabled() )
205 return row;
206 }
207 }
208
209 // Repeat, this time looking for names that were "fixed" by legacy versions because
210 // the old eeschema file format didn't support spaces in tokens.
211 for( const std::pair<const wxString, int>& entry : cur->m_nickIndex )
212 {
213 wxString legacyLibName = entry.first;
214 legacyLibName.Replace( " ", "_" );
215
216 if( legacyLibName == aNickName )
217 {
218 row = &cur->m_rows[entry.second];
219
220 if( !aCheckIfEnabled || row->GetIsEnabled() )
221 return row;
222 }
223 }
224
225 // not found, search fall back table(s), if any
226 } while( ( cur = cur->m_fallBack ) != nullptr );
227
228 return nullptr; // not found
229}
230
231
232const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
233{
234 LIB_TABLE* cur = this;
235
236 do
237 {
238 cur->ensureIndex();
239
240 for( unsigned i = 0; i < cur->m_rows.size(); i++ )
241 {
242 wxString tmp = cur->m_rows[i].GetFullURI( true );
243
244 if( tmp.Find( "://" ) != wxNOT_FOUND )
245 {
246 if( tmp == aURI )
247 return &cur->m_rows[i]; // found as URI
248 }
249 else
250 {
251 wxFileName fn = aURI;
252
253 // This will also test if the file is a symlink so if we are comparing
254 // a symlink to the same real file, the comparison will be true. See
255 // wxFileName::SameAs() in the wxWidgets source.
256 if( fn == wxFileName( tmp ) )
257 return &cur->m_rows[i]; // found as full path and file name
258 }
259 }
260
261 // not found, search fall back table(s), if any
262 } while( ( cur = cur->m_fallBack ) != nullptr );
263
264 return nullptr; // not found
265}
266
267
268std::vector<wxString> LIB_TABLE::GetLogicalLibs()
269{
270 // Only return unique logical library names. Use std::set::insert() to quietly reject any
271 // duplicates (usually due to encountering a duplicate nickname in a fallback table).
272
273 std::set<wxString> unique;
274 std::vector<wxString> ret;
275 const LIB_TABLE* cur = this;
276
277 do
278 {
279 for( LIB_TABLE_ROWS_CITER it = cur->m_rows.begin(); it!=cur->m_rows.end(); ++it )
280 {
281 if( it->GetIsEnabled() )
282 unique.insert( it->GetNickName() );
283 }
284
285 } while( ( cur = cur->m_fallBack ) != nullptr );
286
287 ret.reserve( unique.size() );
288
289 // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
290 for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
291 ret.push_back( *it );
292
293 // We want to allow case-sensitive duplicates but sort by case-insensitive ordering
294 std::sort( ret.begin(), ret.end(),
295 []( const wxString& lhs, const wxString& rhs )
296 {
297 return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
298 } );
299
300 return ret;
301}
302
303
304bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
305{
306 ensureIndex();
307
308 std::lock_guard<std::shared_mutex> lock( m_nickIndexMutex );
309
310 INDEX_CITER it = m_nickIndex.find( aRow->GetNickName() );
311
312 aRow->SetParent( this );
313
314 if( it == m_nickIndex.end() )
315 {
316 m_rows.push_back( aRow );
317 m_nickIndex.insert( INDEX_VALUE( aRow->GetNickName(), m_rows.size() - 1 ) );
318 return true;
319 }
320
321 if( doReplace )
322 {
323 m_rows.replace( it->second, aRow );
324 return true;
325 }
326
327 return false;
328}
329
330
332{
333 bool table_updated = false;
334
335 for( LIB_TABLE_ROW& row : m_rows )
336 {
337 bool row_updated = false;
338 wxString uri = row.GetFullURI( true );
339
340 // If the uri still has a variable in it, that means that the user does not have
341 // these vars defined. We update the old vars to the KICAD7 versions on load
342 row_updated |= ( uri.Replace( wxS( "${KICAD5_" ), wxS( "${KICAD7_" ), false ) > 0 );
343 row_updated |= ( uri.Replace( wxS( "${KICAD6_" ), wxS( "${KICAD7_" ), false ) > 0 );
344
345 if( row_updated )
346 {
347 row.SetFullURI( uri );
348 table_updated = true;
349 }
350 }
351
352 return table_updated;
353}
354
355
356void LIB_TABLE::Load( const wxString& aFileName )
357{
358 // It's OK if footprint library tables are missing.
359 if( wxFileName::IsFileReadable( aFileName ) )
360 {
361 FILE_LINE_READER reader( aFileName );
362 LIB_TABLE_LEXER lexer( &reader );
363
364 Parse( &lexer );
365
366 if( m_version != 7 && migrate() && wxFileName::IsFileWritable( aFileName ) )
367 Save( aFileName );
368 }
369}
370
371
372void LIB_TABLE::Save( const wxString& aFileName ) const
373{
374 FILE_OUTPUTFORMATTER sf( aFileName );
375
376 // Force the lib table version to 7 before saving
377 m_version = 7;
378 Format( &sf, 0 );
379}
380
381
382STRING_UTF8_MAP* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
383{
384 if( aOptionsList.size() )
385 {
386 const char* cp = &aOptionsList[0];
387 const char* end = cp + aOptionsList.size();
388
389 STRING_UTF8_MAP props;
390 std::string pair;
391
392 // Parse all name=value pairs
393 while( cp < end )
394 {
395 pair.clear();
396
397 // Skip leading white space.
398 while( cp < end && isspace( *cp ) )
399 ++cp;
400
401 // Find the end of pair/field
402 while( cp < end )
403 {
404 if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
405 {
406 ++cp; // skip the escape
407 pair += *cp++; // add the separator
408 }
409 else if( *cp == OPT_SEP )
410 {
411 ++cp; // skip the separator
412 break; // process the pair
413 }
414 else
415 {
416 pair += *cp++;
417 }
418 }
419
420 // stash the pair
421 if( pair.size() )
422 {
423 // first equals sign separates 'name' and 'value'.
424 size_t eqNdx = pair.find( '=' );
425
426 if( eqNdx != pair.npos )
427 {
428 std::string name = pair.substr( 0, eqNdx );
429 std::string value = pair.substr( eqNdx + 1 );
430 props[name] = value;
431 }
432 else
433 {
434 props[pair] = ""; // property is present, but with no value.
435 }
436 }
437 }
438
439 if( props.size() )
440 return new STRING_UTF8_MAP( props );
441 }
442
443 return nullptr;
444}
445
446
448{
449 UTF8 ret;
450
451 if( aProperties )
452 {
453 for( STRING_UTF8_MAP::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
454 {
455 const std::string& name = it->first;
456
457 const UTF8& value = it->second;
458
459 if( ret.size() )
460 ret += OPT_SEP;
461
462 ret += name;
463
464 // the separation between name and value is '='
465 if( value.size() )
466 {
467 ret += '=';
468
469 for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
470 {
471 // escape any separator in the value.
472 if( *si == OPT_SEP )
473 ret += '\\';
474
475 ret += *si;
476 }
477 }
478 }
479 }
480
481 return ret;
482}
const char * name
Definition: DXF_plotter.cpp:56
A LINE_READER that reads from an open file.
Definition: richio.h:173
Used for text file output.
Definition: richio.h:457
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.
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.
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.
LIB_TABLE_ROWS m_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.
INDEX m_nickIndex
this particular key is the nickName within each row.
INDEX::value_type INDEX_VALUE
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...
INDEX::const_iterator INDEX_CITER
const LIB_TABLE_ROW * FindRowByURI(const wxString &aURI)
std::shared_mutex m_nickIndexMutex
Mutex to protect access to the nickIndex variable.
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
void ensureIndex()
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:310
std::string Quotew(const wxString &aWrapee) const
Definition: richio.cpp:501
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:433
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:299
The common library.
LIB_TABLE_ROW * new_clone(const LIB_TABLE_ROW &aRow)
Allows boost pointer containers to make clones of the data stored in them.
#define OPT_SEP
options separator character
LIB_TABLE_ROWS::const_iterator LIB_TABLE_ROWS_CITER
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: macros.h:96