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 <dick@softplc.com>
5  * Copyright (C) 2012 Wayne Stambaugh <stambaughw@gmail.com>
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_i.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  cur->ensureIndex();
191 
192  for( const std::pair<const wxString, int>& entry : cur->nickIndex )
193  {
194  if( entry.first == aNickName )
195  {
196  row = &cur->rows[entry.second];
197 
198  if( !aCheckIfEnabled || ( aCheckIfEnabled && row->GetIsEnabled() ) )
199  return row;
200  }
201  }
202 
203  // Repeat, this time looking for names that were "fixed" by legacy versions because
204  // the old eeschema file format didn't support spaces in tokens.
205  for( const std::pair<const wxString, int>& entry : cur->nickIndex )
206  {
207  wxString legacyLibName = entry.first;
208  legacyLibName.Replace( " ", "_" );
209 
210  if( legacyLibName == aNickName )
211  {
212  row = &cur->rows[entry.second];
213 
214  if( !aCheckIfEnabled || ( aCheckIfEnabled && row->GetIsEnabled() ) )
215  return row;
216  }
217  }
218 
219  // not found, search fall back table(s), if any
220  } while( ( cur = cur->fallBack ) != 0 );
221 
222  return nullptr; // not found
223 }
224 
225 
226 const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
227 {
228  LIB_TABLE* cur = this;
229 
230  do
231  {
232  cur->ensureIndex();
233 
234  for( unsigned i = 0; i < cur->rows.size(); i++ )
235  {
236  wxString tmp = cur->rows[i].GetFullURI( true );
237 
238  if( tmp.Find( "://" ) != wxNOT_FOUND )
239  {
240  if( tmp == aURI )
241  return &cur->rows[i]; // found as URI
242  }
243  else
244  {
245  wxFileName fn = aURI;
246 
247  // This will also test if the file is a symlink so if we are comparing
248  // a symlink to the same real file, the comparison will be true. See
249  // wxFileName::SameAs() in the wxWidgets source.
250  if( fn == wxFileName( tmp ) )
251  return &cur->rows[i]; // found as full path and file name
252  }
253  }
254 
255  // not found, search fall back table(s), if any
256  } while( ( cur = cur->fallBack ) != 0 );
257 
258  return nullptr; // not found
259 }
260 
261 
262 std::vector<wxString> LIB_TABLE::GetLogicalLibs()
263 {
264  // Only return unique logical library names. Use std::set::insert() to
265  // quietly reject any duplicates, which can happen when encountering a duplicate
266  // nickname from one of the fall back table(s).
267 
268  std::set< wxString > unique;
269  std::vector< wxString > ret;
270  const LIB_TABLE* cur = this;
271 
272  do
273  {
274  for( LIB_TABLE_ROWS_CITER it = cur->rows.begin(); it!=cur->rows.end(); ++it )
275  {
276  if( it->GetIsEnabled() )
277  {
278  unique.insert( it->GetNickName() );
279  }
280  }
281 
282  } while( ( cur = cur->fallBack ) != 0 );
283 
284  ret.reserve( unique.size() );
285 
286  // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
287  for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
288  {
289  ret.push_back( *it );
290  }
291 
292  // We want to allow case-sensitive duplicates but sort by case-insensitive ordering
293  std::sort( ret.begin(), ret.end(), []( const wxString& lhs, const wxString& rhs )
294  {
295  return lhs.CmpNoCase( rhs ) < 0;
296  } );
297 
298  return ret;
299 }
300 
301 
302 bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
303 {
304  ensureIndex();
305 
306  INDEX_CITER it = nickIndex.find( aRow->GetNickName() );
307 
308  if( it == nickIndex.end() )
309  {
310  rows.push_back( aRow );
311  nickIndex.insert( INDEX_VALUE( aRow->GetNickName(), rows.size() - 1 ) );
312  return true;
313  }
314 
315  if( doReplace )
316  {
317  rows.replace( it->second, aRow );
318  return true;
319  }
320 
321  return false;
322 }
323 
324 
325 void LIB_TABLE::Load( const wxString& aFileName )
326 
327 {
328  // It's OK if footprint library tables are missing.
329  if( wxFileName::IsFileReadable( aFileName ) )
330  {
331  FILE_LINE_READER reader( aFileName );
332  LIB_TABLE_LEXER lexer( &reader );
333 
334  Parse( &lexer );
335  }
336 }
337 
338 
339 void LIB_TABLE::Save( const wxString& aFileName ) const
340 {
341  FILE_OUTPUTFORMATTER sf( aFileName );
342  Format( &sf, 0 );
343 }
344 
345 
346 PROPERTIES* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
347 {
348  if( aOptionsList.size() )
349  {
350  const char* cp = &aOptionsList[0];
351  const char* end = cp + aOptionsList.size();
352 
353  PROPERTIES props;
354  std::string pair;
355 
356  // Parse all name=value pairs
357  while( cp < end )
358  {
359  pair.clear();
360 
361  // Skip leading white space.
362  while( cp < end && isspace( *cp ) )
363  ++cp;
364 
365  // Find the end of pair/field
366  while( cp < end )
367  {
368  if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
369  {
370  ++cp; // skip the escape
371  pair += *cp++; // add the separator
372  }
373  else if( *cp == OPT_SEP )
374  {
375  ++cp; // skip the separator
376  break; // process the pair
377  }
378  else
379  pair += *cp++;
380  }
381 
382  // stash the pair
383  if( pair.size() )
384  {
385  // first equals sign separates 'name' and 'value'.
386  size_t eqNdx = pair.find( '=' );
387 
388  if( eqNdx != pair.npos )
389  {
390  std::string name = pair.substr( 0, eqNdx );
391  std::string value = pair.substr( eqNdx + 1 );
392  props[name] = value;
393  }
394  else
395  props[pair] = ""; // property is present, but with no value.
396  }
397  }
398 
399  if( props.size() )
400  return new PROPERTIES( props );
401  }
402 
403  return nullptr;
404 }
405 
406 
408 {
409  UTF8 ret;
410 
411  if( aProperties )
412  {
413  for( PROPERTIES::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
414  {
415  const std::string& name = it->first;
416 
417  const UTF8& value = it->second;
418 
419  if( ret.size() )
420  ret += OPT_SEP;
421 
422  ret += name;
423 
424  // the separation between name and value is '='
425  if( value.size() )
426  {
427  ret += '=';
428 
429  for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
430  {
431  // escape any separator in the value.
432  if( *si == OPT_SEP )
433  ret += '\\';
434 
435  ret += *si;
436  }
437  }
438  }
439  }
440 
441  return ret;
442 }
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:183
bool InsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Adds aRow if it does not already exist or if doReplace is true.
bool enabled
Whether the LIB_TABLE_ROW is enabled.
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:306
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:269
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()
wxString description
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 indention 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.
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:59
wxString options
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:453
void SetOptions(const wxString &aOptions)
Change the library options strings.
wxString nickName
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:408
std::string::size_type size() const
Definition: utf8.h:110
wxString uri_user
what user entered from UI or loaded from disk
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:476
Manage LIB_TABLE_ROW records (rows), and can be searched based on library nickname.