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_base.h>
31 #include <lib_table_base.h>
32 #include <lib_table_lexer.h>
33 #include <macros.h>
34 
35 
36 #define OPT_SEP     '|'         ///< options separator character
37 
38 
39 using namespace LIB_TABLE_T;
40 
41 
new_clone(const LIB_TABLE_ROW & aRow)42 LIB_TABLE_ROW* new_clone( const LIB_TABLE_ROW& aRow )
43 {
44     return aRow.clone();
45 }
46 
47 
setProperties(PROPERTIES * aProperties)48 void LIB_TABLE_ROW::setProperties( PROPERTIES* aProperties )
49 {
50     properties.reset( aProperties );
51 }
52 
53 
SetFullURI(const wxString & aFullURI)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 
GetFullURI(bool aSubstituted) const64 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 
Format(OUTPUTFORMATTER * out,int nestLevel) const80 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 
operator ==(const LIB_TABLE_ROW & r) const105 bool LIB_TABLE_ROW::operator==( const LIB_TABLE_ROW& r ) const
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 
SetOptions(const wxString & aOptions)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 
LIB_TABLE(LIB_TABLE * aFallBackTable)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 
~LIB_TABLE()132 LIB_TABLE::~LIB_TABLE()
133 {
134     // *fallBack is not owned here.
135 }
136 
137 
IsEmpty(bool aIncludeFallback)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 
GetDescription(const wxString & aNickname)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 
HasLibrary(const wxString & aNickname,bool aCheckEnabled) const159 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 
GetFullURI(const wxString & aNickname,bool aExpandEnvVars) const170 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 
findRow(const wxString & aNickName,bool aCheckIfEnabled) const183 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 
FindRowByURI(const wxString & aURI)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 
GetLogicalLibs()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 
InsertRow(LIB_TABLE_ROW * aRow,bool doReplace)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 
Load(const wxString & aFileName)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 
Save(const wxString & aFileName) const343 void LIB_TABLE::Save( const wxString& aFileName ) const
344 {
345     FILE_OUTPUTFORMATTER sf( aFileName );
346     Format( &sf, 0 );
347 }
348 
349 
ParseOptions(const std::string & aOptionsList)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 
FormatOptions(const PROPERTIES * aProperties)411 UTF8 LIB_TABLE::FormatOptions( const PROPERTIES* aProperties )
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 }
447