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-2017 Wayne Stambaugh <stambaughw@gmail.com>
6  * Copyright (C) 2012-2017 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 <wx/uri.h>
29 
30 #include <set>
31 
32 #include <fctsys.h>
33 #include <common.h>
34 #include <macros.h>
35 #include <kiface_i.h>
36 #include <lib_table_lexer.h>
37 #include <lib_table_base.h>
38 
39 
40 #define OPT_SEP '|'
41 
42 
43 using namespace LIB_TABLE_T;
44 
45 
47 {
48  return aRow.clone();
49 }
50 
51 
53 {
54  properties.reset( aProperties );
55 }
56 
57 
58 void LIB_TABLE_ROW::SetFullURI( const wxString& aFullURI )
59 {
60  uri_user = aFullURI;
61 
62 #if !FP_LATE_ENVVAR
63  uri_expanded = FP_LIB_TABLE::ExpandSubstitutions( aFullURI );
64 #endif
65 }
66 
67 
68 const wxString LIB_TABLE_ROW::GetFullURI( bool aSubstituted ) const
69 {
70  if( aSubstituted )
71  {
72 #if !FP_LATE_ENVVAR // early expansion
73  return uri_expanded;
74 
75 #else // late expansion
76  return LIB_TABLE::ExpandSubstitutions( uri_user );
77 #endif
78  }
79 
80  return uri_user;
81 }
82 
83 
84 void LIB_TABLE_ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const
85 {
86  // In Kicad, we save path and file names using the Unix notation (separator = '/')
87  // So ensure separator is always '/' is saved URI string
88  wxString uri = GetFullURI();
89  uri.Replace( '\\', '/' );
90 
91  wxString extraOptions;
92 
93  if( !GetIsEnabled() )
94  {
95  extraOptions += "(disabled)";
96  }
97 
98  out->Print( nestLevel, "(lib (name %s)(type %s)(uri %s)(options %s)(descr %s)%s)\n",
99  out->Quotew( GetNickName() ).c_str(),
100  out->Quotew( GetType() ).c_str(),
101  out->Quotew( uri ).c_str(),
102  out->Quotew( GetOptions() ).c_str(),
103  out->Quotew( GetDescr() ).c_str(),
104  extraOptions.ToStdString().c_str()
105  );
106 }
107 
108 
109 void LIB_TABLE_ROW::Parse( std::unique_ptr< LIB_TABLE_ROW >& aRow, LIB_TABLE_LEXER* in )
110 {
111  /*
112  * (lib (name NICKNAME)(descr DESCRIPTION)(type TYPE)(full_uri FULL_URI)(options OPTIONS))
113  *
114  * Elements after (name) are order independent.
115  */
116 
117  T tok = in->NextTok();
118 
119  if( tok != T_lib )
120  in->Expecting( T_lib );
121 
122  // (name NICKNAME)
123  in->NeedLEFT();
124 
125  if( ( tok = in->NextTok() ) != T_name )
126  in->Expecting( T_name );
127 
128  in->NeedSYMBOLorNUMBER();
129 
130  aRow->SetNickName( in->FromUTF8() );
131 
132  in->NeedRIGHT();
133 
134  // After (name), remaining (lib) elements are order independent, and in
135  // some cases optional.
136  bool sawType = false;
137  bool sawOpts = false;
138  bool sawDesc = false;
139  bool sawUri = false;
140 
141  while( ( tok = in->NextTok() ) != T_RIGHT )
142  {
143  if( tok == T_EOF )
144  in->Unexpected( T_EOF );
145 
146  if( tok != T_LEFT )
147  in->Expecting( T_LEFT );
148 
149  tok = in->NeedSYMBOLorNUMBER();
150 
151  switch( tok )
152  {
153  case T_uri:
154  if( sawUri )
155  in->Duplicate( tok );
156  sawUri = true;
157  in->NeedSYMBOLorNUMBER();
158  // Saved path and file names use the Unix notation (separator = '/')
159  // However old files, and files edited by hands can use the woindows
160  // separator. Force the unix notation
161  // (It works on windows, and moreover, wxFileName and wxDir takes care to that
162  // on windows)
163  // moreover, URLs use the '/' as separator
164  {
165  wxString uri = in->FromUTF8();
166  uri.Replace( '\\', '/' );
167  aRow->SetFullURI( uri );
168  }
169  break;
170 
171  case T_type:
172  if( sawType )
173  in->Duplicate( tok );
174  sawType = true;
175  in->NeedSYMBOLorNUMBER();
176  aRow->SetType( in->FromUTF8() );
177  break;
178 
179  case T_options:
180  if( sawOpts )
181  in->Duplicate( tok );
182  sawOpts = true;
183  in->NeedSYMBOLorNUMBER();
184  aRow->SetOptions( in->FromUTF8() );
185  break;
186 
187  case T_descr:
188  if( sawDesc )
189  in->Duplicate( tok );
190  sawDesc = true;
191  in->NeedSYMBOLorNUMBER();
192  aRow->SetDescr( in->FromUTF8() );
193  break;
194 
195  default:
196  in->Unexpected( tok );
197  }
198 
199  in->NeedRIGHT();
200  }
201 
202  if( !sawType )
203  in->Expecting( T_type );
204 
205  if( !sawUri )
206  in->Expecting( T_uri );
207 }
208 
209 
211 {
212  return nickName == r.nickName
213  && uri_user == r.uri_user
214  && options == r.options
215  && description == r.description
216  && enabled == r.enabled;
217 }
218 
219 
220 void LIB_TABLE_ROW::SetOptions( const wxString& aOptions )
221 {
222  options = aOptions;
223 
224  // set PROPERTIES* from options
225  setProperties( LIB_TABLE::ParseOptions( TO_UTF8( aOptions ) ) );
226 }
227 
228 
229 LIB_TABLE::LIB_TABLE( LIB_TABLE* aFallBackTable ) :
230  fallBack( aFallBackTable )
231 {
232  // not copying fall back, simply search aFallBackTable separately
233  // if "nickName not found".
234 }
235 
236 
238 {
239  // *fallBack is not owned here.
240 }
241 
242 
243 bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
244 {
245  if( !aIncludeFallback || !fallBack )
246  return rows.empty();
247 
248  return rows.empty() && fallBack->IsEmpty( true );
249 }
250 
251 
252 const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
253 {
254  // use "no exception" form of find row:
255  const LIB_TABLE_ROW* row = findRow( aNickname );
256 
257  if( row )
258  return row->GetDescr();
259  else
260  return wxEmptyString;
261 }
262 
263 
264 bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
265 {
266  const LIB_TABLE_ROW* row = findRow( aNickname );
267 
268  if( row == nullptr )
269  return false;
270 
271  if( aCheckEnabled && !row->GetIsEnabled() )
272  return false;
273 
274  return true;
275 }
276 
277 
278 wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
279 {
280  const LIB_TABLE_ROW* row = findRow( aNickname );
281 
282  wxString retv;
283 
284  if( row )
285  retv = row->GetFullURI( aExpandEnvVars );
286 
287  return retv;
288 }
289 
290 
291 LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName ) const
292 {
293  LIB_TABLE* cur = (LIB_TABLE*) this;
294 
295  do
296  {
297  cur->ensureIndex();
298 
299  INDEX_CITER it = cur->nickIndex.find( aNickName );
300 
301  if( it != cur->nickIndex.end() )
302  {
303  return &cur->rows[it->second]; // found
304  }
305 
306  // not found, search fall back table(s), if any
307  } while( ( cur = cur->fallBack ) != 0 );
308 
309  return NULL; // not found
310 }
311 
312 
313 LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName )
314 {
315  LIB_TABLE* cur = (LIB_TABLE*) this;
316 
317  do
318  {
319  cur->ensureIndex();
320 
321  INDEX_ITER it = cur->nickIndex.find( aNickName );
322 
323  if( it != cur->nickIndex.end() )
324  {
325  return &cur->rows[it->second]; // found
326  }
327 
328  // not found, search fall back table(s), if any
329  } while( ( cur = cur->fallBack ) != 0 );
330 
331  return NULL; // not found
332 }
333 
334 
335 const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
336 {
337  LIB_TABLE* cur = this;
338 
339  do
340  {
341  cur->ensureIndex();
342 
343  for( unsigned i = 0; i < cur->rows.size(); i++ )
344  {
345  wxString tmp = cur->rows[i].GetFullURI( true );
346 
347  if( tmp.Find( "://" ) != wxNOT_FOUND )
348  {
349  if( tmp == aURI )
350  return &cur->rows[i]; // found as URI
351  }
352  else
353  {
354  wxFileName fn = aURI;
355 
356  // This will also test if the file is a symlink so if we are comparing
357  // a symlink to the same real file, the comparison will be true. See
358  // wxFileName::SameAs() in the wxWidgets source.
359  if( fn == wxFileName( tmp ) )
360  return &cur->rows[i]; // found as full path and file name
361  }
362  }
363 
364  // not found, search fall back table(s), if any
365  } while( ( cur = cur->fallBack ) != 0 );
366 
367  return NULL; // not found
368 }
369 
370 
371 std::vector<wxString> LIB_TABLE::GetLogicalLibs()
372 {
373  // Only return unique logical library names. Use std::set::insert() to
374  // quietly reject any duplicates, which can happen when encountering a duplicate
375  // nickname from one of the fall back table(s).
376 
377  std::set< wxString > unique;
378  std::vector< wxString > ret;
379  const LIB_TABLE* cur = this;
380 
381  do
382  {
383  for( LIB_TABLE_ROWS_CITER it = cur->rows.begin(); it!=cur->rows.end(); ++it )
384  {
385  if( it->GetIsEnabled() )
386  {
387  unique.insert( it->GetNickName() );
388  }
389  }
390 
391  } while( ( cur = cur->fallBack ) != 0 );
392 
393  ret.reserve( unique.size() );
394 
395  // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
396  for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
397  {
398  ret.push_back( *it );
399  }
400 
401  return ret;
402 }
403 
404 
405 bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
406 {
407  ensureIndex();
408 
409  INDEX_CITER it = nickIndex.find( aRow->GetNickName() );
410 
411  if( it == nickIndex.end() )
412  {
413  rows.push_back( aRow );
414  nickIndex.insert( INDEX_VALUE( aRow->GetNickName(), rows.size() - 1 ) );
415  return true;
416  }
417 
418  if( doReplace )
419  {
420  rows.replace( it->second, aRow );
421  return true;
422  }
423 
424  return false;
425 }
426 
427 
428 void LIB_TABLE::Load( const wxString& aFileName )
429 
430 {
431  // It's OK if footprint library tables are missing.
432  if( wxFileName::IsFileReadable( aFileName ) )
433  {
434  FILE_LINE_READER reader( aFileName );
435  LIB_TABLE_LEXER lexer( &reader );
436 
437  Parse( &lexer );
438  }
439 }
440 
441 
442 void LIB_TABLE::Save( const wxString& aFileName ) const
443 {
444  FILE_OUTPUTFORMATTER sf( aFileName );
445  Format( &sf, 0 );
446 }
447 
448 
449 PROPERTIES* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
450 {
451  if( aOptionsList.size() )
452  {
453  const char* cp = &aOptionsList[0];
454  const char* end = cp + aOptionsList.size();
455 
456  PROPERTIES props;
457  std::string pair;
458 
459  // Parse all name=value pairs
460  while( cp < end )
461  {
462  pair.clear();
463 
464  // Skip leading white space.
465  while( cp < end && isspace( *cp ) )
466  ++cp;
467 
468  // Find the end of pair/field
469  while( cp < end )
470  {
471  if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
472  {
473  ++cp; // skip the escape
474  pair += *cp++; // add the separator
475  }
476  else if( *cp == OPT_SEP )
477  {
478  ++cp; // skip the separator
479  break; // process the pair
480  }
481  else
482  pair += *cp++;
483  }
484 
485  // stash the pair
486  if( pair.size() )
487  {
488  // first equals sign separates 'name' and 'value'.
489  size_t eqNdx = pair.find( '=' );
490 
491  if( eqNdx != pair.npos )
492  {
493  std::string name = pair.substr( 0, eqNdx );
494  std::string value = pair.substr( eqNdx + 1 );
495  props[name] = value;
496  }
497  else
498  props[pair] = ""; // property is present, but with no value.
499  }
500  }
501 
502  if( props.size() )
503  return new PROPERTIES( props );
504  }
505 
506  return NULL;
507 }
508 
509 
511 {
512  UTF8 ret;
513 
514  if( aProperties )
515  {
516  for( PROPERTIES::const_iterator it = aProperties->begin(); it != aProperties->end(); ++it )
517  {
518  const std::string& name = it->first;
519 
520  const UTF8& value = it->second;
521 
522  if( ret.size() )
523  ret += OPT_SEP;
524 
525  ret += name;
526 
527  // the separation between name and value is '='
528  if( value.size() )
529  {
530  ret += '=';
531 
532  for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
533  {
534  // escape any separator in the value.
535  if( *si == OPT_SEP )
536  ret += '\\';
537 
538  ret += *si;
539  }
540  }
541  }
542  }
543 
544  return ret;
545 }
546 
547 
548 const wxString LIB_TABLE::ExpandSubstitutions( const wxString& aString )
549 {
550  return ExpandEnvVarSubstitutions( aString );
551 }
Class UTF8 is an 8 bit string that is assuredly encoded in UTF8, and supplies special conversion supp...
Definition: utf8.h:73
void ensureIndex()
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE...
std::vector< PROPERTY > PROPERTIES
Definition: specctra.h:184
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 InsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Adds aRow if it does not already exist or if doReplace is true.
LIB_TABLE_ROW * clone() const
static const wxString ExpandSubstitutions(const wxString &aString)
Replaces any environment variable references with their values and is here to fully embellish the TAB...
bool enabled
Whether the LIB_TABLE_ROW is enabled.
INDEX::const_iterator INDEX_CITER
void setProperties(PROPERTIES *aProperties)
Class OUTPUTFORMATTER is an important interface (abstract class) used to output 8 bit text in a conve...
Definition: richio.h:327
LIB_TABLE_ROWS rows
std::string::size_type size() const
Definition: utf8.h:115
Class PROPERTIES is a name/value tuple with unique names and optional values.
Definition: properties.h:34
LIB_TABLE * fallBack
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...
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
virtual ~LIB_TABLE()
wxString description
#define TO_UTF8(wxstring)
Macro TO_UTF8 converts a wxString to a UTF8 encoded C string for all wxWidgets build modes...
Definition: macros.h:47
static PROPERTIES * ParseOptions(const std::string &aOptionsList)
Parses aOptionsList and places the result into a PROPERTIES object which is returned.
Class FILE_LINE_READER is a LINE_READER that reads from an open file.
Definition: richio.h:180
bool HasLibrary(const wxString &aNickname, bool aCheckEnabled=false) const
Test for the existence of aNickname in the library table.
const wxString ExpandEnvVarSubstitutions(const wxString &aString)
Replace any environment variable references with their values.
Definition: common.cpp:255
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)
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.
bool operator==(const LIB_TABLE_ROW &r) const
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
std::string Quotew(const wxString &aWrapee)
Definition: richio.cpp:482
std::string::const_iterator end() const
Definition: utf8.h:197
LIB_TABLE_ROW * findRow(const wxString &aNickname) 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.
const wxString & GetDescr() const
Return the description of the library referenced by this row.
std::string::const_iterator begin() const
Definition: utf8.h:196
wxString GetFullURI(const wxString &aLibNickname, bool aExpandEnvVars=true) const
Return the full URI of the library mapped to aLibNickname.
const wxString & GetNickName() const
void SetFullURI(const wxString &aFullURI)
Change the full URI for the library.
LIB_TABLE_ROWS::const_iterator LIB_TABLE_ROWS_CITER
INDEX::iterator INDEX_ITER
const char * name
Definition: DXF_plotter.cpp:61
wxString options
size_t i
Definition: json11.cpp:597
The common library.
static void Parse(std::unique_ptr< LIB_TABLE_ROW > &aRow, LIB_TABLE_LEXER *in)
Class FILE_OUTPUTFORMATTER may be used for text file output.
Definition: richio.h:492
LIB_TABLE(LIB_TABLE *aFallBackTable=NULL)
Build a library table by pre-pending this table fragment in front of aFallBackTable.
void SetOptions(const wxString &aOptions)
Change the library options strings.
wxString nickName
bool GetIsEnabled() const
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404
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
Manage LIB_TABLE_ROW records (rows), and can be searched based on library nickname.