You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

654 lines
16 KiB

11 months ago
  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 The 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. #include <wx/debug.h>
  26. #include <wx/filename.h>
  27. #include <set>
  28. #include <common.h>
  29. #include <kiface_base.h>
  30. #include <lib_table_base.h>
  31. #include <lib_table_lexer.h>
  32. #include <macros.h>
  33. #include <string_utils.h>
  34. #include <build_version.h>
  35. #define OPT_SEP '|' ///< options separator character
  36. using namespace LIB_TABLE_T;
  37. std::unique_ptr<LINE_READER> FILE_LIB_TABLE_IO::GetReader( const wxString& aURI ) const
  38. {
  39. const wxFileName fn( aURI );
  40. if( !fn.IsOk() || !fn.IsFileReadable() )
  41. return nullptr;
  42. return std::make_unique<FILE_LINE_READER>( aURI );
  43. }
  44. bool FILE_LIB_TABLE_IO::CanSaveToUri( const wxString& aURI ) const
  45. {
  46. const wxFileName fn( aURI );
  47. if( !fn.IsOk() )
  48. return false;
  49. return fn.IsFileWritable();
  50. }
  51. bool FILE_LIB_TABLE_IO::UrisAreEquivalent( const wxString& aURI1, const wxString& aURI2 ) const
  52. {
  53. // Avoid comparing filenames as wxURIs
  54. if( aURI1.Find( "://" ) != wxNOT_FOUND )
  55. {
  56. // found as full path
  57. return aURI1 == aURI2;
  58. }
  59. else
  60. {
  61. const wxFileName fn1( aURI1 );
  62. const wxFileName fn2( aURI2 );
  63. // This will also test if the file is a symlink so if we are comparing
  64. // a symlink to the same real file, the comparison will be true. See
  65. // wxFileName::SameAs() in the wxWidgets source.
  66. // found as full path and file name
  67. return fn1 == fn2;
  68. }
  69. }
  70. std::unique_ptr<OUTPUTFORMATTER> FILE_LIB_TABLE_IO::GetWriter( const wxString& aURI ) const
  71. {
  72. const wxFileName fn( aURI );
  73. return std::make_unique<FILE_OUTPUTFORMATTER>( aURI );
  74. }
  75. LIB_TABLE_ROW* new_clone( const LIB_TABLE_ROW& aRow )
  76. {
  77. return aRow.clone();
  78. }
  79. void LIB_TABLE_ROW::setProperties( std::map<std::string, UTF8>* aProperties )
  80. {
  81. properties.reset( aProperties );
  82. }
  83. void LIB_TABLE_ROW::SetFullURI( const wxString& aFullURI )
  84. {
  85. uri_user = aFullURI;
  86. }
  87. const wxString LIB_TABLE_ROW::GetFullURI( bool aSubstituted ) const
  88. {
  89. if( aSubstituted )
  90. {
  91. return ExpandEnvVarSubstitutions( uri_user, nullptr );
  92. }
  93. return uri_user;
  94. }
  95. void LIB_TABLE_ROW::Format( OUTPUTFORMATTER* out, int nestLevel ) const
  96. {
  97. // In KiCad, we save path and file names using the Unix notation (separator = '/')
  98. // So ensure separator is always '/' is saved URI string
  99. wxString uri = GetFullURI();
  100. uri.Replace( '\\', '/' );
  101. wxString extraOptions;
  102. if( !GetIsEnabled() )
  103. extraOptions += "(disabled)";
  104. if( !GetIsVisible() )
  105. extraOptions += "(hidden)";
  106. out->Print( nestLevel, "(lib (name %s)(type %s)(uri %s)(options %s)(descr %s)%s)\n",
  107. out->Quotew( GetNickName() ).c_str(),
  108. out->Quotew( GetType() ).c_str(),
  109. out->Quotew( uri ).c_str(),
  110. out->Quotew( GetOptions() ).c_str(),
  111. out->Quotew( GetDescr() ).c_str(),
  112. extraOptions.ToStdString().c_str() );
  113. }
  114. bool LIB_TABLE_ROW::operator==( const LIB_TABLE_ROW& r ) const
  115. {
  116. return nickName == r.nickName
  117. && uri_user == r.uri_user
  118. && options == r.options
  119. && description == r.description
  120. && enabled == r.enabled
  121. && visible == r.visible;
  122. }
  123. void LIB_TABLE_ROW::SetOptions( const wxString& aOptions )
  124. {
  125. options = aOptions;
  126. // set PROPERTIES* from options
  127. setProperties( LIB_TABLE::ParseOptions( TO_UTF8( aOptions ) ) );
  128. }
  129. LIB_TABLE::LIB_TABLE( LIB_TABLE* aFallBackTable, std::unique_ptr<LIB_TABLE_IO> aTableIo ) :
  130. m_io( std::move( aTableIo ) ),
  131. m_fallBack( aFallBackTable ),
  132. m_version( 0 )
  133. {
  134. // If not given, use the default file-based I/O.
  135. if( !m_io )
  136. m_io = std::make_unique<FILE_LIB_TABLE_IO>();
  137. // not copying fall back, simply search aFallBackTable separately
  138. // if "nickName not found".
  139. }
  140. LIB_TABLE::~LIB_TABLE()
  141. {
  142. // *fallBack is not owned here.
  143. }
  144. void LIB_TABLE::clear()
  145. {
  146. m_rows.clear();
  147. m_rowsMap.clear();
  148. }
  149. bool LIB_TABLE::IsEmpty( bool aIncludeFallback )
  150. {
  151. if( !aIncludeFallback || !m_fallBack )
  152. return m_rows.empty();
  153. return m_rows.empty() && m_fallBack->IsEmpty( true );
  154. }
  155. const wxString LIB_TABLE::GetDescription( const wxString& aNickname )
  156. {
  157. // Use "no exception" form of find row and ignore disabled flag.
  158. const LIB_TABLE_ROW* row = findRow( aNickname );
  159. if( row )
  160. return row->GetDescr();
  161. else
  162. return wxEmptyString;
  163. }
  164. bool LIB_TABLE::HasLibrary( const wxString& aNickname, bool aCheckEnabled ) const
  165. {
  166. const LIB_TABLE_ROW* row = findRow( aNickname, aCheckEnabled );
  167. if( row == nullptr )
  168. return false;
  169. return true;
  170. }
  171. bool LIB_TABLE::HasLibraryWithPath( const wxString& aPath ) const
  172. {
  173. for( const LIB_TABLE_ROW& row : m_rows )
  174. {
  175. if( row.GetFullURI() == aPath )
  176. return true;
  177. }
  178. return false;
  179. }
  180. wxString LIB_TABLE::GetFullURI( const wxString& aNickname, bool aExpandEnvVars ) const
  181. {
  182. const LIB_TABLE_ROW* row = findRow( aNickname, true );
  183. wxString retv;
  184. if( row )
  185. retv = row->GetFullURI( aExpandEnvVars );
  186. return retv;
  187. }
  188. LIB_TABLE_ROW* LIB_TABLE::findRow( const wxString& aNickName, bool aCheckIfEnabled ) const
  189. {
  190. LIB_TABLE_ROW* row = nullptr;
  191. LIB_TABLE* cur = (LIB_TABLE*) this;
  192. do
  193. {
  194. std::shared_lock<std::shared_mutex> lock( cur->m_mutex );
  195. if( cur->m_rowsMap.count( aNickName ) )
  196. row = &*cur->m_rowsMap.at( aNickName );
  197. if( row )
  198. {
  199. if( !aCheckIfEnabled || row->GetIsEnabled() )
  200. return row;
  201. else
  202. return nullptr; // We found it, but it's disabled
  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, LIB_TABLE_ROWS_ITER>& entry : cur->m_rowsMap )
  207. {
  208. wxString legacyLibName = entry.first;
  209. legacyLibName.Replace( " ", "_" );
  210. if( legacyLibName == aNickName )
  211. {
  212. row = &*entry.second;
  213. if( !aCheckIfEnabled || row->GetIsEnabled() )
  214. return row;
  215. }
  216. }
  217. // not found, search fall back table(s), if any
  218. } while( ( cur = cur->m_fallBack ) != nullptr );
  219. return nullptr; // not found
  220. }
  221. const LIB_TABLE_ROW* LIB_TABLE::FindRowByURI( const wxString& aURI )
  222. {
  223. LIB_TABLE* cur = this;
  224. do
  225. {
  226. for( unsigned i = 0; i < cur->m_rows.size(); i++ )
  227. {
  228. const wxString tmp = cur->m_rows[i].GetFullURI( true );
  229. if( m_io->UrisAreEquivalent( tmp, aURI ) )
  230. return &cur->m_rows[i];
  231. }
  232. // not found, search fall back table(s), if any
  233. } while( ( cur = cur->m_fallBack ) != nullptr );
  234. return nullptr; // not found
  235. }
  236. std::vector<wxString> LIB_TABLE::GetLogicalLibs()
  237. {
  238. // Only return unique logical library names. Use std::set::insert() to quietly reject any
  239. // duplicates (usually due to encountering a duplicate nickname in a fallback table).
  240. std::set<wxString> unique;
  241. std::vector<wxString> ret;
  242. const LIB_TABLE* cur = this;
  243. do
  244. {
  245. for( const LIB_TABLE_ROW& row : cur->m_rows )
  246. {
  247. if( row.GetIsEnabled() )
  248. unique.insert( row.GetNickName() );
  249. }
  250. } while( ( cur = cur->m_fallBack ) != nullptr );
  251. ret.reserve( unique.size() );
  252. // return a sorted, unique set of nicknames in a std::vector<wxString> to caller
  253. for( std::set< wxString >::const_iterator it = unique.begin(); it!=unique.end(); ++it )
  254. ret.push_back( *it );
  255. // We want to allow case-sensitive duplicates but sort by case-insensitive ordering
  256. std::sort( ret.begin(), ret.end(),
  257. []( const wxString& lhs, const wxString& rhs )
  258. {
  259. return StrNumCmp( lhs, rhs, true /* ignore case */ ) < 0;
  260. } );
  261. return ret;
  262. }
  263. bool LIB_TABLE::InsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
  264. {
  265. std::lock_guard<std::shared_mutex> lock( m_mutex );
  266. doInsertRow( aRow, doReplace );
  267. reindex();
  268. return true;
  269. }
  270. bool LIB_TABLE::doInsertRow( LIB_TABLE_ROW* aRow, bool doReplace )
  271. {
  272. auto it = m_rowsMap.find( aRow->GetNickName() );
  273. if( it != m_rowsMap.end() )
  274. {
  275. if( !doReplace )
  276. return false;
  277. m_rows.replace( it->second, aRow );
  278. }
  279. else
  280. {
  281. m_rows.push_back( aRow );
  282. }
  283. aRow->SetParent( this );
  284. reindex();
  285. return true;
  286. }
  287. bool LIB_TABLE::RemoveRow( const LIB_TABLE_ROW* aRow )
  288. {
  289. std::lock_guard<std::shared_mutex> lock( m_mutex );
  290. bool found = false;
  291. auto it = m_rowsMap.find( aRow->GetNickName() );
  292. if( it != m_rowsMap.end() )
  293. {
  294. if( &*it->second == aRow )
  295. {
  296. found = true;
  297. m_rows.erase( it->second );
  298. }
  299. }
  300. if( !found )
  301. {
  302. // Bookkeeping got messed up...
  303. for( int i = (int)m_rows.size() - 1; i >= 0; --i )
  304. {
  305. if( &m_rows[i] == aRow )
  306. {
  307. m_rows.erase( m_rows.begin() + i );
  308. found = true;
  309. break;
  310. }
  311. }
  312. }
  313. if( found )
  314. reindex();
  315. return found;
  316. }
  317. bool LIB_TABLE::ReplaceRow( size_t aIndex, LIB_TABLE_ROW* aRow )
  318. {
  319. std::lock_guard<std::shared_mutex> lock( m_mutex );
  320. if( aIndex >= m_rows.size() )
  321. return false;
  322. m_rowsMap.erase( m_rows[aIndex].GetNickName() );
  323. m_rows.replace( aIndex, aRow );
  324. reindex();
  325. return true;
  326. }
  327. bool LIB_TABLE::ChangeRowOrder( size_t aIndex, int aOffset )
  328. {
  329. std::lock_guard<std::shared_mutex> lock( m_mutex );
  330. if( aIndex >= m_rows.size() )
  331. return false;
  332. int newPos = static_cast<int>( aIndex ) + aOffset;
  333. if( newPos < 0 || newPos > static_cast<int>( m_rows.size() ) - 1 )
  334. return false;
  335. auto element = m_rows.release( m_rows.begin() + aIndex );
  336. m_rows.insert( m_rows.begin() + newPos, element.release() );
  337. reindex();
  338. return true;
  339. }
  340. void LIB_TABLE::TransferRows( LIB_TABLE_ROWS& aRowsList )
  341. {
  342. std::lock_guard<std::shared_mutex> lock( m_mutex );
  343. clear();
  344. m_rows.transfer( m_rows.end(), aRowsList.begin(), aRowsList.end(), aRowsList );
  345. reindex();
  346. }
  347. void LIB_TABLE::reindex()
  348. {
  349. m_rowsMap.clear();
  350. for( LIB_TABLE_ROWS_ITER it = m_rows.begin(); it != m_rows.end(); ++it )
  351. {
  352. it->SetParent( this );
  353. m_rowsMap[it->GetNickName()] = it;
  354. }
  355. }
  356. bool LIB_TABLE::migrate()
  357. {
  358. bool table_updated = false;
  359. for( LIB_TABLE_ROW& row : m_rows )
  360. {
  361. bool row_updated = false;
  362. wxString uri = row.GetFullURI( true );
  363. // If the uri still has a variable in it, that means that the user does not have
  364. // these vars defined. We update the old vars to the current versions on load
  365. static wxString fmtStr = wxS( "${KICAD%d_" );
  366. int version = 0;
  367. std::tie(version, std::ignore, std::ignore) = GetMajorMinorPatchTuple();
  368. for( int ii = 5; ii < version - 1; ++ii )
  369. {
  370. row_updated |= ( uri.Replace( wxString::Format( fmtStr, ii ),
  371. wxString::Format( fmtStr, version ), false ) > 0 );
  372. }
  373. if( row_updated )
  374. {
  375. row.SetFullURI( uri );
  376. table_updated = true;
  377. }
  378. }
  379. return table_updated;
  380. }
  381. void LIB_TABLE::Load( const wxString& aFileName )
  382. {
  383. std::lock_guard<std::shared_mutex> lock( m_mutex );
  384. clear();
  385. std::unique_ptr<LINE_READER> reader = m_io->GetReader( aFileName );
  386. // It's OK if footprint library tables are missing.
  387. if( reader )
  388. {
  389. LIB_TABLE_LEXER lexer( reader.get() );
  390. Parse( &lexer );
  391. if( m_version != 7 && migrate() && m_io->CanSaveToUri( aFileName ) )
  392. Save( aFileName );
  393. reindex();
  394. }
  395. }
  396. void LIB_TABLE::Save( const wxString& aFileName ) const
  397. {
  398. std::unique_ptr<OUTPUTFORMATTER> sf = m_io->GetWriter( aFileName );
  399. if( !sf )
  400. {
  401. THROW_IO_ERROR( wxString::Format( _( "Failed to get writer for %s" ), aFileName ) );
  402. }
  403. // Force the lib table version to 7 before saving
  404. m_version = 7;
  405. Format( sf.get(), 0 );
  406. }
  407. std::map<std::string, UTF8>* LIB_TABLE::ParseOptions( const std::string& aOptionsList )
  408. {
  409. if( aOptionsList.size() )
  410. {
  411. const char* cp = &aOptionsList[0];
  412. const char* end = cp + aOptionsList.size();
  413. std::map<std::string, UTF8> props;
  414. std::string pair;
  415. // Parse all name=value pairs
  416. while( cp < end )
  417. {
  418. pair.clear();
  419. // Skip leading white space.
  420. while( cp < end && isspace( *cp ) )
  421. ++cp;
  422. // Find the end of pair/field
  423. while( cp < end )
  424. {
  425. if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
  426. {
  427. ++cp; // skip the escape
  428. pair += *cp++; // add the separator
  429. }
  430. else if( *cp == OPT_SEP )
  431. {
  432. ++cp; // skip the separator
  433. break; // process the pair
  434. }
  435. else
  436. {
  437. pair += *cp++;
  438. }
  439. }
  440. // stash the pair
  441. if( pair.size() )
  442. {
  443. // first equals sign separates 'name' and 'value'.
  444. size_t eqNdx = pair.find( '=' );
  445. if( eqNdx != pair.npos )
  446. {
  447. std::string name = pair.substr( 0, eqNdx );
  448. std::string value = pair.substr( eqNdx + 1 );
  449. props[name] = value;
  450. }
  451. else
  452. {
  453. props[pair] = ""; // property is present, but with no value.
  454. }
  455. }
  456. }
  457. if( props.size() )
  458. return new std::map<std::string, UTF8>( props );
  459. }
  460. return nullptr;
  461. }
  462. UTF8 LIB_TABLE::FormatOptions( const std::map<std::string, UTF8>* aProperties )
  463. {
  464. UTF8 ret;
  465. if( aProperties )
  466. {
  467. for( std::map<std::string, UTF8>::const_iterator it = aProperties->begin();
  468. it != aProperties->end(); ++it )
  469. {
  470. const std::string& name = it->first;
  471. const UTF8& value = it->second;
  472. if( ret.size() )
  473. ret += OPT_SEP;
  474. ret += name;
  475. // the separation between name and value is '='
  476. if( value.size() )
  477. {
  478. ret += '=';
  479. for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
  480. {
  481. // escape any separator in the value.
  482. if( *si == OPT_SEP )
  483. ret += '\\';
  484. ret += *si;
  485. }
  486. }
  487. }
  488. }
  489. return ret;
  490. }