KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_handler_sch_tasks.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 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <api/api_handler_sch.h>
23
24#include <connection_graph.h>
26#include <erc/erc.h>
27#include <erc/erc_item.h>
28#include <erc/erc_settings.h>
29#include <fmt.h>
30#include <kiway.h>
31#include <layer_ids.h>
33#include <project_sch.h>
34#include <sch_edit_frame.h>
35#include <sch_marker.h>
36#include <sch_screen.h>
37#include <schematic.h>
38#include <string_utils.h>
41
42#include <api/api_enums.h>
43#include <api/api_utils.h>
44#include <api/common/tasks.pb.h>
45#include <api/schematic/schematic_tasks.pb.h>
46
47#include <algorithm>
48#include <memory>
49
50using kiapi::common::tasks::StartTaskResponse;
51using kiapi::common::tasks::TaskState;
52using kiapi::common::tasks::TaskStatusResponse;
53using kiapi::common::tasks::TS_CANCELLED;
54using kiapi::common::tasks::TS_FAILED;
55using kiapi::common::tasks::TS_RUNNING;
56using kiapi::common::tasks::TS_UNKNOWN;
57using kiapi::schematic::tasks::ErcTaskResult;
58using kiapi::schematic::tasks::GetErcTaskResult;
59using kiapi::schematic::tasks::StartErcTask;
60
61
63{
64public:
65 ERC_TASK( API_HANDLER_SCH* aHandler, SCHEMATIC* aSchematic ) :
66 m_handler( aHandler ),
67 m_schematic( aSchematic )
68 {
69 }
70
71 void Run() override
72 {
73 SCH_EDIT_FRAME* frame = m_handler->frame();
74
75 if( frame )
76 frame->ClearErcMarkers();
77
79 adapter->AsyncLoad();
80 adapter->BlockUntilLoaded();
81
82 ERC_TESTER ercTester( m_schematic );
83
84 DS_PROXY_VIEW_ITEM* drawingSheetRaw = new DS_PROXY_VIEW_ITEM(
85 schIUScale, &m_schematic->RootScreen()->GetPageSettings(),
86 &m_schematic->Project(), &m_schematic->RootScreen()->GetTitleBlock(),
87 m_schematic->GetProperties() );
88 drawingSheetRaw->SetPageNumber( TO_UTF8( m_schematic->RootScreen()->GetPageNumber() ) );
89 drawingSheetRaw->SetSheetCount( m_schematic->RootScreen()->GetPageCount() );
90 drawingSheetRaw->SetFileName( TO_UTF8( m_schematic->RootScreen()->GetFileName() ) );
93 drawingSheetRaw->SetIsFirstPage( m_schematic->RootScreen()->GetVirtualPageNumber() == 1 );
94
95 wxString variant = m_schematic->GetCurrentVariant();
96 drawingSheetRaw->SetVariantName( TO_UTF8( variant ) );
97 drawingSheetRaw->SetVariantDesc( TO_UTF8( m_schematic->GetVariantDescription( variant ) ) );
98
99 drawingSheetRaw->SetSheetName( "" );
100 drawingSheetRaw->SetSheetPath( "" );
101 std::unique_ptr<DS_PROXY_VIEW_ITEM> drawingSheet( drawingSheetRaw );
102
103 KIWAY* kiway = m_handler->context()->GetKiway();
104
105 std::unique_ptr<API_TASK_GUI_PROGRESS_REPORTER> reporter;
106
107 if( frame )
108 reporter = std::make_unique<API_TASK_GUI_PROGRESS_REPORTER>( frame, _( "Running ERC" ), 1, 0 );
109
110 ercTester.RunTests( drawingSheet.get(), frame,
111 kiway ? kiway->KiFACE( KIWAY::FACE_CVPCB ) : nullptr,
112 &m_schematic->Project(), reporter.get() );
113
114 reporter.reset();
115
116 if( frame )
117 frame->RefreshErcMarkers();
118
119 buildResult();
120 }
121
122 void FillStatus( TaskStatusResponse& aStatus ) const override
123 {
124 if( m_state != TS_UNKNOWN )
125 aStatus.set_state( m_state );
126
127 if( !m_errorMessage.empty() )
128 aStatus.set_error_message( m_errorMessage );
129 }
130
131 ErcTaskResult Result() const
132 {
133 return m_result;
134 }
135
136private:
138 {
139 m_result.Clear();
140
141 std::vector<SCH_MARKER*> markers;
142
143 SCH_SCREENS screens( m_schematic->Root() );
144
145 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
146 {
147 for( SCH_ITEM* item : screen->Items() )
148 {
149 if( item->Type() == SCH_MARKER_T )
150 markers.push_back( static_cast<SCH_MARKER*>( item ) );
151 }
152 }
153
154 std::stable_sort( markers.begin(), markers.end(),
155 []( const SCH_MARKER* a, const SCH_MARKER* b )
156 {
157 auto rank = []( SEVERITY aSeverity )
158 {
159 return aSeverity == RPT_SEVERITY_IGNORE
160 || aSeverity == RPT_SEVERITY_DEBUG
161 ? 0
162 : static_cast<int>( aSeverity );
163 };
164
165 return rank( a->GetSeverity() ) > rank( b->GetSeverity() );
166 } );
167
168 for( SCH_MARKER* marker : markers )
169 {
170 if( marker->GetSeverity() == RPT_SEVERITY_EXCLUSION )
171 m_result.set_excluded_count( m_result.excluded_count() + 1 );
172
173 kiapi::schematic::ErcMarker markerMsg;
174 SCH_MARKER::ToProto( markerMsg, *marker );
175 *m_result.add_violations() = std::move( markerMsg );
176 }
177
178 for( const std::reference_wrapper<RC_ITEM>& item : ERC_ITEM::GetItemsWithSeverities() )
179 {
180 int code = item.get().GetErrorCode();
181
182 if( code > 0 && m_schematic->ErcSettings().GetSeverity( code ) == RPT_SEVERITY_IGNORE )
183 m_result.set_ignored_count( m_result.ignored_count() + 1 );
184 }
185 }
186
189
190 TaskState m_state = TS_UNKNOWN;
191 std::string m_errorMessage;
192
193 ErcTaskResult m_result;
194};
195
196
198{
199 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
200
201 if( !documentValidation )
202 return tl::unexpected( documentValidation.error() );
203
204 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
205 return tl::unexpected( *busy );
206
208
209 if( !schematic )
210 {
211 ApiResponseStatus e;
212 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
213 e.set_error_message( "no schematic is open" );
214 return tl::unexpected( e );
215 }
216
217 auto task = std::make_shared<API_HANDLER_SCH::ERC_TASK>( this, schematic );
218
219 std::optional<std::string> token = API_TASK_SCHEDULER::Instance().StartTask( task, wxS( "ERC" ) );
220
221 if( !token.has_value() )
222 {
223 ApiResponseStatus e;
224 e.set_status( ApiStatusCode::AS_BUSY );
225 e.set_error_message( "another task is already running" );
226 return tl::unexpected( e );
227 }
228
229 StartTaskResponse response;
230 response.mutable_token()->set_value( *token );
231 return response;
232}
233
234
236{
237 if( !aCtx.Request.has_token() || aCtx.Request.token().value().empty() )
238 {
239 ApiResponseStatus e;
240 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
241 e.set_error_message( "no task token provided" );
242 return tl::unexpected( e );
243 }
244
245 std::optional<TaskStatusResponse> status = API_TASK_SCHEDULER::Instance().GetStatus( aCtx.Request.token().value() );
246
247 if( !status )
248 {
249 ApiResponseStatus e;
250 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
251 e.set_error_message( fmt::format( "unknown task token {}", aCtx.Request.token().value() ) );
252 return tl::unexpected( e );
253 }
254
255 if( status->state() == TS_RUNNING )
256 {
257 ApiResponseStatus e;
258 e.set_status( ApiStatusCode::AS_BUSY );
259 e.set_error_message( "the ERC task is still running" );
260 return tl::unexpected( e );
261 }
262
263 if( status->state() == TS_FAILED || status->state() == TS_CANCELLED )
264 {
265 ApiResponseStatus e;
266 e.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
267 e.set_error_message( status->error_message().empty() ? std::string( "ERC task failed" )
268 : status->error_message() );
269 return tl::unexpected( e );
270 }
271
272 std::shared_ptr<API_TASK> task = API_TASK_SCHEDULER::Instance().GetFinishedTask( aCtx.Request.token().value() );
273
274 if( !task )
275 {
276 ApiResponseStatus e;
277 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
278 e.set_error_message( fmt::format( "no completed task with token {}", aCtx.Request.token().value() ) );
279 return tl::unexpected( e );
280 }
281
282 auto* ercTask = dynamic_cast<API_HANDLER_SCH::ERC_TASK*>( task.get() );
283
284 if( !ercTask )
285 {
286 ApiResponseStatus e;
287 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
288 e.set_error_message( "task is not an ERC task" );
289 return tl::unexpected( e );
290 }
291
292 return ercTask->Result();
293}
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
Definition api_handler.h:47
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
HANDLER_RESULT< bool > validateDocument(const DocumentSpecifier &aDocument)
virtual std::optional< ApiResponseStatus > checkForBusy()
Checks if the editor can accept commands.
ERC_TASK(API_HANDLER_SCH *aHandler, SCHEMATIC *aSchematic)
void FillStatus(TaskStatusResponse &aStatus) const override
void Run() override
The task runner; called on the main thread.
HANDLER_RESULT< kiapi::schematic::tasks::ErcTaskResult > handleGetErcTaskResult(const HANDLER_CONTEXT< kiapi::schematic::tasks::GetErcTaskResult > &aCtx)
SCHEMATIC * schematic() const
API_HANDLER_SCH(SCH_EDIT_FRAME *aFrame)
HANDLER_RESULT< kiapi::common::tasks::StartTaskResponse > handleStartErcTask(const HANDLER_CONTEXT< kiapi::schematic::tasks::StartErcTask > &aCtx)
SCH_EDIT_FRAME * frame() const
SCH_CONTEXT * context() const
std::shared_ptr< API_TASK > GetFinishedTask(const std::string &aToken) const
Look up a task that has finished, for result retrieval.
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()
std::optional< std::string > StartTask(const std::shared_ptr< API_TASK > &aTask, const wxString &aDescription)
Register a new task and begin running it.
void SetSheetPath(const std::string &aSheetPath)
Set the sheet path displayed in the title block.
void SetSheetCount(int aSheetCount)
Change the sheet-count number displayed in the title block.
void SetVariantName(const std::string &aVariant)
Set the current variant name and description to be shown on the drawing sheet.
void SetVariantDesc(const std::string &aVariantDesc)
void SetPageNumber(const std::string &aPageNumber)
Change the page number displayed in the title block.
void SetSheetName(const std::string &aSheetName)
Set the sheet name displayed in the title block.
void SetPageBorderColorLayer(int aLayerId)
Override the layer used to pick the color of the page border (normally LAYER_GRID)
void SetIsFirstPage(bool aIsFirstPage)
Change if this is first page.
void SetFileName(const std::string &aFileName)
Set the file name displayed in the title block.
void SetColorLayer(int aLayerId)
Can be used to override which layer ID is used for drawing sheet item colors.
static std::vector< std::reference_wrapper< RC_ITEM > > GetItemsWithSeverities()
Definition erc_item.h:75
SEVERITY GetSeverity(int aErrorCode) const
Runs the electrical rules checks and adds a SCH_MARKER for each violation.
Definition erc.h:60
void RunTests(DS_PROXY_VIEW_ITEM *aDrawingSheet, SCH_EDIT_FRAME *aEditFrame, KIFACE *aCvPcb, PROJECT *aProject, PROGRESS_REPORTER *aProgressReporter)
Definition erc.cpp:3522
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
@ FACE_CVPCB
Definition kiway.h:357
void AsyncLoad()
Loads all available libraries for this adapter type in the background.
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Holds all the data relating to one schematic.
Definition schematic.h:155
ERC_SETTINGS & ErcSettings() const
virtual SCHEMATIC * GetSchematic() const =0
Schematic editor (Eeschema) main window.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
SEVERITY GetSeverity() const override
static void ToProto(kiapi::schematic::ErcMarker &aMsg, const SCH_MARKER &aMarker)
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
SCH_SCREEN * GetNext()
SCH_SCREEN * GetFirst()
An interface to the global shared library manager that is schematic-specific and linked to one projec...
#define _(s)
@ LAYER_SCHEMATIC_DRAWINGSHEET
Definition layer_ids.h:527
@ LAYER_SCHEMATIC_PAGE_LIMITS
Definition layer_ids.h:528
@ RPT_SEVERITY_EXCLUSION
@ RPT_SEVERITY_IGNORE
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
RequestMessageType Request
Definition api_handler.h:54
IbisParser parser & reporter
@ SCH_MARKER_T
Definition typeinfo.h:154