23#include <fmt/ranges.h>
24#include <magic_enum.hpp>
55#include <api/common/types/base_types.pb.h>
57using namespace kiapi::common::commands;
58using types::CommandStatus;
60using types::DocumentType;
61using types::ItemRequestStatus;
114 const std::string& aCommandName )
const
120 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
121 e.set_error_message( fmt::format(
"{} is not available in headless mode", aCommandName ) );
133 const wxString& aMessage )
137 const bool changed = it !=
m_commits.end() && !it->second.second->Empty();
151 bool isFootprintEditor =
thisDocumentType() == kiapi::common::types::DOCTYPE_FOOTPRINT;
153 return std::make_unique<BOARD_COMMIT>(
toolManager(), !isFootprintEditor, isFootprintEditor );
174 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
175 e.set_error_message(
"Tried to create an item in a null container" );
176 return tl::unexpected( e );
182 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
183 e.set_error_message( fmt::format(
"Tried to create a pad in {}, which is not a footprint",
185 return tl::unexpected( e );
190 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
191 e.set_error_message( fmt::format(
"Tried to create a footprint in {}, which is not a board",
193 return tl::unexpected( e );
196 if(
dynamic_cast<FOOTPRINT*
>( aContainer ) )
198 static const std::set<KICAD_T> s_footprintItemTypes = {
205 if( !s_footprintItemTypes.contains( aType ) )
208 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
209 e.set_error_message( fmt::format(
"items of type {} cannot be created in a footprint",
210 magic_enum::enum_name( aType ) ) );
211 return tl::unexpected( e );
220 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
221 e.set_error_message( fmt::format(
"Tried to create an item of type {}, which is unhandled",
222 magic_enum::enum_name( aType ) ) );
223 return tl::unexpected( e );
231 const std::string& aClientName )
234 std::vector<BOARD_ITEM*> validatedItems;
236 for( std::pair<const KIID, ItemDeletionStatus> pair : aItemsToDelete )
244 aItemsToDelete[pair.first] = ItemDeletionStatus::IDS_IMMUTABLE;
251 aItemsToDelete[pair.first] = ItemDeletionStatus::IDS_IMMUTABLE;
255 validatedItems.push_back( item );
256 aItemsToDelete[pair.first] = ItemDeletionStatus::IDS_OK;
272 static_cast<PCB_TABLECELL*
>( item )->SetText( wxEmptyString );
314 const std::vector<PCB_GENERATOR*>& aGenerators,
315 std::function<
void(
const KIID&, ItemStatus )> aResultHandler )
const
325 generator->EditStart( aTool,
board, aCommit );
326 bool ok = generator->Update( aTool,
board, aCommit );
327 generator->EditFinish( aTool,
board, aCommit );
329 status.set_code( ok ? ItemStatusCode::ISC_OK : ItemStatusCode::ISC_INVALID_DATA );
332 status.set_error_message(
"the generator reported an update failure" );
334 catch(
const std::exception& exc )
336 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
337 status.set_error_message( fmt::format(
"regeneration exception: {}", exc.what() ) );
341 aResultHandler( generator->m_Uuid, status );
347 const DocumentSpecifier& aDocument,
const KIID& aId )
357 const std::string& aClientName,
358 const types::ItemHeader &aHeader,
359 const google::protobuf::RepeatedPtrField<google::protobuf::Any>& aItems,
360 std::function<
void( ItemStatus, google::protobuf::Any )> aItemHandler )
366 if( !containerResult && containerResult.error().status() == ApiStatusCode::AS_UNHANDLED )
369 e.set_status( ApiStatusCode::AS_UNHANDLED );
370 return tl::unexpected( e );
372 else if( !containerResult )
374 e.CopyFrom( containerResult.error() );
375 return tl::unexpected( e );
381 if( containerResult->has_value() )
383 const KIID& containerId = **containerResult;
384 std::optional<BOARD_ITEM*> optItem =
getItemById( containerId );
392 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
393 e.set_error_message( fmt::format(
"The requested container {} is not a valid board item container",
395 return tl::unexpected( e );
400 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
401 e.set_error_message( fmt::format(
"The requested container {} does not exist in this document",
403 return tl::unexpected( e );
410 for(
const google::protobuf::Any& anyItem : aItems )
417 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
418 status.set_error_message( fmt::format(
"Could not decode a valid type from {}", anyItem.type_url() ) );
419 aItemHandler( status, anyItem );
425 board::types::Dimension dimension;
427 if( !anyItem.UnpackTo( &dimension ) )
429 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
430 status.set_error_message(
"Failed to unpack dimension" );
431 aItemHandler( status, anyItem );
435 switch( dimension.dimension_style_case() )
442 case board::types::Dimension::DIMENSION_STYLE_NOT_SET:
break;
448 board::types::BoardGraphicShape shape;
450 if(! anyItem.UnpackTo( &shape ) )
452 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
453 status.set_error_message(
"Failed to unpack shape" );
454 aItemHandler( status, anyItem );
458 if( shape.has_pad_custom_shape_options() )
460 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
461 status.set_error_message(
"pad_custom_shape_options are only valid on shapes inside a pad's "
462 "padstack custom shapes" );
463 aItemHandler( status, anyItem );
477 ItemStatus genStatus;
478 genStatus.set_code( ItemStatusCode::ISC_INVALID_TYPE );
479 genStatus.set_error_message( fmt::format(
"could not decode a generator from {}",
480 anyItem.type_url() ) );
481 aItemHandler( genStatus, anyItem );
489 ItemStatus genStatus;
490 genStatus.set_code( ItemStatusCode::ISC_INVALID_TYPE );
491 genStatus.set_error_message( fmt::format(
"generator type {} is not registered",
492 generatorType->ToStdString() ) );
493 aItemHandler( genStatus, anyItem );
503 if( !creationResult || !creationResult.value() )
505 if( !creationResult )
507 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
508 status.set_error_message( creationResult.error().error_message() );
509 aItemHandler( status, anyItem );
515 std::unique_ptr<BOARD_ITEM> item( std::move( *creationResult ) );
517 bool unpacked =
false;
520 unpacked = item->Deserialize( anyItem );
522 unpacked =
group->DeserializeGroup( anyItem, commit );
524 unpacked = item->Deserialize( anyItem );
530 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
531 e.set_error_message( fmt::format(
"could not unpack {} from request",
532 item->GetClass().ToStdString() ) );
533 return tl::unexpected( e );
541 if( std::vector<wxString> removed = item->RemoveConflictingCustomProperties(); !removed.empty() )
544 [](
const wxString& aIn )
546 return std::string( aIn.ToUTF8() );
549 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
550 status.set_error_message( fmt::format(
"Invalid custom properties for item {}: property name(s) '{}' "
552 item->m_Uuid.AsStdString(),
553 fmt::join( std::views::transform( removed, as_str ),
", " ) ) );
555 aItemHandler( status, anyItem );
559 std::optional<BOARD_ITEM*> optItem =
getItemById( item->m_Uuid );
561 if( aCreate && optItem )
563 status.set_code( ItemStatusCode::ISC_EXISTING );
564 status.set_error_message( fmt::format(
"an item with UUID {} already exists",
565 item->m_Uuid.AsStdString() ) );
566 aItemHandler( status, anyItem );
569 else if( !aCreate && !optItem )
571 status.set_code( ItemStatusCode::ISC_NONEXISTENT );
572 status.set_error_message( fmt::format(
"an item with UUID {} does not exist",
573 item->m_Uuid.AsStdString() ) );
574 aItemHandler( status, anyItem );
578 if( !aCreate && ( *optItem )->Type() != item->Type() )
580 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
581 status.set_error_message( fmt::format(
"item {} is of type {}, not {}",
582 item->m_Uuid.AsStdString(),
583 magic_enum::enum_name( ( *optItem )->Type() ),
584 magic_enum::enum_name( item->Type() ) ) );
585 aItemHandler( status, anyItem );
593 status.set_code( ItemStatusCode::ISC_IMMUTABLE );
594 status.set_error_message( fmt::format(
"cells of generated table {} cannot be modified",
595 ( aCreate ? container->
m_Uuid : ( *optItem )->GetParent()->m_Uuid )
597 aItemHandler( status, anyItem );
602 && !item->FitsEnabledLayers(
board->GetEnabledLayers(),
board->GetCopperLayerCount() ) )
604 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
605 status.set_error_message(
"attempted to add item with no overlapping layers with the board" );
606 aItemHandler( status, anyItem );
610 status.set_code( ItemStatusCode::ISC_OK );
611 google::protobuf::Any newItem;
624 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
625 status.set_error_message(
"a table cell must target a table container" );
626 aItemHandler( status, anyItem );
632 table->AddCell( cell );
650 item->Serialize( newItem );
651 commit->
Add( item.release() );
669 commit->
Modify( boardItem );
672 static_cast<PCB_GROUP*
>( boardItem )->FinalizeGroupDeserialization();
689 table->Serialize( newItem );
703 commit->
Remove( boardItem );
704 item->Serialize( newItem );
707 commit->
Add( newBoardItem );
711 parentGroup->
AddItem( newBoardItem );
718 commit->
Modify( boardItem );
731 aItemHandler( status, newItem );
737 :
_(
"Modified items via API" ) );
740 return ItemRequestStatus::IRS_OK;
745 const google::protobuf::RepeatedField<int>& aTypes )
747 std::vector<KICAD_T>
types;
749 for(
int typeRaw : aTypes )
751 auto typeMessage =
static_cast<common::types::KiCadObjectType
>( typeRaw );
755 types.emplace_back( type );
765 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"RunAction" ) )
766 return tl::unexpected( *headless );
768 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
769 return tl::unexpected( *busy );
771 RunActionResponse response;
774 response.set_status( RunActionStatus::RAS_OK );
776 response.set_status( RunActionStatus::RAS_INVALID );
788 e.set_status( ApiStatusCode::AS_UNHANDLED );
789 return tl::unexpected( e );
792 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
793 return tl::unexpected( *busy );
795 GetItemsResponse response;
797 std::vector<BOARD_ITEM*> items;
799 for(
const kiapi::common::types::KIID&
id : aCtx.
Request.items() )
801 if( std::optional<BOARD_ITEM*> item =
getItemById(
KIID(
id.value() ) ) )
802 items.emplace_back( *item );
808 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
809 e.set_error_message(
"none of the requested IDs were found or valid" );
810 return tl::unexpected( e );
815 google::protobuf::Any itemBuf;
816 item->Serialize( itemBuf );
817 response.mutable_items()->Add( std::move( itemBuf ) );
820 response.set_status( ItemRequestStatus::IRS_OK );
828 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"GetSelection" ) )
829 return tl::unexpected( *headless );
835 e.set_status( ApiStatusCode::AS_UNHANDLED );
836 return tl::unexpected( e );
858 SelectionResponse response;
863 item->Serialize( *response.add_items() );
873 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"ClearSelection" ) )
874 return tl::unexpected( *headless );
880 e.set_status( ApiStatusCode::AS_UNHANDLED );
881 return tl::unexpected( e );
884 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
885 return tl::unexpected( *busy );
898 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"AddToSelection" ) )
899 return tl::unexpected( *headless );
905 e.set_status( ApiStatusCode::AS_UNHANDLED );
906 return tl::unexpected( e );
909 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
910 return tl::unexpected( *busy );
915 std::vector<EDA_ITEM*> toAdd;
917 for(
const types::KIID&
id : aCtx.
Request.items() )
919 if( std::optional<BOARD_ITEM*> item =
getItemById(
KIID(
id.value() ) ) )
920 toAdd.emplace_back( *item );
926 SelectionResponse response;
929 item->Serialize( *response.add_items() );
937 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"FocusOnItems" ) )
938 return tl::unexpected( *headless );
941 return tl::unexpected( documentValidation.error() );
943 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
944 return tl::unexpected( *busy );
946 if( aCtx.
Request.items().empty() )
947 return tl::unexpected(
MakeResponseStatus( AS_BAD_REQUEST,
"no items were given to focus on" ) );
949 std::optional<BOX2I> bbox;
950 std::vector<std::string> missing;
952 for(
const types::KIID& idMsg : aCtx.
Request.items() )
954 std::optional<BOARD_ITEM*> item =
getItemById(
KIID( idMsg.value() ) );
958 missing.push_back( idMsg.value() );
963 bbox->Merge( ( *item )->GetBoundingBox() );
965 bbox = ( *item )->GetBoundingBox();
968 if( !missing.empty() )
970 return tl::unexpected(
971 MakeResponseStatus( AS_BAD_REQUEST, fmt::format(
"the items {} are not in the requested document",
972 fmt::join( missing,
", " ) ) ) );
975 if( aCtx.
Request.has_margin() )
987 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"RemoveFromSelection" ) )
988 return tl::unexpected( *headless );
994 e.set_status( ApiStatusCode::AS_UNHANDLED );
995 return tl::unexpected( e );
998 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
999 return tl::unexpected( *busy );
1004 std::vector<EDA_ITEM*> toRemove;
1006 for(
const types::KIID&
id : aCtx.
Request.items() )
1008 if( std::optional<BOARD_ITEM*> item =
getItemById(
KIID(
id.value() ) ) )
1009 toRemove.emplace_back( *item );
1015 SelectionResponse response;
1018 item->Serialize( *response.add_items() );
1029 if( !documentValidation )
1030 return tl::unexpected( documentValidation.error() );
1032 BoardStackupResponse response;
1045 if( !documentValidation )
1046 return tl::unexpected( documentValidation.error() );
1048 BoardEnabledLayersResponse response;
1051 int copperLayerCount =
board->GetCopperLayerCount();
1053 response.set_copper_layer_count( copperLayerCount );
1055 LSET enabled =
board->GetEnabledLayers();
1074 if( !documentValidation )
1075 return tl::unexpected( documentValidation.error() );
1078 GraphicsDefaultsResponse response;
1081 constexpr std::array<kiapi::board::BoardLayerClass, LAYER_CLASS_COUNT> classOrder = {
1082 kiapi::board::BLC_SILKSCREEN,
1083 kiapi::board::BLC_COPPER,
1084 kiapi::board::BLC_EDGES,
1085 kiapi::board::BLC_COURTYARD,
1086 kiapi::board::BLC_FABRICATION,
1087 kiapi::board::BLC_OTHER
1092 kiapi::board::BoardLayerGraphicsDefaults* l = response.mutable_defaults()->add_layers();
1094 l->set_layer( classOrder[i] );
1097 kiapi::common::types::TextAttributes*
text = l->mutable_text();
1114 ApiResponseStatus e;
1116 e.set_status( ApiStatusCode::AS_UNHANDLED );
1117 return tl::unexpected( e );
1120 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1121 return tl::unexpected( *busy );
1123 GetBoundingBoxResponse response;
1124 bool includeText = aCtx.
Request.mode() == BoundingBoxMode::BBM_ITEM_AND_CHILD_TEXT;
1126 for(
const types::KIID& idMsg : aCtx.
Request.items() )
1128 KIID id( idMsg.value() );
1129 std::optional<BOARD_ITEM*> optItem =
getItemById(
id );
1138 bbox =
static_cast<FOOTPRINT*
>( item )->GetBoundingBox( includeText );
1142 response.add_items()->set_value( idMsg.value() );
1143 PackBox2( *response.add_boxes(), bbox );
1154 return tl::unexpected( documentValidation.error() );
1156 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1157 return tl::unexpected( *busy );
1159 BoardBoundingBoxResponse response;
1165 case BoardBoundingBoxMode::BBBM_PHYSICAL_LAYERS_ONLY: bbox =
board()->
ComputeBoundingBox(
false,
true );
break;
1168 return tl::unexpected(
MakeResponseStatus( AS_BAD_REQUEST,
"invalid bounding box mode requested" ) );
1171 PackBox2( *response.mutable_box(), bbox );
1181 !documentValidation )
1183 return tl::unexpected( documentValidation.error() );
1186 PadShapeAsPolygonResponse response;
1189 for(
const types::KIID& padRequest : aCtx.
Request.pads() )
1191 KIID id( padRequest.value() );
1192 std::optional<BOARD_ITEM*> optPad =
getItemById(
id );
1194 if( !optPad || ( *optPad )->Type() !=
PCB_PAD_T )
1197 response.add_pads()->set_value( padRequest.value() );
1199 PAD*
pad =
static_cast<PAD*
>( *optPad );
1201 pad->TransformShapeToPolygon( poly,
pad->Padstack().EffectiveLayerFor( layer ), 0,
1204 types::PolygonWithHoles* polyMsg = response.mutable_polygons()->Add();
1215 using board::types::BoardLayer;
1218 !documentValidation )
1220 return tl::unexpected( documentValidation.error() );
1223 PadstackPresenceResponse response;
1227 for(
const int layer : aCtx.
Request.layers() )
1234 layers.
set( pcbLayer );
1237 for(
const types::KIID& padRequest : aCtx.
Request.items() )
1239 KIID id( padRequest.value() );
1240 std::optional<BOARD_ITEM*> optItem =
getItemById(
id );
1245 switch( ( *optItem )->Type() )
1249 PAD*
pad =
static_cast<PAD*
>( *optItem );
1253 PadstackPresenceEntry* entry = response.add_entries();
1254 entry->mutable_item()->set_value(
pad->m_Uuid.AsStdString() );
1256 entry->set_presence(
pad->FlashLayer( layer ) ? PSP_PRESENT : PSP_NOT_PRESENT );
1268 PadstackPresenceEntry* entry = response.add_entries();
1269 entry->mutable_item()->set_value(
via->m_Uuid.AsStdString() );
1271 entry->set_presence(
via->FlashLayer( layer ) ? PSP_PRESENT : PSP_NOT_PRESENT );
1291 if( !documentValidation )
1292 return tl::unexpected( documentValidation.error() );
1294 ExpandTextVariablesResponse reply;
1297 std::function<bool( wxString* )> textResolver =
1298 [&]( wxString* token ) ->
bool
1301 return board->ResolveTextVar( token, 0 );
1304 for(
const std::string& textMsg : aCtx.
Request.text() )
1308 if( aCtx.
Request.expand_env_vars() )
1311 reply.add_text(
text.ToUTF8() );
1321 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"InteractiveMoveItems" ) )
1322 return tl::unexpected( *headless );
1326 if( !documentValidation )
1327 return tl::unexpected( documentValidation.error() );
1329 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1330 return tl::unexpected( *busy );
1333 std::vector<EDA_ITEM*> toSelect;
1335 for(
const kiapi::common::types::KIID&
id : aCtx.
Request.items() )
1337 if( std::optional<BOARD_ITEM*> item =
getItemById(
KIID(
id.value() ) ) )
1338 toSelect.emplace_back(
static_cast<EDA_ITEM*
>( *item ) );
1341 if( toSelect.empty() )
1343 ApiResponseStatus e;
1344 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1345 e.set_error_message( fmt::format(
"None of the given items exist on the board",
1346 aCtx.
Request.board().board_filename() ) );
1347 return tl::unexpected( e );
1368 if( !containerResult && containerResult.error().status() == ApiStatusCode::AS_UNHANDLED )
1371 ApiResponseStatus e;
1372 e.set_status( ApiStatusCode::AS_UNHANDLED );
1373 return tl::unexpected( e );
1375 else if( !containerResult )
1377 return tl::unexpected( containerResult.error() );
1380 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1381 return tl::unexpected( *busy );
1386 FlipItemsResponse response;
1387 response.mutable_header()->CopyFrom( aCtx.
Request.header() );
1391 bool anyModified =
false;
1393 for(
const types::KIID&
id : aCtx.
Request.items() )
1395 ItemFlipResult*
result = response.add_flipped_items();
1397 std::optional<BOARD_ITEM*> optItem =
getItemById(
KIID(
id.value() ) );
1401 result->mutable_status()->set_code( ItemStatusCode::ISC_NONEXISTENT );
1402 result->mutable_status()->set_error_message(
1403 fmt::format(
"an item with UUID {} does not exist",
id.value() ) );
1409 static const std::set<KICAD_T> flippableTypes = {
1441 if( !flippableTypes.contains( itemType ) )
1443 result->mutable_status()->set_code( ItemStatusCode::ISC_INVALID_TYPE );
1444 result->mutable_status()->set_error_message(
1445 fmt::format(
"items of type {} cannot be flipped",
1446 magic_enum::enum_name( itemType ) ) );
1456 static_cast<FOOTPRINT*
>( boardItem )->InvalidateComponentClassCache();
1460 google::protobuf::Any itemBuf;
1462 *
result->mutable_item() = std::move( itemBuf );
1464 result->mutable_status()->set_code( ItemStatusCode::ISC_OK );
1467 response.set_status( ItemRequestStatus::IRS_OK );
1481 if( !documentValidation )
1482 return tl::unexpected( documentValidation.error() );
1484 SavedDocumentResponse response;
1485 response.mutable_document()->CopyFrom( aCtx.
Request.document() );
1489 [&](
const wxString& aData )
1491 response.set_contents( aData.ToUTF8() );
1503 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"SaveSelectionToString" ) )
1504 return tl::unexpected( *headless );
1508 SavedSelectionResponse response;
1516 [&](
const wxString& aData )
1518 response.set_contents( aData.ToUTF8() );
1533 if( !documentValidation )
1534 return tl::unexpected( documentValidation.error() );
1536 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1537 return tl::unexpected( *busy );
1539 CreateItemsResponse response;
1546 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"GetVisibleLayers" ) )
1547 return tl::unexpected( *headless );
1551 if( !documentValidation )
1552 return tl::unexpected( documentValidation.error() );
1554 BoardLayers response;
1565 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"SetVisibleLayers" ) )
1566 return tl::unexpected( *headless );
1570 if( !documentValidation )
1571 return tl::unexpected( documentValidation.error() );
1573 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1574 return tl::unexpected( *busy );
1579 for(
int layerIdx : aCtx.
Request.layers() )
1585 visible.
set( layer );
1593 editFrame->Refresh();
1601 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"GetActiveLayer" ) )
1602 return tl::unexpected( *headless );
1606 if( !documentValidation )
1607 return tl::unexpected( documentValidation.error() );
1611 BoardLayerResponse response;
1622 if( std::optional<ApiResponseStatus> headless =
checkForHeadless(
"SetActiveLayer" ) )
1623 return tl::unexpected( *headless );
1627 if( !documentValidation )
1628 return tl::unexpected( documentValidation.error() );
1630 if( std::optional<ApiResponseStatus> busy =
checkForBusy() )
1631 return tl::unexpected( *busy );
1635 if( !
board()->GetEnabledLayers().Contains( layer ) )
1637 ApiResponseStatus err;
1638 err.set_status( ApiStatusCode::AS_BAD_REQUEST );
1639 err.set_error_message( fmt::format(
"Layer {} is not a valid layer for the given board",
1640 magic_enum::enum_name( layer ) ) );
1641 return tl::unexpected( err );
KICOMMON_API types::KiCadObjectType ToProtoEnum(KICAD_T aValue)
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
std::unique_ptr< BOARD_ITEM > CreateGeneratorForType(const wxString &aGeneratorType, BOARD_ITEM_CONTAINER *aContainer)
std::unique_ptr< EDA_ITEM > CreateItemForType(KICAD_T aType, EDA_ITEM *aContainer)
static TOOL_ACTION selectionClear
Clear the current selection.
static TOOL_ACTION selectItems
Select a list of items (specified as the event parameter)
API_HANDLER_BOARD(std::shared_ptr< BOARD_CONTEXT > aContext, EDA_BASE_FRAME *aFrame=nullptr)
HANDLER_RESULT< commands::ExpandTextVariablesResponse > handleExpandTextVariables(const HANDLER_CONTEXT< commands::ExpandTextVariables > &aCtx)
HANDLER_RESULT< BoardEnabledLayersResponse > handleGetBoardEnabledLayers(const HANDLER_CONTEXT< GetBoardEnabledLayers > &aCtx)
std::unique_ptr< COMMIT > createCommit() override
Override this to create an appropriate COMMIT subclass for the frame in question.
HANDLER_RESULT< commands::SelectionResponse > handleGetSelection(const HANDLER_CONTEXT< commands::GetSelection > &aCtx)
HANDLER_RESULT< commands::SavedSelectionResponse > handleSaveSelectionToString(const HANDLER_CONTEXT< commands::SaveSelectionToString > &aCtx)
HANDLER_RESULT< Empty > handleSetActiveLayer(const HANDLER_CONTEXT< SetActiveLayer > &aCtx)
HANDLER_RESULT< BoardLayers > handleGetVisibleLayers(const HANDLER_CONTEXT< GetVisibleLayers > &aCtx)
TOOL_MANAGER * toolManager() const
GENERATOR_TOOL * ensureGeneratorTool() const
Creates the generator tool if needed (e.g. in headless mode); returns it if available.
HANDLER_RESULT< commands::SelectionResponse > handleAddToSelection(const HANDLER_CONTEXT< commands::AddToSelection > &aCtx)
HANDLER_RESULT< commands::CreateItemsResponse > handleParseAndCreateItemsFromString(const HANDLER_CONTEXT< commands::ParseAndCreateItemsFromString > &aCtx)
HANDLER_RESULT< Empty > handleClearSelection(const HANDLER_CONTEXT< commands::ClearSelection > &aCtx)
std::vector< KICAD_T > parseRequestedItemTypes(const google::protobuf::RepeatedField< int > &aTypes)
HANDLER_RESULT< Empty > handleInteractiveMoveItems(const HANDLER_CONTEXT< InteractiveMoveItems > &aCtx)
HANDLER_RESULT< BoardBoundingBoxResponse > handleGetBoardBoundingBox(const HANDLER_CONTEXT< GetBoardBoundingBox > &aCtx)
HANDLER_RESULT< types::ItemRequestStatus > handleCreateUpdateItemsInternal(bool aCreate, const std::string &aClientName, const types::ItemHeader &aHeader, const google::protobuf::RepeatedPtrField< google::protobuf::Any > &aItems, std::function< void(commands::ItemStatus, google::protobuf::Any)> aItemHandler) override
HANDLER_RESULT< BoardStackupResponse > handleGetStackup(const HANDLER_CONTEXT< GetBoardStackup > &aCtx)
void pushCurrentCommit(const std::string &aClientName, const wxString &aMessage) override
HANDLER_RESULT< commands::GetItemsResponse > handleGetItemsById(const HANDLER_CONTEXT< commands::GetItemsById > &aCtx)
std::optional< EDA_ITEM * > getItemFromDocument(const DocumentSpecifier &aDocument, const KIID &aId) override
void deleteItemsInternal(std::map< KIID, ItemDeletionStatus > &aItemsToDelete, const std::string &aClientName) override
HANDLER_RESULT< commands::SelectionResponse > handleRemoveFromSelection(const HANDLER_CONTEXT< commands::RemoveFromSelection > &aCtx)
HANDLER_RESULT< GraphicsDefaultsResponse > handleGetGraphicsDefaults(const HANDLER_CONTEXT< GetGraphicsDefaults > &aCtx)
HANDLER_RESULT< BoardLayerResponse > handleGetActiveLayer(const HANDLER_CONTEXT< GetActiveLayer > &aCtx)
HANDLER_RESULT< commands::GetBoundingBoxResponse > handleGetBoundingBox(const HANDLER_CONTEXT< commands::GetBoundingBox > &aCtx)
static HANDLER_RESULT< std::unique_ptr< BOARD_ITEM > > createItemForType(KICAD_T aType, BOARD_ITEM_CONTAINER *aContainer)
HANDLER_RESULT< commands::RunActionResponse > handleRunAction(const HANDLER_CONTEXT< commands::RunAction > &aCtx)
std::optional< ApiResponseStatus > checkForHeadless(const std::string &aCommandName) const
HANDLER_RESULT< commands::SavedDocumentResponse > handleSaveDocumentToString(const HANDLER_CONTEXT< commands::SaveDocumentToString > &aCtx)
HANDLER_RESULT< PadShapeAsPolygonResponse > handleGetPadShapeAsPolygon(const HANDLER_CONTEXT< GetPadShapeAsPolygon > &aCtx)
HANDLER_RESULT< Empty > handleFocusOnItems(const HANDLER_CONTEXT< commands::FocusOnItems > &aCtx)
std::shared_ptr< BOARD_CONTEXT > m_context
HANDLER_RESULT< PadstackPresenceResponse > handleCheckPadstackPresenceOnLayers(const HANDLER_CONTEXT< CheckPadstackPresenceOnLayers > &aCtx)
virtual BOARD_ITEM_CONTAINER * getDefaultContainer()
HANDLER_RESULT< Empty > handleSetVisibleLayers(const HANDLER_CONTEXT< SetVisibleLayers > &aCtx)
void regenerateGenerators(GENERATOR_TOOL *aTool, BOARD_COMMIT *aCommit, const std::vector< PCB_GENERATOR * > &aGenerators, std::function< void(const KIID &, commands::ItemStatus)> aResultHandler) const
std::optional< BOARD_ITEM * > getItemById(const KIID &aId) const
HANDLER_RESULT< FlipItemsResponse > handleFlipItems(const HANDLER_CONTEXT< FlipItems > &aCtx)
HANDLER_RESULT< bool > validateDocument(const DocumentSpecifier &aDocument)
HANDLER_RESULT< std::optional< KIID > > validateItemHeaderDocument(const kiapi::common::types::ItemHeader &aHeader)
If the header is valid, returns the item container.
API_HANDLER_EDITOR(EDA_BASE_FRAME *aFrame=nullptr)
COMMIT * getCurrentCommit(const std::string &aClientName)
virtual void pushCurrentCommit(const std::string &aClientName, const wxString &aMessage)
std::set< std::string > m_activeClients
std::map< std::string, std::pair< KIID, std::unique_ptr< COMMIT > > > m_commits
virtual std::optional< ApiResponseStatus > checkForBusy()
Checks if the editor can accept commands.
virtual types::DocumentType thisDocumentType() const =0
Override this to specify which document type this editor handles.
virtual void onModified()
void registerHandler(HANDLER_RESULT< ResponseType >(HandlerType::*aHandler)(const HANDLER_CONTEXT< RequestType > &), bool aAllowedDuringTask=false)
Registers an API command handler for the given message types.
void OnBoardChanged()
Update the panel contents from the application and board models.
BASE_SET & reset(size_t pos)
BASE_SET & set(size_t pos)
void RevertToCheckpoint(int aCheckpoint) override
Container for design settings for a BOARD object.
bool m_TextUpright[LAYER_CLASS_COUNT]
int m_TextThickness[LAYER_CLASS_COUNT]
int m_LineThickness[LAYER_CLASS_COUNT]
VECTOR2I m_TextSize[LAYER_CLASS_COUNT]
bool m_TextItalic[LAYER_CLASS_COUNT]
Abstract interface for BOARD_ITEMs capable of storing other items inside.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
virtual void CopyFrom(const BOARD_ITEM *aOther)
BOARD_ITEM_CONTAINER * GetParent() const
virtual void Normalize()
Perform any normalization required after a user rotate and/or flip.
virtual void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection)
Flip this object, i.e.
Information pertinent to a Pcbnew printed circuit board.
void SetVisibleLayers(const LSET &aLayerMask)
A proxy function that calls the correspondent function in m_BoardSettings changes the bit-mask of vis...
const BOX2I GetBoardEdgesBoundingBox() const
Return the board bounding box calculated using exclusively the board edges (graphics on Edge....
const LSET & GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
BOX2I ComputeBoundingBox(bool aBoardEdgesOnly=false, bool aPhysicalLayersOnly=false) const
Calculate the bounding box containing all board items (or board edge segments).
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
BOARD_DESIGN_SETTINGS & GetDesignSettings()
void SaveBoard(const wxString &aFileName, BOARD &aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aBoard to a storage file in a format that this PCB_IO implementation knows about or it can be u...
void SaveSelection(const PCB_SELECTION &selected, bool isFootprintEditor)
void SetWriter(std::function< void(const wxString &)> aWriter)
void SetBoard(BOARD *aBoard)
Represent a set of changes (additions, deletions or modifications) of a data model (e....
COMMIT & Remove(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Remove a new item from the model.
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
The base frame for deriving all KiCad main window classes.
The base class for create windows for drawing purpose.
A set of EDA_ITEMs (i.e., without duplicates).
virtual void FinalizeGroupDeserialization()
void AddItem(EDA_ITEM *aItem)
Add item to group.
A base class for most all the KiCad significant classes used in schematics and boards.
virtual VECTOR2I GetPosition() const
virtual const BOX2I GetBoundingBox() const
Return the orthogonal bounding box of this object for display purposes.
virtual EDA_GROUP * GetParentGroup() const
KICAD_T Type() const
Returns the type of object.
virtual void SetParentGroup(EDA_GROUP *aGroup)
virtual wxString GetFriendlyName() const
virtual void SetParent(EDA_ITEM *aParent)
std::string AsStdString() const
LSET is a set of PCB_LAYER_IDs.
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
static TOOL_ACTION genRemove
static TOOL_ACTION move
move or drag an item
Common, abstract interface for edit frames.
APPEARANCE_CONTROLS * GetAppearancePanel()
virtual void SetActiveLayer(PCB_LAYER_ID aLayer)
PCB_DRAW_PANEL_GAL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
virtual PCB_LAYER_ID GetActiveLayer() const
void SyncLayersVisibility(const BOARD *aBoard)
Update "visibility" property of each layer of a given BOARD.
A table whose cell text is derived from the board and rebuilt whenever it goes stale.
void RebuildCells(const BOARD &aBoard, GENERATED_TABLE_REFRESH *aRefresh=nullptr)
Regenerate the cells from the board.
A set of BOARD_ITEMs (i.e., without duplicates).
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
void SetReferencePoint(const VECTOR2I &aP)
virtual void Serialize(google::protobuf::Any &aContainer) const
Serializes this object to the given Any message.
virtual bool Deserialize(const google::protobuf::Any &aContainer)
Deserializes the given protobuf message into this object.
Represent a set of closed polygons.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
int RefreshGeneratedTables(BOARD &aBoard)
Bring every generated table on the board up to date and return how many were rebuilt.
PCB_LAYER_ID
A quick note on layer IDs:
void PackLayerSet(google::protobuf::RepeatedField< int > &aOutput, const LSET &aLayerSet)
void PackBoardStackup(const BOARD &aBoard, BoardStackup &aOut)
KICOMMON_API int UnpackDistance(const types::Distance &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API std::optional< KICAD_T > TypeNameFromAny(const google::protobuf::Any &aMessage)
KICOMMON_API ApiResponseStatus MakeResponseStatus(ApiStatusCode aCode, const std::string &aMessage)
KICOMMON_API void PackBox2(types::Box2 &aOutput, const BOX2I &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API std::optional< wxString > GeneratorTypeFromAny(const google::protobuf::Any &aMessage)
KICOMMON_API void PackPolyLine(types::PolyLine &aOutput, const SHAPE_LINE_CHAIN &aSlc, const EDA_IU_SCALE &aScale)
Class to handle a set of BOARD_ITEMs.
bool IsGeneratedTableCell(const EDA_ITEM *aItem)
True for a cell whose text is generated from the board, so only its formatting is the user's.
std::vector< EDA_ITEM * > EDA_ITEMS
RequestMessageType Request
wxString result
Test unit parsing edge cases and error handling.
constexpr KICAD_T BaseType(const KICAD_T aType)
Return the underlying type of the given type.
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
@ PCB_CONSTRAINT_T
a geometric constraint between board items
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
@ PCB_DRILL_MAP_T
class PCB_DRILL_MAP, drill symbols drawn at the holes
@ PCB_DIM_CENTER_T
class PCB_DIM_CENTER, a center point marking (graphic item)
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
@ PCB_ZONE_T
class ZONE, a copper pour area
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
@ PCB_3D_BODY_T
class PCB_3D_BODY, a 3D body (extruded or model) on a footprint
@ PCB_REFERENCE_IMAGE_T
class PCB_REFERENCE_IMAGE, bitmap on a layer
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
@ PCB_MARKER_T
class PCB_MARKER, a marker used to show something
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
@ PCB_TARGET_T
class PCB_TARGET, a target (graphic item)
@ PCB_TABLECELL_T
class PCB_TABLECELL, PCB_TEXTBOX for use in tables
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
@ PCB_GRID_ITEM_T
a subgrid placed on a board
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
@ PCB_PAD_T
class PAD, a pad in a footprint
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
@ PCB_DIMENSION_T
class PCB_DIMENSION_BASE: abstract dimension meta-type
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
@ PCB_STACKUP_TABLE_T
class PCB_STACKUP_TABLE, a live stackup table derived from PCB_TABLE
@ PCB_POINT_T
class PCB_POINT, a 0-dimensional point
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
@ PCB_DRILL_CHART_T
class PCB_DRILL_CHART, a live drill chart derived from PCB_TABLE
constexpr bool IsGeneratedTableType(const KICAD_T aType)
A PCB_TABLE subclass whose cells are generated from the board rather than typed by the user.