KiCad PCB EDA Suite
Loading...
Searching...
No Matches
schematic.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
21#include <advanced_config.h>
22#include <api/api_enums.h>
23#include <algorithm>
24#include <common.h>
25#include <inspectable_impl.h>
26#include <set>
27#include <tuple>
28#include <variant>
29#include <bus_alias.h>
30#include <commit.h>
31#include <connection_graph.h>
32#include <core/ignore.h>
33#include <core/kicad_algo.h>
34#include <core/profile.h>
35#include <sch_collectors.h>
36#include <erc/erc_settings.h>
37#include <font/outline_font.h>
39#include <pgm_base.h>
40#include <progress_reporter.h>
41#include <project.h>
45#include <refdes_tracker.h>
46#include <schematic.h>
47#include <mail_type.h>
49#include <sch_bus_entry.h>
50#include <sch_commit.h>
51#include <sch_junction.h>
52#include <sch_label.h>
53#include <sch_line.h>
54#include <sch_marker.h>
55#include <api/schematic/schematic_rules.pb.h>
56#include <sch_no_connect.h>
57#include <sch_rule_area.h>
58#include <sch_symbol.h>
59#include <sch_pin.h>
60#include <sch_sheet.h>
61#include <sch_screen.h>
62#include <sch_sheet_pin.h>
63#include <sch_selection_tool.h>
64#include <sim/spice_settings.h>
65#include <sim/spice_value.h>
66#include <trace_helpers.h>
67#include <string_utils.h>
69#include <tool/tool_manager.h>
70#include <undo_redo_container.h>
72#include <local_history.h>
73#include <richio.h>
74#include <sch_io/sch_io_mgr.h>
76#include <sch_io/sch_io.h>
77
79#include <wx/filename.h>
80#include <wx/log.h>
81
83 EDA_ITEM( nullptr, SCHEMATIC_T ),
84 m_project( nullptr ),
85 m_rootSheet( nullptr ),
86 m_schematicHolder( nullptr )
87{
89 m_netChains = std::make_unique<SCH_CONNECTIVITY::NETCHAIN_MANAGER>( this );
91 m_connectivity = std::make_unique<SCH_CONNECTIVITY::FACADE>();
92
93 SetProject( aPrj );
94
95 // Install the text-variable dependency adapter before any sheets load so
96 // add-notifications reach the tracker.
97 m_textVarAdapter = std::make_unique<SCHEMATIC_TEXT_VAR_ADAPTER>( *this );
99
102 [&]( INSPECTABLE* aItem, PROPERTY_BASE* aProperty, COMMIT* aCommit )
103 {
104 // Special case: propagate value, footprint, and datasheet fields to other units
105 // of a given symbol if they aren't in the selection
106
107 SCH_FIELD* field = dynamic_cast<SCH_FIELD*>( aItem );
108
109 if( !field || !IsValid() )
110 return;
111
112 SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( field->GetParent() );
113
114 if( !symbol || aProperty->Name() != _HKI( "Text" ) )
115 return;
116
117 // TODO(JE) This will need to get smarter to enable API access
118 SCH_SHEET_PATH sheetPath = CurrentSheet();
119
120 wxString newValue = aItem->Get<wxString>( aProperty );
121
122 if( field->GetId() == FIELD_T::REFERENCE )
123 {
124 wxString base;
125
126 if( symbol->BaseRefFromUser( sheetPath, newValue, base ).IsEmpty() )
127 symbol->SetUserRef( sheetPath, base );
128 else
129 symbol->SetRef( &sheetPath, newValue );
130
131 // The user might want to change all the units to the new ref. Or they
132 // might not. Since we have no way of knowing, we default to the most
133 // concrete action (change only the selected reference).
134 return;
135 }
136
137 wxString ref = symbol->GetRef( &sheetPath );
138 int unit = symbol->GetUnit();
139 LIB_ID libId = symbol->GetLibId();
140
141 for( SCH_SHEET_PATH& sheet : Hierarchy() )
142 {
143 std::vector<SCH_SYMBOL*> otherUnits;
144
145 CollectOtherUnits( ref, unit, libId, sheet, &otherUnits );
146
147 for( SCH_SYMBOL* otherUnit : otherUnits )
148 {
149 switch( field->GetId() )
150 {
151 case FIELD_T::VALUE:
154 {
155 if( aCommit )
156 aCommit->Modify( otherUnit, sheet.LastScreen() );
157
158 otherUnit->GetField( field->GetId() )->SetText( newValue );
159 break;
160 }
161
162 default: break;
163 }
164 }
165 }
166 } );
167
168 Reset();
169}
170
171
173{
174 m_connectivity->Clear();
176
177 delete m_currentSheet;
178 delete m_connectionGraph;
179 delete m_rootSheet;
180}
181
182
184{
185 m_importNetMap.reset();
187 m_connectivity->Clear();
188
189 delete m_rootSheet;
190
191 m_rootSheet = nullptr;
192 m_topLevelSheets.clear();
193 m_hierarchy.clear();
195
196 m_connectionGraph->Reset();
197 m_currentSheet->clear();
198
199 m_busAliases.clear();
200
204}
205
206
208{
209 if( m_project )
210 {
211 PROJECT_FILE& project = m_project->GetProjectFile();
212
213 // ERC exclusions migrations can't be resolved until the schematic is loaded.
214 // Make sure to process them here if they exist so that they get persisted by the save below.
215 if( project.m_ErcSettings && !project.m_ErcSettings->m_ErcExclusionsLegacy.empty() )
217
218 // d'tor will save settings to file
219 delete project.m_ErcSettings;
220 project.m_ErcSettings = nullptr;
221
222 // d'tor will save settings to file
223 delete project.m_SchematicSettings;
224 project.m_SchematicSettings = nullptr;
225 }
226
228 m_project = aPrj;
229
230 if( m_project )
231 {
232 PROJECT_FILE& project = m_project->GetProjectFile();
233 project.m_ErcSettings = new ERC_SETTINGS( &project, "erc" );
234 project.m_SchematicSettings = new SCHEMATIC_SETTINGS( &project, "schematic" );
235
236 project.m_SchematicSettings->LoadFromFile();
237 project.m_SchematicSettings->m_NgspiceSettings->LoadFromFile();
238 project.m_ErcSettings->LoadFromFile();
239
241 }
242}
243
244
246{
247 wxASSERT( m_project );
248
249 // Cache all existing annotations in the REFDES_TRACKER
250 std::shared_ptr<REFDES_TRACKER> refdesTracker = m_project->GetProjectFile().m_SchematicSettings->m_refDesTracker;
251
252 SCH_SHEET_LIST sheets = Hierarchy();
253 SCH_REFERENCE_LIST references;
254
255 sheets.GetSymbols( references, SYMBOL_FILTER_NON_POWER );
256
257 for( const SCH_REFERENCE& ref : references )
258 {
259 refdesTracker->Insert( ref.GetCanonicalRef( false ).ToStdString() );
260 }
261}
262
263
264bool SCHEMATIC::Contains( const SCH_REFERENCE& aRef ) const
265{
266 SCH_SHEET_LIST sheets = Hierarchy();
267 SCH_REFERENCE_LIST references;
268
273 sheets.GetSymbols( references, SYMBOL_FILTER_NON_POWER );
274
275 // Bases can differ where composed references meet, as U1 on _M2 and U1_M2 on the root, so the
276 // package is the composed reference and the unit is compared by number
277 auto packageUnit =
278 []( const SCH_REFERENCE& aReference )
279 {
280 int unit = aReference.GetSymbol()->GetUnitCount() > 1 ? aReference.GetUnit() : 0;
281 return std::make_pair( aReference.GetComposedRef(), unit );
282 };
283
284 return std::any_of( references.begin(), references.end(),
285 [&]( const SCH_REFERENCE& ref )
286 {
287 return packageUnit( ref ) == packageUnit( aRef );
288 } );
289}
290
291
293{
294 if( m_rootSheet && m_rootSheet->m_Uuid == niluuid )
295 {
296 if( !m_rootSheet->GetScreen() )
297 m_rootSheet->SetScreen( new SCH_SCREEN( this ) );
298
299 return;
300 }
301
302 SCH_SHEET* previousRoot = m_rootSheet;
303
304 m_rootSheet = new SCH_SHEET( this );
305 const_cast<KIID&>( m_rootSheet->m_Uuid ) = niluuid;
306 m_rootSheet->SetScreen( new SCH_SCREEN( this ) );
307
308 if( previousRoot )
309 {
310 previousRoot->SetParent( m_rootSheet );
311
312 if( m_rootSheet->GetScreen() )
313 m_rootSheet->GetScreen()->Append( previousRoot );
314
315 m_topLevelSheets.clear();
316 m_topLevelSheets.push_back( previousRoot );
317 }
318}
319
320
322{
323 // Early exit if we're already in the process of setting top-level sheets to avoid recursion
325 return;
326
328
329 if( !m_topLevelSheets.empty() )
330 return;
331
332 SCH_SHEET* rootSheet = new SCH_SHEET( this );
333 SCH_SCREEN* rootScreen = new SCH_SCREEN( this );
334
335 rootSheet->SetScreen( rootScreen );
336 rootSheet->SyncUuidToScreen();
337
338 SetTopLevelSheets( { rootSheet } );
339
340 SCH_SHEET_PATH rootSheetPath;
341 rootSheetPath.push_back( m_rootSheet );
342 rootSheetPath.push_back( rootSheet );
343 rootSheetPath.SetPageNumber( wxT( "1" ) );
344}
345
346
348{
349 if( m_topLevelSheets.empty() )
350 return;
351
352 if( m_currentSheet->empty() || !IsTopLevelSheet( m_currentSheet->at( 0 ) ) )
353 {
354 m_currentSheet->clear();
355 m_currentSheet->push_back( m_topLevelSheets[0] );
356 }
357}
358
359
360void SCHEMATIC::rebuildHierarchyState( bool aResetConnectionGraph )
361{
362 // Loaders and importers fill screens directly, bypassing the item listeners
363 if( m_textVarAdapter )
364 m_textVarAdapter->MarkHierarchyChanged();
365
367
368 if( aResetConnectionGraph )
369 {
370 m_connectivity->Clear();
371
372 if( m_project )
373 m_connectionGraph->Reset();
374 }
375
376 m_variantNames.clear();
377
378 if( m_rootSheet && m_rootSheet->GetScreen() )
379 {
380 SCH_SCREENS screens( m_rootSheet );
381 std::set<wxString> variantNames = screens.GetVariantNames();
382 m_variantNames.insert( variantNames.begin(), variantNames.end() );
383 }
384
385 // Also include variants from the project file that may not have any diffs yet.
386 // This ensures newly created variants with no symbol changes are preserved.
387 if( m_project )
388 {
389 for( const auto& [name, description] : Settings().m_VariantDescriptions )
390 m_variantNames.insert( name );
391 }
392}
393
394
395void SCHEMATIC::SetTopLevelSheets( const std::vector<SCH_SHEET*>& aSheets )
396{
397 wxCHECK_RET( !aSheets.empty(), wxS( "Cannot set empty top-level sheets!" ) );
398
399 // Set the recursion guard early before any calls to ensureDefaultTopLevelSheet()
400 bool wasAlreadySetting = m_settingTopLevelSheets;
402
403 std::vector<SCH_SHEET*> validSheets;
404 validSheets.reserve( aSheets.size() );
405
406 for( SCH_SHEET* sheet : aSheets )
407 {
408 // Skip null sheets and virtual roots (which have niluuid)
409 if( sheet && sheet->m_Uuid != niluuid )
410 validSheets.push_back( sheet );
411 }
412
413 if( validSheets.empty() )
414 {
415 // Guard against re-entry to prevent infinite recursion
416 if( !wasAlreadySetting )
418
419 m_settingTopLevelSheets = wasAlreadySetting;
420 return;
421 }
422
424
425 std::set<SCH_SHEET*> desiredSheets( validSheets.begin(), validSheets.end() );
426
427 if( m_rootSheet->GetScreen() )
428 {
429 for( SCH_ITEM* item : m_rootSheet->GetScreen()->Items() )
430 {
431 SCH_SHEET* sheet = dynamic_cast<SCH_SHEET*>( item );
432
433 if( sheet && !desiredSheets.contains( sheet ) )
434 delete sheet;
435 }
436
437 m_rootSheet->GetScreen()->Clear( false );
438 }
439
440 m_currentSheet->clear();
441 m_topLevelSheets.clear();
442
443 for( SCH_SHEET* sheet : validSheets )
444 {
445 // Parent to the root sheet, not the root screen. SCH_SCREEN::Append() reparents to
446 // itself, so this has to follow it. A headless import reaches the schematic through
447 // the sheet, and SCHEMATIC::AdoptContent() parents the same way.
448 if( m_rootSheet->GetScreen() )
449 m_rootSheet->GetScreen()->Append( sheet );
450
451 sheet->SetParent( m_rootSheet );
452 m_topLevelSheets.push_back( sheet );
453 }
454
456 rebuildHierarchyState( true );
457
458 // A single top level sheet recovered its packages when it loaded
459 if( validSheets.size() > 1 )
460 m_hierarchy.RecoverPackageRefs();
461
462 m_settingTopLevelSheets = wasAlreadySetting;
463}
464
465
467{
468 wxCHECK_RET( aContent.connectionGraph && aContent.connectionGraph->m_ownedNetChains,
469 wxS( "AdoptContent requires a staged graph with its own netchain manager" ) );
470
471 SCH_SHEET* target = aContent.targetSheet ? aContent.targetSheet : m_rootSheet;
472 SCH_SCREEN* outgoingScreen = nullptr;
473
474 // Replacing the screen while also replacing the top level sheets frees the outgoing sheets
475 // twice, once through the screen's R-tree and once through the sheet list
476 wxCHECK_RET( !aContent.screen || aContent.topLevelSheets.empty(),
477 wxS( "AdoptContent cannot replace both the screen and the top level sheets" ) );
478
479 // The virtual root's screen owns the top level sheets through its R-tree, so replacing it
480 // outright frees sheets that m_topLevelSheets still names
481 wxCHECK_RET( !aContent.screen || target != m_rootSheet,
482 wxS( "AdoptContent cannot replace the virtual root screen" ) );
483
484 // Replacing the top level sheets deletes the outgoing ones and everything below them, so the
485 // only coherent target is the virtual root whose container index is being replaced with it
486 wxCHECK_RET( aContent.topLevelSheets.empty() || target == m_rootSheet,
487 wxS( "AdoptContent can only replace the top level sheets through the virtual root" ) );
488
489 m_connectivity->Clear();
490
491 if( aContent.screen )
492 {
493 // A sheet and its screen are one identity to the rest of the schematic, so the
494 // incoming screen inherits the identity of the sheet it is hung on.
495 aContent.screen->m_uuid = target->m_Uuid;
496 aContent.screen->IncRefCount();
497 outgoingScreen = std::exchange( target->m_screen, aContent.screen.release() );
498 }
499 else if( SCH_SCREEN* screen = target->GetScreen() )
500 {
501 screen->m_rtree = std::move( aContent.screenItems );
502
503 if( aContent.screenLibSymbols )
504 screen->m_libSymbols.swap( aContent.screenLibSymbols->m_libSymbols );
505
506 --screen->m_modification_sync;
507 screen->BumpConnectivityRevision();
508
509 // The index now owns what it names, so the staged items lose their owners.
510 for( std::unique_ptr<SCH_ITEM>& item : aContent.itemOwners )
511 item.release();
512 }
513
514 std::vector<SCH_SHEET*> outgoingTopLevelSheets;
515
516 if( !aContent.topLevelSheets.empty() )
517 {
518 outgoingTopLevelSheets.swap( m_topLevelSheets );
519 m_topLevelSheets = std::move( aContent.topLevelSheets );
520
521 for( SCH_SHEET* sheet : m_topLevelSheets )
522 sheet->SetParent( m_rootSheet );
523 }
524
525 m_hierarchy.swap( aContent.hierarchy );
527
528 if( aContent.currentSheet )
529 m_currentSheet->Swap( *aContent.currentSheet );
530
531 m_labelToPageRefsMap.clear();
532
533 CONNECTION_GRAPH* outgoingGraph = std::exchange( m_connectionGraph, aContent.connectionGraph.release() );
534
535 // The outgoing graph, deleted below, still points at a replaced manager
536 std::unique_ptr<SCH_CONNECTIVITY::NETCHAIN_MANAGER> outgoingNetChains;
537
538 if( aContent.preserveNetChains )
539 m_connectionGraph->BorrowNetChains( *m_netChains );
540 else
541 outgoingNetChains = std::exchange( m_netChains, m_connectionGraph->ReleaseNetChains() );
542
543 m_connectionGraph->SetSchematic( this );
544
545
546 // The hierarchy and the current sheet named sheets that the outgoing screen and the
547 // outgoing top level sheets own, so neither could be destroyed before now.
548 for( SCH_SHEET* sheet : outgoingTopLevelSheets )
549 delete sheet;
550
551 if( outgoingScreen )
552 {
553 outgoingScreen->DecRefCount();
554
555 if( outgoingScreen->GetRefCount() == 0 )
556 delete outgoingScreen;
557 }
558
559 if( aContent.embeddedFiles )
560 {
561 *GetEmbeddedFiles() = std::move( *aContent.embeddedFiles );
562 Settings().m_SchDrawingSheetFileName.swap( aContent.drawingSheetFileName );
563 }
564
565 // Anything still reachable once the outgoing sheets and screen are gone survived the adoption
566 // while holding SCH_CONNECTIONs that name the outgoing graph. Symbol and sheet pins carry
567 // their own connection maps, so the indexed items alone are not enough, and Recalculate only
568 // re-points what it considers dirty.
569 SCH_SCREENS retained( Root() );
570
571 for( SCH_SCREEN* screen = retained.GetFirst(); screen; screen = retained.GetNext() )
572 {
573 for( SCH_ITEM* item : screen->Items() )
574 {
575 item->SetConnectionGraph( m_connectionGraph );
576
577 if( SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( item ) )
578 {
579 for( std::unique_ptr<SCH_PIN>& pin : symbol->GetRawPins() )
580 pin->SetConnectionGraph( m_connectionGraph );
581 }
582 else if( SCH_SHEET* sheet = dynamic_cast<SCH_SHEET*>( item ) )
583 {
584 for( SCH_SHEET_PIN* pin : sheet->GetPins() )
585 pin->SetConnectionGraph( m_connectionGraph );
586 }
587 }
588 }
589
590 delete outgoingGraph;
591
592 if( m_textVarAdapter )
593 m_textVarAdapter->RebuildIndex();
594}
595
596
598{
599 // Virtual root's screen is just a container - return the first top-level sheet's screen
600 // which is what callers actually want
601 if( !m_topLevelSheets.empty() && m_topLevelSheets[0] )
602 return m_topLevelSheets[0]->GetScreen();
603
604 return nullptr;
605}
606
607
609{
610 wxCHECK( !m_hierarchy.empty(), m_hierarchy );
611
612 return m_hierarchy;
613}
614
615
617{
618 return !m_hierarchy.empty() && m_hierarchy.IsModified();
619}
620
621
632
633
635{
637
638 m_refSuffixes.clear();
640 m_hasRefSuffixFields = false;
641
642 for( const SCH_SHEET_PATH& path : m_hierarchy )
643 {
644 if( const SCH_FIELD* field = std::as_const( *path.Last() ).GetField( FIELD_T::SHEET_REF_SUFFIX ) )
645 m_hasRefSuffixFields |= !field->GetText().IsEmpty();
646
647 wxString suffix = path.ComposeRefSuffix();
648
649 m_refSuffixesBySheetHash.emplace( path.GetCurrentHash(), suffix );
650
651 if( !suffix.IsEmpty() )
652 m_refSuffixes.emplace( path.Path(), std::move( suffix ) );
653 }
654}
655
656
657const wxString* SCHEMATIC::findRefSuffix( const SCH_SHEET_PATH& aPath ) const
658{
659 if( !HasRefSuffixes() )
660 return nullptr;
661
662 if( auto it = m_refSuffixesBySheetHash.find( aPath.GetCurrentHash() ); it != m_refSuffixesBySheetHash.end() )
663 return &it->second;
664
665 // A path built apart from the hierarchy may hash differently, as one differing only in the virtual root does
666 auto it = m_refSuffixes.find( aPath.PathRef() );
667
668 return it == m_refSuffixes.end() ? nullptr : &it->second;
669}
670
671
672wxString SCHEMATIC::GetRefSuffix( const SCH_SHEET_PATH& aPath ) const
673{
674 const wxString* suffix = findRefSuffix( aPath );
675
676 return suffix ? *suffix : wxString();
677}
678
679
680void SCHEMATIC::AppendRefSuffix( wxString& aRef, const SCH_SHEET_PATH& aPath ) const
681{
682 if( const wxString* suffix = findRefSuffix( aPath ) )
683 aRef += *suffix;
684}
685
686
687wxString SCHEMATIC::GetRefSuffix( const KIID_PATH& aPath ) const
688{
689 // Designs without suffixes skip the path hash
690 if( !HasRefSuffixes() )
691 return wxEmptyString;
692
693 auto it = m_refSuffixes.find( aPath );
694
695 return it == m_refSuffixes.end() ? wxString() : it->second;
696}
697
698
699std::optional<wxString> SCHEMATIC::spanningPackageSuffix( const SCH_SYMBOL* aSymbol, const KIID_PATH& aPath ) const
700{
701 if( aSymbol->GetUnitCount() <= 1 )
702 return std::nullopt;
703
704 std::lock_guard<std::mutex> lock( m_packageSuffixesMutex );
706
707 if( m_packageSuffixes.empty() )
708 return std::nullopt;
709
710 if( auto it = m_packageSuffixes.find( { aSymbol->m_Uuid, aPath } ); it != m_packageSuffixes.end() )
711 return it->second;
712
713 return std::nullopt;
714}
715
716
717wxString SCHEMATIC::GetPackageRefSuffix( const SCH_SYMBOL* aSymbol, const SCH_SHEET_PATH& aPath ) const
718{
719 if( !HasRefSuffixes() )
720 return wxEmptyString;
721
722 if( std::optional<wxString> suffix = spanningPackageSuffix( aSymbol, aPath.PathRef() ) )
723 return *suffix;
724
725 return GetRefSuffix( aPath );
726}
727
728
729wxString SCHEMATIC::GetPackageRefSuffix( const SCH_SYMBOL* aSymbol, const KIID_PATH& aPath ) const
730{
731 if( !HasRefSuffixes() )
732 return wxEmptyString;
733
734 if( std::optional<wxString> suffix = spanningPackageSuffix( aSymbol, aPath ) )
735 return *suffix;
736
737 return GetRefSuffix( aPath );
738}
739
740
741wxString SCHEMATIC::GetUnitRefSuffix( const SCH_SYMBOL* aSymbol, const SCH_SHEET_PATH& aPath, int aUnit ) const
742{
743 if( !HasRefSuffixes() )
744 return wxEmptyString;
745
746 {
747 std::lock_guard<std::mutex> lock( m_packageSuffixesMutex );
749
750 auto group = m_packageUnitSuffixes.find( { aSymbol->GetBaseRef( &aPath ), aSymbol->GetLibId().Format() } );
751
752 if( group != m_packageUnitSuffixes.end() )
753 {
754 if( auto unit = group->second.find( aUnit ); unit != group->second.end() )
755 return unit->second;
756 }
757 }
758
759 // An unplaced unit belongs to the package as a whole
760 return GetPackageRefSuffix( aSymbol, aPath );
761}
762
763
765{
766 if( aSymbol->GetUnitCount() < 2 )
767 return false;
768
769 std::lock_guard<std::mutex> lock( m_packageSuffixesMutex );
771 return m_unitSplitSymbols.contains( aSymbol->m_Uuid );
772}
773
774
776{
777 std::map<KIID_PATH, std::vector<std::pair<KIID, wxString>>> packagesOn;
778
779 for( const auto& [key, suffix] : PackageRefSuffixes() )
780 packagesOn[key.second].emplace_back( key.first, suffix );
781
782 std::string reply = std::string( MAIL_SCH_REF_SUFFIXES_TAG ) + "\n";
783
784 for( const SCH_SHEET_PATH& path : m_hierarchy )
785 {
786 const wxString sheet = path.PathAsString();
787 reply += sheet.ToStdString() + "\t" + std::string( GetRefSuffix( path ).ToUTF8() ) + "\n";
788
789 // A footprint placed from such an instance carries the package suffix in its reference
790 for( const auto& [symbol, suffix] : packagesOn[path.Path()] )
791 reply += ( sheet + symbol.AsString() ).ToStdString() + "\t" + std::string( suffix.ToUTF8() ) + "\n";
792 }
793
794 return reply;
795}
796
797
798std::set<KIID> SCHEMATIC::SplitUnitSymbols() const
799{
800 std::lock_guard<std::mutex> lock( m_packageSuffixesMutex );
802 return m_unitSplitSymbols;
803}
804
805
806std::map<std::pair<KIID, KIID_PATH>, wxString> SCHEMATIC::PackageRefSuffixes() const
807{
808 if( !HasRefSuffixes() )
809 return {};
810
811 std::lock_guard<std::mutex> lock( m_packageSuffixesMutex );
813 return m_packageSuffixes;
814}
815
816
818{
819 const uint64_t generation = SCH_SYMBOL::RefGeneration();
820
821 if( m_packageSuffixesGeneration == generation )
822 return;
823
824 struct MEMBER
825 {
826 KIID symbol;
828 int unit;
829 wxString suffix;
830 };
831
832 std::map<std::pair<wxString, wxString>, std::vector<MEMBER>> groups;
833 std::map<std::pair<wxString, wxString>, std::set<int>> units;
834 std::set<std::pair<wxString, wxString>> repeated;
835 std::map<KIID, int> firstUnit;
836
837 // Reused sheets share a screen, so scan each screen once
838 std::unordered_map<const SCH_SCREEN*, std::vector<const SCH_SYMBOL*>> multiUnitSymbols;
839
840 m_unitSplitSymbols.clear();
841
842 for( const SCH_SHEET_PATH& path : m_hierarchy )
843 {
844 auto [screenSymbols, scan] = multiUnitSymbols.try_emplace( path.LastScreen() );
845
846 if( scan )
847 {
848 for( SCH_ITEM* item : path.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
849 {
850 const SCH_SYMBOL* symbol = static_cast<const SCH_SYMBOL*>( item );
851
852 if( symbol->GetUnitCount() > 1 )
853 screenSymbols->second.push_back( symbol );
854 }
855 }
856
857 for( const SCH_SYMBOL* symbol : screenSymbols->second )
858 {
859 SCH_SYMBOL_INSTANCE instance;
860
861 if( !symbol->GetInstance( instance, path.PathRef() ) )
862 continue;
863
864 if( auto [it, inserted] = firstUnit.emplace( symbol->m_Uuid, instance.m_Unit );
865 !inserted && it->second != instance.m_Unit )
866 {
867 m_unitSplitSymbols.insert( symbol->m_Uuid );
868 }
869
870 if( instance.m_Reference.IsEmpty() || instance.m_Reference.EndsWith( wxS( "?" ) ) )
871 continue;
872
873 std::pair<wxString, wxString> key( instance.m_Reference, symbol->GetLibId().Format() );
874
875 if( !units[key].insert( instance.m_Unit ).second )
876 repeated.insert( key );
877
878 const wxString* suffix = findRefSuffix( path );
879
880 groups[key].push_back( { symbol->m_Uuid, path.PathRef(), instance.m_Unit, suffix ? *suffix : wxString() } );
881 }
882 }
883
884 m_packageSuffixes.clear();
885 m_packageUnitSuffixes.clear();
886
887 for( const auto& [key, members] : groups )
888 {
889 if( repeated.count( key ) )
890 continue;
891
892 wxString lowest = members.front().suffix;
893
894 for( const MEMBER& member : members )
895 lowest = std::min( lowest, member.suffix );
896
897 for( const MEMBER& member : members )
898 {
899 if( member.suffix != lowest )
900 m_packageSuffixes[{ member.symbol, member.path }] = lowest;
901 }
902
903 if( std::ranges::any_of( members, [&]( const MEMBER& m ) { return m.suffix != lowest; } ) )
904 {
905 for( const MEMBER& member : members )
906 m_packageUnitSuffixes[key][member.unit] = member.suffix;
907 }
908 }
909
910 m_packageSuffixesGeneration = generation;
911}
912
913
914std::vector<std::pair<SCH_SHEET_PATH, SCH_SHEET_PATH>> SCHEMATIC::RefSuffixCollisions( bool aIncludeEmpty ) const
915{
916 std::vector<std::pair<SCH_SHEET_PATH, SCH_SHEET_PATH>> collisions;
917 std::map<std::pair<const SCH_SCREEN*, wxString>, const SCH_SHEET_PATH*> firstUse;
918
919 for( const SCH_SHEET_PATH& path : m_hierarchy )
920 {
921 const wxString suffix = GetRefSuffix( path );
922
923 if( suffix.IsEmpty() && !aIncludeEmpty )
924 continue;
925
926 auto [it, inserted] = firstUse.emplace( std::make_pair( path.LastScreen(), suffix ), &path );
927
928 if( !inserted )
929 collisions.emplace_back( path, *it->second );
930 }
931
932 return collisions;
933}
934
935
936void SCHEMATIC::GetContextualTextVars( wxArrayString* aVars ) const
937{
938 auto add =
939 [&]( const wxString& aVar )
940 {
941 if( !alg::contains( *aVars, aVar ) )
942 aVars->push_back( aVar );
943 };
944
945 add( wxT( "#" ) );
946 add( wxT( "##" ) );
947 add( wxT( "SHEETPATH" ) );
948 add( wxT( "SHEETNAME" ) );
949 add( wxT( "FILENAME" ) );
950 add( wxT( "FILEPATH" ) );
951 add( wxT( "PROJECTNAME" ) );
952 add( wxT( "VARIANT" ) );
953 add( wxT( "VARIANT_DESC" ) );
954
955 if( !CurrentSheet().empty() )
957
958 for( std::pair<wxString, wxString> entry : m_project->GetTextVars() )
959 add( entry.first );
960}
961
962
963bool SCHEMATIC::ResolveTextVar( const SCH_SHEET_PATH* aSheetPath, wxString* token, int aDepth ) const
964{
965 wxCHECK( aSheetPath, false );
966
967 if( token->IsSameAs( wxT( "#" ) ) )
968 {
969 *token = aSheetPath->GetPageNumber();
970 return true;
971 }
972 else if( token->IsSameAs( wxT( "##" ) ) )
973 {
974 int i = 0;
975
976 for( SCH_SHEET* sheet : GetTopLevelSheets() )
977 i += sheet->CountSheets();
978
979 *token = wxString::Format( "%i", i );
980 return true;
981 }
982 else if( token->IsSameAs( wxT( "SHEETPATH" ) ) )
983 {
984 *token = aSheetPath->PathHumanReadable();
985 return true;
986 }
987 else if( token->IsSameAs( wxT( "SHEETNAME" ) ) )
988 {
989 *token = aSheetPath->Last()->GetName();
990 return true;
991 }
992 else if( token->IsSameAs( wxT( "FILENAME" ) ) )
993 {
994 wxFileName fn( GetFileName() );
995 *token = fn.GetFullName();
996 return true;
997 }
998 else if( token->IsSameAs( wxT( "FILEPATH" ) ) )
999 {
1000 wxFileName fn( GetFileName() );
1001 *token = fn.GetFullPath();
1002 return true;
1003 }
1004 else if( token->IsSameAs( wxT( "PROJECTNAME" ) ) )
1005 {
1006 *token = m_project->GetProjectName();
1007 return true;
1008 }
1009 else if( token->IsSameAs( wxT( "VARIANTNAME" ) ) || token->IsSameAs( wxT( "VARIANT" ) ) )
1010 {
1011 *token = m_currentVariant;
1012 return true;
1013 }
1014 else if( token->IsSameAs( wxT( "VARIANT_DESC" ) ) )
1015 {
1017 return true;
1018 }
1019
1020 // aSheetPath->LastScreen() can be null during schematic loading
1021 if( aSheetPath->LastScreen()
1022 && aSheetPath->LastScreen()->GetTitleBlock().TextVarResolver( token, m_project, INTERNAL ) )
1023 {
1024 return true;
1025 }
1026
1027 if( m_project->TextVarResolver( token ) )
1028 return true;
1029
1030 return false;
1031}
1032
1033
1035{
1036 // With virtual root pattern, m_rootSheet is the virtual root with no file
1037 // Return filename from first top-level sheet if available
1038 if( !IsValid() )
1039 return wxString( wxEmptyString );
1040
1041 if( !m_topLevelSheets.empty() && m_topLevelSheets[0]->GetScreen() )
1042 return m_topLevelSheets[0]->GetScreen()->GetFileName();
1043
1044 return wxString( wxEmptyString );
1045}
1046
1047
1049{
1050 if( !m_project )
1051 {
1052 static SCHEMATIC_SETTINGS defaultSettings( nullptr, "schematic" );
1053 return defaultSettings;
1054 }
1055 wxASSERT( m_project );
1056 return *m_project->GetProjectFile().m_SchematicSettings;
1057}
1058
1059
1061{
1062 wxASSERT( m_project );
1063 return *m_project->GetProjectFile().m_ErcSettings;
1064}
1065
1066
1067std::vector<SCH_MARKER*> SCHEMATIC::ResolveERCExclusions()
1068{
1069 SCH_SHEET_LIST sheetList = Hierarchy();
1070 ERC_SETTINGS& settings = ErcSettings();
1071
1074
1075 // Child exclusions need the loaded hierarchy to recover nonpersistent item IDs.
1076 for( const auto& [markerData, comment] : settings.m_ErcExclusionsLegacy )
1077 {
1078 ERC_EXCLUSION exclusion = ERC_EXCLUSION::FromLegacyStrings( sheetList, markerData, comment );
1079
1080 if( !exclusion.GetSortKey().empty() )
1081 {
1082 // Legacy format can sometimes have the same exclusion multiple times,
1083 // without and with a comment. If this happens, replace the existing one
1084 // if we can go from no comment to comment
1085 auto [it, inserted] = settings.m_ErcExclusions.insert( exclusion );
1086
1087 if( !inserted && !comment.empty() && it->GetComment().empty() )
1088 {
1089 ERC_EXCLUSION updated = *it;
1090 updated.SetComment( comment );
1091 settings.m_ErcExclusions.erase( it );
1092 settings.m_ErcExclusions.insert( updated );
1093 }
1094 }
1095 }
1096
1097 settings.m_ErcExclusionsLegacy.clear();
1098
1099 using GROUP_ANCHOR = std::variant<KIID, std::pair<int, int>>;
1100 using GROUP_KEY = std::tuple<int, KIID_PATH, GROUP_ANCHOR>;
1101 std::map<GROUP_KEY, SCH_MARKER*> groupMarkers;
1102 using NC_GROUPS = std::map<std::pair<KIID_PATH, VECTOR2I>, SCH_CONNECTIVITY::NO_CONNECT_PIN_CONFLICT,
1104 std::optional<NC_GROUPS> ncGroups;
1105 std::optional<std::map<GROUP_KEY, KIID>> ncFlagGroups;
1106 std::optional<std::map<GROUP_KEY, KIID>> hierarchyGroups;
1107 std::optional<std::vector<SCH_CONNECTIVITY::LABEL_WIRE_CONFLICT>> labelWireGroups;
1108 std::optional<std::vector<SCH_CONNECTIVITY::FOUR_WAY_JUNCTION>> fourWayGroups;
1109
1110 const auto groupKey =
1111 [&]( const SCH_MARKER& aMarker ) -> std::optional<GROUP_KEY>
1112 {
1113 const auto error = std::static_pointer_cast<ERC_ITEM>( aMarker.GetRCItem() );
1114
1115 const bool ncPin = error->GetErrorCode() == ERCE_NOCONNECT_CONNECTED
1116 && !error->MainItemHasSheetPath() && !error->AuxItemHasSheetPath();
1117
1118 static const std::set<int> groupedCodes = { ERCE_WIRE_DANGLING, ERCE_BUS_TO_NET_CONFLICT,
1123
1124 if( !ADVANCED_CFG::GetCfg().m_ConnectivityEngine || !groupedCodes.contains( error->GetErrorCode() )
1125 || !error->IsSheetSpecific() )
1126 {
1127 return std::nullopt;
1128 }
1129
1130 if( error->GetErrorCode() == ERCE_FOUR_WAY_JUNCTION )
1131 {
1132 if( error->MainItemHasSheetPath() || error->AuxItemHasSheetPath() )
1133 return std::nullopt;
1134
1135 if( !fourWayGroups )
1136 fourWayGroups = m_connectivity->Engine().FourWayJunctions();
1137
1138 const KIID_PATH& path = error->GetSpecificSheetPath().PathRef();
1139 const VECTOR2I position = aMarker.GetPosition();
1140 const auto group = std::lower_bound( fourWayGroups->begin(), fourWayGroups->end(),
1141 std::tie( path, position.x, position.y ),
1142 []( const auto& junction, const auto& location )
1143 {
1144 return std::tie( junction.sheet, junction.position.x, junction.position.y ) < location;
1145 } );
1146
1147 if( group == fourWayGroups->end() || group->sheet != path || group->position != position )
1148 return std::nullopt;
1149
1150 for( const KIID& id : error->GetIDs() )
1151 {
1152 if( !std::binary_search( group->equivalentItems.begin(), group->equivalentItems.end(), id ) )
1153 return std::nullopt;
1154 }
1155
1156 return GROUP_KEY{ ERCE_FOUR_WAY_JUNCTION, path, std::pair{ position.x, position.y } };
1157 }
1158
1159 const SCH_ITEM* main = ResolveItem( error->GetMainItemID(), nullptr, true );
1160
1161 if( !main || main->GetPosition() != aMarker.GetPosition() )
1162 return std::nullopt;
1163
1164 if( error->GetErrorCode() == ERCE_PIN_NOT_CONNECTED )
1165 {
1166 if( main->Type() != SCH_PIN_T )
1167 return std::nullopt;
1168
1169 // Power-symbol errors identify individual pins, not a canonical witness for an island
1170 if( static_cast<const SCH_PIN*>( main )->GetParentSymbol()->IsPower() )
1171 return std::nullopt;
1172 }
1173
1174 const KIID_PATH& path = error->GetSpecificSheetPath().PathRef();
1175 const auto instance = m_connectivity->Keys().FindInstance( path );
1176
1177 if( !instance )
1178 return std::nullopt;
1179
1180 if( error->GetErrorCode() == ERCE_LABEL_MULTIPLE_WIRES )
1181 {
1182 if( ( main->Type() != SCH_LABEL_T
1183 && main->Type() != SCH_GLOBAL_LABEL_T
1184 && main->Type() != SCH_HIER_LABEL_T )
1185 || error->MainItemHasSheetPath()
1186 || error->AuxItemHasSheetPath() )
1187 {
1188 return std::nullopt;
1189 }
1190
1191 if( !labelWireGroups )
1192 labelWireGroups = m_connectivity->Engine().LabelWireConflicts();
1193
1194 const auto group = std::find_if( labelWireGroups->begin(), labelWireGroups->end(),
1195 [&]( const auto& conflict )
1196 {
1197 return conflict.sheet == path
1198 && conflict.position == aMarker.GetPosition();
1199 } );
1200
1201 if( group == labelWireGroups->end() )
1202 return std::nullopt;
1203
1204 for( const KIID& id : error->GetIDs() )
1205 {
1206 if( id != main->m_Uuid && !std::binary_search( group->wires.begin(), group->wires.end(), id ) )
1207 return std::nullopt;
1208 }
1209
1210 return GROUP_KEY{ ERCE_LABEL_MULTIPLE_WIRES, path, group->label };
1211 }
1212
1213 if( error->GetErrorCode() == ERCE_HIERACHICAL_LABEL )
1214 {
1215 if( !error->MainItemHasSheetPath()
1216 || error->AuxItemHasSheetPath()
1217 || error->GetMainItemSheetPath().PathRef() != path )
1218 {
1219 return std::nullopt;
1220 }
1221
1222 if( !hierarchyGroups )
1223 {
1224 hierarchyGroups.emplace();
1225
1226 for( const auto& diagnostic : m_connectivity->Engine().HierarchyErrors() )
1227 {
1228 for( const KIID& id : diagnostic.equivalentItems )
1229 {
1230 hierarchyGroups->emplace( GROUP_KEY{ ERCE_HIERACHICAL_LABEL, diagnostic.sheet, id },
1231 diagnostic.item );
1232 }
1233 }
1234 }
1235
1236 const auto found = hierarchyGroups->find( { ERCE_HIERACHICAL_LABEL, path, main->m_Uuid } );
1237
1238 if( found == hierarchyGroups->end() )
1239 return std::nullopt;
1240
1241 return GROUP_KEY{ ERCE_HIERACHICAL_LABEL, path, found->second };
1242 }
1243
1244 if( ncPin )
1245 {
1246 if( !ncGroups )
1247 {
1248 ncGroups.emplace();
1249
1250 for( auto& group : m_connectivity->Engine().NoConnectPinConflicts() )
1251 ncGroups->emplace( std::make_pair( group.sheet, group.position ), std::move( group ) );
1252 }
1253
1254 const auto found = ncGroups->find( { path, aMarker.GetPosition() } );
1255
1256 if( found == ncGroups->end() )
1257 return std::nullopt;
1258
1259 const auto& group = found->second;
1260 const auto isPin =
1261 [&]( const KIID& id )
1262 {
1263 return std::binary_search( group.pins.begin(), group.pins.end(), id );
1264 };
1265
1266 if( !isPin( error->GetMainItemID() ) )
1267 return std::nullopt;
1268
1269 for( const KIID& id : error->GetIDs() )
1270 {
1271 if( id == niluuid )
1272 continue;
1273
1274 if( !m_connectivity->GetSubgraphForItem( id, path )
1275 || ( !isPin( id ) && !std::binary_search( group.others.begin(), group.others.end(), id ) ) )
1276 {
1277 return std::nullopt;
1278 }
1279 }
1280
1281 return GROUP_KEY{ error->GetErrorCode(), path, group.pins.front() };
1282 }
1283
1284 if( error->GetErrorCode() == ERCE_NOCONNECT_CONNECTED
1285 || error->GetErrorCode() == ERCE_NOCONNECT_NOT_CONNECTED )
1286 {
1287 if( !error->MainItemHasSheetPath()
1288 || error->AuxItemHasSheetPath()
1289 || error->GetMainItemSheetPath().PathRef() != path )
1290 {
1291 return std::nullopt;
1292 }
1293
1294 KIID flag = niluuid;
1295
1296 for( const KIID& id : error->GetIDs() )
1297 {
1298 const SCH_ITEM* item = ResolveItem( id, nullptr, true );
1299
1300 if( item && item->Type() == SCH_NO_CONNECT_T )
1301 flag = id;
1302 }
1303
1304 const auto& islandOf = m_connectivity->Published().Auxiliary().IslandOf();
1305 const auto flagIsland = islandOf.find( { flag, *instance } );
1306
1307 if( flagIsland == islandOf.end() )
1308 return std::nullopt;
1309
1310 if( !ncFlagGroups )
1311 {
1312 ncFlagGroups.emplace();
1313
1314 for( const auto& diagnostic : m_connectivity->Engine().NoConnectFlagErrors() )
1315 {
1316 const auto inst = m_connectivity->Keys().FindInstance( diagnostic.sheet );
1317 const auto record = inst ? islandOf.find( { diagnostic.flag, *inst } ) : islandOf.end();
1318
1319 if( record == islandOf.end() )
1320 continue;
1321
1322 const int code = diagnostic.connected ? ERCE_NOCONNECT_CONNECTED
1324 ncFlagGroups->emplace( GROUP_KEY{ code, diagnostic.sheet, record->second.anchor },
1325 diagnostic.flag );
1326 }
1327 }
1328
1329 const auto group = ncFlagGroups->find( { error->GetErrorCode(), path, flagIsland->second.anchor } );
1330
1331 if( group == ncFlagGroups->end() )
1332 return std::nullopt;
1333
1334 const auto& rows = m_connectivity->Published().Rows();
1335 const auto flagRow = rows.find( { flag, *instance } );
1336
1337 if( flagRow == rows.end() )
1338 return std::nullopt;
1339
1340 for( const KIID& id : error->GetIDs() )
1341 {
1342 if( id == niluuid || id == flag )
1343 continue;
1344
1345 const SCH_ITEM* item = ResolveItem( id, nullptr, true );
1346 const auto row = rows.find( { id, *instance } );
1347
1348 if( !item || item->Type() != SCH_PIN_T
1349 || row == rows.end()
1350 || row->second.component != flagRow->second.component
1351 || !m_connectivity->GetSubgraphForItem( id, path ) )
1352 {
1353 return std::nullopt;
1354 }
1355 }
1356
1357 return GROUP_KEY{ error->GetErrorCode(), path, group->second };
1358 }
1359
1360 const auto& islands = m_connectivity->Published().Auxiliary().IslandOf();
1361 std::optional<GROUP_KEY> key;
1362
1363 for( const KIID& id : error->GetIDs() )
1364 {
1365 if( id == niluuid )
1366 continue;
1367
1368 const auto island = islands.find( { id, *instance } );
1369
1370 if( !m_connectivity->GetSubgraphForItem( id, path )
1371 || island == islands.end()
1372 || ( key && std::get<2>( *key ) != GROUP_ANCHOR{ island->second.anchor } ) )
1373 {
1374 return std::nullopt;
1375 }
1376
1377 key = GROUP_KEY{ error->GetErrorCode(), path, island->second.anchor };
1378 }
1379
1380 return key;
1381 };
1382
1383 std::set<ERC_EXCLUSION, ERC_EXCLUSION_COMPARE> legacyPathlessExclusions;
1384 std::optional<std::vector<SCH_CONNECTIVITY::OFF_GRID_ENDPOINT>> offGridEndpoints;
1385
1386 const auto findPathless =
1387 [&]( const ERC_EXCLUSION& aLookup )
1388 {
1389 kiapi::schematic::ErcExclusion legacy = aLookup.ToProto();
1390 legacy.mutable_marker()->clear_sheet_specific_path();
1391 legacy.mutable_marker()->clear_main_item_sheet_path();
1392 legacy.mutable_marker()->clear_aux_item_sheet_path();
1393 auto found = settings.m_ErcExclusions.find( ERC_EXCLUSION::FromProto( legacy ) );
1394
1395 if( found != settings.m_ErcExclusions.end() )
1396 legacyPathlessExclusions.insert( *found );
1397
1398 return found;
1399 };
1400
1401 for( const SCH_SHEET_PATH& sheet : sheetList )
1402 {
1403 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_MARKER_T ) )
1404 {
1405 SCH_MARKER* marker = static_cast<SCH_MARKER*>( item );
1406 ERC_EXCLUSION lookup = ERC_EXCLUSION::FromMarker( *marker );
1407 auto it = settings.m_ErcExclusions.find( lookup );
1408
1409 const auto error = std::static_pointer_cast<ERC_ITEM>( marker->GetRCItem() );
1410
1411 if( it == settings.m_ErcExclusions.end()
1412 && !settings.m_ErcExclusions.empty()
1413 && error->IsSheetSpecific()
1414 && error->GetSpecificSheetPath().PathRef() == sheet.PathRef() )
1415 {
1416 const bool engine = ADVANCED_CFG::GetCfg().m_ConnectivityEngine;
1417 const bool hasMain = error->MainItemHasSheetPath();
1418 const bool hasAux = error->AuxItemHasSheetPath();
1419 const bool mainHere = hasMain && error->GetMainItemSheetPath().PathRef() == sheet.PathRef();
1420 const bool auxHere = hasAux && error->GetAuxItemSheetPath().PathRef() == sheet.PathRef();
1421
1422 switch( error->GetErrorCode() )
1423 {
1425 if( engine && !hasMain && !hasAux && sheet.Last()->IsTopLevelSheet() )
1426 {
1427 const SCH_ITEM* source = ResolveItem( error->GetMainItemID(), nullptr, true );
1428
1429 // Root-label exclusions predating instance-specific ERC omitted the sheet path
1430 if( source && source->Type() == SCH_HIER_LABEL_T )
1431 it = findPathless( lookup );
1432 }
1433
1434 break;
1435
1437 case ERCE_GENERIC_ERROR:
1441 if( !marker->IsExcluded() && mainHere && !hasAux )
1442 {
1443 // Older sheet-specific exclusions omitted the main item's sheet path
1444 kiapi::schematic::ErcExclusion previous = lookup.ToProto();
1445 previous.mutable_marker()->clear_main_item_sheet_path();
1446 it = settings.m_ErcExclusions.find( ERC_EXCLUSION::FromProto( previous ) );
1447 }
1448
1449 break;
1450
1459 // Older source diagnostics excluded the item across all of its sheet instances
1460 if( !marker->IsExcluded() && mainHere && !hasAux )
1461 it = findPathless( lookup );
1462
1463 if( it == settings.m_ErcExclusions.end()
1464 && engine
1465 && mainHere
1466 && !hasAux
1467 && error->GetErrorCode() == ERCE_ENDPOINT_OFF_GRID )
1468 {
1469 if( !offGridEndpoints )
1470 {
1471 offGridEndpoints =
1472 m_connectivity->Engine().OffGridEndpoints( Settings().m_ConnectionGridSize );
1473 }
1474
1475 for( const SCH_CONNECTIVITY::OFF_GRID_ENDPOINT& endpoint : *offGridEndpoints )
1476 {
1477 if( endpoint.sheet != sheet.PathRef()
1478 || endpoint.item != error->GetMainItemID()
1479 || endpoint.position != marker->GetPosition() )
1480 {
1481 continue;
1482 }
1483
1484 for( const auto& [pin, position] : endpoint.equivalentPins )
1485 {
1486 std::shared_ptr<ERC_ITEM> alternate = ERC_ITEM::Create( ERCE_ENDPOINT_OFF_GRID );
1487 alternate->SetItems( std::vector<KIID>{ pin } );
1488 alternate->SetSheetSpecificPath( sheet );
1489 alternate->SetItemsSheetPaths( sheet );
1490 SCH_MARKER witness( std::move( alternate ), position );
1491 const ERC_EXCLUSION candidate = ERC_EXCLUSION::FromMarker( witness );
1492 it = settings.m_ErcExclusions.find( candidate );
1493
1494 if( it == settings.m_ErcExclusions.end() )
1495 it = findPathless( candidate );
1496
1497 if( it != settings.m_ErcExclusions.end() )
1498 break;
1499 }
1500
1501 break;
1502 }
1503 }
1504
1505 break;
1506
1508 // Older duplicate-sheet exclusions covered this pair in every parent instance
1509 if( !marker->IsExcluded() && mainHere && auxHere )
1510 it = findPathless( lookup );
1511
1512 break;
1513
1515 // Older exclusions identified the unit pair without either sheet instance
1516 if( hasMain && auxHere )
1517 it = findPathless( lookup );
1518
1519 break;
1520
1521 default:
1522 break;
1523 }
1524 }
1525
1526 if( it != settings.m_ErcExclusions.end() )
1527 {
1528 marker->SetExcluded( true, it->GetComment() );
1529
1530 if( !legacyPathlessExclusions.contains( *it ) )
1531 settings.m_ErcExclusions.erase( it );
1532 }
1533 else if( !marker->IsExcluded() )
1534 {
1535 if( const std::optional<GROUP_KEY> key = groupKey( *marker ) )
1536 groupMarkers.emplace( *key, marker );
1537 }
1538 }
1539 }
1540
1541 for( const ERC_EXCLUSION& exclusion : legacyPathlessExclusions )
1542 settings.m_ErcExclusions.erase( exclusion );
1543
1544 std::vector<SCH_MARKER*> newMarkers;
1545
1546 for( const ERC_EXCLUSION& exclusion : settings.m_ErcExclusions )
1547 {
1548 SCH_MARKER* marker = SCH_MARKER::FromProto( exclusion.ToProto().marker(), sheetList );
1549
1550 if( marker )
1551 {
1552 // Canonical connectivity witnesses can change the marker anchor and reported IDs
1553 if( const std::optional<GROUP_KEY> key = groupKey( *marker ) )
1554 {
1555 const auto current = groupMarkers.find( *key );
1556 const auto itemCount =
1557 []( const SCH_MARKER& aMarker )
1558 {
1559 return std::ranges::count_if( aMarker.GetRCItem()->GetIDs(),
1560 []( const KIID& id )
1561 {
1562 return id != niluuid;
1563 } );
1564 };
1565
1566 if( current != groupMarkers.end()
1567 && itemCount( *current->second ) == itemCount( *marker ) )
1568 {
1569 current->second->SetExcluded( true, exclusion.GetComment() );
1570 groupMarkers.erase( current );
1571 delete marker;
1572 continue;
1573 }
1574 }
1575
1576 marker->SetExcluded( true, exclusion.GetComment() );
1577 newMarkers.push_back( marker );
1578 }
1579 else
1580 {
1581 m_unresolvedErcExclusions.push_back( exclusion );
1582 }
1583 }
1584
1585 settings.m_ErcExclusions.clear();
1586
1587 return newMarkers;
1588}
1589
1590
1591std::shared_ptr<BUS_ALIAS> SCHEMATIC::GetBusAlias( const wxString& aLabel ) const
1592{
1593 for( auto it = m_busAliases.rbegin(); it != m_busAliases.rend(); ++it )
1594 {
1595 const auto& alias = *it;
1596
1597 if( alias && alias->GetName() == aLabel )
1598 return alias;
1599 }
1600
1601 return nullptr;
1602}
1603
1604
1605void SCHEMATIC::AddBusAlias( std::shared_ptr<BUS_ALIAS> aAlias )
1606{
1607 if( !aAlias )
1608 return;
1609
1610 auto sameDefinition =
1611 [&]( const std::shared_ptr<BUS_ALIAS>& candidate ) -> bool
1612 {
1613 return candidate
1614 && candidate->GetName() == aAlias->GetName()
1615 && candidate->Members() == aAlias->Members();
1616 };
1617
1618 auto it = std::find_if( m_busAliases.begin(), m_busAliases.end(), sameDefinition );
1619
1620 if( it != m_busAliases.end() )
1621 std::rotate( it, std::next( it ), m_busAliases.end() );
1622 else
1623 m_busAliases.push_back( aAlias->Clone() );
1624
1626}
1627
1628
1629void SCHEMATIC::SetBusAliases( const std::vector<std::shared_ptr<BUS_ALIAS>>& aAliases )
1630{
1631 std::vector<std::shared_ptr<BUS_ALIAS>> aliases;
1632
1633 for( const std::shared_ptr<BUS_ALIAS>& alias : aAliases )
1634 {
1635 if( !alias )
1636 continue;
1637
1638 std::shared_ptr<BUS_ALIAS> clone = alias->Clone();
1639
1640 auto sameDefinition =
1641 [&]( const std::shared_ptr<BUS_ALIAS>& candidate ) -> bool
1642 {
1643 return candidate
1644 && candidate->GetName() == clone->GetName()
1645 && candidate->Members() == clone->Members();
1646 };
1647
1648 auto it = std::find_if( aliases.begin(), aliases.end(), sameDefinition );
1649
1650 if( it != aliases.end() )
1651 std::rotate( it, std::next( it ), aliases.end() );
1652 else
1653 aliases.push_back( clone );
1654 }
1655
1656 m_busAliases.swap( aliases );
1658
1659 if( m_project )
1660 {
1661 m_project->GetProjectFile().m_BusAliasesDefined = true;
1662 m_busAliasesFromTable = true;
1663 }
1664}
1665
1666
1668{
1669 return m_project && m_project->GetProjectFile().m_BusAliasesDefined;
1670}
1671
1672
1674{
1675 m_busAliases.clear();
1677
1678 if( !m_project )
1679 return;
1680
1681 const std::map<wxString, std::vector<wxString>>& projectAliases = m_project->GetProjectFile().m_BusAliases;
1682
1683 for( const auto& [name, members] : projectAliases )
1684 {
1685 std::shared_ptr<BUS_ALIAS> busAlias = std::make_shared<BUS_ALIAS>();
1686
1687 busAlias->SetName( name );
1688 busAlias->SetMembers( members );
1689
1690 m_busAliases.push_back( busAlias );
1691 }
1692}
1693
1694
1696{
1697 if( !m_project )
1699
1700 if( !HasProjectBusAliases() )
1701 {
1702 // The reread cleared the project copy, and a save without it would drop the aliases in use
1704
1707
1708 // Kept as a table, so an empty one still suppresses the sheets' legacy aliases on reopen
1709 m_project->GetProjectFile().m_BusAliasesDefined = true;
1711 }
1712
1713 std::map<wxString, std::vector<wxString>> inUse;
1714
1715 for( const std::shared_ptr<BUS_ALIAS>& alias : m_busAliases )
1716 {
1717 if( alias )
1718 inUse.insert_or_assign( alias->GetName(), alias->Members() );
1719 }
1720
1722
1723 return inUse != m_project->GetProjectFile().m_BusAliases ? BUS_ALIAS_RELOAD::CHANGED
1725}
1726
1727
1729{
1730 if( !m_project )
1731 return;
1732
1733 std::map<wxString, std::vector<wxString>>& projectAliases = m_project->GetProjectFile().m_BusAliases;
1734
1735 projectAliases.clear();
1736
1737 for( const std::shared_ptr<BUS_ALIAS>& alias : m_busAliases )
1738 {
1739 if( !alias )
1740 continue;
1741
1742 projectAliases.insert_or_assign( alias->GetName(), alias->Members() );
1743 }
1744}
1745
1746
1748{
1749 std::set<wxString> names;
1750
1751 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine )
1752 {
1753 for( const SCH_CONNECTIVITY::NET_GROUP& group : Connectivity().GetNetMap() )
1754 {
1755 // A net without items, such as a member of an unplaced bus, has nothing to assign a netclass to
1756 if( std::ranges::all_of( group.instances,
1757 []( const SCH_CONNECTIVITY::NET_VIEW& net )
1758 {
1759 return net.Items().empty();
1760 } ) )
1761 {
1762 continue;
1763 }
1764
1765 const auto& net = group.instances.front();
1766
1769 {
1770 names.insert( group.name );
1771 }
1772 }
1773
1774 return names;
1775 }
1776
1777 for( const auto& [key, subgraphList] : m_connectionGraph->GetNetMap() )
1778 {
1779 CONNECTION_SUBGRAPH* firstSubgraph = subgraphList[0];
1780
1781 if( !firstSubgraph->GetDriverConnection()->IsBus()
1783 {
1784 names.insert( key.Name );
1785 }
1786 }
1787
1788 return names;
1789}
1790
1791
1792bool SCHEMATIC::ResolveCrossReference( wxString* token, int aDepth ) const
1793{
1795
1796 if( !environment || !environment->IsCollectingSources() )
1797 return resolveCrossReference( token, aDepth );
1798
1799 const TEXT_EVAL::ENVIRONMENT::CROSS_REFERENCE_KEY key{ *token, aDepth };
1800 const bool resolved = resolveCrossReference( token, aDepth );
1801 environment->RecordCrossReference( key, { *token, resolved } );
1802 return resolved;
1803}
1804
1805
1806bool SCHEMATIC::resolveCrossReference( wxString* token, int aDepth ) const
1807{
1808 wxString remainder;
1809 wxString ref = token->BeforeFirst( ':', &remainder );
1810 KIID_PATH path( ref );
1811 KIID uuid( 0 );
1812
1813 if( path.size() > 0 )
1814 uuid = path.back();
1815
1816 SCH_SHEET_PATH sheetPath;
1817 SCH_ITEM* refItem = ResolveItem( KIID( uuid ), &sheetPath, true );
1818
1819 if( path.size() > 1 )
1820 {
1821 path.pop_back();
1822 sheetPath = Hierarchy().GetSheetPathByKIIDPath( path ).value_or( sheetPath );
1823 }
1824
1825 // Parse optional variant name from syntax ${REF:FIELD:VARIANT}
1826 // remainder is "FIELD" or "FIELD:VARIANT"
1827 wxString variantName;
1828 wxString fieldName = remainder;
1829 int colonPos = remainder.Find( ':' );
1830
1831 if( colonPos != wxNOT_FOUND )
1832 {
1833 fieldName = remainder.Left( colonPos );
1834 variantName = remainder.Mid( colonPos + 1 );
1835 }
1836
1837 // Note: We don't expand nested variables or evaluate math expressions here.
1838 // The multi-pass loop in GetShownText handles all variable and expression resolution
1839 // before cross-references are resolved. This ensures table cell variables like ${ROW}
1840 // are expanded correctly.
1841
1842 if( refItem && refItem->Type() == SCH_SYMBOL_T )
1843 {
1844 SCH_SYMBOL* refSymbol = static_cast<SCH_SYMBOL*>( refItem );
1845
1846 if( refSymbol->ResolveTextVar( &sheetPath, &fieldName, variantName, aDepth + 1 ) )
1847 {
1848 *token = std::move( fieldName );
1849 }
1850 else
1851 {
1852 // Field/function not found on symbol
1853 *token = wxString::Format( wxT( "<Unresolved: %s:%s>" ),
1854 refSymbol->GetRef( &sheetPath, false ),
1855 fieldName );
1856 }
1857
1858 return true; // Stop looking
1859 }
1860 else if( refItem && refItem->Type() == SCH_SHEET_T )
1861 {
1862 SCH_SHEET* refSheet = static_cast<SCH_SHEET*>( refItem );
1863
1864 sheetPath.push_back( refSheet );
1865
1866 if( refSheet->ResolveTextVar( &sheetPath, &remainder, aDepth + 1 ) )
1867 {
1868 *token = std::move( remainder );
1869 }
1870 else
1871 {
1872 // Field/function not found on sheet
1873 *token = wxString::Format( wxT( "<Unresolved: %s:%s>" ),
1874 refSheet->GetName(),
1875 remainder );
1876 }
1877
1878 return true; // Stop looking
1879 }
1880
1881 // If UUID resolution failed, try to resolve by reference designator
1882 // This handles both exact matches (J601A) and parent references for multi-unit symbols (J601)
1883 if( !refItem )
1884 {
1885 SCH_SYMBOL* foundSymbol = nullptr;
1886 SCH_SHEET_PATH foundPath;
1887
1888 // Walk symbols directly since an SCH_REFERENCE_LIST resolves fields that may refer back here
1889 auto findSymbol =
1890 [&]()
1891 {
1892 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
1893 {
1894 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
1895 {
1896 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
1897 const wxString baseRef = symbol->GetRef( &sheet, false );
1898
1899 if( !symbol->GetLibSymbolRef() || baseRef.StartsWith( wxT( "#" ) ) )
1900 continue;
1901
1902 // A unit reference (J601A) names one unit exactly
1903 if( symbol->GetRef( &sheet, true ) == ref )
1904 {
1905 foundSymbol = symbol;
1906 foundPath = sheet;
1907 return;
1908 }
1909
1910 // The parent reference (J601) names any unit, so keep looking for an
1911 // exact match
1912 if( !foundSymbol && baseRef == ref )
1913 {
1914 foundSymbol = symbol;
1915 foundPath = sheet;
1916 }
1917 }
1918 }
1919 };
1920
1921 findSymbol();
1922
1923 if( foundSymbol )
1924 {
1925 if( foundSymbol->ResolveTextVar( &foundPath, &fieldName, variantName, aDepth + 1 ) )
1926 {
1927 *token = std::move( fieldName );
1928 }
1929 else
1930 {
1931 // Field/function not found on symbol
1932 *token = wxString::Format( wxT( "<Unresolved: %s:%s>" ),
1933 foundSymbol->GetRef( &foundPath, false ),
1934 fieldName );
1935 }
1936
1937 return true; // Stop looking
1938 }
1939
1940 // Symbol not found - set unresolved error
1941 *token = wxString::Format( wxT( "<Unresolved: %s>" ), ref );
1942 return true;
1943 }
1944
1945 // Reference not found - show error message
1946 *token = wxString::Format( wxT( "<Unknown reference: %s>" ), ref );
1947 return true;
1948}
1949
1950
1951std::map<int, wxString> SCHEMATIC::GetVirtualPageToSheetNamesMap() const
1952{
1953 std::map<int, wxString> namesMap;
1954
1955 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
1956 {
1957 if( sheet.size() == 1 )
1958 namesMap[sheet.GetVirtualPageNumber()] = _( "<root sheet>" );
1959 else
1960 namesMap[sheet.GetVirtualPageNumber()] = sheet.Last()->GetName();
1961 }
1962
1963 return namesMap;
1964}
1965
1966
1967std::map<int, wxString> SCHEMATIC::GetVirtualPageToSheetPagesMap() const
1968{
1969 std::map<int, wxString> pagesMap;
1970
1971 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
1972 pagesMap[sheet.GetVirtualPageNumber()] = sheet.GetPageNumber();
1973
1974 return pagesMap;
1975}
1976
1977
1978wxString SCHEMATIC::ConvertRefsToKIIDs( const wxString& aSource ) const
1979{
1980 wxString newbuf;
1981 size_t sourceLen = aSource.length();
1982
1983 for( size_t i = 0; i < sourceLen; ++i )
1984 {
1985 // Check for escaped expressions: \${ or \@{
1986 // These should be copied verbatim without any ref→KIID conversion
1987 if( aSource[i] == '\\' && i + 2 < sourceLen && aSource[i + 2] == '{' &&
1988 ( aSource[i + 1] == '$' || aSource[i + 1] == '@' ) )
1989 {
1990 // Copy the escape sequence and the entire escaped expression
1991 newbuf.append( aSource[i] ); // backslash
1992 newbuf.append( aSource[i + 1] ); // $ or @
1993 newbuf.append( aSource[i + 2] ); // {
1994 i += 2;
1995
1996 // Find and copy everything until the matching closing brace
1997 int braceDepth = 1;
1998 for( i = i + 1; i < sourceLen && braceDepth > 0; ++i )
1999 {
2000 if( aSource[i] == '{' )
2001 braceDepth++;
2002 else if( aSource[i] == '}' )
2003 braceDepth--;
2004
2005 newbuf.append( aSource[i] );
2006 }
2007 i--; // Back up one since the for loop will increment
2008 continue;
2009 }
2010
2011 if( aSource[i] == '$' && i + 1 < sourceLen && aSource[i + 1] == '{' )
2012 {
2013 wxString token;
2014 bool isCrossRef = false;
2015 int nesting = 0;
2016
2017 for( i = i + 2; i < sourceLen; ++i )
2018 {
2019 if( aSource[i] == '{' && ( aSource[i - 1] == '_' || aSource[i - 1] == '^' || aSource[i - 1] == '~' ) )
2020 {
2021 nesting++;
2022 }
2023
2024 if( aSource[i] == '}' )
2025 {
2026 nesting--;
2027
2028 if( nesting < 0 )
2029 break;
2030 }
2031
2032 if( aSource[i] == ':' )
2033 isCrossRef = true;
2034
2035 token.append( aSource[i] );
2036 }
2037
2038 if( isCrossRef )
2039 {
2040 wxString remainder;
2041 wxString ref = token.BeforeFirst( ':', &remainder );
2042 SCH_REFERENCE_LIST references;
2043
2045
2046 for( size_t jj = 0; jj < references.GetCount(); jj++ )
2047 {
2048 SCH_SYMBOL* refSymbol = references[jj].GetSymbol();
2049
2050 if( ref == refSymbol->GetRef( &references[jj].GetSheetPath(), true ) )
2051 {
2052 KIID_PATH path = references[jj].GetSheetPath().Path();
2053 path.push_back( refSymbol->m_Uuid );
2054
2055 token = path.AsString() + wxS( ":" ) + remainder;
2056 break;
2057 }
2058 }
2059 }
2060
2061 newbuf.append( wxS( "${" ) + token + wxS( "}" ) );
2062 }
2063 else
2064 {
2065 newbuf.append( aSource[i] );
2066 }
2067 }
2068
2069 return newbuf;
2070}
2071
2072
2073wxString SCHEMATIC::ConvertKIIDsToRefs( const wxString& aSource ) const
2074{
2075 wxString newbuf;
2076 size_t sourceLen = aSource.length();
2077
2078 for( size_t i = 0; i < sourceLen; ++i )
2079 {
2080 // Check for escaped expressions: \${ or \@{
2081 // These should be copied verbatim without any KIID→ref conversion
2082 if( aSource[i] == '\\' && i + 2 < sourceLen && aSource[i + 2] == '{' &&
2083 ( aSource[i + 1] == '$' || aSource[i + 1] == '@' ) )
2084 {
2085 // Copy the escape sequence and the entire escaped expression
2086 newbuf.append( aSource[i] ); // backslash
2087 newbuf.append( aSource[i + 1] ); // $ or @
2088 newbuf.append( aSource[i + 2] ); // {
2089 i += 2;
2090
2091 // Find and copy everything until the matching closing brace
2092 int braceDepth = 1;
2093 for( i = i + 1; i < sourceLen && braceDepth > 0; ++i )
2094 {
2095 if( aSource[i] == '{' )
2096 braceDepth++;
2097 else if( aSource[i] == '}' )
2098 braceDepth--;
2099
2100 newbuf.append( aSource[i] );
2101 }
2102 i--; // Back up one since the for loop will increment
2103 continue;
2104 }
2105
2106 if( aSource[i] == '$' && i + 1 < sourceLen && aSource[i + 1] == '{' )
2107 {
2108 wxString token;
2109 bool isCrossRef = false;
2110
2111 for( i = i + 2; i < sourceLen; ++i )
2112 {
2113 if( aSource[i] == '}' )
2114 break;
2115
2116 if( aSource[i] == ':' )
2117 isCrossRef = true;
2118
2119 token.append( aSource[i] );
2120 }
2121
2122 if( isCrossRef )
2123 {
2124 wxString remainder;
2125 wxString ref = token.BeforeFirst( ':', &remainder );
2126 KIID_PATH path( ref );
2127 KIID uuid = path.back();
2128 SCH_SHEET_PATH sheetPath;
2129 SCH_ITEM* refItem = ResolveItem( uuid, &sheetPath, true );
2130
2131 if( path.size() > 1 )
2132 {
2133 path.pop_back();
2134 sheetPath = Hierarchy().GetSheetPathByKIIDPath( path ).value_or( sheetPath );
2135 }
2136
2137 if( refItem && refItem->Type() == SCH_SYMBOL_T )
2138 {
2139 SCH_SYMBOL* refSymbol = static_cast<SCH_SYMBOL*>( refItem );
2140 token = refSymbol->GetRef( &sheetPath, true ) + wxS( ":" ) + remainder;
2141 }
2142 }
2143
2144 newbuf.append( wxS( "${" ) + token + wxS( "}" ) );
2145 }
2146 else
2147 {
2148 newbuf.append( aSource[i] );
2149 }
2150 }
2151
2152 return newbuf;
2153}
2154
2155
2162
2163
2165{
2166 // Filename is rootSheetName-sheetName-...-sheetName
2167 // Note that we need to fetch the rootSheetName out of its filename, as the root SCH_SHEET's
2168 // name is just a timestamp.
2169
2170 // Skip virtual root if present
2171 size_t startIdx = 0;
2172 if( CurrentSheet().size() > 0 && CurrentSheet().at( 0 )->IsVirtualRootSheet() )
2173 startIdx = 1;
2174
2175 // Handle the case where we only have a virtual root (shouldn't happen in practice)
2176 if( startIdx >= CurrentSheet().size() )
2177 return wxEmptyString;
2178
2179 SCH_SHEET* topSheet = CurrentSheet().at( startIdx );
2180
2181 // A top-level sheet keeps its file on the screen, because the SHEET_FILENAME field is only
2182 // set on the sheet instances that a parent sheet owns
2183 wxString topFileName;
2184
2185 if( topSheet->GetScreen() )
2186 topFileName = topSheet->GetScreen()->GetFileName();
2187
2188 if( topFileName.IsEmpty() )
2189 topFileName = topSheet->GetFileName();
2190
2191 wxFileName rootFn( topFileName );
2192 wxString filename = rootFn.GetName();
2193
2194 for( unsigned i = startIdx + 1; i < CurrentSheet().size(); i++ )
2195 filename += wxT( "-" ) + CurrentSheet().at( i )->GetName();
2196
2197 return filename;
2198}
2199
2200
2202{
2203 SCH_SCREEN* screen;
2204 SCH_SCREENS s_list( Root() );
2205
2206 // Set the sheet count, and the sheet number (1 for root sheet)
2207 int sheet_count;
2208
2209 // Handle virtual root case
2210 if( Root().m_Uuid == niluuid )
2211 {
2212 // Virtual root: count all top-level sheets
2213 sheet_count = 0;
2214
2215 for( const SCH_SHEET* topSheet : m_topLevelSheets )
2216 {
2217 if( topSheet )
2218 sheet_count += topSheet->CountSheets();
2219 }
2220 }
2221 else
2222 {
2223 // Traditional single root
2224 sheet_count = Root().CountSheets();
2225 }
2226
2227 int sheet_number = 1;
2228
2229 if( m_hierarchy.empty() )
2230 {
2231 for( screen = s_list.GetFirst(); screen != nullptr; screen = s_list.GetNext() )
2232 screen->SetPageCount( sheet_count );
2233
2234 CurrentSheet().SetVirtualPageNumber( sheet_number );
2235 screen = CurrentSheet().LastScreen();
2236
2237 if( screen )
2238 screen->SetVirtualPageNumber( sheet_number );
2239
2240 return;
2241 }
2242
2243 const KIID_PATH& current_sheetpath = CurrentSheet().Path();
2244
2245 // @todo Remove all pseudo page number system is left over from prior to real page number
2246 // implementation.
2247 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
2248 {
2249 if( sheet.Path() == current_sheetpath ) // Current sheet path found
2250 break;
2251
2252 sheet_number++; // Not found, increment before this current path
2253 }
2254
2255 for( screen = s_list.GetFirst(); screen != nullptr; screen = s_list.GetNext() )
2256 screen->SetPageCount( sheet_count );
2257
2258 CurrentSheet().SetVirtualPageNumber( sheet_number );
2259 CurrentSheet().LastScreen()->SetVirtualPageNumber( sheet_number );
2260 CurrentSheet().LastScreen()->SetPageNumber( CurrentSheet().GetPageNumber() );
2261}
2262
2263
2265{
2266 std::map<wxString, std::set<int>>& pageRefsMap = GetPageRefsMap();
2267
2268 pageRefsMap.clear();
2269
2270 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
2271 {
2272 for( SCH_ITEM* item : sheet.LastScreen()->Items().OfType( SCH_GLOBAL_LABEL_T ) )
2273 {
2274 SCH_GLOBALLABEL* global = static_cast<SCH_GLOBALLABEL*>( item );
2275 wxString resolvedLabel = global->GetShownText( &sheet, FOR_GUI );
2276
2277 pageRefsMap[resolvedLabel].insert( sheet.GetVirtualPageNumber() );
2278 }
2279 }
2280
2281 bool show = Settings().m_IntersheetRefsShow;
2282
2283 // Refresh all visible global labels. Note that we have to collect them first as the
2284 // SCH_SCREEN::Update() call is going to invalidate the RTree iterator.
2285
2286 std::vector<SCH_GLOBALLABEL*> currentSheetGlobalLabels;
2287
2288 for( EDA_ITEM* item : CurrentSheet().LastScreen()->Items().OfType( SCH_GLOBAL_LABEL_T ) )
2289 currentSheetGlobalLabels.push_back( static_cast<SCH_GLOBALLABEL*>( item ) );
2290
2291 for( SCH_GLOBALLABEL* globalLabel : currentSheetGlobalLabels )
2292 {
2293 std::vector<SCH_FIELD>& fields = globalLabel->GetFields();
2294
2295 fields[0].SetVisible( show );
2296
2297 if( show )
2298 {
2299 if( fields.size() == 1 && fields[0].GetTextPos() == globalLabel->GetPosition() )
2300 globalLabel->AutoplaceFields( CurrentSheet().LastScreen(), AUTOPLACE_AUTO );
2301
2302 CurrentSheet().LastScreen()->Update( globalLabel );
2303
2304 for( SCH_FIELD& field : globalLabel->GetFields() )
2305 field.ClearBoundingBoxCache();
2306
2307 globalLabel->ClearBoundingBoxCache();
2308
2309 if( m_schematicHolder )
2310 m_schematicHolder->IntersheetRefUpdate( globalLabel );
2311 }
2312 }
2313}
2314
2315
2316void SCHEMATIC::SyncLibSymbolPinMaps( const wxString& aSchLibSymbolName, const LIB_SYMBOL& aSource,
2317 SCH_COMMIT* aCommit )
2318{
2319 SCH_SCREENS screens( Root() );
2320
2321 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2322 {
2323 auto it = screen->GetLibSymbols().find( aSchLibSymbolName );
2324
2325 if( it != screen->GetLibSymbols().end() && it->second && it->second != &aSource )
2326 {
2327 it->second->SetPinMaps( aSource.GetPinMaps() );
2328 it->second->SetAssociatedFootprints( aSource.GetAssociatedFootprints() );
2329 }
2330
2331 for( SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
2332 {
2333 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
2334
2335 if( symbol->GetSchSymbolLibraryName() != aSchLibSymbolName )
2336 continue;
2337
2338 LIB_SYMBOL* copy = symbol->GetLibSymbolRef().get();
2339
2340 if( !copy || copy == &aSource )
2341 continue;
2342
2343 if( copy->GetPinMaps() == aSource.GetPinMaps()
2344 && copy->GetAssociatedFootprints() == aSource.GetAssociatedFootprints() )
2345 {
2346 continue;
2347 }
2348
2349 if( aCommit )
2350 aCommit->Modify( symbol, screen );
2351
2352 copy->SetPinMaps( aSource.GetPinMaps() );
2353 copy->SetAssociatedFootprints( aSource.GetAssociatedFootprints() );
2354 }
2355 }
2356}
2357
2358
2359wxString SCHEMATIC::GetOperatingPoint( const wxString& aNetName, int aPrecision, const wxString& aRange )
2360{
2361 wxString spiceNetName( aNetName );
2363 spiceNetName.MakeLower();
2364
2365 if( spiceNetName == wxS( "gnd" ) || spiceNetName == wxS( "0" ) )
2366 return wxEmptyString;
2367
2368 auto it = m_operatingPoints.find( spiceNetName );
2369
2370 if( it != m_operatingPoints.end() )
2371 return SPICE_VALUE( it->second ).ToString( { aPrecision, aRange } );
2372 else if( m_operatingPoints.empty() )
2373 return wxS( "--" );
2374 else
2375 return wxS( "?" );
2376}
2377
2378
2379int SCHEMATIC::FixupJunctionsAfterImport( const std::function<void( SCH_LINE*, SCH_LINE* )>& aOnSplit )
2380{
2381 SCH_SCREENS screens( Root() );
2382 int count = 0;
2383
2384 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2385 {
2386 std::deque<EDA_ITEM*> allItems;
2387
2388 for( SCH_ITEM* item : screen->Items() )
2389 allItems.push_back( item );
2390
2391 // Add missing junctions and breakup wires as needed
2392 for( const VECTOR2I& point : screen->GetNeededJunctions( allItems ) )
2393 {
2394 count++;
2395
2396 SCH_JUNCTION* junction = new SCH_JUNCTION( point );
2397 screen->Append( junction );
2398
2399 // Breakup wires
2400 for( SCH_LINE* wire : screen->GetBusesAndWires( point, true ) )
2401 {
2402 SCH_LINE* newSegment = wire->NonGroupAware_BreakAt( point );
2403 screen->Append( newSegment );
2404
2405 if( aOnSplit )
2406 aOnSplit( wire, newSegment );
2407 }
2408 }
2409 }
2410
2411 return count;
2412}
2413
2414
2415void SCHEMATIC::OnItemsAdded( std::vector<SCH_ITEM*>& aNewItems )
2416{
2418}
2419
2420
2421void SCHEMATIC::OnItemsRemoved( std::vector<SCH_ITEM*>& aRemovedItems )
2422{
2424}
2425
2426
2427void SCHEMATIC::OnItemsChanged( std::vector<SCH_ITEM*>& aItems )
2428{
2430}
2431
2432
2437
2438
2443
2444
2446{
2447 if( !alg::contains( m_listeners, aListener ) )
2448 m_listeners.push_back( aListener );
2449}
2450
2451
2453{
2454 auto it = std::find( m_listeners.begin(), m_listeners.end(), aListener );
2455
2456 if( it != m_listeners.end() )
2457 {
2458 std::iter_swap( it, m_listeners.end() - 1 );
2459 m_listeners.pop_back();
2460 }
2461}
2462
2463
2465{
2466 m_listeners.clear();
2467}
2468
2469
2471{
2472 std::erase_if( m_unresolvedErcExclusions,
2473 [&]( const ERC_EXCLUSION& exclusion )
2474 {
2475 if( aErrorCode >= 0 )
2476 {
2477 kiapi::schematic::ErcErrorType error = exclusion.ToProto().marker().error_type();
2478
2480 return false;
2481 }
2482
2483 ErcSettings().m_ErcExclusions.erase( exclusion );
2484 return true;
2485 } );
2486}
2487
2488
2490{
2491 // Use a sorted sheetList to reduce file churn
2492 SCH_SHEET_LIST sheetList = Hierarchy();
2493 ERC_SETTINGS& ercSettings = ErcSettings();
2494
2495 ercSettings.m_ErcExclusions.clear();
2496 ercSettings.m_ErcExclusions.insert( m_unresolvedErcExclusions.begin(), m_unresolvedErcExclusions.end() );
2497
2498 for( unsigned i = 0; i < sheetList.size(); i++ )
2499 {
2500 for( SCH_ITEM* item : sheetList[i].LastScreen()->Items().OfType( SCH_MARKER_T ) )
2501 {
2502 SCH_MARKER* marker = static_cast<SCH_MARKER*>( item );
2503
2504 if( marker->IsExcluded() )
2505 {
2506 ercSettings.m_ErcExclusions.insert( ERC_EXCLUSION::FromMarker( *marker ) );
2507 }
2508 }
2509 }
2510}
2511
2512
2514{
2515 SCH_SHEET_LIST sheetList = Hierarchy();
2516
2517 for( SCH_MARKER* marker : ResolveERCExclusions() )
2518 {
2519 SCH_SHEET_PATH errorPath;
2520 ignore_unused( sheetList.ResolveItem( marker->GetRCItem()->GetMainItemID(), &errorPath ) );
2521
2522 if( errorPath.LastScreen() )
2523 errorPath.LastScreen()->Append( marker );
2524 else
2525 RootScreen()->Append( marker );
2526 }
2527
2528 // Once we have the ERC Exclusions, record them in the project file so that
2529 // they are retained even before the schematic is saved (PCB Editor can also save the project)
2531}
2532
2533
2534std::vector<SCH_MARKER*> SCHEMATIC::ReloadERCExclusions()
2535{
2536 // The reread file carries every exclusion the old unresolved list held
2538
2539 std::vector<std::pair<SCH_MARKER*, SCH_SCREEN*>> wereExcluded;
2540 SCH_SCREENS screens( Root() );
2541
2542 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2543 {
2544 for( SCH_ITEM* item : screen->Items().OfType( SCH_MARKER_T ) )
2545 {
2546 SCH_MARKER* marker = static_cast<SCH_MARKER*>( item );
2547
2548 if( marker->IsExcluded() )
2549 {
2550 wereExcluded.emplace_back( marker, screen );
2551 marker->SetExcluded( false );
2552 }
2553 }
2554 }
2555
2557
2558 std::vector<SCH_MARKER*> stale;
2559
2560 for( auto& [marker, screen] : wereExcluded )
2561 {
2562 if( !marker->IsExcluded() )
2563 {
2564 screen->Remove( marker );
2565 stale.push_back( marker );
2566 }
2567 }
2568
2569 return stale;
2570}
2571
2572
2574{
2575 return static_cast<EMBEDDED_FILES*>( this );
2576}
2577
2578
2580{
2581 return static_cast<const EMBEDDED_FILES*>( this );
2582}
2583
2584
2585void SCHEMATIC::RunOnNestedEmbeddedFiles( const std::function<void( EMBEDDED_FILES* )>& aFunction )
2586{
2587 SCH_SCREENS screens( Root() );
2588
2589 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2590 {
2591 for( auto& [name, libSym] : screen->GetLibSymbols() )
2592 aFunction( libSym->GetEmbeddedFiles() );
2593 }
2594}
2595
2596
2597std::set<KIFONT::OUTLINE_FONT*> SCHEMATIC::GetFonts() const
2598{
2599 std::set<KIFONT::OUTLINE_FONT*> fonts;
2600
2601 SCH_SHEET_LIST sheetList = Hierarchy();
2602
2603 for( const SCH_SHEET_PATH& sheet : sheetList )
2604 {
2605 for( SCH_ITEM* item : sheet.LastScreen()->Items() )
2606 {
2607 if( EDA_TEXT* text = dynamic_cast<EDA_TEXT*>( item ) )
2608 {
2609 KIFONT::FONT* font = text->GetFont();
2610
2611 if( !font || font->IsStroke() )
2612 continue;
2613
2614 using EMBEDDING_PERMISSION = KIFONT::OUTLINE_FONT::EMBEDDING_PERMISSION;
2615 KIFONT::OUTLINE_FONT* outline = static_cast<KIFONT::OUTLINE_FONT*>( font );
2616
2617 if( outline->GetEmbeddingPermission() == EMBEDDING_PERMISSION::EDITABLE
2618 || outline->GetEmbeddingPermission() == EMBEDDING_PERMISSION::INSTALLABLE )
2619 {
2620 fonts.insert( outline );
2621 }
2622 }
2623 }
2624 }
2625
2626 return fonts;
2627}
2628
2629
2631{
2632 std::set<KIFONT::OUTLINE_FONT*> fonts = GetFonts();
2633
2634 for( KIFONT::OUTLINE_FONT* font : fonts )
2635 {
2636 EMBEDDED_FILES::EMBEDDED_FILE* file = GetEmbeddedFiles()->AddFile( font->GetFileName(), false );
2637
2638 if( !file )
2639 {
2640 wxLogTrace( "EMBED", "Failed to add font file: %s", font->GetFileName() );
2641 continue;
2642 }
2643
2645 }
2646}
2647
2648
2649std::set<const SCH_SCREEN*> SCHEMATIC::GetSchematicsSharedByMultipleProjects() const
2650{
2651 std::set<const SCH_SCREEN*> retv;
2652
2653 wxCHECK( m_rootSheet, retv );
2654
2655 SCH_SHEET_LIST hierarchy( m_rootSheet );
2656 SCH_SCREENS screens( m_rootSheet );
2657
2658 for( const SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2659 {
2660 for( const SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
2661 {
2662 const SCH_SYMBOL* symbol = static_cast<const SCH_SYMBOL*>( item );
2663
2664 const std::vector<SCH_SYMBOL_INSTANCE> symbolInstances = symbol->GetInstances();
2665
2666 for( const SCH_SYMBOL_INSTANCE& instance : symbolInstances )
2667 {
2668 if( !hierarchy.HasPath( instance.m_Path ) )
2669 {
2670 retv.insert( screen );
2671 break;
2672 }
2673 }
2674
2675 if( retv.count( screen ) )
2676 break;
2677 }
2678 }
2679
2680 return retv;
2681}
2682
2683
2685{
2686 wxCHECK( m_rootSheet, false );
2687
2688 SCH_SCREENS screens( m_rootSheet );
2689
2690 for( const SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
2691 {
2692 wxCHECK2( screen, continue );
2693
2694 if( screen->GetRefCount() > 1 )
2695 return true;
2696 }
2697
2698 return false;
2699}
2700
2701
2702void SCHEMATIC::CleanUp( SCH_COMMIT* aCommit, SCH_SCREEN* aScreen )
2703{
2704 SCH_SELECTION_TOOL* selectionTool = m_schematicHolder ? m_schematicHolder->GetSelectionTool() : nullptr;
2705 std::vector<SCH_LINE*> lines;
2706 std::vector<SCH_JUNCTION*> junctions;
2707 std::vector<SCH_NO_CONNECT*> ncs;
2708 std::vector<SCH_ITEM*> items_to_remove;
2709 std::unordered_set<SCH_LINE*> generatedLines;
2710 std::vector<std::unique_ptr<SCH_LINE>> retiredLines;
2711 bool changed = true;
2712
2713 if( aScreen == nullptr )
2714 aScreen = GetCurrentScreen();
2715
2716 auto remove_item =
2717 [&]( SCH_ITEM* aItem ) -> void
2718 {
2719 changed = true;
2720
2721 if( !( aItem->GetFlags() & STRUCT_DELETED ) )
2722 {
2723 aItem->SetFlags( STRUCT_DELETED );
2724
2725 if( aItem->IsSelected() && selectionTool )
2726 selectionTool->RemoveItemFromSel( aItem, true /*quiet mode*/ );
2727
2728 if( m_schematicHolder )
2729 m_schematicHolder->RemoveFromScreen( aItem, aScreen );
2730 else
2731 aScreen->Remove( aItem );
2732
2733 aCommit->RemovedForCleanup( aItem, aScreen );
2734
2735 if( aItem->Type() == SCH_LINE_T && generatedLines.erase( static_cast<SCH_LINE*>( aItem ) )
2736 && !aCommit->GetStatus( aItem, aScreen ) )
2737 {
2738 // An intermediate merge has no undo owner when its Add/Remove entries cancel.
2739 retiredLines.emplace_back( static_cast<SCH_LINE*>( aItem ) );
2740 }
2741 }
2742 };
2743
2744 for( SCH_ITEM* item : aScreen->Items().OfType( SCH_JUNCTION_T ) )
2745 {
2746 if( !aScreen->IsExplicitJunctionAllowed( item->GetPosition() ) )
2747 {
2748 if( item->IsSelected() || item->HasFlag( SELECTED_BY_DRAG ) )
2749 continue;
2750
2751 items_to_remove.push_back( item );
2752 }
2753 else
2754 junctions.push_back( static_cast<SCH_JUNCTION*>( item ) );
2755 }
2756
2757 for( SCH_ITEM* item : items_to_remove )
2758 remove_item( item );
2759
2760 for( SCH_ITEM* item : aScreen->Items().OfType( SCH_NO_CONNECT_T ) )
2761 ncs.push_back( static_cast<SCH_NO_CONNECT*>( item ) );
2762
2763 alg::for_all_pairs( junctions.begin(), junctions.end(),
2764 [&]( SCH_JUNCTION* aFirst, SCH_JUNCTION* aSecond )
2765 {
2766 if( ( aFirst->GetEditFlags() & STRUCT_DELETED )
2767 || ( aSecond->GetEditFlags() & STRUCT_DELETED ) )
2768 {
2769 return;
2770 }
2771
2772 if( aFirst->GetPosition() == aSecond->GetPosition() )
2773 remove_item( aSecond );
2774 } );
2775
2776 alg::for_all_pairs( ncs.begin(), ncs.end(),
2777 [&]( SCH_NO_CONNECT* aFirst, SCH_NO_CONNECT* aSecond )
2778 {
2779 if( ( aFirst->GetEditFlags() & STRUCT_DELETED )
2780 || ( aSecond->GetEditFlags() & STRUCT_DELETED ) )
2781 {
2782 return;
2783 }
2784
2785 if( aFirst->GetPosition() == aSecond->GetPosition() )
2786 remove_item( aSecond );
2787 } );
2788
2789
2790 auto minX =
2791 []( const SCH_LINE* l )
2792 {
2793 return std::min( l->GetStartPoint().x, l->GetEndPoint().x );
2794 };
2795
2796 auto maxX =
2797 []( const SCH_LINE* l )
2798 {
2799 return std::max( l->GetStartPoint().x, l->GetEndPoint().x );
2800 };
2801
2802 auto minY =
2803 []( const SCH_LINE* l )
2804 {
2805 return std::min( l->GetStartPoint().y, l->GetEndPoint().y );
2806 };
2807
2808 auto maxY =
2809 []( const SCH_LINE* l )
2810 {
2811 return std::max( l->GetStartPoint().y, l->GetEndPoint().y );
2812 };
2813
2814 // Would be nice to put lines in a canonical form here by swapping
2815 // start <-> end as needed but I don't know what swapping breaks.
2816 while( changed )
2817 {
2818 changed = false;
2819 lines.clear();
2820
2821 for( SCH_ITEM* item : aScreen->Items().OfType( SCH_LINE_T ) )
2822 {
2823 if( item->GetLayer() == LAYER_WIRE || item->GetLayer() == LAYER_BUS )
2824 lines.push_back( static_cast<SCH_LINE*>( item ) );
2825 }
2826
2827 // Sort by minimum X position
2828 std::sort( lines.begin(), lines.end(),
2829 [&]( const SCH_LINE* a, const SCH_LINE* b )
2830 {
2831 return minX( a ) < minX( b );
2832 } );
2833
2834 for( auto it1 = lines.begin(); it1 != lines.end(); ++it1 )
2835 {
2836 SCH_LINE* firstLine = *it1;
2837
2838 if( firstLine->GetEditFlags() & STRUCT_DELETED )
2839 continue;
2840
2841 if( firstLine->IsNull() )
2842 {
2843 remove_item( firstLine );
2844 continue;
2845 }
2846
2847 int firstRightXEdge = maxX( firstLine );
2848 auto it2 = it1;
2849
2850 for( ++it2; it2 != lines.end(); ++it2 )
2851 {
2852 SCH_LINE* secondLine = *it2;
2853 int secondLeftXEdge = minX( secondLine );
2854
2855 // impossible to overlap remaining lines
2856 if( secondLeftXEdge > firstRightXEdge )
2857 break;
2858
2859 // No Y axis overlap
2860 if( !( std::max( minY( firstLine ), minY( secondLine ) )
2861 <= std::min( maxY( firstLine ), maxY( secondLine ) ) ) )
2862 {
2863 continue;
2864 }
2865
2866 if( secondLine->GetFlags() & STRUCT_DELETED )
2867 continue;
2868
2869 if( !secondLine->IsParallel( firstLine ) || !secondLine->IsStrokeEquivalent( firstLine )
2870 || secondLine->GetLayer() != firstLine->GetLayer() )
2871 {
2872 continue;
2873 }
2874
2875 // Remove identical lines
2876 if( firstLine->IsEndPoint( secondLine->GetStartPoint() )
2877 && firstLine->IsEndPoint( secondLine->GetEndPoint() ) )
2878 {
2879 remove_item( secondLine );
2880 continue;
2881 }
2882
2883 // See if we can merge an overlap (or two colinear touching segments with
2884 // no junction where they meet).
2885 SCH_LINE* mergedLine = secondLine->MergeOverlap( aScreen, firstLine, true );
2886
2887 if( mergedLine != nullptr )
2888 {
2889 remove_item( firstLine );
2890 remove_item( secondLine );
2891
2892 if( m_schematicHolder )
2893 {
2894 m_schematicHolder->AddToScreen( mergedLine, aScreen );
2895 }
2896 else
2897 {
2898 aScreen->Append( mergedLine );
2899 }
2900
2901 generatedLines.insert( mergedLine );
2902 aCommit->Added( mergedLine, aScreen );
2903
2904 if( selectionTool && ( firstLine->IsSelected() || secondLine->IsSelected() ) )
2905 selectionTool->AddItemToSel( mergedLine, true /*quiet mode*/ );
2906
2907 break;
2908 }
2909 }
2910 }
2911 }
2912}
2913
2914
2916 const std::set<SCH_SCREEN*>& aLocalScreens )
2917{
2919 PROF_TIMER timer;
2920
2921 if( aCleanupFlags == LOCAL_CLEANUP )
2922 {
2923 if( aLocalScreens.empty() )
2924 CleanUp( aCommit, GetCurrentScreen() );
2925 else
2926 {
2927 for( SCH_SCREEN* screen : aLocalScreens )
2928 CleanUp( aCommit, screen );
2929 }
2930 }
2931 else if( aCleanupFlags == GLOBAL_CLEANUP )
2932 {
2933 std::unordered_set<SCH_SCREEN*> cleanedScreens;
2934
2935 for( const SCH_SHEET_PATH& sheet : Hierarchy() )
2936 {
2937 SCH_SCREEN* screen = sheet.LastScreen();
2938
2939 if( cleanedScreens.insert( screen ).second )
2940 {
2941 screen->BumpConnectivityRevision();
2942 CleanUp( aCommit, screen );
2943 }
2944 }
2945 }
2946
2947 timer.Stop();
2948 wxLogTrace( "CONN_PROFILE", "SchematicCleanUp() %0.4f ms", timer.msecs() );
2949
2950 if( Settings().m_IntersheetRefsShow )
2952}
2953
2954
2955void SCHEMATIC::RebuildConnectivity( std::function<void( SCH_ITEM* )>* aChangedItemHandler,
2956 PROGRESS_REPORTER* aProgressReporter,
2957 KIGFX::SCH_VIEW* aSchView )
2958{
2959 // Some importers populate screens after installing the hierarchy
2960 if( m_textVarAdapter )
2961 m_textVarAdapter->MarkHierarchyChanged();
2962
2964 m_project->GetProjectFile().NetSettings()->ClearAllCaches();
2965 std::unordered_set<SCH_SCREEN*> screens;
2966
2967 for( const SCH_SHEET_PATH& path : Hierarchy() )
2968 {
2969 if( SCH_SCREEN* screen = path.LastScreen() )
2970 screens.insert( screen );
2971 }
2972
2973 SCH_RULE_AREA::UpdateRuleAreasInScreens( screens, aSchView );
2974
2975 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine )
2976 {
2977 m_connectivity->Recalculate( *this, true,
2978 aChangedItemHandler ? *aChangedItemHandler
2979 : std::function<void( SCH_ITEM* )>() );
2980 }
2981 else
2982 {
2983 ConnectionGraph()->Recalculate( Hierarchy(), true, aChangedItemHandler, aProgressReporter );
2984 }
2985}
2986
2987
2989 TOOL_MANAGER* aToolManager, PROGRESS_REPORTER* aProgressReporter,
2990 KIGFX::SCH_VIEW* aSchView,
2991 std::function<void( SCH_ITEM* )>* aChangedItemHandler,
2992 PICKED_ITEMS_LIST* aLastChangeList, bool aCleanupDone )
2993{
2994 SCH_COMMIT localCommit( aToolManager );
2995
2996 if( !aCommit )
2997 aCommit = &localCommit;
2998
2999 if( !aCleanupDone )
3000 CleanUpConnections( aCommit, aCleanupFlags );
3001
3002 SCH_SHEET_LIST list = Hierarchy();
3003
3004 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine )
3005 {
3006 if( !ADVANCED_CFG::GetCfg().m_IncrementalConnectivity || aCleanupFlags == GLOBAL_CLEANUP )
3007 {
3008 if( !localCommit.Empty() )
3009 localCommit.Push( _( "Schematic Cleanup" ), SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
3010
3011 RebuildConnectivity( aChangedItemHandler, aProgressReporter, aSchView );
3012 return;
3013 }
3014
3015 std::unordered_set<SCH_SCREEN*> screens;
3016
3017 for( const SCH_SHEET_PATH& path : list )
3018 screens.insert( path.LastScreen() );
3019
3020 SCH_RULE_AREA::UpdateRuleAreasInScreens( screens, aSchView );
3021
3022 // Commit cleanup before callbacks, which may close or replace the schematic
3023 if( !localCommit.Empty() )
3024 localCommit.Push( _( "Schematic Cleanup" ), SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
3025
3026 m_connectivity->Recalculate( *this, false, aChangedItemHandler ? *aChangedItemHandler
3027 : std::function<void( SCH_ITEM* )>() );
3028 return;
3029 }
3030
3031 if( !ADVANCED_CFG::GetCfg().m_IncrementalConnectivity || aCleanupFlags == GLOBAL_CLEANUP
3032 || aLastChangeList == nullptr || ConnectionGraph()->IsMinor() )
3033 {
3034 if( !localCommit.Empty() )
3035 localCommit.Push( _( "Schematic Cleanup" ), SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
3036
3037 RebuildConnectivity( aChangedItemHandler, aProgressReporter, aSchView );
3038 return;
3039 }
3040 else
3041 {
3042 struct CHANGED_ITEM
3043 {
3044 SCH_ITEM* item;
3045 SCH_ITEM* linked_item;
3046 SCH_SCREEN* screen;
3047 };
3048
3049 // Final change sets
3050 std::set<SCH_ITEM*> changed_items;
3051 std::set<VECTOR2I> pts;
3052 std::set<std::pair<SCH_SHEET_PATH, SCH_ITEM*>> item_paths;
3053
3054 // Working change sets
3055 std::unordered_set<SCH_SCREEN*> changed_screens;
3056 std::set<std::pair<SCH_RULE_AREA*, SCH_SCREEN*>> changed_rule_areas;
3057 std::vector<CHANGED_ITEM> changed_connectable_items;
3058
3059 // Lambda to add an item to the connectivity update sets
3060 auto addItemToChangeSet =
3061 [&changed_items, &pts, &item_paths]( CHANGED_ITEM itemData )
3062 {
3063 std::vector<SCH_SHEET_PATH>& paths = itemData.screen->GetClientSheetPaths();
3064
3065 std::vector<VECTOR2I> tmp_pts = itemData.item->GetConnectionPoints();
3066 pts.insert( tmp_pts.begin(), tmp_pts.end() );
3067 changed_items.insert( itemData.item );
3068
3069 for( SCH_SHEET_PATH& path : paths )
3070 item_paths.insert( std::make_pair( path, itemData.item ) );
3071
3072 if( !itemData.linked_item || !itemData.linked_item->IsConnectable() )
3073 return;
3074
3075 tmp_pts = itemData.linked_item->GetConnectionPoints();
3076 pts.insert( tmp_pts.begin(), tmp_pts.end() );
3077 changed_items.insert( itemData.linked_item );
3078
3079 // We have to directly add the pins here because the link may not exist on the schematic
3080 // anymore and so won't be picked up by GetScreen()->Items().Overlapping() below.
3081 if( SCH_SYMBOL* symbol = dynamic_cast<SCH_SYMBOL*>( itemData.linked_item ) )
3082 {
3083 std::vector<SCH_PIN*> pins = symbol->GetGraphicalPins( ALL_UNITS, ALL_BODY_STYLES );
3084 changed_items.insert( pins.begin(), pins.end() );
3085 }
3086
3087 for( SCH_SHEET_PATH& path : paths )
3088 item_paths.insert( std::make_pair( path, itemData.linked_item ) );
3089 };
3090
3091 // Get all changed connectable items and determine all changed screens
3092 for( unsigned ii = 0; ii < aLastChangeList->GetCount(); ++ii )
3093 {
3094 switch( aLastChangeList->GetPickedItemStatus( ii ) )
3095 {
3096 // Only care about changed, new, and deleted items, the other
3097 // cases are not connectivity-related
3098 case UNDO_REDO::CHANGED:
3099 case UNDO_REDO::NEWITEM:
3100 case UNDO_REDO::DELETED: break;
3101
3102 default: continue;
3103 }
3104
3105 SCH_ITEM* item = dynamic_cast<SCH_ITEM*>( aLastChangeList->GetPickedItem( ii ) );
3106
3107 if( item )
3108 {
3109 SCH_SCREEN* screen = static_cast<SCH_SCREEN*>( aLastChangeList->GetScreenForItem( ii ) );
3110 changed_screens.insert( screen );
3111
3112 if( item->Type() == SCH_RULE_AREA_T )
3113 {
3114 SCH_RULE_AREA* ruleArea = static_cast<SCH_RULE_AREA*>( item );
3115 changed_rule_areas.insert( { ruleArea, screen } );
3116 }
3117 else if( item->IsConnectable() )
3118 {
3119 SCH_ITEM* linked_item = dynamic_cast<SCH_ITEM*>( aLastChangeList->GetPickedItemLink( ii ) );
3120 changed_connectable_items.push_back( { item, linked_item, screen } );
3121 }
3122 }
3123 }
3124
3125 // Update rule areas in changed screens to propagate any directive connectivity changes
3126 std::vector<std::pair<SCH_RULE_AREA*, SCH_SCREEN*>> forceUpdateRuleAreas =
3127 SCH_RULE_AREA::UpdateRuleAreasInScreens( changed_screens, aSchView );
3128
3129 std::for_each( forceUpdateRuleAreas.begin(), forceUpdateRuleAreas.end(),
3130 [&]( std::pair<SCH_RULE_AREA*, SCH_SCREEN*>& updatedRuleArea )
3131 {
3132 changed_rule_areas.insert( updatedRuleArea );
3133 } );
3134
3135 // If a SCH_RULE_AREA was changed, we need to add all past and present contained items to
3136 // update their connectivity
3137 std::unordered_map<KIID, EDA_ITEM*> itemMap;
3138 list.FillItemMap( itemMap );
3139
3140 auto addPastAndPresentContainedItems =
3141 [&]( SCH_RULE_AREA* changedRuleArea, SCH_SCREEN* screen )
3142 {
3143 for( const KIID& pastItem : changedRuleArea->GetPastContainedItems() )
3144 {
3145 if( itemMap.contains( pastItem ) )
3146 addItemToChangeSet( { static_cast<SCH_ITEM*>( itemMap[pastItem] ), nullptr, screen } );
3147 }
3148
3149 for( SCH_ITEM* containedItem : changedRuleArea->GetContainedItems() )
3150 addItemToChangeSet( { containedItem, nullptr, screen } );
3151 };
3152
3153 for( const auto& [changedRuleArea, screen] : changed_rule_areas )
3154 addPastAndPresentContainedItems( changedRuleArea, screen );
3155
3156 // Add all changed items, and associated items, to the change set
3157 for( CHANGED_ITEM& changed_item : changed_connectable_items )
3158 {
3159 addItemToChangeSet( changed_item );
3160
3161 // If a SCH_DIRECTIVE_LABEL was changed which is attached to a SCH_RULE_AREA, we need
3162 // to add the contained items to the change set to force update of their connectivity
3163 if( changed_item.item->Type() == SCH_DIRECTIVE_LABEL_T )
3164 {
3165 const std::vector<VECTOR2I> labelConnectionPoints = changed_item.item->GetConnectionPoints();
3166
3167 auto candidateRuleAreas = changed_item.screen->Items()
3168 .Overlapping( SCH_RULE_AREA_T, changed_item.item->GetBoundingBox() );
3169
3170 for( SCH_ITEM* candidateRuleArea : candidateRuleAreas )
3171 {
3172 SCH_RULE_AREA* ruleArea = static_cast<SCH_RULE_AREA*>( candidateRuleArea );
3173
3174 if( ruleArea->GetPolyShape().CollideEdge( labelConnectionPoints[0], nullptr, 5 ) )
3175 addPastAndPresentContainedItems( ruleArea, changed_item.screen );
3176 }
3177 }
3178 }
3179
3180 for( const VECTOR2I& pt : pts )
3181 {
3182 for( SCH_ITEM* item : GetCurrentScreen()->Items().Overlapping( pt ) )
3183 {
3184 // Leave this check in place. Overlapping items are not necessarily connectable.
3185 if( !item->IsConnectable() )
3186 continue;
3187
3188 SCH_SCREEN* screen = GetCurrentScreen();
3189 std::vector<SCH_SHEET_PATH>& paths = screen->GetClientSheetPaths();
3190
3191 if( item->Type() == SCH_LINE_T )
3192 {
3193 if( item->HitTest( pt ) )
3194 {
3195 changed_items.insert( item );
3196
3197 for( SCH_SHEET_PATH& path : paths )
3198 item_paths.insert( std::make_pair( path, item ) );
3199 }
3200 }
3201 else if( item->Type() == SCH_SYMBOL_T && item->IsConnected( pt ) )
3202 {
3203 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
3204 std::vector<SCH_PIN*> pins = symbol->GetGraphicalPins( ALL_UNITS, ALL_BODY_STYLES );
3205
3206 changed_items.insert( pins.begin(), pins.end() );
3207
3208 for( SCH_PIN* pin : pins )
3209 {
3210 for( SCH_SHEET_PATH& path : paths )
3211 item_paths.insert( std::make_pair( path, pin ) );
3212 }
3213 }
3214 else if( item->Type() == SCH_SHEET_T )
3215 {
3216 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
3217
3218 wxCHECK2( sheet, continue );
3219
3220 std::vector<SCH_SHEET_PIN*> sheetPins = sheet->GetPins();
3221 changed_items.insert( sheetPins.begin(), sheetPins.end() );
3222
3223 for( SCH_SHEET_PIN* pin : sheetPins )
3224 {
3225 for( SCH_SHEET_PATH& path : paths )
3226 item_paths.insert( std::make_pair( path, pin ) );
3227 }
3228 }
3229 else
3230 {
3231 if( item->IsConnected( pt ) )
3232 {
3233 changed_items.insert( item );
3234
3235 for( SCH_SHEET_PATH& path : paths )
3236 item_paths.insert( std::make_pair( path, item ) );
3237 }
3238 }
3239 }
3240 }
3241
3242 std::set<std::pair<SCH_SHEET_PATH, SCH_ITEM*>> all_items =
3243 ConnectionGraph()->ExtractAffectedItems( changed_items );
3244
3245 all_items.insert( item_paths.begin(), item_paths.end() );
3246
3247 CONNECTION_GRAPH new_graph( this );
3248
3249 new_graph.SetLastCodes( ConnectionGraph() );
3250
3251 std::shared_ptr<NET_SETTINGS> netSettings = m_project->GetProjectFile().NetSettings();
3252
3253 std::set<wxString> affectedNets;
3254
3255 for( auto& [path, item] : all_items )
3256 {
3257 wxCHECK2( item, continue );
3258 item->SetConnectivityDirty();
3259 SCH_CONNECTION* conn = item->Connection();
3260
3261 if( conn )
3262 affectedNets.insert( conn->Name() );
3263 }
3264
3265 // For label items, also capture the old net name from the linked item (original state).
3266 // This ensures cache is cleared for both old and new net names when a label is renamed.
3267 for( const CHANGED_ITEM& changedItem : changed_connectable_items )
3268 {
3269 if( SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( changedItem.item ) )
3270 {
3271 const wxString& driverName = label->GetCachedDriverName();
3272
3273 if( !driverName.IsEmpty() )
3274 affectedNets.insert( driverName );
3275 }
3276
3277 if( SCH_LABEL_BASE* linkedLabel = dynamic_cast<SCH_LABEL_BASE*>( changedItem.linked_item ) )
3278 {
3279 const wxString& driverName = linkedLabel->GetCachedDriverName();
3280
3281 if( !driverName.IsEmpty() )
3282 affectedNets.insert( driverName );
3283 }
3284 }
3285
3286 // Reset resolved netclass cache for this connection
3287 for( const wxString& netName : affectedNets )
3288 netSettings->ClearCacheForNet( netName );
3289
3290 new_graph.Recalculate( list, false, aChangedItemHandler, aProgressReporter );
3291 ConnectionGraph()->Merge( new_graph );
3292 }
3293
3294 if( !localCommit.Empty() )
3295 localCommit.Push( _( "Schematic Cleanup" ), SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
3296
3297}
3298
3299
3301{
3302 Reset();
3303
3305
3306 // Create the actual first top-level sheet
3307 SCH_SHEET* rootSheet = new SCH_SHEET( this );
3308 SCH_SCREEN* rootScreen = new SCH_SCREEN( this );
3309
3310 rootSheet->SetScreen( rootScreen );
3311 rootSheet->SyncUuidToScreen();
3312 rootScreen->SetFileName( "untitled.kicad_sch" ); // Set default filename to avoid conflicts
3313 rootScreen->SetPageNumber( wxT( "1" ) );
3314
3315 // Don't leave root page number empty
3316 SCH_SHEET_PATH rootSheetPath;
3317 rootSheetPath.push_back( m_rootSheet );
3318 rootSheetPath.push_back( rootSheet );
3319 rootSheetPath.SetPageNumber( wxT( "1" ) );
3320
3321 SetTopLevelSheets( { rootSheet } );
3322}
3323
3324
3325std::vector<SCH_SHEET*> SCHEMATIC::GetTopLevelSheets() const
3326{
3327 return m_topLevelSheets;
3328}
3329
3331{
3332 if( aIndex < 0 )
3333 return nullptr;
3334
3335 size_t index = static_cast<size_t>( aIndex );
3336
3337 if( index >= m_topLevelSheets.size() )
3338 return nullptr;
3339
3340 return m_topLevelSheets[index];
3341}
3342
3343
3344std::vector<TOP_LEVEL_SHEET_INFO> SCHEMATIC::TopLevelSheetInfos() const
3345{
3346 std::vector<TOP_LEVEL_SHEET_INFO> infos;
3347 wxString projectPath = m_project ? m_project->GetProjectPath() : wxString();
3348
3349 for( SCH_SHEET* sheet : GetTopLevelSheets() )
3350 {
3351 if( !sheet->GetScreen() )
3352 continue;
3353
3354 // A top-level sheet's file is its screen's; the SHEET_FILENAME field is for instances
3355 wxFileName sheetFn( sheet->GetScreen()->GetFileName() );
3356
3357 if( sheetFn.IsAbsolute() )
3358 sheetFn.MakeRelativeTo( projectPath );
3359
3360 infos.emplace_back( sheet->m_Uuid, sheet->GetName(), sheetFn.GetFullPath() );
3361 }
3362
3363 return infos;
3364}
3365
3366
3367bool SCHEMATIC::TopLevelSheetsMatch( const std::vector<TOP_LEVEL_SHEET_INFO>& aSheets ) const
3368{
3369 std::vector<TOP_LEVEL_SHEET_INFO> loaded = TopLevelSheetInfos();
3370
3371 if( loaded.size() != aSheets.size() )
3372 return false;
3373
3374 wxString projectPath = m_project ? m_project->GetProjectPath() : wxString();
3375
3376 for( size_t ii = 0; ii < loaded.size(); ++ii )
3377 {
3378 wxFileName have( loaded[ii].filename );
3379 have.MakeAbsolute( projectPath );
3380
3381 wxFileName want = TopLevelSheetFile( aSheets[ii], projectPath,
3382 have.GetExt() == FILEEXT::LegacySchematicFileExtension );
3383
3384 if( ( aSheets[ii].uuid != niluuid && aSheets[ii].uuid != loaded[ii].uuid )
3385 || aSheets[ii].name != loaded[ii].name || !have.SameAs( want ) )
3386 {
3387 return false;
3388 }
3389 }
3390
3391 return true;
3392}
3393
3394
3395wxFileName SCHEMATIC::TopLevelSheetFile( const TOP_LEVEL_SHEET_INFO& aSheet, const wxString& aProjectPath,
3396 bool aLegacy )
3397{
3398 wxFileName fn( aSheet.filename );
3399 fn.MakeAbsolute( aProjectPath );
3400
3401 if( aLegacy )
3403
3404 return fn;
3405}
3406
3407
3408bool SCHEMATIC::IsTopLevelSheetUuid( const KIID& aUuid ) const
3409{
3410 if( !m_rootSheet )
3411 return false;
3412
3413 // A non-virtual root is the only sheet above the hierarchy
3414 if( m_rootSheet->m_Uuid != niluuid )
3415 return aUuid == m_rootSheet->m_Uuid;
3416
3417 for( const SCH_SHEET* sheet : m_topLevelSheets )
3418 {
3419 if( sheet && sheet->m_Uuid == aUuid )
3420 return true;
3421 }
3422
3423 return false;
3424}
3425
3426
3428{
3429 KIID_PATH path = aPath;
3430
3431 if( m_rootSheet && m_rootSheet->m_Uuid == niluuid && !path.empty() && path.front() == niluuid )
3432 path.erase( path.begin() );
3433
3434 return path;
3435}
3436
3437
3439{
3440 const KIID_PATH path = NormalizeInstancePath( aPath );
3441
3442 return !path.empty() && IsTopLevelSheetUuid( path.front() );
3443}
3444
3445
3447{
3448 wxCHECK_RET( aSheet, wxS( "Cannot add null sheet!" ) );
3449 wxCHECK_RET( aSheet->GetScreen(), wxS( "Cannot add virtual root as top-level sheet!" ) );
3450
3452
3453 // Set parent to virtual root
3454 aSheet->SetParent( m_rootSheet );
3455
3456 // Add to the virtual root's screen if it exists
3457 if( m_rootSheet->GetScreen() )
3458 {
3459 m_rootSheet->GetScreen()->Append( aSheet );
3460 }
3461
3462 // Add to our list
3463 m_topLevelSheets.push_back( aSheet );
3464
3466 rebuildHierarchyState( true );
3467}
3468
3470{
3471 auto it = std::find( m_topLevelSheets.begin(), m_topLevelSheets.end(), aSheet );
3472
3473 if( it == m_topLevelSheets.end() )
3474 return false;
3475
3476 if( m_topLevelSheets.size() == 1 )
3477 return false;
3478
3479 m_topLevelSheets.erase( it );
3480
3481 if( m_rootSheet && m_rootSheet->GetScreen() )
3482 m_rootSheet->GetScreen()->Remove( aSheet, false );
3483
3484 // If we're removing the current sheet, switch to another one
3485 if( !m_currentSheet->empty() && m_currentSheet->at( 0 ) == aSheet )
3486 {
3487 m_currentSheet->clear();
3488 if( !m_topLevelSheets.empty() )
3489 {
3490 m_currentSheet->push_back( m_topLevelSheets[0] );
3491 }
3492 }
3493
3494 rebuildHierarchyState( true );
3495 return true;
3496}
3497
3498
3499bool SCHEMATIC::IsTopLevelSheet( const SCH_SHEET* aSheet ) const
3500{
3501 return std::find( m_topLevelSheets.begin(), m_topLevelSheets.end(), aSheet ) != m_topLevelSheets.end();
3502}
3503
3504
3506{
3507 SCH_SHEET_LIST hierarchy;
3508
3509 wxLogTrace( traceSchSheetPaths, "BuildSheetListSortedByPageNumbers: %zu top-level sheets",
3510 m_topLevelSheets.size() );
3511
3512 // Can't build hierarchy without top-level sheets
3513 if( m_topLevelSheets.empty() )
3514 return hierarchy;
3515
3516 // For each top-level sheet, build its hierarchy
3517 for( SCH_SHEET* sheet : m_topLevelSheets )
3518 {
3519 if( sheet )
3520 {
3521 wxLogTrace( traceSchSheetPaths, " Top-level sheet: '%s' (UUID=%s, isVirtualRoot=%d)", sheet->GetName(),
3522 sheet->m_Uuid.AsString(), sheet->m_Uuid == niluuid ? 1 : 0 );
3523
3524 // Build the sheet list for this top-level sheet
3525 SCH_SHEET_LIST sheetList;
3526 sheetList.BuildSheetList( sheet, false );
3527
3528 // Add all sheets from this top-level sheet's hierarchy
3529 for( const SCH_SHEET_PATH& path : sheetList )
3530 {
3531 hierarchy.push_back( path );
3532 }
3533 }
3534 }
3535
3536 hierarchy.SortByPageNumbers();
3537
3538 return hierarchy;
3539}
3540
3541
3543{
3544 SCH_SHEET_LIST sheets;
3545
3546 // For each top-level sheet, build its hierarchy
3547 for( SCH_SHEET* sheet : m_topLevelSheets )
3548 {
3549 if( sheet )
3550 {
3551 SCH_SHEET_LIST sheetList;
3552 sheetList.BuildSheetList( sheet, false );
3553
3554 // Add all sheets from this top-level sheet's hierarchy
3555 for( const SCH_SHEET_PATH& path : sheetList )
3556 {
3557 sheets.push_back( path );
3558 }
3559 }
3560 }
3561
3562 return sheets;
3563}
3564
3565
3567{
3568 wxArrayString variantNames;
3569
3570 // There is no default variant name. This is just a place holder for UI controls.
3571 variantNames.Add( GetDefaultVariantName() );
3572
3573 for( const wxString& name : m_variantNames )
3574 variantNames.Add( name );
3575
3576 variantNames.Sort( SortVariantNames ); // SortVariantNames ensures the default is always first
3577
3578 return variantNames;
3579}
3580
3581
3583{
3584 if( m_currentVariant.IsEmpty() || ( m_currentVariant == GetDefaultVariantName() ) )
3585 return wxEmptyString;
3586
3587 return m_currentVariant;
3588}
3589
3590
3591bool SCHEMATIC::HasVariant( const wxString& aVariantName ) const
3592{
3593 for( const wxString& name : m_variantNames )
3594 {
3595 if( name.CmpNoCase( aVariantName ) == 0 )
3596 return true;
3597 }
3598
3599 return false;
3600}
3601
3602
3603void SCHEMATIC::SetCurrentVariant( const wxString& aVariantName )
3604{
3605 wxString newVariant;
3606
3607 // Internally an empty string is the default variant. Set to default if the variant name doesn't exist.
3608 if( ( aVariantName != GetDefaultVariantName() ) && m_variantNames.contains( aVariantName ) )
3609 newVariant = aVariantName;
3610
3611 m_currentVariant = newVariant;
3612
3613 // Variant-specific field values affect text geometry, so bounding box caches computed
3614 // with the previous variant's text are now stale.
3615 if( m_rootSheet )
3616 {
3617 SCH_SCREENS allScreens( m_rootSheet );
3618
3619 for( SCH_SCREEN* screen = allScreens.GetFirst(); screen; screen = allScreens.GetNext() )
3620 {
3621 for( SCH_ITEM* item : screen->Items() )
3622 item->ClearCaches();
3623 }
3624 }
3625
3626 // Variant-driven cross-ref / local-field value changes require a
3627 // reactive fan-out so dependent text items repaint without waiting for
3628 // an unrelated edit to nudge the view.
3629 if( m_textVarAdapter )
3630 m_textVarAdapter->Tracker().InvalidateVariantScoped();
3631}
3632
3633
3634void SCHEMATIC::AddVariant( const wxString& aVariantName )
3635{
3636 m_variantNames.emplace( aVariantName );
3637
3638 // Ensure the variant is registered in the project file
3639 std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3640
3641 if( descriptions.find( aVariantName ) == descriptions.end() )
3642 descriptions[aVariantName] = wxEmptyString;
3643}
3644
3645
3646void SCHEMATIC::DeleteVariantDefinition( const wxString& aVariantName )
3647{
3648 if( m_currentVariant == aVariantName )
3649 SetCurrentVariant( wxEmptyString );
3650
3651 m_variantNames.erase( aVariantName );
3652 Settings().m_VariantDescriptions.erase( aVariantName );
3653}
3654
3655
3656void SCHEMATIC::DeleteVariant( const wxString& aVariantName, SCH_COMMIT* aCommit )
3657{
3658 wxCHECK( m_rootSheet, /* void */ );
3659
3660 SCH_SCREENS allScreens( m_rootSheet );
3661
3662 allScreens.DeleteVariant( aVariantName, aCommit );
3663 DeleteVariantDefinition( aVariantName );
3664}
3665
3666
3667void SCHEMATIC::RenameVariant( const wxString& aOldName, const wxString& aNewName, SCH_COMMIT* aCommit )
3668{
3669 wxCHECK( m_rootSheet, /* void */ );
3670 wxCHECK( !aOldName.IsEmpty() && !aNewName.IsEmpty(), /* void */ );
3671 wxCHECK( m_variantNames.contains( aOldName ), /* void */ );
3672
3673 m_variantNames.erase( aOldName );
3674 m_variantNames.insert( aNewName );
3675
3676 std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3677
3678 if( descriptions.count( aOldName ) )
3679 {
3680 descriptions[aNewName] = descriptions[aOldName];
3681 descriptions.erase( aOldName );
3682 }
3683
3684 // Retarget through SetCurrentVariant so the whole-schematic cache/text-var invalidation runs;
3685 // otherwise ${VARIANT} text on off-sheet items keeps its stale render cache after the rename.
3686 if( m_currentVariant == aOldName )
3687 SetCurrentVariant( aNewName );
3688
3689 SCH_SCREENS allScreens( m_rootSheet );
3690 allScreens.RenameVariant( aOldName, aNewName, aCommit );
3691}
3692
3693
3694void SCHEMATIC::CopyVariant( const wxString& aSourceVariant, const wxString& aNewVariant,
3695 SCH_COMMIT* aCommit )
3696{
3697 wxCHECK( m_rootSheet, /* void */ );
3698 wxCHECK( !aSourceVariant.IsEmpty() && !aNewVariant.IsEmpty(), /* void */ );
3699 wxCHECK( m_variantNames.contains( aSourceVariant ), /* void */ );
3700 wxCHECK( !m_variantNames.contains( aNewVariant ), /* void */ );
3701
3702 AddVariant( aNewVariant );
3703
3704 std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3705
3706 if( descriptions.count( aSourceVariant ) )
3707 descriptions[aNewVariant] = descriptions[aSourceVariant];
3708
3709 SCH_SCREENS allScreens( m_rootSheet );
3710 allScreens.CopyVariant( aSourceVariant, aNewVariant, aCommit );
3711}
3712
3713
3714wxString SCHEMATIC::GetVariantDescription( const wxString& aVariantName ) const
3715{
3716 const std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3717 auto it = descriptions.find( aVariantName );
3718
3719 if( it != descriptions.end() )
3720 return it->second;
3721
3722 return wxEmptyString;
3723}
3724
3725
3726void SCHEMATIC::SetVariantDescription( const wxString& aVariantName, const wxString& aDescription )
3727{
3728 std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3729
3730 if( aDescription.IsEmpty() )
3731 descriptions.erase( aVariantName );
3732 else
3733 descriptions[aVariantName] = aDescription;
3734
3735 if( m_textVarAdapter )
3736 m_textVarAdapter->Tracker().InvalidateVariantScoped();
3737}
3738
3739
3741{
3742 if( m_rootSheet && m_rootSheet->GetScreen() )
3743 {
3744 SCH_SCREENS screens( m_rootSheet );
3745 std::set<wxString> variantNames = screens.GetVariantNames();
3746 m_variantNames.insert( variantNames.begin(), variantNames.end() );
3747
3748 // Register any unknown variants to the project file with empty descriptions
3749 std::map<wxString, wxString>& descriptions = Settings().m_VariantDescriptions;
3750
3751 for( const wxString& name : variantNames )
3752 {
3753 if( descriptions.find( name ) == descriptions.end() )
3754 descriptions[name] = wxEmptyString;
3755 }
3756
3757 // Also include variants from the project file that may not have any diffs yet.
3758 // This ensures newly created variants with no symbol changes are preserved.
3759 for( const auto& [name, description] : descriptions )
3760 m_variantNames.insert( name );
3761 }
3762}
3763
3764
3766{
3767 std::set<wxString> before;
3768 before.swap( m_variantNames );
3769 LoadVariants();
3770
3771 bool changed = m_variantNames != before;
3772
3773 if( !m_currentVariant.IsEmpty() && !m_variantNames.contains( m_currentVariant ) )
3774 {
3775 SetCurrentVariant( wxEmptyString );
3776 changed = true;
3777 }
3778
3779 return changed;
3780}
3781
3782
3783void SCHEMATIC::SaveToHistory( const wxString& aProjectPath, std::vector<HISTORY_FILE_DATA>& aFileData )
3784{
3785 if( !IsValid() )
3786 return;
3787
3788 wxString projPath = m_project->GetProjectPath();
3789
3790 if( projPath.IsEmpty() )
3791 return; // no project yet
3792
3793 // Verify we're saving for the correct project
3794 if( !projPath.IsSameAs( aProjectPath ) )
3795 {
3796 wxLogTrace( traceAutoSave, wxS( "[history] sch saver skipping - project path mismatch: %s vs %s" ), projPath,
3797 aProjectPath );
3798 return;
3799 }
3800
3801 if( !projPath.EndsWith( wxFILE_SEP_PATH ) )
3802 projPath += wxFILE_SEP_PATH;
3803
3804 SCH_SHEET_LIST sheetList = Hierarchy();
3805
3807
3808 KICAD_FORMAT::FORMAT_MODE mode = KICAD_FORMAT::FORMAT_MODE::NORMAL;
3809
3810 if( ADVANCED_CFG::GetCfg().m_CompactSave )
3811 mode = KICAD_FORMAT::FORMAT_MODE::COMPACT_TEXT_PROPERTIES;
3812
3813 // In ZIP mode the only caller is the autosave timer, so skipping clean sheets
3814 // avoids spurious _autosave-* files. In INCREMENTAL mode the manual-save flow
3815 // clears dirty flags before calling here, so filtering would skip the whole
3816 // snapshot. Git's diff-against-HEAD check rejects no-op commits there anyway.
3817 bool filterClean = !Pgm().GetCommonSettings()->AutosaveUsesLocalHistory();
3818
3819 for( const SCH_SHEET_PATH& path : sheetList )
3820 {
3821 SCH_SHEET* sheet = path.Last();
3822 SCH_SCREEN* screen = path.LastScreen();
3823
3824 if( !sheet || !screen )
3825 continue;
3826
3827 if( filterClean && !screen->IsContentModified() )
3828 continue;
3829
3830 wxFileName abs = m_project->AbsolutePath( screen->GetFileName() );
3831
3832 if( !abs.IsOk() )
3833 continue;
3834
3835 wxString absPath = abs.GetFullPath();
3836
3837 if( absPath.IsEmpty()
3838 || !absPath.Left( projPath.length() ).IsSameAs( projPath, wxFileName::IsCaseSensitive() ) )
3839 continue;
3840
3841 wxString rel = absPath.Mid( projPath.length() );
3842
3843 try
3844 {
3845 STRING_FORMATTER formatter;
3846 pi.FormatSchematicToFormatter( &formatter, sheet, this );
3847
3848 HISTORY_FILE_DATA entry;
3849 entry.relativePath = rel;
3850 entry.content = std::move( formatter.MutableString() );
3851 entry.prettify = true;
3852 entry.formatMode = mode;
3853 aFileData.push_back( std::move( entry ) );
3854
3855 wxLogTrace( traceAutoSave,
3856 wxS( "[history] sch saver serialized %zu bytes for '%s' -> '%s'" ),
3857 aFileData.back().content.size(), absPath, rel );
3858 }
3859 catch( const IO_ERROR& ioe )
3860 {
3861 wxLogTrace( traceAutoSave, wxS( "[history] sch saver serialize failed for '%s': %s" ),
3862 absPath, wxString::FromUTF8( ioe.What() ) );
3863 }
3864 }
3865}
int index
const char * name
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
Definition api_enums.cpp:56
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void SetPageCount(int aPageCount)
void SetPageNumber(const wxString &aPageNumber)
Definition base_screen.h:75
bool IsContentModified() const
Definition base_screen.h:56
void SetVirtualPageNumber(int aPageNumber)
Definition base_screen.h:72
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition commit.h:68
bool Empty() const
Definition commit.h:145
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
int GetStatus(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Returns status of an item.
Definition commit.cpp:235
bool AutosaveUsesLocalHistory() const
The backup format is the single switch that selects the autosave mechanism: the incremental format re...
Calculate the connectivity of a schematic and generate netlists.
void Recalculate(const SCH_SHEET_LIST &aSheetList, bool aUnconditional=false, std::function< void(SCH_ITEM *)> *aChangedItemHandler=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr)
Update the connection graph for the given list of sheets.
std::set< std::pair< SCH_SHEET_PATH, SCH_ITEM * > > ExtractAffectedItems(const std::set< SCH_ITEM * > &aItems)
For a set of items, this will remove the connected items and their associated data including subgraph...
void SetLastCodes(const CONNECTION_GRAPH *aOther)
void Merge(CONNECTION_GRAPH &aGraph)
Combine the input graph contents into the current graph.
A subgraph is a set of items that are electrically connected on a single sheet.
static PRIORITY GetDriverPriority(SCH_ITEM *aDriver)
Return the priority (higher is more important) of a candidate driver.
const SCH_CONNECTION * GetDriverConnection() const
EDA_ITEM_FLAGS GetEditFlags() const
Definition eda_item.h:170
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
bool IsSelected() const
Definition eda_item.h:134
EDA_ITEM * GetParent() const
Definition eda_item.h:112
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
EDA_ITEM_FLAGS GetFlags() const
Definition eda_item.h:167
EDA_ITEM(EDA_ITEM *parent, KICAD_T idType, bool isSCH_ITEM=false, bool isBOARD_ITEM=false)
Definition eda_item.cpp:84
SHAPE_POLY_SET & GetPolyShape()
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
EMBEDDED_FILES()=default
Container for an ERC exclusion, which is a SCH_MARKER plus an optional comment.
static ERC_EXCLUSION FromLegacyStrings(const SCH_SHEET_LIST &aSheetList, const wxString &aMarkerData, const wxString &aComment)
const kiapi::schematic::ErcExclusion & ToProto() const
void SetComment(const wxString &aComment)
static ERC_EXCLUSION FromMarker(const SCH_MARKER &aMarker)
wxString GetComment() const
std::string GetSortKey() const
static ERC_EXCLUSION FromProto(const kiapi::schematic::ErcExclusion &aMessage)
static std::shared_ptr< ERC_ITEM > Create(int aErrorCode)
Constructs an ERC_ITEM for the given error code.
Definition erc_item.cpp:321
Container for ERC settings.
std::set< std::pair< wxString, wxString > > m_ErcExclusionsLegacy
std::set< ERC_EXCLUSION, ERC_EXCLUSION_COMPARE > m_ErcExclusions
Class that other classes need to inherit from, in order to be inspectable.
Definition inspectable.h:39
wxAny Get(PROPERTY_BASE *aProperty) const
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()
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
virtual bool IsStroke() const
Definition font.h:101
Implement outline font drawing.
EMBEDDING_PERMISSION GetEmbeddingPermission() const
Definition kiid.h:46
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
UTF8 Format() const
Definition lib_id.cpp:132
Define a library symbol object.
Definition lib_symbol.h:114
const PIN_MAP_SET & GetPinMaps() const
Pin-to-pad mapping (issue #2282).
Definition lib_symbol.h:268
const std::vector< ASSOCIATED_FOOTPRINT > & GetAssociatedFootprints() const
Definition lib_symbol.h:272
bool IsExcluded() const
Definition marker_base.h:88
std::shared_ptr< RC_ITEM > GetRCItem() const
void SetExcluded(bool aExcluded, const wxString &aComment=wxEmptyString)
Definition marker_base.h:89
static void ConvertToSpiceMarkup(wxString *aNetName)
Convert an escaped schematic net name to SPICE, preserving literal slashes when mapping ground names.
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:576
A holder to handle information on schematic or board items.
UNDO_REDO GetPickedItemStatus(unsigned int aIdx) const
EDA_ITEM * GetPickedItemLink(unsigned int aIdx) const
unsigned GetCount() const
BASE_SCREEN * GetScreenForItem(unsigned int aIdx) const
EDA_ITEM * GetPickedItem(unsigned int aIdx) const
A small class to help profiling.
Definition profile.h:46
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:86
double msecs(bool aSinceLast=false)
Definition profile.h:148
A progress reporter interface for use in multi-threaded environments.
The backing store for a PROJECT, in JSON format.
Container for project specific data.
Definition project.h:63
const wxString & Name() const
Definition property.h:221
static PROPERTY_MANAGER & Instance()
class PROPERTY_LISTENER_SUBSCRIPTION RegisterListener(TYPE_ID aType, PROPERTY_LISTENER aListenerFunc)
Register a listener for the given type and return a move-only subscription that auto-unregisters in i...
virtual void OnSchItemsRemoved(SCHEMATIC &aSch, std::vector< SCH_ITEM * > &aSchItem)
Definition schematic.h:87
virtual void OnSchItemsChanged(SCHEMATIC &aSch, std::vector< SCH_ITEM * > &aSchItem)
Definition schematic.h:88
virtual void OnSchSelectionChanged(SCHEMATIC &aSch)
Definition schematic.h:94
virtual void OnSchSheetChanged(SCHEMATIC &aSch)
Definition schematic.h:92
virtual void OnSchItemsAdded(SCHEMATIC &aSch, std::vector< SCH_ITEM * > &aSchItem)
Definition schematic.h:86
These are loaded from Eeschema settings but then overwritten by the project settings.
std::map< wxString, wxString > m_VariantDescriptions
A map of variant names to their descriptions.
void DeleteVariantDefinition(const wxString &aVariantName)
Delete the definition of a variant.
void SetCurrentVariant(const wxString &aVariantName)
bool m_settingTopLevelSheets
Re-entry guard to prevent infinite recursion between ensureDefaultTopLevelSheet and RefreshHierarchy ...
Definition schematic.h:961
std::unique_ptr< SCH_CONNECTIVITY::NETCHAIN_MANAGER > m_netChains
Definition schematic.h:880
void updatePackageSuffixes() const
Rebuild m_packageSuffixes when a reference changed; the caller holds m_packageSuffixesMutex.
wxString GetUnitRefSuffix(const SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aPath, int aUnit) const
void Reset()
Initialize this schematic to a blank one, unloading anything existing.
std::set< const SCH_SCREEN * > GetSchematicsSharedByMultipleProjects() const
Return a list of schematic files in the current project that contain instance data for multiple proje...
std::map< std::pair< KIID, KIID_PATH >, wxString > m_packageSuffixes
Package suffix of each instance whose package spans suffixes and is not its own sheet's.
Definition schematic.h:923
void CreateDefaultScreens()
void SetLegacySymbolInstanceData()
Update the symbol value and footprint instance data for legacy designs.
void OnItemsAdded(std::vector< SCH_ITEM * > &aNewItems)
Must be used if Add() is used using a BULK_x ADD_MODE to generate a change event for listeners.
CONNECTION_GRAPH * m_connectionGraph
Hold and calculate connectivity information of this schematic.
Definition schematic.h:878
bool IsTopLevelSheet(const SCH_SHEET *aSheet) const
Check if a sheet is a top-level sheet (direct child of virtual root).
void loadBusAliasesFromProject()
std::unordered_map< size_t, wxString > m_refSuffixesBySheetHash
Every hierarchy path's suffix by its cached sheet path hash, which SCH_SHEET_PATH equality also relie...
Definition schematic.h:910
void AddTopLevelSheet(SCH_SHEET *aSheet)
Add a new top-level sheet to the schematic.
SCH_SHEET_LIST m_hierarchy
Cache of the entire schematic hierarchy sorted by sheet page number.
Definition schematic.h:904
@ TABLE_REMOVED
The reread file has no table; the one in use is kept, even empty, and saved back.
Definition schematic.h:448
@ CHANGED
The project table changed the aliases in use, so connectivity needs a rebuild.
Definition schematic.h:447
void rebuildHierarchyState(bool aResetConnectionGraph)
void ResolveERCExclusionsPostUpdate()
Update markers to match recorded exclusions.
void RecomputeIntersheetRefs()
Update the schematic's page reference map for all global labels, and refresh the labels so that they ...
std::vector< SCH_MARKER * > ReloadERCExclusions()
Resolve exclusions again after the project file was reread.
void CacheExistingAnnotation()
Store all existing annotations in the REFDES_TRACKER.
wxString GetVariantDescription(const wxString &aVariantName) const
Return the description for a variant.
void LoadVariants()
This is a throw away method for variant testing.
SCH_SHEET_LIST BuildSheetListSortedByPageNumbers() const
void RemoveListener(SCHEMATIC_LISTENER *aListener)
Remove the specified listener.
bool HasVariant(const wxString &aVariantName) const
Return true if a variant with this name exists in the schematic (case-insensitively).
std::set< KIID > m_unitSplitSymbols
Symbols whose copies select different units.
Definition schematic.h:929
std::vector< std::pair< SCH_SHEET_PATH, SCH_SHEET_PATH > > RefSuffixCollisions(bool aIncludeEmpty) const
Find instances of one sheet file whose composed reference suffixes collide.
bool resolveCrossReference(wxString *aToken, int aDepth) const
bool IsComplexHierarchy() const
Test if the schematic is a complex hierarchy.
void OnSchSheetChanged()
Notify the schematic and its listeners that the current sheet has been changed.
wxString GetFileName() const
Helper to retrieve the filename from the root sheet screen.
SCH_SHEET_PATH * m_currentSheet
The sheet path of the sheet currently being edited or displayed.
Definition schematic.h:875
std::vector< SCH_SHEET * > m_topLevelSheets
List of top-level sheets (direct children of virtual root)
Definition schematic.h:866
wxString GetOperatingPoint(const wxString &aNetName, int aPrecision, const wxString &aRange)
void CleanUp(SCH_COMMIT *aCommit, SCH_SCREEN *aScreen=nullptr)
Perform routine schematic cleaning including breaking wire and buses and deleting identical objects s...
void CopyVariant(const wxString &aSourceVariant, const wxString &aNewVariant, SCH_COMMIT *aCommit)
Copy a variant from aSourceVariant to aNewVariant.
bool TopLevelSheetsMatch(const std::vector< TOP_LEVEL_SHEET_INFO > &aSheets) const
Check a project file's top-level sheet list against the sheets this schematic loaded.
bool IsTopLevelSheetUuid(const KIID &aUuid) const
Check if a UUID names one of this schematic's top level sheets.
void OnItemsRemoved(std::vector< SCH_ITEM * > &aRemovedItems)
Must be used if Remove() is used using a BULK_x REMOVE_MODE to generate a change event for listeners.
void AddVariant(const wxString &aVariantName)
void OnSchSelectionChanged()
Notify the schematic and its listeners that the editor selection has changed.
std::string FormatRefSuffixes() const
virtual ~SCHEMATIC()
void AdoptContent(SCHEMATIC_CONTENT &&aContent) noexcept
Take a staged schematic over from an importer in one indivisible step.
bool m_hasRefSuffixFields
Definition schematic.h:911
std::shared_ptr< BUS_ALIAS > GetBusAlias(const wxString &aLabel) const
Return a pointer to a bus alias object for the given label, or null if one doesn't exist.
bool HasRefSuffixes() const
True when suffix numbering is enabled and a hierarchy path has a composed suffix.
Definition schematic.h:267
std::vector< SCH_MARKER * > ResolveERCExclusions()
void SaveToHistory(const wxString &aProjectPath, std::vector< HISTORY_FILE_DATA > &aFileData)
Serialize schematic sheets into HISTORY_FILE_DATA for non-blocking history commit.
const wxString * findRefSuffix(const SCH_SHEET_PATH &aPath) const
The cached suffix of aPath, or nullptr when it has none.
void EmbedFonts() override
Embed fonts in the schematic.
SCHEMATIC_SETTINGS & Settings() const
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_SCREEN * GetCurrentScreen() const
Definition schematic.h:409
wxString ConvertKIIDsToRefs(const wxString &aSource) const
SCH_ITEM * ResolveItem(const KIID &aID, SCH_SHEET_PATH *aPathOut=nullptr, bool aAllowNullptrReturn=false) const
Definition schematic.h:276
void ensureVirtualRoot()
void ensureCurrentSheetIsTopLevel()
void SyncLibSymbolPinMaps(const wxString &aSchLibSymbolName, const LIB_SYMBOL &aSource, SCH_COMMIT *aCommit)
void RecordERCExclusions()
Scan existing markers and record data from any that are Excluded.
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
std::map< std::pair< wxString, wxString >, std::map< int, wxString > > m_packageUnitSuffixes
Sheet suffix of each placed unit of a package spanning suffixes, keyed by base and LIB_ID.
Definition schematic.h:926
wxString m_currentVariant
Definition schematic.h:955
std::map< wxString, std::set< int > > & GetPageRefsMap()
Definition schematic.h:478
SCH_SHEET_LIST BuildUnorderedSheetList() const
std::unordered_map< KIID_PATH, wxString > m_refSuffixes
Composed reference suffix of each hierarchy path that has one.
Definition schematic.h:907
std::map< wxString, std::set< int > > m_labelToPageRefsMap
Holds a map of labels to the page sequence (virtual page number) that they appear on.
Definition schematic.h:889
std::mutex m_packageSuffixesMutex
Definition schematic.h:931
std::set< KIFONT::OUTLINE_FONT * > GetFonts() const override
Get a set of fonts used in the schematic.
SCH_SHEET * GetTopLevelSheet(int aIndex=0) const
bool RemoveTopLevelSheet(SCH_SHEET *aSheet)
Remove a top-level sheet from the schematic.
std::optional< IMPORT_NET_MAP > m_importNetMap
Definition schematic.h:857
bool Contains(const SCH_REFERENCE &aRef) const
Check if the schematic contains the specified reference.
std::optional< wxString > spanningPackageSuffix(const SCH_SYMBOL *aSymbol, const KIID_PATH &aPath) const
The suffix of a package spanning sheets that aSymbol on aPath belongs to, if any.
void ClearUnresolvedERCExclusions(int aErrorCode=-1)
std::vector< ERC_EXCLUSION > m_unresolvedErcExclusions
Exclusions whose saved identity cannot currently be reconstructed as a marker.
Definition schematic.h:934
SCH_CONNECTIVITY::FACADE & Connectivity() const
Definition schematic.h:411
wxString ConvertRefsToKIIDs(const wxString &aSource) const
void SetProject(PROJECT *aPrj)
void DeleteVariant(const wxString &aVariantName, SCH_COMMIT *aCommit)
Delete all information for aVariantName.
bool IsHierarchyModified() const
True when any sheet in the hierarchy has unsaved changes.
wxString GetCurrentVariant() const
Return the current variant being edited.
void AddListener(SCHEMATIC_LISTENER *aListener)
Add a listener to the schematic to receive calls whenever something on the schematic has been modifie...
void CleanUpConnections(SCH_COMMIT *aCommit, SCH_CLEANUP_FLAGS aCleanupFlags, const std::set< SCH_SCREEN * > &aLocalScreens={})
std::map< int, wxString > GetVirtualPageToSheetPagesMap() const
EMBEDDED_FILES * GetEmbeddedFiles() override
wxString GetRefSuffix(const SCH_SHEET_PATH &aPath) const
Return the composed reference suffix of aPath as of the last RefreshHierarchy().
PROJECT * m_project
Definition schematic.h:856
CONNECTION_GRAPH * ConnectionGraph() const
Definition schematic.h:414
SCH_SCREEN * RootScreen() const
Helper to retrieve the screen of the root sheet.
SCHEMATIC(PROJECT *aPrj)
Definition schematic.cpp:82
bool ResolveTextVar(const SCH_SHEET_PATH *aSheetPath, wxString *token, int aDepth) const
std::set< wxString > GetNetClassAssignmentCandidates()
Return the set of netname candidates for netclass assignment.
std::vector< std::shared_ptr< BUS_ALIAS > > m_busAliases
Definition schematic.h:950
bool ReloadProjectVariants()
Take the variant list from the project file again after it was reread.
void RefreshRefSuffixes()
Recompose the reference suffix of every sheet path in the hierarchy.
void InvokeListeners(Func &&aFunc, Args &&... args)
Definition schematic.h:845
bool IsValid() const
A simple test if the schematic is loaded, not a complete one.
Definition schematic.h:384
void updateProjectBusAliases()
void SetVariantDescription(const wxString &aVariantName, const wxString &aDescription)
Set the description for a variant.
void RemoveAllListeners()
Remove all listeners.
std::optional< uint64_t > m_packageSuffixesGeneration
Definition schematic.h:930
void SetTopLevelSheets(const std::vector< SCH_SHEET * > &aSheets)
Replace the top level sheets, rebuilding the hierarchy and connectivity around them.
void RebuildConnectivity(std::function< void(SCH_ITEM *)> *aChangedItemHandler=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr, KIGFX::SCH_VIEW *aSchView=nullptr)
std::unique_ptr< class SCHEMATIC_TEXT_VAR_ADAPTER > m_textVarAdapter
Reactive text-variable dependency adapter.
Definition schematic.h:965
void RenameVariant(const wxString &aOldName, const wxString &aNewName, SCH_COMMIT *aCommit)
Rename a variant from aOldName to aNewName.
bool HasProjectBusAliases() const
PROPERTY_LISTENER_SUBSCRIPTION m_fieldListenerSubscription
PROPERTY_MANAGER listener subscription installed in the ctor.
Definition schematic.h:970
BUS_ALIAS_RELOAD ReloadProjectBusAliases()
Take the bus aliases from the project file again after it was reread.
void GetContextualTextVars(wxArrayString *aVars) const
void ensureDefaultTopLevelSheet()
SCH_SHEET & Root() const
Definition schematic.h:282
std::set< KIID > SplitUnitSymbols() const
Symbols whose copies select different units, for loops that change references as they go.
std::map< int, wxString > GetVirtualPageToSheetNamesMap() const
void RecalculateConnections(SCH_COMMIT *aCommit, SCH_CLEANUP_FLAGS aCleanupFlags, TOOL_MANAGER *aToolManager, PROGRESS_REPORTER *aProgressReporter=nullptr, KIGFX::SCH_VIEW *aSchView=nullptr, std::function< void(SCH_ITEM *)> *aChangedItemHandler=nullptr, PICKED_ITEMS_LIST *aLastChangeList=nullptr, bool aCleanupDone=false)
Generate the connection data for the entire schematic hierarchy.
void AddBusAlias(std::shared_ptr< BUS_ALIAS > aAlias)
std::vector< SCH_SHEET * > GetTopLevelSheets() const
Get the list of top-level sheets.
wxArrayString GetVariantNamesForUI() const
Return an array of variant names for using in wxWidgets UI controls.
bool CopiesSelectDifferentUnits(const SCH_SYMBOL *aSymbol) const
void RunOnNestedEmbeddedFiles(const std::function< void(EMBEDDED_FILES *)> &aFunction) override
Provide access to nested embedded files, such as symbols in schematics and footprints in boards.
std::unique_ptr< SCH_CONNECTIVITY::FACADE > m_connectivity
Definition schematic.h:879
SCHEMATIC_HOLDER * m_schematicHolder
What currently "Holds" the schematic, i.e.
Definition schematic.h:944
wxString GetUniqueFilenameForCurrentSheet()
Get the unique file name for the current sheet.
void SetSheetNumberAndCount()
Set the m_ScreenNumber and m_NumberOfScreens members for screens.
void SetBusAliases(const std::vector< std::shared_ptr< BUS_ALIAS > > &aAliases)
std::vector< SCHEMATIC_LISTENER * > m_listeners
Currently installed listeners.
Definition schematic.h:939
void AppendRefSuffix(wxString &aRef, const SCH_SHEET_PATH &aPath) const
Append the composed reference suffix of aPath to aRef without copying it.
SCH_SHEET_PATH & CurrentSheet() const
Definition schematic.h:399
bool m_busAliasesFromTable
The aliases in use came from a project table rather than from the sheets.
Definition schematic.h:953
std::vector< TOP_LEVEL_SHEET_INFO > TopLevelSheetInfos() const
The top-level sheets as the project file records them, with file names relative to the project.
bool ResolveCrossReference(wxString *token, int aDepth) const
Resolves text vars that refer to other items.
int FixupJunctionsAfterImport(const std::function< void(SCH_LINE *, SCH_LINE *)> &aOnSplit={})
Add junctions to this schematic where required.
KIID_PATH NormalizeInstancePath(const KIID_PATH &aPath) const
Strip the leading virtual root from a stored instance path, which SCH_SHEET_PATH::Path() omits but st...
std::map< wxString, double > m_operatingPoints
Simulation operating points for text variable substitution.
Definition schematic.h:899
ERC_SETTINGS & ErcSettings() const
std::set< wxString > m_variantNames
Definition schematic.h:957
std::map< std::pair< KIID, KIID_PATH >, wxString > PackageRefSuffixes() const
Symbol and sheet path of each instance whose package suffix is another sheet's, with that suffix.
void RefreshHierarchy()
void OnItemsChanged(std::vector< SCH_ITEM * > &aItems)
Notify the schematic and its listeners that an item on the schematic has been modified in some way.
static wxFileName TopLevelSheetFile(const TOP_LEVEL_SHEET_INFO &aSheet, const wxString &aProjectPath, bool aLegacy)
The file loaded for a listed top-level sheet. A legacy project reads it under the legacy extension.
SCH_SHEET * m_rootSheet
The virtual root sheet (has no screen, contains all top-level sheets)
Definition schematic.h:863
bool IsInstancePathInProject(const KIID_PATH &aPath) const
Test whether an instance path is rooted in this schematic's top level sheets.
Commit for the schematic and symbol editors.
Definition sch_commit.h:54
void RemovedForCleanup(SCH_ITEM *aItem, SCH_SCREEN *aScreen)
Retain the pre-edit state of an item already removed from its screen by cleanup.
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
Each graphical item can have a SCH_CONNECTION describing its logical connection (to a bus or net).
wxString Name(bool aIgnoreSheet=false) const
bool IsBus() const
SCH_ITEM * Driver() const
FIELD_T GetId() const
Definition sch_field.h:143
A SCH_IO derivation for loading schematic files using the new s-expression file format.
void FormatSchematicToFormatter(OUTPUTFORMATTER *aOut, SCH_SHEET *aSheet, SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties=nullptr)
Serialize a schematic sheet to an OUTPUTFORMATTER without file I/O or Prettify.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
virtual bool IsConnectable() const
Definition sch_item.h:550
int GetUnit() const
Definition sch_item.h:243
SCH_LAYER_ID GetLayer() const
Return the layer this item is on.
Definition sch_item.h:353
VECTOR2I GetPosition() const override
wxString GetShownText(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, int aDepth=0) const override
Segment description base class to describe items which have 2 end points (track, wire,...
Definition sch_line.h:39
SCH_LINE * NonGroupAware_BreakAt(const VECTOR2I &aPoint)
This version should only be used when importing files.
Definition sch_line.cpp:685
bool IsParallel(const SCH_LINE *aLine) const
Definition sch_line.cpp:537
VECTOR2I GetEndPoint() const
Definition sch_line.h:145
VECTOR2I GetStartPoint() const
Definition sch_line.h:136
SCH_LINE * MergeOverlap(SCH_SCREEN *aScreen, SCH_LINE *aLine, bool aCheckJunctions)
Check line against aLine to see if it overlaps and merge if it does.
Definition sch_line.cpp:550
bool IsNull() const
Definition sch_line.h:134
bool IsStrokeEquivalent(const SCH_LINE *aLine)
Definition sch_line.h:228
bool IsEndPoint(const VECTOR2I &aPoint) const override
Test if aPt is an end point of this schematic object.
Definition sch_line.h:88
static SCH_MARKER * FromProto(const kiapi::schematic::ErcMarker &aMsg, const SCH_SHEET_LIST &aSheetList)
VECTOR2I GetPosition() const override
Definition sch_marker.h:106
VECTOR2I GetPosition() const override
Container to create a flattened list of symbols because in a complex hierarchy, a symbol can be used ...
A helper to define a symbol's reference designator in a schematic.
const std::unordered_set< SCH_ITEM * > & GetContainedItems() const
Return a set of all items contained within the rule area.
static std::vector< std::pair< SCH_RULE_AREA *, SCH_SCREEN * > > UpdateRuleAreasInScreens(std::unordered_set< SCH_SCREEN * > &screens, KIGFX::SCH_VIEW *view)
Update all rule area connectvity / caches in the given sheet paths.
const std::unordered_set< KIID > & GetPastContainedItems() const
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
SCH_SCREEN * GetNext()
void CopyVariant(const wxString &aSourceVariant, const wxString &aNewVariant, SCH_COMMIT *aCommit=nullptr)
SCH_SCREEN * GetFirst()
void RenameVariant(const wxString &aOldName, const wxString &aNewName, SCH_COMMIT *aCommit=nullptr)
std::set< wxString > GetVariantNames() const
void DeleteVariant(const wxString &aVariantName, SCH_COMMIT *aCommit=nullptr)
void SetLegacySymbolInstanceData()
Update the symbol value and footprint instance data for legacy designs.
void Append(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
std::vector< SCH_SHEET_PATH > & GetClientSheetPaths()
Return the number of times this screen is used.
Definition sch_screen.h:226
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
const wxString & GetFileName() const
Definition sch_screen.h:157
void DecRefCount()
bool IsExplicitJunctionAllowed(const VECTOR2I &aPosition) const
Indicate that a junction dot may be placed at the given location.
void BumpConnectivityRevision(KICAD_T aChangedType=TYPE_NOT_INIT)
Increment the connectivity revisions of this screen.
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
bool Remove(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Remove aItem from the schematic associated with this screen.
TITLE_BLOCK & GetTitleBlock()
Definition sch_screen.h:168
void Update(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Refresh a changed item in the tree and invalidate connectivity.
int GetRefCount() const
Definition sch_screen.h:175
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
std::optional< SCH_SHEET_PATH > GetSheetPathByKIIDPath(const KIID_PATH &aPath, bool aIncludeLastSheet=true) const
Finds a SCH_SHEET_PATH that matches the provided KIID_PATH.
SCH_ITEM * ResolveItem(const KIID &aID, SCH_SHEET_PATH *aPathOut=nullptr, bool aAllowNullptrReturn=false) const
Fetch a SCH_ITEM by ID.
void SortByPageNumbers(bool aUpdateVirtualPageNums=true)
Sort the list of sheets by page number.
void BuildSheetList(SCH_SHEET *aSheet, bool aCheckIntegrity)
Build the list of sheets and their sheet path from aSheet.
bool HasPath(const KIID_PATH &aPath) const
void GetSymbols(SCH_REFERENCE_LIST &aReferences, SYMBOL_FILTER aSymbolFilter, bool aForceIncludeOrphanSymbols=false) const
Add a SCH_REFERENCE object to aReferences for each symbol in the list of sheets.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
size_t GetCurrentHash() const
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
SCH_SCREEN * LastScreen()
wxString GetPageNumber() const
SCH_SHEET * at(size_t aIndex) const
Forwarded method from std::vector.
void SetVirtualPageNumber(int aPageNumber)
Set the sheet instance virtual page number.
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.
void SetPageNumber(const wxString &aPageNumber)
Set the sheet instance user definable page number.
SCH_SHEET * Last() const
Return a pointer to the last SCH_SHEET of the list.
const KIID_PATH & PathRef() const
Borrow the cached path until this sheet path is modified or destroyed.
void push_back(SCH_SHEET *aSheet)
Forwarded method from std::vector.
size_t size() const
Forwarded method from std::vector.
Define a sheet pin (label) used in sheets to create hierarchical schematics.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
void SyncUuidToScreen()
Take the identity of the screen this sheet owns.
wxString GetName() const
Definition sch_sheet.h:150
SCH_SCREEN * m_screen
Definition sch_sheet.h:746
int CountSheets() const
Count the number of sheets found in "this" sheet including all of the subsheets.
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
std::vector< SCH_SHEET_PIN * > & GetPins()
Definition sch_sheet.h:285
bool ResolveTextVar(const SCH_SHEET_PATH *aPath, wxString *token, int aDepth=0) const
Resolve any references to system tokens supported by the sheet.
Schematic symbol object.
Definition sch_symbol.h:76
const std::vector< SCH_SYMBOL_INSTANCE > & GetInstances() const
Definition sch_symbol.h:136
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.
wxString GetSchSymbolLibraryName() const
wxString GetBaseRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const
void SetRef(const SCH_SHEET_PATH *aSheet, const wxString &aReference)
Set the base reference for the given sheet path for this symbol.
bool ResolveTextVar(const SCH_SHEET_PATH *aPath, wxString *token, int aDepth=0) const
Resolve any references to system tokens supported by the symbol.
const LIB_ID & GetLibId() const override
Definition sch_symbol.h:166
void SetUserRef(const SCH_SHEET_PATH &aSheet, const wxString &aBase)
Set a base reference chosen by the user on aSheet.
std::vector< SCH_PIN * > GetGraphicalPins(int aUnit, int aBodyStyle) const override
bool GetInstance(SCH_SYMBOL_INSTANCE &aInstance, const KIID_PATH &aSheetPath, bool aTestFromEnd=false) const
static uint64_t RefGeneration()
Count of changes to any symbol's references, units, library links or placement.
static void BumpRefGeneration()
Mark every cache built from references as stale.
int GetUnitCount() const override
Return the number of units per package of the symbol.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
int RemoveItemFromSel(const TOOL_EVENT &aEvent)
bool CollideEdge(const VECTOR2I &aPoint, VERTEX_INDEX *aClosestVertex=nullptr, int aClearance=0) const
Check whether aPoint collides with any edge of any of the contours of the polygon.
Helper class to handle Spice way of expressing values (e.g. 10.5 Meg)
Definition spice_value.h:51
wxString ToString() const
Return string value as when converting double to string (e.g.
Implement an OUTPUTFORMATTER to a memory buffer.
Definition richio.h:430
std::string & MutableString()
Definition richio.h:458
A text evaluation frame with one frozen clock and memoized external queries.
static ENVIRONMENT * Current()
void RecordCrossReference(const CROSS_REFERENCE_KEY &aKey, const CROSS_REFERENCE_VALUE &aValue)
std::pair< wxString, int > CROSS_REFERENCE_KEY
bool TextVarResolver(wxString *aToken, const PROJECT *aProject, RESOLUTION_CONTEXT aContext) const
static void GetContextualTextVars(wxArrayString *aVars)
Master controller class:
@ FOR_GUI
Definition common.h:93
@ INTERNAL
Definition common.h:96
static bool empty(const wxTextEntryBase *aCtrl)
#define _(s)
#define SELECTED_BY_DRAG
Item was algorithmically selected as a dragged item.
#define STRUCT_DELETED
flag indication structures to be erased
@ ERCE_VARIANT_SYMBOL_INCOMPATIBLE
Variant symbol override fails pin compatibility.
@ ERCE_ENDPOINT_OFF_GRID
Pin or wire-end off grid.
@ ERCE_BUS_TO_BUS_CONFLICT
A connection between bus objects doesn't share at least one net.
@ ERCE_FOOTPRINT_LINK_ISSUES
The footprint link is invalid, or points to a missing (or inactive) footprint or library.
@ ERCE_BUS_TO_NET_CONFLICT
A bus wire is graphically connected to a net port/pin (or vice versa).
@ ERCE_NOCONNECT_NOT_CONNECTED
A no connect symbol is not connected to anything.
@ ERCE_FOUR_WAY_JUNCTION
A four-way junction was found.
@ ERCE_PIN_NOT_CONNECTED
Pin not connected and not no connect symbol.
@ ERCE_UNDEFINED_NETCLASS
A netclass was referenced but not defined.
@ ERCE_UNRESOLVED_VARIABLE
A text variable could not be resolved.
@ ERCE_SIMULATION_MODEL
An error was found in the simulation model.
@ ERCE_LIB_SYMBOL_MISMATCH
Symbol doesn't match copy in library.
@ ERCE_GENERIC_ERROR
@ ERCE_DIFFERENT_UNIT_FP
Different units of the same symbol have different footprints assigned.
@ ERCE_NOCONNECT_CONNECTED
A no connect symbol is connected to more than 1 pin.
@ ERCE_DUPLICATE_SHEET_NAME
Duplicate sheet names within a given sheet.
@ ERCE_LIB_SYMBOL_ISSUES
Symbol not found in active libraries.
@ ERCE_FOOTPRINT_FILTERS
The assigned footprint doesn't match the footprint filters.
@ ERCE_HIERACHICAL_LABEL
Mismatch between hierarchical labels and pins sheets.
@ ERCE_WIRE_DANGLING
Some wires are not connected to anything else.
@ ERCE_GENERIC_WARNING
@ ERCE_VARIANT_SYMBOL_INVALID
Variant symbol override LIB_ID cannot be resolved.
@ ERCE_PIN_MAP_UNMAPPED_PIN
A connected pin resolves to no footprint pad.
@ ERCE_LABEL_MULTIPLE_WIRES
A label is connected to more than one wire.
bool m_ConnectivityEngine
Use the schematic connectivity engine instead of CONNECTION_GRAPH.
static const std::string LegacySchematicFileExtension
const wxChar *const traceAutoSave
Flag to enable auto save feature debug tracing.
const wxChar *const traceSchSheetPaths
Flag to enable debug output of schematic symbol sheet path manipulation code.
std::string source
void ignore_unused(const T &)
Definition ignore.h:20
KIID niluuid(0)
@ LAYER_WIRE
Definition layer_ids.h:483
@ LAYER_BUS
Definition layer_ids.h:484
#define MAIL_SCH_REF_SUFFIXES_TAG
First line of a MAIL_SCH_GET_REF_SUFFIXES reply, so a schematic with no sheets still answers.
Definition mail_type.h:85
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
void for_all_pairs(_InputIterator __first, _InputIterator __last, _Function __f)
Apply a function to every possible pair of elements of a sequence.
Definition kicad_algo.h:80
#define _HKI(x)
Definition page_info.cpp:40
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
static LIB_SYMBOL * findSymbol(const wxString &aName, LEGACY_SYMBOL_LIBS *aLibs, bool aCached)
Search the libraries for the first symbol with a given name.
#define TYPE_HASH(x)
Macro to generate unique identifier for a type.
Definition property.h:74
void CollectOtherUnits(const wxString &aRef, int aUnit, const LIB_ID &aLibId, SCH_SHEET_PATH &aSheet, std::vector< SCH_SYMBOL * > *otherUnits)
#define SKIP_CONNECTIVITY
Definition sch_commit.h:41
#define DELETE_REMOVED_ITEMS
Definition sch_commit.h:43
@ AUTOPLACE_AUTO
Definition sch_item.h:75
@ SYMBOL_FILTER_NON_POWER
SCH_CLEANUP_FLAGS
Definition schematic.h:98
@ LOCAL_CLEANUP
Definition schematic.h:100
@ GLOBAL_CLEANUP
Definition schematic.h:101
wxString GetDefaultVariantName()
int SortVariantNames(const wxString &aLhs, const wxString &aRhs)
Data produced by a registered saver on the UI thread, consumed by either the background local-history...
std::string content
Serialized content (mutually exclusive with sourcePath)
KICAD_FORMAT::FORMAT_MODE formatMode
wxString relativePath
Destination path relative to the project root.
A schematic staged off to the side by an importer, ready to be swapped into a live SCHEMATIC in one s...
Definition schematic.h:115
Pins of type no-connect that touch other items at one position.
A wire end, a bus entry end or a symbol pin that is not on the connection grid.
A simple container for schematic symbol instance information.
Information about a top-level schematic sheet.
wxString filename
Relative path to the sheet file.
#define ALL_UNITS
Definition symbol.h:150
#define ALL_BODY_STYLES
Definition symbol.h:151
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ SHEET_REF_SUFFIX
Optional sheet field appended to the references of the sheet's symbols.
@ DATASHEET
name of datasheet
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
std::vector< DATABASE_CONNECTION::ROW > rows
std::string path
KIBIS_PIN * pin
VECTOR2I location
wxLogTrace helper definitions.
@ SCH_LINE_T
Definition typeinfo.h:159
@ SCH_NO_CONNECT_T
Definition typeinfo.h:156
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_DIRECTIVE_LABEL_T
Definition typeinfo.h:167
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_MARKER_T
Definition typeinfo.h:154
@ SCH_RULE_AREA_T
Definition typeinfo.h:166
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCHEMATIC_T
Definition typeinfo.h:200
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_JUNCTION_T
Definition typeinfo.h:155
@ SCH_PIN_T
Definition typeinfo.h:149
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.