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 = wxString::Format( _( "Unknown library type %s " ), row->Type() );
71 return tl::unexpected( LIBRARY_ERROR( msg ) );
72 }
73
75 wxCHECK( plugin, tl::unexpected( LIBRARY_ERROR( _( "Internal error" ) ) ) );
76
77 return plugin;
78}
79
80
82{
83 return dbplugin( aRow );
84}
85
86
88std::optional<LIB_STATUS> DESIGN_BLOCK_LIBRARY_ADAPTER::LoadOne( LIB_DATA* aLib )
89{
90 wxArrayString dummyList;
91 std::lock_guard lock ( aLib->mutex );
93
94 std::map<std::string, UTF8> options = aLib->row->GetOptionsMap();
95
96 try
97 {
98 dbplugin( aLib )->DesignBlockEnumerate( dummyList, getUri( aLib->row ), false, &options );
99 wxLogTrace( traceLibraries, "DB: %s: library enumerated %zu items", aLib->row->Nickname(), dummyList.size() );
101 }
102 catch( IO_ERROR& e )
103 {
105 aLib->status.error = LIBRARY_ERROR( { e.What() } );
106 wxLogTrace( traceLibraries, "DB: %s: plugin threw exception: %s", aLib->row->Nickname(), e.What() );
107 }
108
109 return aLib->status;
110}
111
112
114{
115 // TODO(JE) library tables - how much of this can be shared with other library types?
116 // TODO(JE) any reason to clean these up earlier?
117 std::erase_if( m_futures,
118 []( const std::future<void>& aFuture ) { return aFuture.valid(); } );
119
120 if( !m_futures.empty() )
121 {
122 wxLogTrace( traceLibraries, "DB: Cannot AsyncLoad, futures from a previous call remain!" );
123 return;
124 }
125
126 std::vector<LIBRARY_TABLE_ROW*> rows = m_manager.Rows( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
127
128 m_loadTotal = rows.size();
129 m_loadCount.store( 0 );
130
131 if( m_loadTotal == 0 )
132 {
133 wxLogTrace( traceLibraries, "DB: AsyncLoad: no libraries left to load; exiting" );
134 return;
135 }
136
138
139 auto check =
140 []( const wxString& aLib, std::map<wxString, LIB_DATA>& aMap, std::mutex& aMutex )
141 {
142 std::lock_guard lock( aMutex );
143
144 if( aMap.contains( aLib ) )
145 {
146 if( aMap[aLib].status.load_status == LOAD_STATUS::LOADED )
147 return true;
148
149 aMap.erase( aLib );
150 }
151
152 return false;
153 };
154
155 std::set<wxString> libNamesCurrentlyValid;
156
157 for( const LIBRARY_TABLE_ROW* row : rows )
158 {
159 LIBRARY_TABLE_SCOPE scope = row->Scope();
160 const wxString& nickname = row->Nickname();
161
162 libNamesCurrentlyValid.insert( nickname );
163
164 // TODO(JE) library tables -- check for modified global files
165 if( check( nickname, m_libraries, m_libraries_mutex ) )
166 {
167 --m_loadTotal;
168 continue;
169 }
170
171 if( check( nickname, GlobalLibraries, GlobalLibraryMutex ) )
172 {
173 --m_loadTotal;
174 continue;
175 }
176
177 m_futures.emplace_back( tp.submit_task(
178 [this, nickname, scope]()
179 {
180 if( m_abort.load() )
181 return;
182
183 LIBRARY_RESULT<LIB_DATA*> result = loadIfNeeded( nickname );
184
185 if( result.has_value() )
186 {
187 std::optional<LIB_STATUS> loadResult = LoadOne( *result );
188
189 // for design blocks, LoadOne should always return something
190 wxCHECK2( loadResult, ++m_loadCount; return );
191
192 switch( scope )
193 {
194 case LIBRARY_TABLE_SCOPE::GLOBAL:
195 {
196 std::lock_guard lock( GlobalLibraryMutex );
197 GlobalLibraries[nickname].status = *loadResult;
198 break;
199 }
200
201 case LIBRARY_TABLE_SCOPE::PROJECT:
202 {
203 std::lock_guard lock( m_libraries_mutex );
204 m_libraries[nickname].status = *loadResult;
205 break;
206 }
207
208 default:
209 wxFAIL_MSG( "Unexpected library table scope" );
210 }
211 }
212 else
213 {
214 switch( scope )
215 {
216 case LIBRARY_TABLE_SCOPE::GLOBAL:
217 {
218 std::lock_guard lock( GlobalLibraryMutex );
219
220 GlobalLibraries[nickname].status = LIB_STATUS( {
221 .load_status = LOAD_STATUS::LOAD_ERROR,
222 .error = result.error()
223 } );
224
225 break;
226 }
227
228 case LIBRARY_TABLE_SCOPE::PROJECT:
229 {
230 wxLogTrace( traceLibraries, "DB: project library error: %s: %s", nickname, result.error().message );
231 std::lock_guard lock( m_libraries_mutex );
232
233 m_libraries[nickname].status = LIB_STATUS( {
234 .load_status = LOAD_STATUS::LOAD_ERROR,
235 .error = result.error()
236 } );
237
238 break;
239 }
240
241 default:
242 wxFAIL_MSG( "Unexpected library table scope" );
243 }
244 }
245
246 ++m_loadCount;
247 }, BS::pr::lowest ) );
248 }
249
250 // Cleanup libraries that were removed from the table
251 {
252 std::lock_guard lock( GlobalLibraryMutex );
253 std::erase_if( GlobalLibraries, [&]( const auto& pair )
254 {
255 return !libNamesCurrentlyValid.contains( pair.first );
256 } );
257 }
258
259 {
260 std::lock_guard lock( m_libraries_mutex );
261 std::erase_if( m_libraries, [&]( const auto& pair )
262 {
263 return !libNamesCurrentlyValid.contains( pair.first );
264 } );
265 }
266
267 if( m_loadTotal > 0 )
268 wxLogTrace( traceLibraries, "DB: Started async load of %zu libraries", m_loadTotal );
269}
270
271
272std::vector<DESIGN_BLOCK*> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlocks( const wxString& aNickname )
273{
274 std::vector<DESIGN_BLOCK*> blocks;
275
276 std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname );
277
278 if( !maybeLib )
279 return blocks;
280
281 const LIB_DATA* lib = *maybeLib;
282 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
283 wxArrayString blockNames;
284
285 try
286 {
287 dbplugin( lib )->DesignBlockEnumerate( blockNames, getUri( lib->row ), false, &options );
288 }
289 catch( IO_ERROR& e )
290 {
291 wxLogTrace( traceLibraries, "DB: Exception enumerating library %s: %s", lib->row->Nickname(), e.What() );
292 }
293
294 for( const wxString& blockName : blockNames )
295 {
296 try
297 {
298 blocks.emplace_back( dbplugin( lib )->DesignBlockLoad( getUri( lib->row ), blockName, false, &options ) );
299 }
300 catch( IO_ERROR& e )
301 {
302 wxLogTrace( traceLibraries, "DB: Exception enumerating design block %s: %s", blockName, e.What() );
303 }
304 }
305
306 return blocks;
307}
308
309
310std::vector<wxString> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlockNames( const wxString& aNickname )
311{
312 // TODO(JE) can we kill wxArrayString in internal API?
313 wxArrayString namesAS;
314 std::vector<wxString> names;
315
316 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
317 {
318 const LIB_DATA* lib = *maybeLib;
319 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
320
321 dbplugin( lib )->DesignBlockEnumerate( namesAS, getUri( lib->row ), true, &options );
322 }
323
324 for( const wxString& name : namesAS )
325 names.emplace_back( name );
326
327 return names;
328}
329
330
332 const wxString& aDesignBlockName, bool aKeepUUID )
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 DESIGN_BLOCK* db = dbplugin( lib )->DesignBlockLoad( getUri( lib->row ), aDesignBlockName, aKeepUUID, &options );
340 db->GetLibId().SetLibNickname( aNickname );
341 return db;
342 }
343
344 return nullptr;
345}
346
347
348bool DESIGN_BLOCK_LIBRARY_ADAPTER::DesignBlockExists( const wxString& aNickname, const wxString& aDesignBlockName )
349{
350 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
351 {
352 const LIB_DATA* lib = *maybeLib;
353 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
354
355 return dbplugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlockName, &options );
356 }
357
358 return false;
359}
360
361
363 const wxString& aDesignBlockName )
364{
365 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
366 {
367 const LIB_DATA* lib = *maybeLib;
368 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
369
370 return dbplugin( lib )->GetEnumeratedDesignBlock( getUri( lib->row ), aDesignBlockName, &options );
371 }
372
373 return nullptr;
374}
375
376
378 const DESIGN_BLOCK* aDesignBlock,
379 bool aOverwrite )
380{
381 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
382 {
383 const LIB_DATA* lib = *maybeLib;
384 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
385
386 if( !aOverwrite && dbplugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlock->GetName(), &options ) )
387 return SAVE_SKIPPED;
388
389 dbplugin( lib )->DesignBlockSave( getUri( lib->row ), aDesignBlock, &options );
390 }
391
392 return SAVE_OK;
393}
394
395
397 const wxString& aDesignBlockName )
398{
399 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
400 {
401 const LIB_DATA* lib = *maybeLib;
402 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
403 return dbplugin( lib )->DesignBlockDelete( getUri( lib->row ), aDesignBlockName, &options );
404 }
405}
406
407
409{
410 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
411 {
412 const LIB_DATA* lib = *maybeLib;
413 return plugin( lib )->IsLibraryWritable( getUri( lib->row ) );
414 }
415
416 return false;
417}
418
419
421 bool aKeepUUID )
422{
423 wxString nickname = aDesignBlockId.GetLibNickname();
424 wxString DesignBlockname = aDesignBlockId.GetLibItemName();
425
426 if( nickname.size() )
427 return LoadDesignBlock( nickname, DesignBlockname, aKeepUUID );
428
429 // nickname is empty, sequentially search (alphabetically) all libs/nicks for first match:
430 for( const wxString& library : GetLibraryNames() )
431 {
432 // DesignBlockLoad() returns NULL on not found, does not throw exception
433 // unless there's an IO_ERROR.
434 if( DESIGN_BLOCK* ret = LoadDesignBlock( library, DesignBlockname, aKeepUUID ) )
435 return ret;
436 }
437
438 return nullptr;
439}
440
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)
std::vector< wxString > GetDesignBlockNames(const wxString &aNickname)
SAVE_T
The set of return values from DesignBlockSave() below.
std::vector< DESIGN_BLOCK * > GetDesignBlocks(const wxString &aNickname)
IO_BASE * plugin(const LIB_DATA *aRow) override
static DESIGN_BLOCK_IO * dbplugin(const LIB_DATA *aRow)
Helper to cast the ABC plugin in the LIB_DATA* to a concrete plugin.
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.
std::optional< LIB_STATUS > LoadOne(LIB_DATA *aLib) override
Loads or reloads the given library, if it exists.
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
virtual bool IsLibraryWritable(const wxString &aLibraryPath)
Return true if the library at aLibraryPath is writable.
Definition io_base.cpp:60
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)
LIB_STATUS status
std::unique_ptr< IO_BASE > plugin
std::mutex mutex
const LIBRARY_TABLE_ROW * row
std::optional< LIBRARY_ERROR > error
LOAD_STATUS load_status
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::priority_thread_pool thread_pool
Definition thread_pool.h:31
wxLogTrace helper definitions.