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.

587 lines
15 KiB

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