KiCad PCB EDA Suite
fp_lib_table.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-2019 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 <fctsys.h>
28 #include <kiface_i.h>
29 #include <footprint_info.h>
30 #include <lib_id.h>
31 #include <lib_table_lexer.h>
32 #include <pgm_base.h>
33 #include <search_stack.h>
35 #include <systemdirsappend.h>
36 #include <fp_lib_table.h>
37 #include <class_module.h>
38 
39 #define OPT_SEP '|'
40 
41 using namespace LIB_TABLE_T;
42 
43 
44 static const wxChar global_tbl_name[] = wxT( "fp-lib-table" );
45 
46 
48 {
49  return LIB_TABLE_ROW::operator == ( aRow ) && type == aRow.type;
50 }
51 
52 
53 void FP_LIB_TABLE_ROW::SetType( const wxString& aType )
54 {
55  type = IO_MGR::EnumFromStr( aType );
56 
57  if( IO_MGR::PCB_FILE_T( -1 ) == type )
58  type = IO_MGR::KICAD_SEXP;
59 
60  plugin.release();
61 }
62 
63 
65  LIB_TABLE( aFallBackTable )
66 {
67  // not copying fall back, simply search aFallBackTable separately
68  // if "nickName not found".
69 }
70 
71 
72 void FP_LIB_TABLE::Parse( LIB_TABLE_LEXER* in )
73 {
74  T tok;
75  wxString errMsg; // to collect error messages
76 
77  // This table may be nested within a larger s-expression, or not.
78  // Allow for parser of that optional containing s-epression to have looked ahead.
79  if( in->CurTok() != T_fp_lib_table )
80  {
81  in->NeedLEFT();
82 
83  if( ( tok = in->NextTok() ) != T_fp_lib_table )
84  in->Expecting( T_fp_lib_table );
85  }
86 
87  while( ( tok = in->NextTok() ) != T_RIGHT )
88  {
89  std::unique_ptr< FP_LIB_TABLE_ROW > row( new FP_LIB_TABLE_ROW );
90 
91  if( tok == T_EOF )
92  in->Expecting( T_RIGHT );
93 
94  if( tok != T_LEFT )
95  in->Expecting( T_LEFT );
96 
97  // in case there is a "row integrity" error, tell where later.
98  int lineNum = in->CurLineNumber();
99 
100  if( ( tok = in->NextTok() ) != T_lib )
101  in->Expecting( T_lib );
102 
103  // (name NICKNAME)
104  in->NeedLEFT();
105 
106  if( ( tok = in->NextTok() ) != T_name )
107  in->Expecting( T_name );
108 
109  in->NeedSYMBOLorNUMBER();
110 
111  row->SetNickName( in->FromUTF8() );
112 
113  in->NeedRIGHT();
114 
115  // After (name), remaining (lib) elements are order independent, and in
116  // some cases optional.
117  bool sawType = false;
118  bool sawOpts = false;
119  bool sawDesc = false;
120  bool sawUri = false;
121  bool sawDisabled = false;
122 
123  while( ( tok = in->NextTok() ) != T_RIGHT )
124  {
125  if( tok == T_EOF )
126  in->Unexpected( T_EOF );
127 
128  if( tok != T_LEFT )
129  in->Expecting( T_LEFT );
130 
131  tok = in->NeedSYMBOLorNUMBER();
132 
133  switch( tok )
134  {
135  case T_uri:
136  if( sawUri )
137  in->Duplicate( tok );
138  sawUri = true;
139  in->NeedSYMBOLorNUMBER();
140  row->SetFullURI( in->FromUTF8() );
141  break;
142 
143  case T_type:
144  if( sawType )
145  in->Duplicate( tok );
146  sawType = true;
147  in->NeedSYMBOLorNUMBER();
148  row->SetType( in->FromUTF8() );
149  break;
150 
151  case T_options:
152  if( sawOpts )
153  in->Duplicate( tok );
154  sawOpts = true;
155  in->NeedSYMBOLorNUMBER();
156  row->SetOptions( in->FromUTF8() );
157  break;
158 
159  case T_descr:
160  if( sawDesc )
161  in->Duplicate( tok );
162  sawDesc = true;
163  in->NeedSYMBOLorNUMBER();
164  row->SetDescr( in->FromUTF8() );
165  break;
166 
167  case T_disabled:
168  if( sawDisabled )
169  in->Duplicate( tok );
170  sawDisabled = true;
171  row->SetEnabled( false );
172  break;
173 
174  default:
175  in->Unexpected( tok );
176  }
177 
178  in->NeedRIGHT();
179  }
180 
181  if( !sawType )
182  in->Expecting( T_type );
183 
184  if( !sawUri )
185  in->Expecting( T_uri );
186 
187  // all nickNames within this table fragment must be unique, so we do not
188  // use doReplace in InsertRow(). (However a fallBack table can have a
189  // conflicting nickName and ours will supercede that one since in
190  // FindLib() we search this table before any fall back.)
191  wxString nickname = row->GetNickName(); // store it to be able to used it
192  // after row deletion if an error occurs
193  LIB_TABLE_ROW* tmp = row.release();
194 
195  if( !InsertRow( tmp ) )
196  {
197  delete tmp; // The table did not take ownership of the row.
198 
199  wxString msg = wxString::Format( _( "Duplicate library nickname \"%s\" found in "
200  "footprint library table file line %d" ),
201  nickname,
202  lineNum );
203 
204  if( !errMsg.IsEmpty() )
205  errMsg << '\n';
206 
207  errMsg << msg;
208  }
209  }
210 
211  if( !errMsg.IsEmpty() )
212  THROW_IO_ERROR( errMsg );
213 }
214 
215 
216 bool FP_LIB_TABLE::operator==( const FP_LIB_TABLE& aFpTable ) const
217 {
218  if( rows.size() == aFpTable.rows.size() )
219  {
220  for( unsigned i = 0; i < rows.size(); ++i )
221  {
222  if( (FP_LIB_TABLE_ROW&)rows[i] != (FP_LIB_TABLE_ROW&)aFpTable.rows[i] )
223  return false;
224  }
225 
226  return true;
227  }
228 
229  return false;
230 }
231 
232 
233 void FP_LIB_TABLE::Format( OUTPUTFORMATTER* aOutput, int aIndentLevel ) const
234 {
235  aOutput->Print( aIndentLevel, "(fp_lib_table\n" );
236 
237  for( LIB_TABLE_ROWS_CITER it = rows.begin(); it != rows.end(); ++it )
238  it->Format( aOutput, aIndentLevel+1 );
239 
240  aOutput->Print( aIndentLevel, ")\n" );
241 }
242 
243 
244 long long FP_LIB_TABLE::GenerateTimestamp( const wxString* aNickname )
245 {
246  if( aNickname )
247  {
248  const FP_LIB_TABLE_ROW* row = FindRow( *aNickname );
249  wxASSERT( (PLUGIN*) row->plugin );
250  return row->plugin->GetLibraryTimestamp( row->GetFullURI( true ) ) + wxHashTable::MakeKey( *aNickname );
251  }
252 
253  long long hash = 0;
254  for( wxString const& nickname : GetLogicalLibs() )
255  {
256  const FP_LIB_TABLE_ROW* row = FindRow( nickname );
257  wxASSERT( (PLUGIN*) row->plugin );
258  hash += row->plugin->GetLibraryTimestamp( row->GetFullURI( true ) ) + wxHashTable::MakeKey( nickname );
259  }
260 
261  return hash;
262 }
263 
264 
265 void FP_LIB_TABLE::FootprintEnumerate( wxArrayString& aFootprintNames, const wxString& aNickname,
266  bool aBestEfforts )
267 {
268  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
269  wxASSERT( (PLUGIN*) row->plugin );
270  row->plugin->FootprintEnumerate( aFootprintNames, row->GetFullURI( true ), aBestEfforts,
271  row->GetProperties() );
272 }
273 
274 
275 void FP_LIB_TABLE::PrefetchLib( const wxString& aNickname )
276 {
277  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
278  wxASSERT( (PLUGIN*) row->plugin );
279  row->plugin->PrefetchLib( row->GetFullURI( true ), row->GetProperties() );
280 }
281 
282 
283 const FP_LIB_TABLE_ROW* FP_LIB_TABLE::FindRow( const wxString& aNickname )
284 {
285  // Do not optimize this code. Is done this way specifically to fix a runtime
286  // error with clang 4.0.1.
287  LIB_TABLE_ROW* ltrow = findRow( aNickname );
288  FP_LIB_TABLE_ROW* row = dynamic_cast< FP_LIB_TABLE_ROW* >( ltrow );
289 
290  if( !row )
291  {
292  wxString msg = wxString::Format(
293  _( "fp-lib-table files contain no library with nickname \"%s\"" ),
294  aNickname );
295 
296  THROW_IO_ERROR( msg );
297  }
298 
299  // We've been 'lazy' up until now, but it cannot be deferred any longer,
300  // instantiate a PLUGIN of the proper kind if it is not already in this
301  // FP_LIB_TABLE_ROW.
302  if( !row->plugin )
303  row->setPlugin( IO_MGR::PluginFind( row->type ) );
304 
305  return row;
306 }
307 
308 
309 static void setLibNickname( MODULE* aModule,
310  const wxString& aNickname, const wxString& aFootprintName )
311 {
312  // The library cannot know its own name, because it might have been renamed or moved.
313  // Therefore footprints cannot know their own library nickname when residing in
314  // a footprint library.
315  // Only at this API layer can we tell the footprint about its actual library nickname.
316  if( aModule )
317  {
318  // remove "const"-ness, I really do want to set nickname without
319  // having to copy the LIB_ID and its two strings, twice each.
320  LIB_ID& fpid = (LIB_ID&) aModule->GetFPID();
321 
322  // Catch any misbehaving plugin, which should be setting internal footprint name properly:
323  wxASSERT( aFootprintName == fpid.GetLibItemName().wx_str() );
324 
325  // and clearing nickname
326  wxASSERT( !fpid.GetLibNickname().size() );
327 
328  fpid.SetLibNickname( aNickname );
329  }
330 }
331 
332 
333 const MODULE* FP_LIB_TABLE::GetEnumeratedFootprint( const wxString& aNickname,
334  const wxString& aFootprintName )
335 {
336  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
337  wxASSERT( (PLUGIN*) row->plugin );
338 
339  return row->plugin->GetEnumeratedFootprint( row->GetFullURI( true ), aFootprintName,
340  row->GetProperties() );
341 }
342 
343 
344 bool FP_LIB_TABLE::FootprintExists( const wxString& aNickname, const wxString& aFootprintName )
345 {
346  try
347  {
348  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
349  wxASSERT( (PLUGIN*) row->plugin );
350 
351  return row->plugin->FootprintExists( row->GetFullURI( true ), aFootprintName,
352  row->GetProperties() );
353  }
354  catch( ... )
355  {
356  return false;
357  }
358 }
359 
360 
361 MODULE* FP_LIB_TABLE::FootprintLoad( const wxString& aNickname, const wxString& aFootprintName )
362 {
363  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
364  wxASSERT( (PLUGIN*) row->plugin );
365 
366  MODULE* ret = row->plugin->FootprintLoad( row->GetFullURI( true ), aFootprintName,
367  row->GetProperties() );
368 
369  setLibNickname( ret, row->GetNickName(), aFootprintName );
370 
371  return ret;
372 }
373 
374 
376  const MODULE* aFootprint, bool aOverwrite )
377 {
378  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
379  wxASSERT( (PLUGIN*) row->plugin );
380 
381  if( !aOverwrite )
382  {
383  // Try loading the footprint to see if it already exists, caller wants overwrite
384  // protection, which is atypical, not the default.
385 
386  wxString fpname = aFootprint->GetFPID().GetLibItemName();
387 
388  std::unique_ptr<MODULE> footprint( row->plugin->FootprintLoad( row->GetFullURI( true ),
389  fpname, row->GetProperties() ) );
390 
391  if( footprint.get() )
392  return SAVE_SKIPPED;
393  }
394 
395  row->plugin->FootprintSave( row->GetFullURI( true ), aFootprint, row->GetProperties() );
396 
397  return SAVE_OK;
398 }
399 
400 
401 void FP_LIB_TABLE::FootprintDelete( const wxString& aNickname, const wxString& aFootprintName )
402 {
403  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
404  wxASSERT( (PLUGIN*) row->plugin );
405  return row->plugin->FootprintDelete( row->GetFullURI( true ), aFootprintName,
406  row->GetProperties() );
407 }
408 
409 
410 bool FP_LIB_TABLE::IsFootprintLibWritable( const wxString& aNickname )
411 {
412  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
413  wxASSERT( (PLUGIN*) row->plugin );
414  return row->plugin->IsFootprintLibWritable( row->GetFullURI( true ) );
415 }
416 
417 
418 void FP_LIB_TABLE::FootprintLibDelete( const wxString& aNickname )
419 {
420  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
421  wxASSERT( (PLUGIN*) row->plugin );
422  row->plugin->FootprintLibDelete( row->GetFullURI( true ), row->GetProperties() );
423 }
424 
425 
426 void FP_LIB_TABLE::FootprintLibCreate( const wxString& aNickname )
427 {
428  const FP_LIB_TABLE_ROW* row = FindRow( aNickname );
429  wxASSERT( (PLUGIN*) row->plugin );
430  row->plugin->FootprintLibCreate( row->GetFullURI( true ), row->GetProperties() );
431 }
432 
433 
435 {
436  wxString nickname = aFootprintId.GetLibNickname();
437  wxString fpname = aFootprintId.GetLibItemName();
438 
439  if( nickname.size() )
440  {
441  return FootprintLoad( nickname, fpname );
442  }
443 
444  // nickname is empty, sequentially search (alphabetically) all libs/nicks for first match:
445  else
446  {
447  std::vector<wxString> nicks = GetLogicalLibs();
448 
449  // Search each library going through libraries alphabetically.
450  for( unsigned i = 0; i < nicks.size(); ++i )
451  {
452  // FootprintLoad() returns NULL on not found, does not throw exception
453  // unless there's an IO_ERROR.
454  MODULE* ret = FootprintLoad( nicks[i], fpname );
455 
456  if( ret )
457  return ret;
458  }
459 
460  return NULL;
461  }
462 }
463 
464 
466 {
467  return "KISYSMOD";
468 }
469 
470 
472 {
473  bool tableExists = true;
474  wxFileName fn = GetGlobalTableFileName();
475 
476  if( !fn.FileExists() )
477  {
478  tableExists = false;
479 
480  if( !fn.DirExists() && !fn.Mkdir( 0x777, wxPATH_MKDIR_FULL ) )
481  {
482  THROW_IO_ERROR( wxString::Format( _( "Cannot create global library table path \"%s\"." ),
483  fn.GetPath() ) );
484  }
485 
486  // Attempt to copy the default global file table from the KiCad
487  // template folder to the user's home configuration path.
488  SEARCH_STACK ss;
489 
490  SystemDirsAppend( &ss );
491 
492  wxString templatePath =
493  Pgm().GetLocalEnvVariables().at( wxT( "KICAD_TEMPLATE_DIR" ) ).GetValue();
494 
495  if( !templatePath.IsEmpty() )
496  ss.AddPaths( templatePath, 0 );
497 
498  wxString fileName = ss.FindValidPath( global_tbl_name );
499 
500  // The fallback is to create an empty global footprint table for the user to populate.
501  if( fileName.IsEmpty() || !::wxCopyFile( fileName, fn.GetFullPath(), false ) )
502  {
503  FP_LIB_TABLE emptyTable;
504 
505  emptyTable.Save( fn.GetFullPath() );
506  }
507  }
508 
509  aTable.Load( fn.GetFullPath() );
510 
511  return tableExists;
512 }
513 
514 
516 {
517  wxFileName fn;
518 
520  fn.SetName( global_tbl_name );
521 
522  return fn.GetFullPath();
523 }
void setPlugin(PLUGIN *aPlugin)
Definition: fp_lib_table.h:93
static const wxChar global_tbl_name[]
bool IsFootprintLibWritable(const wxString &aNickname)
Function IsFootprintLibWritable.
wxString FindValidPath(const wxString &aFileName) const
Definition: search_stack.h:73
const UTF8 & GetLibItemName() const
Definition: lib_id.h:114
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:104
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE.
FP_LIB_TABLE_ROW.
Definition: fp_lib_table.h:42
bool InsertRow(LIB_TABLE_ROW *aRow, bool doReplace=false)
Adds aRow if it does not already exist or if doReplace is true.
MODULE * FootprintLoad(const wxString &aNickname, const wxString &aFootprintName)
Function FootprintLoad.
FP_LIB_TABLE(FP_LIB_TABLE *aFallBackTable=NULL)
Constructor FP_LIB_TABLE.
System directories search utilities.
OUTPUTFORMATTER is an important interface (abstract class) used to output 8 bit text in a convenient ...
Definition: richio.h:327
const LIB_ID & GetFPID() const
Definition: class_module.h:221
SEARCH_STACK looks for files in a number of places.
Definition: search_stack.h:41
LIB_TABLE_ROWS rows
A logical library item identifier and consists of various portions much like a URI.
Definition: lib_id.h:51
void FootprintLibDelete(const wxString &aNickname)
bool operator==(const LIB_TABLE_ROW &r) const
PLUGIN::RELEASER plugin
Definition: fp_lib_table.h:98
long long GenerateTimestamp(const wxString *aNickname)
Generate a hashed timestamp representing the last-mod-times of the library indicated by aNickname,...
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...
void FootprintEnumerate(wxArrayString &aFootprintNames, const wxString &aNickname, bool aBestEfforts)
Return a list of footprint names contained within the library given by aNickname.
const wxString & GetNickName() const
static const wxString GlobalPathEnvVariableName()
Function GlobalPathEnvVarVariableName.
virtual void Parse(LIB_TABLE_LEXER *aLexer) override
Parse the #LIB_TABLE_LEXER s-expression library table format into the appropriate LIB_TABLE_ROW objec...
#define NULL
static bool LoadGlobalTable(FP_LIB_TABLE &aTable)
Function LoadGlobalTable loads the global footprint library table into aTable.
const MODULE * GetEnumeratedFootprint(const wxString &aNickname, const wxString &aFootprintName)
Function GetEnumeratedFootprint.
static PCB_FILE_T EnumFromStr(const wxString &aFileType)
Function EnumFromStr returns the PCB_FILE_T from the corresponding plugin type name: "kicad",...
Definition: io_mgr.cpp:97
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition: lib_id.h:97
void PrefetchLib(const wxString &aNickname)
Function PrefetchLib If possible, prefetches the specified library (e.g.
void SystemDirsAppend(SEARCH_STACK *aSearchStack)
Function SystemDirsAppend appends system places to aSearchStack in a platform specific way,...
void Load(const wxString &aFileName)
Load the library table using the path defined by aFileName aFallBackTable.
virtual void Format(OUTPUTFORMATTER *aOutput, int aIndentLevel) const override
Generate the table in s-expression format to aOutput with an indention level of aIndentLevel.
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
int SetLibNickname(const UTF8 &aNickname)
Override the logical library name portion of the LIB_ID to aNickname.
Definition: lib_id.cpp:193
bool operator==(const FP_LIB_TABLE &aFpTable) const
void FootprintLibCreate(const wxString &aNickname)
const FP_LIB_TABLE_ROW * FindRow(const wxString &aNickName)
Function FindRow.
SAVE_T
Enum SAVE_T is the set of return values from FootprintSave() below.
Definition: fp_lib_table.h:212
see class PGM_BASE
LIB_TABLE_ROWS::const_iterator LIB_TABLE_ROWS_CITER
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:201
#define _(s)
Definition: 3d_actions.cpp:33
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,...
static PLUGIN * PluginFind(PCB_FILE_T aFileType)
Function PluginFind returns a PLUGIN which the caller can use to import, export, save,...
Definition: io_mgr.cpp:62
PLUGIN is a base class that BOARD loading and saving plugins should derive from.
Definition: io_mgr.h:274
wxString wx_str() const
Definition: utf8.cpp:51
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
static void setLibNickname(MODULE *aModule, const wxString &aNickname, const wxString &aFootprintName)
MODULE * FootprintLoadWithOptionalNickname(const LIB_ID &aFootprintId)
Function FootprintLoadWithOptionalNickname loads a footprint having aFootprintId with possibly an emp...
const PROPERTIES * GetProperties() const
Return the constant PROPERTIES for this library (LIB_TABLE_ROW).
void SetType(const wxString &aType) override
Function SetType.
int PRINTF_FUNC Print(int nestLevel, const char *fmt,...)
Function Print formats and writes text to the output stream.
Definition: richio.cpp:404
std::string::size_type size() const
Definition: utf8.h:115
SAVE_T FootprintSave(const wxString &aNickname, const MODULE *aFootprint, bool aOverwrite=true)
Function FootprintSave.
void FootprintDelete(const wxString &aNickname, const wxString &aFootprintName)
Function FootprintDelete.
PCB_FILE_T
Enum PCB_FILE_T is a set of file types that the IO_MGR knows about, and for which there has been a pl...
Definition: io_mgr.h:54
#define THROW_IO_ERROR(msg)
Definition: ki_exception.h:38
bool operator==(const FP_LIB_TABLE_ROW &aRow) const
void AddPaths(const wxString &aPaths, int aIndex=-1)
Function AddPaths insert or append path(s)
bool FootprintExists(const wxString &aNickname, const wxString &aFootprintName)
Function FootprintExists.
static wxString GetGlobalTableFileName()
Function GetGlobalTableFileName.
std::vector< wxString > GetLogicalLibs()
Return the logical library names, all of them that are pertinent to a look up done on this LIB_TABLE.
S-expression Pcbnew file format.
Definition: io_mgr.h:57
Manage LIB_TABLE_ROW records (rows), and can be searched based on library nickname.