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