KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_sch_utils.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2024 Jon Evans <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <algorithm>
22#include <set>
23#include <trace_helpers.h>
24
25#include <sch_pin.h>
26#include <lib_symbol.h>
27#include <schematic.h>
28#include <sch_symbol.h>
29#include <sch_bitmap.h>
30#include <sch_bus_entry.h>
31#include <sch_field.h>
32#include <sch_group.h>
33#include <sch_junction.h>
34#include <sch_label.h>
35#include <sch_line.h>
36#include <sch_no_connect.h>
37#include <sch_rule_area.h>
38#include <sch_shape.h>
39#include <sch_sheet.h>
40#include <sch_sheet_path.h>
41#include <sch_screen.h>
42#include <sch_sheet_pin.h>
43#include <sch_table.h>
44#include <sch_tablecell.h>
45#include <sch_text.h>
46#include <sch_textbox.h>
47
48#include "api_sch_utils.h"
49
50#include <fmt/format.h>
51#include <fmt/ranges.h>
52#include <schematic.h>
53
54#include <api/api_utils.h>
55#include <api/api_enums.h>
56
57
58using namespace kiapi::common;
59
60
61std::unique_ptr<EDA_ITEM> CreateItemForType( KICAD_T aType, EDA_ITEM* aContainer )
62{
63 SCH_ITEM* parentSchItem = dynamic_cast<SCH_ITEM*>( aContainer );
64
65 switch( aType )
66 {
67 case SCH_JUNCTION_T: return std::make_unique<SCH_JUNCTION>();
68 case SCH_NO_CONNECT_T: return std::make_unique<SCH_NO_CONNECT>();
69 case SCH_BUS_WIRE_ENTRY_T: return std::make_unique<SCH_BUS_WIRE_ENTRY>();
70 case SCH_BUS_BUS_ENTRY_T: return std::make_unique<SCH_BUS_BUS_ENTRY>();
71 case SCH_LINE_T: return std::make_unique<SCH_LINE>();
72 case SCH_SHAPE_T: return std::make_unique<SCH_SHAPE>();
73 case SCH_BITMAP_T: return std::make_unique<SCH_BITMAP>();
74 case SCH_TEXTBOX_T: return std::make_unique<SCH_TEXTBOX>();
75 case SCH_TEXT_T: return std::make_unique<SCH_TEXT>();
76 case SCH_TABLE_T: return std::make_unique<SCH_TABLE>();
77 case SCH_TABLECELL_T: return std::make_unique<SCH_TABLECELL>();
78 case SCH_LABEL_T: return std::make_unique<SCH_LABEL>();
79 case SCH_GLOBAL_LABEL_T: return std::make_unique<SCH_GLOBALLABEL>();
80 case SCH_HIER_LABEL_T: return std::make_unique<SCH_HIERLABEL>();
81 case SCH_DIRECTIVE_LABEL_T: return std::make_unique<SCH_DIRECTIVE_LABEL>();
82 case SCH_RULE_AREA_T: return std::make_unique<SCH_RULE_AREA>();
83 case SCH_FIELD_T: return std::make_unique<SCH_FIELD>( parentSchItem );
84 case SCH_GROUP_T: return std::make_unique<SCH_GROUP>();
85 case SCH_SYMBOL_T: return std::make_unique<SCH_SYMBOL>();
86 case LIB_SYMBOL_T: return std::make_unique<LIB_SYMBOL>( wxEmptyString );
87 case SCH_SHEET_T:
88 {
89 if( aContainer && aContainer->Type() == SCH_SCREEN_T )
90 return std::make_unique<SCH_SHEET>( static_cast<SCH_SCREEN*>( aContainer ) );
91
92 return nullptr;
93 }
94
95
96 case SCH_SHEET_PIN_T:
97 if( aContainer && aContainer->Type() == SCH_SHEET_T )
98 return std::make_unique<SCH_SHEET_PIN>( static_cast<SCH_SHEET*>( aContainer ) );
99
100 return nullptr;
101
102 case SCH_PIN_T:
103 if( aContainer && aContainer->Type() == LIB_SYMBOL_T )
104 return std::make_unique<SCH_PIN>( static_cast<LIB_SYMBOL*>( aContainer ) );
105
106 return nullptr;
107
108 default:
109 return nullptr;
110 }
111}
112
113
114void PackPinMapOverride( kiapi::schematic::types::PinMapInstanceOverride* aOutput,
115 const PIN_MAP_INSTANCE_OVERRIDE& aOverride )
116{
117 aOutput->Clear();
118 aOutput->set_mode(
120 aOutput->set_active_map_name( aOverride.m_ActiveMapName.ToUTF8() );
121
122 for( const PIN_MAP_ENTRY& edit : aOverride.m_Edits )
123 {
124 kiapi::schematic::types::PinMapEntry* e = aOutput->add_edits();
125 e->set_pin_number( edit.m_PinNumber.ToUTF8() );
126 e->set_pad_number( edit.m_PadNumber.ToUTF8() );
127 }
128}
129
130
131PIN_MAP_INSTANCE_OVERRIDE UnpackPinMapOverride( const kiapi::schematic::types::PinMapInstanceOverride& aInput )
132{
134 override.m_Mode = FromProtoEnum<PIN_MAP_OVERRIDE_MODE>( aInput.mode() );
135 override.m_ActiveMapName = wxString::FromUTF8( aInput.active_map_name() );
136
137 for( const kiapi::schematic::types::PinMapEntry& e : aInput.edits() )
138 {
139 override.m_Edits.push_back( { wxString::FromUTF8( e.pin_number() ), wxString::FromUTF8( e.pad_number() ) } );
140 }
141
142 return override;
143}
144
145
146bool PackSymbol( kiapi::schematic::types::SchematicSymbolInstance* aOutput, const SCH_SYMBOL* aInput,
147 const SCH_SHEET_PATH& aPath, const SCHEMATIC* aSchematic )
148{
149 KIID_PATH path = aPath.Path();
150 SCH_SYMBOL_INSTANCE instance;
151
152 if( !aInput->GetInstance( instance, path ) )
153 {
154 wxLogTrace( traceApi, "error: instance data for symbol %s on %s is missing",
155 aInput->m_Uuid.AsString(), aPath.PathHumanReadable() );
156 return false;
157 }
158
159 google::protobuf::Any any;
160 aInput->Serialize( any );
161
162 if( !any.UnpackTo( aOutput ) )
163 return false;
164
165 PackSheetPath( *aOutput->mutable_path(), aPath );
166
167 const SCHEMATIC* owner = aInput->Schematic() ? aInput->Schematic() : aSchematic;
168 wxString reference = aInput->GetRef( &aPath );
169 wxString suffix;
170
171 // The reference names the package, whose suffix may be another sheet's
172 if( owner )
173 suffix = owner->GetPackageRefSuffix( aInput, aPath );
174
175 // A staged symbol has no parent yet, so GetRef cannot compose it
176 if( !aInput->Schematic() && !reference.EndsWith( wxS( "?" ) ) )
177 reference += suffix;
178
179 aOutput->mutable_reference_field()->mutable_text()->set_text( reference.ToUTF8() );
180 aOutput->mutable_unit()->set_unit( instance.m_Unit );
181
182 kiapi::schematic::types::SchematicSymbol* def = aOutput->mutable_definition();
183
184 std::vector<const SCH_PIN*> pins = aInput->GetPins( &aPath );
185
186 std::ranges::sort( pins,
187 []( const SCH_PIN* a, const SCH_PIN* b )
188 {
189 return a->m_Uuid < b->m_Uuid;
190 } );
191
192 for( const SCH_PIN* pin : pins )
193 {
194 kiapi::schematic::types::SchematicSymbolChild* item = def->add_items();
195 item->mutable_unit()->set_unit( pin->GetUnit() );
196 item->mutable_body_style()->set_style( pin->GetBodyStyle() );
197 item->set_is_private( pin->IsPrivate() );
198 pin->Serialize( *item->mutable_item() );
199 }
200
201 // Also include the pins from non-placed units
202 if( const LIB_SYMBOL* lib = aInput->GetLibSymbolRef().get() )
203 {
204 std::set<wxString> placedNumbers;
205
206 for( const SCH_PIN* pin : pins )
207 placedNumbers.insert( pin->GetNumber() );
208
209 for( const SCH_PIN* libPin : lib->GetGraphicalPins( ALL_UNITS, ALL_BODY_STYLES ) )
210 {
211 if( libPin->GetBodyStyle() != ALL_BODY_STYLES
212 && aInput->GetBodyStyle() != ALL_BODY_STYLES
213 && aInput->GetBodyStyle() != libPin->GetBodyStyle() )
214 {
215 continue;
216 }
217
218 if( placedNumbers.count( libPin->GetNumber() ) )
219 continue;
220
221 kiapi::schematic::types::SchematicSymbolChild* item = def->add_items();
222 item->mutable_unit()->set_unit( libPin->GetUnit() );
223 item->mutable_body_style()->set_style( libPin->GetBodyStyle() );
224 item->set_is_private( libPin->IsPrivate() );
225 libPin->Serialize( *item->mutable_item() );
226 }
227 }
228
229 PIN_MAP_INSTANCE_OVERRIDE override = aInput->GetPinMapOverride( &aPath );
230
231 if( !override.IsDefault() )
232 PackPinMapOverride( aOutput->mutable_pin_map_override(), override );
233
234 kiapi::schematic::types::SchematicSymbolAttributes* attributes = aOutput->mutable_attributes();
235
236 attributes->set_exclude_from_simulation( aInput->GetExcludedFromSim() );
237 attributes->set_exclude_from_bill_of_materials( aInput->GetExcludedFromBOM() );
238 attributes->set_exclude_from_board( aInput->GetExcludedFromBoard() );
239 attributes->set_exclude_from_position_files( aInput->GetExcludedFromPosFiles() );
240 attributes->set_do_not_populate( aInput->GetDNP() );
241
242 // Descriptions belong to the schematic's variant registry rather than to each record.
243 SCHEMATIC* schematic = aInput->Schematic();
244
245 // Always set, so that sending the response back describes the placement's variants in full.
246 kiapi::schematic::types::SchematicSymbolVariants* variants = aOutput->mutable_variants();
247
248 for( const auto& [name, variantInfo] : instance.m_Variants )
249 {
250 kiapi::schematic::types::SchematicSymbolVariant* variant = variants->add_variants();
251 variant->set_name( name.ToUTF8() );
252
253 if( schematic )
254 variant->set_description( schematic->GetVariantDescription( name ).ToUTF8() );
255
256 attributes = variant->mutable_attributes();
257 attributes->set_exclude_from_simulation( variantInfo.m_ExcludedFromSim );
258 attributes->set_exclude_from_bill_of_materials( variantInfo.m_ExcludedFromBOM );
259 attributes->set_exclude_from_board( variantInfo.m_ExcludedFromBoard );
260 attributes->set_exclude_from_position_files( variantInfo.m_ExcludedFromPosFiles );
261 attributes->set_do_not_populate( variantInfo.m_DNP );
262
263 for( const auto& [key, value] : variantInfo.m_Fields )
264 ( *variant->mutable_fields() )[std::string( key.ToUTF8() )] = value.ToUTF8();
265
266 if( variantInfo.m_SymbolOverride )
267 PackLibId( variant->mutable_symbol_override(), *variantInfo.m_SymbolOverride );
268
269 if( !variantInfo.m_PinMapOverride.IsDefault() )
270 PackPinMapOverride( variant->mutable_pin_map_override(), variantInfo.m_PinMapOverride );
271 }
272
273 return true;
274}
275
276
277bool UnpackSymbol( SCH_SYMBOL* aOutput, const kiapi::schematic::types::SchematicSymbolInstance& aInput )
278{
279 using namespace kiapi::common::types;
280 using namespace kiapi::schematic::types;
281
282 if( !aOutput->Deserialize( aInput ) )
283 return false;
284
285 if( aInput.has_attributes() )
286 {
287 const SchematicSymbolAttributes& attrs = aInput.attributes();
288
289 aOutput->SetExcludedFromSim( attrs.exclude_from_simulation() );
290 aOutput->SetExcludedFromBOM( attrs.exclude_from_bill_of_materials() );
291 aOutput->SetExcludedFromBoard( attrs.exclude_from_board() );
292 aOutput->SetExcludedFromPosFiles( attrs.exclude_from_position_files() );
293 aOutput->SetDNP( attrs.do_not_populate() );
294 }
295
296 aOutput->SetPinMapOverride( aInput.has_pin_map_override() ? UnpackPinMapOverride( aInput.pin_map_override() )
298
299 return true;
300}
301
302
303// Variant names are stored and compared exactly, but SCHEMATIC::HasVariant matches case-insensitively
304std::optional<wxString> FindVariantNoCase( const SCHEMATIC* aSchematic, const wxString& aName )
305{
306 for( const wxString& variantName : aSchematic->GetVariantNames() )
307 {
308 if( variantName.CmpNoCase( aName ) == 0 )
309 return variantName;
310 }
311
312 return std::nullopt;
313}
314
315
317template <typename VariantProto>
318static void registerVariant( SCHEMATIC* aSchematic, const wxString& aName, const VariantProto& aInput )
319{
320 if( !aSchematic )
321 return;
322
323 wxString name( aName );
324
325 if( std::optional<wxString> canonical = FindVariantNoCase( aSchematic, name ) )
326 name = *canonical;
327
328 aSchematic->AddVariant( name );
329
330 // An empty description clears the one the variant has, so honour presence rather than text.
331 if( aInput.has_description() )
332 aSchematic->SetVariantDescription( aName, wxString::FromUTF8( aInput.description() ) );
333}
334
335
337static bool applySymbolVariants( kiapi::common::commands::ItemStatus* aStatus, SCH_SYMBOL* aSymbol,
338 const kiapi::schematic::types::SchematicSymbolVariants& aInput,
339 const SCH_SHEET_PATH& aPath, SCHEMATIC* aSchematic )
340{
341 using namespace kiapi::schematic::types;
342
343 std::set<wxString> requested;
344
345 for( const SchematicSymbolVariant& variantProto : aInput.variants() )
346 {
347 wxString name = wxString::FromUTF8( variantProto.name() );
348
349 // The empty name selects the default variant, whose values are the symbol's own.
350 if( name.IsEmpty() )
351 continue;
352
353 requested.insert( name );
354 registerVariant( aSchematic, name, variantProto );
355
356 if( variantProto.has_attributes() )
357 {
358 const SchematicSymbolAttributes& attrs = variantProto.attributes();
359
360 aSymbol->SetExcludedFromSim( attrs.exclude_from_simulation(), &aPath, name );
361 aSymbol->SetExcludedFromBOM( attrs.exclude_from_bill_of_materials(), &aPath, name );
362 aSymbol->SetExcludedFromBoard( attrs.exclude_from_board(), &aPath, name );
363 aSymbol->SetExcludedFromPosFiles( attrs.exclude_from_position_files(), &aPath, name );
364 aSymbol->SetDNP( attrs.do_not_populate(), &aPath, name );
365 }
366
367 // Overrides the request dropped go back to resolving as the symbol's own value.
368 SCH_SYMBOL_INSTANCE stored;
369
370 if( aSymbol->GetInstance( stored, aPath.Path() ) && stored.m_Variants.contains( name ) )
371 {
372 for( const auto& [fieldName, unused] : stored.m_Variants[name].m_Fields )
373 {
374 if( variantProto.fields().find( std::string( fieldName.ToUTF8() ) ) == variantProto.fields().end() )
375 aSymbol->ClearVariantField( aPath.Path(), name, fieldName );
376 }
377 }
378
379 if( variantProto.has_symbol_override() )
380 aSymbol->SetVariantSymbolOverride( aPath, name, UnpackLibId( variantProto.symbol_override() ) );
381 else
382 aSymbol->ClearVariantSymbolOverride( aPath, name );
383
384 if( variantProto.has_pin_map_override() )
385 aSymbol->SetPinMapOverride( UnpackPinMapOverride( variantProto.pin_map_override() ), &aPath, name );
386 else
387 aSymbol->SetPinMapOverride( PIN_MAP_INSTANCE_OVERRIDE(), &aPath, name );
388
389 for( const auto& [key, value] : variantProto.fields() )
390 {
391 wxString fieldName = wxString::FromUTF8( key );
392 wxString fieldValue = wxString::FromUTF8( value );
393
394 if( SCH_FIELD* field = aSymbol->GetField( fieldName ); field && field->GetId() != FIELD_T::REFERENCE )
395 aSymbol->SetFieldText( field, fieldName, fieldValue, &aPath, name );
396 }
397 }
398
399 // Variants the request left out are removed from this placement only; the variant itself
400 // stays registered with the schematic and other placements keep theirs.
401 SCH_SYMBOL_INSTANCE stored;
402
403 if( aSymbol->GetInstance( stored, aPath.Path() ) )
404 {
405 for( const auto& [name, unused] : stored.m_Variants )
406 {
407 if( !requested.contains( name ) )
408 aSymbol->DeleteVariant( aPath.Path(), name );
409 }
410 }
411
412 return true;
413}
414
415
416bool ValidateSymbolInstance( kiapi::common::commands::ItemStatus* aStatus, const SCH_SYMBOL* aSymbol,
417 const kiapi::schematic::types::SchematicSymbolInstance& aInput,
418 const SCH_SHEET_PATH& aPath, const SCHEMATIC* aSchematic )
419{
420 wxString reference = wxString::FromUTF8( aInput.reference_field().text().text() );
421 wxString base;
422 wxString error;
423
424 if( !reference.IsEmpty() )
425 error = aSymbol->BaseRefFromUser( aPath, reference, base, aSchematic );
426
427 for( const kiapi::schematic::types::SchematicSymbolVariant& variantProto : aInput.variants().variants() )
428 {
429 for( const auto& [key, unused] : variantProto.fields() )
430 {
431 const SCH_FIELD* field = aSymbol->GetField( wxString::FromUTF8( key ) );
432
433 if( !variantProto.name().empty() && field && field->GetId() == FIELD_T::REFERENCE )
434 error = wxS( "symbol reference can not be changed in a variant" );
435 }
436 }
437
438 if( error.IsEmpty() )
439 return true;
440
441 aStatus->set_code( commands::ItemStatusCode::ISC_INVALID_DATA );
442 aStatus->set_error_message( error.ToUTF8() );
443 return false;
444}
445
446
447bool ApplySymbolInstance( kiapi::common::commands::ItemStatus* aStatus, SCH_SYMBOL* aSymbol,
448 const kiapi::schematic::types::SchematicSymbolInstance& aInput,
449 const SCH_SHEET_PATH& aPath, SCHEMATIC* aSchematic )
450{
451 if( !ValidateSymbolInstance( aStatus, aSymbol, aInput, aPath, aSchematic ) )
452 return false;
453
454 wxString reference = wxString::FromUTF8( aInput.reference_field().text().text() );
455 int unit = aInput.has_unit() ? aInput.unit().unit() : 1;
456 SCH_SYMBOL_INSTANCE existing;
457 wxString base;
458
459 // Clients send back the composed reference they read, so the path suffix comes off here
460 if( !reference.IsEmpty() )
461 aSymbol->BaseRefFromUser( aPath, reference, base, aSchematic );
462
463 if( aSymbol->GetInstance( existing, aPath.Path() ) )
464 {
465 // An unchanged base must not touch the other instances, which may disagree on purpose,
466 // but SetRef still runs so a request's default prefix follows the base
467 if( !base.IsEmpty() && base != existing.m_Reference )
468 aSymbol->SetUserRef( aPath, base );
469 else if( !base.IsEmpty() )
470 aSymbol->SetRef( &aPath, base );
471
472 aSymbol->SetUnitSelection( &aPath, unit );
473 }
474 else
475 {
476 SCH_SYMBOL_INSTANCE instance;
477 instance.m_Path = aPath.Path();
478 instance.m_Reference = base;
479 instance.m_Unit = unit;
480
481 aSymbol->AddHierarchicalReference( instance );
482 }
483
484 // The displayed unit follows the placement the request targeted, as it does in the editor.
485 aSymbol->SetUnit( unit );
486
487 // A request that carries no variant set leaves the placement's variants as they are.
488 if( aInput.has_variants() && !applySymbolVariants( aStatus, aSymbol, aInput.variants(), aPath, aSchematic ) )
489 return false;
490
491 return true;
492}
493
494
495bool PackSheet( kiapi::schematic::types::SheetSymbol* aOutput, const SCH_SHEET* aInput,
496 const SCH_SHEET_PATH& aPath )
497{
498 google::protobuf::Any any;
499 aInput->Serialize( any );
500
501 if( !any.UnpackTo( aOutput ) )
502 return false;
503
504 PackSheetPath( *aOutput->mutable_path(), aPath );
505
506 SCHEMATIC* schematic = aInput->Schematic();
507
508 kiapi::schematic::types::SheetVariants* variants = aOutput->mutable_variants();
509
510 if( const SCH_SHEET_INSTANCE* instance = aInput->GetInstance( aPath.Path() ) )
511 {
512 aOutput->set_page_number( instance->m_PageNumber.ToUTF8() );
513
514 for( const auto& [name, variantInfo] : instance->m_Variants )
515 {
516 kiapi::schematic::types::SheetVariant* variant = variants->add_variants();
517 variant->set_name( name.ToUTF8() );
518
519 if( schematic )
520 variant->set_description( schematic->GetVariantDescription( name ).ToUTF8() );
521
522 variant->set_exclude_from_sim( variantInfo.m_ExcludedFromSim );
523 variant->set_exclude_from_bom( variantInfo.m_ExcludedFromBOM );
524 variant->set_dnp( variantInfo.m_DNP );
525
526 for( const auto& [key, value] : variantInfo.m_Fields )
527 ( *variant->mutable_fields() )[std::string( key.ToUTF8() )] = value.ToUTF8();
528 }
529 }
530
531 return true;
532}
533
534
535bool ValidateSheetInstance( commands::ItemStatus* aStatus, const SCH_SHEET* aSheet,
536 const kiapi::schematic::types::SheetSymbol& aInput )
537{
538 for( const kiapi::schematic::types::SheetVariant& variant : aInput.variants().variants() )
539 {
540 if( variant.name().empty() )
541 continue;
542
543 for( const auto& [key, unused] : variant.fields() )
544 {
545 if( const SCH_FIELD* field = aSheet->GetField( wxString::FromUTF8( key ) ) )
546 {
547 if( field->GetId() == FIELD_T::SHEET_NAME )
548 {
549 aStatus->set_code( commands::ItemStatusCode::ISC_INVALID_DATA );
550 aStatus->set_error_message( "sheet name can not be changed in a variant" );
551 return false;
552 }
553 else if( field->GetId() == FIELD_T::SHEET_FILENAME )
554 {
555 aStatus->set_code( commands::ItemStatusCode::ISC_INVALID_DATA );
556 aStatus->set_error_message( "sheet filename can not be changed in a variant" );
557 return false;
558 }
559 else if( field->GetId() == FIELD_T::SHEET_REF_SUFFIX )
560 {
561 aStatus->set_code( commands::ItemStatusCode::ISC_INVALID_DATA );
562 aStatus->set_error_message( "reference suffix can not be changed in a variant" );
563 return false;
564 }
565 }
566 }
567 }
568
569 return true;
570}
571
572
576static void applySheetVariants( SCH_SHEET* aSheet, const kiapi::schematic::types::SheetVariants& aInput,
577 const SCH_SHEET_PATH& aParentPath, SCHEMATIC* aSchematic )
578{
579 using namespace kiapi::schematic::types;
580
581 std::set<wxString> requested;
582
583 for( const SheetVariant& variantProto : aInput.variants() )
584 {
585 wxString name = wxString::FromUTF8( variantProto.name() );
586
587 // The empty name selects the default variant, whose values are the sheet's own.
588 if( name.IsEmpty() )
589 continue;
590
591 requested.insert( name );
592 registerVariant( aSchematic, name, variantProto );
593
594 // Each attribute the request leaves out keeps the value this variant already has.
595 if( variantProto.has_exclude_from_sim() )
596 aSheet->SetExcludedFromSim( variantProto.exclude_from_sim(), &aParentPath, name );
597
598 if( variantProto.has_exclude_from_bom() )
599 aSheet->SetExcludedFromBOM( variantProto.exclude_from_bom(), &aParentPath, name );
600
601 if( variantProto.has_dnp() )
602 aSheet->SetDNP( variantProto.dnp(), &aParentPath, name );
603
604 // Overrides the request dropped go back to resolving as the sheet's own value.
605 if( const SCH_SHEET_INSTANCE* stored = aSheet->GetInstance( aParentPath.Path() );
606 stored && stored->m_Variants.contains( name ) )
607 {
608 std::map<wxString, wxString> storedFields = stored->m_Variants.at( name ).m_Fields;
609
610 for( const auto& [fieldName, unused] : storedFields )
611 {
612 if( variantProto.fields().find( std::string( fieldName.ToUTF8() ) ) == variantProto.fields().end() )
613 aSheet->ClearVariantField( aParentPath.Path(), name, fieldName );
614 }
615 }
616
617 for( const auto& [key, value] : variantProto.fields() )
618 {
619 wxString fieldName = wxString::FromUTF8( key );
620 wxString fieldValue = wxString::FromUTF8( value );
621
622 if( SCH_FIELD* field = aSheet->GetField( fieldName ) )
623 aSheet->SetFieldText( field, fieldName, fieldValue, &aParentPath, name );
624 }
625 }
626
627 // Remove variants from the sheet (not the schematic) that the client didn't send.
628 if( const SCH_SHEET_INSTANCE* stored = aSheet->GetInstance( aParentPath.Path() ) )
629 {
630 std::vector<wxString> obsolete;
631
632 for( const auto& [name, unused] : stored->m_Variants )
633 {
634 if( !requested.contains( name ) )
635 obsolete.push_back( name );
636 }
637
638 for( const wxString& name : obsolete )
639 aSheet->DeleteVariant( aParentPath.Path(), name );
640 }
641}
642
643
644bool ApplySheetInstance( commands::ItemStatus* aStatus, SCH_SHEET* aSheet,
645 const kiapi::schematic::types::SheetSymbol& aInput,
646 const SCH_SHEET_PATH& aParentPath, SCHEMATIC* aSchematic )
647{
648 if( !ValidateSheetInstance( aStatus, aSheet, aInput ) )
649 return false;
650
651 wxString pageNumber = wxString::FromUTF8( aInput.page_number() );
652 SCH_SHEET_PATH path( aParentPath );
653
654 path.push_back( aSheet );
655
656 // Creates the placement record when it is missing and keeps an existing one's variants; an
657 // empty page number in the request leaves the placement on the page it already has.
658 path.SetPageNumber( pageNumber.IsEmpty() ? path.GetPageNumber() : pageNumber );
659
660 // A request that carries no variant set leaves the placement's variants as they are.
661 if( aInput.has_variants() )
662 applySheetVariants( aSheet, aInput.variants(), aParentPath, aSchematic );
663
664 return true;
665}
666
667
668tl::expected<bool, ApiResponseStatus> UnpackSheet( SCH_SHEET* aOutput,
669 const kiapi::schematic::types::SheetSymbol& aInput )
670{
671 google::protobuf::Any any;
672
673 if( !any.PackFrom( aInput ) || !aOutput->Deserialize( any ) )
674 {
675 ApiResponseStatus e;
676 e.set_status( ApiStatusCode::AS_BAD_REQUEST );
677 e.set_error_message( "could not unpack SCH_SHEET from SheetSymbol in request" );
678 return tl::unexpected( e );
679 }
680
681 return true;
682}
683
684
685void PackSheetPath( types::SheetPath& aOutput, const SCH_SHEET_PATH& aInput )
686{
687 PackSheetPath( aOutput, aInput.Path() );
688 aOutput.set_path_human_readable( aInput.PathHumanReadable().ToUTF8() );
689}
690
691
692tl::expected<SCH_FOCUS_TARGET, ApiResponseStatus>
693ResolveFocusItems( SCHEMATIC& aSchematic, const std::vector<KIID>& aIds, const std::optional<KIID_PATH>& aSheetPath )
694{
695 if( aIds.empty() )
696 return tl::unexpected( MakeResponseStatus( AS_BAD_REQUEST, "no items were given to focus on" ) );
697
698 if( !aSchematic.HasHierarchy() )
699 aSchematic.RefreshHierarchy();
700
701 std::optional<SCH_SHEET_PATH> sheet;
702
703 if( aSheetPath )
704 {
705 sheet = aSchematic.Hierarchy().GetSheetPathByKIIDPath( *aSheetPath );
706
707 if( !sheet )
708 {
709 return tl::unexpected( MakeResponseStatus( AS_BAD_REQUEST, "the requested sheet path is not valid for "
710 "this schematic" ) );
711 }
712 }
713
714 std::optional<BOX2I> bbox;
715 std::vector<std::string> missing;
716
717 for( const KIID& id : aIds )
718 {
719 SCH_SHEET_PATH itemSheet;
720 SCH_ITEM* item = aSheetPath ? sheet->ResolveItem( id ) : aSchematic.ResolveItem( id, &itemSheet, true );
721
722 if( !item )
723 {
724 missing.push_back( id.AsStdString() );
725 continue;
726 }
727
728 if( !sheet )
729 {
730 sheet = itemSheet;
731 }
732 else if( !aSheetPath && itemSheet != *sheet )
733 {
734 return tl::unexpected( MakeResponseStatus( AS_BAD_REQUEST, "the items are not all on one sheet; set "
735 "the document's sheet path to choose the "
736 "sheet to focus" ) );
737 }
738
739 if( bbox )
740 bbox->Merge( item->GetBoundingBox() );
741 else
742 bbox = item->GetBoundingBox();
743 }
744
745 if( !missing.empty() )
746 {
747 return tl::unexpected( MakeResponseStatus( AS_BAD_REQUEST, fmt::format( "the items {} are not in the "
748 "requested document",
749 fmt::join( missing, ", " ) ) ) );
750 }
751
752 return SCH_FOCUS_TARGET{ *sheet, *bbox };
753}
const char * name
KICOMMON_API types::KiCadObjectType ToProtoEnum(KICAD_T aValue)
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
Definition api_enums.cpp:56
static void registerVariant(SCHEMATIC *aSchematic, const wxString &aName, const VariantProto &aInput)
Make the schematic aware of a variant a request named. Accepts either variant message.
bool ValidateSymbolInstance(kiapi::common::commands::ItemStatus *aStatus, const SCH_SYMBOL *aSymbol, const kiapi::schematic::types::SchematicSymbolInstance &aInput, const SCH_SHEET_PATH &aPath, const SCHEMATIC *aSchematic)
Check what ApplySymbolInstance would refuse, so a caller can reject a request before it changes anyth...
static void applySheetVariants(SCH_SHEET *aSheet, const kiapi::schematic::types::SheetVariants &aInput, const SCH_SHEET_PATH &aParentPath, SCHEMATIC *aSchematic)
Make the set of variant records on one placement of a sheet match aInput, by name.
bool ValidateSheetInstance(commands::ItemStatus *aStatus, const SCH_SHEET *aSheet, const kiapi::schematic::types::SheetSymbol &aInput)
std::unique_ptr< EDA_ITEM > CreateItemForType(KICAD_T aType, EDA_ITEM *aContainer)
tl::expected< bool, ApiResponseStatus > UnpackSheet(SCH_SHEET *aOutput, const kiapi::schematic::types::SheetSymbol &aInput)
Unpack the every placement data from the input.
bool ApplySymbolInstance(kiapi::common::commands::ItemStatus *aStatus, SCH_SYMBOL *aSymbol, const kiapi::schematic::types::SchematicSymbolInstance &aInput, const SCH_SHEET_PATH &aPath, SCHEMATIC *aSchematic)
Apply placement-specific data to an aSymbol at aPath: reference, unit, and the per-placement attribut...
std::optional< wxString > FindVariantNoCase(const SCHEMATIC *aSchematic, const wxString &aName)
Variant names are stored and compared exactly, but SCHEMATIC::HasVariant matches case-insensitively.
bool PackSheet(kiapi::schematic::types::SheetSymbol *aOutput, const SCH_SHEET *aInput, const SCH_SHEET_PATH &aPath)
bool ApplySheetInstance(commands::ItemStatus *aStatus, SCH_SHEET *aSheet, const kiapi::schematic::types::SheetSymbol &aInput, const SCH_SHEET_PATH &aParentPath, SCHEMATIC *aSchematic)
static bool applySymbolVariants(kiapi::common::commands::ItemStatus *aStatus, SCH_SYMBOL *aSymbol, const kiapi::schematic::types::SchematicSymbolVariants &aInput, const SCH_SHEET_PATH &aPath, SCHEMATIC *aSchematic)
Make the set of variant records on one placement of a symbol match aInput, by name.
bool PackSymbol(kiapi::schematic::types::SchematicSymbolInstance *aOutput, const SCH_SYMBOL *aInput, const SCH_SHEET_PATH &aPath, const SCHEMATIC *aSchematic)
PIN_MAP_INSTANCE_OVERRIDE UnpackPinMapOverride(const kiapi::schematic::types::PinMapInstanceOverride &aInput)
void PackPinMapOverride(kiapi::schematic::types::PinMapInstanceOverride *aOutput, const PIN_MAP_INSTANCE_OVERRIDE &aOverride)
Pack/unpack a pin-to-pad map instance override to/from its protobuf form (issue #2282).
tl::expected< SCH_FOCUS_TARGET, ApiResponseStatus > ResolveFocusItems(SCHEMATIC &aSchematic, const std::vector< KIID > &aIds, const std::optional< KIID_PATH > &aSheetPath)
Resolve the items of a FocusOnItems request to the sheet that shows them and their combined bounding ...
bool UnpackSymbol(SCH_SYMBOL *aOutput, const kiapi::schematic::types::SchematicSymbolInstance &aInput)
Unpack the geometry, the library definition, fields, and the default-variant attributes that are shar...
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
virtual const BOX2I GetBoundingBox() const
Return the orthogonal bounding box of this object for display purposes.
Definition eda_item.cpp:280
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
Define a library symbol object.
Definition lib_symbol.h:114
Holds all the data relating to one schematic.
Definition schematic.h:155
void AddVariant(const wxString &aVariantName)
wxString GetPackageRefSuffix(const SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aPath) const
Return the suffix the package of a multi-unit symbol's instance composes with.
SCH_ITEM * ResolveItem(const KIID &aID, SCH_SHEET_PATH *aPathOut=nullptr, bool aAllowNullptrReturn=false) const
Definition schematic.h:276
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
bool HasHierarchy() const
Check if the hierarchy has been built.
Definition schematic.h:204
void SetVariantDescription(const wxString &aVariantName, const wxString &aDescription)
Set the description for a variant.
const std::set< wxString > & GetVariantNames() const
Return the set of variant names (without the default placeholder).
Definition schematic.h:770
void RefreshHierarchy()
FIELD_T GetId() const
Definition sch_field.h:143
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
SCHEMATIC * Schematic() const
Search the item hierarchy to find a SCHEMATIC.
Definition sch_item.cpp:302
int GetBodyStyle() const
Definition sch_item.h:253
virtual void SetUnit(int aUnit)
Definition sch_item.h:242
std::optional< SCH_SHEET_PATH > GetSheetPathByKIIDPath(const KIID_PATH &aPath, bool aIncludeLastSheet=true) const
Finds a SCH_SHEET_PATH that matches the provided KIID_PATH.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
wxString PathHumanReadable(bool aUseShortRootName=true, bool aStripTrailingSeparator=false, bool aEscapeSheetNames=false) const
Return the sheet path in a human readable form made from the sheet names.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
void ClearVariantField(const KIID_PATH &aPath, const wxString &aVariantName, const wxString &aFieldName)
void SetFieldText(SCH_FIELD *aField, const wxString &aFieldName, const wxString &aFieldText, const SCH_SHEET_PATH *aPath, const wxString &aVariantName)
void SetExcludedFromSim(bool aExcludeFromSim, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from simulation flag.
const SCH_SHEET_INSTANCE * GetInstance(const KIID_PATH &aParentPath) const
Return this sheet's placement record under aParentPath, or nullptr if it has none.
Definition sch_sheet.h:566
void SetDNP(bool aDNP, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
void SetExcludedFromBOM(bool aExcludeFromBOM, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from schematic bill of materials flag.
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this sheet.
void DeleteVariant(const KIID_PATH &aPath, const wxString &aVariantName)
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
Schematic symbol object.
Definition sch_symbol.h:76
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
void SetFieldText(SCH_FIELD *aField, const wxString &aFieldName, const wxString &aFieldText, const SCH_SHEET_PATH *aPath, const wxString &aVariantName)
virtual void SetDNP(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
bool ClearVariantSymbolOverride(const SCH_SHEET_PATH &aPath, const wxString &aVariantName)
Remove the alternate-symbol override for a given variant and sheet instance.
void SetVariantSymbolOverride(const SCH_SHEET_PATH &aPath, const wxString &aVariantName, const LIB_ID &aLibId)
Set the alternate-symbol override for a given variant and sheet instance.
wxString BaseRefFromUser(const SCH_SHEET_PATH &aSheet, const wxString &aText, wxString &aBase, const SCHEMATIC *aSchematic=nullptr) const
Convert a reference typed on aSheet to the base reference.
void SetExcludedFromSim(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from simulation flag.
PIN_MAP_INSTANCE_OVERRIDE GetPinMapOverride(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
void SetPinMapOverride(const PIN_MAP_INSTANCE_OVERRIDE &aOverride, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString)
Set the per-instance pin-to-pad map override (issue #2282).
void ClearVariantField(const KIID_PATH &aPath, const wxString &aVariantName, const wxString &aFieldName)
void SetRef(const SCH_SHEET_PATH *aSheet, const wxString &aReference)
Set the base reference for the given sheet path for this symbol.
void AddHierarchicalReference(const KIID_PATH &aPath, const wxString &aRef, int aUnit)
Add a full hierarchical reference to this symbol.
void SetExcludedFromPosFiles(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
void SetUserRef(const SCH_SHEET_PATH &aSheet, const wxString &aBase)
Set a base reference chosen by the user on aSheet.
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
bool GetExcludedFromPosFiles(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
bool GetInstance(SCH_SYMBOL_INSTANCE &aInstance, const KIID_PATH &aSheetPath, bool aTestFromEnd=false) const
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
void SetUnitSelection(const SCH_SHEET_PATH *aSheet, int aUnitSelection)
Set the selected unit of this symbol on one sheet.
void SetExcludedFromBOM(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from schematic bill of materials flag.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
void DeleteVariant(const KIID_PATH &aPath, const wxString &aVariantName)
virtual bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flag.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
void SetExcludedFromBoard(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
A type-safe container of any type.
Definition ki_any.h:92
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
KICOMMON_API ApiResponseStatus MakeResponseStatus(ApiStatusCode aCode, const std::string &aMessage)
Definition api_utils.cpp:39
KICOMMON_API void PackSheetPath(types::SheetPath &aOutput, const KIID_PATH &aInput)
KICOMMON_API void PackLibId(types::LibraryIdentifier *aOutput, const LIB_ID &aId)
KICOMMON_API LIB_ID UnpackLibId(const types::LibraryIdentifier &aId)
Class to handle a set of SCH_ITEMs.
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
One symbol-pin to footprint-pad mapping inside a PIN_MAP.
Definition pin_map.h:42
Per-instance override of the active pin map and a sparse delta on top.
Definition pin_map.h:200
std::vector< PIN_MAP_ENTRY > m_Edits
Definition pin_map.h:203
PIN_MAP_OVERRIDE_MODE m_Mode
Definition pin_map.h:201
A simple container for sheet instance information.
std::map< wxString, SCH_SHEET_VARIANT > m_Variants
A list of sheet variants.
A simple container for schematic symbol instance information.
std::map< wxString, SCH_SYMBOL_VARIANT > m_Variants
A list of symbol variants.
#define ALL_UNITS
Definition symbol.h:150
#define ALL_BODY_STYLES
Definition symbol.h:151
@ SHEET_REF_SUFFIX
Optional sheet field appended to the references of the sheet's symbols.
@ REFERENCE
Field Reference of part, i.e. "IC21".
std::string path
KIBIS_PIN * pin
wxLogTrace helper definitions.
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
Definition typeinfo.h:70
@ SCH_GROUP_T
Definition typeinfo.h:169
@ SCH_TABLE_T
Definition typeinfo.h:161
@ SCH_LINE_T
Definition typeinfo.h:159
@ LIB_SYMBOL_T
Definition typeinfo.h:144
@ SCH_NO_CONNECT_T
Definition typeinfo.h:156
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_TABLECELL_T
Definition typeinfo.h:162
@ SCH_FIELD_T
Definition typeinfo.h:146
@ SCH_DIRECTIVE_LABEL_T
Definition typeinfo.h:167
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_SHAPE_T
Definition typeinfo.h:145
@ SCH_RULE_AREA_T
Definition typeinfo.h:166
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCH_BUS_BUS_ENTRY_T
Definition typeinfo.h:158
@ SCH_SCREEN_T
Definition typeinfo.h:198
@ SCH_SHEET_PIN_T
Definition typeinfo.h:170
@ SCH_TEXT_T
Definition typeinfo.h:147
@ SCH_BUS_WIRE_ENTRY_T
Definition typeinfo.h:157
@ SCH_BITMAP_T
Definition typeinfo.h:160
@ SCH_TEXTBOX_T
Definition typeinfo.h:148
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_JUNCTION_T
Definition typeinfo.h:155
@ SCH_PIN_T
Definition typeinfo.h:149