KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_handler_sch.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 (C) 2024 Jon Evans <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
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#include <api/api_handler_sch.h>
22#include <api/api_enums.h>
23#include <api/api_sch_utils.h>
24#include <api/api_utils.h>
25#include <api/api_server.h>
27#include <api/sch_context.h>
28#include <fmt.h>
29#include <fmt/ranges.h>
30#include <wx/log.h>
31#include <magic_enum.hpp>
32#include <base_screen.h>
33#include <base_units.h>
34#include <jobs/job_export_bom.h>
37#include <kiway.h>
39#include <sch_field.h>
40#include <sch_group.h>
41#include <common.h>
42#include <connection_graph.h>
44#include <advanced_config.h>
45#include <sch_commit.h>
46#include <string_utils.h>
47#include <sch_edit_frame.h>
49#include <ki_error.h>
50#include <pgm_base.h>
51#include <richio.h>
53
54#include <sch_label.h>
55#include <sch_screen.h>
56#include <sch_sheet.h>
57#include <sch_sheet_path.h>
58#include <sch_sheet_pin.h>
59#include <sch_symbol.h>
60#include <schematic.h>
62#include <tool/actions.h>
63#include <tool/common_tools.h>
64#include <tool/tool_manager.h>
65#include <tools/sch_actions.h>
67#include <project.h>
69#include <wx/filename.h>
70
71#include <api/common/commands/library_commands.pb.h>
72#include <api/common/types/base_types.pb.h>
74#include <project_sch.h>
75#include <trace_helpers.h>
76
77using namespace kiapi::common::commands;
78using kiapi::common::types::CommandStatus;
79using kiapi::common::types::DocumentType;
80using kiapi::common::types::ItemRequestStatus;
81
82
83std::set<KICAD_T> API_HANDLER_SCH::s_allowedTypes = {
102};
103
104
106{
107 types::RunJobResponse response;
109 int exitCode = aKiway->ProcessJob( KIWAY::FACE_SCH, &aJob, &reporter );
110
111 for( const JOB_OUTPUT& output : aJob.GetOutputs() )
112 response.add_output_path( output.m_outputPath.ToUTF8() );
113
114 if( exitCode == 0 )
115 {
116 response.set_status( types::JobStatus::JS_SUCCESS );
117 return response;
118 }
119
120 response.set_status( types::JobStatus::JS_ERROR );
121 response.set_message( fmt::format( "Schematic export job '{}' failed with exit code {}: {}",
122 aJob.GetType(), exitCode,
123 reporter.GetMessages().ToStdString() ) );
124 return response;
125}
126
127
132
133
134API_HANDLER_SCH::API_HANDLER_SCH( std::shared_ptr<SCH_CONTEXT> aContext,
135 SCH_EDIT_FRAME* aFrame ) :
136 API_HANDLER_EDITOR( aFrame ),
137 m_context( std::move( aContext ) )
138{
139 using namespace kiapi::schematic::jobs;
140 using namespace kiapi::schematic::types;
141 using namespace kiapi::schematic::commands;
142
151
158
165
204}
205
206
207std::unique_ptr<COMMIT> API_HANDLER_SCH::createCommit()
208{
209 if( m_frame )
210 return std::make_unique<SCH_COMMIT>( static_cast<SCH_EDIT_FRAME*>( m_frame ) );
211
212 return std::make_unique<SCH_COMMIT>( toolManager() );
213}
214
215
217{
218 wxCHECK( m_context, nullptr );
219 return m_context->GetSchematic();
220}
221
222
224{
225 return static_cast<SCH_EDIT_FRAME*>( m_frame );
226}
227
228
229std::optional<ApiResponseStatus> API_HANDLER_SCH::checkForHeadless( const std::string& aCommandName ) const
230{
231 if( m_frame )
232 return std::nullopt;
233
234 ApiResponseStatus e;
235 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
236 e.set_error_message( fmt::format( "{} is not available in headless mode", aCommandName ) );
237 return e;
238}
239
240
241bool API_HANDLER_SCH::packSchItem( google::protobuf::Any& aOut, SCH_ITEM* aItem,
242 const SCH_SHEET_PATH& aPath )
243{
244 if( aItem->Type() == SCH_SYMBOL_T )
245 {
246 kiapi::schematic::types::SchematicSymbolInstance symbol;
247
248 if( !PackSymbol( &symbol, static_cast<SCH_SYMBOL*>( aItem ), aPath ) )
249 return false;
250
251 if( !aOut.PackFrom( symbol ) )
252 {
253 wxFAIL_MSG( wxT( "Failed to pack SCH_SYMBOL" ) );
254 return false;
255 }
256 }
257 else if( aItem->Type() == SCH_SHEET_T )
258 {
259 kiapi::schematic::types::SheetSymbol sheet;
260
261 if( !PackSheet( &sheet, static_cast<SCH_SHEET*>( aItem ), aPath ) )
262 return false;
263
264 if( !aOut.PackFrom( sheet ) )
265 {
266 wxFAIL_MSG( wxT( "Failed to pack SCH_SHEET" ) );
267 return false;
268 }
269 }
270 else
271 {
272 aItem->Serialize( aOut );
273 }
274
275 return true;
276}
277
278
279std::optional<SCH_ITEM*> API_HANDLER_SCH::getItemById( const KIID& aId, SCH_SHEET_PATH* aPathOut ) const
280{
281 if( !schematic()->HasHierarchy() )
283
284 SCH_ITEM* item = schematic()->ResolveItem( aId, aPathOut, true );
285
286 if( !item )
287 return std::nullopt;
288
289 return item;
290}
291
292
293tl::expected<bool, ApiResponseStatus>
294API_HANDLER_SCH::validateDocumentInternal( const DocumentSpecifier& aDocument ) const
295{
296 if( aDocument.type() != DocumentType::DOCTYPE_SCHEMATIC )
297 {
298 ApiResponseStatus e;
299 e.set_status( ApiStatusCode::AS_UNHANDLED );
300 return tl::unexpected( e );
301 }
302
303 const PROJECT& prj = m_context->Prj();
304
305 if( aDocument.project().name().compare( prj.GetProjectName().ToUTF8() ) != 0 )
306 {
307 ApiResponseStatus e;
308 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
309 e.set_error_message( fmt::format( "the requested project {} is not open",
310 aDocument.project().name() ) );
311 return tl::unexpected( e );
312 }
313
314 if( aDocument.project().path().compare( prj.GetProjectPath().ToUTF8() ) != 0 )
315 {
316 ApiResponseStatus e;
317 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
318 e.set_error_message( fmt::format( "the requested project {} is not open at path {}",
319 aDocument.project().name(),
320 aDocument.project().path() ) );
321 return tl::unexpected( e );
322 }
323
324 if( aDocument.has_sheet_path() )
325 {
326 KIID_PATH path = UnpackSheetPath( aDocument.sheet_path() );
327
328 if( !schematic()->Hierarchy().HasPath( path ) )
329 {
330 ApiResponseStatus e;
331 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
332 e.set_error_message( fmt::format( "the requested sheet path {} is not valid for this schematic",
333 path.AsString().ToStdString() ) );
334 return tl::unexpected( e );
335 }
336 }
337
338 return true;
339}
340
341
343{
344 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
345 return tl::unexpected( documentValidation.error() );
346
347 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
348 return tl::unexpected( *busy );
349
350 if( project().IsNullProject() || schematic()->GetFileName().IsEmpty() )
351 {
352 ApiResponseStatus e;
353 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
354 e.set_error_message( "the schematic is untitled; use SaveDocumentAs to save it to a new file" );
355 return tl::unexpected( e );
356 }
357
358 if( !context()->SaveSchematic() )
359 {
360 ApiResponseStatus e;
361 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
362 e.set_error_message( "failed to save schematic" );
363 return tl::unexpected( e );
364 }
365
366 return google::protobuf::Empty();
367}
368
369
372{
373 // In GUI mode a project change may require closing other editor frames, which the API is
374 // not allowed to do; headless mode has no other frames, so it is safe there
375 if( Pgm().IsGUI() )
376 {
377 ApiResponseStatus e;
378 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
379 e.set_error_message( "SaveDocumentAs is not available in GUI mode" );
380 return tl::unexpected( e );
381 }
382
383 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
384 return tl::unexpected( *busy );
385
386 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
387
388 if( !documentValidation )
389 return tl::unexpected( documentValidation.error() );
390
391 wxString pathStr = wxString::FromUTF8( aCtx.Request.path() );
392
393 if( pathStr.IsEmpty() )
394 {
395 ApiResponseStatus e;
396 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
397 e.set_error_message( "path is required" );
398 return tl::unexpected( e );
399 }
400
401 wxFileName oldSchematicFile( m_context->GetCurrentFileName() );
402
403 if( !context()->SaveSchematicAs( pathStr ) )
404 {
405 ApiResponseStatus e;
406 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
407 e.set_error_message( fmt::format( "failed to save schematic to '{}'", pathStr.ToStdString() ) );
408 return tl::unexpected( e );
409 }
410
411 if( KICAD_API_SERVER* server = apiServer() )
412 {
413 wxFileName newSchematicFile( pathStr );
414 newSchematicFile.SetExt( FILEEXT::KiCadSchematicFileExtension );
415
416 server->NotifyDocumentRenamed( thisDocumentType(), oldSchematicFile.GetFullPath(),
417 newSchematicFile.GetFullPath() );
418 }
419
420 return google::protobuf::Empty();
421}
422
423
426{
427 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
428
429 if( !documentValidation )
430 return tl::unexpected( documentValidation.error() );
431
432 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
433 return tl::unexpected( *busy );
434
435 wxFileName schematicPath( project().AbsolutePath( wxString::FromUTF8( aCtx.Request.path() ) ) );
436
437 if( !schematicPath.IsOk() || !schematicPath.IsDirWritable() )
438 {
439 ApiResponseStatus e;
440 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
441 e.set_error_message(
442 fmt::format( "save path '{}' could not be opened", schematicPath.GetFullPath().ToStdString() ) );
443 return tl::unexpected( e );
444 }
445
446 if( schematicPath.FileExists() && ( !schematicPath.IsFileWritable() || !aCtx.Request.options().overwrite() ) )
447 {
448 ApiResponseStatus e;
449 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
450 e.set_error_message( fmt::format( "save path '{}' exists and cannot be overwritten",
451 schematicPath.GetFullPath().ToStdString() ) );
452 return tl::unexpected( e );
453 }
454
455 if( schematicPath.GetExt() != FILEEXT::KiCadSchematicFileExtension )
456 {
457 ApiResponseStatus e;
458 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
459 e.set_error_message( fmt::format( "save path '{}' must have a kicad_sch extension",
460 schematicPath.GetFullPath().ToStdString() ) );
461 return tl::unexpected( e );
462 }
463
464 bool includeProject = true;
465
466 if( aCtx.Request.has_options() )
467 includeProject = aCtx.Request.options().include_project();
468
469 if( !context()->SaveSchematicCopy( schematicPath.GetFullPath(), includeProject ) )
470 {
471 ApiResponseStatus e;
472 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
473 e.set_error_message( "failed to save schematic copy" );
474 return tl::unexpected( e );
475 }
476
477 return google::protobuf::Empty();
478}
479
480
483{
484 if( aCtx.Request.document().type() != DocumentType::DOCTYPE_SCHEMATIC )
485 {
486 ApiResponseStatus e;
487 e.set_status( ApiStatusCode::AS_UNHANDLED );
488 return tl::unexpected( e );
489 }
490
491 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
492
493 if( !documentValidation )
494 return tl::unexpected( documentValidation.error() );
495
496 if( !m_commits.empty() )
497 {
498 ApiResponseStatus e;
499 e.set_status( ApiStatusCode::AS_BUSY );
500 e.set_error_message( "cannot revert while a commit is open" );
501 return tl::unexpected( e );
502 }
503
504 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
505 return tl::unexpected( *busy );
506
507 if( !context()->RevertToSaved() )
508 {
509 ApiResponseStatus e;
510 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
511 e.set_error_message( "could not revert: there is no saved file on disk to revert to" );
512 return tl::unexpected( e );
513 }
514
515 return google::protobuf::Empty();
516}
517
518
521{
522 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
523
524 if( !documentValidation )
525 return tl::unexpected( documentValidation.error() );
526
527 commands::SavedDocumentResponse response;
528
529 SCH_SHEET* topLevelSheet = schematic()->GetTopLevelSheet( 0 );
530
531 if( aCtx.Request.document().has_sheet_path() )
532 {
533 KIID_PATH kiidPath = UnpackSheetPath( aCtx.Request.document().sheet_path() );
534
535 if( std::optional<SCH_SHEET_PATH> resolvedPath = schematic()->Hierarchy().GetSheetPathByKIIDPath( kiidPath ) )
536 topLevelSheet = resolvedPath->Last();
537 }
538
539 if( !topLevelSheet || !topLevelSheet->GetScreen() )
540 {
541 ApiResponseStatus e;
542 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
543 e.set_error_message( "schematic has no top-level sheet to save" );
544 return tl::unexpected( e );
545 }
546
547 STRING_FORMATTER formatter;
548 SCH_IO_KICAD_SEXPR plugin;
549
550 plugin.FormatSchematicToFormatter( &formatter, topLevelSheet, schematic(), nullptr );
551
552 std::string contents = formatter.GetString();
553 KICAD_FORMAT::Prettify( contents, KICAD_FORMAT::FORMAT_MODE::COMPACT_TEXT_PROPERTIES );
554 response.set_contents( contents );
555
556 return response;
557}
558
559
562{
563 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "SaveSelectionToString" ) )
564 return tl::unexpected( *headless );
565
567 SCH_SELECTION& selection = selTool->GetSelection();
568
569 if( selection.Empty() )
570 {
571 ApiResponseStatus e;
572 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
573 e.set_error_message( "the selection is empty" );
574 return tl::unexpected( e );
575 }
576
577 commands::SavedSelectionResponse response;
578
579 SCH_SHEET_PATH selPath = frame()->GetCurrentSheet();
580
581 for( EDA_ITEM* item : selection )
582 response.add_ids()->set_value( item->m_Uuid.AsStdString() );
583
584 STRING_FORMATTER formatter;
585 SCH_IO_KICAD_SEXPR plugin;
586
587 plugin.Format( &selection, &selPath, *schematic(), &formatter, true );
588
589 std::string contents = formatter.GetString();
590 KICAD_FORMAT::Prettify( contents, KICAD_FORMAT::FORMAT_MODE::COMPACT_TEXT_PROPERTIES );
591 response.set_contents( contents );
592
593 return response;
594}
595
596
599{
600 if( aCtx.Request.type() != DocumentType::DOCTYPE_SCHEMATIC )
601 {
602 ApiResponseStatus e;
603
604 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
605 e.set_status( ApiStatusCode::AS_UNHANDLED );
606 return tl::unexpected( e );
607 }
608
609 GetOpenDocumentsResponse response;
610 common::types::DocumentSpecifier doc;
611
612 wxFileName fn( m_context->GetCurrentFileName() );
613
614 doc.set_type( DocumentType::DOCTYPE_SCHEMATIC );
615
616 if( std::optional<SCH_SHEET_PATH> path = m_context->GetCurrentSheet() )
617 PackSheetPath( *doc.mutable_sheet_path(), *path );
618
619 PackProject( *doc.mutable_project(), m_context->Prj() );
620
621 response.mutable_documents()->Add( std::move( doc ) );
622 return response;
623}
624
625
628{
629 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
630 return tl::unexpected( documentValidation.error() );
631
632 GetDocumentModifiedStateResponse response;
633
634 if( aCtx.Request.document().has_sheet_path() )
635 {
636 KIID_PATH path = UnpackSheetPath( aCtx.Request.document().sheet_path() );
637
638 std::optional<SCH_SHEET_PATH> sheetPath = schematic()->Hierarchy().GetSheetPathByKIIDPath( path );
639
640 if( !sheetPath )
641 {
642 ApiResponseStatus e;
643 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
644 e.set_error_message( "the requested sheet path is not valid for this schematic" );
645 return tl::unexpected( e );
646 }
647
648 if( const SCH_SCREEN* screen = sheetPath->LastScreen() )
649 {
650 response.set_state( screen->IsContentModified() ? DocumentModifiedState::DMS_MODIFIED
651 : DocumentModifiedState::DMS_UNMODIFIED );
652 }
653
654 return response;
655 }
656
657 if( !schematic()->HasHierarchy() )
659
660 response.set_state( schematic()->Hierarchy().IsModified() ? DocumentModifiedState::DMS_MODIFIED
661 : DocumentModifiedState::DMS_UNMODIFIED );
662 return response;
663}
664
665
666void API_HANDLER_SCH::filterValidSchTypes( std::set<KICAD_T>& aTypeList )
667{
668 std::erase_if( aTypeList,
669 []( KICAD_T aType )
670 {
671 return !s_allowedTypes.contains( aType );
672 } );
673}
674
675
677{
678 if( HANDLER_RESULT<std::optional<KIID>> valid = validateItemHeaderDocument( aCtx.Request.header() );
679 !valid.has_value() )
680 {
681 return tl::unexpected( valid.error() );
682 }
683
684 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
685 return tl::unexpected( *busy );
686
687 std::vector<KICAD_T> requestedTypes = parseRequestedItemTypes( aCtx.Request.types() );
688
689 if( aCtx.Request.types().empty() )
690 requestedTypes.assign( s_allowedTypes.begin(), s_allowedTypes.end() );
691
692 std::set<KICAD_T> typesRequested;
693
694 for( KICAD_T type : requestedTypes )
695 typesRequested.insert( type );
696
697 filterValidSchTypes( typesRequested );
698
699 if( typesRequested.empty() )
700 {
701 ApiResponseStatus e;
702 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
703 e.set_error_message( "none of the requested types are valid for a Schematic object" );
704 return tl::unexpected( e );
705 }
706
707 SCH_SHEET_LIST hierarchy = schematic()->Hierarchy();
708 std::optional<SCH_SHEET_PATH> pathFilter;
709
710 if( aCtx.Request.header().document().has_sheet_path() )
711 {
712 KIID_PATH kp = UnpackSheetPath( aCtx.Request.header().document().sheet_path() );
713 pathFilter = hierarchy.GetSheetPathByKIIDPath( kp );
714 }
715
716 std::map<KICAD_T, std::vector<std::pair<EDA_ITEM*, SCH_SHEET_PATH>>> itemMap;
717
718 auto processScreen =
719 [&]( const SCH_SHEET_PATH& aPath )
720 {
721 const SCH_SCREEN* aScreen = aPath.LastScreen();
722
723 if( !aScreen )
724 return;
725
726 for( SCH_ITEM* aItem : aScreen->Items() )
727 {
728 itemMap[ aItem->Type() ].emplace_back( aItem, aPath );
729
730 // Group members live in the screen's rtree as well as in the group
731 if( aItem->Type() == SCH_GROUP_T )
732 continue;
733
734 aItem->RunOnChildren(
735 [&]( SCH_ITEM* aChild )
736 {
737 itemMap[ aChild->Type() ].emplace_back( aChild, aPath );
738 },
740 }
741 };
742
743 if( pathFilter )
744 {
745 processScreen( *pathFilter );
746 }
747 else
748 {
749 for( const SCH_SHEET_PATH& path : hierarchy )
750 processScreen( path );
751 }
752
753 GetItemsResponse response;
754 google::protobuf::Any any;
755
756 for( KICAD_T type : typesRequested )
757 {
758 for( const auto& [item, itemPath] : itemMap[type] )
759 {
760 if( packSchItem( any, static_cast<SCH_ITEM*>( item ), itemPath ) )
761 response.mutable_items()->Add( std::move( any ) );
762 }
763 }
764
765 response.set_status( ItemRequestStatus::IRS_OK );
766 return response;
767}
768
769
771{
772 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
773 {
774 ApiResponseStatus e;
775 e.set_status( ApiStatusCode::AS_UNHANDLED );
776 return tl::unexpected( e );
777 }
778
779 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
780 return tl::unexpected( *busy );
781
782 SCH_SHEET_LIST hierarchy = schematic()->Hierarchy();
783 std::optional<SCH_SHEET_PATH> pathFilter;
784
785 if( aCtx.Request.header().document().has_sheet_path() )
786 {
787 KIID_PATH kp = UnpackSheetPath( aCtx.Request.header().document().sheet_path() );
788 pathFilter = hierarchy.GetSheetPathByKIIDPath( kp );
789 }
790
791 GetItemsResponse response;
792 SCH_ITEM* item = nullptr;
793
794 for( const types::KIID& idProto : aCtx.Request.items() )
795 {
796 google::protobuf::Any any;
797 KIID id( idProto.value() );
798
799 SCH_SHEET_PATH itemPath;
800
801 if( pathFilter )
802 {
803 item = pathFilter->ResolveItem( id );
804 itemPath = *pathFilter;
805 }
806 else
807 {
808 item = hierarchy.ResolveItem( id, &itemPath, true );
809 }
810
811 if( !item || !s_allowedTypes.contains( item->Type() ) )
812 continue;
813
814 if( item->Type() == SCH_SYMBOL_T )
815 {
816 kiapi::schematic::types::SchematicSymbolInstance symbol;
817
818 if( !PackSymbol( &symbol, static_cast<SCH_SYMBOL*>( item ), itemPath ) )
819 continue;
820
821 if( !any.PackFrom( symbol ) )
822 continue;
823 }
824 else if( item->Type() == SCH_SHEET_T )
825 {
826 kiapi::schematic::types::SheetSymbol sheet;
827
828 if( !PackSheet( &sheet, static_cast<SCH_SHEET*>( item ), itemPath ) )
829 continue;
830
831 if( !any.PackFrom( sheet ) )
832 continue;
833 }
834 else
835 {
836 item->Serialize( any );
837 }
838
839 response.mutable_items()->Add( std::move( any ) );
840 }
841
842 if( response.items().empty() )
843 {
844 ApiResponseStatus e;
845 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
846 e.set_error_message( "none of the requested IDs were found or valid" );
847 return tl::unexpected( e );
848 }
849
850 response.set_status( ItemRequestStatus::IRS_OK );
851 return response;
852}
853
854
857{
858 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "GetSelection" ) )
859 return tl::unexpected( *headless );
860
861 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
862 {
863 ApiResponseStatus e;
864 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
865 e.set_status( ApiStatusCode::AS_UNHANDLED );
866 return tl::unexpected( e );
867 }
868
869 std::set<KICAD_T> filter;
870
871 for( KICAD_T type : parseRequestedItemTypes( aCtx.Request.types() ) )
872 filter.insert( type );
873
874 SCH_SELECTION_TOOL* tool = m_context->GetToolManager()->GetTool<SCH_SELECTION_TOOL>();
875 SCH_SHEET_PATH path = m_context->GetCurrentSheet().value_or( SCH_SHEET_PATH() );
876
877 SelectionResponse response;
878 google::protobuf::Any any;
879
880 for( EDA_ITEM* item : tool->GetSelection() )
881 {
882 if( filter.empty() || filter.contains( item->Type() ) )
883 {
884 if( packSchItem( any, static_cast<SCH_ITEM*>( item ), path ) )
885 response.mutable_items()->Add( std::move( any ) );
886 }
887 }
888
889 return response;
890}
891
892
895{
896 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "ClearSelection" ) )
897 return tl::unexpected( *headless );
898
899 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
900 {
901 ApiResponseStatus e;
902 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
903 e.set_status( ApiStatusCode::AS_UNHANDLED );
904 return tl::unexpected( e );
905 }
906
907 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
908 return tl::unexpected( *busy );
909
910 m_context->GetToolManager()->RunAction( ACTIONS::selectionClear );
911 frame()->Refresh();
912
913 return Empty();
914}
915
916
919{
920 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "AddToSelection" ) )
921 return tl::unexpected( *headless );
922
923 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
924 {
925 ApiResponseStatus e;
926 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
927 e.set_status( ApiStatusCode::AS_UNHANDLED );
928 return tl::unexpected( e );
929 }
930
931 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
932 return tl::unexpected( *busy );
933
934 SCH_SELECTION_TOOL* tool = m_context->GetToolManager()->GetTool<SCH_SELECTION_TOOL>();
935 SCH_SHEET_PATH current = m_context->GetCurrentSheet().value_or( SCH_SHEET_PATH() );
936
937 EDA_ITEMS toAdd;
938
939 for( const types::KIID& id : aCtx.Request.items() )
940 {
941 SCH_SHEET_PATH itemPath;
942
943 // Selection only operates on the currently-displayed sheet; off-sheet items are skipped
944 if( std::optional<SCH_ITEM*> item = getItemById( KIID( id.value() ), &itemPath );
945 item && itemPath == current )
946 {
947 toAdd.push_back( *item );
948 }
949 }
950
951 tool->AddItemsToSel( &toAdd );
952 frame()->Refresh();
953
954 SelectionResponse response;
955 google::protobuf::Any any;
956
957 for( EDA_ITEM* item : tool->GetSelection() )
958 {
959 if( packSchItem( any, static_cast<SCH_ITEM*>( item ), current ) )
960 response.mutable_items()->Add( std::move( any ) );
961 }
962
963 return response;
964}
965
966
969{
970 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "RemoveFromSelection" ) )
971 return tl::unexpected( *headless );
972
973 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
974 {
975 ApiResponseStatus e;
976 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
977 e.set_status( ApiStatusCode::AS_UNHANDLED );
978 return tl::unexpected( e );
979 }
980
981 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
982 return tl::unexpected( *busy );
983
984 SCH_SELECTION_TOOL* tool = m_context->GetToolManager()->GetTool<SCH_SELECTION_TOOL>();
985 SCH_SHEET_PATH current = m_context->GetCurrentSheet().value_or( SCH_SHEET_PATH() );
986
987 EDA_ITEMS toRemove;
988
989 for( const types::KIID& id : aCtx.Request.items() )
990 {
991 SCH_SHEET_PATH itemPath;
992
993 if( std::optional<SCH_ITEM*> item = getItemById( KIID( id.value() ), &itemPath );
994 item && itemPath == current )
995 {
996 toRemove.push_back( *item );
997 }
998 }
999
1000 tool->RemoveItemsFromSel( &toRemove );
1001 frame()->Refresh();
1002
1003 SelectionResponse response;
1004 google::protobuf::Any any;
1005
1006 for( EDA_ITEM* item : tool->GetSelection() )
1007 {
1008 if( packSchItem( any, static_cast<SCH_ITEM*>( item ), current ) )
1009 response.mutable_items()->Add( std::move( any ) );
1010 }
1011
1012 return response;
1013}
1014
1015
1017{
1018 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "FocusOnItems" ) )
1019 return tl::unexpected( *headless );
1020
1021 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
1022 return tl::unexpected( documentValidation.error() );
1023
1024 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1025 return tl::unexpected( *busy );
1026
1027 std::vector<KIID> ids;
1028
1029 for( const types::KIID& id : aCtx.Request.items() )
1030 ids.emplace_back( id.value() );
1031
1032 std::optional<KIID_PATH> sheetPath;
1033
1034 if( aCtx.Request.document().has_sheet_path() )
1035 sheetPath = UnpackSheetPath( aCtx.Request.document().sheet_path() );
1036
1037 tl::expected<SCH_FOCUS_TARGET, ApiResponseStatus> target = ResolveFocusItems( *schematic(), ids, sheetPath );
1038
1039 if( !target )
1040 return tl::unexpected( target.error() );
1041
1042 if( m_context->GetCurrentSheet().value_or( SCH_SHEET_PATH() ) != target->Sheet )
1043 m_context->GetToolManager()->RunAction<SCH_SHEET_PATH*>( SCH_ACTIONS::changeSheet, &target->Sheet );
1044
1045 BOX2I bbox = target->BBox;
1046
1047 if( aCtx.Request.has_margin() )
1048 bbox.Inflate( UnpackDistance( aCtx.Request.margin(), schIUScale ) );
1049
1050 m_context->GetToolManager()->GetTool<COMMON_TOOLS>()->ZoomFitBox( bbox );
1051
1052 return Empty();
1053}
1054
1055
1057{
1058 if( !aContainer )
1059 {
1060 ApiResponseStatus e;
1061 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1062 e.set_error_message( "Tried to create an item in a null container" );
1063 return tl::unexpected( e );
1064 }
1065
1066 if( !s_allowedTypes.contains( aType ) )
1067 {
1068 ApiResponseStatus e;
1069 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1070 e.set_error_message( fmt::format( "type {} is not supported by the schematic API handler",
1071 magic_enum::enum_name( aType ) ) );
1072 return tl::unexpected( e );
1073 }
1074
1075 if( aType == SCH_PIN_T && !dynamic_cast<SCH_SYMBOL*>( aContainer ) )
1076 {
1077 ApiResponseStatus e;
1078 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1079 e.set_error_message( fmt::format( "Tried to create a pin in {}, which is not a symbol",
1080 aContainer->GetFriendlyName().ToStdString() ) );
1081 return tl::unexpected( e );
1082 }
1083 else if( aType == SCH_SHEET_T && !dynamic_cast<SCH_SCREEN*>( aContainer ) )
1084 {
1085 ApiResponseStatus e;
1086 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1087 e.set_error_message( fmt::format( "Tried to create a sheet symbol in {}, which is not a "
1088 "schematic sheet",
1089 aContainer->GetFriendlyName().ToStdString() ) );
1090 return tl::unexpected( e );
1091 }
1092 else if( aType == SCH_SYMBOL_T && !dynamic_cast<SCH_SCREEN*>( aContainer ) )
1093 {
1094 ApiResponseStatus e;
1095 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1096 e.set_error_message( fmt::format( "Tried to create a symbol in {}, which is not a "
1097 "schematic sheet",
1098 aContainer->GetFriendlyName().ToStdString() ) );
1099 return tl::unexpected( e );
1100 }
1101
1102 std::unique_ptr<EDA_ITEM> created = CreateItemForType( aType, aContainer );
1103
1104 if( created && !created->GetParent() )
1105 created->SetParent( aContainer );
1106
1107 if( !created )
1108 {
1109 ApiResponseStatus e;
1110 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1111 e.set_error_message( fmt::format( "Tried to create an item of type {}, which is unhandled",
1112 magic_enum::enum_name( aType ) ) );
1113 return tl::unexpected( e );
1114 }
1115
1116 return created;
1117}
1118
1119
1121 const std::string& aClientName,
1122 const types::ItemHeader &aHeader,
1123 const google::protobuf::RepeatedPtrField<google::protobuf::Any>& aItems,
1124 std::function<void( ItemStatus, google::protobuf::Any )> aItemHandler )
1125{
1126 ApiResponseStatus e;
1127
1129
1130 if( !containerResult && containerResult.error().status() == ApiStatusCode::AS_UNHANDLED )
1131 {
1132 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
1133 e.set_status( ApiStatusCode::AS_UNHANDLED );
1134 return tl::unexpected( e );
1135 }
1136 else if( !containerResult )
1137 {
1138 e.CopyFrom( containerResult.error() );
1139 return tl::unexpected( e );
1140 }
1141
1142 SCH_SHEET_LIST hierarchy = schematic()->Hierarchy();
1143 SCH_SCREEN* targetScreen = schematic()->GetCurrentScreen();
1144 SCH_SHEET_PATH targetPath = m_context->GetCurrentSheet().value_or( *hierarchy.begin() );
1145
1146 if( aHeader.document().has_sheet_path() )
1147 {
1148 KIID_PATH kp = UnpackSheetPath( aHeader.document().sheet_path() );
1149
1150 if( std::optional<SCH_SHEET_PATH> path = hierarchy.GetSheetPathByKIIDPath( kp ) )
1151 {
1152 targetPath = *path;
1153 targetScreen = targetPath.LastScreen();
1154 }
1155 }
1156
1157 SCH_COMMIT* commit = static_cast<SCH_COMMIT*>( getCurrentCommit( aClientName ) );
1158 int commitCheckpoint = commit->Checkpoint();
1159 bool connectivityChanged = false; // an in-place symbol update invalidated the net graph
1160 EDA_ITEM* container = targetScreen;
1161
1162 if( containerResult->has_value() )
1163 {
1164 SCH_ITEM* containerItem = hierarchy.ResolveItem( **containerResult, nullptr, true );
1165
1166 if( !containerItem )
1167 {
1168 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1169 e.set_error_message( "the requested container does not exist in this document" );
1170 return tl::unexpected( e );
1171 }
1172
1173 container = containerItem;
1174 }
1175
1176 for( const google::protobuf::Any& anyItem : aItems )
1177 {
1178 ItemStatus status;
1179 std::optional<KICAD_T> type = TypeNameFromAny( anyItem );
1180
1181 if( !type )
1182 {
1183 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
1184 status.set_error_message( fmt::format( "Could not decode a valid type from {}", anyItem.type_url() ) );
1185 aItemHandler( status, anyItem );
1186 continue;
1187 }
1188
1189 HANDLER_RESULT<std::unique_ptr<EDA_ITEM>> creationResult = createItemForType( *type, container );
1190
1191 if( !creationResult )
1192 {
1193 status.set_code( ItemStatusCode::ISC_INVALID_TYPE );
1194 status.set_error_message( creationResult.error().error_message() );
1195 aItemHandler( status, anyItem );
1196 continue;
1197 }
1198
1199 std::unique_ptr<EDA_ITEM> item( std::move( *creationResult ) );
1200
1201 bool unpacked = false;
1202
1203 // Retained past the unpack: the placement data they carry is applied once the item is
1204 // in the schematic.
1205 kiapi::schematic::types::SchematicSymbolInstance symbolProto;
1206 kiapi::schematic::types::SheetSymbol sheetProto;
1207
1208 if( *type == SCH_SYMBOL_T )
1209 {
1210 unpacked = anyItem.UnpackTo( &symbolProto )
1211 && UnpackSymbol( static_cast<SCH_SYMBOL*>( item.get() ), symbolProto );
1212 }
1213 else if( *type == SCH_SHEET_T )
1214 {
1215 unpacked = anyItem.UnpackTo( &sheetProto );
1216
1217 if( unpacked )
1218 {
1219 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item.get() );
1220
1221 if( tl::expected<bool, ApiResponseStatus> result = UnpackSheet( sheet, sheetProto );
1222 result.has_value() )
1223 {
1224 unpacked = *result;
1225 }
1226 else
1227 {
1228 return tl::unexpected( result.error() );
1229 }
1230 }
1231 }
1232 else if( SCH_GROUP* group = dynamic_cast<SCH_GROUP*>( item.get() ) )
1233 {
1234 unpacked = group->DeserializeGroup( anyItem, commit );
1235 }
1236 else
1237 {
1238 unpacked = item->Deserialize( anyItem );
1239 }
1240
1241 if( !unpacked )
1242 {
1243 commit->RevertToCheckpoint( commitCheckpoint );
1244
1245 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1246 e.set_error_message( fmt::format( "could not unpack {} from request", item->GetClass().ToStdString() ) );
1247 return tl::unexpected( e );
1248 }
1249
1250 if( std::vector<wxString> removed = item->RemoveConflictingCustomProperties(); !removed.empty() )
1251 {
1252 auto as_str =
1253 []( const wxString& aIn )
1254 {
1255 return std::string( aIn.ToUTF8() );
1256 };
1257
1258 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1259 status.set_error_message( fmt::format( "Invalid custom properties for item {}: property name(s) '{}' "
1260 "already in use",
1261 item->m_Uuid.AsStdString(),
1262 fmt::join( std::views::transform( removed, as_str ), ", " ) ) );
1263
1264 aItemHandler( status, anyItem );
1265 continue;
1266 }
1267
1268 SCH_ITEM* existingItem = nullptr;
1269 SCH_SHEET_PATH existingPath;
1270
1271 existingItem = targetPath.ResolveItem( item->m_Uuid );
1272
1273 if( existingItem )
1274 existingPath = targetPath;
1275
1276 if( aCreate && existingItem )
1277 {
1278 status.set_code( ItemStatusCode::ISC_EXISTING );
1279 status.set_error_message( fmt::format( "an item with UUID {} already exists",
1280 item->m_Uuid.AsStdString() ) );
1281 aItemHandler( status, anyItem );
1282 continue;
1283 }
1284 else if( !aCreate && !existingItem )
1285 {
1286 status.set_code( ItemStatusCode::ISC_NONEXISTENT );
1287 status.set_error_message( fmt::format( "an item with UUID {} does not exist",
1288 item->m_Uuid.AsStdString() ) );
1289 aItemHandler( status, anyItem );
1290 continue;
1291 }
1292
1293 if( !aCreate && existingItem->Type() != *type )
1294 {
1295 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1296 status.set_error_message( fmt::format( "item {} is not of the requested type",
1297 item->m_Uuid.AsStdString() ) );
1298 aItemHandler( status, anyItem );
1299 continue;
1300 }
1301
1302 if( !aCreate )
1303 {
1304 SCH_SCREEN* itemScreen = existingPath.LastScreen();
1305
1306 if( itemScreen != targetScreen )
1307 {
1308 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1309 status.set_error_message( fmt::format( "item {} exists on a different sheet than targeted",
1310 item->m_Uuid.AsStdString() ) );
1311 aItemHandler( status, anyItem );
1312 continue;
1313 }
1314 }
1315
1316 if( *type == SCH_SYMBOL_T )
1317 {
1318 if( symbolProto.has_definition() )
1319 {
1320 if( symbolProto.definition().id().entry_name().empty() )
1321 {
1322 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1323 status.set_error_message( "symbol definition is missing an entry name" );
1324 aItemHandler( status, anyItem );
1325 continue;
1326 }
1327 }
1328 else if( aCreate )
1329 {
1330 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1331 status.set_error_message( "a symbol definition is required" );
1332 aItemHandler( status, anyItem );
1333 continue;
1334 }
1335 else
1336 {
1337 // Definition-less update: re-point the temporary at the existing symbol's
1338 // library identity so the swap below keeps the library link
1339 SCH_SYMBOL* existingSymbol = static_cast<SCH_SYMBOL*>( existingItem );
1340 SCH_SYMBOL* tempSymbol = static_cast<SCH_SYMBOL*>( item.get() );
1341
1342 tempSymbol->SetLibId( existingSymbol->GetLibId() );
1343 tempSymbol->SetSchSymbolLibraryName( existingSymbol->UseLibIdLookup()
1344 ? wxString( wxEmptyString )
1345 : existingSymbol->GetSchSymbolLibraryName() );
1346
1347 for( const std::unique_ptr<SCH_PIN>& pin : existingSymbol->GetRawPins() )
1348 {
1349 tempSymbol->GetRawPins().emplace_back( std::make_unique<SCH_PIN>( *pin ) );
1350 tempSymbol->GetRawPins().back()->SetParent( tempSymbol );
1351 }
1352
1353 if( existingSymbol->GetLibSymbolRef() )
1354 tempSymbol->SetLibSymbol( new LIB_SYMBOL( *existingSymbol->GetLibSymbolRef() ) );
1355 }
1356 }
1357
1358 if( *type == SCH_SHEET_T )
1359 {
1360 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item.get() );
1361
1362 if( !ValidateSheetInstance( &status, sheet, sheetProto ) )
1363 {
1364 aItemHandler( status, anyItem );
1365 continue;
1366 }
1367
1368 if( aCreate && !sheet->GetScreen() )
1369 {
1370 sheet->SetScreen( new SCH_SCREEN( schematic() ) );
1371
1372 if( wxString rawFilename = sheet->GetFileName(); !rawFilename.IsEmpty() )
1373 {
1374 wxFileName fileName( ExpandTextVars( rawFilename, &schematic()->Project(), INTERNAL ) );
1375 wxFileName parentFileName( targetPath.LastScreen()->GetFileName() );
1376
1377 if( !fileName.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS,
1378 parentFileName.GetPath() ) )
1379 {
1380 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1381 status.set_error_message( fmt::format( "could not resolve sheet filename '{}' for new sheet",
1382 rawFilename.ToStdString() ) );
1383 aItemHandler( status, anyItem );
1384 continue;
1385 }
1386
1387 sheet->GetScreen()->SetFileName( fileName.GetFullPath() );
1388 sheet->GetScreen()->SetContentModified();
1389 }
1390 }
1391
1392 SCH_SHEET_PATH parentPath;
1393
1394 if( aCreate )
1395 parentPath = targetPath;
1396 else
1397 parentPath = existingPath;
1398
1399 wxString destFilePath = parentPath.LastScreen()->GetFileName();
1400
1401 if( !destFilePath.IsEmpty() )
1402 {
1403 SCH_SHEET_LIST schematicSheets = schematic()->Hierarchy();
1404 SCH_SHEET_LIST loadedSheets( sheet );
1405
1406 if( schematicSheets.TestForRecursion( loadedSheets, destFilePath ) )
1407 {
1408 status.set_code( ItemStatusCode::ISC_INVALID_DATA );
1409 status.set_error_message( "sheet update would create recursive hierarchy" );
1410 aItemHandler( status, anyItem );
1411 continue;
1412 }
1413 }
1414 }
1415
1416 status.set_code( ItemStatusCode::ISC_OK );
1417 google::protobuf::Any newItem;
1418
1419 if( aCreate && !item )
1420 {
1421 commit->RevertToCheckpoint( commitCheckpoint );
1422
1423 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1424 e.set_error_message( "could not add the requested item to its parent container" );
1425 return tl::unexpected( e );
1426 }
1427
1428 if( item->Type() == SCH_GROUP_T )
1429 static_cast<SCH_GROUP*>( item.get() )->FinalizeGroupDeserialization();
1430
1431 if( aCreate )
1432 {
1433 if( item->Type() == SCH_SYMBOL_T )
1434 {
1435 for( const std::unique_ptr<SCH_PIN>& pin : static_cast<SCH_SYMBOL*>( item.get() )->GetRawPins() )
1436 const_cast<KIID&>( pin->m_Uuid ) = KIID();
1437 }
1438 else if( item->Type() == SCH_SHEET_T )
1439 {
1440 for( SCH_SHEET_PIN* pin : static_cast<SCH_SHEET*>( item.get() )->GetPins() )
1441 const_cast<KIID&>( pin->m_Uuid ) = KIID();
1442 }
1443 }
1444
1445 // A refused request must not leave the created item staged
1446 if( aCreate && item->Type() == SCH_SYMBOL_T
1447 && !ValidateSymbolInstance( &status, static_cast<SCH_SYMBOL*>( item.get() ), symbolProto, targetPath,
1448 schematic() ) )
1449 {
1450 aItemHandler( status, anyItem );
1451 continue;
1452 }
1453
1454 if( aCreate )
1455 {
1456 SCH_ITEM* createdItem = static_cast<SCH_ITEM*>( item.release() );
1457 commit->Add( createdItem, targetScreen );
1458
1459 if( createdItem->Type() == SCH_SYMBOL_T )
1460 {
1461 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( createdItem );
1462 kiapi::schematic::types::SchematicSymbolInstance packed;
1463
1464 if( !ApplySymbolInstance( &status, symbol, symbolProto, targetPath, schematic() ) )
1465 {
1466 aItemHandler( status, anyItem );
1467 continue;
1468 }
1469
1470 if( PackSymbol( &packed, symbol, targetPath, schematic() ) )
1471 (void) newItem.PackFrom( packed );
1472 }
1473 else if( createdItem->Type() == SCH_SHEET_T )
1474 {
1475 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( createdItem );
1476 kiapi::schematic::types::SheetSymbol packed;
1477
1478 if( sheetProto.page_number().empty() )
1479 sheetProto.set_page_number( hierarchy.GetNextPageNumber().ToUTF8() );
1480
1481 if( !ApplySheetInstance( &status, sheet, sheetProto, targetPath, schematic() ) )
1482 {
1483 aItemHandler( status, anyItem );
1484 continue;
1485 }
1486
1487 if( PackSheet( &packed, sheet, targetPath ) )
1488 (void) newItem.PackFrom( packed );
1489 }
1490 else
1491 {
1492 createdItem->Serialize( newItem );
1493 }
1494 }
1495 else
1496 {
1497 // SwapItemData hands the item the temporary's (empty) instance list, so keep the
1498 // placements to restore afterwards.
1499 std::vector<SCH_SYMBOL_INSTANCE> symbolPlacements;
1500 std::vector<SCH_SHEET_INSTANCE> sheetPlacements;
1501
1502 if( existingItem->Type() == SCH_SYMBOL_T )
1503 symbolPlacements = static_cast<SCH_SYMBOL*>( existingItem )->GetInstances();
1504 else if( existingItem->Type() == SCH_SHEET_T )
1505 sheetPlacements = static_cast<SCH_SHEET*>( existingItem )->GetInstances();
1506
1507 // A refused request must not leave the swapped data behind
1508 if( existingItem->Type() == SCH_SYMBOL_T
1509 && !ValidateSymbolInstance( &status, static_cast<SCH_SYMBOL*>( existingItem ), symbolProto,
1510 existingPath, schematic() ) )
1511 {
1512 aItemHandler( status, anyItem );
1513 continue;
1514 }
1515
1516 commit->Modify( existingItem, targetScreen );
1517 existingItem->SwapItemData( static_cast<SCH_ITEM*>( item.get() ) );
1518
1519 if( existingItem->IsConnectable() )
1520 {
1521 existingItem->SetConnectivityDirty();
1522 connectivityChanged = true;
1523 }
1524
1525 if( existingItem->Type() == SCH_SYMBOL_T )
1526 {
1527 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( existingItem );
1528 kiapi::schematic::types::SchematicSymbolInstance packed;
1529
1530 for( const SCH_SYMBOL_INSTANCE& placement : symbolPlacements )
1531 symbol->AddHierarchicalReference( placement );
1532
1533 if( !ApplySymbolInstance( &status, symbol, symbolProto, existingPath, schematic() ) )
1534 {
1535 aItemHandler( status, anyItem );
1536 continue;
1537 }
1538
1539 if( PackSymbol( &packed, symbol, existingPath ) )
1540 (void) newItem.PackFrom( packed );
1541 }
1542 else if( existingItem->Type() == SCH_SHEET_T )
1543 {
1544 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( existingItem );
1545 kiapi::schematic::types::SheetSymbol packed;
1546
1547 for( const SCH_SHEET_INSTANCE& placement : sheetPlacements )
1548 sheet->AddInstance( placement );
1549
1550 if( !ApplySheetInstance( &status, sheet, sheetProto, existingPath, schematic() ) )
1551 {
1552 aItemHandler( status, anyItem );
1553 continue;
1554 }
1555
1556 if( PackSheet( &packed, sheet, existingPath ) )
1557 (void) newItem.PackFrom( packed );
1558 }
1559 else
1560 {
1561 existingItem->Serialize( newItem );
1562 }
1563 }
1564
1565 aItemHandler( status, newItem );
1566 }
1567
1568 if( !m_activeClients.contains( aClientName ) )
1569 {
1570 pushCurrentCommit( aClientName, aCreate ? _( "Created items via API" )
1571 : _( "Modified items via API" ) );
1572 }
1573
1574 if( m_frame && connectivityChanged )
1576
1577 return ItemRequestStatus::IRS_OK;
1578}
1579
1580
1581void API_HANDLER_SCH::deleteItemsInternal( std::map<KIID, ItemDeletionStatus>& aItemsToDelete,
1582 const std::string& aClientName )
1583{
1584 SCH_SHEET_LIST hierarchy = schematic()->Hierarchy();
1585 COMMIT* commit = getCurrentCommit( aClientName );
1586
1587 for( auto& [id, status] : aItemsToDelete )
1588 {
1590 SCH_ITEM* item = hierarchy.ResolveItem( id, &path, true );
1591
1592 if( !item )
1593 continue;
1594
1595 if( !s_allowedTypes.contains( item->Type() ) )
1596 {
1597 status = ItemDeletionStatus::IDS_IMMUTABLE;
1598 continue;
1599 }
1600
1601 commit->Remove( item, path.LastScreen() );
1602 status = ItemDeletionStatus::IDS_OK;
1603 }
1604
1605 if( !m_activeClients.contains( aClientName ) )
1606 pushCurrentCommit( aClientName, _( "Deleted items via API" ) );
1607}
1608
1609
1610std::optional<EDA_ITEM*> API_HANDLER_SCH::getItemFromDocument( const DocumentSpecifier& aDocument, const KIID& aId )
1611{
1612 if( !validateDocument( aDocument ) )
1613 return std::nullopt;
1614
1615 SCH_ITEM* item = schematic()->Hierarchy().ResolveItem( aId, nullptr, true );
1616
1617 if( !item)
1618 return std::nullopt;
1619
1620 return item;
1621}
1622
1623
1624SCH_SCREEN* API_HANDLER_SCH::resolveScreenFromDocument( const DocumentSpecifier& aDocument ) const
1625{
1626 if( aDocument.has_sheet_path() )
1627 {
1628 KIID_PATH path = UnpackSheetPath( aDocument.sheet_path() );
1629
1630 if( std::optional<SCH_SHEET_PATH> sheetPath = schematic()->Hierarchy().GetSheetPathByKIIDPath( path ) )
1631 return sheetPath->LastScreen();
1632
1633 return nullptr;
1634 }
1635
1636 if( std::optional<SCH_SHEET_PATH> current = m_context->GetCurrentSheet() )
1637 return current->LastScreen();
1638
1639 // Headless mode has no current sheet; the first top-level sheet is the implicit target.
1640 return schematic()->RootScreen();
1641}
1642
1643
1644std::optional<TITLE_BLOCK*> API_HANDLER_SCH::getTitleBlock( const DocumentSpecifier& aDocument )
1645{
1646 if( SCH_SCREEN* screen = resolveScreenFromDocument( aDocument ) )
1647 return &screen->GetTitleBlock();
1648
1649 return std::nullopt;
1650}
1651
1652
1653std::optional<PAGE_INFO> API_HANDLER_SCH::getPageSettings( const DocumentSpecifier& aDocument )
1654{
1655 if( SCH_SCREEN* screen = resolveScreenFromDocument( aDocument ) )
1656 return screen->GetPageSettings();
1657
1658 return std::nullopt;
1659}
1660
1661
1662bool API_HANDLER_SCH::setPageSettings( const DocumentSpecifier& aDocument, const PAGE_INFO& aPageInfo )
1663{
1664 if( SCH_SCREEN* screen = resolveScreenFromDocument( aDocument ) )
1665 {
1666 screen->SetPageSettings( aPageInfo );
1667 screen->SetContentModified();
1668 return true;
1669 }
1670
1671 return false;
1672}
1673
1674
1679
1680
1681void API_HANDLER_SCH::setDrawingSheetFileName( const wxString& aFileName )
1682{
1685
1686 if( m_frame )
1688}
1689
1690
1692{
1693 if( m_frame )
1694 {
1695 frame()->Refresh();
1696 frame()->OnModify();
1697 }
1698 else if( schematic()->GetCurrentScreen() )
1699 {
1701 }
1702}
1703
1704
1706{
1707 if( m_frame )
1708 frame()->Refresh();
1709}
1710
1711
1712static std::optional<ApiResponseStatus>
1713applySchematicPlotSettings( const schematic::jobs::SchematicPlotSettings& aSettings,
1714 const types::DocumentSpecifier& aDocument, JOB_EXPORT_SCH_PLOT& aJob )
1715{
1716 aJob.m_drawingSheet = wxString::FromUTF8( aSettings.drawing_sheet() );
1717 aJob.m_defaultFont = wxString::FromUTF8( aSettings.default_font() );
1718 aJob.m_variant = wxString::FromUTF8( aSettings.variant() );
1719 aJob.m_plotAll = aSettings.plot_all();
1720 aJob.m_plotDrawingSheet = aSettings.plot_drawing_sheet();
1721 aJob.m_show_hop_over = aSettings.show_hop_over();
1722 aJob.m_blackAndWhite = aSettings.black_and_white();
1723 aJob.m_useBackgroundColor = aSettings.use_background_color();
1724 aJob.m_minPenWidth = aSettings.min_pen_width();
1725 aJob.m_theme = wxString::FromUTF8( aSettings.theme() );
1726
1727 aJob.m_plotPages.clear();
1728
1729 for( const std::string& page : aSettings.plot_pages() )
1730 aJob.m_plotPages.push_back( wxString::FromUTF8( page ) );
1731
1732 if( aSettings.page_size() != schematic::jobs::SchematicJobPageSize::SJPS_UNKNOWN )
1733 aJob.m_pageSizeSelect = FromProtoEnum<JOB_PAGE_SIZE>( aSettings.page_size() );
1734
1735 // An unspecified sheet mode keeps the value from aSettings.plot_all()
1736 if( aSettings.sheet_mode() == schematic::jobs::SJSM_ALL_SHEETS )
1737 aJob.m_plotAll = true;
1738 else if( aSettings.sheet_mode() == schematic::jobs::SJSM_SINGLE_SHEET )
1739 aJob.m_plotAll = false;
1740
1741 if( aDocument.has_sheet_path() )
1742 aJob.m_sheetPath = UnpackSheetPath( aDocument.sheet_path() ).AsString();
1743
1744 return std::nullopt;
1745}
1746
1747
1750{
1751 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1752
1753 if( !documentValidation )
1754 return tl::unexpected( documentValidation.error() );
1755
1756 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1757 return tl::unexpected( *busy );
1758
1759 auto plotJob = std::make_unique<JOB_EXPORT_SCH_PLOT_SVG>( aCtx.Request.plot_settings().sheet_mode()
1760 != schematic::jobs::SJSM_SINGLE_SHEET );
1761 plotJob->m_filename = m_context->GetCurrentFileName();
1762
1763 if( !aCtx.Request.job_settings().output_path().empty() )
1764 plotJob->SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1765
1766 if( std::optional<ApiResponseStatus> err = applySchematicPlotSettings(
1767 aCtx.Request.plot_settings(), aCtx.Request.job_settings().document(), *plotJob ) )
1768 {
1769 return tl::unexpected( *err );
1770 }
1771
1772 return ExecuteSchematicJob( m_context->GetKiway(), *plotJob );
1773}
1774
1775
1778{
1779 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1780
1781 if( !documentValidation )
1782 return tl::unexpected( documentValidation.error() );
1783
1784 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1785 return tl::unexpected( *busy );
1786
1787 auto plotJob = std::make_unique<JOB_EXPORT_SCH_PLOT_DXF>( aCtx.Request.plot_settings().sheet_mode()
1788 != schematic::jobs::SJSM_SINGLE_SHEET );
1789
1790 plotJob->m_filename = m_context->GetCurrentFileName();
1791
1792 if( !aCtx.Request.job_settings().output_path().empty() )
1793 plotJob->SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1794
1795 if( std::optional<ApiResponseStatus> err = applySchematicPlotSettings(
1796 aCtx.Request.plot_settings(), aCtx.Request.job_settings().document(), *plotJob ) )
1797 {
1798 return tl::unexpected( *err );
1799 }
1800
1801 return ExecuteSchematicJob( m_context->GetKiway(), *plotJob );
1802}
1803
1804
1807{
1808 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1809
1810 if( !documentValidation )
1811 return tl::unexpected( documentValidation.error() );
1812
1813 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1814 return tl::unexpected( *busy );
1815
1816 auto plotJob = std::make_unique<JOB_EXPORT_SCH_PLOT_PDF>( false );
1817 plotJob->m_filename = m_context->GetCurrentFileName();
1818
1819 if( !aCtx.Request.job_settings().output_path().empty() )
1820 plotJob->SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1821
1822 if( std::optional<ApiResponseStatus> err = applySchematicPlotSettings(
1823 aCtx.Request.plot_settings(), aCtx.Request.job_settings().document(), *plotJob ) )
1824 {
1825 return tl::unexpected( *err );
1826 }
1827
1828 plotJob->m_PDFPropertyPopups = aCtx.Request.property_popups();
1829 plotJob->m_PDFHierarchicalLinks = aCtx.Request.hierarchical_links();
1830 plotJob->m_PDFMetadata = aCtx.Request.include_metadata();
1831
1832 return ExecuteSchematicJob( m_context->GetKiway(), *plotJob );
1833}
1834
1835
1838{
1839 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1840
1841 if( !documentValidation )
1842 return tl::unexpected( documentValidation.error() );
1843
1844 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1845 return tl::unexpected( *busy );
1846
1847 auto plotJob = std::make_unique<JOB_EXPORT_SCH_PLOT_PS>( aCtx.Request.plot_settings().sheet_mode()
1848 != schematic::jobs::SJSM_SINGLE_SHEET );
1849 plotJob->m_filename = m_context->GetCurrentFileName();
1850
1851 if( !aCtx.Request.job_settings().output_path().empty() )
1852 plotJob->SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1853
1854 if( std::optional<ApiResponseStatus> err = applySchematicPlotSettings(
1855 aCtx.Request.plot_settings(), aCtx.Request.job_settings().document(), *plotJob ) )
1856 {
1857 return tl::unexpected( *err );
1858 }
1859
1860 return ExecuteSchematicJob( m_context->GetKiway(), *plotJob );
1861}
1862
1863
1866{
1867 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
1868 return tl::unexpected( validation.error() );
1869
1870 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1871 return tl::unexpected( *busy );
1872
1873 const schematic::jobs::SchematicJobSheetMode sheetMode = aCtx.Request.plot_settings().sheet_mode();
1874
1875 auto plotJob = std::make_unique<JOB_EXPORT_SCH_PLOT_PNG>( sheetMode != schematic::jobs::SJSM_SINGLE_SHEET );
1876 plotJob->m_filename = m_context->GetCurrentFileName();
1877
1878 if( !aCtx.Request.job_settings().output_path().empty() )
1879 plotJob->SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1880
1881 if( std::optional<ApiResponseStatus> err = applySchematicPlotSettings(
1882 aCtx.Request.plot_settings(), aCtx.Request.job_settings().document(), *plotJob ) )
1883 {
1884 return tl::unexpected( *err );
1885 }
1886
1887 if( aCtx.Request.has_dpi() )
1888 {
1889 int dpi = aCtx.Request.dpi();
1890
1891 if( dpi < MIN_PNG_DPI || dpi > MAX_PNG_DPI )
1892 {
1893 ApiResponseStatus status;
1894 status.set_status( ApiStatusCode::AS_BAD_REQUEST );
1895 status.set_error_message( fmt::format( "dpi must be between {} and {}", MIN_PNG_DPI, MAX_PNG_DPI ) );
1896 return tl::unexpected( status );
1897 }
1898
1899 plotJob->m_dpi = dpi;
1900 }
1901
1902 // Unknown -> default AA on
1903 plotJob->m_antialias = aCtx.Request.antialiasing() != types::AntialiasingMode::AAM_NONE;
1904 plotJob->m_useBackgroundColor = aCtx.Request.plot_background_color();
1905
1906 return ExecuteSchematicJob( m_context->GetKiway(), *plotJob );
1907}
1908
1909
1912{
1913 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1914
1915 if( !documentValidation )
1916 return tl::unexpected( documentValidation.error() );
1917
1918 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1919 return tl::unexpected( *busy );
1920
1921 if( aCtx.Request.format() == kiapi::schematic::jobs::SchematicNetlistFormat::SNF_UNKNOWN )
1922 {
1923 ApiResponseStatus e;
1924 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1925 e.set_error_message( "RunSchematicJobExportNetlist requires a valid format" );
1926 return tl::unexpected( e );
1927 }
1928
1929 JOB_EXPORT_SCH_NETLIST netlistJob;
1930 netlistJob.m_filename = m_context->GetCurrentFileName();
1931
1932 if( !aCtx.Request.job_settings().output_path().empty() )
1933 netlistJob.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1934
1935 netlistJob.format = FromProtoEnum<JOB_EXPORT_SCH_NETLIST::FORMAT>( aCtx.Request.format() );
1936
1937 if( !aCtx.Request.variant_name().empty() )
1938 netlistJob.m_variantNames.emplace_back( wxString::FromUTF8( aCtx.Request.variant_name() ) );
1939
1940 return ExecuteSchematicJob( m_context->GetKiway(), netlistJob );
1941}
1942
1943
1946{
1947 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.job_settings().document() );
1948
1949 if( !documentValidation )
1950 return tl::unexpected( documentValidation.error() );
1951
1952 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1953 return tl::unexpected( *busy );
1954
1955 JOB_EXPORT_BOM bomJob;
1956 bomJob.m_filename = m_context->GetCurrentFileName();
1957
1958 if( !aCtx.Request.job_settings().output_path().empty() )
1959 bomJob.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
1960
1961 bomJob.m_bomFmtPresetName = wxString::FromUTF8( aCtx.Request.format().preset_name() );
1962 bomJob.m_fieldDelimiter = wxString::FromUTF8( aCtx.Request.format().field_delimiter() );
1963 bomJob.m_stringDelimiter = wxString::FromUTF8( aCtx.Request.format().string_delimiter() );
1964 bomJob.m_refDelimiter = wxString::FromUTF8( aCtx.Request.format().ref_delimiter() );
1965 bomJob.m_refRangeDelimiter = wxString::FromUTF8( aCtx.Request.format().ref_range_delimiter() );
1966 bomJob.m_keepTabs = aCtx.Request.format().keep_tabs();
1967 bomJob.m_keepLineBreaks = aCtx.Request.format().keep_line_breaks();
1968 bomJob.m_includeByteOrderMark = aCtx.Request.format().include_byte_order_mark();
1969
1970 bomJob.m_bomPresetName = wxString::FromUTF8( aCtx.Request.fields().preset_name() );
1971 bomJob.m_sortField = wxString::FromUTF8( aCtx.Request.fields().sort_field() );
1972 bomJob.m_filterString = wxString::FromUTF8( aCtx.Request.fields().filter() );
1973
1974 if( bomJob.m_bomPresetName.IsEmpty() && aCtx.Request.fields().fields().empty() )
1975 {
1976 ApiResponseStatus e;
1977 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1978 e.set_error_message( "A list of fields fields or a fields preset are required" );
1979 return tl::unexpected( e );
1980 }
1981
1982 switch( aCtx.Request.fields().filter_scope() )
1983 {
1984 case kiapi::schematic::jobs::BOMFilterScope::BFS_VISIBLE:
1986 break;
1987
1988 case kiapi::schematic::jobs::BOMFilterScope::BFS_ALL:
1990 break;
1991
1992 case kiapi::schematic::jobs::BOMFilterScope::BFS_REFERENCE:
1993 default:
1995 break;
1996 }
1997
1998 if( aCtx.Request.fields().sort_direction() == kiapi::schematic::jobs::BOMSortDirection::BSD_ASCENDING )
1999 {
2000 bomJob.m_sortAsc = true;
2001 }
2002 else if( aCtx.Request.fields().sort_direction() == kiapi::schematic::jobs::BOMSortDirection::BSD_DESCENDING )
2003 {
2004 bomJob.m_sortAsc = false;
2005 }
2006
2007 for( const kiapi::schematic::jobs::BOMField& field : aCtx.Request.fields().fields() )
2008 {
2009 bomJob.m_fieldsOrdered.emplace_back( wxString::FromUTF8( field.name() ) );
2010 bomJob.m_fieldsLabels.emplace_back( wxString::FromUTF8( field.label() ) );
2011
2012 if( field.group_by() )
2013 bomJob.m_fieldsGroupBy.emplace_back( wxString::FromUTF8( field.name() ) );
2014 }
2015
2016 bomJob.m_excludeDNP = aCtx.Request.exclude_dnp();
2017 bomJob.m_groupSymbols = aCtx.Request.group_symbols();
2018
2019 if( !aCtx.Request.variant_name().empty() )
2020 bomJob.m_variantNames.emplace_back( wxString::FromUTF8( aCtx.Request.variant_name() ) );
2021
2022 return ExecuteSchematicJob( m_context->GetKiway(), bomJob );
2023}
2024
2025
2026void API_HANDLER_SCH::packSheetInstance( kiapi::schematic::types::SheetInstance* aInstance, SCH_SHEET_PATH& aPath,
2027 SCH_SHEET* aSheet )
2028{
2029 aPath.push_back( aSheet );
2030
2031 PackSheetPath( *aInstance->mutable_path(), aPath );
2032
2033 wxString sheetName = aSheet->GetShownName( INTERNAL );
2034
2035 if( sheetName.IsEmpty() && aSheet->GetScreen() )
2036 {
2037 wxFileName fn( aSheet->GetScreen()->GetFileName() );
2038 sheetName = fn.GetName();
2039 }
2040
2041 aInstance->set_name( sheetName.ToUTF8() );
2042 aInstance->set_filename( aSheet->GetFileName().ToUTF8() );
2043 aInstance->set_page_number( aPath.GetPageNumber().ToUTF8() );
2044
2045 if( aSheet->GetScreen() )
2046 {
2047 std::vector<SCH_ITEM*> childSheets;
2048 aSheet->GetScreen()->GetSheets( &childSheets );
2049
2050 std::ranges::sort( childSheets,
2051 [&]( SCH_ITEM* a, SCH_ITEM* b )
2052 {
2053 SCH_SHEET_PATH pathA = aPath;
2054 pathA.push_back( static_cast<SCH_SHEET*>( a ) );
2055
2056 SCH_SHEET_PATH pathB = aPath;
2057 pathB.push_back( static_cast<SCH_SHEET*>( b ) );
2058
2059 return pathA.ComparePageNum( pathB ) < 0;
2060 } );
2061
2062 for( SCH_ITEM* childItem : childSheets )
2063 {
2064 SCH_SHEET* childSheet = static_cast<SCH_SHEET*>( childItem );
2065 kiapi::schematic::types::SheetInstance* childInstance = aInstance->add_children();
2066 packSheetInstance( childInstance, aPath, childSheet );
2067 }
2068 }
2069
2070 aPath.pop_back();
2071}
2072
2073
2076{
2077 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
2078
2079 if( !documentValidation )
2080 return tl::unexpected( documentValidation.error() );
2081
2082 kiapi::schematic::commands::SchematicHierarchyResponse response;
2083 response.mutable_document()->CopyFrom( aCtx.Request.document() );
2084
2085 if( !schematic()->HasHierarchy() )
2087
2089 std::vector<SCH_SHEET*> topLevelSheets = schematic()->GetTopLevelSheets();
2090
2091 std::ranges::sort( topLevelSheets,
2092 [&]( SCH_SHEET* a, SCH_SHEET* b )
2093 {
2094 SCH_SHEET_PATH pathA;
2095 pathA.push_back( a );
2096
2097 SCH_SHEET_PATH pathB;
2098 pathB.push_back( b );
2099
2100 return pathA.ComparePageNum( pathB ) < 0;
2101 } );
2102
2103 for( SCH_SHEET* topSheet : topLevelSheets )
2104 {
2105 kiapi::schematic::types::SheetInstance* instance = response.add_top_level_sheets();
2106 packSheetInstance( instance, path, topSheet );
2107 }
2108
2109 return response;
2110}
2111
2112
2115{
2116 const bool engine = ADVANCED_CFG::GetCfg().m_ConnectivityEngine;
2117
2118 // The engine rebuilds before answering, which an interactive tool must not observe
2119 if( engine && m_frame && !m_frame->ToolStackIsEmpty() )
2120 {
2121 ApiResponseStatus status;
2122 status.set_status( ApiStatusCode::AS_BUSY );
2123 status.set_error_message( "Cannot rebuild connectivity during an interactive operation" );
2124 return tl::unexpected( status );
2125 }
2126
2127 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
2128
2129 if( !documentValidation )
2130 return tl::unexpected( documentValidation.error() );
2131
2132 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2133 return tl::unexpected( *busy );
2134
2135 std::vector<KICAD_T> types = parseRequestedItemTypes( aCtx.Request.types() );
2136 const bool filterByType = aCtx.Request.types_size() > 0;
2137
2138 static const std::set<KICAD_T> s_netlistTypes = {
2139 SCH_PIN_T,
2141 SCH_LINE_T,
2151 };
2152
2153 std::set<KICAD_T> typeFilter( types.begin(), types.end() );
2154 std::erase_if( typeFilter, []( KICAD_T aType ) { return !s_netlistTypes.contains( aType ); } );
2155
2156 if( filterByType && typeFilter.empty() )
2157 {
2158 ApiResponseStatus e;
2159 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2160 e.set_error_message( "none of the requested types are valid for a netlist object" );
2161 return tl::unexpected( e );
2162 }
2163
2164 CONNECTION_GRAPH* connectionGraph = schematic()->ConnectionGraph();
2165
2166 if( !connectionGraph )
2167 {
2168 ApiResponseStatus e;
2169 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2170 e.set_error_message( "schematic has no connection graph" );
2171 return tl::unexpected( e );
2172 }
2173
2174 if( engine )
2175 {
2176 try
2177 {
2179 }
2180 catch( const std::exception& error )
2181 {
2182 if( m_frame )
2183 {
2184 m_frame->ShowInfoBarError( _( "Unable to rebuild schematic connectivity." ), true );
2185 frame()->RefreshConnectivity( true );
2186 }
2187
2188 wxLogTrace( traceApi, wxS( "GetSchematicNetlist rebuild failed: %s" ),
2189 wxString::FromUTF8( error.what() ) );
2190
2191 ApiResponseStatus status;
2192 status.set_status( ApiStatusCode::AS_UNKNOWN );
2193 status.set_error_message( error.what() );
2194 return tl::unexpected( status );
2195 }
2196 }
2197
2198 kiapi::schematic::commands::SchematicNetlistResponse response;
2199 response.mutable_document()->CopyFrom( aCtx.Request.document() );
2200
2201 if( engine )
2202 {
2203 for( const auto& group : schematic()->Connectivity().GetNetMap() )
2204 {
2205 if( group.instances.empty() || !group.instances.front().IsNet()
2206 || !group.instances.front().Driver() )
2207 {
2208 continue;
2209 }
2210
2211 kiapi::schematic::types::SchematicNet* net = nullptr;
2212
2213 for( const auto& view : group.instances )
2214 {
2215 const auto physicalItems = view.Items();
2216
2217 if( physicalItems.empty() )
2218 continue;
2219
2220 if( !net )
2221 {
2222 net = response.add_nets();
2223 net->set_name( group.name.ToUTF8() );
2224 }
2225
2226 auto* sheet = net->add_sheets();
2227 PackSheetPath( *sheet->mutable_path(), view.Instance() );
2228
2229 for( SCH_ITEM* item : physicalItems )
2230 {
2231 if( !filterByType || typeFilter.contains( item->Type() ) )
2232 sheet->add_items()->set_value( item->m_Uuid.AsStdString() );
2233 }
2234 }
2235 }
2236
2237 return response;
2238 }
2239
2240 for( const auto& [key, subgraphList] : connectionGraph->GetNetMap() )
2241 {
2242 if( subgraphList.empty() )
2243 continue;
2244
2245 CONNECTION_SUBGRAPH* firstSubgraph = subgraphList[0];
2246
2247 if( firstSubgraph->GetDriverConnection() && firstSubgraph->GetDriverConnection()->IsBus() )
2248 continue;
2249
2251 continue;
2252
2253 kiapi::schematic::types::SchematicNet* net = response.add_nets();
2254 net->set_name( key.Name.ToUTF8() );
2255
2256 for( CONNECTION_SUBGRAPH* subGraph : subgraphList )
2257 {
2258 kiapi::schematic::types::SchematicNetSheetContents* sheetContents = net->add_sheets();
2259 PackSheetPath( *sheetContents->mutable_path(), subGraph->GetSheet() );
2260
2261 for( SCH_ITEM* item : subGraph->GetItems() )
2262 {
2263 if( filterByType && !typeFilter.contains( item->Type() ) )
2264 continue;
2265
2266 sheetContents->add_items()->set_value( item->m_Uuid.AsStdString() );
2267 }
2268 }
2269 }
2270
2271 return response;
2272}
2273
2274
2275// TODO(JE) factor out
2278{
2279 wxLogTrace( traceApi, "Received announce from frame %d at %s",
2280 aCtx.Request.frame_type(), aCtx.Request.socket_path() );
2281
2282 CROSS_PROBE_CLIENT::RegisterPeer( static_cast<FRAME_T>( aCtx.Request.frame_type() ),
2283 aCtx.Request.socket_path() );
2284
2285 CrossProbeAnnounceResponse response;
2286 response.set_status( CPS_OK );
2287 return response;
2288}
2289
2290
2291bool findSymbolsAndPins( const SCH_SHEET_LIST& aSchematicSheetList, const SCH_SHEET_PATH& aSheetPath,
2292 std::unordered_map<wxString, std::vector<SCH_REFERENCE>>& aSyncSymMap,
2293 std::unordered_map<wxString, std::unordered_map<wxString, SCH_PIN*>>& aSyncPinMap,
2294 const wxString& aVariantName = wxEmptyString, bool aRecursive = false )
2295{
2296 if( aRecursive )
2297 {
2298 // Iterate over children
2299 for( const SCH_SHEET_PATH& candidate : aSchematicSheetList )
2300 {
2301 if( candidate == aSheetPath || !candidate.IsContainedWithin( aSheetPath ) )
2302 continue;
2303
2304 findSymbolsAndPins( aSchematicSheetList, candidate, aSyncSymMap, aSyncPinMap, aVariantName, aRecursive );
2305 }
2306 }
2307
2308 SCH_REFERENCE_LIST references;
2309
2310 aSheetPath.GetSymbols( references, SYMBOL_FILTER_NON_POWER, true );
2311
2312 for( unsigned ii = 0; ii < references.GetCount(); ii++ )
2313 {
2314 SCH_REFERENCE& schRef = references[ii];
2315
2316 if( schRef.IsSplitNeeded() )
2317 schRef.Split();
2318
2319 SCH_SYMBOL* symbol = schRef.GetSymbol();
2320 wxString refNum = schRef.GetRefNumber();
2321 wxString fullRef = schRef.GetComposedRef();
2322
2323 // Skip power symbols
2324 if( fullRef.StartsWith( wxS( "#" ) ) )
2325 continue;
2326
2327 // Unannotated symbols are not supported
2328 if( refNum.compare( wxS( "?" ) ) == 0 )
2329 continue;
2330
2331 // Look for whole footprint
2332 auto symMatchIt = aSyncSymMap.find( fullRef );
2333
2334 if( symMatchIt != aSyncSymMap.end() )
2335 {
2336 symMatchIt->second.emplace_back( schRef );
2337
2338 // Whole footprint was selected, no need to select pins
2339 continue;
2340 }
2341
2342 // Look for pins
2343 auto symPinMatchIt = aSyncPinMap.find( fullRef );
2344
2345 if( symPinMatchIt != aSyncPinMap.end() )
2346 {
2347 std::unordered_map<wxString, SCH_PIN*>& pinMap = symPinMatchIt->second;
2348 std::vector<SCH_PIN*> pinsOnSheet = symbol->GetPins( &aSheetPath );
2349
2350 for( SCH_PIN* pin : pinsOnSheet )
2351 {
2352 int pinUnit = pin->GetLibPin() ? pin->GetLibPin()->GetUnit() : ALL_UNITS;
2353
2354 if( pinUnit > 0 && pinUnit != schRef.GetUnit() )
2355 continue;
2356
2357 // Reverse-map the requested pad back to the owning pin (issue #2282). A pin may
2358 // resolve to several pads via the map; match the first that pcbnew asked for.
2359 for( const wxString& pad :
2360 ExpandStackedPinNotation( pin->GetEffectivePadNumber( aSheetPath, aVariantName ) ) )
2361 {
2362 auto pinIt = pinMap.find( pad );
2363
2364 if( pinIt != pinMap.end() )
2365 {
2366 pinIt->second = pin;
2367 break;
2368 }
2369 }
2370 }
2371 }
2372 }
2373
2374 return false;
2375}
2376
2377
2379 const SCH_SHEET_LIST& aSchematicSheetList, const SCH_SHEET_PATH& aSheetPath,
2380 std::unordered_map<wxString, std::vector<SCH_REFERENCE>>& aSyncSymMap,
2381 std::unordered_map<wxString, std::unordered_map<wxString, SCH_PIN*>>& aSyncPinMap,
2382 std::unordered_map<SCH_SHEET_PATH, bool>& aCache )
2383{
2384 auto cacheIt = aCache.find( aSheetPath );
2385
2386 if( cacheIt != aCache.end() )
2387 return cacheIt->second;
2388
2389 // Iterate over children
2390 for( const SCH_SHEET_PATH& candidate : aSchematicSheetList )
2391 {
2392 if( candidate == aSheetPath || !candidate.IsContainedWithin( aSheetPath ) )
2393 continue;
2394
2395 bool childRet = sheetContainsOnlyWantedItems( aSchematicSheetList, candidate, aSyncSymMap,
2396 aSyncPinMap, aCache );
2397
2398 if( !childRet )
2399 {
2400 aCache.emplace( aSheetPath, false );
2401 return false;
2402 }
2403 }
2404
2405 SCH_REFERENCE_LIST references;
2406 aSheetPath.GetSymbols( references, SYMBOL_FILTER_NON_POWER, true );
2407
2408 if( references.GetCount() == 0 ) // Empty sheet, obviously do not contain wanted items
2409 {
2410 aCache.emplace( aSheetPath, false );
2411 return false;
2412 }
2413
2414 for( unsigned ii = 0; ii < references.GetCount(); ii++ )
2415 {
2416 SCH_REFERENCE& schRef = references[ii];
2417
2418 if( schRef.IsSplitNeeded() )
2419 schRef.Split();
2420
2421 wxString refNum = schRef.GetRefNumber();
2422 wxString fullRef = schRef.GetComposedRef();
2423
2424 // Skip power symbols
2425 if( fullRef.StartsWith( wxS( "#" ) ) )
2426 continue;
2427
2428 // Unannotated symbols are not supported
2429 if( refNum.compare( wxS( "?" ) ) == 0 )
2430 continue;
2431
2432 if( aSyncSymMap.find( fullRef ) == aSyncSymMap.end() )
2433 {
2434 aCache.emplace( aSheetPath, false );
2435 return false; // Some symbol is not wanted.
2436 }
2437
2438 if( aSyncPinMap.find( fullRef ) != aSyncPinMap.end() )
2439 {
2440 aCache.emplace( aSheetPath, false );
2441 return false; // Looking for specific pins, so can't be mapped
2442 }
2443 }
2444
2445 aCache.emplace( aSheetPath, true );
2446 return true;
2447}
2448
2449
2450std::optional<std::tuple<SCH_SHEET_PATH, SCH_ITEM*, std::vector<SCH_ITEM*>>>
2452 const kiapi::common::commands::SyncSelection& aSync )
2453{
2454 std::unordered_map<wxString, std::vector<SCH_REFERENCE>> syncSymMap;
2455 std::unordered_map<wxString, std::unordered_map<wxString, SCH_PIN*>> syncPinMap;
2456 std::unordered_map<SCH_SHEET_PATH, bool> fullyWantedCache;
2457
2458 std::optional<wxString> focusSymbol;
2459 std::optional<std::pair<wxString, wxString>> focusPin;
2460 std::unordered_map<SCH_SHEET_PATH, std::vector<SCH_ITEM*>> focusItemResults;
2461
2462 const SCH_SHEET_LIST allSheetsList = aSchematic.Hierarchy();
2463
2464 // In orderedSheets, the current sheet comes first.
2465 std::vector<SCH_SHEET_PATH> orderedSheets;
2466 orderedSheets.reserve( allSheetsList.size() );
2467 orderedSheets.push_back( aSchematic.CurrentSheet() );
2468
2469 for( const SCH_SHEET_PATH& sheetPath : allSheetsList )
2470 {
2471 if( sheetPath != aSchematic.CurrentSheet() )
2472 orderedSheets.push_back( sheetPath );
2473 }
2474
2475 const bool focusOnFirst = ( aSync.mode() == kiapi::common::commands::SSM_ITEMS_AND_NETS ) && aSync.has_focus_item();
2476
2477 for( const kiapi::common::commands::SelectionSpec& spec : aSync.items() )
2478 {
2479 switch( spec.spec_case() )
2480 {
2481 case kiapi::common::commands::SelectionSpec::kFootprint:
2482 {
2483 wxString symRef = wxString::FromUTF8( spec.footprint().reference() );
2484 syncSymMap[symRef] = std::vector<SCH_REFERENCE>();
2485 break;
2486 }
2487
2488 case kiapi::common::commands::SelectionSpec::kPad:
2489 {
2490 wxString symRef = wxString::FromUTF8( spec.pad().reference() );
2491 wxString padNum = wxString::FromUTF8( spec.pad().number() );
2492 syncPinMap[symRef][padNum] = nullptr;
2493 break;
2494 }
2495
2496 default:
2497 break;
2498 }
2499 }
2500
2501 if( focusOnFirst )
2502 {
2503 const kiapi::common::commands::SelectionSpec& focusSpec = aSync.focus_item();
2504
2505 if( focusSpec.has_footprint() )
2506 focusSymbol = wxString::FromUTF8( focusSpec.footprint().reference() );
2507 else if( focusSpec.has_pad() )
2508 focusPin = std::make_pair( wxString::FromUTF8( focusSpec.pad().reference() ),
2509 wxString::FromUTF8( focusSpec.pad().number() ) );
2510 }
2511
2512 // Lambda definitions
2513 auto flattenSyncMaps =
2514 [&syncSymMap, &syncPinMap]() -> std::vector<SCH_ITEM*>
2515 {
2516 std::vector<SCH_ITEM*> allVec;
2517
2518 for( const auto& [symRef, symbols] : syncSymMap )
2519 {
2520 for( const SCH_REFERENCE& ref : symbols )
2521 allVec.push_back( ref.GetSymbol() );
2522 }
2523
2524 for( const auto& [symRef, pinMap] : syncPinMap )
2525 {
2526 for( const auto& [padNum, pin] : pinMap )
2527 {
2528 if( pin )
2529 allVec.push_back( pin );
2530 }
2531 }
2532
2533 return allVec;
2534 };
2535
2536 auto clearSyncMaps =
2537 [&syncSymMap, &syncPinMap]()
2538 {
2539 for( auto& [symRef, symbols] : syncSymMap )
2540 symbols.clear();
2541
2542 for( auto& [reference, pins] : syncPinMap )
2543 {
2544 for( auto& [number, pin] : pins )
2545 pin = nullptr;
2546 }
2547 };
2548
2549 auto syncMapsValuesEmpty =
2550 [&syncSymMap, &syncPinMap]() -> bool
2551 {
2552 for( const auto& [symRef, symbols] : syncSymMap )
2553 {
2554 if( symbols.size() > 0 )
2555 return false;
2556 }
2557
2558 for( const auto& [symRef, pins] : syncPinMap )
2559 {
2560 for( const auto& [padNum, pin] : pins )
2561 {
2562 if( pin )
2563 return false;
2564 }
2565 }
2566
2567 return true;
2568 };
2569
2570 auto checkFocusItems =
2571 [&]( const SCH_SHEET_PATH& aSheet )
2572 {
2573 if( focusSymbol )
2574 {
2575 auto findIt = syncSymMap.find( *focusSymbol );
2576
2577 if( findIt != syncSymMap.end() )
2578 {
2579 if( findIt->second.size() > 0 )
2580 focusItemResults[aSheet].push_back( findIt->second.front().GetSymbol() );
2581 }
2582 }
2583 else if( focusPin )
2584 {
2585 auto findIt = syncPinMap.find( focusPin->first );
2586
2587 if( findIt != syncPinMap.end() )
2588 {
2589 if( findIt->second[focusPin->second] )
2590 focusItemResults[aSheet].push_back( findIt->second[focusPin->second] );
2591 }
2592 }
2593 };
2594
2595 auto makeRetForSheet =
2596 [&]( const SCH_SHEET_PATH& aSheet, SCH_ITEM* aFocusItem )
2597 {
2598 clearSyncMaps();
2599
2600 // Fill sync maps
2601 findSymbolsAndPins( allSheetsList, aSheet, syncSymMap, syncPinMap, aSchematic.GetCurrentVariant() );
2602 std::vector<SCH_ITEM*> itemsVector = flattenSyncMaps();
2603
2604 // Add fully wanted sheets to vector
2605 for( SCH_ITEM* item : aSheet.LastScreen()->Items().OfType( SCH_SHEET_T ) )
2606 {
2607 KIID_PATH kiidPath = aSheet.Path();
2608 kiidPath.push_back( item->m_Uuid );
2609
2610 std::optional<SCH_SHEET_PATH> subsheetPath =
2611 allSheetsList.GetSheetPathByKIIDPath( kiidPath );
2612
2613 if( !subsheetPath )
2614 continue;
2615
2616 if( sheetContainsOnlyWantedItems( allSheetsList, *subsheetPath, syncSymMap,
2617 syncPinMap, fullyWantedCache ) )
2618 {
2619 itemsVector.push_back( item );
2620 }
2621 }
2622
2623 return std::make_tuple( aSheet, aFocusItem, itemsVector );
2624 };
2625
2626 if( focusOnFirst )
2627 {
2628 for( const SCH_SHEET_PATH& sheetPath : orderedSheets )
2629 {
2630 clearSyncMaps();
2631
2632 findSymbolsAndPins( allSheetsList, sheetPath, syncSymMap, syncPinMap, aSchematic.GetCurrentVariant() );
2633
2634 checkFocusItems( sheetPath );
2635 }
2636
2637 if( focusItemResults.size() > 0 )
2638 {
2639 for( const SCH_SHEET_PATH& sheetPath : orderedSheets )
2640 {
2641 const std::vector<SCH_ITEM*>& items = focusItemResults[sheetPath];
2642
2643 if( !items.empty() )
2644 return makeRetForSheet( sheetPath, items.front() );
2645 }
2646 }
2647 }
2648 else
2649 {
2650 for( const SCH_SHEET_PATH& sheetPath : orderedSheets )
2651 {
2652 clearSyncMaps();
2653
2654 findSymbolsAndPins( allSheetsList, sheetPath, syncSymMap, syncPinMap, aSchematic.GetCurrentVariant() );
2655
2656 if( !syncMapsValuesEmpty() )
2657 {
2658 // Something found on sheet
2659 return makeRetForSheet( sheetPath, nullptr );
2660 }
2661 }
2662 }
2663
2664 return std::nullopt;
2665}
2666
2667
2669 const HANDLER_CONTEXT<SyncSelection>& aCtx )
2670{
2671 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "SyncSelection" ) )
2672 return tl::unexpected( *headless );
2673
2674 SyncSelectionResponse response;
2675
2676 const CROSS_PROBING_SETTINGS& settings = frame()->eeconfig()->m_CrossProbing;
2677
2678 if( !settings.on_selection && aCtx.Request.context() != SyncSelectionContext::SSC_EXPLICIT )
2679 {
2680 response.set_status( CPS_DISABLED );
2681 response.set_message( "implicit selection sync disabled by user" );
2682 return response;
2683 }
2684
2685 // A request carrying no items asks for nothing to be selected, so there is nothing to find.
2686 if( aCtx.Request.items_size() == 0 )
2687 {
2688 frame()->SetSyncingSelection( true ); // recursion guard
2689
2690 frame()->GetToolManager()->GetTool<SCH_SELECTION_TOOL>()->SyncSelection( std::nullopt, nullptr, {} );
2691
2692 frame()->SetSyncingSelection( false );
2693
2694 response.set_status( CPS_OK );
2695 return response;
2696 }
2697
2698 std::optional<std::tuple<SCH_SHEET_PATH, SCH_ITEM*, std::vector<SCH_ITEM*>>> findRet =
2700
2701 if( findRet )
2702 {
2703 auto& [sheetPath, focusItem, items] = *findRet;
2704
2705 frame()->SetSyncingSelection( true ); // recursion guard
2706
2707 frame()->GetToolManager()->GetTool<SCH_SELECTION_TOOL>()->SyncSelection( sheetPath, focusItem, items );
2708
2709 frame()->SetSyncingSelection( false );
2710
2711 if( frame()->eeconfig()->m_CrossProbing.flash_selection )
2712 {
2713 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE): flash enabled, items=%zu",
2714 items.size() );
2715
2716 if( items.empty() )
2717 {
2718 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE): nothing to flash" );
2719 }
2720 else
2721 {
2722 std::vector<SCH_ITEM*> itemPtrs;
2723 std::copy( items.begin(), items.end(), std::back_inserter( itemPtrs ) );
2724
2725 frame()->StartCrossProbeFlash( itemPtrs );
2726 }
2727 }
2728 else
2729 {
2730 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE): flash disabled" );
2731 }
2732 }
2733
2734 response.set_status( CPS_OK );
2735 return response;
2736}
2737
2738
2740 const HANDLER_CONTEXT<HighlightNets>& aCtx )
2741{
2742 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "HighlightNets" ) )
2743 return tl::unexpected( *headless );
2744
2745 HighlightNetsResponse response;
2746 CROSS_PROBING_SETTINGS& crossProbingSettings = frame()->eeconfig()->m_CrossProbing;
2747
2749 || aCtx.ClientName == KiwayClientName )
2750 {
2751 if( !crossProbingSettings.auto_highlight )
2752 {
2753 response.set_status( CPS_DISABLED );
2754 return response;
2755 }
2756 }
2757
2758 wxString net;
2759
2760 if( aCtx.Request.net_name_size() > 0 )
2761 net = wxString::FromUTF8( aCtx.Request.net_name( 0 ) );
2762
2764
2765 response.set_status( CPS_OK );
2766 return response;
2767}
2768
2769
2770
2773{
2774 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() );
2775
2776 if( !documentValidation )
2777 return tl::unexpected( documentValidation.error() );
2778
2779 SCH_SHEET_PATH path = m_context->GetCurrentSheet().value_or( *schematic()->Hierarchy().begin() );
2780
2781 if( aCtx.Request.document().has_sheet_path() )
2782 {
2783 KIID_PATH kiidPath = UnpackSheetPath( aCtx.Request.document().sheet_path() );
2784
2785 if( std::optional<SCH_SHEET_PATH> resolvedPath = schematic()->Hierarchy().GetSheetPathByKIIDPath( kiidPath ) )
2786 {
2787 path = *resolvedPath;
2788 }
2789 }
2790
2791 ExpandTextVariablesResponse reply;
2792
2793 std::function<bool( wxString* )> textResolver =
2794 [&]( wxString* token ) -> bool
2795 {
2796 return schematic()->ResolveTextVar( &path, token, 0 );
2797 };
2798
2799 PROJECT& project = m_context->Prj();
2800
2801 for( const std::string& textMsg : aCtx.Request.text() )
2802 {
2803 wxString text = ExpandTextVars( wxString::FromUTF8( textMsg ), &textResolver, INTERNAL );
2804
2805 if( aCtx.Request.expand_env_vars() )
2807
2808 reply.add_text( text.ToUTF8() );
2809 }
2810
2811 return reply;
2812}
2813
2814
2816{
2817 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
2818 return tl::unexpected( documentValidation.error() );
2819
2820 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2821 return tl::unexpected( *busy );
2822
2823 VariantsResponse response;
2824
2825 response.mutable_document()->CopyFrom( aCtx.Request.document() );
2826
2827 for( const wxString& name : schematic()->GetVariantNames() )
2828 {
2829 types::DesignVariant* var = response.add_variants();
2830 var->set_name( name.ToUTF8() );
2831 var->set_description( schematic()->GetVariantDescription( name ).ToUTF8() );
2832 }
2833
2834 return response;
2835}
2836
2837
2839{
2840 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
2841 return tl::unexpected( documentValidation.error() );
2842
2843 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2844 return tl::unexpected( *busy );
2845
2846 SCHEMATIC* schematic = this->schematic();
2847 wxString name = wxString::FromUTF8( aCtx.Request.name() );
2848
2849 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 || schematic->HasVariant( name ) )
2850 {
2851 ApiResponseStatus e;
2852 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2853 e.set_error_message( fmt::format( "'{}' is not a usable new variant name", aCtx.Request.name() ) );
2854 return tl::unexpected( e );
2855 }
2856
2858
2859 if( std::optional<wxString> canonical = FindVariantNoCase( schematic, name ) )
2860 name = *canonical;
2861
2862 schematic->AddVariant( name );
2863
2864 if( aCtx.Request.has_description() )
2865 schematic->SetVariantDescription( name, wxString::FromUTF8( aCtx.Request.description() ) );
2866
2867 onModified();
2868
2869 if( m_frame )
2870 {
2871 PICKED_ITEMS_LIST* undoCmd = new PICKED_ITEMS_LIST();
2872
2873 undoCmd->PushItem( ITEM_PICKER( frame()->GetScreen(), undoItem, UNDO_REDO::VARIANTS ) );
2874 undoCmd->SetDescription( _( "Add Variant" ) );
2875 frame()->PushCommandToUndoList( undoCmd );
2876
2877 frame()->SyncVariantUI();
2878 }
2879
2880 return Empty();
2881}
2882
2883
2885{
2886 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
2887 return tl::unexpected( documentValidation.error() );
2888
2889 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2890 return tl::unexpected( *busy );
2891
2892 SCHEMATIC* schematic = this->schematic();
2893 wxString name = wxString::FromUTF8( aCtx.Request.name() );
2894
2895 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 )
2896 {
2897 ApiResponseStatus e;
2898 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2899 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.name() ) );
2900 return tl::unexpected( e );
2901 }
2902
2903 if( !schematic->HasVariant( name ) )
2904 {
2905 ApiResponseStatus e;
2906 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2907 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
2908 return tl::unexpected( e );
2909 }
2910
2912 SCH_COMMIT commit( m_frame ? frame()->GetToolManager() : toolManager() );
2913 bool pushedCommit = false;
2914
2915 if( std::optional<wxString> canonical = FindVariantNoCase( schematic, name ) )
2916 name = *canonical;
2917
2918 schematic->DeleteVariant( name, &commit );
2919
2920 if( !commit.Empty() )
2921 {
2922 commit.Push();
2923 pushedCommit = true;
2924 }
2925
2926 onModified();
2927
2928 if( m_frame )
2929 {
2930 PICKED_ITEMS_LIST* undoCmd = pushedCommit ? frame()->PopCommandFromUndoList()
2931 : new PICKED_ITEMS_LIST();
2932
2933 undoCmd->PushItem( ITEM_PICKER( frame()->GetScreen(), undoItem, UNDO_REDO::VARIANTS ) );
2934 undoCmd->SetDescription( _( "Delete Variant" ) );
2935 frame()->PushCommandToUndoList( undoCmd );
2936
2937 if( frame()->Schematic().GetCurrentVariant().CmpNoCase( name ) == 0 )
2938 frame()->SetCurrentVariant( wxEmptyString );
2939
2940 frame()->SyncVariantUI();
2941 frame()->GetCanvas()->Refresh();
2942 }
2943
2944 return Empty();
2945}
2946
2947
2949{
2950 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
2951 return tl::unexpected( documentValidation.error() );
2952
2953 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2954 return tl::unexpected( *busy );
2955
2956 SCHEMATIC* schematic = this->schematic();
2957 wxString oldName = wxString::FromUTF8( aCtx.Request.old_name() );
2958 wxString newName = wxString::FromUTF8( aCtx.Request.new_name() );
2959
2960 if( oldName.IsEmpty() || oldName.CmpNoCase( GetDefaultVariantName() ) == 0 )
2961 {
2962 ApiResponseStatus e;
2963 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2964 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.old_name() ) );
2965 return tl::unexpected( e );
2966 }
2967
2968 if( newName.IsEmpty() || newName.CmpNoCase( GetDefaultVariantName() ) == 0 )
2969 {
2970 ApiResponseStatus e;
2971 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2972 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.new_name() ) );
2973 return tl::unexpected( e );
2974 }
2975
2976 if( !schematic->HasVariant( oldName ) )
2977 {
2978 ApiResponseStatus e;
2979 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2980 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.old_name() ) );
2981 return tl::unexpected( e );
2982 }
2983
2984 if( schematic->HasVariant( newName ) )
2985 {
2986 ApiResponseStatus e;
2987 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2988 e.set_error_message( fmt::format( "a variant named '{}' already exists", aCtx.Request.new_name() ) );
2989 return tl::unexpected( e );
2990 }
2991
2992 bool isCurrent = frame() ? frame()->Schematic().GetCurrentVariant().CmpNoCase( oldName ) == 0 : false;
2993
2995 SCH_COMMIT commit( m_frame ? frame()->GetToolManager() : toolManager() );
2996 bool pushedCommit = false;
2997
2998 if( std::optional<wxString> canonicalOld = FindVariantNoCase( schematic, oldName ) )
2999 oldName = *canonicalOld;
3000
3001 schematic->RenameVariant( oldName, newName, &commit );
3002
3003 if( !commit.Empty() )
3004 {
3005 commit.Push();
3006 pushedCommit = true;
3007 }
3008
3009 onModified();
3010
3011 if( m_frame )
3012 {
3013 PICKED_ITEMS_LIST* undoCmd = pushedCommit ? frame()->PopCommandFromUndoList()
3014 : new PICKED_ITEMS_LIST();
3015
3016 undoCmd->PushItem( ITEM_PICKER( frame()->GetScreen(), undoItem, UNDO_REDO::VARIANTS ) );
3017 undoCmd->SetDescription( _( "Rename Variant" ) );
3018 frame()->PushCommandToUndoList( undoCmd );
3019
3020 frame()->SyncVariantUI();
3021
3022 // Repaint ${VARIANT} text under the new name
3023 if( isCurrent )
3024 frame()->SetCurrentVariant( newName );
3025 }
3026
3027 return Empty();
3028}
3029
3030
3032{
3033 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3034 return tl::unexpected( documentValidation.error() );
3035
3036 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3037 return tl::unexpected( *busy );
3038
3039 SCHEMATIC* schematic = this->schematic();
3040 wxString oldName = wxString::FromUTF8( aCtx.Request.old_name() );
3041 wxString newName = wxString::FromUTF8( aCtx.Request.new_name() );
3042
3043 if( oldName.IsEmpty() || oldName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3044 {
3045 ApiResponseStatus e;
3046 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3047 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.old_name() ) );
3048 return tl::unexpected( e );
3049 }
3050
3051 if( newName.IsEmpty() || newName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3052 {
3053 ApiResponseStatus e;
3054 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3055 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.new_name() ) );
3056 return tl::unexpected( e );
3057 }
3058
3059 if( !schematic->HasVariant( oldName ) )
3060 {
3061 ApiResponseStatus e;
3062 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3063 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.old_name() ) );
3064 return tl::unexpected( e );
3065 }
3066
3067 if( schematic->HasVariant( newName ) )
3068 {
3069 ApiResponseStatus e;
3070 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3071 e.set_error_message( fmt::format( "a variant named '{}' already exists", aCtx.Request.new_name() ) );
3072 return tl::unexpected( e );
3073 }
3074
3076 SCH_COMMIT commit( m_frame ? frame()->GetToolManager() : toolManager() );
3077 bool pushedCommit = false;
3078
3079 if( std::optional<wxString> canonicalOld = FindVariantNoCase( schematic, oldName ) )
3080 oldName = *canonicalOld;
3081
3082 schematic->CopyVariant( oldName, newName, &commit );
3083
3084 if( aCtx.Request.has_new_description() )
3085 schematic->SetVariantDescription( newName, wxString::FromUTF8( aCtx.Request.new_description() ) );
3086
3087 if( !commit.Empty() )
3088 {
3089 commit.Push();
3090 pushedCommit = true;
3091 }
3092
3093 onModified();
3094
3095 if( m_frame )
3096 {
3097 PICKED_ITEMS_LIST* undoCmd = pushedCommit ? frame()->PopCommandFromUndoList()
3098 : new PICKED_ITEMS_LIST();
3099
3100 undoCmd->PushItem( ITEM_PICKER( frame()->GetScreen(), undoItem, UNDO_REDO::VARIANTS ) );
3101 undoCmd->SetDescription( _( "Copy Variant" ) );
3102 frame()->PushCommandToUndoList( undoCmd );
3103
3104 frame()->SyncVariantUI();
3105 }
3106
3107 return Empty();
3108}
3109
3110
3112{
3113 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3114 return tl::unexpected( documentValidation.error() );
3115
3116 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3117 return tl::unexpected( *busy );
3118
3119 SCHEMATIC* schematic = this->schematic();
3120 wxString name = wxString::FromUTF8( aCtx.Request.name() );
3121
3122 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 || !schematic->HasVariant( name ) )
3123 {
3124 ApiResponseStatus e;
3125 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3126 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
3127 return tl::unexpected( e );
3128 }
3129
3131
3132 if( std::optional<wxString> canonical = FindVariantNoCase( schematic, name ) )
3133 name = *canonical;
3134
3135 schematic->SetVariantDescription( name, wxString::FromUTF8( aCtx.Request.description() ) );
3136
3137 if( m_frame )
3138 {
3139 PICKED_ITEMS_LIST* undoCmd = new PICKED_ITEMS_LIST();
3140
3141 undoCmd->PushItem( ITEM_PICKER( frame()->GetScreen(), undoItem, UNDO_REDO::VARIANTS ) );
3142 undoCmd->SetDescription( _( "Edit Variant Description" ) );
3143 frame()->PushCommandToUndoList( undoCmd );
3144 }
3145
3146 return Empty();
3147}
3148
3149
3151{
3152 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3153 return tl::unexpected( documentValidation.error() );
3154
3155 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3156 return tl::unexpected( *busy );
3157
3158 SCHEMATIC* schematic = this->schematic();
3159
3160 if( aCtx.Request.has_name() && !aCtx.Request.name().empty() )
3161 {
3162 if( wxString name = wxString::FromUTF8( aCtx.Request.name() ); !schematic->HasVariant( name ) )
3163 {
3164 ApiResponseStatus e;
3165 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3166 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
3167 return tl::unexpected( e );
3168 }
3169 }
3170
3171 wxString name = aCtx.Request.has_name() ? wxString::FromUTF8( aCtx.Request.name() ) : wxString();
3172
3173 if( std::optional<wxString> canonical = FindVariantNoCase( schematic, name ) )
3174 name = *canonical;
3175
3176 if( m_frame )
3178 else
3179 schematic->SetCurrentVariant( name );
3180
3181 return Empty();
3182}
3183
3184
3187{
3188 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3189 return tl::unexpected( documentValidation.error() );
3190
3191 CurrentVariantResponse response;
3192
3193 if( wxString current = schematic()->GetCurrentVariant(); !current.IsEmpty() )
3194 response.set_name( current.ToUTF8() );
3195
3196 return response;
3197}
3198
3199
3202{
3203 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
3204 {
3205 ApiResponseStatus e;
3206 e.set_status( ApiStatusCode::AS_UNHANDLED );
3207 return tl::unexpected( e );
3208 }
3209
3210 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3211 return tl::unexpected( *busy );
3212
3213 LIB_ID libId = UnpackLibId( aCtx.Request.lib_id() );
3214
3215 if( !libId.IsValid() )
3216 {
3217 ApiResponseStatus e;
3218 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3219 e.set_error_message( "lib_id must specify both a library nickname and an entry name" );
3220 return tl::unexpected( e );
3221 }
3222
3224 LIB_SYMBOL* libSymbol = nullptr;
3225
3226 try
3227 {
3228 libSymbol = adapter->LoadSymbol( libId );
3229 }
3230 catch( const IO_ERROR& ioe )
3231 {
3232 ApiResponseStatus e;
3233 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3234 e.set_error_message( fmt::format( "error loading symbol '{}' from library", libId.Format().wx_str() ) );
3235 return tl::unexpected( e );
3236 }
3237
3238 if( !libSymbol )
3239 {
3240 ApiResponseStatus e;
3241 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3242 e.set_error_message( fmt::format( "symbol '{}' not found", libId.Format().wx_str() ) );
3243 return tl::unexpected( e );
3244 }
3245
3246 SCH_SHEET_LIST hierarchy = schematic()->Hierarchy();
3247 SCH_SHEET_PATH targetPath = m_context->GetCurrentSheet().value_or( *hierarchy.begin() );
3248
3249 if( aCtx.Request.header().document().has_sheet_path() )
3250 {
3251 KIID_PATH kp = UnpackSheetPath( aCtx.Request.header().document().sheet_path() );
3252
3253 if( std::optional<SCH_SHEET_PATH> path = hierarchy.GetSheetPathByKIIDPath( kp ) )
3254 {
3255 targetPath = *path;
3256 }
3257 else
3258 {
3259 ApiResponseStatus e;
3260 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3261 e.set_error_message( fmt::format( "the requested sheet path {} is not valid for this schematic",
3262 kp.AsString().ToStdString() ) );
3263 return tl::unexpected( e );
3264 }
3265 }
3266
3267 SCH_SCREEN* targetScreen = targetPath.LastScreen();
3268
3269 int unit = aCtx.Request.has_unit() ? aCtx.Request.unit().unit() : 1;
3270
3271 if( unit < 1 || ( libSymbol->GetUnitCount() > 0 && unit > libSymbol->GetUnitCount() ) )
3272 {
3273 ApiResponseStatus e;
3274 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3275 e.set_error_message( fmt::format( "unit {} is out of range for symbol '{}' ({} units)", unit,
3276 libId.Format().wx_str(), libSymbol->GetUnitCount() ) );
3277 return tl::unexpected( e );
3278 }
3279
3280 VECTOR2I position = UnpackVector2( aCtx.Request.position(), schIUScale );
3281
3282 std::unique_ptr<SCH_SYMBOL> symbol(
3283 std::make_unique<SCH_SYMBOL>( *libSymbol, libId, &targetPath, unit, 0, position ) );
3284
3285 if( aCtx.Request.has_orientation() )
3286 symbol->SetOrientationProp( FromProtoEnum<SYMBOL_ORIENTATION_PROP>( aCtx.Request.orientation() ) );
3287
3288 if( !aCtx.Request.reference().empty() )
3289 {
3290 wxString base;
3291 wxString error = symbol->BaseRefFromUser( targetPath, wxString::FromUTF8( aCtx.Request.reference() ), base,
3292 schematic() );
3293
3294 if( !error.IsEmpty() )
3295 {
3296 ApiResponseStatus e;
3297 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3298 e.set_error_message( error.ToStdString() );
3299 return tl::unexpected( e );
3300 }
3301
3302 symbol->SetRef( &targetPath, base );
3303 }
3304 else
3305 {
3306 SCH_REFERENCE newReference( symbol.get(), targetPath );
3307 SCH_REFERENCE_LIST existingRefs;
3308 hierarchy.GetSymbols( existingRefs, SYMBOL_FILTER_NON_POWER );
3309
3310 bool annotate = newReference.AlwaysAnnotate();
3311
3312 if( SCH_EDIT_FRAME* frame = this->frame() )
3313 annotate |= frame->eeconfig()->m_AnnotatePanel.automatic;
3314
3315 if( annotate )
3316 {
3317 existingRefs.SortByReferenceOnly();
3318
3319 // Suffix mode numbers every instance of the sheet file together, so they share one base
3320 std::vector<SCH_SHEET_PATH> paths = { targetPath };
3321
3322 if( schematic()->Settings().m_AnnotateReusedSheetSuffixes )
3323 {
3324 SCH_SHEET_LIST screenPaths = hierarchy.FindAllSheetsForScreen( targetPath.LastScreen() );
3325 screenPaths.SortByPageNumbers();
3326 paths.assign( screenPaths.begin(), screenPaths.end() );
3327 }
3328
3329 AnnotateNewSymbol( symbol.get(), paths, existingRefs, schematic()->Settings(), &hierarchy );
3330 }
3331 }
3332
3333 if( SCH_EDIT_FRAME* frame = this->frame() )
3334 {
3335 if( frame->eeconfig()->m_AutoplaceFields.enable )
3336 symbol->AutoplaceFields( nullptr, AUTOPLACE_AUTO );
3337 }
3338
3339 SCH_COMMIT* commit = static_cast<SCH_COMMIT*>( getCurrentCommit( aCtx.ClientName ) );
3340 SCH_SYMBOL* placed = symbol.release();
3341 commit->Add( placed, targetScreen );
3342
3343 if( !m_activeClients.contains( aCtx.ClientName ) )
3344 pushCurrentCommit( aCtx.ClientName, _( "Placed symbol via API" ) );
3345
3346 PlaceFromLibraryResponse response;
3347 response.mutable_header()->CopyFrom( aCtx.Request.header() );
3348
3349 kiapi::schematic::types::SchematicSymbolInstance packed;
3350
3351 if( PackSymbol( &packed, placed, targetPath, schematic() ) )
3352 (void) response.mutable_item()->PackFrom( packed );
3353
3354 return response;
3355}
const char * name
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 std::optional< ApiResponseStatus > applySchematicPlotSettings(const schematic::jobs::SchematicPlotSettings &aSettings, const types::DocumentSpecifier &aDocument, JOB_EXPORT_SCH_PLOT &aJob)
HANDLER_RESULT< types::RunJobResponse > ExecuteSchematicJob(KIWAY *aKiway, JOB &aJob)
bool findSymbolsAndPins(const SCH_SHEET_LIST &aSchematicSheetList, const SCH_SHEET_PATH &aSheetPath, std::unordered_map< wxString, std::vector< SCH_REFERENCE > > &aSyncSymMap, std::unordered_map< wxString, std::unordered_map< wxString, SCH_PIN * > > &aSyncPinMap, const wxString &aVariantName=wxEmptyString, bool aRecursive=false)
std::optional< std::tuple< SCH_SHEET_PATH, SCH_ITEM *, std::vector< SCH_ITEM * > > > findItemsFromSyncSelection(const SCHEMATIC &aSchematic, const kiapi::common::commands::SyncSelection &aSync)
bool sheetContainsOnlyWantedItems(const SCH_SHEET_LIST &aSchematicSheetList, const SCH_SHEET_PATH &aSheetPath, std::unordered_map< wxString, std::vector< SCH_REFERENCE > > &aSyncSymMap, std::unordered_map< wxString, std::unordered_map< wxString, SCH_PIN * > > &aSyncPinMap, std::unordered_map< SCH_SHEET_PATH, bool > &aCache)
bool ValidateSymbolInstance(kiapi::common::commands::ItemStatus *aStatus, const SCH_SYMBOL *aSymbol, const kiapi::schematic::types::SchematicSymbolInstance &aInput, const SCH_SHEET_PATH &aPath, const SCHEMATIC *aSchematic)
Check what ApplySymbolInstance would refuse, so a caller can reject a request before it changes anyth...
bool ValidateSheetInstance(commands::ItemStatus *aStatus, const SCH_SHEET *aSheet, const kiapi::schematic::types::SheetSymbol &aInput)
std::unique_ptr< EDA_ITEM > CreateItemForType(KICAD_T aType, EDA_ITEM *aContainer)
tl::expected< bool, ApiResponseStatus > UnpackSheet(SCH_SHEET *aOutput, const kiapi::schematic::types::SheetSymbol &aInput)
Unpack the every placement data from the input.
bool ApplySymbolInstance(kiapi::common::commands::ItemStatus *aStatus, SCH_SYMBOL *aSymbol, const kiapi::schematic::types::SchematicSymbolInstance &aInput, const SCH_SHEET_PATH &aPath, SCHEMATIC *aSchematic)
Apply placement-specific data to an aSymbol at aPath: reference, unit, and the per-placement attribut...
std::optional< wxString > FindVariantNoCase(const SCHEMATIC *aSchematic, const wxString &aName)
Variant names are stored and compared exactly, but SCHEMATIC::HasVariant matches case-insensitively.
bool PackSheet(kiapi::schematic::types::SheetSymbol *aOutput, const SCH_SHEET *aInput, const SCH_SHEET_PATH &aPath)
bool ApplySheetInstance(commands::ItemStatus *aStatus, SCH_SHEET *aSheet, const kiapi::schematic::types::SheetSymbol &aInput, const SCH_SHEET_PATH &aParentPath, SCHEMATIC *aSchematic)
bool PackSymbol(kiapi::schematic::types::SchematicSymbolInstance *aOutput, const SCH_SYMBOL *aInput, const SCH_SHEET_PATH &aPath, const SCHEMATIC *aSchematic)
tl::expected< SCH_FOCUS_TARGET, ApiResponseStatus > ResolveFocusItems(SCHEMATIC &aSchematic, const std::vector< KIID > &aIds, const std::optional< KIID_PATH > &aSheetPath)
Resolve the items of a FocusOnItems request to the sheet that shows them and their combined bounding ...
bool UnpackSymbol(SCH_SYMBOL *aOutput, const kiapi::schematic::types::SchematicSymbolInstance &aInput)
Unpack the geometry, the library definition, fields, and the default-variant attributes that are shar...
BASE_SCREEN class implementation.
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
HANDLER_RESULT< bool > validateDocument(const DocumentSpecifier &aDocument)
HANDLER_RESULT< types::PageSettings > handleSetPageSettings(const HANDLER_CONTEXT< commands::SetPageSettings > &aCtx)
HANDLER_RESULT< std::optional< KIID > > validateItemHeaderDocument(const kiapi::common::types::ItemHeader &aHeader)
If the header is valid, returns the item container.
HANDLER_RESULT< types::PageSettings > handleGetPageSettings(const HANDLER_CONTEXT< commands::GetPageSettings > &aCtx)
API_HANDLER_EDITOR(EDA_BASE_FRAME *aFrame=nullptr)
static std::vector< KICAD_T > parseRequestedItemTypes(const google::protobuf::RepeatedField< int > &aTypes)
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.
EDA_BASE_FRAME * m_frame
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportDxf(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportDxf > &aCtx)
HANDLER_RESULT< Empty > handleFocusOnItems(const HANDLER_CONTEXT< commands::FocusOnItems > &aCtx)
wxString getDrawingSheetFileName() override
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportPng(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportPng > &aCtx)
HANDLER_RESULT< kiapi::schematic::tasks::ErcTaskResult > handleGetErcTaskResult(const HANDLER_CONTEXT< kiapi::schematic::tasks::GetErcTaskResult > &aCtx)
HANDLER_RESULT< Empty > handleSetCurrentVariant(const HANDLER_CONTEXT< commands::SetCurrentVariant > &aCtx)
HANDLER_RESULT< kiapi::schematic::commands::SchematicHierarchyResponse > handleGetSchematicHierarchy(const HANDLER_CONTEXT< kiapi::schematic::commands::GetSchematicHierarchy > &aCtx)
HANDLER_RESULT< commands::VariantsResponse > handleGetVariants(const HANDLER_CONTEXT< commands::GetVariants > &aCtx)
std::unique_ptr< COMMIT > createCommit() override
Override this to create an appropriate COMMIT subclass for the frame in question.
SCHEMATIC * schematic() const
HANDLER_RESULT< commands::SelectionResponse > handleGetSelection(const HANDLER_CONTEXT< commands::GetSelection > &aCtx)
HANDLER_RESULT< Empty > handleCopyVariant(const HANDLER_CONTEXT< commands::CopyVariant > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportPdf(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportPdf > &aCtx)
SCH_SCREEN * resolveScreenFromDocument(const DocumentSpecifier &aDocument) const
Returns the sheet path's screen when one is given and it is found, or null.
HANDLER_RESULT< commands::CurrentVariantResponse > handleGetCurrentVariant(const HANDLER_CONTEXT< commands::GetCurrentVariant > &aCtx)
static std::set< KICAD_T > s_allowedTypes
HANDLER_RESULT< commands::GetItemsResponse > handleGetItemsById(const HANDLER_CONTEXT< commands::GetItemsById > &aCtx)
HANDLER_RESULT< google::protobuf::Empty > handleSaveDocument(const HANDLER_CONTEXT< commands::SaveDocument > &aCtx)
std::optional< PAGE_INFO > getPageSettings(const DocumentSpecifier &aDocument) override
HANDLER_RESULT< kiapi::schematic::commands::SchematicNetlistResponse > handleGetSchematicNetlist(const HANDLER_CONTEXT< kiapi::schematic::commands::GetSchematicNetlist > &aCtx)
std::optional< SCH_ITEM * > getItemById(const KIID &aId, SCH_SHEET_PATH *aPathOut=nullptr) const
std::shared_ptr< SCH_CONTEXT > m_context
std::optional< EDA_ITEM * > getItemFromDocument(const DocumentSpecifier &aDocument, const KIID &aId) override
TOOL_MANAGER * toolManager() const
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportSvg(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportSvg > &aCtx)
HANDLER_RESULT< Empty > handleDeleteVariant(const HANDLER_CONTEXT< commands::DeleteVariant > &aCtx)
HANDLER_RESULT< Empty > handleClearSelection(const HANDLER_CONTEXT< commands::ClearSelection > &aCtx)
HANDLER_RESULT< commands::HighlightNetsResponse > handleHighlightNets(const HANDLER_CONTEXT< commands::HighlightNets > &aCtx)
std::optional< ApiResponseStatus > checkForHeadless(const std::string &aCommandName) const
bool setPageSettings(const DocumentSpecifier &aDocument, const PAGE_INFO &aPageInfo) override
HANDLER_RESULT< commands::SavedSelectionResponse > handleSaveSelectionToString(const HANDLER_CONTEXT< commands::SaveSelectionToString > &aCtx)
HANDLER_RESULT< commands::CrossProbeAnnounceResponse > handleCrossProbeAnnounce(const HANDLER_CONTEXT< commands::CrossProbeAnnounce > &aCtx)
HANDLER_RESULT< std::unique_ptr< EDA_ITEM > > createItemForType(KICAD_T aType, EDA_ITEM *aContainer)
HANDLER_RESULT< kiapi::common::commands::PlaceFromLibraryResponse > handlePlaceSymbolFromLibrary(const HANDLER_CONTEXT< kiapi::schematic::commands::PlaceSymbolFromLibrary > &aCtx)
HANDLER_RESULT< commands::GetDocumentModifiedStateResponse > handleGetDocumentModifiedState(const HANDLER_CONTEXT< commands::GetDocumentModifiedState > &aCtx) override
HANDLER_RESULT< Empty > handleRenameVariant(const HANDLER_CONTEXT< commands::RenameVariant > &aCtx)
void filterValidSchTypes(std::set< KICAD_T > &aTypeList)
std::optional< TITLE_BLOCK * > getTitleBlock(const DocumentSpecifier &aDocument) override
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportBOM(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportBOM > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportPs(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportPs > &aCtx)
HANDLER_RESULT< commands::SavedDocumentResponse > handleSaveDocumentToString(const HANDLER_CONTEXT< commands::SaveDocumentToString > &aCtx)
PROJECT & project() const
void onModified() override
API_HANDLER_SCH(SCH_EDIT_FRAME *aFrame)
bool packSchItem(google::protobuf::Any &aOut, SCH_ITEM *aItem, const SCH_SHEET_PATH &aPath)
Serializes a schematic item into aOut, using path-aware packing for symbols and sheets.
HANDLER_RESULT< Empty > handleAddVariant(const HANDLER_CONTEXT< commands::AddVariant > &aCtx)
kiapi::common::types::DocumentType thisDocumentType() const override
Override this to specify which document type this editor handles.
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< commands::GetOpenDocumentsResponse > handleGetOpenDocuments(const HANDLER_CONTEXT< commands::GetOpenDocuments > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunSchematicJobExportNetlist(const HANDLER_CONTEXT< kiapi::schematic::jobs::RunSchematicJobExportNetlist > &aCtx)
HANDLER_RESULT< google::protobuf::Empty > handleRevertDocument(const HANDLER_CONTEXT< commands::RevertDocument > &aCtx)
HANDLER_RESULT< commands::SelectionResponse > handleAddToSelection(const HANDLER_CONTEXT< commands::AddToSelection > &aCtx)
HANDLER_RESULT< commands::SelectionResponse > handleRemoveFromSelection(const HANDLER_CONTEXT< commands::RemoveFromSelection > &aCtx)
void onNetSettingsChanged() override
Called on all registered handlers after project net settings (netclasses or netclass assignments) hav...
HANDLER_RESULT< kiapi::common::tasks::StartTaskResponse > handleStartErcTask(const HANDLER_CONTEXT< kiapi::schematic::tasks::StartErcTask > &aCtx)
HANDLER_RESULT< commands::ExpandTextVariablesResponse > handleExpandTextVariables(const HANDLER_CONTEXT< commands::ExpandTextVariables > &aCtx)
void deleteItemsInternal(std::map< KIID, ItemDeletionStatus > &aItemsToDelete, const std::string &aClientName) override
void packSheetInstance(kiapi::schematic::types::SheetInstance *aInstance, SCH_SHEET_PATH &aPath, SCH_SHEET *aSheet)
tl::expected< bool, ApiResponseStatus > validateDocumentInternal(const DocumentSpecifier &aDocument) const override
HANDLER_RESULT< commands::SyncSelectionResponse > handleSyncSelection(const HANDLER_CONTEXT< commands::SyncSelection > &aCtx)
SCH_EDIT_FRAME * frame() const
HANDLER_RESULT< google::protobuf::Empty > handleSaveCopyOfDocument(const HANDLER_CONTEXT< commands::SaveCopyOfDocument > &aCtx)
SCH_CONTEXT * context() const
void setDrawingSheetFileName(const wxString &aFileName) override
HANDLER_RESULT< Empty > handleSetVariantDescription(const HANDLER_CONTEXT< commands::SetVariantDescription > &aCtx)
HANDLER_RESULT< commands::GetItemsResponse > handleGetItems(const HANDLER_CONTEXT< commands::GetItems > &aCtx)
HANDLER_RESULT< google::protobuf::Empty > handleSaveDocumentAs(const HANDLER_CONTEXT< commands::SaveDocumentAs > &aCtx)
KICAD_API_SERVER * apiServer() const
void registerHandler(HANDLER_RESULT< ResponseType >(HandlerType::*aHandler)(const HANDLER_CONTEXT< RequestType > &), bool aAllowedDuringTask=false)
Registers an API command handler for the given message types.
CROSS_PROBING_SETTINGS m_CrossProbing
static wxString m_DrawingSheetFileName
the name of the drawing sheet file, or empty to use the default drawing sheet
Definition base_screen.h:81
void SetContentModified(bool aModified=true)
Definition base_screen.h:55
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition commit.h:68
COMMIT & Remove(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Remove a new item from the model.
Definition commit.h:86
int Checkpoint()
Definition commit.h:134
bool Empty() const
Definition commit.h:145
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
Handles action that are shared between different applications.
Calculate the connectivity of a schematic and generate netlists.
const NET_MAP & GetNetMap() const
A subgraph is a set of items that are electrically connected on a single sheet.
static PRIORITY GetDriverPriority(SCH_ITEM *aDriver)
Return the priority (higher is more important) of a candidate driver.
const SCH_CONNECTION * GetDriverConnection() const
static void RegisterPeer(FRAME_T aFrameType, const std::string &aSocketPath)
virtual void PushCommandToUndoList(PICKED_ITEMS_LIST *aItem)
Add a command to undo in the undo list.
virtual PICKED_ITEMS_LIST * PopCommandFromUndoList()
Return the last command to undo and remove it from list, nothing is deleted.
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
virtual void FinalizeGroupDeserialization()
Definition eda_group.h:66
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
virtual wxString GetFriendlyName() const
Definition eda_item.cpp:575
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
bool IsEmpty() const
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
std::vector< wxString > m_variantNames
wxString m_stringDelimiter
wxString m_fieldDelimiter
bool m_includeByteOrderMark
wxString m_filename
wxString m_filterString
std::vector< wxString > m_fieldsOrdered
wxString m_refRangeDelimiter
std::vector< wxString > m_fieldsLabels
wxString m_refDelimiter
std::vector< wxString > m_fieldsGroupBy
wxString m_bomFmtPresetName
wxString m_sortField
wxString m_bomPresetName
BOM_FILTER_SCOPE m_filterScope
std::vector< wxString > m_variantNames
JOB_PAGE_SIZE m_pageSizeSelect
std::vector< wxString > m_plotPages
An simple container class that lets us dispatch output jobs to kifaces.
Definition job.h:184
void SetConfiguredOutputPath(const wxString &aPath)
Sets the configured output path for the job, this path is always saved to file.
Definition job.cpp:181
const std::vector< JOB_OUTPUT > & GetOutputs()
Definition job.h:215
const std::string & GetType() const
Definition job.h:195
wxString AsString() const
Definition kiid.cpp:423
Definition kiid.h:46
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
int ProcessJob(KIWAY::FACE_T aFace, JOB *aJob, REPORTER *aReporter=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr)
Definition kiway.cpp:765
@ FACE_SCH
eeschema DSO
Definition kiway.h:355
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
UTF8 Format() const
Definition lib_id.cpp:132
Define a library symbol object.
Definition lib_symbol.h:114
int GetUnitCount() const override
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
A holder to handle information on schematic or board items.
void PushItem(const ITEM_PICKER &aItem)
Push aItem to the top of the list.
void SetDescription(const wxString &aDescription)
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:289
Holds all the data relating to one schematic.
Definition schematic.h:155
SCHEMATIC_SETTINGS & Settings() const
SCH_SCREEN * GetCurrentScreen() const
Definition schematic.h:409
SCH_ITEM * ResolveItem(const KIID &aID, SCH_SHEET_PATH *aPathOut=nullptr, bool aAllowNullptrReturn=false) const
Definition schematic.h:276
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
SCH_SHEET * GetTopLevelSheet(int aIndex=0) const
wxString GetCurrentVariant() const
Return the current variant being edited.
CONNECTION_GRAPH * ConnectionGraph() const
Definition schematic.h:414
SCH_SCREEN * RootScreen() const
Helper to retrieve the screen of the root sheet.
bool ResolveTextVar(const SCH_SHEET_PATH *aSheetPath, wxString *token, int aDepth) const
void RebuildConnectivity(std::function< void(SCH_ITEM *)> *aChangedItemHandler=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr, KIGFX::SCH_VIEW *aSchView=nullptr)
std::vector< SCH_SHEET * > GetTopLevelSheets() const
Get the list of top-level sheets.
SCH_SHEET_PATH & CurrentSheet() const
Definition schematic.h:399
void RefreshHierarchy()
static TOOL_ACTION changeSheet
SCH_DRAW_PANEL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
EESCHEMA_SETTINGS * eeconfig() const
Commit for the schematic and symbol editors.
Definition sch_commit.h:54
void RevertToCheckpoint(int aCheckpoint) override
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
bool IsBus() const
Schematic editor (Eeschema) main window.
void OnModify() override
Must be called after a schematic change in order to set the "modify" flag and update other data struc...
void SyncVariantUI()
Refill the toolbar variant control and any open symbol fields table from the schematic.
void RefreshConnectivity(bool aForce=false, const SCH_CONNECTIVITY::CHANGE_SET *aChanges=nullptr)
void SetCurrentVariant(const wxString &aVariantName)
bool RecalculateConnections(SCH_COMMIT *aCommit, SCH_CLEANUP_FLAGS aCleanupFlags, PROGRESS_REPORTER *aProgressReporter=nullptr, bool aCleanupDone=false)
Generate the connection data for the entire schematic hierarchy.
SCH_SHEET_PATH & GetCurrentSheet() const
SCHEMATIC & Schematic() const
void LoadDrawingSheet()
Load the drawing sheet file.
void SetSyncingSelection(bool aSet)
void StartCrossProbeFlash(const std::vector< SCH_ITEM * > &aItems)
void HandleRemoteNetHighlight(const wxString &aNetName)
A set of SCH_ITEMs (i.e., without duplicates).
Definition sch_group.h:48
A SCH_IO derivation for loading schematic files using the new s-expression file format.
void FormatSchematicToFormatter(OUTPUTFORMATTER *aOut, SCH_SHEET *aSheet, SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties=nullptr)
Serialize a schematic sheet to an OUTPUTFORMATTER without file I/O or Prettify.
void Format(SCH_SHEET *aSheet)
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
virtual bool IsConnectable() const
Definition sch_item.h:550
void SetConnectivityDirty(bool aDirty=true)
Set the dirty flag.
Definition sch_item.cpp:314
void SwapItemData(SCH_ITEM *aImage)
Swap data between aItem and aImage.
Definition sch_item.cpp:840
Container to create a flattened list of symbols because in a complex hierarchy, a symbol can be used ...
void SortByReferenceOnly()
Sort the list of references by reference.
A helper to define a symbol's reference designator in a schematic.
wxString GetComposedRef() const
Return the reference as shown on this sheet path, with its sheet suffix.
bool AlwaysAnnotate() const
Verify the reference should always be automatically annotated.
void Split()
Attempt to split the reference designator into a name (U) and number (1).
SCH_SYMBOL * GetSymbol() const
bool IsSplitNeeded() const
Determine if this reference needs to be split or if it likely already has been.
wxString GetRefNumber() const
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
const wxString & GetFileName() const
Definition sch_screen.h:157
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
TITLE_BLOCK & GetTitleBlock()
Definition sch_screen.h:168
void GetSheets(std::vector< SCH_ITEM * > *aItems) const
Similar to Items().OfType( SCH_SHEET_T ), but return the sheets in a deterministic order (L-R,...
SCH_SELECTION & GetSelection()
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
std::optional< SCH_SHEET_PATH > GetSheetPathByKIIDPath(const KIID_PATH &aPath, bool aIncludeLastSheet=true) const
Finds a SCH_SHEET_PATH that matches the provided KIID_PATH.
SCH_ITEM * ResolveItem(const KIID &aID, SCH_SHEET_PATH *aPathOut=nullptr, bool aAllowNullptrReturn=false) const
Fetch a SCH_ITEM by ID.
void SortByPageNumbers(bool aUpdateVirtualPageNums=true)
Sort the list of sheets by page number.
SCH_SHEET_LIST FindAllSheetsForScreen(const SCH_SCREEN *aScreen) const
Return a SCH_SHEET_LIST with a copy of all the SCH_SHEET_PATH using a particular screen.
wxString GetNextPageNumber() const
void GetSymbols(SCH_REFERENCE_LIST &aReferences, SYMBOL_FILTER aSymbolFilter, bool aForceIncludeOrphanSymbols=false) const
Add a SCH_REFERENCE object to aReferences for each symbol in the list of sheets.
bool TestForRecursion(const SCH_SHEET_LIST &aSrcSheetHierarchy, const wxString &aDestFileName)
Test every SCH_SHEET_PATH in this SCH_SHEET_LIST to verify if adding the sheets stored in aSrcSheetHi...
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
int ComparePageNum(const SCH_SHEET_PATH &aSheetPathToTest) const
Compare sheets by their page number.
void GetSymbols(SCH_REFERENCE_LIST &aReferences, SYMBOL_FILTER aSymbolFilter, bool aForceIncludeOrphanSymbols=false) const
Adds SCH_REFERENCE object to aReferences for each symbol in the sheet.
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
SCH_ITEM * ResolveItem(const KIID &aID) const
Fetch a SCH_ITEM by ID.
SCH_SCREEN * LastScreen()
wxString GetPageNumber() const
bool IsContainedWithin(const SCH_SHEET_PATH &aSheetPathToTest) const
Check if this path is contained inside aSheetPathToTest.
void push_back(SCH_SHEET *aSheet)
Forwarded method from std::vector.
void pop_back()
Forwarded method from std::vector.
Define a sheet pin (label) used in sheets to create hierarchical schematics.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
void AddInstance(const SCH_SHEET_INSTANCE &aInstance)
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
wxString GetShownName(RESOLUTION_CONTEXT aContext) const
Definition sch_sheet.h:146
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
std::vector< SCH_SHEET_PIN * > & GetPins()
Definition sch_sheet.h:285
Schematic symbol object.
Definition sch_symbol.h:76
void SetLibId(const LIB_ID &aName)
std::vector< std::unique_ptr< SCH_PIN > > & GetRawPins()
Definition sch_symbol.h:715
bool UseLibIdLookup() const
Definition sch_symbol.h:183
wxString GetSchSymbolLibraryName() const
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
void AddHierarchicalReference(const KIID_PATH &aPath, const wxString &aRef, int aUnit)
Add a full hierarchical reference to this symbol.
const LIB_ID & GetLibId() const override
Definition sch_symbol.h:166
void SetSchSymbolLibraryName(const wxString &aName)
The name of the symbol in the schematic library symbol list.
Definition sch_symbol.h:181
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
void SetLibSymbol(LIB_SYMBOL *aLibSymbol)
Set this schematic symbol library symbol reference to aLibSymbol.
int AddItemsToSel(const TOOL_EVENT &aEvent)
int RemoveItemsFromSel(const TOOL_EVENT &aEvent)
virtual void Serialize(google::protobuf::Any &aContainer) const
Serializes this object to the given Any message.
Implement an OUTPUTFORMATTER to a memory buffer.
Definition richio.h:430
const std::string & GetString()
Definition richio.h:453
An interface to the global shared library manager that is schematic-specific and linked to one projec...
LIB_SYMBOL * LoadSymbol(const wxString &aNickname, const wxString &aName)
Load a LIB_SYMBOL having aName from the library given by aNickname.
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
T * GetTool()
Return the tool of given type or nullptr if there is no such tool registered.
wxString wx_str() const
Definition utf8.cpp:41
A wrapper for reporting to a wxString object.
Definition reporter.h:242
A type-safe container of any type.
Definition ki_any.h:92
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
Definition common.cpp:777
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
Definition common.cpp:60
@ INTERNAL
Definition common.h:96
#define _(s)
@ NO_RECURSE
Definition eda_item.h:52
FRAME_T
The set of EDA_BASE_FRAME derivatives, typically stored in EDA_BASE_FRAME::m_Ident.
Definition frame_type.h:29
bool m_ConnectivityEngine
Use the schematic connectivity engine instead of CONNECTION_GRAPH.
static const std::string KiCadSchematicFileExtension
const wxChar *const traceCrossProbeFlash
Flag to enable debug output for cross-probe flash operations.
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
void Prettify(std::string &aSource, FORMAT_MODE aMode)
Pretty-prints s-expression text according to KiCad format rules.
KICOMMON_API void PackProject(types::ProjectSpecifier &aOutput, const PROJECT &aInput)
KICOMMON_API int UnpackDistance(const types::Distance &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API KIID_PATH UnpackSheetPath(const types::SheetPath &aInput)
KICOMMON_API std::optional< KICAD_T > TypeNameFromAny(const google::protobuf::Any &aMessage)
Definition api_utils.cpp:50
KICOMMON_API VECTOR2I UnpackVector2(const types::Vector2 &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API void PackSheetPath(types::SheetPath &aOutput, const KIID_PATH &aInput)
KICOMMON_API LIB_ID UnpackLibId(const types::LibraryIdentifier &aId)
const KICOMMON_API std::string KiwayClientName
const KICOMMON_API std::string StandaloneCrossProbeClientName
STL namespace.
static int plotJob(JOB_EXPORT_PCB_PLOT *aJob, PCB_PLOTTER &aPlotter, const LSEQ &aLayersToPlot, const wxString &aOutPath, bool aSingleOutput, bool aUseVarOverrides, bool aForceAllLayersToOnePage=false)
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
constexpr int MIN_PNG_DPI
Definition plotter_png.h:29
constexpr int MAX_PNG_DPI
Definition plotter_png.h:30
std::shared_ptr< SCH_CONTEXT > CreateSchFrameContext(SCH_EDIT_FRAME *aFrame)
Class to handle a set of SCH_ITEMs.
@ AUTOPLACE_AUTO
Definition sch_item.h:75
std::vector< EDA_ITEM * > EDA_ITEMS
void AnnotateNewSymbol(SCH_SYMBOL *aSymbol, const std::vector< SCH_SHEET_PATH > &aPaths, SCH_REFERENCE_LIST &aExistingRefs, const SCHEMATIC_SETTINGS &aSettings, SCH_SHEET_LIST *aHierarchy)
Annotate a newly placed symbol on each of aPaths in turn, avoiding aExistingRefs and adding the resul...
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
@ SYMBOL_FILTER_NON_POWER
@ LOCAL_CLEANUP
Definition schematic.h:100
wxString GetDefaultVariantName()
std::vector< wxString > ExpandStackedPinNotation(const wxString &aPinName, bool *aValid)
Expand stacked pin notation like [1,2,3], [1-4], [A1-A4], or [AA1-AA3,AB4,CD12-CD14] into individual ...
Cross-probing behavior.
bool on_selection
Synchronize the selection for multiple items too.
bool auto_highlight
Automatically turn on highlight mode in the target frame.
std::string ClientName
Definition api_handler.h:53
RequestMessageType Request
Definition api_handler.h:54
A simple container for sheet instance information.
A simple container for schematic symbol instance information.
#define ALL_UNITS
Definition symbol.h:150
std::string path
IbisParser parser & reporter
KIBIS_PIN * pin
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
Definition typeinfo.h:70
@ SCH_GROUP_T
Definition typeinfo.h:169
@ SCH_TABLE_T
Definition typeinfo.h:161
@ SCH_LINE_T
Definition typeinfo.h:159
@ SCH_NO_CONNECT_T
Definition typeinfo.h:156
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_DIRECTIVE_LABEL_T
Definition typeinfo.h:167
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_SHAPE_T
Definition typeinfo.h:145
@ SCH_RULE_AREA_T
Definition typeinfo.h:166
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCH_BUS_BUS_ENTRY_T
Definition typeinfo.h:158
@ SCH_SHEET_PIN_T
Definition typeinfo.h:170
@ SCH_TEXT_T
Definition typeinfo.h:147
@ SCH_BUS_WIRE_ENTRY_T
Definition typeinfo.h:157
@ SCH_BITMAP_T
Definition typeinfo.h:160
@ SCH_TEXTBOX_T
Definition typeinfo.h:148
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_JUNCTION_T
Definition typeinfo.h:155
@ SCH_PIN_T
Definition typeinfo.h:149
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:35