33#include <google/protobuf/empty.pb.h>
43using namespace kiapi::common::commands;
45using google::protobuf::Empty;
88 GetVersionResponse reply;
93 reply.mutable_version()->set_major( std::get<0>( version ) );
94 reply.mutable_version()->set_minor( std::get<1>( version ) );
95 reply.mutable_version()->set_patch( std::get<2>( version ) );
104 wxFileName fn( wxEmptyString, wxString::FromUTF8( aCtx.
Request.binary_name() ) );
106 fn.SetExt( wxT(
"exe" ) );
111 reply.set_path(
path.ToUTF8() );
119 if( !aAllowEmpty && ( aProject.name().empty() || aProject.path().empty() ) )
122 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
123 e.set_error_message(
"a project name and path must be specified" );
124 return tl::unexpected( e );
129 if( !aProject.name().empty() && aProject.name() != prj.
GetProjectName().utf8_string() )
132 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
133 e.set_error_message( fmt::format(
"the requested project {} is not open", aProject.name() ) );
134 return tl::unexpected( e );
137 if( !aProject.path().empty() && aProject.path() != prj.
GetProjectPath().utf8_string() )
140 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
141 e.set_error_message( fmt::format(
"the requested project {} is not open at path {}",
144 return tl::unexpected( e );
154 return tl::unexpected(
result.error() );
156 NetClassesResponse reply;
160 google::protobuf::Any
any;
162 netSettings->GetDefaultNetclass()->Serialize(
any );
164 if( !
any.UnpackTo( reply.add_net_classes() ) )
165 wxFAIL_MSG( wxT(
"Failed to unpack Default netclasss from internal serialization" ) );
167 for(
const std::shared_ptr<NETCLASS>& netClass : netSettings->GetNetclasses() | std::views::values )
169 netClass->Serialize(
any );
171 if( !
any.UnpackTo( reply.add_net_classes() ) )
173 wxFAIL_MSG( wxString::Format( wxT(
"Failed to unpack netclass %s from internal serialization" ),
174 netClass->GetName() ) );
185 return tl::unexpected(
result.error() );
189 std::map<wxString, std::shared_ptr<NETCLASS>> netClasses;
190 google::protobuf::Any
any;
192 if( aCtx.
Request.merge_mode() != MapMergeMode::MMM_REPLACE )
193 netClasses = netSettings->GetNetclasses();
195 for(
const kiapi::common::project::NetClass& ncProto : aCtx.
Request.net_classes() )
197 wxString
name = wxString::FromUTF8( ncProto.name() );
198 bool deserialized =
false;
200 if(
any.PackFrom( ncProto ) )
202 if(
name == wxT(
"Default" ) )
204 deserialized = netSettings->GetDefaultNetclass()->Deserialize(
any );
208 if( !netClasses.contains(
name ) )
209 netClasses.insert( {
name, std::make_shared<NETCLASS>(
name,
false ) } );
211 deserialized = netClasses[
name]->Deserialize(
any );
218 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
219 e.set_error_message( fmt::format(
"could not unpack netclass '{}'",
name.ToUTF8().data() ) );
220 return tl::unexpected( e );
224 netSettings->ClearNetclasses();
225 netSettings->SetNetclasses( netClasses );
236 return tl::unexpected(
result.error() );
240 NetClassAssignmentsResponse reply;
242 for(
const auto& [netName, netclassNames] : netSettings->GetNetclassLabelAssignments() )
244 project::NetClassAssignment* assignment = reply.add_assignments();
245 assignment->set_net( netName.ToUTF8() );
247 for(
const wxString& netclassName : netclassNames )
248 assignment->add_netclasses( netclassName.ToUTF8() );
251 for(
const auto& [matcher, netclassName] : netSettings->GetNetclassPatternAssignments() )
253 project::NetClassPatternAssignment* pattern = reply.add_pattern_assignments();
254 pattern->set_pattern( matcher->GetPattern().ToUTF8() );
255 pattern->set_netclass( netclassName.ToUTF8() );
266 return tl::unexpected(
result.error() );
270 std::set<wxString, std::less<>> knownNetclasses;
273 for(
const wxString&
name : netSettings->GetNetclasses() | std::views::keys )
274 knownNetclasses.insert(
name );
276 auto checkNetclassName =
277 [&](
const std::string& aName,
const char* aKind ) -> std::optional<ApiResponseStatus>
279 if( knownNetclasses.contains( wxString::FromUTF8( aName ) ) )
283 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
284 e.set_error_message( fmt::format(
"unknown netclass '{}' in {} assignment", aName, aKind ) );
288 for(
const project::NetClassAssignment& assignment : aCtx.
Request.assignments() )
290 if( assignment.net().empty() )
293 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
294 e.set_error_message(
"net name cannot be empty in a netclass assignment" );
295 return tl::unexpected( e );
298 for(
const std::string& netclassName : assignment.netclasses() )
300 if( std::optional<ApiResponseStatus> err = checkNetclassName( netclassName,
"net" ) )
301 return tl::unexpected( *err );
305 for(
const project::NetClassPatternAssignment& pattern : aCtx.
Request.pattern_assignments() )
307 if( pattern.pattern().empty() )
310 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
311 e.set_error_message(
"pattern cannot be empty in a netclass pattern assignment" );
312 return tl::unexpected( e );
315 if( !pattern.netclass().empty() )
317 if( std::optional<ApiResponseStatus> err = checkNetclassName( pattern.netclass(),
"pattern" ) )
318 return tl::unexpected( *err );
322 if( aCtx.
Request.merge_mode() == MapMergeMode::MMM_REPLACE )
324 netSettings->ClearNetclassLabelAssignments();
325 netSettings->ClearNetclassPatternAssignments();
328 for(
const project::NetClassAssignment& assignment : aCtx.
Request.assignments() )
330 std::set<wxString> netclasses;
332 for(
const std::string& netclassName : assignment.netclasses() )
333 netclasses.insert( wxString::FromUTF8( netclassName ) );
335 if( netclasses.empty() )
336 netSettings->ClearNetclassLabelAssignment( wxString::FromUTF8( assignment.net() ) );
338 netSettings->SetNetclassLabelAssignment( wxString::FromUTF8( assignment.net() ), netclasses );
341 for(
const project::NetClassPatternAssignment& pattern : aCtx.
Request.pattern_assignments() )
343 std::vector<std::pair<std::unique_ptr<EDA_COMBINED_MATCHER>, wxString>> kept;
345 for(
auto& existing : netSettings->GetNetclassPatternAssignments() )
347 if( existing.first->GetPattern() != wxString::FromUTF8( pattern.pattern() ) )
348 kept.emplace_back( std::move( existing ) );
351 netSettings->SetNetclassPatternAssignments( std::move( kept ) );
353 if( !pattern.netclass().empty() )
355 netSettings->SetNetclassPatternAssignment( wxString::FromUTF8( pattern.pattern() ),
356 wxString::FromUTF8( pattern.netclass() ) );
360 netSettings->ClearAllCaches();
376 google::protobuf::Any
any;
381 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
382 e.set_error_message(
"Could not decode text in GetTextExtents message" );
383 return tl::unexpected( e );
386 types::Box2 response;
394 response.mutable_position()->set_x_nm( bbox.
GetPosition().
x );
395 response.mutable_position()->set_y_nm( bbox.
GetPosition().
y );
396 response.mutable_size()->set_x_nm( bbox.
GetSize().
x );
397 response.mutable_size()->set_y_nm( bbox.
GetSize().
y );
406 GetTextAsShapesResponse reply;
408 for(
const TextOrTextBox& textMsg : aCtx.
Request.text() )
411 const Text* textPtr = &textMsg.text();
413 if( textMsg.has_textbox() )
415 dummyText.set_text( textMsg.textbox().text() );
416 dummyText.mutable_attributes()->CopyFrom( textMsg.textbox().attributes() );
417 textPtr = &dummyText;
421 google::protobuf::Any
any;
423 if( !
any.PackFrom( *textPtr ) || !
text.Deserialize(
any ) )
426 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
427 e.set_error_message(
"Could not decode text in GetTextAsShapes message" );
428 return tl::unexpected( e );
431 std::shared_ptr<SHAPE_COMPOUND> shapes =
text.GetEffectiveTextShape(
false );
433 TextWithShapes* entry = reply.add_text_with_shapes();
434 entry->mutable_text()->CopyFrom( textMsg );
436 for(
SHAPE* subshape : shapes->Shapes() )
440 GraphicShape* shapeMsg = entry->mutable_shapes()->add_shapes();
442 if( !
any.UnpackTo( shapeMsg ) )
443 wxFAIL_MSG( wxT(
"Failed to unpack text-as-shapes component from internal serialization" ) );
446 if( textMsg.has_textbox() && textMsg.textbox().border_enabled() )
448 GraphicShape* border = entry->mutable_shapes()->add_shapes();
449 int width = (int) textMsg.textbox().attributes().stroke_width().value_nm();
450 border->mutable_attributes()->mutable_stroke()->mutable_width()->set_value_nm( width );
455 PackVector2( *border->mutable_segment()->mutable_start(), tl );
459 border = entry->mutable_shapes()->add_shapes();
460 border->mutable_attributes()->mutable_stroke()->mutable_width()->set_value_nm( width );
462 PackVector2( *border->mutable_segment()->mutable_end(), br );
465 border = entry->mutable_shapes()->add_shapes();
466 border->mutable_attributes()->mutable_stroke()->mutable_width()->set_value_nm( width );
467 PackVector2( *border->mutable_segment()->mutable_start(), br );
471 border = entry->mutable_shapes()->add_shapes();
472 border->mutable_attributes()->mutable_stroke()->mutable_width()->set_value_nm( width );
474 PackVector2( *border->mutable_segment()->mutable_end(), tl );
485 if( !aCtx.
Request.has_document() || aCtx.
Request.document().type() != DOCTYPE_PROJECT )
488 e.set_status( ApiStatusCode::AS_UNHANDLED );
490 return tl::unexpected( e );
493 ExpandTextVariablesResponse reply;
496 for(
const std::string& textMsg : aCtx.
Request.text() )
500 if( aCtx.
Request.expand_env_vars() )
503 reply.add_text(
result.ToUTF8() );
513 wxString identifier = wxString::FromUTF8( aCtx.
Request.identifier() );
515 if( identifier.IsEmpty() )
518 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
519 e.set_error_message(
"plugin identifier is missing" );
520 return tl::unexpected( e );
526 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
527 e.set_error_message(
"plugin identifier is invalid" );
528 return tl::unexpected( e );
532 path.AppendDir(
"plugins" );
537 path.AppendDir( identifier );
539 StringResponse reply;
540 reply.set_response(
path.GetPath() );
548 if( !aCtx.
Request.has_document() || aCtx.
Request.document().type() != DOCTYPE_PROJECT )
551 e.set_status( ApiStatusCode::AS_UNHANDLED );
553 return tl::unexpected( e );
559 return tl::unexpected(
result.error() );
567 e.set_status( ApiStatusCode::AS_NOT_READY );
568 e.set_error_message(
"no valid project is loaded, cannot get text variables" );
569 return tl::unexpected( e );
572 const std::map<wxString, wxString>& vars =
project.GetTextVars();
574 project::TextVariables reply;
575 auto map = reply.mutable_variables();
577 for(
const auto& [key, value] : vars )
578 ( *map )[ std::string( key.ToUTF8() ) ] = value.ToUTF8();
587 if( !aCtx.
Request.has_document() || aCtx.
Request.document().type() != DOCTYPE_PROJECT )
590 e.set_status( ApiStatusCode::AS_UNHANDLED );
592 return tl::unexpected( e );
598 return tl::unexpected(
result.error() );
606 e.set_status( ApiStatusCode::AS_NOT_READY );
607 e.set_error_message(
"no valid project is loaded, cannot set text variables" );
608 return tl::unexpected( e );
611 const project::TextVariables& newVars = aCtx.
Request.variables();
612 std::map<wxString, wxString>& vars =
project.GetTextVars();
614 if( aCtx.
Request.merge_mode() == MapMergeMode::MMM_REPLACE )
617 for(
const auto& [key, value] : newVars.variables() )
618 vars[wxString::FromUTF8( key )] = wxString::FromUTF8( value );
620 if( !
Pgm().GetSettingsManager().SaveProject() )
623 e.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
624 e.set_error_message(
"failed to save project text variables" );
625 return tl::unexpected( e );
638 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
639 e.set_error_message(
"OpenDocument is not available in this KiCad mode" );
640 return tl::unexpected( e );
653 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
654 e.set_error_message(
"CloseDocument is not available in this KiCad mode" );
655 return tl::unexpected( e );
668 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
669 e.set_error_message(
"CreateDocument is not available in this KiCad mode" );
670 return tl::unexpected( e );
682 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
683 e.set_error_message(
"CloseAllDocuments is not available in this KiCad mode" );
684 return tl::unexpected( e );
693 GetPathsResponse reply;
695 auto addPath = [&]( types::PathType aType,
const wxString& aPath )
697 PathEntry* entry = reply.add_paths();
698 entry->set_type( aType );
699 entry->set_path( aPath.ToUTF8() );
718 if( !aCtx.
Request.has_token() || aCtx.
Request.token().value().empty() )
721 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
722 e.set_error_message(
"no task token provided" );
723 return tl::unexpected( e );
726 std::optional<tasks::TaskStatusResponse> status =
732 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
733 e.set_error_message( fmt::format(
"unknown task token {}", aCtx.
Request.token().value() ) );
734 return tl::unexpected( e );
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
constexpr EDA_IU_SCALE pcbIUScale
const std::tuple< int, int, int > & GetMajorMinorPatchTuple()
Get the build version numbers as a tuple.
wxString GetBuildVersion()
Get the full KiCad version string.
HANDLER_RESULT< Empty > handlePing(const HANDLER_CONTEXT< commands::Ping > &aCtx)
HANDLER_RESULT< types::Box2 > handleGetTextExtents(const HANDLER_CONTEXT< commands::GetTextExtents > &aCtx)
CLOSE_ALL_DOCUMENTS_HANDLER m_closeAllDocumentsHandler
HANDLER_RESULT< tasks::TaskStatusResponse > handleGetTaskStatus(const HANDLER_CONTEXT< tasks::GetTaskStatus > &aCtx)
HANDLER_RESULT< commands::GetTextAsShapesResponse > handleGetTextAsShapes(const HANDLER_CONTEXT< commands::GetTextAsShapes > &aCtx)
HANDLER_RESULT< commands::GetVersionResponse > handleGetVersion(const HANDLER_CONTEXT< commands::GetVersion > &aCtx)
CREATE_DOCUMENT_HANDLER m_createDocumentHandler
HANDLER_RESULT< Empty > handleCloseAllDocuments(const HANDLER_CONTEXT< commands::CloseAllDocuments > &aCtx)
HANDLER_RESULT< Empty > handleSetNetClassAssignments(const HANDLER_CONTEXT< commands::SetNetClassAssignments > &aCtx)
HANDLER_RESULT< commands::OpenDocumentResponse > handleCreateDocument(const HANDLER_CONTEXT< commands::CreateDocument > &aCtx)
HANDLER_RESULT< commands::NetClassAssignmentsResponse > handleGetNetClassAssignments(const HANDLER_CONTEXT< commands::GetNetClassAssignments > &aCtx)
HANDLER_RESULT< commands::PathResponse > handleGetKiCadBinaryPath(const HANDLER_CONTEXT< commands::GetKiCadBinaryPath > &aCtx)
HANDLER_RESULT< commands::NetClassesResponse > handleGetNetClasses(const HANDLER_CONTEXT< commands::GetNetClasses > &aCtx)
CLOSE_DOCUMENT_HANDLER m_closeDocumentHandler
OPEN_DOCUMENT_HANDLER m_openDocumentHandler
HANDLER_RESULT< Empty > handleCloseDocument(const HANDLER_CONTEXT< commands::CloseDocument > &aCtx)
HANDLER_RESULT< Empty > handleSetNetClasses(const HANDLER_CONTEXT< commands::SetNetClasses > &aCtx)
static tl::expected< bool, ApiResponseStatus > validateProject(const ProjectSpecifier &aProject, bool aAllowEmpty=false)
HANDLER_RESULT< commands::StringResponse > handleGetPluginSettingsPath(const HANDLER_CONTEXT< commands::GetPluginSettingsPath > &aCtx)
HANDLER_RESULT< commands::OpenDocumentResponse > handleOpenDocument(const HANDLER_CONTEXT< commands::OpenDocument > &aCtx)
HANDLER_RESULT< commands::ExpandTextVariablesResponse > handleExpandTextVariables(const HANDLER_CONTEXT< commands::ExpandTextVariables > &aCtx)
HANDLER_RESULT< Empty > handleSetTextVariables(const HANDLER_CONTEXT< commands::SetTextVariables > &aCtx)
HANDLER_RESULT< commands::GetPathsResponse > handleGetPaths(const HANDLER_CONTEXT< commands::GetPaths > &aCtx)
HANDLER_RESULT< project::TextVariables > handleGetTextVariables(const HANDLER_CONTEXT< commands::GetTextVariables > &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.
void requestNetSettingsNotification()
static bool IsValidIdentifier(const wxString &aIdentifier)
std::optional< kiapi::common::tasks::TaskStatusResponse > GetStatus(const std::string &aToken) const
Get a snapshot of the task's current status.
static API_TASK_SCHEDULER & Instance()
constexpr const Vec & GetPosition() const
const BOX2< Vec > GetBoundingBoxRotated(const VECTOR2I &aRotCenter, const EDA_ANGLE &aAngle) const
Useful to calculate bounding box of rotated items, when rotation is not cardinal.
constexpr const SizeVec & GetSize() const
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
static const char Default[]
the name of the default NETCLASS
static wxString GetUserPluginsPath()
Gets the user path for plugins.
static wxString GetStockSymbolsPath()
Gets the stock (install) symbols path.
static wxString GetUserTemplatesPath()
Gets the user path for custom templates.
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
static wxString GetStock3dmodelsPath()
Gets the stock (install) 3dmodels path.
static wxString GetStockTemplatesPath()
Gets the stock (install) templates path.
static wxString GetUserSettingsPath()
Return the user configuration path used to store KiCad's configuration files.
static wxString GetStockDesignBlocksPath()
Gets the stock (install) footprints path.
static wxString GetStockFootprintsPath()
Gets the stock (install) footprints path.
virtual SETTINGS_MANAGER & GetSettingsManager() const
std::shared_ptr< NET_SETTINGS > m_NetSettings
Net settings for this project (owned here)
Container for project specific data.
virtual const wxString GetProjectPath() const
Return the full path of the project.
virtual const wxString GetProjectName() const
Return the short name of the project.
virtual PROJECT_FILE & GetProjectFile() const
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
An abstract shape on 2D plane.
A type-safe container of any type.
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)
static std::string ToStdString(const wxString &aStr)
wxString FindKicadFile(const wxString &shortname)
Search the executable file shortname in KiCad binary path and return full file name if found or short...
KICOMMON_API VECTOR2I UnpackVector2(const types::Vector2 &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API void PackVector2(types::Vector2 &aOutput, const VECTOR2I &aInput, const EDA_IU_SCALE &aScale)
PGM_BASE & Pgm()
The global program "get" accessor.
RequestMessageType Request
wxString result
Test unit parsing edge cases and error handling.
VECTOR2< int32_t > VECTOR2I