KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_handler_pcb.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) 2023 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 <magic_enum.hpp>
22#include <memory>
23#include <pgm_base.h>
24#include <properties/property.h>
25#include <ranges>
26
27#include <common.h>
28#include <fmt.h>
29#include <api/api_handler_pcb.h>
30#include <api/api_pcb_utils.h>
31#include <api/api_enums.h>
32#include <api/api_server.h>
33#include <api/api_utils.h>
34#include <api/common/commands/library_commands.pb.h>
36#include <wx/log.h>
37#include <base_screen.h>
38#include <board_commit.h>
41#include <core/kicad_algo.h>
42#include <footprint.h>
44#include <kicad_clipboard.h>
45#include <netinfo.h>
46#include <pad.h>
47#include <pcb_draw_panel_gal.h>
48#include <pcb_edit_frame.h>
49#include <pcb_group.h>
50#include <pcb_reference_image.h>
51#include <pcb_shape.h>
52#include <pcb_text.h>
53#include <pcb_textbox.h>
54#include <pcb_track.h>
55#include <pcbnew_id.h>
56#include <pcb_marker.h>
57#include <pcb_3d_body.h>
58#include <pcb_point.h>
59#include <kiway.h>
60#include <drc/drc_item.h>
74#include <project_pcb.h>
80#include <pcb_plot_params.h>
82#include <jobs/job_pcb_render.h>
83#include <layer_ids.h>
86#include <project.h>
88#include <tool/actions.h>
89#include <string_utils.h>
90#include <tool/tool_manager.h>
91#include <tools/pcb_actions.h>
95#include <zone.h>
96#include <zone_filler.h>
97
98#include <api/common/types/base_types.pb.h>
99
101#include <reporter.h>
102#include <api/board/board_rules.pb.h>
104#include <google/protobuf/util/json_util.h>
106#include <drc/drc_rule_parser.h>
110#include <trace_helpers.h>
111#include <wx/ffile.h>
112
113using namespace kiapi::common::commands;
114using namespace kiapi::board::commands;
115using types::CommandStatus;
116using types::DocumentType;
117using types::ItemRequestStatus;
118
119
124
125
126API_HANDLER_PCB::API_HANDLER_PCB( std::shared_ptr<PCB_CONTEXT> aContext, PCB_EDIT_FRAME* aFrame ) :
127 API_HANDLER_BOARD( std::move( aContext ), aFrame )
128{
135
137
150
163 registerHandler<kiapi::board::tasks::StartDrcTask,
164 kiapi::common::tasks::StartTaskResponse>(
168
177
187
222
225
229
232}
233
234
236{
237 return static_cast<PCB_EDIT_FRAME*>( m_frame );
238}
239
240
243{
244 if( aCtx.Request.type() != DocumentType::DOCTYPE_PCB )
245 {
246 ApiResponseStatus e;
247 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
248 e.set_status( ApiStatusCode::AS_UNHANDLED );
249 return tl::unexpected( e );
250 }
251
252 GetOpenDocumentsResponse response;
253 common::types::DocumentSpecifier doc;
254
255 wxFileName fn( pcbContext()->GetCurrentFileName() );
256
257 doc.set_type( DocumentType::DOCTYPE_PCB );
258 doc.set_board_filename( fn.GetFullName() );
259
260 doc.mutable_project()->set_name( project().GetProjectName().ToStdString() );
261 doc.mutable_project()->set_path( project().GetProjectDirectory().ToStdString() );
262
263 response.mutable_documents()->Add( std::move( doc ) );
264 return response;
265}
266
267
270{
271 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
272 return tl::unexpected( documentValidation.error() );
273
274 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
275 return tl::unexpected( *busy );
276
277 if( board()->GetFileName().IsEmpty() )
278 {
279 ApiResponseStatus e;
280 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
281 e.set_error_message( "the board is untitled; use SaveDocumentAs to save it to a new file" );
282 return tl::unexpected( e );
283 }
284
285 if( !pcbContext()->SaveBoard() )
286 {
287 ApiResponseStatus e;
288 e.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
289 e.set_error_message( "board could not be saved" );
290 return tl::unexpected( e );
291 }
292
293 return Empty();
294}
295
296
298{
299 if( Pgm().IsGUI() )
300 {
301 ApiResponseStatus e;
302 e.set_status( ApiStatusCode::AS_UNIMPLEMENTED );
303 e.set_error_message( "SaveDocumentAs is not available in GUI mode" );
304 return tl::unexpected( e );
305 }
306
307 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
308 return tl::unexpected( documentValidation.error() );
309
310 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
311 return tl::unexpected( *busy );
312
313 wxString pathStr = wxString::FromUTF8( aCtx.Request.path() );
314
315 if( pathStr.IsEmpty() )
316 {
317 ApiResponseStatus e;
318 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
319 e.set_error_message( "path is required" );
320 return tl::unexpected( e );
321 }
322
323 wxFileName oldBoardFile( pcbContext()->GetCurrentFileName() );
324
325 if( !pcbContext()->SaveBoardAs( pathStr ) )
326 {
327 ApiResponseStatus e;
328 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
329 e.set_error_message( fmt::format( "failed to save board to '{}'", pathStr.ToStdString() ) );
330 return tl::unexpected( e );
331 }
332
333 if( KICAD_API_SERVER* server = apiServer() )
334 {
335 wxFileName newBoardFile( pathStr );
336 newBoardFile.SetExt( FILEEXT::KiCadPcbFileExtension );
337
338 server->NotifyDocumentRenamed( thisDocumentType(), oldBoardFile.GetFullPath(), newBoardFile.GetFullPath() );
339 }
340
341 return Empty();
342}
343
344
347{
348 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
349 return tl::unexpected( documentValidation.error() );
350
351 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
352 return tl::unexpected( *busy );
353
354 wxFileName boardPath( project().AbsolutePath( wxString::FromUTF8( aCtx.Request.path() ) ) );
355
356 if( !boardPath.IsOk() || !boardPath.IsDirWritable() )
357 {
358 ApiResponseStatus e;
359 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
360 e.set_error_message( fmt::format( "save path '{}' could not be opened",
361 boardPath.GetFullPath().ToStdString() ) );
362 return tl::unexpected( e );
363 }
364
365 if( boardPath.FileExists()
366 && ( !boardPath.IsFileWritable() || !aCtx.Request.options().overwrite() ) )
367 {
368 ApiResponseStatus e;
369 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
370 e.set_error_message( fmt::format( "save path '{}' exists and cannot be overwritten",
371 boardPath.GetFullPath().ToStdString() ) );
372 return tl::unexpected( e );
373 }
374
375 if( boardPath.GetExt() != FILEEXT::KiCadPcbFileExtension )
376 {
377 ApiResponseStatus e;
378 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
379 e.set_error_message( fmt::format( "save path '{}' must have a kicad_pcb extension",
380 boardPath.GetFullPath().ToStdString() ) );
381 return tl::unexpected( e );
382 }
383
384 BOARD* board = this->board();
385
386 if( board->GetFileName().Matches( boardPath.GetFullPath() ) )
387 {
388 if( !pcbContext()->SaveBoard() )
389 {
390 ApiResponseStatus e;
391 e.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
392 e.set_error_message( "board could not be saved" );
393 return tl::unexpected( e );
394 }
395
396 return Empty();
397 }
398
399 bool includeProject = true;
400
401 if( aCtx.Request.has_options() )
402 includeProject = aCtx.Request.options().include_project();
403
404 if( !pcbContext()->SavePcbCopy( boardPath.GetFullPath(), includeProject, /* aHeadless = */ true ) )
405 {
406 ApiResponseStatus e;
407 e.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
408 e.set_error_message( fmt::format( "board could not be saved to '{}'",
409 boardPath.GetFullPath().ToStdString() ) );
410 return tl::unexpected( e );
411 }
412
413 return Empty();
414}
415
416
419{
420 // Validate first so a request meant for another editor's document is not captured here
421 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
422 return tl::unexpected( documentValidation.error() );
423
424 // Reloading frees every item, so refuse while any client transaction is open; the staged
425 // commit would otherwise dangle
426 if( !m_commits.empty() )
427 {
428 ApiResponseStatus e;
429 e.set_status( ApiStatusCode::AS_BUSY );
430 e.set_error_message( "cannot revert while a commit is open" );
431 return tl::unexpected( e );
432 }
433
434 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
435 return tl::unexpected( *busy );
436
437 if( !pcbContext()->RevertToSaved() )
438 {
439 ApiResponseStatus e;
440 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
441 e.set_error_message( "could not revert: there is no saved file on disk to revert to" );
442 return tl::unexpected( e );
443 }
444
445 return Empty();
446}
447
448
449tl::expected<bool, ApiResponseStatus> API_HANDLER_PCB::validateDocumentInternal( const DocumentSpecifier& aDocument ) const
450{
451 if( aDocument.type() != DocumentType::DOCTYPE_PCB )
452 {
453 ApiResponseStatus e;
454 e.set_status( ApiStatusCode::AS_UNHANDLED );
455 return tl::unexpected( e );
456 }
457
458 wxFileName fn( pcbContext()->GetCurrentFileName() );
459
460 if( aDocument.board_filename().compare( fn.GetFullName() ) != 0 )
461 {
462 ApiResponseStatus e;
463 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
464 e.set_error_message( fmt::format( "the requested document {} is not open",
465 aDocument.board_filename() ) );
466 return tl::unexpected( e );
467 }
468
469 return true;
470}
471
472
473// Board types that are directly retrievable by GetItems
498
499
501{
502 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
503 {
504 ApiResponseStatus e;
505 // No message needed for AS_UNHANDLED; this is an internal flag for the API server
506 e.set_status( ApiStatusCode::AS_UNHANDLED );
507 return tl::unexpected( e );
508 }
509
510 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
511 return tl::unexpected( *busy );
512
513 GetItemsResponse response;
514
515 BOARD* board = this->board();
516 std::vector<BOARD_ITEM*> items;
517 std::set<KICAD_T> typesRequested, typesHandled;
518
519 std::vector<KICAD_T> requestedTypes = parseRequestedItemTypes( aCtx.Request.types() );
520
521 if( aCtx.Request.types().empty() )
522 requestedTypes.assign( s_allowedBoardTypes.begin(), s_allowedBoardTypes.end() );
523
524 for( KICAD_T type : requestedTypes )
525 {
526 typesRequested.emplace( type );
527
528 if( typesHandled.count( type ) )
529 continue;
530
531 switch( type )
532 {
533 case PCB_TRACE_T:
534 case PCB_ARC_T:
535 case PCB_VIA_T:
536 std::ranges::copy( board->Tracks(), std::back_inserter( items ) );
537 typesHandled.insert( { PCB_TRACE_T, PCB_ARC_T, PCB_VIA_T } );
538 break;
539
540 case PCB_PAD_T:
541 for( FOOTPRINT* fp : board->Footprints() )
542 std::ranges::copy( fp->Pads(), std::back_inserter( items ) );
543
544 typesHandled.insert( PCB_PAD_T );
545 break;
546
547 case PCB_FOOTPRINT_T:
548 std::ranges::copy( board->Footprints(), std::back_inserter( items ) );
549 typesHandled.insert( PCB_FOOTPRINT_T );
550 break;
551
552 case PCB_SHAPE_T:
553 case PCB_TABLE_T:
556 case PCB_DRILL_MAP_T:
557 case PCB_TEXT_T:
558 case PCB_TEXTBOX_T:
559 case PCB_BARCODE_T:
561 case PCB_GRID_ITEM_T:
562 case PCB_DIMENSION_T:
563 for( BOARD_ITEM* item : board->Drawings() )
564 {
565 if( item->Type() == type || BaseType( item->Type() ) == type )
566 items.emplace_back( item );
567 }
568
569 typesHandled.insert( type );
570 break;
571
572 case PCB_ZONE_T:
573 std::ranges::copy( board->Zones(), std::back_inserter( items ) );
574 typesHandled.insert( PCB_ZONE_T );
575 break;
576
577 case PCB_GROUP_T:
578 std::ranges::copy( board->Groups(), std::back_inserter( items ) );
579 typesHandled.insert( PCB_GROUP_T );
580 break;
581
582 case PCB_POINT_T:
583 std::ranges::copy( board->Points(), std::back_inserter( items ) );
584 typesHandled.insert( PCB_POINT_T );
585 break;
586
587 case PCB_3D_BODY_T:
588 // Not supported on a board context yet
589 break;
590
591 case PCB_GENERATOR_T:
592 std::ranges::copy( board->Generators(), std::back_inserter( items ) );
593 typesHandled.insert( PCB_GENERATOR_T );
594 break;
595
596 case PCB_CONSTRAINT_T:
597 std::ranges::copy( board->Constraints(), std::back_inserter( items ) );
598 typesHandled.insert( PCB_CONSTRAINT_T );
599 break;
600
601 default:
602 break;
603 }
604 }
605
606 if( typesHandled.empty() )
607 {
608 ApiResponseStatus e;
609 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
610 e.set_error_message( "none of the requested types are valid for a Board object" );
611 return tl::unexpected( e );
612 }
613
614 for( const BOARD_ITEM* item : items )
615 {
616 if( !typesRequested.count( item->Type() ) && !typesRequested.count( BaseType( item->Type() ) ) )
617 continue;
618
619 google::protobuf::Any itemBuf;
620 item->Serialize( itemBuf );
621 response.mutable_items()->Add( std::move( itemBuf ) );
622 }
623
624 response.set_status( ItemRequestStatus::IRS_OK );
625 return response;
626}
627
628
631{
632 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
633 return tl::unexpected( documentValidation.error() );
634
635 if( aCtx.Request.copper_layer_count() < 2 || aCtx.Request.copper_layer_count() % 2 != 0 )
636 {
637 ApiResponseStatus e;
638 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
639 e.set_error_message( "copper_layer_count must be an even number of at least 2" );
640 return tl::unexpected( e );
641 }
642
643 if( aCtx.Request.copper_layer_count() > MAX_CU_LAYERS )
644 {
645 ApiResponseStatus e;
646 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
647 e.set_error_message( fmt::format( "copper_layer_count must be below %d", MAX_CU_LAYERS ) );
648 return tl::unexpected( e );
649 }
650
651 int copperLayerCount = static_cast<int>( aCtx.Request.copper_layer_count() );
652 LSET enabled = board::UnpackLayerSet( aCtx.Request.layers() );
653
654 // Sanitize the input
655 enabled |= LSET( { Edge_Cuts, Margin, F_CrtYd, B_CrtYd } );
656 enabled &= ~LSET::AllCuMask();
657 enabled |= LSET::AllCuMask( copperLayerCount );
658
659 BOARD* board = this->board();
660
661 LSET previousEnabled = board->GetEnabledLayers();
662 LSET changedLayers = enabled ^ previousEnabled;
663
664 board->SetEnabledLayers( enabled );
665 board->SetVisibleLayers( board->GetVisibleLayers() | changedLayers );
666
667 LSEQ removedLayers;
668
669 for( PCB_LAYER_ID layer_id : previousEnabled )
670 {
671 if( !enabled[layer_id] && board->HasItemsOnLayer( layer_id ) )
672 removedLayers.push_back( layer_id );
673 }
674
675 bool modified = false;
676
677 if( !removedLayers.empty() )
678 {
680
681 for( PCB_LAYER_ID layer_id : removedLayers )
682 modified |= board->RemoveAllItemsOnLayer( layer_id );
683 }
684
685 if( enabled != previousEnabled || modified )
686 onModified();
687
688 BoardEnabledLayersResponse response;
689
690 response.set_copper_layer_count( copperLayerCount );
691 board::PackLayerSet( *response.mutable_layers(), enabled );
692
693 return response;
694}
695
696
699{
700 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
701 return tl::unexpected( documentValidation.error() );
702
703 common::types::EmbeddedFiles response;
704 board::PackEmbeddedFiles( response, *board()->GetEmbeddedFiles() );
705 return response;
706}
707
708
709HANDLER_RESULT<Empty> unpackEmbeddedFiles( EMBEDDED_FILES& aOutput, const common::types::EmbeddedFiles& aProto )
710{
711 if( !board::UnpackEmbeddedFiles( aOutput, aProto ) )
712 {
713 ApiResponseStatus e;
714 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
715 e.set_error_message( "embedded file validation failed" );
716 return tl::unexpected( e );
717 }
718
719 return Empty();
720}
721
722
724{
725 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
726 return tl::unexpected( documentValidation.error() );
727
728 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
729 return tl::unexpected( *busy );
730
731 EMBEDDED_FILES files;
733
734 if( !result.has_value() )
735 return result;
736
737 EMBEDDED_FILES* boardFiles = board()->GetEmbeddedFiles();
738
739 for( const std::shared_ptr<EMBEDDED_FILES::EMBEDDED_FILE>& file : files.EmbeddedFileMap() | std::views::values )
740 {
741 auto copy = std::make_shared<EMBEDDED_FILES::EMBEDDED_FILE>( *file );
742 boardFiles->AddFile( copy );
743 }
744
745 onModified();
746 return result;
747}
748
749
751{
752 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
753 return tl::unexpected( documentValidation.error() );
754
755 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
756 return tl::unexpected( *busy );
757
758 HANDLER_RESULT<Empty> result = unpackEmbeddedFiles( *board()->GetEmbeddedFiles(),
759 aCtx.Request.files() );
760
761 if( !result.has_value() )
762 return result;
763
764 onModified();
765 return result;
766}
767
768
771{
772 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
773
774 if( !documentValidation )
775 return tl::unexpected( documentValidation.error() );
776
778 BoardDesignRulesResponse response;
779 kiapi::board::BoardDesignRules* rules = response.mutable_rules();
780
781 kiapi::board::MinimumConstraints* constraints = rules->mutable_constraints();
782
783 constraints->mutable_min_clearance()->set_value_nm( bds.m_MinClearance );
784 constraints->mutable_min_groove_width()->set_value_nm( bds.m_MinGrooveWidth );
785 constraints->mutable_min_connection_width()->set_value_nm( bds.m_MinConn );
786 constraints->mutable_min_track_width()->set_value_nm( bds.m_TrackMinWidth );
787 constraints->mutable_min_via_annular_width()->set_value_nm( bds.m_ViasMinAnnularWidth );
788 constraints->mutable_min_via_size()->set_value_nm( bds.m_ViasMinSize );
789 constraints->mutable_min_through_drill()->set_value_nm( bds.m_MinThroughDrill );
790 constraints->mutable_min_microvia_size()->set_value_nm( bds.m_MicroViasMinSize );
791 constraints->mutable_min_microvia_drill()->set_value_nm( bds.m_MicroViasMinDrill );
792 constraints->mutable_copper_edge_clearance()->set_value_nm( bds.m_CopperEdgeClearance );
793 constraints->mutable_hole_clearance()->set_value_nm( bds.m_HoleClearance );
794 constraints->mutable_hole_to_hole_min()->set_value_nm( bds.m_HoleToHoleMin );
795 constraints->mutable_silk_clearance()->set_value_nm( bds.m_SilkClearance );
796 constraints->set_min_resolved_spokes( bds.m_MinResolvedSpokes );
797 constraints->mutable_min_silk_text_height()->set_value_nm( bds.m_MinSilkTextHeight );
798 constraints->mutable_min_silk_text_thickness()->set_value_nm( bds.m_MinSilkLineWidth );
799
800 kiapi::board::PredefinedSizes* sizes = rules->mutable_predefined_sizes();
801
802 for( size_t ii = 1; ii < bds.m_TrackWidthList.size(); ++ii )
803 sizes->add_tracks()->mutable_width()->set_value_nm( bds.m_TrackWidthList[ii] );
804
805 for( size_t ii = 1; ii < bds.m_ViasDimensionsList.size(); ++ii )
806 {
807 kiapi::board::PresetViaDimension* via = sizes->add_vias();
808 via->mutable_diameter()->set_value_nm( bds.m_ViasDimensionsList[ii].m_Diameter );
809 via->mutable_drill()->set_value_nm( bds.m_ViasDimensionsList[ii].m_Drill );
810 }
811
812 for( size_t ii = 1; ii < bds.m_DiffPairDimensionsList.size(); ++ii )
813 {
814 kiapi::board::PresetDiffPairDimension* pair = sizes->add_diff_pairs();
815 pair->mutable_width()->set_value_nm( bds.m_DiffPairDimensionsList[ii].m_Width );
816 pair->mutable_gap()->set_value_nm( bds.m_DiffPairDimensionsList[ii].m_Gap );
817 pair->mutable_via_gap()->set_value_nm( bds.m_DiffPairDimensionsList[ii].m_ViaGap );
818 }
819
820 kiapi::board::SolderMaskPasteDefaults* maskPaste = rules->mutable_solder_mask_paste();
821
822 maskPaste->mutable_mask_expansion()->set_value_nm( bds.m_SolderMaskExpansion );
823 maskPaste->mutable_mask_min_width()->set_value_nm( bds.m_SolderMaskMinWidth );
824 maskPaste->mutable_mask_to_copper_clearance()->set_value_nm( bds.m_SolderMaskToCopperClearance );
825 maskPaste->mutable_paste_margin()->set_value_nm( bds.m_SolderPasteMargin );
826 maskPaste->set_paste_margin_ratio( bds.m_SolderPasteMarginRatio );
827 maskPaste->set_allow_soldermask_bridges_in_footprints( bds.m_AllowSoldermaskBridgesInFPs );
828
829 kiapi::board::TeardropDefaults* teardrops = rules->mutable_teardrops();
830
831 teardrops->set_target_vias( bds.m_TeardropParamsList.m_TargetVias );
832 teardrops->set_target_pth_pads( bds.m_TeardropParamsList.m_TargetPTHPads );
833 teardrops->set_target_smd_pads( bds.m_TeardropParamsList.m_TargetSMDPads );
834 teardrops->set_target_track_to_track( bds.m_TeardropParamsList.m_TargetTrack2Track );
835 teardrops->set_use_round_shapes_only( bds.m_TeardropParamsList.m_UseRoundShapesOnly );
836
838
839 for( int target = TARGET_ROUND; target <= TARGET_TRACK; ++target )
840 {
841 const TEARDROP_PARAMETERS* params = tdList.GetParameters( static_cast<TARGET_TD>( target ) );
842 kiapi::board::TeardropTargetEntry* entry = teardrops->add_target_params();
843
845 static_cast<TARGET_TD>( target ) ) );
846 entry->mutable_params()->set_enabled( params->m_Enabled );
847 entry->mutable_params()->mutable_max_length()->set_value_nm( params->m_TdMaxLen );
848 entry->mutable_params()->mutable_max_width()->set_value_nm( params->m_TdMaxWidth );
849 entry->mutable_params()->set_best_length_ratio( params->m_BestLengthRatio );
850 entry->mutable_params()->set_best_width_ratio( params->m_BestWidthRatio );
851 entry->mutable_params()->set_width_to_size_filter_ratio( params->m_WidthtoSizeFilterRatio );
852 entry->mutable_params()->set_curved_edges( params->m_CurvedEdges );
853 entry->mutable_params()->set_allow_two_tracks( params->m_AllowUseTwoTracks );
854 entry->mutable_params()->set_on_pads_in_zones( params->m_TdOnPadsInZones );
855 }
856
857 kiapi::board::ViaProtectionDefaults* viaProtection = rules->mutable_via_protection();
858
859 viaProtection->set_tent_front( bds.m_TentViasFront );
860 viaProtection->set_tent_back( bds.m_TentViasBack );
861 viaProtection->set_cover_front( bds.m_CoverViasFront );
862 viaProtection->set_cover_back( bds.m_CoverViasBack );
863 viaProtection->set_plug_front( bds.m_PlugViasFront );
864 viaProtection->set_plug_back( bds.m_PlugViasBack );
865 viaProtection->set_cap( bds.m_CapVias );
866 viaProtection->set_fill( bds.m_FillVias );
867
868 for( const auto& [errorCode, severity] : bds.m_DRCSeverities )
869 {
870 board::DrcSeveritySetting* setting = rules->add_severities();
871 setting->set_rule_type(
873 setting->set_severity( ToProtoEnum<SEVERITY, types::RuleSeverity>( severity ) );
874 }
875
876 for( const DRC_EXCLUSION& exclusion : bds.m_DrcExclusions )
877 rules->add_exclusions()->CopyFrom( exclusion.ToProto() );
878
879 response.set_custom_rules_status( CRS_NONE );
880
881 wxString rulesPath = board()->GetDesignRulesPath();
882
883 if( !rulesPath.IsEmpty() && wxFileName::IsFileReadable( rulesPath ) )
884 {
885 wxFFile file( rulesPath, "r" );
886 wxString content;
887 std::vector<std::shared_ptr<DRC_RULE>> parsedRules;
888
889 if( !file.IsOpened() )
890 {
891 response.set_custom_rules_status( CRS_INVALID );
892 return response;
893 }
894
895 file.ReadAll( &content );
896 file.Close();
897
898 try
899 {
900 DRC_RULES_PARSER parser( content, "File" );
901 parser.Parse( parsedRules, nullptr );
902 response.set_custom_rules_status( CRS_VALID );
903 }
904 catch( const IO_ERROR& )
905 {
906 response.set_custom_rules_status( CRS_INVALID );
907 }
908 }
909
910 return response;
911}
912
913
916{
917 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
918
919 if( !documentValidation )
920 return tl::unexpected( documentValidation.error() );
921
922 BOARD_DESIGN_SETTINGS newSettings( board()->GetDesignSettings() );
923 const kiapi::board::BoardDesignRules& rules = aCtx.Request.rules();
924
925 if( rules.has_constraints() )
926 {
927 const kiapi::board::MinimumConstraints& constraints = rules.constraints();
928
929 newSettings.m_MinClearance = constraints.min_clearance().value_nm();
930 newSettings.m_MinGrooveWidth = constraints.min_groove_width().value_nm();
931 newSettings.m_MinConn = constraints.min_connection_width().value_nm();
932 newSettings.m_TrackMinWidth = constraints.min_track_width().value_nm();
933 newSettings.m_ViasMinAnnularWidth = constraints.min_via_annular_width().value_nm();
934 newSettings.m_ViasMinSize = constraints.min_via_size().value_nm();
935 newSettings.m_MinThroughDrill = constraints.min_through_drill().value_nm();
936 newSettings.m_MicroViasMinSize = constraints.min_microvia_size().value_nm();
937 newSettings.m_MicroViasMinDrill = constraints.min_microvia_drill().value_nm();
938 newSettings.m_CopperEdgeClearance = constraints.copper_edge_clearance().value_nm();
939 newSettings.m_HoleClearance = constraints.hole_clearance().value_nm();
940 newSettings.m_HoleToHoleMin = constraints.hole_to_hole_min().value_nm();
941 newSettings.m_SilkClearance = constraints.silk_clearance().value_nm();
942 newSettings.m_MinResolvedSpokes = constraints.min_resolved_spokes();
943 newSettings.m_MinSilkTextHeight = constraints.min_silk_text_height().value_nm();
944 newSettings.m_MinSilkLineWidth = constraints.min_silk_text_thickness().value_nm();
945 }
946
947 if( rules.has_predefined_sizes() )
948 {
949 newSettings.m_TrackWidthList.clear();
950 newSettings.m_TrackWidthList.emplace_back( 0 );
951
952 for( const kiapi::board::PresetTrackWidth& track : rules.predefined_sizes().tracks() )
953 newSettings.m_TrackWidthList.emplace_back( track.width().value_nm() );
954
955 newSettings.m_ViasDimensionsList.clear();
956 newSettings.m_ViasDimensionsList.emplace_back( 0, 0 );
957
958 for( const kiapi::board::PresetViaDimension& via : rules.predefined_sizes().vias() )
959 {
960 newSettings.m_ViasDimensionsList.emplace_back( static_cast<int>( via.diameter().value_nm() ),
961 static_cast<int>( via.drill().value_nm() ) );
962 }
963
964 newSettings.m_DiffPairDimensionsList.clear();
965 newSettings.m_DiffPairDimensionsList.emplace_back( 0, 0, 0 );
966
967 for( const kiapi::board::PresetDiffPairDimension& pair : rules.predefined_sizes().diff_pairs() )
968 {
969 newSettings.m_DiffPairDimensionsList.emplace_back(
970 static_cast<int>( pair.width().value_nm() ),
971 static_cast<int>( pair.gap().value_nm() ),
972 static_cast<int>( pair.via_gap().value_nm() ) );
973 }
974 }
975
976 if( rules.has_solder_mask_paste() )
977 {
978 const kiapi::board::SolderMaskPasteDefaults& maskPaste = rules.solder_mask_paste();
979
980 newSettings.m_SolderMaskExpansion = maskPaste.mask_expansion().value_nm();
981 newSettings.m_SolderMaskMinWidth = maskPaste.mask_min_width().value_nm();
982 newSettings.m_SolderMaskToCopperClearance = maskPaste.mask_to_copper_clearance().value_nm();
983 newSettings.m_SolderPasteMargin = maskPaste.paste_margin().value_nm();
984 newSettings.m_SolderPasteMarginRatio = maskPaste.paste_margin_ratio();
986 maskPaste.allow_soldermask_bridges_in_footprints();
987 }
988
989 if( rules.has_teardrops() )
990 {
991 const kiapi::board::TeardropDefaults& teardrops = rules.teardrops();
992
993 newSettings.m_TeardropParamsList.m_TargetVias = teardrops.target_vias();
994 newSettings.m_TeardropParamsList.m_TargetPTHPads = teardrops.target_pth_pads();
995 newSettings.m_TeardropParamsList.m_TargetSMDPads = teardrops.target_smd_pads();
996 newSettings.m_TeardropParamsList.m_TargetTrack2Track = teardrops.target_track_to_track();
997 newSettings.m_TeardropParamsList.m_UseRoundShapesOnly = teardrops.use_round_shapes_only();
998
999 for( const kiapi::board::TeardropTargetEntry& entry : teardrops.target_params() )
1000 {
1001 if( entry.target() == kiapi::board::TeardropTarget::TDT_UNKNOWN )
1002 continue;
1003
1005 entry.target() );
1006
1007 if( target == TARGET_UNKNOWN )
1008 {
1009 ApiResponseStatus e;
1010 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1011 e.set_error_message( "unknown teardrop target" );
1012 return tl::unexpected( e );
1013 }
1014
1015 TEARDROP_PARAMETERS* params = newSettings.m_TeardropParamsList.GetParameters( target );
1016
1017 params->m_Enabled = entry.params().enabled();
1018 params->m_TdMaxLen = entry.params().max_length().value_nm();
1019 params->m_TdMaxWidth = entry.params().max_width().value_nm();
1020 params->m_BestLengthRatio = entry.params().best_length_ratio();
1021 params->m_BestWidthRatio = entry.params().best_width_ratio();
1022 params->m_WidthtoSizeFilterRatio = entry.params().width_to_size_filter_ratio();
1023 params->m_CurvedEdges = entry.params().curved_edges();
1024 params->m_AllowUseTwoTracks = entry.params().allow_two_tracks();
1025 params->m_TdOnPadsInZones = entry.params().on_pads_in_zones();
1026 }
1027 }
1028
1029 if( rules.has_via_protection() )
1030 {
1031 const kiapi::board::ViaProtectionDefaults& viaProtection = rules.via_protection();
1032
1033 newSettings.m_TentViasFront = viaProtection.tent_front();
1034 newSettings.m_TentViasBack = viaProtection.tent_back();
1035 newSettings.m_CoverViasFront = viaProtection.cover_front();
1036 newSettings.m_CoverViasBack = viaProtection.cover_back();
1037 newSettings.m_PlugViasFront = viaProtection.plug_front();
1038 newSettings.m_PlugViasBack = viaProtection.plug_back();
1039 newSettings.m_CapVias = viaProtection.cap();
1040 newSettings.m_FillVias = viaProtection.fill();
1041 }
1042
1043 newSettings.m_DRCSeverities.clear();
1044
1045 for( const kiapi::board::DrcSeveritySetting& severitySetting : rules.severities() )
1046 {
1047 PCB_DRC_CODE ruleType =
1048 FromProtoEnum<PCB_DRC_CODE, kiapi::board::DrcErrorType>( severitySetting.rule_type() );
1049
1050 const std::unordered_set<SEVERITY> permitted( { RPT_SEVERITY_ERROR, RPT_SEVERITY_WARNING, RPT_SEVERITY_IGNORE } );
1051 SEVERITY setting = FromProtoEnum<SEVERITY, kiapi::common::types::RuleSeverity>( severitySetting.severity() );
1052
1053 if( !permitted.contains( setting ) )
1054 {
1055 ApiResponseStatus e;
1056 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1057 e.set_error_message( fmt::format( "DRC severity must be error, warning, or ignore" ) );
1058 return tl::unexpected( e );
1059 }
1060
1061 newSettings.m_DRCSeverities[ruleType] = setting;
1062 }
1063
1064 newSettings.m_DrcExclusions.clear();
1065
1066 for( const kiapi::board::DrcExclusion& exclusion : rules.exclusions() )
1067 newSettings.m_DrcExclusions.insert( DRC_EXCLUSION::FromProto( exclusion ) );
1068
1069 std::vector<BOARD_DESIGN_SETTINGS::VALIDATION_ERROR> errors = newSettings.ValidateDesignRules();
1070
1071 if( !errors.empty() )
1072 {
1073 const BOARD_DESIGN_SETTINGS::VALIDATION_ERROR& error = errors.front();
1074
1075 ApiResponseStatus e;
1076 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1077 e.set_error_message( fmt::format( "Invalid board design rules: {}: {}",
1078 error.setting_name.ToStdString(),
1079 error.error_message.ToStdString() ) );
1080 return tl::unexpected( e );
1081 }
1082
1083 board()->SetDesignSettings( newSettings );
1084
1085 onModified();
1086
1087 HANDLER_CONTEXT<GetBoardDesignRules> getCtx = { aCtx.ClientName, GetBoardDesignRules() };
1088 *getCtx.Request.mutable_board() = aCtx.Request.board();
1089
1090 return handleGetBoardDesignRules( getCtx );
1091}
1092
1093
1096{
1097 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1098
1099 if( !documentValidation )
1100 return tl::unexpected( documentValidation.error() );
1101
1102 CustomRulesResponse response;
1103 response.set_status( CRS_NONE );
1104
1105 wxString rulesPath = board()->GetDesignRulesPath();
1106
1107 if( rulesPath.IsEmpty() || !wxFileName::IsFileReadable( rulesPath ) )
1108 return response;
1109
1110 wxFFile file( rulesPath, "r" );
1111
1112 if( !file.IsOpened() )
1113 {
1114 response.set_status( CRS_INVALID );
1115 response.set_error_text( "Failed to open custom rules file" );
1116 return response;
1117 }
1118
1119 wxString content;
1120 file.ReadAll( &content );
1121 file.Close();
1122
1123 std::vector<std::shared_ptr<DRC_RULE>> parsedRules;
1124
1125 try
1126 {
1127 DRC_RULES_PARSER parser( content, "File" );
1128 parser.Parse( parsedRules, nullptr );
1129 }
1130 catch( const IO_ERROR& ioe )
1131 {
1132 response.set_status( CRS_INVALID );
1133 response.set_error_text( ioe.What().ToStdString() );
1134 return response;
1135 }
1136
1137 for( const std::shared_ptr<DRC_RULE>& rule : parsedRules )
1138 {
1139 // TODO(JE) since we now need this for both here and the rules editor, maybe it's time
1140 // to just make comment parsing part of the parser?
1141 wxString text = DRC_RULE_LOADER::ExtractRuleText( content, rule->m_Name );
1142 wxString comment = DRC_RULE_LOADER::ExtractRuleComment( text );
1143
1144 kiapi::board::CustomRule* customRule = response.add_rules();
1145
1146 if( rule->m_Condition )
1147 customRule->set_condition( rule->m_Condition->GetExpression().ToUTF8() );
1148
1149 for( const DRC_CONSTRAINT& constraint : rule->m_Constraints )
1150 {
1151 board::CustomRuleConstraint* constraintProto = customRule->add_constraints();
1152 constraint.ToProto( *constraintProto );
1153 }
1154
1155 customRule->set_severity( ToProtoEnum<SEVERITY, types::RuleSeverity>( rule->m_Severity ) );
1156 customRule->set_name( rule->m_Name.ToUTF8() );
1157
1158 if( rule->m_LayerSource.CmpNoCase( wxS( "outer" ) ) == 0 )
1159 {
1160 customRule->set_layer_mode( kiapi::board::CRLM_OUTER );
1161 }
1162 else if( rule->m_LayerSource.CmpNoCase( wxS( "inner" ) ) == 0 )
1163 {
1164 customRule->set_layer_mode( kiapi::board::CRLM_INNER );
1165 }
1166 else if( !rule->m_LayerSource.IsEmpty() )
1167 {
1168 int layer = LSET::NameToLayer( rule->m_LayerSource );
1169
1170 if( layer != UNDEFINED_LAYER && layer != UNSELECTED_LAYER && layer < PCB_LAYER_ID_COUNT )
1171 {
1172 customRule->set_single_layer(
1174 }
1175 }
1176
1177 if( !comment.IsEmpty() )
1178 customRule->set_comments( comment );
1179 }
1180
1181 response.set_status( CRS_VALID );
1182 return response;
1183}
1184
1185
1188{
1189 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1190
1191 if( !documentValidation )
1192 return tl::unexpected( documentValidation.error() );
1193
1194 wxString rulesPath = board()->GetDesignRulesPath();
1195
1196 if( aCtx.Request.rules_size() == 0 )
1197 {
1198 if( wxFileName::FileExists( rulesPath ) )
1199 {
1200 if( !wxRemoveFile( rulesPath ) )
1201 {
1202 CustomRulesResponse response;
1203 response.set_status( CRS_INVALID );
1204 response.set_error_text( "Failed to remove custom rules file" );
1205 return response;
1206 }
1207 }
1208
1209 CustomRulesResponse response;
1210 response.set_status( CRS_NONE );
1211 return response;
1212 }
1213
1214 wxString rulesText;
1215 rulesText << "(version 2)\n";
1216
1217 for( const board::CustomRule& rule : aCtx.Request.rules() )
1218 {
1219 wxString serializationError;
1220 wxString serializedRule = DRC_RULE::FormatRuleFromProto( rule, &serializationError );
1221
1222 if( serializedRule.IsEmpty() )
1223 {
1224 CustomRulesResponse response;
1225 response.set_status( CRS_INVALID );
1226
1227 if( serializationError.IsEmpty() )
1228 response.set_error_text( "Failed to serialize custom rule" );
1229 else
1230 response.set_error_text( serializationError.ToUTF8() );
1231
1232 return response;
1233 }
1234
1235 rulesText << "\n" << serializedRule;
1236 }
1237
1238 // Validate generated file text before writing so callers get parser errors in response.
1239 try
1240 {
1241 std::vector<std::shared_ptr<DRC_RULE>> parsedRules;
1242 DRC_RULES_PARSER parser( rulesText, "SetCustomDesignRules" );
1243 parser.Parse( parsedRules, nullptr );
1244 }
1245 catch( const IO_ERROR& ioe )
1246 {
1247 CustomRulesResponse response;
1248 response.set_status( CRS_INVALID );
1249 response.set_error_text( ioe.What().ToStdString() );
1250 return response;
1251 }
1252
1253 wxFFile file( rulesPath, "w" );
1254
1255 if( !file.IsOpened() )
1256 {
1257 CustomRulesResponse response;
1258 response.set_status( CRS_INVALID );
1259 response.set_error_text( "Failed to open custom rules file for writing" );
1260 return response;
1261 }
1262
1263 if( !file.Write( rulesText ) )
1264 {
1265 file.Close();
1266
1267 CustomRulesResponse response;
1268 response.set_status( CRS_INVALID );
1269 response.set_error_text( "Failed to write custom rules file" );
1270 return response;
1271 }
1272
1273 file.Close();
1274
1275 HANDLER_CONTEXT<GetCustomDesignRules> getCtx = { aCtx.ClientName, GetCustomDesignRules() };
1276 *getCtx.Request.mutable_board() = aCtx.Request.board();
1277 return handleGetCustomDesignRules( getCtx );
1278}
1279
1280
1283{
1284 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1285 !documentValidation )
1286 {
1287 return tl::unexpected( documentValidation.error() );
1288 }
1289
1290 VECTOR2I origin;
1291 const BOARD_DESIGN_SETTINGS& settings = board()->GetDesignSettings();
1292
1293 switch( aCtx.Request.type() )
1294 {
1295 case BOT_GRID:
1296 origin = settings.GetGridOrigin();
1297 break;
1298
1299 case BOT_DRILL:
1300 origin = settings.GetAuxOrigin();
1301 break;
1302
1303 default:
1304 case BOT_UNKNOWN:
1305 {
1306 ApiResponseStatus e;
1307 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1308 e.set_error_message( "Unexpected origin type" );
1309 return tl::unexpected( e );
1310 }
1311 }
1312
1313 types::Vector2 reply;
1314 PackVector2( reply, origin );
1315 return reply;
1316}
1317
1320{
1321 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
1322 return tl::unexpected( documentValidation.error() );
1323
1324 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1325 return tl::unexpected( *busy );
1326
1327 VECTOR2I origin = UnpackVector2( aCtx.Request.origin() );
1328
1329 switch( aCtx.Request.type() )
1330 {
1331 case BOT_GRID:
1332 {
1333 PCB_EDIT_FRAME* f = frame();
1334
1335 if( f )
1336 {
1337 frame()->CallAfter(
1338 [f, origin]()
1339 {
1340 // gridSetOrigin takes ownership and frees this
1341 VECTOR2D* dorigin = new VECTOR2D( origin );
1342 TOOL_MANAGER* mgr = f->GetToolManager();
1343 mgr->RunAction( PCB_ACTIONS::gridSetOrigin, dorigin );
1344 f->Refresh();
1345 } );
1346 }
1347 else
1348 {
1349 board()->GetDesignSettings().SetGridOrigin( origin );
1351 }
1352
1353 break;
1354 }
1355
1356 case BOT_DRILL:
1357 {
1358 PCB_EDIT_FRAME* f = frame();
1359
1360 if( f )
1361 {
1362 frame()->CallAfter(
1363 [f, origin]()
1364 {
1365 TOOL_MANAGER* mgr = f->GetToolManager();
1366 mgr->RunAction( PCB_ACTIONS::drillSetOrigin, origin );
1367 f->Refresh();
1368 } );
1369 }
1370 else
1371 {
1372 board()->GetDesignSettings().SetAuxOrigin( origin );
1374 }
1375
1376 break;
1377 }
1378
1379 default:
1380 case BOT_UNKNOWN:
1381 {
1382 ApiResponseStatus e;
1383 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1384 e.set_error_message( "Unexpected origin type" );
1385 return tl::unexpected( e );
1386 }
1387 }
1388
1389 return Empty();
1390}
1391
1392
1395{
1396 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1397 !documentValidation )
1398 {
1399 return tl::unexpected( documentValidation.error() );
1400 }
1401
1402 BoardLayerNameResponse response;
1403
1405
1406 response.set_name( board()->GetLayerName( id ) );
1407
1408 return response;
1409}
1410
1411
1414{
1415 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1416 !documentValidation )
1417 {
1418 return tl::unexpected( documentValidation.error() );
1419 }
1420
1421 BoardLayerResponse response;
1422
1423 PCB_LAYER_ID id = board()->GetLayerID( wxString::FromUTF8( aCtx.Request.name() ) );
1424 response.set_layer( ToProtoEnum<PCB_LAYER_ID, board::types::BoardLayer>( id ) );
1425
1426 return response;
1427}
1428
1429
1430std::optional<TITLE_BLOCK*> API_HANDLER_PCB::getTitleBlock( const DocumentSpecifier& aDocument )
1431{
1432 return &context()->GetBoard()->GetTitleBlock();
1433}
1434
1435
1436std::optional<PAGE_INFO> API_HANDLER_PCB::getPageSettings( const DocumentSpecifier& aDocument )
1437{
1438 return context()->GetBoard()->GetPageSettings();
1439}
1440
1441
1442bool API_HANDLER_PCB::setPageSettings( const DocumentSpecifier& aDocument, const PAGE_INFO& aPageInfo )
1443{
1444 context()->GetBoard()->SetPageSettings( aPageInfo );
1445 return true;
1446}
1447
1448
1453
1454
1455void API_HANDLER_PCB::setDrawingSheetFileName( const wxString& aFileName )
1456{
1458
1459 if( frame() )
1460 {
1463 }
1464}
1465
1466
1468{
1470
1471 if( frame() )
1472 {
1473 frame()->Refresh();
1474 frame()->OnModify();
1476 }
1477}
1478
1479
1481{
1482 if( BOARD* brd = board() )
1483 brd->SynchronizeNetsAndNetClasses( false );
1484
1485 // Refresh UI that depends on netclasses, such as the properties panel
1486 if( TOOL_MANAGER* mgr = toolManager() )
1487 mgr->ProcessEvent( EVENTS::SelectedItemsModified );
1488
1489 if( frame() )
1490 {
1491 frame()->Refresh();
1493 }
1494}
1495
1496
1499{
1500 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
1501 return tl::unexpected( documentValidation.error() );
1502
1503 GetDocumentModifiedStateResponse response;
1504 response.set_state( pcbContext()->IsContentModified() ? DocumentModifiedState::DMS_MODIFIED
1505 : DocumentModifiedState::DMS_UNMODIFIED );
1506 return response;
1507}
1508
1509
1511{
1512 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
1513 return tl::unexpected( documentValidation.error() );
1514
1515 NetsResponse response;
1516 BOARD* board = this->board();
1517
1518 std::set<wxString> netclassFilter;
1519
1520 for( const std::string& nc : aCtx.Request.netclass_filter() )
1521 netclassFilter.insert( wxString( nc.c_str(), wxConvUTF8 ) );
1522
1523 for( NETINFO_ITEM* net : board->GetNetInfo() )
1524 {
1525 NETCLASS* nc = net->GetNetClass();
1526
1527 if( !netclassFilter.empty() && nc )
1528 {
1529 bool inClass = false;
1530
1531 for( const wxString& filter : netclassFilter )
1532 {
1533 if( nc->ContainsNetclassWithName( filter ) )
1534 {
1535 inClass = true;
1536 break;
1537 }
1538 }
1539
1540 if( !inClass )
1541 continue;
1542 }
1543
1544 board::types::Net* netProto = response.add_nets();
1545 netProto->set_name( net->GetNetname() );
1546 netProto->mutable_code()->set_value( net->GetNetCode() );
1547 }
1548
1549 return response;
1550}
1551
1552
1555{
1556 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
1557 {
1558 ApiResponseStatus e;
1559 e.set_status( ApiStatusCode::AS_UNHANDLED );
1560 return tl::unexpected( e );
1561 }
1562
1563 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1564 return tl::unexpected( *busy );
1565
1566 std::vector<KICAD_T> types = parseRequestedItemTypes( aCtx.Request.types() );
1567 const bool filterByType = aCtx.Request.types_size() > 0;
1568
1569 if( filterByType && types.empty() )
1570 {
1571 ApiResponseStatus e;
1572 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1573 e.set_error_message( "none of the requested types are valid for a Board object" );
1574 return tl::unexpected( e );
1575 }
1576
1577 std::set<KICAD_T> typeFilter( types.begin(), types.end() );
1578 std::vector<BOARD_CONNECTED_ITEM*> sourceItems;
1579
1580 for( const types::KIID& id : aCtx.Request.items() )
1581 {
1582 if( std::optional<BOARD_ITEM*> item = getItemById( KIID( id.value() ) ) )
1583 {
1584 if( BOARD_CONNECTED_ITEM* connected = dynamic_cast<BOARD_CONNECTED_ITEM*>( *item ) )
1585 sourceItems.emplace_back( connected );
1586 }
1587 }
1588
1589 if( sourceItems.empty() )
1590 {
1591 ApiResponseStatus e;
1592 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1593 e.set_error_message( "none of the requested IDs were found or valid connected items" );
1594 return tl::unexpected( e );
1595 }
1596
1597 GetItemsResponse response;
1598 std::shared_ptr<CONNECTIVITY_DATA> conn = board()->GetConnectivity();
1599 std::set<KIID> insertedItems;
1600
1601 for( BOARD_CONNECTED_ITEM* source : sourceItems )
1602 {
1603 for( BOARD_CONNECTED_ITEM* connected : conn->GetConnectedItems( source ) )
1604 {
1605 if( filterByType && !typeFilter.contains( connected->Type() ) )
1606 continue;
1607
1608 if( !insertedItems.insert( connected->m_Uuid ).second )
1609 continue;
1610
1611 connected->Serialize( *response.add_items() );
1612 }
1613 }
1614
1615 response.set_status( ItemRequestStatus::IRS_OK );
1616 return response;
1617}
1618
1619
1621 const HANDLER_CONTEXT<GetItemsByNet>& aCtx )
1622{
1623 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
1624 {
1625 ApiResponseStatus e;
1626 e.set_status( ApiStatusCode::AS_UNHANDLED );
1627 return tl::unexpected( e );
1628 }
1629
1630 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1631 return tl::unexpected( *busy );
1632
1633 std::vector<KICAD_T> types = parseRequestedItemTypes( aCtx.Request.types() );
1634 const bool filterByType = aCtx.Request.types_size() > 0;
1635
1636 if( filterByType && types.empty() )
1637 {
1638 ApiResponseStatus e;
1639 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1640 e.set_error_message( "none of the requested types are valid for a Board object" );
1641 return tl::unexpected( e );
1642 }
1643
1644 if( !filterByType )
1646
1647 GetItemsResponse response;
1648 BOARD* board = this->board();
1649 std::shared_ptr<CONNECTIVITY_DATA> conn = board->GetConnectivity();
1650 std::set<KIID> insertedItems;
1651
1652 const NETINFO_LIST& nets = board->GetNetInfo();
1653
1654 for( const board::types::Net& net : aCtx.Request.nets() )
1655 {
1656 NETINFO_ITEM* netInfo = nets.GetNetItem( wxString::FromUTF8( net.name() ) );
1657
1658 if( !netInfo )
1659 continue;
1660
1661 for( BOARD_CONNECTED_ITEM* item : conn->GetNetItems( netInfo->GetNetCode(), types ) )
1662 {
1663 if( !insertedItems.insert( item->m_Uuid ).second )
1664 continue;
1665
1666 item->Serialize( *response.add_items() );
1667 }
1668 }
1669
1670 response.set_status( ItemRequestStatus::IRS_OK );
1671 return response;
1672}
1673
1674
1677{
1678 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
1679 {
1680 ApiResponseStatus e;
1681 e.set_status( ApiStatusCode::AS_UNHANDLED );
1682 return tl::unexpected( e );
1683 }
1684
1685 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1686 return tl::unexpected( *busy );
1687
1688 std::vector<KICAD_T> types = parseRequestedItemTypes( aCtx.Request.types() );
1689 const bool filterByType = aCtx.Request.types_size() > 0;
1690
1691 if( filterByType && types.empty() )
1692 {
1693 ApiResponseStatus e;
1694 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1695 e.set_error_message( "none of the requested types are valid for a Board object" );
1696 return tl::unexpected( e );
1697 }
1698
1699 if( !filterByType )
1701
1702 std::set<wxString> requestedClasses;
1703
1704 for( const std::string& netClass : aCtx.Request.net_classes() )
1705 requestedClasses.insert( wxString( netClass.c_str(), wxConvUTF8 ) );
1706
1707 GetItemsResponse response;
1708 BOARD* board = this->board();
1709 std::shared_ptr<CONNECTIVITY_DATA> conn = board->GetConnectivity();
1710 std::set<KIID> insertedItems;
1711
1712 for( NETINFO_ITEM* net : board->GetNetInfo() )
1713 {
1714 if( !net )
1715 continue;
1716
1717 NETCLASS* nc = net->GetNetClass();
1718
1719 if( !requestedClasses.empty() )
1720 {
1721 if( !nc )
1722 continue;
1723
1724 bool inClass = false;
1725
1726 for( const wxString& filter : requestedClasses )
1727 {
1728 if( nc->ContainsNetclassWithName( filter ) )
1729 {
1730 inClass = true;
1731 break;
1732 }
1733 }
1734
1735 if( !inClass )
1736 continue;
1737 }
1738
1739 for( BOARD_CONNECTED_ITEM* item : conn->GetNetItems( net->GetNetCode(), types ) )
1740 {
1741 if( !insertedItems.insert( item->m_Uuid ).second )
1742 continue;
1743
1744 item->Serialize( *response.add_items() );
1745 }
1746 }
1747
1748 response.set_status( ItemRequestStatus::IRS_OK );
1749 return response;
1750}
1751
1752
1755{
1756 NetClassForNetsResponse response;
1757
1758 BOARD* board = this->board();
1759 const NETINFO_LIST& nets = board->GetNetInfo();
1760
1761 for( const board::types::Net& net : aCtx.Request.net() )
1762 {
1763 NETINFO_ITEM* netInfo = nets.GetNetItem( wxString::FromUTF8( net.name() ) );
1764
1765 if( !netInfo )
1766 continue;
1767
1768 auto [pair, rc] = response.mutable_classes()->insert( { net.name(), {} } );
1769 netInfo->GetNetClass()->Serialize( pair->second );
1770 }
1771
1772 return response;
1773}
1774
1775
1777 const google::protobuf::RepeatedPtrField<kiapi::common::types::KIID>& aZoneIds ) const
1778{
1779 std::vector<ZONE*> toFill;
1780
1781 for( const types::KIID& id : aZoneIds )
1782 {
1783 std::optional<BOARD_ITEM*> item = getItemById( KIID( id.value() ) );
1784
1785 if( !item || ( *item )->Type() != PCB_ZONE_T )
1786 {
1787 ApiResponseStatus e;
1788 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1789 e.set_error_message( fmt::format( "zone with ID {} not found on the board", id.value() ) );
1790 return tl::unexpected( e );
1791 }
1792
1793 ZONE* zone = static_cast<ZONE*>( *item );
1794
1795 // The filler silently skips rule areas, which would turn this into a false success
1796 if( zone->GetIsRuleArea() )
1797 {
1798 ApiResponseStatus e;
1799 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1800 e.set_error_message( fmt::format( "zone with ID {} is a rule area and cannot be filled",
1801 id.value() ) );
1802 return tl::unexpected( e );
1803 }
1804
1805 // A repeated id would enqueue concurrent fill tasks for the same zone
1806 if( !alg::contains( toFill, zone ) )
1807 toFill.push_back( zone );
1808 }
1809
1810 return toFill;
1811}
1812
1813
1815{
1816 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
1817 return tl::unexpected( documentValidation.error() );
1818
1819 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1820 return tl::unexpected( *busy );
1821
1822 TOOL_MANAGER* mgr = toolManager();
1823
1824 // A frame's tool manager always carries the zone filler tool; headless sessions start with a
1825 // bare tool manager and register it on first use, like the CLI jobs do.
1826 if( !mgr->FindTool( ZONE_FILLER_TOOL_NAME ) )
1827 mgr->RegisterTool( new ZONE_FILLER_TOOL );
1828
1829 if( aCtx.Request.zones().empty() )
1830 {
1831 if( frame() )
1832 {
1833 frame()->CallAfter( [mgr]()
1834 {
1836 } );
1837 }
1838 else
1839 {
1840 // Headless sessions have no event loop to defer to; fill synchronously through the
1841 // same tool the CLI jobs use.
1842 mgr->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, nullptr, true );
1843 }
1844 }
1845 else
1846 {
1848
1849 if( !toFill )
1850 return tl::unexpected( toFill.error() );
1851
1852 std::unique_ptr<COMMIT> commit = createCommit();
1853 ZONE_FILLER filler( board(), commit.get() );
1854
1855 if( !filler.Fill( *toFill ) )
1856 {
1857 commit->Revert();
1858
1859 ApiResponseStatus e;
1860 e.set_status( ApiStatusCode::AS_UNKNOWN );
1861 e.set_error_message( "zone fill failed" );
1862 return tl::unexpected( e );
1863 }
1864
1865 commit->Push( _( "Fill Zone(s)" ), SKIP_CONNECTIVITY | ZONE_FILL_OP );
1866
1867 // Push skipped connectivity, so run the same post-fill refresh as the interactive fill
1868 mgr->GetTool<ZONE_FILLER_TOOL>()->PostFillRefresh( frame() == nullptr );
1869 }
1870
1871 onModified();
1872 return Empty();
1873}
1874
1875
1877{
1878 HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() );
1879
1880 if( !documentValidation )
1881 return tl::unexpected( documentValidation.error() );
1882
1883 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1884 return tl::unexpected( *busy );
1885
1886 wxFileName netlistPath( project().AbsolutePath( wxString::FromUTF8( aCtx.Request.netlist_path() ) ) );
1887
1888 if( !netlistPath.IsOk() || !netlistPath.FileExists() )
1889 {
1890 ApiResponseStatus e;
1891 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1892 e.set_error_message(
1893 fmt::format( "netlist file '{}' could not be opened", netlistPath.GetFullPath().ToStdString() ) );
1894 return tl::unexpected( e );
1895 }
1896
1897 PCB_CONTEXT* ctx = pcbContext();
1899
1900 const bool lookupByTimestamp = aCtx.Request.match_mode() != NetlistMatchMode::NMM_REFERENCE;
1901
1903 netlist.SetFindByTimeStamp( lookupByTimestamp );
1904 netlist.SetReplaceFootprints( aCtx.Request.update_footprints() );
1905
1906 if( !ctx->ReadNetlistFromFile( netlistPath.GetFullPath(), netlist, reporter ) )
1907 {
1908 ApiResponseStatus e;
1909 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1910 e.set_error_message( fmt::format( "unable to handle netlist file '{}': {}",
1911 netlistPath.GetFullPath().ToStdString(),
1912 reporter.GetMessages().ToStdString() ) );
1913 return tl::unexpected( e );
1914 }
1915
1916 std::unique_ptr<BOARD_NETLIST_UPDATER> updater = ctx->MakeNetlistUpdater();
1917
1918 updater->SetReporter( &reporter );
1919 updater->SetIsDryRun( aCtx.Request.dry_run() );
1920 updater->SetWillDrag( false );
1921 updater->SetLookupByTimestamp( lookupByTimestamp );
1922 updater->SetDeleteUnusedFootprints( aCtx.Request.delete_extra_footprints() );
1923 updater->SetReplaceFootprints( aCtx.Request.update_footprints() );
1924 updater->SetTransferGroups( aCtx.Request.transfer_groups() );
1925 updater->SetOverrideLocks( aCtx.Request.override_locks() );
1926 updater->SetUpdateFields( true );
1927
1928 const bool success = updater->UpdateNetlist( netlist );
1929
1930 if( !aCtx.Request.dry_run() && success )
1931 ctx->OnNetlistChanged( *updater );
1932
1933 ImportNetlistResponse response;
1934 response.set_report( reporter.GetMessages().ToUTF8() );
1935 response.set_error_count( updater->GetErrorCount() );
1936 response.set_warning_count( updater->GetWarningCount() );
1937 response.set_new_footprint_count( updater->GetNewFootprintCount() );
1938 return response;
1939}
1940
1941
1944{
1945 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
1946 return tl::unexpected( documentValidation.error() );
1947
1948 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
1949 return tl::unexpected( *busy );
1950
1951 wxFileName sesPath( project().AbsolutePath( wxString::FromUTF8( aCtx.Request.session_path() ) ) );
1952
1953 if( !sesPath.IsOk() || !sesPath.FileExists() )
1954 {
1955 ApiResponseStatus e;
1956 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1957 e.set_error_message(
1958 fmt::format( "session file '{}' could not be opened", sesPath.GetFullPath().ToStdString() ) );
1959 return tl::unexpected( e );
1960 }
1961
1962 int skippedCount = 0;
1963 BOARD_COMMIT* commit = static_cast<BOARD_COMMIT*>( getCurrentCommit( aCtx.ClientName ) );
1965
1966 try
1967 {
1968 DSN::ImportSpecctraSession( board(), sesPath.GetFullPath(), *commit, &reporter, &skippedCount );
1969 }
1970 catch( const IO_ERROR& ioe )
1971 {
1972 commit->Revert();
1973
1974 ApiResponseStatus e;
1975 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
1976 e.set_error_message( fmt::format( "failed to import session '{}': {}", sesPath.GetFullPath().ToStdString(),
1977 ioe.What().ToStdString() ) );
1978 return tl::unexpected( e );
1979 }
1980
1981 if( !m_activeClients.count( aCtx.ClientName ) )
1982 pushCurrentCommit( aCtx.ClientName, _( "Imported Specctra session via API" ) );
1983
1984 ImportSpecctraSessionResponse response;
1985 response.set_report( reporter.GetMessages().ToUTF8() );
1986 response.set_skipped_count( skippedCount );
1987 return response;
1988}
1989
1990
1993{
1994 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "GetBoardEditorAppearanceSettings" ) )
1995 return tl::unexpected( *headless );
1996
1997 BoardEditorAppearanceSettings reply;
1998
1999 // TODO: might be nice to put all these things in one place and have it derive SERIALIZABLE
2000
2001 const PCB_DISPLAY_OPTIONS& displayOptions = frame()->GetDisplayOptions();
2002
2003 reply.set_inactive_layer_display( ToProtoEnum<HIGH_CONTRAST_MODE, InactiveLayerDisplayMode>(
2004 displayOptions.m_ContrastModeDisplay ) );
2005 reply.set_net_color_display(
2007
2008 reply.set_board_flip( frame()->GetCanvas()->GetView()->IsMirroredX()
2009 ? BoardFlipMode::BFM_FLIPPED_X
2010 : BoardFlipMode::BFM_NORMAL );
2011
2012 PCBNEW_SETTINGS* editorSettings = frame()->GetPcbNewSettings();
2013
2014 reply.set_ratsnest_display( ToProtoEnum<RATSNEST_MODE, RatsnestDisplayMode>(
2015 editorSettings->m_Display.m_RatsnestMode ) );
2016
2017 return reply;
2018}
2019
2020
2023{
2024 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "SetBoardEditorAppearanceSettings" ) )
2025 return tl::unexpected( *headless );
2026
2027 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2028 return tl::unexpected( *busy );
2029
2031 PCBNEW_SETTINGS* editorSettings = frame()->GetPcbNewSettings();
2032 const BoardEditorAppearanceSettings& newSettings = aCtx.Request.settings();
2033
2034 options.m_ContrastModeDisplay =
2035 FromProtoEnum<HIGH_CONTRAST_MODE>( newSettings.inactive_layer_display() );
2036 options.m_NetColorMode =
2037 FromProtoEnum<NET_COLOR_MODE>( newSettings.net_color_display() );
2038 options.m_FlipBoardView = newSettings.board_flip() == BoardFlipMode::BFM_FLIPPED_X;
2039
2040 editorSettings->m_Display.m_RatsnestMode =
2041 FromProtoEnum<RATSNEST_MODE>( newSettings.ratsnest_display() );
2042
2043 frame()->SetDisplayOptions( options );
2045 frame()->GetCanvas()->Refresh();
2046
2047 return Empty();
2048}
2049
2050
2053{
2054 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
2055 return tl::unexpected( documentValidation.error() );
2056
2057 const PCB_PLOT_PARAMS& plotOpts = board()->GetPlotOptions();
2058
2059 BoardPlotSettingsResponse response;
2060 BoardPlotSettings* settings = response.mutable_plot_settings();
2061
2062 board::PackLayerSet( *settings->mutable_layers(), plotOpts.GetLayerSelection() );
2063
2064 for( PCB_LAYER_ID layer : plotOpts.GetPlotOnAllLayersSequence() )
2065 settings->add_common_layers( ToProtoEnum<PCB_LAYER_ID, board::types::BoardLayer>( layer ) );
2066
2067 settings->set_mirror( plotOpts.GetMirror() );
2068 settings->set_black_and_white( plotOpts.GetBlackAndWhite() );
2069 settings->set_negative( plotOpts.GetNegative() );
2070 settings->set_scale( plotOpts.GetScale() );
2071
2072 settings->set_sketch_pads_on_fab_layers( plotOpts.GetSketchPadsOnFabLayers() );
2073 settings->set_hide_dnp_footprints_on_fab_layers( plotOpts.GetHideDNPFPsOnFabLayers() );
2074 settings->set_sketch_dnp_footprints_on_fab_layers( plotOpts.GetSketchDNPFPsOnFabLayers() );
2075 settings->set_crossout_dnp_footprints_on_fab_layers( plotOpts.GetCrossoutDNPFPsOnFabLayers() );
2076
2077 settings->set_plot_footprint_values( plotOpts.GetPlotValue() );
2078 settings->set_plot_reference_designators( plotOpts.GetPlotReference() );
2079 settings->set_plot_drawing_sheet( plotOpts.GetPlotFrameRef() );
2080 settings->set_subtract_solder_mask_from_silk( plotOpts.GetSubtractMaskFromSilk() );
2081 settings->set_plot_pad_numbers( plotOpts.GetPlotPadNumbers() );
2082
2083 settings->set_drill_marks( ToProtoEnum<DRILL_MARKS, PlotDrillMarks>( plotOpts.GetDrillMarksType() ) );
2084 settings->set_use_drill_origin( plotOpts.GetUseAuxOrigin() );
2085
2086 return response;
2087}
2088
2089
2091{
2092 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
2093 return tl::unexpected( documentValidation.error() );
2094
2095 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2096 return tl::unexpected( *busy );
2097
2098 const BoardPlotSettings& settings = aCtx.Request.plot_settings();
2099 PCB_PLOT_PARAMS plotOpts = board()->GetPlotOptions();
2100
2101 plotOpts.SetLayerSelection( board::UnpackLayerSet( settings.layers() ) );
2102
2103 LSEQ commonLayers;
2104
2105 for( int layer : settings.common_layers() )
2106 {
2107 PCB_LAYER_ID layerId =
2108 FromProtoEnum<PCB_LAYER_ID, board::types::BoardLayer>( static_cast<board::types::BoardLayer>( layer ) );
2109
2110 if( !IsPcbLayer( layerId ) )
2111 {
2112 ApiResponseStatus e;
2113 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2114 e.set_error_message( fmt::format( "SetBoardPlotSettings contains an invalid layer {}",
2115 magic_enum::enum_name( layerId ) ) );
2116 return tl::unexpected( e );
2117 }
2118
2119 commonLayers.push_back( layerId );
2120 }
2121
2122 plotOpts.SetPlotOnAllLayersSequence( commonLayers );
2123
2124 plotOpts.SetMirror( settings.mirror() );
2125 plotOpts.SetBlackAndWhite( settings.black_and_white() );
2126 plotOpts.SetNegative( settings.negative() );
2127 plotOpts.SetScale( settings.scale() );
2128
2129 plotOpts.SetSketchPadsOnFabLayers( settings.sketch_pads_on_fab_layers() );
2130 plotOpts.SetHideDNPFPsOnFabLayers( settings.hide_dnp_footprints_on_fab_layers() );
2131 plotOpts.SetSketchDNPFPsOnFabLayers( settings.sketch_dnp_footprints_on_fab_layers() );
2132 plotOpts.SetCrossoutDNPFPsOnFabLayers( settings.crossout_dnp_footprints_on_fab_layers() );
2133
2134 plotOpts.SetPlotValue( settings.plot_footprint_values() );
2135 plotOpts.SetPlotReference( settings.plot_reference_designators() );
2136 plotOpts.SetPlotFrameRef( settings.plot_drawing_sheet() );
2137 plotOpts.SetSubtractMaskFromSilk( settings.subtract_solder_mask_from_silk() );
2138 plotOpts.SetPlotPadNumbers( settings.plot_pad_numbers() );
2139
2140 plotOpts.SetDrillMarksType( FromProtoEnum<DRILL_MARKS>( settings.drill_marks() ) );
2141 plotOpts.SetUseAuxOrigin( settings.use_drill_origin() );
2142
2143 board()->SetPlotOptions( plotOpts );
2144
2145 onModified();
2146
2147 return Empty();
2148}
2149
2150
2153{
2154 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.board() ); !documentValidation )
2155 return tl::unexpected( documentValidation.error() );
2156
2157 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2158 return tl::unexpected( *busy );
2159
2160 SEVERITY severity = FromProtoEnum<SEVERITY>( aCtx.Request.severity() );
2161 int layer = severity == RPT_SEVERITY_WARNING ? LAYER_DRC_WARNING : LAYER_DRC_ERROR;
2163
2164 std::shared_ptr<DRC_ITEM> drcItem = DRC_ITEM::Create( code );
2165
2166 drcItem->SetErrorMessage( wxString::FromUTF8( aCtx.Request.message() ) );
2167
2168 std::vector<KIID> ids;
2169
2170 for( const auto& id : aCtx.Request.items() )
2171 ids.emplace_back( KIID( id.value() ) );
2172
2173 if( !ids.empty() )
2174 drcItem->SetItems( ids );
2175
2176 const auto& pos = aCtx.Request.position();
2177 VECTOR2I position( static_cast<int>( pos.x_nm() ), static_cast<int>( pos.y_nm() ) );
2178
2179 PCB_MARKER* marker = new PCB_MARKER( drcItem, position, layer );
2180
2181 COMMIT* commit = getCurrentCommit( aCtx.ClientName );
2182 commit->Add( marker );
2183
2184 if( !m_activeClients.count( aCtx.ClientName ) )
2185 pushCurrentCommit( aCtx.ClientName, _( "API injected DRC marker" ) );
2186
2187 InjectDrcErrorResponse response;
2188 response.mutable_marker()->set_value( marker->GetUUID().AsStdString() );
2189
2190 return response;
2191}
2192
2193
2194std::optional<ApiResponseStatus> ValidateUnitsInchMm( types::Units aUnits,
2195 const std::string& aCommandName )
2196{
2197 if( aUnits == types::Units::U_INCH || aUnits == types::Units::U_MM
2198 || aUnits == types::Units::U_UNKNOWN )
2199 {
2200 return std::nullopt;
2201 }
2202
2203 ApiResponseStatus e;
2204 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2205 e.set_error_message( fmt::format( "{} supports only inch and mm units", aCommandName ) );
2206 return e;
2207}
2208
2209
2210std::optional<ApiResponseStatus>
2211ValidatePaginationModeForSingleOrPerFile( kiapi::board::jobs::BoardJobPaginationMode aMode,
2212 const std::string& aCommandName )
2213{
2214 if( aMode == kiapi::board::jobs::BoardJobPaginationMode::BJPM_UNKNOWN
2215 || aMode == kiapi::board::jobs::BoardJobPaginationMode::BJPM_ALL_LAYERS_ONE_PAGE
2216 || aMode == kiapi::board::jobs::BoardJobPaginationMode::BJPM_EACH_LAYER_OWN_FILE )
2217 {
2218 return std::nullopt;
2219 }
2220
2221 ApiResponseStatus e;
2222 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2223 e.set_error_message( fmt::format( "{} does not support EACH_LAYER_OWN_PAGE pagination mode",
2224 aCommandName ) );
2225 return e;
2226}
2227
2228
2229std::optional<ApiResponseStatus> ApplyBoardPlotSettings( const BoardPlotSettings& aSettings,
2230 JOB_EXPORT_PCB_PLOT& aJob )
2231{
2232 for( int layer : aSettings.layers() )
2233 {
2235 static_cast<board::types::BoardLayer>( layer ) );
2236
2237 if( !IsPcbLayer( static_cast<int>( layerId ) ) )
2238 {
2239 ApiResponseStatus e;
2240 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2241 e.set_error_message( "Board plot settings contain an invalid layer" );
2242 return e;
2243 }
2244
2245 aJob.m_plotLayerSequence.push_back( layerId );
2246 }
2247
2248 for( int layer : aSettings.common_layers() )
2249 {
2251 static_cast<board::types::BoardLayer>( layer ) );
2252
2253 if( !IsPcbLayer( static_cast<int>( layerId ) ) )
2254 {
2255 ApiResponseStatus e;
2256 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2257 e.set_error_message( "Board plot settings contain an invalid common layer" );
2258 return e;
2259 }
2260
2261 aJob.m_plotOnAllLayersSequence.push_back( layerId );
2262 }
2263
2264 aJob.m_colorTheme = wxString::FromUTF8( aSettings.color_theme() );
2265 aJob.m_drawingSheet = wxString::FromUTF8( aSettings.drawing_sheet() );
2266 aJob.m_variant = wxString::FromUTF8( aSettings.variant() );
2267
2268 aJob.m_mirror = aSettings.mirror();
2269 aJob.m_blackAndWhite = aSettings.black_and_white();
2270 aJob.m_negative = aSettings.negative();
2271 aJob.m_scale = aSettings.scale();
2272
2273 aJob.m_sketchPadsOnFabLayers = aSettings.sketch_pads_on_fab_layers();
2274 aJob.m_hideDNPFPsOnFabLayers = aSettings.hide_dnp_footprints_on_fab_layers();
2275 aJob.m_sketchDNPFPsOnFabLayers = aSettings.sketch_dnp_footprints_on_fab_layers();
2276 aJob.m_crossoutDNPFPsOnFabLayers = aSettings.crossout_dnp_footprints_on_fab_layers();
2277
2278 aJob.m_plotFootprintValues = aSettings.plot_footprint_values();
2279 aJob.m_plotRefDes = aSettings.plot_reference_designators();
2280 aJob.m_plotDrawingSheet = aSettings.plot_drawing_sheet();
2281 aJob.m_subtractSolderMaskFromSilk = aSettings.subtract_solder_mask_from_silk();
2282 aJob.m_plotPadNumbers = aSettings.plot_pad_numbers();
2283
2284 aJob.m_drillShapeOption = FromProtoEnum<DRILL_MARKS>( aSettings.drill_marks() );
2285
2286 aJob.m_useDrillOrigin = aSettings.use_drill_origin();
2287 aJob.m_checkZonesBeforePlot = aSettings.check_zones_before_plot();
2288
2289 return std::nullopt;
2290}
2291
2292
2294{
2295 types::RunJobResponse response;
2297
2298 if( !aContext || !aContext->GetKiway() )
2299 {
2300 response.set_status( types::JobStatus::JS_ERROR );
2301 response.set_message( "Internal error" );
2302 wxCHECK_MSG( false, response, "context missing valid kiway in ExecuteBoardJob?" );
2303 return response;
2304 }
2305
2306 int exitCode = aContext->GetKiway()->ProcessJob( KIWAY::FACE_PCB, &aJob, &reporter );
2307
2308 for( const JOB_OUTPUT& output : aJob.GetOutputs() )
2309 response.add_output_path( output.m_outputPath.ToUTF8() );
2310
2311 if( exitCode == 0 )
2312 {
2313 response.set_status( types::JobStatus::JS_SUCCESS );
2314 return response;
2315 }
2316
2317 response.set_status( types::JobStatus::JS_ERROR );
2318 response.set_message( fmt::format( "Board export job '{}' failed with exit code {}: {}",
2319 aJob.GetType(), exitCode,
2320 reporter.GetMessages().ToStdString() ) );
2321 return response;
2322}
2323
2324
2327{
2328 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2329 return tl::unexpected( validation.error() );
2330
2331 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2332 return tl::unexpected( *busy );
2333
2336 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2337
2339
2340 job.m_variant = wxString::FromUTF8( aCtx.Request.variant() );
2341 job.m_3dparams.m_NetFilter = wxString::FromUTF8( aCtx.Request.net_filter() );
2342 job.m_3dparams.m_ComponentFilter = wxString::FromUTF8( aCtx.Request.component_filter() );
2343
2344 job.m_hasUserOrigin = aCtx.Request.has_user_origin();
2345 job.m_3dparams.m_Origin = VECTOR2D( aCtx.Request.origin().x_nm(), aCtx.Request.origin().y_nm() );
2346
2347 job.m_3dparams.m_Overwrite = aCtx.Request.overwrite();
2348 job.m_3dparams.m_UseGridOrigin = aCtx.Request.use_grid_origin();
2349 job.m_3dparams.m_UseDrillOrigin = aCtx.Request.use_drill_origin();
2350 job.m_3dparams.m_UseDefinedOrigin = aCtx.Request.use_defined_origin() || aCtx.Request.has_user_origin();
2351 job.m_3dparams.m_UsePcbCenterOrigin = aCtx.Request.use_pcb_center_origin();
2352
2353 job.m_3dparams.m_IncludeUnspecified = aCtx.Request.include_unspecified();
2354 job.m_3dparams.m_IncludeDNP = aCtx.Request.include_dnp();
2355 job.m_3dparams.m_SubstModels = aCtx.Request.substitute_models();
2356
2357 job.m_3dparams.m_BoardOutlinesChainingEpsilon = aCtx.Request.board_outlines_chaining_epsilon();
2358 job.m_3dparams.m_BoardOnly = aCtx.Request.board_only();
2359 job.m_3dparams.m_CutViasInBody = aCtx.Request.cut_vias_in_body();
2360 job.m_3dparams.m_ExportBoardBody = aCtx.Request.export_board_body();
2361 job.m_3dparams.m_ExportComponents = aCtx.Request.export_components();
2362 job.m_3dparams.m_ExportTracksVias = aCtx.Request.export_tracks_and_vias();
2363 job.m_3dparams.m_ExportPads = aCtx.Request.export_pads();
2364 job.m_3dparams.m_ExportZones = aCtx.Request.export_zones();
2365 job.m_3dparams.m_ExportInnerCopper = aCtx.Request.export_inner_copper();
2366 job.m_3dparams.m_ExportSilkscreen = aCtx.Request.export_silkscreen();
2367 job.m_3dparams.m_ExportSoldermask = aCtx.Request.export_soldermask();
2368 job.m_3dparams.m_FuseShapes = aCtx.Request.fuse_shapes();
2369 job.m_3dparams.m_FillAllVias = aCtx.Request.fill_all_vias();
2370 job.m_3dparams.m_OptimizeStep = aCtx.Request.optimize_step();
2371 job.m_3dparams.m_ExtraPadThickness = aCtx.Request.extra_pad_thickness();
2372
2374
2375 job.m_vrmlModelDir = wxString::FromUTF8( aCtx.Request.vrml_model_dir() );
2376 job.m_vrmlRelativePaths = aCtx.Request.vrml_relative_paths();
2377
2378 return ExecuteBoardJob( pcbContext(), job );
2379}
2380
2381
2384{
2385 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2386 return tl::unexpected( validation.error() );
2387
2388 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2389 return tl::unexpected( *busy );
2390
2391 JOB_PCB_RENDER job;
2393 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2394
2397 job.m_bgStyle = FromProtoEnum<JOB_PCB_RENDER::BG_STYLE>( aCtx.Request.background_style() );
2398
2399 job.m_width = aCtx.Request.width();
2400 job.m_height = aCtx.Request.height();
2401 job.m_appearancePreset = aCtx.Request.appearance_preset();
2402 job.m_useBoardStackupColors = aCtx.Request.use_board_stackup_colors();
2403
2405
2406 job.m_zoom = aCtx.Request.zoom();
2407 job.m_perspective = aCtx.Request.perspective();
2408
2409 job.m_rotation = UnpackVector3D( aCtx.Request.rotation() );
2410 job.m_pan = UnpackVector3D( aCtx.Request.pan() );
2411 job.m_pivot = UnpackVector3D( aCtx.Request.pivot() );
2412
2413 job.m_proceduralTextures = aCtx.Request.procedural_textures();
2414 job.m_floor = aCtx.Request.floor();
2415 job.m_antiAlias = aCtx.Request.anti_alias();
2416 job.m_postProcess = aCtx.Request.post_process();
2417
2418 job.m_lightTopIntensity = UnpackVector3D( aCtx.Request.light_top_intensity() );
2419 job.m_lightBottomIntensity = UnpackVector3D( aCtx.Request.light_bottom_intensity() );
2420 job.m_lightCameraIntensity = UnpackVector3D( aCtx.Request.light_camera_intensity() );
2421 job.m_lightSideIntensity = UnpackVector3D( aCtx.Request.light_side_intensity() );
2422 job.m_lightSideElevation = aCtx.Request.light_side_elevation();
2423
2424 return ExecuteBoardJob( pcbContext(), job );
2425}
2426
2427
2430{
2431 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2432 return tl::unexpected( validation.error() );
2433
2434 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2435 return tl::unexpected( *busy );
2436
2439 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2440
2441 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2442 return tl::unexpected( *err );
2443
2444 job.m_fitPageToBoard = aCtx.Request.fit_page_to_board();
2445 job.m_precision = aCtx.Request.precision();
2446
2447 if( std::optional<ApiResponseStatus> paginationError =
2449 "RunBoardJobExportSvg" ) )
2450 {
2451 return tl::unexpected( *paginationError );
2452 }
2453
2455
2456 return ExecuteBoardJob( pcbContext(), job );
2457}
2458
2459
2462{
2463 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2464 return tl::unexpected( validation.error() );
2465
2466 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2467 return tl::unexpected( *busy );
2468
2471 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2472
2473 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2474 return tl::unexpected( *err );
2475
2476 job.m_plotGraphicItemsUsingContours = aCtx.Request.plot_graphic_items_using_contours();
2477 job.m_polygonMode = aCtx.Request.polygon_mode();
2478
2479 if( std::optional<ApiResponseStatus> unitError =
2480 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportDxf" ) )
2481 {
2482 return tl::unexpected( *unitError );
2483 }
2484
2486
2487 if( std::optional<ApiResponseStatus> paginationError =
2489 "RunBoardJobExportDxf" ) )
2490 {
2491 return tl::unexpected( *paginationError );
2492 }
2493
2495
2496 return ExecuteBoardJob( pcbContext(), job );
2497}
2498
2499
2502{
2503 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2504 return tl::unexpected( validation.error() );
2505
2506 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2507 return tl::unexpected( *busy );
2508
2511 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2512
2513 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2514 return tl::unexpected( *err );
2515
2516 job.m_pdfFrontFPPropertyPopups = aCtx.Request.front_footprint_property_popups();
2517 job.m_pdfBackFPPropertyPopups = aCtx.Request.back_footprint_property_popups();
2518 job.m_pdfMetadata = aCtx.Request.include_metadata();
2519 job.m_pdfSingle = aCtx.Request.single_document();
2520 job.m_pdfBackgroundColor = wxString::FromUTF8( aCtx.Request.background_color() );
2521
2523
2524 return ExecuteBoardJob( pcbContext(), job );
2525}
2526
2527
2530{
2531 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2532 return tl::unexpected( validation.error() );
2533
2534 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2535 return tl::unexpected( *busy );
2536
2539 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2540
2541 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2542 return tl::unexpected( *err );
2543
2544 if( std::optional<ApiResponseStatus> paginationError =
2546 "RunBoardJobExportPs" ) )
2547 {
2548 return tl::unexpected( *paginationError );
2549 }
2550
2552
2553 job.m_trackWidthCorrection = aCtx.Request.track_width_correction();
2554 job.m_XScaleAdjust = aCtx.Request.x_scale_adjust();
2555 job.m_YScaleAdjust = aCtx.Request.y_scale_adjust();
2556 job.m_forceA4 = aCtx.Request.force_a4();
2557 job.m_useGlobalSettings = aCtx.Request.use_global_settings();
2558
2559 return ExecuteBoardJob( pcbContext(), job );
2560}
2561
2562
2565{
2566 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2567 return tl::unexpected( validation.error() );
2568
2569 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2570 return tl::unexpected( *busy );
2571
2574 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2575
2576 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2577 return tl::unexpected( *err );
2578
2579 if( std::optional<ApiResponseStatus> paginationError =
2580 ValidatePaginationModeForSingleOrPerFile( aCtx.Request.page_mode(), "RunBoardJobExportPng" ) )
2581 {
2582 return tl::unexpected( *paginationError );
2583 }
2584
2586
2587 if( aCtx.Request.has_dpi() )
2588 {
2589 int dpi = aCtx.Request.dpi();
2590
2591 if( dpi < MIN_PNG_DPI || dpi > MAX_PNG_DPI )
2592 {
2593 ApiResponseStatus status;
2594 status.set_status( ApiStatusCode::AS_BAD_REQUEST );
2595 status.set_error_message( fmt::format( "dpi must be between {} and {}", MIN_PNG_DPI, MAX_PNG_DPI ) );
2596 return tl::unexpected( status );
2597 }
2598
2599 job.m_dpi = dpi;
2600 }
2601
2602 // Unknown -> default AA on
2603 job.m_antialias = aCtx.Request.antialiasing() != types::AntialiasingMode::AAM_NONE;
2604 job.m_useBackgroundColor = aCtx.Request.plot_background_color();
2605
2606 return ExecuteBoardJob( pcbContext(), job );
2607}
2608
2609
2612{
2613 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2614 return tl::unexpected( validation.error() );
2615
2616 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2617 return tl::unexpected( *busy );
2618
2621 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2622
2623 job.m_useBoardPlotParams = aCtx.Request.use_board_plot_params();
2624
2625 if( !job.m_useBoardPlotParams )
2626 {
2627 if( std::optional<ApiResponseStatus> err = ApplyBoardPlotSettings( aCtx.Request.plot_settings(), job ) )
2628 return tl::unexpected( *err );
2629 }
2630
2631 job.m_createJobsFile = aCtx.Request.create_gerber_job_file();
2632 job.m_includeNetlistAttributes = aCtx.Request.include_netlist_attributes();
2633 job.m_useX2Format = aCtx.Request.use_x2_format();
2634 job.m_disableApertureMacros = aCtx.Request.disable_aperture_macros();
2635 job.m_useProtelFileExtension = aCtx.Request.use_protel_file_extensions();
2636
2637 switch( aCtx.Request.precision() )
2638 {
2639 default:
2640 case GerberPrecision::GP_5: job.m_precision = 5; break;
2641 case GerberPrecision::GP_6: job.m_precision = 6; break;
2642 }
2643
2644 return ExecuteBoardJob( pcbContext(), job );
2645}
2646
2647
2650{
2651 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2652 return tl::unexpected( validation.error() );
2653
2654 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2655 return tl::unexpected( *busy );
2656
2659 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2660
2662
2663 if( std::optional<ApiResponseStatus> unitError =
2664 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportDrill" ) )
2665 {
2666 return tl::unexpected( *unitError );
2667 }
2668
2672
2673 if( aCtx.Request.has_excellon() )
2674 {
2675 const ExcellonFormatOptions& excellonOptions = aCtx.Request.excellon();
2676
2677 if( excellonOptions.has_mirror_y() )
2678 job.m_excellonMirrorY = excellonOptions.mirror_y();
2679
2680 if( excellonOptions.has_minimal_header() )
2681 job.m_excellonMinimalHeader = excellonOptions.minimal_header();
2682
2683 if( excellonOptions.has_combine_pth_npth() )
2684 job.m_excellonCombinePTHNPTH = excellonOptions.combine_pth_npth();
2685
2686 if( excellonOptions.has_route_oval_holes() )
2687 job.m_excellonOvalDrillRoute = excellonOptions.route_oval_holes();
2688 }
2689
2690 if( aCtx.Request.map_format() != DrillMapFormat::DMF_UNKNOWN )
2691 {
2692 job.m_generateMap = true;
2694 }
2695
2696 job.m_gerberPrecision = aCtx.Request.gerber_precision() == DrillGerberPrecision::DGP_4_5 ? 5 : 6;
2697
2698 if( aCtx.Request.has_gerber_generate_tenting() )
2699 job.m_generateTenting = aCtx.Request.gerber_generate_tenting();
2700
2701 if( aCtx.Request.report_format() != DrillReportFormat::DRF_UNKNOWN )
2702 {
2703 job.m_generateReport = true;
2704
2705 if( aCtx.Request.has_report_filename() )
2706 job.m_reportPath = wxString::FromUTF8( aCtx.Request.report_filename() );
2707 }
2708
2709 return ExecuteBoardJob( pcbContext(), job );
2710}
2711
2712
2715{
2716 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2717 return tl::unexpected( validation.error() );
2718
2719 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2720 return tl::unexpected( *busy );
2721
2724 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2725
2726 if( aCtx.Request.has_use_drill_place_file_origin() )
2727 job.m_useDrillPlaceFileOrigin = aCtx.Request.use_drill_place_file_origin();
2728
2729 job.m_smdOnly = aCtx.Request.smd_only();
2730 job.m_excludeFootprintsWithTh = aCtx.Request.exclude_footprints_with_th();
2731 job.m_excludeDNP = aCtx.Request.exclude_dnp();
2732 job.m_excludeBOM = aCtx.Request.exclude_from_bom();
2733 job.m_negateBottomX = aCtx.Request.negate_bottom_x();
2734 job.m_singleFile = aCtx.Request.single_file();
2735 job.m_nakedFilename = aCtx.Request.naked_filename();
2736 if( aCtx.Request.has_include_board_edge_for_gerber() )
2737 job.m_gerberBoardEdge = aCtx.Request.include_board_edge_for_gerber();
2738
2739 job.m_variant = wxString::FromUTF8( aCtx.Request.variant() );
2740
2742
2743 if( std::optional<ApiResponseStatus> unitError =
2744 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportPosition" ) )
2745 {
2746 return tl::unexpected( *unitError );
2747 }
2748
2751
2752 return ExecuteBoardJob( pcbContext(), job );
2753}
2754
2755
2758{
2759 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2760 return tl::unexpected( validation.error() );
2761
2762 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2763 return tl::unexpected( *busy );
2764
2767 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2768
2769 job.m_flipBottomPads = aCtx.Request.flip_bottom_pads();
2770 job.m_useIndividualShapes = aCtx.Request.use_individual_shapes();
2771 job.m_storeOriginCoords = aCtx.Request.store_origin_coords();
2772 job.m_useDrillOrigin = aCtx.Request.use_drill_origin();
2773 job.m_useUniquePins = aCtx.Request.use_unique_pins();
2774
2775 return ExecuteBoardJob( pcbContext(), job );
2776}
2777
2778
2781{
2782 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2783 return tl::unexpected( validation.error() );
2784
2785 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2786 return tl::unexpected( *busy );
2787
2790 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2791
2792 return ExecuteBoardJob( pcbContext(), job );
2793}
2794
2795
2798{
2799 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2800 return tl::unexpected( validation.error() );
2801
2802 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2803 return tl::unexpected( *busy );
2804
2807 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2808
2809 job.m_drawingSheet = wxString::FromUTF8( aCtx.Request.drawing_sheet() );
2810 if( !aCtx.Request.variant().empty() )
2811 {
2812 job.m_variantNames.push_back( wxString::FromUTF8( aCtx.Request.variant() ) );
2813 }
2814
2815 if( aCtx.Request.has_precision() )
2816 job.m_precision = aCtx.Request.precision();
2817
2818 job.m_compress = aCtx.Request.compress();
2819 job.m_colInternalId = wxString::FromUTF8( aCtx.Request.internal_id_column() );
2820 job.m_colMfgPn = wxString::FromUTF8( aCtx.Request.manufacturer_part_number_column() );
2821 job.m_colMfg = wxString::FromUTF8( aCtx.Request.manufacturer_column() );
2822 job.m_colDistPn = wxString::FromUTF8( aCtx.Request.distributor_part_number_column() );
2823 job.m_colDist = wxString::FromUTF8( aCtx.Request.distributor_column() );
2824 job.m_bomRev = wxString::FromUTF8( aCtx.Request.bom_revision() );
2825
2826 if( std::optional<ApiResponseStatus> unitError =
2827 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportIpc2581" ) )
2828 {
2829 return tl::unexpected( *unitError );
2830 }
2831
2833 job.m_checkZonesBeforeExport = aCtx.Request.check_zones();
2836 ApplyFabExportContent( aCtx.Request.content(), job );
2837
2838 return ExecuteBoardJob( pcbContext(), job );
2839}
2840
2841
2844{
2845 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2846 return tl::unexpected( validation.error() );
2847
2848 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2849 return tl::unexpected( *busy );
2850
2853 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2854
2855 return ExecuteBoardJob( pcbContext(), job );
2856}
2857
2858
2859void ApplyFabExportContent( const FabExportContent& aContent, JOB_EXPORT_PCB_FAB& aJob )
2860{
2861 aJob.m_dataSet = FromProtoEnum<JOB_EXPORT_PCB_FAB::DATA_SET>( aContent.data_set() );
2862 aJob.m_sections = aContent.sections().empty()
2863 ? std::nullopt
2864 : std::optional<wxString>( wxString::FromUTF8( aContent.sections() ) );
2865 aJob.m_netNames = FromProtoEnum<JOB_EXPORT_PCB_FAB::NET_NAMES>( aContent.net_names() );
2866}
2867
2868
2869void ApplyOdbJobRequest( const RunBoardJobExportODB& aRequest, JOB_EXPORT_PCB_ODB& aJob )
2870{
2871 aJob.m_drawingSheet = wxString::FromUTF8( aRequest.drawing_sheet() );
2872
2873 if( aRequest.variant_names_size() > 0 )
2874 {
2875 for( const std::string& name : aRequest.variant_names() )
2876 aJob.m_variantNames.push_back( wxString::FromUTF8( name ) );
2877 }
2878 else if( !aRequest.variant().empty() )
2879 {
2880 aJob.m_variantNames.push_back( wxString::FromUTF8( aRequest.variant() ) );
2881 }
2882
2884 aRequest.variant_packaging() );
2885
2886 if( aRequest.has_precision() )
2887 aJob.m_precision = aRequest.precision();
2888
2889 aJob.m_units = FromProtoEnum<JOB_EXPORT_PCB_FAB::UNITS>( aRequest.units() );
2890 aJob.m_checkZonesBeforeExport = aRequest.check_zones();
2892 aJob.m_colMfgPn = wxString::FromUTF8( aRequest.manufacturer_part_number_column() );
2893 aJob.m_origin = FromProtoEnum<JOB_EXPORT_PCB_ODB::ORIGIN>( aRequest.origin() );
2894 aJob.m_productName = wxString::FromUTF8( aRequest.product_name() );
2895 ApplyFabExportContent( aRequest.content(), aJob );
2896}
2897
2898
2901{
2902 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2903 return tl::unexpected( validation.error() );
2904
2905 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2906 return tl::unexpected( *busy );
2907
2910 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2911
2912 if( std::optional<ApiResponseStatus> unitError =
2913 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportODB" ) )
2914 {
2915 return tl::unexpected( *unitError );
2916 }
2917
2918 ApplyOdbJobRequest( aCtx.Request, job );
2919
2920 return ExecuteBoardJob( pcbContext(), job );
2921}
2922
2923
2926{
2927 if( HANDLER_RESULT<bool> validation = validateDocument( aCtx.Request.job_settings().document() ); !validation )
2928 return tl::unexpected( validation.error() );
2929
2930 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2931 return tl::unexpected( *busy );
2932
2935 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2936
2938
2939 if( std::optional<ApiResponseStatus> unitError =
2940 ValidateUnitsInchMm( aCtx.Request.units(), "RunBoardJobExportStats" ) )
2941 {
2942 return tl::unexpected( *unitError );
2943 }
2944
2946
2947 job.m_excludeFootprintsWithoutPads = aCtx.Request.exclude_footprints_without_pads();
2948 job.m_subtractHolesFromBoardArea = aCtx.Request.subtract_holes_from_board_area();
2949 job.m_subtractHolesFromCopperAreas = aCtx.Request.subtract_holes_from_copper_areas();
2950
2951 return ExecuteBoardJob( pcbContext(), job );
2952}
2953
2954
2957{
2958 if( HANDLER_RESULT<bool> valid = validateDocument( aCtx.Request.job_settings().document() ); !valid )
2959 return tl::unexpected( valid.error() );
2960
2961 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
2962 return tl::unexpected( *busy );
2963
2964 switch( aCtx.Request.units() )
2965 {
2966 case types::Units::U_UNKNOWN:
2967 case types::Units::U_MM:
2968 case types::Units::U_MILS:
2969 break;
2970
2971 default:
2972 {
2973 ApiResponseStatus e;
2974 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
2975 e.set_error_message( "RunBoardJobExportIdf supports only mm and mils units" );
2976 return tl::unexpected( e );
2977 }
2978 }
2979
2982 job.SetConfiguredOutputPath( wxString::FromUTF8( aCtx.Request.job_settings().output_path() ) );
2983
2986
2987 if( aCtx.Request.origin_mode() == IdfOriginMode::IOM_USER )
2988 {
2989 // m_userOrigin is expressed in the units selected by m_units
2990 double scale = job.m_units == IDF_SETTINGS::UNITS::MM ? pcbIUScale.MM_PER_IU : pcbIUScale.MILS_PER_IU;
2991 job.m_userOrigin = UnpackVector2( aCtx.Request.user_origin() ) * scale;
2992 }
2993
2994 job.m_includeUnspecified = aCtx.Request.include_unspecified();
2995 job.m_includeDNP = aCtx.Request.include_dnp();
2996 job.m_calculateHeightFromModels = !aCtx.Request.only_use_explicit_heights();
2997
2998 if( aCtx.Request.has_part_number_field() )
2999 job.m_partNumberField = wxString::FromUTF8( aCtx.Request.part_number_field() );
3000 else
3001 job.m_partNumberField = wxS( "Value" );
3002
3003 return ExecuteBoardJob( pcbContext(), job );
3004}
3005
3006
3009{
3010 wxLogTrace( traceApi, "Received announce from frame %d at %s",
3011 aCtx.Request.frame_type(), aCtx.Request.socket_path() );
3012
3013 CROSS_PROBE_CLIENT::RegisterPeer( static_cast<FRAME_T>( aCtx.Request.frame_type() ),
3014 aCtx.Request.socket_path() );
3015
3016 CrossProbeAnnounceResponse response;
3017 response.set_status( CPS_OK );
3018 return response;
3019}
3020
3021
3023{
3024 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "SyncSelection" ) )
3025 return tl::unexpected( *headless );
3026
3027 SyncSelectionResponse response;
3028
3030
3031 if( !settings.on_selection && aCtx.Request.context() != SyncSelectionContext::SSC_EXPLICIT )
3032 {
3033 response.set_status( CPS_DISABLED );
3034 response.set_message( "implicit selection sync disabled by user" );
3035 return response;
3036 }
3037
3038 std::vector<BOARD_ITEM*> items =
3040
3041 frame()->m_ProbingSchToPcb = true; // recursion guard
3042
3043 if( aCtx.Request.mode() == SyncSelectionMode::SSM_ITEMS_AND_NETS )
3045 else
3047
3048 // Update 3D viewer highlighting
3049 frame()->Update3DView( false, frame()->GetPcbNewSettings()->m_Display.m_Live3DRefresh );
3050
3051 frame()->m_ProbingSchToPcb = false;
3052
3053 if( settings.flash_selection )
3054 {
3055 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE) PCB: flash enabled, items=%zu", items.size() );
3056 if( items.empty() )
3057 {
3058 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE) PCB: nothing to flash" );
3059 }
3060 else
3061 {
3062 std::vector<BOARD_ITEM*> boardItems;
3063 std::copy( items.begin(), items.end(), std::back_inserter( boardItems ) );
3064 frame()->StartCrossProbeFlash( boardItems );
3065 }
3066 }
3067 else
3068 {
3069 wxLogTrace( traceCrossProbeFlash, "MAIL_SELECTION(_FORCE) PCB: flash disabled" );
3070 }
3071
3072 response.set_status( CPS_OK );
3073 return response;
3074}
3075
3076
3078 const HANDLER_CONTEXT<HighlightNets>& aCtx )
3079{
3080 if( std::optional<ApiResponseStatus> headless = checkForHeadless( "HighlightNets" ) )
3081 return tl::unexpected( *headless );
3082
3083 HighlightNetsResponse response;
3084 CROSS_PROBING_SETTINGS& crossProbingSettings = frame()->GetPcbNewSettings()->m_CrossProbing;
3085
3087 || aCtx.ClientName == KiwayClientName )
3088 {
3089 if( !crossProbingSettings.auto_highlight )
3090 {
3091 response.set_status( CPS_DISABLED );
3092 response.set_message( "net highlight cross-probing disabled by user" );
3093 return response;
3094 }
3095 }
3096
3097 std::vector<wxString> nets;
3098
3099 for( const std::string& name : aCtx.Request.net_name() )
3100 nets.emplace_back( wxString::FromUTF8( name ) );
3101
3103
3104 response.set_status( CPS_OK );
3105 return response;
3106}
3107
3108
3110{
3111 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3112 return tl::unexpected( documentValidation.error() );
3113
3114 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3115 return tl::unexpected( *busy );
3116
3118 VariantsResponse response;
3119
3120 response.mutable_document()->CopyFrom( aCtx.Request.document() );
3121
3122 for( const wxString& name : board->GetVariantNames() )
3123 {
3124 types::DesignVariant* var = response.add_variants();
3125 var->set_name( name.ToUTF8() );
3126 var->set_description( board->GetVariantDescription( name ).ToUTF8() );
3127 }
3128
3129 return response;
3130}
3131
3132
3134{
3135 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3136 return tl::unexpected( documentValidation.error() );
3137
3138 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3139 return tl::unexpected( *busy );
3140
3142
3143 wxString name = wxString::FromUTF8( aCtx.Request.name() );
3144
3145 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 )
3146 {
3147 ApiResponseStatus e;
3148 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3149 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.name() ) );
3150 return tl::unexpected( e );
3151 }
3152
3153 if( board->HasVariant( name ) )
3154 {
3155 ApiResponseStatus e;
3156 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3157 e.set_error_message( fmt::format( "a variant named '{}' already exists", aCtx.Request.name() ) );
3158 return tl::unexpected( e );
3159 }
3160
3161 board->AddVariant( name );
3162
3163 if( aCtx.Request.has_description() )
3164 board->SetVariantDescription( name, wxString::FromUTF8( aCtx.Request.description() ) );
3165
3166 onModified();
3167
3168 if( frame() )
3170
3171 return Empty();
3172}
3173
3174
3176{
3177 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3178 return tl::unexpected( documentValidation.error() );
3179
3180 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3181 return tl::unexpected( *busy );
3182
3184
3185 wxString name = wxString::FromUTF8( aCtx.Request.name() );
3186
3187 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 )
3188 {
3189 ApiResponseStatus e;
3190 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3191 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.name() ) );
3192 return tl::unexpected( e );
3193 }
3194
3195 if( !board->HasVariant( name ) )
3196 {
3197 ApiResponseStatus e;
3198 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3199 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
3200 return tl::unexpected( e );
3201 }
3202
3203 board->DeleteVariant( name );
3204
3205 onModified();
3206
3207 if( frame() )
3209
3210 return Empty();
3211}
3212
3213
3215{
3216 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3217 return tl::unexpected( documentValidation.error() );
3218
3219 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3220 return tl::unexpected( *busy );
3221
3223
3224 wxString oldName = wxString::FromUTF8( aCtx.Request.old_name() );
3225 wxString newName = wxString::FromUTF8( aCtx.Request.new_name() );
3226
3227 if( oldName.IsEmpty() || oldName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3228 {
3229 ApiResponseStatus e;
3230 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3231 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.old_name() ) );
3232 return tl::unexpected( e );
3233 }
3234
3235 if( newName.IsEmpty() || newName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3236 {
3237 ApiResponseStatus e;
3238 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3239 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.new_name() ) );
3240 return tl::unexpected( e );
3241 }
3242
3243 if( !board->HasVariant( oldName ) )
3244 {
3245 ApiResponseStatus e;
3246 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3247 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.old_name() ) );
3248 return tl::unexpected( e );
3249 }
3250
3251 if( board->HasVariant( newName ) )
3252 {
3253 ApiResponseStatus e;
3254 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3255 e.set_error_message( fmt::format( "a variant named '{}' already exists", aCtx.Request.new_name() ) );
3256 return tl::unexpected( e );
3257 }
3258
3259 board->RenameVariant( oldName, newName );
3260
3261 onModified();
3262
3263 if( frame() )
3265
3266 return Empty();
3267}
3268
3269
3271{
3272 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3273 return tl::unexpected( documentValidation.error() );
3274
3275 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3276 return tl::unexpected( *busy );
3277
3279
3280 wxString oldName = wxString::FromUTF8( aCtx.Request.old_name() );
3281 wxString newName = wxString::FromUTF8( aCtx.Request.new_name() );
3282
3283 if( oldName.IsEmpty() || oldName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3284 {
3285 ApiResponseStatus e;
3286 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3287 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.old_name() ) );
3288 return tl::unexpected( e );
3289 }
3290
3291 if( newName.IsEmpty() || newName.CmpNoCase( GetDefaultVariantName() ) == 0 )
3292 {
3293 ApiResponseStatus e;
3294 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3295 e.set_error_message( fmt::format( "'{}' is not a valid variant name", aCtx.Request.new_name() ) );
3296 return tl::unexpected( e );
3297 }
3298
3299 if( !board->HasVariant( oldName ) )
3300 {
3301 ApiResponseStatus e;
3302 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3303 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.old_name() ) );
3304 return tl::unexpected( e );
3305 }
3306
3307 if( board->HasVariant( newName ) )
3308 {
3309 ApiResponseStatus e;
3310 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3311 e.set_error_message( fmt::format( "a variant named '{}' already exists", aCtx.Request.new_name() ) );
3312 return tl::unexpected( e );
3313 }
3314
3315 board->CopyVariant( oldName, newName,
3316 aCtx.Request.has_new_description() ? wxString::FromUTF8( aCtx.Request.new_description() )
3317 : wxString() );
3318
3319 onModified();
3320
3321 if( frame() )
3323
3324 return Empty();
3325}
3326
3327
3329{
3330 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3331 return tl::unexpected( documentValidation.error() );
3332
3333 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3334 return tl::unexpected( *busy );
3335
3337
3338 wxString name = wxString::FromUTF8( aCtx.Request.name() );
3339
3340 if( name.IsEmpty() || name.CmpNoCase( GetDefaultVariantName() ) == 0 || !board->HasVariant( name ) )
3341 {
3342 ApiResponseStatus e;
3343 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3344 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
3345 return tl::unexpected( e );
3346 }
3347
3348 board->SetVariantDescription( name, wxString::FromUTF8( aCtx.Request.description() ) );
3349
3350 onModified();
3351
3352 return Empty();
3353}
3354
3355
3357{
3358 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3359 return tl::unexpected( documentValidation.error() );
3360
3361 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3362 return tl::unexpected( *busy );
3363
3365
3366 if( aCtx.Request.has_name() && !aCtx.Request.name().empty() )
3367 {
3368 if( wxString name = wxString::FromUTF8( aCtx.Request.name() ); !board->HasVariant( name ) )
3369 {
3370 ApiResponseStatus e;
3371 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3372 e.set_error_message( fmt::format( "no variant named '{}' exists", aCtx.Request.name() ) );
3373 return tl::unexpected( e );
3374 }
3375 }
3376
3377 wxString varName = aCtx.Request.has_name() ? wxString::FromUTF8( aCtx.Request.name() ) : wxString();
3378
3379 if( frame() )
3380 frame()->SetCurrentVariant( varName );
3381 else
3382 board->SetCurrentVariant( varName );
3383
3384 return Empty();
3385}
3386
3387
3390{
3391 if( HANDLER_RESULT<bool> documentValidation = validateDocument( aCtx.Request.document() ); !documentValidation )
3392 return tl::unexpected( documentValidation.error() );
3393
3394 CurrentVariantResponse response;
3395
3396 if( wxString current = pcbContext()->GetBoard()->GetCurrentVariant(); !current.IsEmpty() )
3397 response.set_name( current.ToUTF8() );
3398
3399 return response;
3400}
3401
3402
3405{
3406 if( !validateItemHeaderDocument( aCtx.Request.header() ) )
3407 {
3408 ApiResponseStatus e;
3409 e.set_status( ApiStatusCode::AS_UNHANDLED );
3410 return tl::unexpected( e );
3411 }
3412
3413 if( std::optional<ApiResponseStatus> busy = checkForBusy() )
3414 return tl::unexpected( *busy );
3415
3416 LIB_ID libId = UnpackLibId( aCtx.Request.lib_id() );
3417
3418 if( !libId.IsValid() )
3419 {
3420 ApiResponseStatus e;
3421 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3422 e.set_error_message( "lib_id must specify both a library nickname and an entry name" );
3423 return tl::unexpected( e );
3424 }
3425
3427
3428 if( layer == UNDEFINED_LAYER )
3429 layer = F_Cu;
3430
3431 // TODO update if we support inner layer footprints in the future
3432 if( !IsExternalCopperLayer( layer ) )
3433 {
3434 ApiResponseStatus e;
3435 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3436 e.set_error_message( "layer must be F_Cu or B_Cu" );
3437 return tl::unexpected( e );
3438 }
3439
3440 std::unique_ptr<FOOTPRINT> footprint( LoadFootprintFromProject( board(), libId ) );
3441
3442 if( !footprint )
3443 {
3444 ApiResponseStatus e;
3445 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
3446 e.set_error_message( fmt::format( "footprint '{}' not found", libId.Format().wx_str() ) );
3447 return tl::unexpected( e );
3448 }
3449
3450 footprint->SetUuid( KIID() );
3451 footprint->RunOnChildren(
3452 []( BOARD_ITEM* aChild )
3453 {
3454 aChild->ResetUuid();
3455 },
3457
3458 footprint->SetParent( board() );
3459
3460 footprint->SetPosition( UnpackVector2( aCtx.Request.position() ) );
3461
3462 if( aCtx.Request.has_orientation() )
3463 footprint->SetOrientationDegrees( aCtx.Request.orientation().value_degrees() );
3464
3465 footprint->SetLayerAndFlip( layer );
3466
3467 BOARD_COMMIT* commit = static_cast<BOARD_COMMIT*>( getCurrentCommit( aCtx.ClientName ) );
3468 FOOTPRINT* placed = footprint.release();
3469 commit->Add( placed );
3470
3471 if( !m_activeClients.contains( aCtx.ClientName ) )
3472 pushCurrentCommit( aCtx.ClientName, _( "Placed footprint via API" ) );
3473
3474 PlaceFromLibraryResponse response;
3475 response.mutable_header()->CopyFrom( aCtx.Request.header() );
3476 placed->Serialize( *response.mutable_item() );
3477
3478 return response;
3479}
const char * name
KICOMMON_API types::KiCadObjectType ToProtoEnum(KICAD_T aValue)
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
Definition api_enums.cpp:56
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
Definition api_handler.h:47
std::optional< ApiResponseStatus > ValidatePaginationModeForSingleOrPerFile(kiapi::board::jobs::BoardJobPaginationMode aMode, const std::string &aCommandName)
HANDLER_RESULT< Empty > unpackEmbeddedFiles(EMBEDDED_FILES &aOutput, const common::types::EmbeddedFiles &aProto)
void ApplyOdbJobRequest(const RunBoardJobExportODB &aRequest, JOB_EXPORT_PCB_ODB &aJob)
std::optional< ApiResponseStatus > ApplyBoardPlotSettings(const BoardPlotSettings &aSettings, JOB_EXPORT_PCB_PLOT &aJob)
std::optional< ApiResponseStatus > ValidateUnitsInchMm(types::Units aUnits, const std::string &aCommandName)
HANDLER_RESULT< types::RunJobResponse > ExecuteBoardJob(PCB_CONTEXT *aContext, JOB &aJob)
void ApplyFabExportContent(const FabExportContent &aContent, JOB_EXPORT_PCB_FAB &aJob)
static const std::vector< KICAD_T > s_allowedBoardTypes
void ApplyOdbJobRequest(const kiapi::board::jobs::RunBoardJobExportODB &aRequest, JOB_EXPORT_PCB_ODB &aJob)
void ApplyFabExportContent(const kiapi::board::jobs::FabExportContent &aContent, JOB_EXPORT_PCB_FAB &aJob)
BASE_SCREEN class implementation.
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
#define ZONE_FILL_OP
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
static TOOL_ACTION gridSetOrigin
Definition actions.h:192
API_HANDLER_BOARD(std::shared_ptr< BOARD_CONTEXT > aContext, EDA_BASE_FRAME *aFrame=nullptr)
std::unique_ptr< COMMIT > createCommit() override
Override this to create an appropriate COMMIT subclass for the frame in question.
TOOL_MANAGER * toolManager() const
std::vector< KICAD_T > parseRequestedItemTypes(const google::protobuf::RepeatedField< int > &aTypes)
PROJECT & project() const
void pushCurrentCommit(const std::string &aClientName, const wxString &aMessage) override
BOARD * board() const
BOARD_CONTEXT * context() const
std::optional< ApiResponseStatus > checkForHeadless(const std::string &aCommandName) const
std::optional< BOARD_ITEM * > getItemById(const KIID &aId) const
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)
COMMIT * getCurrentCommit(const std::string &aClientName)
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< ImportNetlistResponse > handleImportNetlist(const HANDLER_CONTEXT< ImportNetlist > &aCtx)
HANDLER_RESULT< BoardPlotSettingsResponse > handleGetBoardPlotSettings(const HANDLER_CONTEXT< GetBoardPlotSettings > &aCtx)
HANDLER_RESULT< Empty > handleDeleteVariant(const HANDLER_CONTEXT< commands::DeleteVariant > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportPdf(const HANDLER_CONTEXT< RunBoardJobExportPdf > &aCtx)
HANDLER_RESULT< google::protobuf::Empty > handleSetEmbeddedFiles(const HANDLER_CONTEXT< SetEmbeddedFiles > &aCtx)
HANDLER_RESULT< commands::CurrentVariantResponse > handleGetCurrentVariant(const HANDLER_CONTEXT< commands::GetCurrentVariant > &aCtx)
HANDLER_RESULT< BoardDesignRulesResponse > handleSetBoardDesignRules(const HANDLER_CONTEXT< SetBoardDesignRules > &aCtx)
HANDLER_RESULT< kiapi::common::tasks::StartTaskResponse > handleStartDrcTask(const HANDLER_CONTEXT< kiapi::board::tasks::StartDrcTask > &aCtx)
API_HANDLER_PCB(PCB_EDIT_FRAME *aFrame)
HANDLER_RESULT< Empty > handleAddVariant(const HANDLER_CONTEXT< commands::AddVariant > &aCtx)
HANDLER_RESULT< commands::GetItemsResponse > handleGetConnectedItems(const HANDLER_CONTEXT< GetConnectedItems > &aCtx)
HANDLER_RESULT< commands::VariantsResponse > handleGetVariants(const HANDLER_CONTEXT< commands::GetVariants > &aCtx)
HANDLER_RESULT< types::Vector2 > handleGetBoardOrigin(const HANDLER_CONTEXT< GetBoardOrigin > &aCtx)
HANDLER_RESULT< commands::GetItemsResponse > handleGetItemsByNetClass(const HANDLER_CONTEXT< GetItemsByNetClass > &aCtx)
HANDLER_RESULT< Empty > handleSaveDocumentAs(const HANDLER_CONTEXT< commands::SaveDocumentAs > &aCtx)
HANDLER_RESULT< NetClassForNetsResponse > handleGetNetClassForNets(const HANDLER_CONTEXT< GetNetClassForNets > &aCtx)
HANDLER_RESULT< commands::CrossProbeAnnounceResponse > handleCrossProbeAnnounce(const HANDLER_CONTEXT< commands::CrossProbeAnnounce > &aCtx)
HANDLER_RESULT< Empty > handleCopyVariant(const HANDLER_CONTEXT< commands::CopyVariant > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportIpcD356(const HANDLER_CONTEXT< RunBoardJobExportIpcD356 > &aCtx)
PCB_CONTEXT * pcbContext() const
HANDLER_RESULT< BoardDesignRulesResponse > handleGetBoardDesignRules(const HANDLER_CONTEXT< GetBoardDesignRules > &aCtx)
HANDLER_RESULT< commands::GetDocumentModifiedStateResponse > handleGetDocumentModifiedState(const HANDLER_CONTEXT< commands::GetDocumentModifiedState > &aCtx) override
HANDLER_RESULT< kiapi::common::tasks::StartTaskResponse > handleStartRefillZonesTask(const HANDLER_CONTEXT< kiapi::board::tasks::StartRefillZonesTask > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportGerbers(const HANDLER_CONTEXT< RunBoardJobExportGerbers > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportODB(const HANDLER_CONTEXT< RunBoardJobExportODB > &aCtx)
HANDLER_RESULT< Empty > handleSaveCopyOfDocument(const HANDLER_CONTEXT< commands::SaveCopyOfDocument > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExport3D(const HANDLER_CONTEXT< RunBoardJobExport3D > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportSpecctraDsn(const HANDLER_CONTEXT< RunBoardJobExportSpecctraDsn > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportPng(const HANDLER_CONTEXT< RunBoardJobExportPng > &aCtx)
HANDLER_RESULT< Empty > handleSetCurrentVariant(const HANDLER_CONTEXT< commands::SetCurrentVariant > &aCtx)
void setDrawingSheetFileName(const wxString &aFileName) override
HANDLER_RESULT< commands::GetItemsResponse > handleGetItemsByNet(const HANDLER_CONTEXT< GetItemsByNet > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportIpc2581(const HANDLER_CONTEXT< RunBoardJobExportIpc2581 > &aCtx)
std::optional< TITLE_BLOCK * > getTitleBlock(const DocumentSpecifier &aDocument) override
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportPosition(const HANDLER_CONTEXT< RunBoardJobExportPosition > &aCtx)
HANDLER_RESULT< Empty > handleSetBoardOrigin(const HANDLER_CONTEXT< SetBoardOrigin > &aCtx)
HANDLER_RESULT< Empty > handleSetBoardPlotSettings(const HANDLER_CONTEXT< SetBoardPlotSettings > &aCtx)
HANDLER_RESULT< BoardLayerNameResponse > handleGetBoardLayerName(const HANDLER_CONTEXT< GetBoardLayerName > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportStats(const HANDLER_CONTEXT< RunBoardJobExportStats > &aCtx)
void onModified() override
HANDLER_RESULT< ImportSpecctraSessionResponse > handleImportSpecctraSession(const HANDLER_CONTEXT< ImportSpecctraSession > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportPs(const HANDLER_CONTEXT< RunBoardJobExportPs > &aCtx)
HANDLER_RESULT< CustomRulesResponse > handleGetCustomDesignRules(const HANDLER_CONTEXT< GetCustomDesignRules > &aCtx)
bool setPageSettings(const DocumentSpecifier &aDocument, const PAGE_INFO &aPageInfo) override
HANDLER_RESULT< std::vector< ZONE * > > resolveZonesToFill(const google::protobuf::RepeatedPtrField< kiapi::common::types::KIID > &aZoneIds) const
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportSvg(const HANDLER_CONTEXT< RunBoardJobExportSvg > &aCtx)
kiapi::common::types::DocumentType thisDocumentType() const override
Override this to specify which document type this editor handles.
HANDLER_RESULT< commands::GetOpenDocumentsResponse > handleGetOpenDocuments(const HANDLER_CONTEXT< commands::GetOpenDocuments > &aCtx)
HANDLER_RESULT< commands::SyncSelectionResponse > handleSyncSelection(const HANDLER_CONTEXT< commands::SyncSelection > &aCtx)
HANDLER_RESULT< BoardEditorAppearanceSettings > handleGetBoardEditorAppearanceSettings(const HANDLER_CONTEXT< GetBoardEditorAppearanceSettings > &aCtx)
HANDLER_RESULT< NetsResponse > handleGetNets(const HANDLER_CONTEXT< GetNets > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportDxf(const HANDLER_CONTEXT< RunBoardJobExportDxf > &aCtx)
HANDLER_RESULT< Empty > handleSetVariantDescription(const HANDLER_CONTEXT< commands::SetVariantDescription > &aCtx)
HANDLER_RESULT< Empty > handleSaveDocument(const HANDLER_CONTEXT< commands::SaveDocument > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportDrill(const HANDLER_CONTEXT< RunBoardJobExportDrill > &aCtx)
HANDLER_RESULT< commands::GetItemsResponse > handleGetItems(const HANDLER_CONTEXT< commands::GetItems > &aCtx)
HANDLER_RESULT< kiapi::common::commands::PlaceFromLibraryResponse > handlePlaceFootprintFromLibrary(const HANDLER_CONTEXT< kiapi::board::commands::PlaceFootprintFromLibrary > &aCtx)
HANDLER_RESULT< kiapi::board::tasks::DrcTaskResult > handleGetDrcTaskResult(const HANDLER_CONTEXT< kiapi::board::tasks::GetDrcTaskResult > &aCtx)
HANDLER_RESULT< InjectDrcErrorResponse > handleInjectDrcError(const HANDLER_CONTEXT< InjectDrcError > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportRender(const HANDLER_CONTEXT< RunBoardJobExportRender > &aCtx)
PCB_EDIT_FRAME * frame() const
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportGencad(const HANDLER_CONTEXT< RunBoardJobExportGencad > &aCtx)
HANDLER_RESULT< BoardEnabledLayersResponse > handleSetBoardEnabledLayers(const HANDLER_CONTEXT< SetBoardEnabledLayers > &aCtx)
HANDLER_RESULT< Empty > handleRenameVariant(const HANDLER_CONTEXT< commands::RenameVariant > &aCtx)
std::optional< PAGE_INFO > getPageSettings(const DocumentSpecifier &aDocument) override
HANDLER_RESULT< Empty > handleSetBoardEditorAppearanceSettings(const HANDLER_CONTEXT< SetBoardEditorAppearanceSettings > &aCtx)
tl::expected< bool, ApiResponseStatus > validateDocumentInternal(const DocumentSpecifier &aDocument) const override
HANDLER_RESULT< Empty > handleRefillZones(const HANDLER_CONTEXT< RefillZones > &aCtx)
HANDLER_RESULT< commands::HighlightNetsResponse > handleHighlightNets(const HANDLER_CONTEXT< commands::HighlightNets > &aCtx)
HANDLER_RESULT< types::RunJobResponse > handleRunBoardJobExportIdf(const HANDLER_CONTEXT< RunBoardJobExportIdf > &aCtx)
HANDLER_RESULT< google::protobuf::Empty > handleAddEmbeddedFiles(const HANDLER_CONTEXT< AddEmbeddedFiles > &aCtx)
HANDLER_RESULT< common::types::EmbeddedFiles > handleGetEmbeddedFiles(const HANDLER_CONTEXT< GetEmbeddedFiles > &aCtx)
HANDLER_RESULT< BoardLayerResponse > handleGetBoardLayerByName(const HANDLER_CONTEXT< GetBoardLayerByName > &aCtx)
HANDLER_RESULT< Empty > handleRevertDocument(const HANDLER_CONTEXT< commands::RevertDocument > &aCtx)
HANDLER_RESULT< CustomRulesResponse > handleSetCustomDesignRules(const HANDLER_CONTEXT< SetCustomDesignRules > &aCtx)
void onNetSettingsChanged() override
Called on all registered handlers after project net settings (netclasses or netclass assignments) hav...
wxString getDrawingSheetFileName() override
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 Revert() override
Revert the commit by restoring the modified items state.
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
virtual KIWAY * GetKiway() const =0
virtual BOARD * GetBoard() const =0
Container for design settings for a BOARD object.
std::map< int, SEVERITY > m_DRCSeverities
void SetGridOrigin(const VECTOR2I &aOrigin)
std::vector< DIFF_PAIR_DIMENSION > m_DiffPairDimensionsList
const VECTOR2I & GetGridOrigin() const
TEARDROP_PARAMETERS_LIST m_TeardropParamsList
The parameters of teardrops for the different teardrop targets (via/pad, track end).
void SetAuxOrigin(const VECTOR2I &aOrigin)
const VECTOR2I & GetAuxOrigin() const
std::vector< int > m_TrackWidthList
std::vector< VALIDATION_ERROR > ValidateDesignRules(std::optional< EDA_UNITS > aUnits=std::nullopt) const
Validate design settings values and return per-field errors.
std::vector< VIA_DIMENSION > m_ViasDimensionsList
std::set< DRC_EXCLUSION, DRC_EXCLUSION_COMPARE > m_DrcExclusions
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
virtual void CopyFrom(const BOARD_ITEM *aOther)
void ResetUuid()
Definition board_item.h:295
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
void SetPlotOptions(const PCB_PLOT_PARAMS &aOptions)
Definition board.h:1033
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition board.cpp:3709
const PAGE_INFO & GetPageSettings() const
Definition board.h:1029
void SetDesignSettings(const BOARD_DESIGN_SETTINGS &aSettings)
Definition board.cpp:1330
TITLE_BLOCK & GetTitleBlock()
Definition board.h:1035
PCB_LAYER_ID GetLayerID(const wxString &aLayerName) const
Return the ID of a layer.
Definition board.cpp:940
void SetPageSettings(const PAGE_INFO &aPageSettings)
Definition board.h:1030
const wxString & GetFileName() const
Definition board.h:454
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition board.h:1032
wxString GetDesignRulesPath() const
Return the absolute path to the design rules file for this board.
Definition board.cpp:437
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
std::shared_ptr< CONNECTIVITY_DATA > GetConnectivity() const
Return a list of missing connections between components/tracks.
Definition board.h:758
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition commit.h:68
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
static void RegisterPeer(FRAME_T aFrameType, const std::string &aSocketPath)
void ToProto(kiapi::board::CustomRuleConstraint &aProto) const
Definition drc_rule.cpp:475
Container for an DRC exclusion, which is a PCB_MARKER plus an optional comment.
static DRC_EXCLUSION FromProto(const kiapi::board::DrcExclusion &aMessage)
const kiapi::board::DrcExclusion & ToProto() const
static std::shared_ptr< DRC_ITEM > Create(int aErrorCode)
Constructs a DRC_ITEM for the given error code.
Definition drc_item.cpp:495
void Parse(std::vector< std::shared_ptr< DRC_RULE > > &aRules, REPORTER *aReporter)
static wxString ExtractRuleComment(const wxString &aOriginalText)
Extract comment lines from a rule.
static wxString ExtractRuleText(const wxString &aContent, const wxString &aRuleName)
Extract the complete original text of a rule from file content.
static wxString FormatRuleFromProto(const kiapi::board::CustomRule &aRule, wxString *aErrorText=nullptr)
Definition drc_rule.cpp:145
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
const std::map< wxString, std::shared_ptr< EMBEDDED_FILE > > & EmbeddedFileMap() const
Provide an iterable view of the file collection.
static const TOOL_EVENT SelectedItemsModified
Selected item had a property changed (except movement)
Definition actions.h:354
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
JOB_EXPORT_PCB_3D::FORMAT m_format
EXPORTER_STEP_PARAMS m_3dparams
Despite the name; also used for other formats.
std::optional< wxString > m_sections
Section key that replaces the optional sections of the data set Unset lets the data set select them a...
std::vector< wxString > m_variantNames
IDF_SETTINGS::COORD_ORIGIN m_originMode
VECTOR2D m_userOrigin
In whatever units the user specified in m_units.
IDF_SETTINGS::UNITS m_units
VARIANT_PACKAGING m_variantPackaging
ODB_COMPRESSION m_compressionMode
wxString m_pdfBackgroundColor
The background color specified in a hex string.
GEN_MODE m_pdfGenMode
uused by the cli, will be removed when the other behavior is deprecated
bool m_useDrillOrigin
Used by SVG/DXF/PDF/Gerbers.
LSEQ m_plotOnAllLayersSequence
Layers to include on all individual layer prints.
DRILL_MARKS m_drillShapeOption
Used by SVG & PDF.
bool m_mirror
Common Options.
wxString m_variant
Variant name for variant-aware filtering.
VECTOR3D m_lightBottomIntensity
VECTOR3D m_lightTopIntensity
VECTOR3D m_lightCameraIntensity
VECTOR3D m_rotation
wxString m_filename
bool m_useBoardStackupColors
VECTOR3D m_lightSideIntensity
std::string m_appearancePreset
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
void UpdateAllLayersColor()
Apply the new coloring scheme to all layers.
Definition view.cpp:1171
Definition kiid.h:46
std::string AsStdString() const
Definition kiid.cpp:270
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
int ProcessJob(KIWAY::FACE_T aFace, JOB *aJob, REPORTER *aReporter=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr)
Definition kiway.cpp:753
@ FACE_PCB
pcbnew DSO
Definition kiway.h:356
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
LSEQ is a sequence (and therefore also a set) of PCB_LAYER_IDs.
Definition lseq.h:47
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
static int NameToLayer(wxString &aName)
Return the layer number from a layer name.
Definition lset.cpp:113
A collection of nets and the parameters used to route or test these nets.
Definition netclass.h:44
bool ContainsNetclassWithName(const wxString &netclass) const
Determines if the given netclass name is a constituent of this (maybe aggregate) netclass.
Definition netclass.cpp:338
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
Definition netclass.cpp:232
Handle the data for a net.
Definition netinfo.h:50
NETCLASS * GetNetClass()
Definition netinfo.h:101
int GetNetCode() const
Definition netinfo.h:104
Container for NETINFO_ITEM elements, which are the nets.
Definition netinfo.h:232
NETINFO_ITEM * GetNetItem(int aNetCode) const
Store information read from a netlist along with the flags used to update the NETLIST in the BOARD.
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
DISPLAY_OPTIONS m_Display
static TOOL_ACTION zoneFillAll
static TOOL_ACTION syncSelection
Sets selection to specified items, zooms to fit, if enabled.
Definition pcb_actions.h:63
static TOOL_ACTION drillSetOrigin
static TOOL_ACTION syncSelectionWithNets
Sets selection to specified items with connected nets, zooms to fit, if enabled.
Definition pcb_actions.h:66
const PCB_DISPLAY_OPTIONS & GetDisplayOptions() const
Display options control the way tracks, vias, outlines and other things are shown (for instance solid...
PCBNEW_SETTINGS * GetPcbNewSettings() const
PCB_DRAW_PANEL_GAL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
void SetDisplayOptions(const PCB_DISPLAY_OPTIONS &aOptions, bool aRefresh=true)
Update the current display options.
virtual void Update3DView(bool aMarkDirty, bool aRefresh, const wxString *aTitle=nullptr)
Update the 3D view, if the viewer is opened by this frame.
PCB-editor-specific context; extends BOARD_CONTEXT with save/filename operations.
Definition pcb_context.h:38
virtual wxString GetCurrentFileName() const =0
virtual void OnNetlistChanged(BOARD_NETLIST_UPDATER &aUpdater)=0
Post-import board sync (nets, classes, DRC, ratsnest, new footprint placement).
virtual bool ReadNetlistFromFile(const wxString &aFilename, NETLIST &aNetlist, REPORTER &aReporter)=0
Read a netlist file and preload component footprints.
virtual void SetContentModified(bool aModified=true)=0
virtual std::unique_ptr< BOARD_NETLIST_UPDATER > MakeNetlistUpdater()=0
Create a netlist updater bound to this context's board.
bool m_FlipBoardView
true if the board is flipped to show the mirrored view
HIGH_CONTRAST_MODE m_ContrastModeDisplay
How inactive layers are displayed.
NET_COLOR_MODE m_NetColorMode
How to use color overrides on specific nets and netclasses.
virtual KIGFX::PCB_VIEW * GetView() const override
Return a pointer to the KIGFX::VIEW instance used in the panel.
The main frame for Pcbnew.
void LoadDrawingSheet()
Load the drawing sheet file.
void OnModify() override
Must be called after a board change to set the modified flag.
void StartCrossProbeFlash(const std::vector< BOARD_ITEM * > &aItems)
void UpdateVariantSelectionCtrl()
Update the variant selection dropdown with the current board's variant names.
void SetCurrentVariant(const wxString &aVariantName)
Set the current variant on the board and update the drawing sheet's cached variant name and descripti...
void UpdateUserInterface()
Update the layer manager and other widgets from the board setup (layer and items visibility,...
void HandleRemoteNetHighlight(const std::vector< wxString > &aNetNames)
const KIID GetUUID() const override
Definition pcb_marker.h:50
Parameters and options when plotting/printing a board.
bool GetNegative() const
void SetDrillMarksType(DRILL_MARKS aVal)
bool GetUseAuxOrigin() const
LSEQ GetPlotOnAllLayersSequence() const
bool GetHideDNPFPsOnFabLayers() const
void SetLayerSelection(const LSET &aSelection)
void SetPlotReference(bool aFlag)
void SetSketchPadsOnFabLayers(bool aFlag)
bool GetMirror() const
bool GetCrossoutDNPFPsOnFabLayers() const
bool GetSketchDNPFPsOnFabLayers() const
void SetPlotOnAllLayersSequence(LSEQ aSeq)
void SetPlotFrameRef(bool aFlag)
void SetSketchDNPFPsOnFabLayers(bool aFlag)
double GetScale() const
void SetPlotPadNumbers(bool aFlag)
LSET GetLayerSelection() const
bool GetPlotReference() const
void SetScale(double aVal)
void SetMirror(bool aFlag)
void SetBlackAndWhite(bool blackAndWhite)
void SetSubtractMaskFromSilk(bool aSubtract)
bool GetSketchPadsOnFabLayers() const
void SetHideDNPFPsOnFabLayers(bool aFlag)
bool GetSubtractMaskFromSilk() const
void SetPlotValue(bool aFlag)
bool GetPlotPadNumbers() const
DRILL_MARKS GetDrillMarksType() const
bool GetPlotValue() const
void SetNegative(bool aFlag)
bool GetBlackAndWhite() const
void SetUseAuxOrigin(bool aAux)
bool GetPlotFrameRef() const
void SetCrossoutDNPFPsOnFabLayers(bool aFlag)
wxString m_BoardDrawingSheetFile
PcbNew params.
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
TEARDROP_PARAMETERS_LIST is a helper class to handle the list of TEARDROP_PARAMETERS needed to build ...
bool m_UseRoundShapesOnly
True to create teardrops for round shapes only.
bool m_TargetVias
True to create teardrops for vias.
bool m_TargetPTHPads
True to create teardrops for pads with holes.
bool m_TargetTrack2Track
True to create teardrops at the end of a track connected to the end of another track having a differe...
TEARDROP_PARAMETERS * GetParameters(TARGET_TD aTdType)
bool m_TargetSMDPads
True to create teardrops for pads SMD, edge connectors,.
TEARDROP_PARAMETARS is a helper class to handle parameters needed to build teardrops for a board thes...
double m_BestWidthRatio
The height of a teardrop as ratio between height and size of pad/via.
int m_TdMaxLen
max allowed length for teardrops in IU. <= 0 to disable
bool m_AllowUseTwoTracks
True to create teardrops using 2 track segments if the first in too small.
int m_TdMaxWidth
max allowed height for teardrops in IU. <= 0 to disable
double m_BestLengthRatio
The length of a teardrop as ratio between length and size of pad/via.
double m_WidthtoSizeFilterRatio
The ratio (H/D) between the via/pad size and the track width max value to create a teardrop 1....
bool m_TdOnPadsInZones
A filter to exclude pads inside zone fills.
bool m_Enabled
Flag to enable teardrops.
bool m_CurvedEdges
True if the teardrop should be curved.
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
Master controller class:
T * GetTool()
Return the tool of given type or nullptr if there is no such tool registered.
bool RunAction(const std::string &aActionName, T aParam)
Run the specified action immediately, pausing the current action to run the new one.
TOOL_BASE * FindTool(int aId) const
Search for a tool with given ID.
void RegisterTool(TOOL_BASE *aTool)
Add a tool to the manager set and sets it up.
wxString wx_str() const
Definition utf8.cpp:41
A wrapper for reporting to a wxString object.
Definition reporter.h:242
Handle actions specific to filling copper zones.
bool Fill(const std::vector< ZONE * > &aZones, bool aCheck=false, wxWindow *aParent=nullptr)
Fills the given list of zones.
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
PCB_DRC_CODE
Definition drc_item.h:46
@ DRCE_GENERIC_ERROR
Definition drc_item.h:105
@ DRCE_GENERIC_WARNING
Definition drc_item.h:104
static std::string ToStdString(const wxString &aStr)
#define _(s)
@ RECURSE
Definition eda_item.h:51
FRAME_T
The set of EDA_BASE_FRAME derivatives, typically stored in EDA_BASE_FRAME::m_Ident.
Definition frame_type.h:29
static const std::string KiCadPcbFileExtension
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
std::string source
bool IsPcbLayer(int aLayer)
Test whether a layer is a valid layer for Pcbnew.
Definition layer_ids.h:733
#define MAX_CU_LAYERS
Definition layer_ids.h:172
@ LAYER_DRC_WARNING
Layer for DRC markers with RPT_SEVERITY_WARNING.
Definition layer_ids.h:297
@ LAYER_DRC_ERROR
Layer for DRC markers with RPT_SEVERITY_ERROR.
Definition layer_ids.h:273
bool IsExternalCopperLayer(int aLayerId)
Test whether a layer is an external (F_Cu or B_Cu) copper layer.
Definition layer_ids.h:755
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ Edge_Cuts
Definition layer_ids.h:108
@ UNSELECTED_LAYER
Definition layer_ids.h:58
@ Margin
Definition layer_ids.h:109
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ PCB_LAYER_ID_COUNT
Definition layer_ids.h:167
@ F_Cu
Definition layer_ids.h:60
bool ImportSpecctraSession(BOARD *aBoard, const wxString &fullFileName, COMMIT &aCommit, REPORTER *aReporter=nullptr, int *aSkippedCount=nullptr)
Helper method to import SES file to a board.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
void PackLayerSet(google::protobuf::RepeatedField< int > &aOutput, const LSET &aLayerSet)
void PackEmbeddedFiles(common::types::EmbeddedFiles &aOutput, const EMBEDDED_FILES &aFiles)
bool UnpackEmbeddedFiles(EMBEDDED_FILES &aOutput, const common::types::EmbeddedFiles &aProto)
LSET UnpackLayerSet(const google::protobuf::RepeatedField< int > &aProtoLayerSet)
std::vector< BOARD_ITEM * > FindItemsFromSyncSelection(const BOARD *aBoard, const google::protobuf::RepeatedPtrField< kiapi::common::commands::SelectionSpec > &aItems)
Resolve a cross-probe selection request against a board.
KICOMMON_API VECTOR3D UnpackVector3D(const types::Vector3D &aInput)
KICOMMON_API VECTOR2I UnpackVector2(const types::Vector2 &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API void PackVector2(types::Vector2 &aOutput, const VECTOR2I &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API LIB_ID UnpackLibId(const types::LibraryIdentifier &aId)
const KICOMMON_API std::string KiwayClientName
const KICOMMON_API std::string StandaloneCrossProbeClientName
STL namespace.
std::shared_ptr< PCB_CONTEXT > CreatePcbFrameContext(PCB_EDIT_FRAME *aFrame)
Class to handle a set of BOARD_ITEMs.
FOOTPRINT * LoadFootprintFromProject(BOARD *aBoard, const LIB_ID &aFootprintId, bool aKeepUuid)
Load a footprint from the project library table and apply board default settings.
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
SEVERITY
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_IGNORE
#define SKIP_CONNECTIVITY
Definition sch_commit.h:41
const int scale
wxString GetDefaultVariantName()
Cross-probing behavior.
bool flash_selection
Flash newly cross-probed selection (visual attention aid).
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
@ TARGET_UNKNOWN
@ TARGET_ROUND
@ TARGET_TRACK
std::string netlist
IbisParser parser & reporter
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
constexpr KICAD_T BaseType(const KICAD_T aType)
Return the underlying type of the given type.
Definition typeinfo.h:261
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
Definition typeinfo.h:70
@ PCB_CONSTRAINT_T
a geometric constraint between board items
Definition typeinfo.h:237
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
Definition typeinfo.h:83
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_DRILL_MAP_T
class PCB_DRILL_MAP, drill symbols drawn at the holes
Definition typeinfo.h:240
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:85
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_3D_BODY_T
class PCB_3D_BODY, a 3D body (extruded or model) on a footprint
Definition typeinfo.h:241
@ PCB_REFERENCE_IMAGE_T
class PCB_REFERENCE_IMAGE, bitmap on a layer
Definition typeinfo.h:81
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_GRID_ITEM_T
a subgrid placed on a board
Definition typeinfo.h:238
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_DIMENSION_T
class PCB_DIMENSION_BASE: abstract dimension meta-type
Definition typeinfo.h:92
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:86
@ PCB_STACKUP_TABLE_T
class PCB_STACKUP_TABLE, a live stackup table derived from PCB_TABLE
Definition typeinfo.h:242
@ PCB_POINT_T
class PCB_POINT, a 0-dimensional point
Definition typeinfo.h:105
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
@ PCB_DRILL_CHART_T
class PCB_DRILL_CHART, a live drill chart derived from PCB_TABLE
Definition typeinfo.h:239
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
#define ZONE_FILLER_TOOL_NAME