KiCad PCB EDA Suite
Loading...
Searching...
No Matches
design_block_library_adapter.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 * @author Jon Evans <[email protected]>
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21
22#include "design_block.h"
23
24
26#include <design_block_io.h>
27#include <env_vars.h>
28#include <ki_exception.h>
29#include <thread_pool.h>
30#include <trace_helpers.h>
31
32#include <set>
33#include <magic_enum.hpp>
34#include <wx/log.h>
35
36
37std::map<wxString, LIB_DATA> DESIGN_BLOCK_LIBRARY_ADAPTER::GlobalLibraries;
38
40
41
46
47
49{
50 return ENV_VAR::GetVersionedEnvVarName( wxS( "DESIGN_BLOCK_DIR" ) );
51}
52
53
55{
56 DESIGN_BLOCK_IO* ret = dynamic_cast<DESIGN_BLOCK_IO*>( aRow->plugin.get() );
57 wxCHECK( aRow->plugin && ret, nullptr );
58 return ret;
59}
60
61
63{
64 // TODO(JE) do we maintain a precondition that URIs are absolute paths after expansion?
66
68 {
69 wxLogTrace( traceLibraries, "Sym: Plugin type %s is unknown!", row->Type() );
70 wxString msg =
71 wxString::Format( _( "Unknown library type %s " ), row->Type() );
72 return tl::unexpected( LIBRARY_ERROR( msg ) );
73 }
74
76 wxCHECK( plugin, tl::unexpected( LIBRARY_ERROR( _( "Internal error" ) ) ) );
77
78 return plugin;
79}
80
81
83{
84 // TODO(JE) library tables - how much of this can be shared with other library types?
85 // TODO(JE) any reason to clean these up earlier?
86 std::erase_if( m_futures,
87 []( const std::future<void>& aFuture ) { return aFuture.valid(); } );
88
89 if( !m_futures.empty() )
90 {
91 wxLogTrace( traceLibraries, "DB: Cannot AsyncLoad, futures from a previous call remain!" );
92 return;
93 }
94
95 std::vector<LIBRARY_TABLE_ROW*> rows = m_manager.Rows( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
96
97 m_loadTotal = rows.size();
98 m_loadCount.store( 0 );
99
100 if( m_loadTotal == 0 )
101 {
102 wxLogTrace( traceLibraries, "DB: AsyncLoad: no libraries left to load; exiting" );
103 std::lock_guard lock( GlobalLibraryMutex );
104 std::lock_guard projectLock( m_libraries_mutex );
105 GlobalLibraries.clear();
106 m_libraries.clear();
107 return;
108 }
109
111
112 auto check =
113 []( const wxString& aLib, std::map<wxString, LIB_DATA>& aMap, std::mutex& aMutex )
114 {
115 std::lock_guard lock( aMutex );
116
117 if( aMap.contains( aLib ) )
118 {
119 if( aMap[aLib].status.load_status == LOAD_STATUS::LOADED )
120 return true;
121
122 aMap.erase( aLib );
123 }
124
125 return false;
126 };
127
128 std::set<wxString> libNamesCurrentlyValid;
129
130 for( const LIBRARY_TABLE_ROW* row : rows )
131 {
132 LIBRARY_TABLE_SCOPE scope = row->Scope();
133 const wxString& nickname = row->Nickname();
134
135 libNamesCurrentlyValid.insert( nickname );
136
137 // TODO(JE) library tables -- check for modified global files
138 if( check( nickname, m_libraries, m_libraries_mutex ) )
139 {
140 --m_loadTotal;
141 continue;
142 }
143
144 if( check( nickname, GlobalLibraries, GlobalLibraryMutex ) )
145 {
146 --m_loadTotal;
147 continue;
148 }
149
150 m_futures.emplace_back( tp.submit_task(
151 [this, nickname, scope]()
152 {
153 if( m_abort.load() )
154 return;
155
156 LIBRARY_RESULT<LIB_DATA*> result = loadIfNeeded( nickname );
157
158 if( result.has_value() )
159 {
160 LIB_DATA* lib = *result;
161 wxArrayString dummyList;
162 std::lock_guard lock ( lib->mutex );
163 lib->status.load_status = LOAD_STATUS::LOADING;
164
165 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
166
167 try
168 {
169 plugin( lib )->DesignBlockEnumerate( dummyList, getUri( lib->row ), false, &options );
170 wxLogTrace( traceLibraries, "DB: %s: library enumerated %zu items", nickname, dummyList.size() );
171 lib->status.load_status = LOAD_STATUS::LOADED;
172 }
173 catch( IO_ERROR& e )
174 {
175 lib->status.load_status = LOAD_STATUS::LOAD_ERROR;
176 lib->status.error = LIBRARY_ERROR( { e.What() } );
177 wxLogTrace( traceLibraries, "DB: %s: plugin threw exception: %s", nickname, e.What() );
178 }
179 }
180 else
181 {
182 switch( scope )
183 {
184 case LIBRARY_TABLE_SCOPE::GLOBAL:
185 {
186 std::lock_guard lock( GlobalLibraryMutex );
187
188 GlobalLibraries[nickname].status = LIB_STATUS( {
189 .load_status = LOAD_STATUS::LOAD_ERROR,
190 .error = result.error()
191 } );
192
193 break;
194 }
195
196 case LIBRARY_TABLE_SCOPE::PROJECT:
197 {
198 wxLogTrace( traceLibraries, "DB: project library error: %s: %s", nickname, result.error().message );
199 std::lock_guard lock( m_libraries_mutex );
200
201 m_libraries[nickname].status = LIB_STATUS( {
202 .load_status = LOAD_STATUS::LOAD_ERROR,
203 .error = result.error()
204 } );
205
206 break;
207 }
208
209 default:
210 wxFAIL_MSG( "Unexpected library table scope" );
211 }
212 }
213
214 ++m_loadCount;
215 } ) );
216 }
217
218 // Cleanup libraries that were removed from the table
219 {
220 std::lock_guard lock( GlobalLibraryMutex );
221 std::erase_if( GlobalLibraries, [&]( const auto& pair )
222 {
223 return libNamesCurrentlyValid.contains( pair.first );
224 } );
225 }
226
227 {
228 std::lock_guard lock( m_libraries_mutex );
229 std::erase_if( m_libraries, [&]( const auto& pair )
230 {
231 return libNamesCurrentlyValid.contains( pair.first );
232 } );
233 }
234
235 if( m_loadTotal > 0 )
236 wxLogTrace( traceLibraries, "DB: Started async load of %zu libraries", m_loadTotal );
237}
238
239
240std::vector<DESIGN_BLOCK*> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlocks( const wxString& aNickname )
241{
242 std::vector<DESIGN_BLOCK*> blocks;
243
244 std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname );
245
246 if( !maybeLib )
247 return blocks;
248
249 const LIB_DATA* lib = *maybeLib;
250 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
251 wxArrayString blockNames;
252
253 try
254 {
255 plugin( lib )->DesignBlockEnumerate( blockNames, getUri( lib->row ), false, &options );
256 }
257 catch( IO_ERROR& e )
258 {
259 wxLogTrace( traceLibraries, "DB: Exception enumerating library %s: %s",
260 lib->row->Nickname(), e.What() );
261 }
262
263 for( const wxString& blockName : blockNames )
264 {
265 try
266 {
267 blocks.emplace_back( plugin( lib )->DesignBlockLoad( getUri( lib->row ), blockName, false, &options ) );
268 }
269 catch( IO_ERROR& e )
270 {
271 wxLogTrace( traceLibraries, "DB: Exception enumerating design block %s: %s", blockName, e.What() );
272 }
273 }
274
275 return blocks;
276}
277
278
279std::vector<wxString> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlockNames( const wxString& aNickname )
280{
281 // TODO(JE) can we kill wxArrayString in internal API?
282 wxArrayString namesAS;
283 std::vector<wxString> names;
284
285 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
286 {
287 const LIB_DATA* lib = *maybeLib;
288 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
289
290 plugin( lib )->DesignBlockEnumerate( namesAS, getUri( lib->row ), true, &options );
291 }
292
293 for( const wxString& name : namesAS )
294 names.emplace_back( name );
295
296 return names;
297}
298
299
301 const wxString& aDesignBlockName, bool aKeepUUID )
302{
303 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
304 {
305 const LIB_DATA* lib = *maybeLib;
306 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
307
308 DESIGN_BLOCK* db = plugin( lib )->DesignBlockLoad( getUri( lib->row ), aDesignBlockName, aKeepUUID, &options );
309 db->GetLibId().SetLibNickname( aNickname );
310 return db;
311 }
312
313 return nullptr;
314}
315
316
317bool DESIGN_BLOCK_LIBRARY_ADAPTER::DesignBlockExists( const wxString& aNickname, const wxString& aDesignBlockName )
318{
319 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
320 {
321 const LIB_DATA* lib = *maybeLib;
322 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
323
324 return plugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlockName, &options );
325 }
326
327 return false;
328}
329
330
332 const wxString& aDesignBlockName )
333{
334 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
335 {
336 const LIB_DATA* lib = *maybeLib;
337 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
338
339 return plugin( lib )->GetEnumeratedDesignBlock( getUri( lib->row ), aDesignBlockName, &options );
340 }
341
342 return nullptr;
343}
344
345
347 const DESIGN_BLOCK* aDesignBlock, bool aOverwrite )
348{
349 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
350 {
351 const LIB_DATA* lib = *maybeLib;
352 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
353
354 if( !aOverwrite && plugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlock->GetName(), &options ) )
355 return SAVE_SKIPPED;
356
357 plugin( lib )->DesignBlockSave( getUri( lib->row ), aDesignBlock, &options );
358 }
359
360 return SAVE_OK;
361}
362
363
365 const wxString& aDesignBlockName )
366{
367 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
368 {
369 const LIB_DATA* lib = *maybeLib;
370 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
371 return plugin( lib )->DesignBlockDelete( getUri( lib->row ), aDesignBlockName, &options );
372 }
373}
374
375
377{
378 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
379 {
380 const LIB_DATA* lib = *maybeLib;
381 return plugin( lib )->IsLibraryWritable( getUri( lib->row ) );
382 }
383
384 return false;
385}
386
387
389 bool aKeepUUID )
390{
391 wxString nickname = aDesignBlockId.GetLibNickname();
392 wxString DesignBlockname = aDesignBlockId.GetLibItemName();
393
394 if( nickname.size() )
395 return LoadDesignBlock( nickname, DesignBlockname, aKeepUUID );
396
397 // nickname is empty, sequentially search (alphabetically) all libs/nicks for first match:
398 for( const wxString& library : GetLibraryNames() )
399 {
400 // DesignBlockLoad() returns NULL on not found, does not throw exception
401 // unless there's an IO_ERROR.
402 if( DESIGN_BLOCK* ret = LoadDesignBlock( library, DesignBlockname, aKeepUUID ) )
403 return ret;
404 }
405
406 return nullptr;
407}
408
409
410std::optional<LIBRARY_ERROR> DESIGN_BLOCK_LIBRARY_ADAPTER::LibraryError( const wxString& aNickname ) const
411{
412 // TODO(JE) library tables
413 return std::nullopt;
414}
const char * name
@ DESIGN_BLOCK_FILE_UNKNOWN
0 is not a legal menu id on Mac
static DESIGN_BLOCK_FILE_T EnumFromStr(const wxString &aFileType)
static DESIGN_BLOCK_IO * FindPlugin(DESIGN_BLOCK_FILE_T aFileType)
bool DesignBlockExists(const wxString &aLibraryPath, const wxString &aDesignBlockName, const std::map< std::string, UTF8 > *aProperties=nullptr)
void DesignBlockDelete(const wxString &aLibraryPath, const wxString &aDesignBlockName, const std::map< std::string, UTF8 > *aProperties=nullptr)
DESIGN_BLOCK * DesignBlockLoad(const wxString &aLibraryPath, const wxString &aDesignBlockName, bool aKeepUUID=false, const std::map< std::string, UTF8 > *aProperties=nullptr)
void DesignBlockSave(const wxString &aLibraryPath, const DESIGN_BLOCK *aDesignBlock, const std::map< std::string, UTF8 > *aProperties=nullptr)
const DESIGN_BLOCK * GetEnumeratedDesignBlock(const wxString &aLibraryPath, const wxString &aDesignBlockName, const std::map< std::string, UTF8 > *aProperties=nullptr)
void DesignBlockEnumerate(wxArrayString &aDesignBlockNames, const wxString &aLibraryPath, bool aBestEfforts, const std::map< std::string, UTF8 > *aProperties=nullptr)
bool IsLibraryWritable(const wxString &aLibraryPath) override
Return true if the library at aLibraryPath is writable.
std::vector< wxString > GetDesignBlockNames(const wxString &aNickname)
SAVE_T
The set of return values from DesignBlockSave() below.
static DESIGN_BLOCK_IO * plugin(const LIB_DATA *aRow)
Helper to cast the ABC plugin in the LIB_DATA* to a concrete plugin.
std::vector< DESIGN_BLOCK * > GetDesignBlocks(const wxString &aNickname)
std::optional< LIBRARY_ERROR > LibraryError(const wxString &aNickname) const
void DeleteDesignBlock(const wxString &aNickname, const wxString &aDesignBlockName)
Delete the aDesignBlockName from the library given by aNickname.
LIBRARY_RESULT< IO_BASE * > createPlugin(const LIBRARY_TABLE_ROW *row) override
Creates a concrete plugin for the given row.
void AsyncLoad() override
Loads all available libraries for this adapter type in the background.
DESIGN_BLOCK * LoadDesignBlock(const wxString &aNickname, const wxString &aDesignBlockName, bool aKeepUUID=false)
Load a design block having aDesignBlockName from the library given by aNickname.
DESIGN_BLOCK * DesignBlockLoadWithOptionalNickname(const LIB_ID &aDesignBlockId, bool aKeepUUID=false)
Load a design block having aDesignBlockId with possibly an empty nickname.
SAVE_T SaveDesignBlock(const wxString &aNickname, const DESIGN_BLOCK *aDesignBlock, bool aOverwrite=true)
Write aDesignBlock to an existing library given by aNickname.
static std::map< wxString, LIB_DATA > GlobalLibraries
DESIGN_BLOCK_LIBRARY_ADAPTER(LIBRARY_MANAGER &aManager)
bool IsDesignBlockLibWritable(const wxString &aNickname)
Return true if the library given by aNickname is writable.
const DESIGN_BLOCK * GetEnumeratedDesignBlock(const wxString &aNickname, const wxString &aDesignBlockName)
A version of #DesignBlockLoad() for use after #DesignBlockEnumerate() for more efficient cache manage...
bool DesignBlockExists(const wxString &aNickname, const wxString &aDesignBlockName)
Indicates whether or not the given design block already exists in the given library.
const LIB_ID & GetLibId() const
wxString GetName() const override
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
LIBRARY_MANAGER_ADAPTER(LIBRARY_MANAGER &aManager)
Constructs a type-specific adapter into the library manager.
std::map< wxString, LIB_DATA > m_libraries
std::vector< wxString > GetLibraryNames() const
Returns a list of library nicknames that are available (skips any that failed to load)
std::vector< std::future< void > > m_futures
static wxString getUri(const LIBRARY_TABLE_ROW *aRow)
std::atomic< size_t > m_loadCount
LIBRARY_MANAGER & m_manager
std::optional< const LIB_DATA * > fetchIfLoaded(const wxString &aNickname) const
std::map< std::string, UTF8 > GetOptionsMap() const
const wxString & Type() const
const wxString & Nickname() const
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:49
int SetLibNickname(const UTF8 &aLibNickname)
Override the logical library name portion of the LIB_ID to aLibNickname.
Definition lib_id.cpp:100
const UTF8 & GetLibItemName() const
Definition lib_id.h:102
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:87
#define _(s)
Functions related to environment variables, including help functions.
const wxChar *const traceLibraries
Flag to enable library table and library manager tracing.
tl::expected< ResultType, LIBRARY_ERROR > LIBRARY_RESULT
LIBRARY_TABLE_SCOPE
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:77
Storage for an actual loaded library (including library content owned by the plugin)
std::unique_ptr< IO_BASE > plugin
const LIBRARY_TABLE_ROW * row
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::thread_pool< 0 > thread_pool
Definition thread_pool.h:31
wxLogTrace helper definitions.