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-2021 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 
35 
36 #define OPT_SEP '|'
37 
38 
39 using namespace LIB_TABLE_T;
40 
41 
43 {
44  return aRow.clone();
45 }
46 
47 
49 {
50  properties.reset( aProperties );
51 }
52 
53 
54 void LIB_TABLE_ROW::SetFullURI( const wxString& aFullURI )
55 {
56  uri_user = aFullURI;
57 
58 #if !FP_LATE_ENVVAR
59  uri_expanded = FP_LIB_TABLE::ExpandSubstitutions( aFullURI );
60 #endif
61 }
62 
63 
64 const wxString LIB_TABLE_ROW::GetFullURI( bool aSubstituted ) const
65 {
66  if( aSubstituted )
67  {
68 #if !FP_LATE_ENVVAR // early expansion
69  return uri_expanded;
70 
71 #else // late expansion
72  return ExpandEnvVarSubstitutions( uri_user, nullptr );
73 #endif
74  }
75 
76  return uri_user;
77 }
78 
79 
80 void LIB_TABLE_ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const
81 {
82  // In Kicad, we save path and file names using the Unix notation (separator = '/')
83  // So ensure separator is always '/' is saved URI string
84  wxString uri = GetFullURI();
85  uri.Replace( '\\', '/' );
86 
87  wxString extraOptions;
88 
89  if( !GetIsEnabled() )
90  {
91  extraOptions += "(disabled)";
92  }
93 
94  out->Print( nestLevel, "(lib (name %s)(type %s)(uri %s)(options %s)(descr %s)%s)\n",
95  out->Quotew( GetNickName() ).c_str(),
96  out->Quotew( GetType() ).c_str(),
97  out->Quotew( uri ).c_str(),
98  out->Quotew( GetOptions() ).c_str(),
99  out->Quotew( GetDescr() ).c_str(),
100  extraOptions.ToStdString().c_str()
101  );
102 }
103 
104 
106 {
107  return nickName == r.nickName
108  && uri_user == r.uri_user
109  && options == r.options
110  && description == r.description
111  && enabled == r.enabled;
112 }
113 
114 
115 void LIB_TABLE_ROW::SetOptions( const wxString& aOptions )
116 {
117  options = aOptions;
118 
119  // set PROPERTIES* from options
120  setProperties( LIB_TABLE::ParseOptions( TO_UTF8( aOptions ) ) );
121 }
122 
123 
124 LIB_TABLE::LIB_TABLE( LIB_TABLE* aFallBackTable ) :
125  fallBack( aFallBackTable )
126 {
127  // not copying fall back, simply search aFallBackTable separately
128  // if "nickName not found".
129 }
130 
131 
133 {
134  // *fallBack is not owned here.
135 }
136 
137 
138 bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
139 {
140  if( !aIncludeFallback || !fallBack )
141  return rows.empty();
142 
143  return rows.empty() && fallBack->IsEmpty( true );
144 }
145 
146 
147 const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
148 {
149  // Use "no exception" form of find row and ignore disabled flag.
150  const LIB_TABLE_ROW* row = findRow( aNickname );
151 
152  if( row )
153  return row->GetDescr();
154  else
155  return wxEmptyString;
156 }
157 
158 
159 bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
160 {
161  const LIB_TABLE_ROW* row = findRow( aNickname, aCheckEnabled );
162 
163  if( row == nullptr )
164  return false;
165 
166  return true;
167 }
168 
169 
170 wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
171 {
172  const LIB_TABLE_ROW* row = findRow( aNickname, true );
173 
174  wxString retv;
175 
176  if( row )
177  retv = row->GetFullURI( aExpandEnvVars );
178 
179  return retv;
180 }
181 
182 
183 LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName, bool aCheckIfEnabled ) const
184 {
185  LIB_TABLE_ROW* row = nullptr;
186  LIB_TABLE* cur = (LIB_TABLE*) this;
187 
188  do
189  {
190  std::lock_guard<std::recursive_mutex> lock( cur->m_nickIndexMutex );
191  cur->ensureIndex();
192 
193  for( const std::pair<const wxString, int>& entry : cur->nickIndex )
194  {
195  if( entry.first == aNickName )
196  {
197  row = &cur->rows[entry.second];
198 
199  if( !aCheckIfEnabled || ( aCheckIfEnabled && row->GetIsEnabled() ) )
200  return row;
201  }
202  }
203 
204  // Repeat, this time looking for names that were "fixed" by legacy versions because
205  // the old eeschema file format didn't support spaces in tokens.
206  for( const std::pair<const wxString, int>& entry : cur->nickIndex )
207  {
208  wxString legacyLibName = entry.first;
209  legacyLibName.Replace( " ", "_" );
210 
211  if( legacyLibName == aNickName )
212  {
213  row = &cur->rows[entry.second];
214 
215  if( !aCheckIfEnabled || ( aCheckIfEnabled && row->GetIsEnabled() ) )
216  return row;
217  }
218  }
219 
220  // not found, search fall back table(s), if any
221  } while( ( cur = cur->fallBack ) != nullptr );
222 
223  return nullptr; // not found
224 }
225 
226 
227 const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
228 {
229  LIB_TABLE* cur = this;
230 
231  do
232  {
233  cur->ensureIndex();
234 
235  for( unsigned i = 0; i < cur->rows.size(); i++ )
236  {
237  wxString tmp = cur->rows[i].GetFullURI( true );
238 
239  if( tmp.Find( "://" ) != wxNOT_FOUND )
240  {
241  if( tmp == aURI )
242  return &cur->rows[i]; // found as URI
243  }
244  else
245  {
246  wxFileName fn = aURI;
247 
248  // This will also test if the file is a symlink so if we are comparing
249  // a symlink to the same real file, the comparison will be true. See
250  // wxFileName::SameAs() in the wxWidgets source.
251  if( fn == wxFileName( tmp ) )
252  return &cur->rows[i]; // found as full path and file name
253  }
254  }
255 
256  // not found, search fall back table(s), if any
257  } while( ( cur = cur->fallBack ) != nullptr );
258 
259  return nullptr; // not found
260 }
261 
262 
263 std::vector<wxString> LIB_TABLE::GetLogicalLibs()
264 {
265  // Only return unique logical library names. Use std::set::insert() to
266  // quietly reject any duplicates, which can happen when encountering a duplicate
267  // nickname from one of the fall back table(s).
268 
269  std::set< wxString > unique;
270  std::vector< wxString > ret;
271  const LIB_TABLE* cur = this;
272 
273  do
274  {
275  for( LIB_TABLE_ROWS_CITER it = cur->rows.begin(); it!=cur->rows.end(); ++it )
276  {
277  if( it->GetIsEnabled() )
278  {
279  unique.insert( it->GetNickName() );
280  }
281  }
282 
283  } while( ( cur = cur->fallBack ) != nullptr );
284 
285  ret.reserve( unique.size() );
286 
287  // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
288  for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
289  {
290  ret.push_back( *it );
291  }
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 lhs.CmpNoCase( rhs ) < 0;
298  } );
299 
300  return ret;
301 }
302 
303 
304 bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
305 {
306  std::lock_guard<std::recursive_mutex> lock( m_nickIndexMutex );
307 
308  ensureIndex();
309 
310  INDEX_CITER it = nickIndex.find( aRow->GetNickName() );
311 
312  if( it == nickIndex.end() )
313  {
314  rows.push_back( aRow );
315  nickIndex.insert( INDEX_VALUE( aRow->GetNickName(), rows.size() - 1 ) );
316  return true;
317  }
318 
319  if( doReplace )
320  {
321  rows.replace( it->second, aRow );
322  return true;
323  }
324 
325  return false;
326 }
327 
328 
329 void LIB_TABLE::Load( const wxString& aFileName )
330 
331 {
332  // It's OK if footprint library tables are missing.
333  if( wxFileName::IsFileReadable( aFileName ) )
334  {
335  FILE_LINE_READER reader( aFileName );
336  LIB_TABLE_LEXER lexer( &reader );
337 
338  Parse( &lexer );
339  }
340 }
341 
342 
343 void LIB_TABLE::Save( const wxString& aFileName ) const
344 {
345  FILE_OUTPUTFORMATTER sf( aFileName );
346  Format( &sf, 0 );
347 }
348 
349 
350 PROPERTIES* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
351 {
352  if( aOptionsList.size() )
353  {
354  const char* cp = &aOptionsList[0];
355  const char* end = cp + aOptionsList.size();
356 
357  PROPERTIES props;
358  std::string pair;
359 
360  // Parse all name=value pairs
361  while( cp < end )
362  {
363  pair.clear();
364 
365  // Skip leading white space.
366  while( cp < end && isspace( *cp ) )
367  ++cp;
368 
369  // Find the end of pair/field
370  while( cp < end )
371  {
372  if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
373  {
374  ++cp; // skip the escape
375  pair += *cp++; // add the separator
376  }
377  else if( *cp == OPT_SEP )
378  {
379  ++cp; // skip the separator
380  break; // process the pair
381  }
382  else
383  pair += *cp++;
384  }
385 
386  // stash the pair
387  if( pair.size() )
388  {
389  // first equals sign separates 'name' and 'value'.
390  size_t eqNdx = pair.find( '=' );
391 
392  if( eqNdx != pair.npos )
393  {
394  std::string name = pair.substr( 0, eqNdx );
395  std::string value = pair.substr( eqNdx + 1 );
396  props[name] = value;
397  }
398  else
399  props[pair] = ""; // property is present, but with no value.
400  }
401  }
402 
403  if( props.size() )
404  return new PROPERTIES( props );
405  }
406 
407  return nullptr;
408 }
409 
410 
412 {
413  UTF8 ret;
414 
415  if( aProperties )
416  {
417  for( PROPERTIES::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
418  {
419  const std::string& name = it->first;
420 
421  const UTF8& value = it->second;
422 
423  if( ret.size() )
424  ret += OPT_SEP;
425 
426  ret += name;
427 
428  // the separation between name and value is '='
429  if( value.size() )
430  {
431  ret += '=';
432 
433  for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
434  {
435  // escape any separator in the value.
436  if( *si == OPT_SEP )
437  ret += '\\';
438 
439  ret += *si;
440  }
441  }
442  }
443  }
444 
445  return ret;
446 }
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition: utf8.h:70
void ensureIndex()
bool HasLibrary(const wxString &aNickname, bool aCheckEnabled=false) const
Test for the existence of aNickname in the library table.
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE.
std::vector< PROPERTY > PROPERTIES
Definition: specctra.h:192
bool InsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Adds aRow if it does not already exist or if doReplace is true.
INDEX::const_iterator INDEX_CITER
void setProperties(PROPERTIES *aProperties)
LIB_TABLE(LIB_TABLE *aFallBackTable=nullptr)
Build a library table by pre-pending this table fragment in front of aFallBackTable.
An interface used to output 8 bit text in a convenient way.
Definition: richio.h:309
LIB_TABLE_ROWS rows
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:267
A name/value tuple with unique names and optional values.
Definition: properties.h:33
bool operator==(const LIB_TABLE_ROW &r) const
LIB_TABLE * fallBack
static UTF8 FormatOptions(const PROPERTIES *aProperties)
Returns a list of options from the aProperties parameter.
This file contains miscellaneous commonly used macros and functions.
INDEX::value_type INDEX_VALUE
const wxString & GetDescr() const
Return the description of the library referenced by this row.
virtual ~LIB_TABLE()
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...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:96
const wxString & GetNickName() const
static PROPERTIES * ParseOptions(const std::string &aOptionsList)
Parses aOptionsList and places the result into a PROPERTIES object which is returned.
A LINE_READER that reads from an open file.
Definition: richio.h:172
LIB_TABLE_ROW * clone() const
bool GetIsEnabled() const
LIB_TABLE_ROW * new_clone(const LIB_TABLE_ROW &aRow)
Allows boost pointer containers to make clones of the data stored in them.
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 wxString GetDescription(const wxString &aNickname)
wxString GetFullURI(const wxString &aLibNickname, bool aExpandEnvVars=true) const
Return the full URI of the library mapped to aLibNickname.
const LIB_TABLE_ROW * FindRowByURI(const wxString &aURI)
virtual void Format(OUTPUTFORMATTER *aOutput, int aIndentLevel) const =0
Generate the table in s-expression format to aOutput with an indentation level of aIndentLevel.
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,...
void Load(const wxString &aFileName)
Load the library table using the path defined by aFileName aFallBackTable.
E_SERIE r
Definition: eserie.cpp:41
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...
void SetFullURI(const wxString &aFullURI)
Change the full URI for the library.
LIB_TABLE_ROWS::const_iterator LIB_TABLE_ROWS_CITER
const char * name
Definition: DXF_plotter.cpp:56
std::string::const_iterator end() const
Definition: utf8.h:193
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
The common library.
Used for text file output.
Definition: richio.h:456
void SetOptions(const wxString &aOptions)
Change the library options strings.
std::string::const_iterator begin() const
Definition: utf8.h:192
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:426
std::string::size_type size() const
Definition: utf8.h:110
std::recursive_mutex m_nickIndexMutex
Mutex to protect access to the nickIndex variable.
INDEX nickIndex
this particular key is the nickName within each row.
bool IsEmpty(bool aIncludeFallback=true)
Return true if the table is empty.
std::vector< wxString > GetLogicalLibs()
Return the logical library names, all of them that are pertinent to a look up done on this LIB_TABLE.
#define OPT_SEP
options separator character
std::string Quotew(const wxString &aWrapee) const
Definition: richio.cpp:494
Manage LIB_TABLE_ROW records (rows), and can be searched based on library nickname.