KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_handler_libraries.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
22
23#include <magic_enum.hpp>
24#include <ranges>
25
26#include <api/api_enums.h>
27#include <api/api_utils.h>
29#include <kiway.h>
30#include <pgm_base.h>
32
33#include <api/common/types/base_types.pb.h>
34#include <api/common/commands/editor_commands.pb.h>
35#include <api/common/types/library_types.pb.h>
36
38#include <design_block.h>
39
40using namespace kiapi::common::commands;
41using kiapi::common::types::LibraryCommandStatus;
42using kiapi::common::types::LibraryLoadStatus;
43using kiapi::common::types::LibraryTableScope;
44using kiapi::common::types::LibraryType;
45
47 m_type( aType )
48{
53
54 // Only the design-block instance registers LoadAllLibraries: it is the dispatcher that
55 // lazily loads the schematic and PCB kifaces and forwards to their per-type loads. If
56 // the per-type (SYMBOL/FOOTPRINT) handlers registered it too, the server's handler set
57 // (ordered by pointer, not registration order) could route the command to an instance
58 // without a KIWAY, which would fail the request.
61}
62
63
65
66
71
72
74 const wxString& aNickname ) const
75{
76 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER&>( aAdapter ).GetDesignBlockNames( aNickname );
77}
78
79
82{
84 {
85 ApiResponseStatus e;
86 e.set_status( ApiStatusCode::AS_UNHANDLED );
87 return tl::unexpected( e );
88 }
89
92
93 if( !adapter )
94 {
95 ApiResponseStatus e;
96 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
97 e.set_error_message( "no library adapter is available for this library type" );
98 return tl::unexpected( e );
99 }
100
101 std::vector<wxString> nicknames;
102
103 if( aCtx.Request.nickname_size() > 0 )
104 {
105 for( const std::string& nickname : aCtx.Request.nickname() )
106 {
107 wxString nicknameStr = wxString::FromUTF8( nickname );
108
109 // TODO(JE) decide whether or not to do blocking loads for explicit requests
110 adapter->LoadLibraryEntry( nicknameStr );
111
112 nicknames.emplace_back( nicknameStr );
113 }
114 }
115 else
116 {
117 for( const LIBRARY_TABLE_ROW* row : adapter->Rows() )
118 nicknames.emplace_back( row->Nickname() );
119 }
120
121 LibraryItemsResponse response;
122
123 for( const wxString& nickname : nicknames )
124 {
125 for( const wxString& itemName : getItemNames( *adapter, nickname ) )
126 {
127 kiapi::common::types::LibraryIdentifier* id = response.add_items();
128 id->set_library_nickname( nickname.ToUTF8() );
129 id->set_entry_name( itemName.ToUTF8() );
130 }
131 }
132
133 return response;
134}
135
136
137static void packTableEntry( kiapi::common::types::LibraryTableEntry& aEntry, LIBRARY_TABLE_TYPE aTableType,
138 const LIBRARY_TABLE_ROW& aRow )
139{
140 aEntry.set_nickname( aRow.Nickname().ToUTF8() );
141 aEntry.set_uri( aRow.URI().ToUTF8() );
142 aEntry.set_type( ToProtoEnum<LIBRARY_TABLE_TYPE, LibraryType>( aTableType ) );
144 aEntry.set_description( aRow.Description().ToUTF8() );
145
146 for( const auto& [key, value] : aRow.GetOptionsMap() )
147 ( *aEntry.mutable_options() )[key] = value;
148
149 if( std::optional<LIBRARY_MANAGER_ADAPTER*> adapter = Pgm().GetLibraryManager().Adapter( aTableType ) )
150 aEntry.set_writable( ( *adapter )->IsWritable( aRow.Nickname() ) );
151
152 aEntry.set_disabled( aRow.Disabled() );
153 aEntry.set_hidden( aRow.Hidden() );
154}
155
156
157static void packLibraryStatusEntry( kiapi::common::types::LibraryStatusEntry* aEntry, LIBRARY_TABLE_TYPE aTableType,
158 const LIBRARY_TABLE_ROW& aRow, const LIB_STATUS& aStatus )
159{
160 packTableEntry( *aEntry->mutable_entry(), aTableType, aRow );
161 aEntry->set_status( ToProtoEnum<LOAD_STATUS, LibraryLoadStatus>( aStatus.load_status ) );
162
163 if( aStatus.error )
164 aEntry->set_error_message( aStatus.error->message.ToUTF8() );
165}
166
167
170{
172
174 {
175 ApiResponseStatus e;
176 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
177 e.set_error_message( "unknown library table scope" );
178 return tl::unexpected( e );
179 }
180
182 LibraryStatusResponse response;
183
185
186 if( !aCtx.Request.types().empty() )
187 {
188 types.clear();
189
190 for( int typeProto : aCtx.Request.types() )
191 {
192 LIBRARY_TABLE_TYPE type = FromProtoEnum<LIBRARY_TABLE_TYPE>( static_cast<LibraryType>( typeProto ) );
193
195 {
196 ApiResponseStatus e;
197 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
198 e.set_error_message( wxString::Format( "invalid library table type %d", typeProto ).ToUTF8() );
199 return tl::unexpected( e );
200 }
201
202 types.push_back( type );
203 }
204 }
205
206 for( LIBRARY_TABLE_TYPE tableType : types )
207 {
208 LIBRARY_MANAGER_ADAPTER* adapter = nullptr;
209
210 if( std::optional<LIBRARY_MANAGER_ADAPTER*> optAdapter = manager.Adapter( tableType ) )
211 adapter = *optAdapter;
212
213 for( const LIBRARY_TABLE_ROW* row : manager.Rows( tableType, scope ) )
214 {
215 if( row->Disabled() )
216 continue;
217
218 kiapi::common::types::LibraryStatusEntry* entry = response.add_libraries();
219
220 if( adapter )
221 {
222 if( std::optional<LIB_STATUS> status = adapter->GetLibraryStatus( row->Nickname() ) )
223 {
224 packLibraryStatusEntry( entry, tableType, *row, *status );
225 continue;
226 }
227 }
228
229 packLibraryStatusEntry( entry, tableType, *row, LIB_STATUS{} );
230 }
231 }
232
233 return response;
234}
235
236
239{
240 auto makeStatus =
241 []( LibraryCommandStatus::Code aCode, const wxString& aMessage = wxEmptyString )
242 {
243 LibraryCommandStatus status;
244 status.set_code( aCode );
245
246 if( !aMessage.empty() )
247 status.set_error_message( aMessage.ToUTF8() );
248
249 return status;
250 };
251
252 if( aCtx.Request.type() == LibraryType::LT_UNKNOWN )
253 {
254 ApiResponseStatus e;
255 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
256 e.set_error_message( "a valid library type is required" );
257 return tl::unexpected( e );
258 }
259
260 if( aCtx.Request.scope() == LibraryTableScope::LTS_BOTH || aCtx.Request.scope() == LibraryTableScope::LTS_UNKNOWN )
261 {
262 ApiResponseStatus e;
263 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
264 e.set_error_message( "LTS_BOTH is invalid for ReloadLibrary; choose one table" );
265 return tl::unexpected( e );
266 }
267
269 const LIBRARY_TABLE_SCOPE scope = ( aCtx.Request.scope() == LibraryTableScope::LTS_GLOBAL )
272
274
275 if( !manager.Adapter( tableType ) )
276 {
277 ApiResponseStatus e;
278 e.set_status( ApiStatusCode::AS_UNHANDLED );
279 return tl::unexpected( e );
280 }
281
282 std::vector<wxString> nicknames;
283
284 if( aCtx.Request.nickname_size() > 0 )
285 {
286 for( const std::string& nickname : aCtx.Request.nickname() )
287 {
288 std::optional<LIBRARY_TABLE_ROW*> row = manager.GetRow( tableType, nickname, scope );
289
290 if( !row.has_value() )
291 {
292 return makeStatus( LibraryCommandStatus::LCS_NOT_FOUND,
293 wxString::Format( "Library '%s' not found", nickname ) );
294 }
295 else if( row.value()->Disabled() )
296 {
297 return makeStatus( LibraryCommandStatus::LCS_NOT_FOUND,
298 wxString::Format( "Library '%s' not enabled", nickname ) );
299 }
300
301 nicknames.emplace_back( wxString::FromUTF8( nickname ) );
302 }
303 }
304 else
305 {
306 for( const LIBRARY_TABLE_ROW* row : manager.Rows( tableType, scope ) )
307 {
308 if( !row->Disabled() )
309 nicknames.emplace_back( row->Nickname() );
310 }
311 }
312
313 if( nicknames.empty() )
314 return makeStatus( LibraryCommandStatus::LCS_NOT_FOUND, "No libraries found to reload" );
315
316 for( const wxString& nickname : nicknames )
317 manager.ReloadLibraryEntry( tableType, nickname, scope );
318
319 return makeStatus( LibraryCommandStatus::LCS_OK );
320}
321
322
325{
326 auto makeStatus =
327 []( LibraryCommandStatus::Code aCode, const wxString& aMessage = wxEmptyString )
328 {
329 LibraryCommandStatus status;
330 status.set_code( aCode );
331
332 if( !aMessage.empty() )
333 status.set_error_message( aMessage.ToUTF8() );
334
335 return status;
336 };
337
338 if( Pgm().IsGUI() )
339 {
340 ApiResponseStatus e;
341 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
342 e.set_error_message( "LoadAllLibraries is not available in GUI mode" );
343 return tl::unexpected( e );
344 }
345
346 std::map<LIBRARY_TABLE_TYPE, KIWAY::FACE_T> typesToLoad;
347
348 if( aCtx.Request.type_size() == 0 )
349 {
350 typesToLoad = { { LIBRARY_TABLE_TYPE::SYMBOL, KIWAY::FACE_SCH },
353 }
354 else
355 {
356 for( int protoRaw : aCtx.Request.type() )
357 {
358 LibraryType protoType = static_cast<LibraryType>( protoRaw );
360
361 switch( type )
362 {
363 case LIBRARY_TABLE_TYPE::SYMBOL: typesToLoad.emplace( type, KIWAY::FACE_SCH ); break;
364 case LIBRARY_TABLE_TYPE::FOOTPRINT: typesToLoad.emplace( type, KIWAY::FACE_PCB ); break;
365 case LIBRARY_TABLE_TYPE::DESIGN_BLOCK: typesToLoad.emplace( type, KIWAY::KIWAY_FACE_COUNT ); break;
366
367 default:
368 {
369 ApiResponseStatus e;
370 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
371 e.set_error_message( wxString::Format( wxS( "invalid library type %s" ),
372 magic_enum::enum_name( protoType ) ).ToUTF8() );
373 return tl::unexpected( e );
374 }
375 }
376 }
377 }
378
379 // should always be set in this path
380 if( !m_kiway )
381 {
382 ApiResponseStatus e;
383 e.set_status( ApiStatusCode::AS_NOT_READY );
384 e.set_error_message( "internal error while attempting to load all libraries" );
385 return tl::unexpected( e );
386 }
387
388 KIWAY& kiway = *m_kiway;
389 bool error = false;
390
391 for( const auto& [type, face] : typesToLoad )
392 {
394 {
395 LibraryCommandStatus status = loadAllLibraries();
396
397 if( status.code() != LibraryCommandStatus::LCS_OK )
398 error = true;
399
400 continue;
401 }
402
403 KIFACE* kiface = kiway.KiFACE( face );
404
405 if( !kiface )
406 {
407 wxFAIL;
408 error = true;
409 continue;
410 }
411
414
415 // A result of "true" only means that it -started- a load, not that it finished successfully.
416 // But we should still report an error if it couldn't even start.
417 if( !kiface->LoadAllLibraries() )
418 error = true;
419 }
420
421 return makeStatus( error ? LibraryCommandStatus::LCS_ERROR : LibraryCommandStatus::LCS_OK );
422}
423
424
426{
427 // This base implementation handles design blocks
428 LIBRARY_MANAGER_ADAPTER* adapter = adapterForProject( Pgm().GetSettingsManager().Prj() );
429 LibraryCommandStatus status;
430
431 if( !adapter )
432 {
433 status.set_code( LibraryCommandStatus::LCS_ERROR );
434 return status;
435 }
436
437 adapter->AsyncLoad();
438 status.set_code( LibraryCommandStatus::LCS_OK );
439 return status;
440}
441
442
445{
447 {
448 ApiResponseStatus e;
449 e.set_status( ApiStatusCode::AS_UNHANDLED );
450 return tl::unexpected( e );
451 }
452
453 wxString projectPath = wxString::FromUTF8( aCtx.Request.document().project().path() );
455 PROJECT* project = projectPath.IsEmpty() ? &mgr.Prj() : mgr.GetProjectForPath( projectPath );
456
457 if( !project )
458 {
459 ApiResponseStatus e;
460 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
461 e.set_error_message( "the requested project is not open" );
462 return tl::unexpected( e );
463 }
464
466
467 if( !adapter )
468 {
469 ApiResponseStatus e;
470 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
471 e.set_error_message( "no library adapter is available for this library type" );
472 return tl::unexpected( e );
473 }
474
475 GetItemsResponse response;
476 response.mutable_header()->mutable_document()->CopyFrom( aCtx.Request.document() );
477 google::protobuf::Any any;
478
479 if( aCtx.Request.item_ids().empty() )
480 {
481 ApiResponseStatus e;
482 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
483 e.set_error_message( "specify at least one lib_id to retrieve" );
484 return tl::unexpected( e );
485 }
486
487 std::map<wxString, std::vector<wxString>> byNickname;
488
489 for( const kiapi::common::types::LibraryIdentifier& id : aCtx.Request.item_ids() )
490 {
491 byNickname[wxString::FromUTF8( id.library_nickname() )].emplace_back( wxString::FromUTF8( id.entry_name() ) );
492 }
493
494 for( auto& [nickname, entryNames] : byNickname )
495 {
496 // TODO(JE) decide whether or not to do blocking loads for explicit requests
497 adapter->LoadLibraryEntry( nickname );
498
499 for( const wxString& entryName : entryNames )
500 {
501 if( packLibraryItem( LIB_ID( nickname, entryName ), any ) )
502 {
503 any.Swap( response.add_items() );
504 any.Clear();
505 }
506 }
507 }
508
509 if( response.items().empty() )
510 {
511 ApiResponseStatus e;
512 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
513 e.set_error_message( "none of the requested items were found" );
514 return tl::unexpected( e );
515 }
516
517 response.set_status( kiapi::common::types::ItemRequestStatus::IRS_OK );
518 return response;
519}
520
521
522bool API_HANDLER_LIBRARIES::packLibraryItem( const LIB_ID& aId, google::protobuf::Any& aOutput ) const
523{
525 static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( adapterForProject( Pgm().GetSettingsManager().Prj() ) );
526
527 DESIGN_BLOCK* designBlock = adapter->LoadDesignBlock( aId.GetLibNickname(), aId.GetLibItemName() );
528
529 if( !designBlock )
530 return false;
531
532 designBlock->Serialize( aOutput );
533 return true;
534}
535
KICOMMON_API types::KiCadObjectType ToProtoEnum(KICAD_T aValue)
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
Definition api_enums.cpp:56
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
Definition api_handler.h:47
static void packLibraryStatusEntry(kiapi::common::types::LibraryStatusEntry *aEntry, LIBRARY_TABLE_TYPE aTableType, const LIBRARY_TABLE_ROW &aRow, const LIB_STATUS &aStatus)
static void packTableEntry(kiapi::common::types::LibraryTableEntry &aEntry, LIBRARY_TABLE_TYPE aTableType, const LIBRARY_TABLE_ROW &aRow)
HANDLER_RESULT< kiapi::common::commands::LibraryItemsResponse > handleGetLibraryItems(const HANDLER_CONTEXT< kiapi::common::commands::GetLibraryItems > &aCtx)
HANDLER_RESULT< kiapi::common::commands::LibraryStatusResponse > handleGetLibraryStatuses(const HANDLER_CONTEXT< kiapi::common::commands::GetLibraryStatuses > &aCtx)
~API_HANDLER_LIBRARIES() override
HANDLER_RESULT< kiapi::common::types::LibraryCommandStatus > handleReloadLibrary(const HANDLER_CONTEXT< kiapi::common::commands::ReloadLibrary > &aCtx)
kiapi::common::types::LibraryCommandStatus loadAllLibraries()
Starts a background load of all libraries of this handler's type.
virtual std::vector< wxString > getItemNames(LIBRARY_MANAGER_ADAPTER &aAdapter, const wxString &aNickname) const
Returns the names of all entries in the given library, or an empty vector if the library is not loade...
virtual LIBRARY_MANAGER_ADAPTER * adapterForProject(PROJECT &aProject) const
API_HANDLER_LIBRARIES(LIBRARY_TABLE_TYPE aType=LIBRARY_TABLE_TYPE::DESIGN_BLOCK)
std::function< void(KIFACE *)> m_handlerRegisterCallback
Invoked with a lazily-loaded KIFACE so its handlers can be registered on the server.
KIWAY * m_kiway
Used to lazily load kifaces for LoadAllLibraries in headless; null in GUI mode.
virtual bool packLibraryItem(const LIB_ID &aId, google::protobuf::Any &aOutput) const
HANDLER_RESULT< kiapi::common::types::LibraryCommandStatus > handleLoadAllLibraries(const HANDLER_CONTEXT< kiapi::common::commands::LoadAllLibraries > &aCtx)
HANDLER_RESULT< kiapi::common::commands::GetItemsResponse > handleGetItemsFromLibrary(const HANDLER_CONTEXT< kiapi::common::commands::GetItemsFromLibrary > &aCtx)
void registerHandler(HANDLER_RESULT< ResponseType >(HandlerType::*aHandler)(const HANDLER_CONTEXT< RequestType > &), bool aAllowedDuringTask=false)
Registers an API command handler for the given message types.
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.
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:216
@ KIWAY_FACE_COUNT
Definition kiway.h:361
@ FACE_SCH
eeschema DSO
Definition kiway.h:355
@ FACE_PCB
pcbnew DSO
Definition kiway.h:356
The interface used by the classes that actually can load IO plugins for the different parts of KiCad ...
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)
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.
void AsyncLoad()
Loads all available libraries for this adapter type in the background.
std::optional< LIB_STATUS > LoadLibraryEntry(const wxString &aNickname)
Synchronously loads the named library to LOADED state.
std::optional< LIBRARY_MANAGER_ADAPTER * > Adapter(LIBRARY_TABLE_TYPE aType) const
void ReloadLibraryEntry(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH)
Synchronously recreates the plugin for and reloads the given library.
std::vector< LIBRARY_TABLE_ROW * > Rows(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH, bool aIncludeInvalid=false) const
Returns a flattened list of libraries of the given type.
std::optional< LIBRARY_TABLE_ROW * > GetRow(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH)
LIBRARY_TABLE_SCOPE Scope() const
bool Disabled() const
std::map< std::string, UTF8 > GetOptionsMap() const
const wxString & Description() const
bool Hidden() 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
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:126
Container for project specific data.
Definition project.h:63
virtual DESIGN_BLOCK_LIBRARY_ADAPTER * DesignBlockLibs()
Return the table of design block libraries.
Definition project.cpp:527
PROJECT * GetProjectForPath(const wxString &aProjectPath) const
Return the active project iff its path matches aProjectPath, else nullptr.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
A type-safe container of any type.
Definition ki_any.h:92
PROJECT & Prj()
Definition kicad.cpp:730
LIBRARY_TABLE_TYPE
LIBRARY_TABLE_SCOPE
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
RequestMessageType Request
Definition api_handler.h:54
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
The overall status of a loaded or loading library.
std::optional< LIBRARY_ERROR > error
LOAD_STATUS load_status
IFACE KIFACE_BASE kiface("pcb_test_frame", KIWAY::FACE_PCB)