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
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21
22#include "design_block.h"
23
25#include <design_block_io.h>
26#include <env_vars.h>
27#include <ki_exception.h>
28#include <trace_helpers.h>
29
30#include <magic_enum.hpp>
31#include <wx/log.h>
32
33
35
37
38
43
44
49
50
52{
53 return ENV_VAR::GetVersionedEnvVarName( wxS( "DESIGN_BLOCK_DIR" ) );
54}
55
56
58{
59 DESIGN_BLOCK_IO* ret = dynamic_cast<DESIGN_BLOCK_IO*>( aRow->plugin.get() );
60 wxCHECK( aRow->plugin && ret, nullptr );
61 return ret;
62}
63
64
66{
67 // TODO(JE) do we maintain a precondition that URIs are absolute paths after expansion?
69
71 {
72 wxString msg;
73 wxFileName fileName( m_manager.GetFullURI( row, true ) );
74
75 if( fileName.FileExists() )
76 return tl::unexpected( LIBRARY_TABLE_OK() );
77 else
78 msg = wxString::Format( _( "Nested table '%s' not found." ), row->URI() );
79
80 return tl::unexpected( LIBRARY_ERROR( msg ) );
81 }
83 {
84 wxLogTrace( traceLibraries, "Sym: Plugin type %s is unknown!", row->Type() );
85 wxString msg = wxString::Format( _( "Unknown library type %s " ), row->Type() );
86 return tl::unexpected( LIBRARY_ERROR( msg ) );
87 }
88
90 wxCHECK( plugin, tl::unexpected( LIBRARY_ERROR( _( "Internal error" ) ) ) );
91
92 return plugin;
93}
94
95
97{
98 return dbplugin( aRow );
99}
100
101
103{
104 wxArrayString dummyList;
105 std::map<std::string, UTF8> options = aLib->row->GetOptionsMap();
106 dbplugin( aLib )->DesignBlockEnumerate( dummyList, aUri, false, &options );
107}
108
109
110std::optional<LIB_STATUS> DESIGN_BLOCK_LIBRARY_ADAPTER::LoadOne( LIB_DATA* aLib )
111{
113
114 std::map<std::string, UTF8> options = aLib->row->GetOptionsMap();
115
116 try
117 {
118 wxArrayString dummyList;
119 dbplugin( aLib )->DesignBlockEnumerate( dummyList, getUri( aLib->row ), false, &options );
120 wxLogTrace( traceLibraries, "DB: %s: library enumerated %zu items", aLib->row->Nickname(), dummyList.size() );
122 aLib->status.error.reset();
123 }
124 catch( IO_ERROR& e )
125 {
127 aLib->status.error = LIBRARY_ERROR( e.Problem(), e.Where() );
128 wxLogTrace( traceLibraries, "DB: %s: plugin threw exception: %s", aLib->row->Nickname(), e.What() );
129 }
130
131 return aLib->status;
132}
133
134
135std::optional<LIB_STATUS> DESIGN_BLOCK_LIBRARY_ADAPTER::LoadOne( const wxString& nickname )
136{
138
139 if( result.has_value() )
140 return LoadOne( *result );
141
142 return LIB_STATUS{ .load_status = LOAD_STATUS::LOAD_ERROR,
143 .error = LIBRARY_ERROR( { result.error() } ) };
144}
145
146
147std::vector<DESIGN_BLOCK*> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlocks( const wxString& aNickname )
148{
149 std::vector<DESIGN_BLOCK*> blocks;
150
151 std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname );
152
153 if( !maybeLib )
154 return blocks;
155
156 const LIB_DATA* lib = *maybeLib;
157 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
158 wxArrayString blockNames;
159
160 try
161 {
162 dbplugin( lib )->DesignBlockEnumerate( blockNames, getUri( lib->row ), false, &options );
163 }
164 catch( IO_ERROR& e )
165 {
166 wxLogTrace( traceLibraries, "DB: Exception enumerating library %s: %s", lib->row->Nickname(), e.What() );
167 }
168
169 for( const wxString& blockName : blockNames )
170 {
171 try
172 {
173 blocks.emplace_back( dbplugin( lib )->DesignBlockLoad( getUri( lib->row ), blockName, false, &options ) );
174 }
175 catch( IO_ERROR& e )
176 {
177 wxLogTrace( traceLibraries, "DB: Exception enumerating design block %s: %s", blockName, e.What() );
178 }
179 }
180
181 return blocks;
182}
183
184
185std::vector<wxString> DESIGN_BLOCK_LIBRARY_ADAPTER::GetDesignBlockNames( const wxString& aNickname )
186{
187 // TODO(JE) can we kill wxArrayString in internal API?
188 wxArrayString namesAS;
189 std::vector<wxString> names;
190
191 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
192 {
193 const LIB_DATA* lib = *maybeLib;
194 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
195
196 dbplugin( lib )->DesignBlockEnumerate( namesAS, getUri( lib->row ), true, &options );
197 }
198
199 for( const wxString& name : namesAS )
200 names.emplace_back( name );
201
202 return names;
203}
204
205
206static wxString describeMissingLibrary( const wxString& aNickname, const std::vector<LIBRARY_TABLE_ROW*>& aRows )
207{
208 wxString message = wxString::Format( _( "Design block library '%s' is not in the design block "
209 "library table." ),
210 aNickname );
211
212 // If one name sits inside the other, it can be the same library after a rename.
213 if( !aNickname.IsEmpty() )
214 {
215 const wxString wanted = aNickname.Lower();
216
217 for( const LIBRARY_TABLE_ROW* row : aRows )
218 {
219 const wxString candidate = row->Nickname().Lower();
220
221 if( candidate.IsEmpty() || ( !candidate.Contains( wanted ) && !wanted.Contains( candidate ) ) )
222 continue;
223
224 message += wxString::Format( _( " Did you mean '%s'?" ), row->Nickname() );
225 break;
226 }
227 }
228
229 if( aRows.empty() )
230 return message + wxS( "\n\n" ) + _( "No design block libraries are configured." );
231
232 message += wxS( "\n\n" ) + _( "Configured design block libraries:" );
233
234 const size_t maxListed = 20;
235
236 for( size_t ii = 0; ii < aRows.size(); ii++ )
237 {
238 if( ii == maxListed )
239 {
240 message += wxT( "\n" ) + wxString::Format( _( "and %d more" ), (int) ( aRows.size() - maxListed ) );
241 break;
242 }
243
244 message +=
245 wxString::Format( wxT( "\n %s (%s)" ), aRows[ii]->Nickname(),
246 aRows[ii]->Scope() == LIBRARY_TABLE_SCOPE::PROJECT ? _( "project" ) : _( "global" ) );
247 }
248
249 return message;
250}
251
252
253wxString DESIGN_BLOCK_LIBRARY_ADAPTER::libraryUnavailableMessage( const wxString& aNickname ) const
254{
255 std::optional<LIBRARY_TABLE_ROW*> row = GetRow( aNickname );
256
257 if( !row )
258 return describeMissingLibrary( aNickname, Rows() );
259
260 if( ( *row )->Disabled() )
261 return wxString::Format( _( "Design block library '%s' is disabled in the library table." ), aNickname );
262
263 std::optional<LIB_STATUS> status = GetLibraryStatus( aNickname );
264
265 if( status && status->load_status == LOAD_STATUS::LOAD_ERROR )
266 {
267 return wxString::Format( _( "Design block library '%s' could not be opened." ) + wxS( "\n%s" ), aNickname,
268 status->error ? status->error->message : wxString() );
269 }
270
271 return wxString::Format( _( "Design block library '%s' is still loading." ), aNickname );
272}
273
274
276 const wxString& aDesignBlockName, bool aKeepUUID,
277 wxString* aErrorMsg )
278{
279 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
280 {
281 const LIB_DATA* lib = *maybeLib;
282
283 std::lock_guard pluginGuard( pluginMutex( aNickname ) );
284
285 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
286
287 try
288 {
289 if( DESIGN_BLOCK* db =
290 dbplugin( lib )->DesignBlockLoad( getUri( lib->row ), aDesignBlockName, aKeepUUID, &options ) )
291 {
292 db->GetLibId().SetLibNickname( aNickname );
293 return db;
294 }
295 }
296 catch( const IO_ERROR& ioe )
297 {
298 wxLogTrace( traceLibraries, "LoadDesignBlock: error loading %s:%s: %s", aNickname, aDesignBlockName,
299 ioe.What() );
300
301 if( aErrorMsg )
302 *aErrorMsg = ioe.What();
303 }
304 }
305 else
306 {
307 wxLogTrace( traceLibraries, "LoadDesignBlock: requested library %s not loaded", aNickname );
308
309 if( aErrorMsg )
310 *aErrorMsg = libraryUnavailableMessage( aNickname );
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
323 std::lock_guard pluginGuard( pluginMutex( aNickname ) );
324
325 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
326
327 return dbplugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlockName, &options );
328 }
329
330 return false;
331}
332
333
335 const wxString& aDesignBlockName )
336{
337 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
338 {
339 const LIB_DATA* lib = *maybeLib;
340 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
341
342 return dbplugin( lib )->GetEnumeratedDesignBlock( getUri( lib->row ), aDesignBlockName, &options );
343 }
344
345 return nullptr;
346}
347
348
350 const DESIGN_BLOCK* aDesignBlock,
351 bool aOverwrite )
352{
353 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
354 {
355 const LIB_DATA* lib = *maybeLib;
356 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
357
358 if( !aOverwrite && dbplugin( lib )->DesignBlockExists( getUri( lib->row ), aDesignBlock->GetName(), &options ) )
359 return SAVE_SKIPPED;
360
361 dbplugin( lib )->DesignBlockSave( getUri( lib->row ), aDesignBlock, &options );
362 return SAVE_OK;
363 }
364
365 return SAVE_SKIPPED;
366}
367
368
370 const wxString& aDesignBlockName )
371{
372 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
373 {
374 const LIB_DATA* lib = *maybeLib;
375 std::map<std::string, UTF8> options = lib->row->GetOptionsMap();
376 return dbplugin( lib )->DesignBlockDelete( getUri( lib->row ), aDesignBlockName, &options );
377 }
378}
379
380
382{
383 if( std::optional<const LIB_DATA*> maybeLib = fetchIfLoaded( aNickname ) )
384 {
385 const LIB_DATA* lib = *maybeLib;
386 return plugin( lib )->IsLibraryWritable( getUri( lib->row ) );
387 }
388
389 return false;
390}
391
392
394 bool aKeepUUID, wxString* aErrorMsg )
395{
396 wxString nickname = aDesignBlockId.GetLibNickname();
397 wxString DesignBlockname = aDesignBlockId.GetLibItemName();
398
399 if( nickname.size() )
400 return LoadDesignBlock( nickname, DesignBlockname, aKeepUUID, aErrorMsg );
401
402 // nickname is empty, sequentially search (alphabetically) all libs/nicks for first match:
403 for( const wxString& library : GetLibraryNames() )
404 {
405 if( DesignBlockExists( library, DesignBlockname ) )
406 return LoadDesignBlock( library, DesignBlockname, aKeepUUID, aErrorMsg );
407 }
408
409 if( aErrorMsg )
410 *aErrorMsg = wxString::Format( _( "Design block '%s' not found in any library." ), DesignBlockname );
411
412 return nullptr;
413}
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)
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)
wxString libraryUnavailableMessage(const wxString &aNickname) const
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 LEAK_AT_EXIT< std::shared_mutex > GlobalLibraryMutex
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.
static LEAK_AT_EXIT< std::map< wxString, LIB_DATA > > GlobalLibraries
SAVE_T SaveDesignBlock(const wxString &aNickname, const DESIGN_BLOCK *aDesignBlock, bool aOverwrite=true)
Write aDesignBlock to an existing library given by aNickname.
DESIGN_BLOCK * DesignBlockLoadWithOptionalNickname(const LIB_ID &aDesignBlockId, bool aKeepUUID=false, wxString *aErrorMsg=nullptr)
Load a design block having aDesignBlockId with possibly an empty nickname.
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
const DESIGN_BLOCK * GetEnumeratedDesignBlock(const wxString &aNickname, const wxString &aDesignBlockName)
A version of LoadDesignBlock() for use after enumerateLibrary() for more efficient cache management.
DESIGN_BLOCK * LoadDesignBlock(const wxString &aNickname, const wxString &aDesignBlockName, bool aKeepUUID=false, wxString *aErrorMsg=nullptr)
Load a design block having aDesignBlockName from the library given by aNickname.
bool DesignBlockExists(const wxString &aNickname, const wxString &aDesignBlockName)
Indicates whether or not the given design block already exists in the given library.
void enumerateLibrary(LIB_DATA *aLib, const wxString &aUri) override
Override in derived class to perform library-specific enumeration.
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()
virtual const wxString Problem() const
what was the problem?
virtual const wxString Where() const
where did the Problem() occur?
A wrapper for static data that should not be destroyed at program exit.
std::optional< LIB_STATUS > GetLibraryStatus(const wxString &aNickname) const
Returns the status of a loaded library, or nullopt if the library hasn't been loaded (yet)
LIBRARY_MANAGER_ADAPTER(LIBRARY_MANAGER &aManager)
Constructs a type-specific adapter into the library manager.
std::vector< LIBRARY_TABLE_ROW * > Rows(LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH, bool aIncludeInvalid=false) const
Like LIBRARY_MANAGER::Rows but filtered to the LIBRARY_TABLE_TYPE of this adapter.
wxString getUri(const LIBRARY_TABLE_ROW *aRow) const
void retireAllLibraries()
For derived destructors, while globalLibs() is still resolvable and plugin worker threads can still c...
LIBRARY_RESULT< LIB_DATA * > loadIfNeeded(const wxString &aNickname)
Fetches a loaded library, triggering a load of that library if it isn't loaded yet.
std::optional< LIBRARY_TABLE_ROW * > GetRow(const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH) const
Like LIBRARY_MANAGER::GetRow but filtered to the LIBRARY_TABLE_TYPE of this adapter.
std::vector< wxString > GetLibraryNames() const
Returns a list of library nicknames that are available (skips any that failed to load)
static std::recursive_mutex & pluginMutex(const wxString &aNickname)
Serializes access to a library's shared plugin instance so its single mutable cache is not raced by c...
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 & URI() const
const wxString & Nickname() const
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
static wxString describeMissingLibrary(const wxString &aNickname, const std::vector< LIBRARY_TABLE_ROW * > &aRows)
#define _(s)
Functions related to environment variables, including help functions.
const wxChar *const traceLibraries
Flag to enable library table and library manager tracing.
std::string message
tl::expected< ResultType, LIBRARY_ERROR > LIBRARY_RESULT
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:79
Storage for an actual loaded library (including library content owned by the plugin)
LIB_STATUS status
std::unique_ptr< IO_BASE > plugin
Never destroyed while holding the map's mutex; a plugin's worker thread may be blocked on it.
const LIBRARY_TABLE_ROW * row
The overall status of a loaded or loading library.
std::optional< LIBRARY_ERROR > error
LOAD_STATUS load_status
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.