KiCad PCB EDA Suite
Loading...
Searching...
No Matches
backannotate.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2019 Alexander Shuklin <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21
22#include <backannotate.h>
23#include <boost/property_tree/ptree.hpp>
24#include <confirm.h>
25#include <common.h>
26#include <dsnlexer.h>
27#include <ptree.h>
28#include <reporter.h>
29#include <sch_edit_frame.h>
30#include <sch_sheet_path.h>
31#include <sch_label.h>
32#include <lib_symbol.h>
33#include <schematic.h>
34#include <advanced_config.h>
36#include <sch_commit.h>
37#include <string_utils.h>
38#include <kiface_base.h>
40#include <connection_graph.h>
41#include <limits>
42#include <set>
43#include <tool/tool_manager.h>
45#include <tools/sch_selection.h>
47#include <wx/log.h>
48#include <fmt.h>
49#include <fmt/ranges.h>
50#include <fmt/xchar.h>
51
52// Compare nets in the deterministic library order so diode arrays and similar map cleanly.
53static std::vector<wxString> netsInUnitOrder( const std::vector<wxString>& aPins,
54 const std::map<wxString, wxString>& aNetByPin )
55{
56 std::vector<wxString> nets;
57
58 if( !aPins.empty() )
59 {
60 for( const wxString& pinNum : aPins )
61 {
62 auto it = aNetByPin.find( pinNum );
63 nets.push_back( it != aNetByPin.end() ? it->second : wxString() );
64 }
65 }
66 else
67 {
68 for( const std::pair<const wxString, wxString>& kv : aNetByPin )
69 nets.push_back( kv.second );
70 }
71
72 return nets;
73}
74
75
76// The board reports pad numbers, the unit planner compares logical pin numbers.
77bool CollectBackannotatePcbNets( const SCH_SYMBOL& aSymbol, const SCH_SHEET_PATH& aSheetPath,
78 const wxString& aVariantName, const std::map<wxString, wxString>& aPcbNetsByPad,
79 std::map<wxString, wxString>& aPcbNetsByLogicalPin )
80{
81 for( const SCH_PIN* pin : aSymbol.GetPins( &aSheetPath ) )
82 {
83 // Pins on symbols can have more than one pin stacked
84 bool logicalPinsValid = false;
85 const std::vector<wxString> logicalPins = pin->GetStackedPinNumbers( &logicalPinsValid );
86
87 if( !logicalPinsValid || logicalPins.empty() )
88 return false;
89
90 // Map those multiple stacked pins to whatever we have them mapped to on the PCB side
91 bool padsValid = false;
92 const std::vector<wxString> pads =
93 ExpandStackedPinNotation( pin->GetEffectivePadNumber( aSheetPath, aVariantName ), &padsValid );
94
95 if( !padsValid || pads.empty() )
96 return false;
97
98 // Get all our nets now that we have all our pads
99 std::set<wxString> pcbNets;
100
101 for( const wxString& pad : pads )
102 {
103 auto it = aPcbNetsByPad.find( pad );
104 pcbNets.insert( it != aPcbNetsByPad.end() ? it->second : wxString() );
105 }
106
107 // A stacked pin represents one schematic net. More than one pad net corresponding
108 // to a single stacked pin cannot be resolved by a unit swap
109 if( pcbNets.size() != 1 )
110 return false;
111
112 const wxString& pcbNet = *pcbNets.begin();
113
114 for( const wxString& pinNum : logicalPins )
115 {
116 auto [it, inserted] = aPcbNetsByLogicalPin.emplace( pinNum, pcbNet );
117
118 // We might already have some mappings from previous calls to this function,
119 // same mappings are fine, but new different mappings are not
120 if( !inserted && it->second != pcbNet )
121 return false;
122 }
123 }
124
125 return true;
126}
127
128
130 const std::vector<BACKANNOTATE_UNIT_SWAP_CANDIDATE>& aCandidates,
131 const std::map<wxString, wxString>& aPcbPinMap )
132{
134
135 if( aCandidates.size() < 2 )
136 {
137 plan.m_mappingOk = true;
138 return plan;
139 }
140
141 std::map<size_t, size_t> desiredTarget;
142 std::set<size_t> usedTargets;
143
144 for( size_t candidateIdx = 0; candidateIdx < aCandidates.size(); ++candidateIdx )
145 {
146 const BACKANNOTATE_UNIT_SWAP_CANDIDATE& candidate = aCandidates[candidateIdx];
147 std::map<wxString, wxString> pcbNetsByPin;
148
149 for( const wxString& pinNum : candidate.m_unitPinNumbers )
150 {
151 auto it = aPcbPinMap.find( pinNum );
152 pcbNetsByPin[pinNum] = ( it != aPcbPinMap.end() ) ? it->second : wxString();
153 }
154
155 std::vector<wxString> pcbNets = netsInUnitOrder( candidate.m_unitPinNumbers, pcbNetsByPin );
156 bool matched = false;
157
158 for( size_t matchIdx = 0; matchIdx < aCandidates.size(); ++matchIdx )
159 {
160 if( usedTargets.count( matchIdx ) )
161 continue;
162
163 const BACKANNOTATE_UNIT_SWAP_CANDIDATE& potentialMatch = aCandidates[matchIdx];
164 std::vector<wxString> schNets =
165 netsInUnitOrder( potentialMatch.m_unitPinNumbers, potentialMatch.m_schNetsByPin );
166
167 if( pcbNets == schNets )
168 {
169 desiredTarget[candidateIdx] = matchIdx;
170 usedTargets.insert( matchIdx );
171 matched = true;
172 break;
173 }
174 }
175
176 if( !matched )
177 return plan;
178 }
179
180 plan.m_mappingOk = true;
181 plan.m_identity = true;
182
183 for( size_t candidateIdx = 0; candidateIdx < aCandidates.size(); ++candidateIdx )
184 {
185 auto it = desiredTarget.find( candidateIdx );
186
187 if( it == desiredTarget.end() || it->second != candidateIdx )
188 {
189 plan.m_identity = false;
190 break;
191 }
192 }
193
194 if( plan.m_identity )
195 return plan;
196
197 std::set<size_t> visited;
198
199 for( size_t startIdx = 0; startIdx < aCandidates.size(); ++startIdx )
200 {
201 if( visited.count( startIdx ) )
202 continue;
203
204 std::vector<size_t> cycle;
205 size_t curIdx = startIdx;
206
207 while( !visited.count( curIdx ) )
208 {
209 visited.insert( curIdx );
210 cycle.push_back( curIdx );
211
212 auto nextIt = desiredTarget.find( curIdx );
213
214 if( nextIt == desiredTarget.end() || nextIt->second == curIdx )
215 break;
216
217 curIdx = nextIt->second;
218 }
219
220 if( cycle.size() < 2 )
221 continue;
222
223 for( size_t i = cycle.size() - 1; i > 0; --i )
224 {
225 size_t firstIdx = cycle[i - 1];
226 size_t secondIdx = cycle[i];
227
228 plan.m_steps.push_back( { firstIdx, secondIdx,
229 aCandidates[firstIdx].m_currentUnit,
230 aCandidates[secondIdx].m_currentUnit } );
231 plan.m_swappedCandidateIndices.insert( firstIdx );
232 plan.m_swappedCandidateIndices.insert( secondIdx );
233 }
234 }
235
236 return plan;
237}
238
239
240BACK_ANNOTATE::BACK_ANNOTATE( SCH_EDIT_FRAME* aFrame, REPORTER& aReporter, bool aRelinkFootprints,
241 bool aProcessFootprints, bool aProcessValues, bool aProcessReferences,
242 bool aProcessNetNames, bool aProcessAttributes, bool aProcessOtherFields,
243 bool aPreferUnitSwaps, bool aPreferPinSwaps, bool aDryRun ) :
244 m_reporter( aReporter ),
245 m_matchByReference( aRelinkFootprints ),
246 m_processFootprints( aProcessFootprints ),
247 m_processValues( aProcessValues ),
248 m_processReferences( aProcessReferences ),
249 m_processNetNames( aProcessNetNames ),
250 m_processAttributes( aProcessAttributes ),
251 m_processOtherFields( aProcessOtherFields ),
252 m_preferUnitSwaps( aPreferUnitSwaps ),
253 m_preferPinSwaps( aPreferPinSwaps ),
254 m_dryRun( aDryRun ),
255 m_frame( aFrame ),
256 m_changesCount( 0 )
257{ }
258
259
260bool BACK_ANNOTATE::BackAnnotateSymbols( const std::string& aNetlist )
261{
262 m_changesCount = 0;
263
266 {
267 m_reporter.ReportTail( _( "Select at least one property to back annotate." ), RPT_SEVERITY_ERROR );
268 return false;
269 }
270
271 getPcbModulesFromString( aNetlist );
272
273 SCH_SHEET_LIST sheets = m_frame->Schematic().Hierarchy();
276
279
281 return true;
282}
283
284
285bool BACK_ANNOTATE::FetchNetlistFromPCB( std::string& aNetlist )
286{
287 if( Kiface().IsSingle() )
288 {
289 DisplayErrorMessage( m_frame, _( "Cannot fetch PCB netlist because Schematic Editor is opened in "
290 "stand-alone mode.\n"
291 "You must launch the KiCad project manager and create a project." ) );
292 return false;
293 }
294
295 KIWAY_PLAYER* frame = m_frame->Kiway().Player( FRAME_PCB_EDITOR, false );
296
297 if( !frame )
298 {
299 wxFileName fn( m_frame->Prj().GetProjectFullName() );
300 fn.SetExt( FILEEXT::PcbFileExtension );
301
302 frame = m_frame->Kiway().Player( FRAME_PCB_EDITOR, true );
303 frame->OpenProjectFiles( std::vector<wxString>( 1, fn.GetFullPath() ) );
304 }
305
306 m_frame->Kiway().ExpressMail( FRAME_PCB_EDITOR, MAIL_PCB_GET_NETLIST, aNetlist );
307 return true;
308}
309
310
312{
313 std::string nullPayload;
314
315 m_frame->Kiway().ExpressMail( FRAME_PCB_EDITOR, MAIL_PCB_UPDATE_LINKS, nullPayload );
316}
317
318
319void BACK_ANNOTATE::getPcbModulesFromString( const std::string& aPayload )
320{
321 auto getStr = []( const PTREE& pt ) -> wxString
322 {
323 return UTF8( pt.front().first );
324 };
325
326 DSNLEXER lexer( aPayload, From_UTF8( __func__ ) );
327 PTREE doc;
328
329 // NOTE: KiCad's PTREE scanner constructs a property *name* tree, not a property tree.
330 // Every token in the s-expr is stored as a property name; the property's value is then
331 // either the nested s-exprs or an empty PTREE; there are *no* literal property values.
332
333 Scan( &doc, &lexer );
334
335 PTREE& tree = doc.get_child( "pcb_netlist" );
336 wxString msg;
337 m_pcbFootprints.clear();
338
339 for( const std::pair<const std::string, PTREE>& item : tree )
340 {
341 wxString path, value, footprint;
342 bool dnp = false, exBOM = false, exSim = false, exPosFiles = false;
343 std::map<wxString, wxString> pinNetMap, fieldsMap;
344 wxASSERT( item.first == "ref" );
345 wxString ref = getStr( item.second );
346
347 try
348 {
350 path = ref;
351 else
352 path = getStr( item.second.get_child( "timestamp" ) );
353
354 if( path == "" )
355 {
356 msg.Printf( _( "Footprint '%s' has no assigned symbol." ), DescribeRef( ref ) );
357 m_reporter.ReportHead( msg, RPT_SEVERITY_WARNING );
358 continue;
359 }
360
361 footprint = getStr( item.second.get_child( "fpid" ) );
362 value = getStr( item.second.get_child( "value" ) );
363
364 // Get child PTREE of fields
365 boost::optional<const PTREE&> fields = item.second.get_child_optional( "fields" );
366
367 // Parse each field out of the fields string
368 if( fields )
369 {
370 for( const std::pair<const std::string, PTREE>& field : fields.get() )
371 {
372 if( field.first != "field" )
373 continue;
374
375 // Fields are of the format "(field (name "name") "12345")
376 const auto& fieldName = field.second.get_child_optional( "name" );
377 const std::string& fieldValue = field.second.back().first;
378
379 if( !fieldName )
380 continue;
381
382 fieldsMap[getStr( fieldName.get() )] = wxString::FromUTF8( fieldValue );
383 }
384 }
385
386
387 // Get DNP and exclusion attributes out of the properties if they exist
388 for( const auto& child : item.second )
389 {
390 if( child.first != "property" )
391 continue;
392
393 auto property = child.second;
394 auto name = property.get_child_optional( "name" );
395
396 if( !name )
397 continue;
398
399 if( name.get().front().first == "dnp" )
400 dnp = true;
401 else if( name.get().front().first == "exclude_from_bom" )
402 exBOM = true;
403 else if( name.get().front().first == "exclude_from_sim" )
404 exSim = true;
405 else if( name.get().front().first == "exclude_from_pos_files" )
406 exPosFiles = true;
407 }
408
409 boost::optional<const PTREE&> nets = item.second.get_child_optional( "nets" );
410
411 if( nets )
412 {
413 for( const std::pair<const std::string, PTREE>& pin_net : nets.get() )
414 {
415 wxASSERT( pin_net.first == "pin_net" );
416 wxString pinNumber = UTF8( pin_net.second.front().first );
417 wxString netName = UTF8( pin_net.second.back().first );
418 pinNetMap[ pinNumber ] = netName;
419 }
420 }
421 }
422 catch( ... )
423 {
424 wxLogWarning( "Cannot parse PCB netlist for back-annotation." );
425 }
426
427 // Use lower_bound for not to iterate over map twice
428 auto nearestItem = m_pcbFootprints.lower_bound( path );
429
430 if( nearestItem != m_pcbFootprints.end() && nearestItem->first == path )
431 {
432 // Module with this path already exists - generate error
433 msg.Printf( _( "Footprints '%s' and '%s' linked to same symbol." ),
434 DescribeRef( nearestItem->second->m_ref ),
435 DescribeRef( ref ) );
436 m_reporter.ReportHead( msg, RPT_SEVERITY_ERROR );
437 }
438 else
439 {
440 // Add footprint to the map
441 std::shared_ptr<PCB_FP_DATA> data = std::make_shared<PCB_FP_DATA>(
442 ref, footprint, value, dnp, exBOM, exSim, exPosFiles, pinNetMap, fieldsMap );
443 m_pcbFootprints.insert( nearestItem, std::make_pair( path, data ) );
444 }
445 }
446}
447
448
450{
451 for( const auto& [pcbPath, pcbData] : m_pcbFootprints )
452 {
453 int refIndex;
454 bool foundInMultiunit = false;
455
456 for( const auto& [_, refList] : m_multiUnitsRefs )
457 {
459 refIndex = refList.FindRef( pcbPath );
460 else
461 refIndex = refList.FindRefByFullPath( pcbPath );
462
463 if( refIndex >= 0 )
464 {
465 // If footprint linked to multi unit symbol, we add all symbol's units to
466 // the change list
467 foundInMultiunit = true;
468
469 for( size_t i = 0; i < refList.GetCount(); ++i )
470 {
471 refList[ i ].GetSymbol()->ClearFlags(SKIP_STRUCT );
472 m_changelist.emplace_back( CHANGELIST_ITEM( refList[i], pcbData ) );
473 }
474
475 break;
476 }
477 }
478
479 if( foundInMultiunit )
480 continue;
481
483 refIndex = m_refs.FindRef( pcbPath );
484 else
485 refIndex = m_refs.FindRefByFullPath( pcbPath );
486
487 if( refIndex >= 0 )
488 {
489 m_refs[ refIndex ].GetSymbol()->ClearFlags( SKIP_STRUCT );
490 m_changelist.emplace_back( CHANGELIST_ITEM( m_refs[refIndex], pcbData ) );
491 }
492 else
493 {
494 // Haven't found linked symbol in multiunits or common refs. Generate error
495 m_reporter.ReportTail( wxString::Format( _( "Cannot find symbol for footprint '%s'." ),
496 DescribeRef( pcbData->m_ref ) ),
498 }
499 }
500}
501
503{
504 m_refs.SortByTimeStamp();
505
506 std::sort( m_changelist.begin(), m_changelist.end(),
507 []( const CHANGELIST_ITEM& a, const CHANGELIST_ITEM& b )
508 {
509 return SCH_REFERENCE_LIST::sortByTimeStamp( a.first, b.first );
510 } );
511
512 size_t i = 0;
513
514 for( const std::pair<SCH_REFERENCE, std::shared_ptr<PCB_FP_DATA>>& item : m_changelist )
515 {
516 // Refs and changelist are both sorted by paths, so we just go over m_refs and
517 // generate errors before we will find m_refs member to which item linked
518 while( i < m_refs.GetCount() && m_refs[i].GetPath() != item.first.GetPath() )
519 {
520 const SCH_REFERENCE& ref = m_refs[i];
521
522 if( ref.GetSymbol()->GetExcludedFromBoard() )
523 {
524 m_reporter.ReportTail( wxString::Format( _( "Footprint '%s' is not present on PCB. "
525 "Corresponding symbols in schematic must be "
526 "manually deleted (if desired)." ),
527 DescribeRef( m_refs[i].GetRef() ) ),
529 }
530
531 ++i;
532 }
533
534 ++i;
535 }
536
537 if( m_matchByReference && !m_frame->ReadyToNetlist( _( "Re-linking footprints requires a fully "
538 "annotated schematic." ) ) )
539 {
540 m_reporter.ReportTail( _( "Footprint re-linking canceled by user." ), RPT_SEVERITY_ERROR );
541 }
542}
543
544
545std::vector<BACKANNOTATE_REF>
546ResolveBackannotatedRefs( const std::vector<std::pair<const SCH_REFERENCE*, wxString>>& aRequests,
547 bool aShareBases )
548{
549 std::vector<BACKANNOTATE_REF> result( aRequests.size() );
550 std::map<const SCH_SYMBOL*, wxString> firstBase;
551 std::set<const SCH_SYMBOL*> refusedSymbols;
552 std::set<wxString> refusedBoardRefs;
553
554 auto shares =
555 [&]( const SCH_SYMBOL* aSymbol )
556 {
557 return aShareBases
558 && !( aSymbol->Schematic() && aSymbol->Schematic()->CopiesSelectDifferentUnits( aSymbol ) );
559 };
560
561 for( size_t ii = 0; ii < aRequests.size(); ++ii )
562 {
563 const SCH_REFERENCE& ref = *aRequests[ii].first;
564 const wxString& boardRef = aRequests[ii].second;
565 const SCH_SYMBOL* symbol = ref.GetSymbol();
566 const SCHEMATIC* schematic = symbol->Schematic();
567
568 // A footprint whose units span sheets carries the package's suffix, not each unit's own
569 const wxString suffix = schematic ? schematic->GetPackageRefSuffix( symbol, ref.GetSheetPath() ) : wxString();
570
571 if( !boardRef.EndsWith( suffix ) || boardRef.length() <= suffix.length() )
572 {
573 result[ii].m_error = wxString::Format( _( "Cannot change %s to '%s', which lacks the sheet "
574 "suffix '%s'." ),
575 DescribeRef( ref.GetComposedRef() ), boardRef, suffix );
576 continue;
577 }
578
579 result[ii].m_base = boardRef.Left( boardRef.length() - suffix.length() );
580
581 if( shares( symbol ) )
582 {
583 auto [it, inserted] = firstBase.emplace( ref.GetSymbol(), result[ii].m_base );
584
585 if( !inserted && it->second != result[ii].m_base )
586 refusedSymbols.insert( ref.GetSymbol() );
587 }
588 }
589
590 // A rename is all or nothing for a footprint's units and, with shared bases, for a symbol's sheets
591 for( bool changed = true; changed; )
592 {
593 changed = false;
594
595 for( size_t ii = 0; ii < aRequests.size(); ++ii )
596 {
597 const SCH_SYMBOL* symbol = aRequests[ii].first->GetSymbol();
598 const wxString& boardRef = aRequests[ii].second;
599
600 if( result[ii].m_error.IsEmpty() && !refusedSymbols.contains( symbol )
601 && !refusedBoardRefs.contains( boardRef ) )
602 {
603 continue;
604 }
605
606 changed |= refusedBoardRefs.insert( boardRef ).second;
607
608 if( shares( symbol ) )
609 changed |= refusedSymbols.insert( symbol ).second;
610
611 if( result[ii].m_error.IsEmpty() )
612 {
613 result[ii].m_error = wxString::Format( _( "Cannot change %s to '%s', because the change "
614 "cannot reach all of its units and sheets." ),
615 DescribeRef( aRequests[ii].first->GetComposedRef() ),
616 boardRef );
617 result[ii].m_base.clear();
618 }
619 }
620 }
621
622 return result;
623}
624
625
627{
628 SCH_COMMIT commit( m_frame );
629 wxString msg;
630
631 // Staged edits hide published nets on their screens; read every net from the pre-edit publication
632 std::optional<SCH_CONNECTIVITY::PUBLICATION_HOLD> hold( std::in_place, m_frame->Schematic().Connectivity() );
633
634 std::set<CHANGELIST_ITEM*> unitSwapItems;
635
636 // First, optionally handle unit swaps across multi-unit symbols where possible
637 // This needs to happen before the rest of the normal changelist processing,
638 // because the swaps will modify the changelist
640 {
641 const wxString variantName = m_frame->Schematic().GetCurrentVariant();
642 REPORTER& debugReporter = NULL_REPORTER::GetInstance(); // Change to m_reporter for debugging
643
644 // Group changelist items by shared PCB footprint data pointer
645 std::map<std::shared_ptr<PCB_FP_DATA>, std::vector<CHANGELIST_ITEM*>> changesPerFp;
646
647 msg.Printf( wxT( "DEBUG(unit-swap): grouped changelist into %zu footprint(s) for unit-swap processing:" ),
648 changesPerFp.size() );
649
650 // The changelist will have multiple entries for multi-unit symbols, each unit ref, e.g. U1A, U1B
651 // will point to the same PCB_FP_DATA. Grouping by pointer allows us to handle all units of a symbol
652 // together by working on all changes to the same PCB footprint at once.
653 for( CHANGELIST_ITEM& item : m_changelist )
654 {
655 changesPerFp[item.second].push_back( &item );
656 msg += wxT( " " ) + item.first.GetRef();
657 }
658
659 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
660
661 // Handle all changes per footprint
662 for( auto& fpChangelistPair : changesPerFp )
663 {
664 std::set<SCH_SYMBOL*> swappedSymbols;
665 std::set<CHANGELIST_ITEM*> swappedItems;
666 std::shared_ptr<PCB_FP_DATA> fp = fpChangelistPair.first;
667 auto& changedFpItems = fpChangelistPair.second;
668
669 // Build symbol unit list for this footprint (multi-unit candidates)
670 // Snapshot of one schematic unit instance (ref + sheet path + nets) for matching
671 struct SYM_UNIT
672 {
673 SCH_SYMBOL* sym = nullptr;
674 SCH_SCREEN* screen = nullptr;
675 const SCH_SHEET_PATH* sheetPath = nullptr;
676 wxString ref;
677 int currentUnit = 0;
678 // Track these so we avoid re-applying label/field changes to swapped units
679 CHANGELIST_ITEM* changeItem = nullptr;
680 std::map<wxString, wxString> schNetsByPin; // pinNumber -> net (schematic)
681 std::map<wxString, wxString> pcbNetsByPin; // pinNumber -> net (from PCB pin map)
682 std::vector<wxString> unitPinNumbers; // library-defined pin numbers per unit
683 std::vector<wxString> schNetsInUnitOrder;
684 std::vector<wxString> pcbNetsInUnitOrder;
685 };
686
687 // All symbol units for this footprint
688 std::vector<SYM_UNIT> symbolUnits;
689 std::map<wxString, wxString> pcbNetsByLogicalPin;
690 bool mappingValid = true;
691
692 std::map<LIB_SYMBOL*, std::vector<LIB_SYMBOL::UNIT_PIN_INFO>> unitPinsByLibSymbol;
693
694 auto getUnitPins =
695 [&]( SCH_SYMBOL* symbol, int unitNumber ) -> std::vector<wxString>
696 {
697 if( unitNumber <= 0 )
698 return {};
699
700 if( !symbol )
701 return {};
702
703 LIB_SYMBOL* libSymbol = symbol->GetLibSymbolRef().get();
704
705 if( !libSymbol )
706 return {};
707
708 auto found = unitPinsByLibSymbol.find( libSymbol );
709
710 if( found == unitPinsByLibSymbol.end() )
711 found = unitPinsByLibSymbol.emplace( libSymbol, libSymbol->GetUnitPinInfo() ).first;
712
713 const std::vector<LIB_SYMBOL::UNIT_PIN_INFO>& unitInfos = found->second;
714
715 if( unitNumber > static_cast<int>( unitInfos.size() ) )
716 return {};
717
718 return unitInfos[unitNumber - 1].m_pinNumbers;
719 };
720
721 for( CHANGELIST_ITEM* changedItem : changedFpItems )
722 {
723 SCH_REFERENCE& ref = changedItem->first;
724 SCH_SYMBOL* symbol = ref.GetSymbol();
725 SCH_SCREEN* screen = ref.GetSheetPath().LastScreen();
726
727 if( !symbol )
728 continue;
729
730 // Collect nets keyed by pin number. Ordering by XY is intentionally avoided
731 // here; see comment in SYM_UNIT above.
732 SYM_UNIT symbolUnit;
733 symbolUnit.sym = symbol;
734 symbolUnit.screen = screen;
735 symbolUnit.ref = symbol->GetRef( &ref.GetSheetPath(), true );
736 symbolUnit.sheetPath = &ref.GetSheetPath();
737 symbolUnit.changeItem = changedItem;
738
739 int currentUnit = ref.GetUnit();
740
741 if( currentUnit <= 0 )
742 currentUnit = symbol->GetUnitSelection( &ref.GetSheetPath() );
743
744 if( currentUnit <= 0 )
745 currentUnit = symbol->GetUnit();
746
747 symbolUnit.currentUnit = currentUnit;
748 symbolUnit.unitPinNumbers = getUnitPins( symbol, symbolUnit.currentUnit );
749
750 const SCH_SHEET_PATH& sheetPath = ref.GetSheetPath();
751
752 if( !CollectBackannotatePcbNets( *symbol, sheetPath, variantName, fp->m_pinMap, pcbNetsByLogicalPin ) )
753 {
754 mappingValid = false;
755 break;
756 }
757
758 for( SCH_PIN* pin : symbol->GetPins( &sheetPath ) )
759 {
760 const wxString schNet = pin->GetConnectionName( &sheetPath, false, true ).value_or( wxString() );
761
762 for( const wxString& pinNum : pin->GetStackedPinNumbers() )
763 {
764 symbolUnit.pcbNetsByPin[pinNum] = pcbNetsByLogicalPin.at( pinNum );
765 symbolUnit.schNetsByPin[pinNum] = schNet;
766 }
767 }
768
769 symbolUnit.pcbNetsInUnitOrder = netsInUnitOrder( symbolUnit.unitPinNumbers, symbolUnit.pcbNetsByPin );
770 symbolUnit.schNetsInUnitOrder = netsInUnitOrder( symbolUnit.unitPinNumbers, symbolUnit.schNetsByPin );
771
772 symbolUnits.push_back( symbolUnit );
773 }
774
775 auto vectorToString =
776 []( const std::vector<wxString>& values ) -> wxString
777 {
778 return fmt::format( L"{}", fmt::join( values, L", " ) );
779 };
780
781 auto mapToString =
782 [vectorToString]( const std::map<wxString, wxString>& pinMap ) -> wxString
783 {
784 std::vector<wxString> entries;
785
786 for( const std::pair<const wxString, wxString>& pin : pinMap )
787 entries.push_back( pin.first + '=' + pin.second );
788
789 return vectorToString( entries );
790 };
791
792 msg.Printf( wxT( "DEBUG(unit-swap): footprint %s processed (%zu units, dryRun=%d)." ), fp->m_ref,
793 symbolUnits.size(), m_dryRun ? 1 : 0 );
794 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
795
796 // For debugging, sort the symbol units by ref
797 std::sort( symbolUnits.begin(), symbolUnits.end(),
798 []( const SYM_UNIT& a, const SYM_UNIT& b )
799 {
800 return a.ref < b.ref;
801 } );
802
803 for( const SYM_UNIT& su : symbolUnits )
804 {
805 wxString pcbPins = mapToString( su.pcbNetsByPin );
806 wxString schPins = mapToString( su.schNetsByPin );
807 wxString unitPins = vectorToString( su.unitPinNumbers );
808 wxString pcbUnitNetSeq = vectorToString( su.pcbNetsInUnitOrder );
809 wxString schUnitNetSeq = vectorToString( su.schNetsInUnitOrder );
810
811 msg.Printf( wxT( "DEBUG(unit-swap): unit %d: %s pcbPins[%s] schPins[%s] unitPins[%s] pcbUnitNets[%s] "
812 "schUnitNets[%s]." ),
813 su.currentUnit, su.ref, pcbPins, schPins, unitPins, pcbUnitNetSeq, schUnitNetSeq );
814 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
815 }
816
817 if( !mappingValid || symbolUnits.size() < 2 )
818 continue;
819
820 std::vector<BACKANNOTATE_UNIT_SWAP_CANDIDATE> candidates;
821
822 for( const SYM_UNIT& symbolUnit : symbolUnits )
823 {
825 candidate.m_ref = symbolUnit.ref;
826 candidate.m_currentUnit = symbolUnit.currentUnit;
827 candidate.m_schNetsByPin = symbolUnit.schNetsByPin;
828 candidate.m_unitPinNumbers = symbolUnit.unitPinNumbers;
829 candidates.push_back( candidate );
830 }
831
833
834 if( !plan.m_mappingOk )
835 {
836 msg.Printf( wxT( "DEBUG(unit-swap): mapping failed for footprint %s." ), fp->m_ref );
837 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
838 continue;
839 }
840
841 if( plan.m_identity )
842 {
843 msg.Printf( wxT( "DEBUG(unit-swap): footprint %s already aligned (identity mapping)." ), fp->m_ref );
844 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
845 continue;
846 }
847
848 if( !m_dryRun )
849 {
850 for( size_t candidateIdx : plan.m_swappedCandidateIndices )
851 commit.Modify( symbolUnits[candidateIdx].sym, symbolUnits[candidateIdx].screen );
852 }
853
854 for( const BACKANNOTATE_UNIT_SWAP_STEP& step : plan.m_steps )
855 {
856 SYM_UNIT& a = symbolUnits[step.m_firstIndex];
857 SYM_UNIT& b = symbolUnits[step.m_secondIndex];
858 int aUnit = a.currentUnit;
859 int bUnit = b.currentUnit;
860
861 if( !m_dryRun )
862 {
863 a.sym->SetUnit( bUnit );
864 b.sym->SetUnit( aUnit );
865
866 if( const SCH_SHEET_PATH* sheet = a.sheetPath )
867 a.sym->SetUnitSelection( sheet, bUnit );
868
869 if( const SCH_SHEET_PATH* sheet = b.sheetPath )
870 b.sym->SetUnitSelection( sheet, aUnit );
871 }
872
873 a.currentUnit = bUnit;
874 b.currentUnit = aUnit;
875
876 swappedSymbols.insert( a.sym );
877 swappedSymbols.insert( b.sym );
878
879 if( a.changeItem )
880 {
881 swappedItems.insert( a.changeItem );
882 unitSwapItems.insert( a.changeItem );
883 }
884
885 if( b.changeItem )
886 {
887 swappedItems.insert( b.changeItem );
888 unitSwapItems.insert( b.changeItem );
889 }
890
891 wxString baseRef = a.sym->GetRef( a.sheetPath, false );
892 wxString unitAString = a.sym->SubReference( aUnit, false );
893 wxString unitBString = b.sym->SubReference( bUnit, false );
894
895 if( unitAString.IsEmpty() )
896 unitAString.Printf( wxT( "%d" ), aUnit );
897
898 if( unitBString.IsEmpty() )
899 unitBString.Printf( wxT( "%d" ), bUnit );
900
901 msg.Printf( _( "Swap %s unit %s with unit %s." ),
902 DescribeRef( baseRef ),
903 unitAString,
904 unitBString );
905 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
907 }
908
909 msg.Printf( wxT( "DEBUG(unit-swap): applied %zu swap steps for footprint %s." ),
910 plan.m_steps.size(), fp->m_ref );
911 debugReporter.ReportHead( msg, RPT_SEVERITY_INFO );
912
913 // Remove label updates for swapped symbols by marking their SKIP_STRUCT flag
914 if( !m_dryRun )
915 {
916 for( CHANGELIST_ITEM* changedItem : changedFpItems )
917 {
918 SCH_SYMBOL* symbol = changedItem->first.GetSymbol();
919
920 if( !symbol )
921 continue;
922
923 if( swappedItems.count( changedItem ) || swappedSymbols.count( symbol ) )
924 symbol->SetFlags( SKIP_STRUCT );
925
926 int updatedUnit = symbol->GetUnitSelection( &changedItem->first.GetSheetPath() );
927 changedItem->first.SetUnit( updatedUnit );
928 }
929 }
930 }
931 }
932
933 std::vector<std::pair<const SCH_REFERENCE*, wxString>> refRequests;
934 const bool shareBases = m_frame->Schematic().Settings().m_AnnotateReusedSheetSuffixes;
935
936 for( const CHANGELIST_ITEM& item : m_changelist )
937 refRequests.emplace_back( &item.first, item.second->m_ref );
938
939 std::vector<BACKANNOTATE_REF> newRefs = ResolveBackannotatedRefs( refRequests, shareBases );
940
941 // Apply changes from change list
942 for( size_t itemIdx = 0; itemIdx < m_changelist.size(); ++itemIdx )
943 {
944 CHANGELIST_ITEM& item = m_changelist[itemIdx];
945 SCH_REFERENCE& ref = item.first;
946 PCB_FP_DATA& fpData = *item.second;
947 SCH_SYMBOL* symbol = ref.GetSymbol();
948 SCH_SCREEN* screen = ref.GetSheetPath().LastScreen();
949 wxString oldFootprint = ref.GetFootprint();
950 wxString oldValue = ref.GetValue();
951 bool oldDNP = ref.GetSymbol()->GetDNP();
952 bool oldExBOM = ref.GetSymbol()->GetExcludedFromBOM();
953 bool oldExSim = ref.GetSymbol()->GetExcludedFromSim();
954 bool oldExPosFiles = ref.GetSymbol()->GetExcludedFromPosFiles();
955 // Skip prevents us from re-applying label/field changes to units we just swapped
956 bool skip = ( ref.GetSymbol()->GetFlags() & SKIP_STRUCT ) > 0 || unitSwapItems.count( &item ) > 0;
957
958 auto boolString =
959 []( bool b ) -> wxString
960 {
961 return b ? _( "true" ) : _( "false" );
962 };
963
964 if( !m_dryRun )
965 commit.Modify( symbol, screen, RECURSE_MODE::NO_RECURSE );
966
967 if( m_processReferences && ref.GetComposedRef() != fpData.m_ref && !skip
968 && !symbol->GetField( FIELD_T::REFERENCE )->HasTextVars() )
969 {
970 const BACKANNOTATE_REF& newRef = newRefs[itemIdx];
971
972 if( !newRef.m_error.IsEmpty() )
973 {
974 m_reporter.ReportHead( newRef.m_error, RPT_SEVERITY_ERROR );
975 }
976 else
977 {
979 msg.Printf( _( "Change %s reference designator to '%s'." ),
981 fpData.m_ref );
982
983 if( !m_dryRun && shareBases )
984 symbol->SetUserRef( ref.GetSheetPath(), newRef.m_base );
985 else if( !m_dryRun )
986 symbol->SetRef( &ref.GetSheetPath(), newRef.m_base );
987
988 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
989 }
990 }
991
992 if( m_processFootprints && oldFootprint != fpData.m_footprint && !skip
993 && !symbol->GetField( FIELD_T::FOOTPRINT )->HasTextVars() )
994 {
996 msg.Printf( _( "Change %s footprint assignment from '%s' to '%s'." ),
997 DescribeRef( ref.GetRef() ),
998 EscapeHTML( oldFootprint ),
999 EscapeHTML( fpData.m_footprint ) );
1000
1001 if( !m_dryRun )
1002 symbol->SetFootprintFieldText( fpData.m_footprint );
1003
1004 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1005 }
1006
1007 if( m_processValues && oldValue != fpData.m_value && !skip
1008 && !symbol->GetField( FIELD_T::VALUE )->HasTextVars() )
1009 {
1011 msg.Printf( _( "Change %s value from '%s' to '%s'." ),
1012 DescribeRef( ref.GetRef() ),
1013 EscapeHTML( oldValue ),
1014 EscapeHTML( fpData.m_value ) );
1015
1016 if( !m_dryRun )
1017 symbol->SetValueFieldText( fpData.m_value );
1018
1019 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1020 }
1021
1022 if( m_processAttributes && oldDNP != fpData.m_DNP && !skip )
1023 {
1025 msg.Printf( _( "Change %s 'Do not populate' from '%s' to '%s'." ),
1026 DescribeRef( ref.GetRef() ),
1027 boolString( oldDNP ),
1028 boolString( fpData.m_DNP ) );
1029
1030 if( !m_dryRun )
1031 symbol->SetDNP( fpData.m_DNP );
1032
1033 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1034 }
1035
1036 if( m_processAttributes && oldExBOM != fpData.m_excludeFromBOM && !skip )
1037 {
1039 msg.Printf( _( "Change %s 'Exclude from bill of materials' from '%s' to '%s'." ),
1040 DescribeRef( ref.GetRef() ),
1041 boolString( oldExBOM ),
1042 boolString( fpData.m_excludeFromBOM ) );
1043
1044 if( !m_dryRun )
1045 symbol->SetExcludedFromBOM( fpData.m_excludeFromBOM );
1046
1047 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1048 }
1049
1050 if( m_processAttributes && oldExSim != fpData.m_excludeFromSim && !skip )
1051 {
1053 msg.Printf( _( "Change %s 'Exclude from simulation' from '%s' to '%s'." ),
1054 DescribeRef( ref.GetRef() ),
1055 boolString( oldExSim ),
1056 boolString( fpData.m_excludeFromSim ) );
1057
1058 if( !m_dryRun )
1059 symbol->SetExcludedFromSim( fpData.m_excludeFromSim );
1060
1061 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1062 }
1063
1064 if( m_processAttributes && oldExPosFiles != fpData.m_excludeFromPosFiles && !skip )
1065 {
1067 msg.Printf( _( "Change %s 'Exclude from position files' from '%s' to '%s'." ), DescribeRef( ref.GetRef() ),
1068 boolString( oldExPosFiles ), boolString( fpData.m_excludeFromPosFiles ) );
1069
1070 if( !m_dryRun )
1072
1073 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1074 }
1075
1076 std::set<wxString> swappedPins;
1077
1078 // Try to satisfy footprint pad net swaps by moving symbol pins before falling back to labels.
1079 if( m_preferPinSwaps && m_processNetNames && !skip )
1080 swappedPins = applyPinSwaps( symbol, ref, fpData, &commit );
1081
1082 if( m_processNetNames && !skip )
1083 {
1084 for( const std::pair<const wxString, wxString>& entry : fpData.m_pinMap )
1085 {
1086 const wxString& pinNumber = entry.first;
1087 const wxString& shortNetName = entry.second;
1088 SCH_PIN* pin = symbol->GetPin( pinNumber );
1089
1090 // Skip pins that the user preferred to handle with pin swaps in applyPreferredPinSwaps()
1091 if( swappedPins.count( pinNumber ) > 0 )
1092 continue;
1093
1094 if( !pin )
1095 {
1096 msg.Printf( _( "Cannot find %s pin '%s'." ),
1097 DescribeRef( ref.GetRef() ),
1098 EscapeHTML( pinNumber ) );
1099 m_reporter.ReportHead( msg, RPT_SEVERITY_ERROR );
1100
1101 continue;
1102 }
1103
1104 const std::optional<wxString> netName = pin->GetConnectionName( &ref.GetSheetPath(), false, true );
1105
1106 if( netName && *netName != shortNetName )
1107 processNetNameChange( &commit, ref.GetRef(), pin, ref.GetSheetPath(), *netName, shortNetName );
1108 }
1109 }
1110
1112 {
1113 // Need to handle three cases: existing field, new field, deleted field
1114 for( const std::pair<const wxString, wxString>& field : fpData.m_fieldsMap )
1115 {
1116 const wxString& fpFieldName = field.first;
1117 const wxString& fpFieldValue = field.second;
1118 SCH_FIELD* symField = symbol->GetField( fpFieldName );
1119
1120 // Skip fields that are individually controlled
1122 || fpFieldName == GetDefaultFieldName( FIELD_T::VALUE, UNTRANSLATED ) )
1123 {
1124 continue;
1125 }
1126
1127 // 1. Existing fields has changed value
1128 // PCB Field value is checked against the shown text because this is the value
1129 // with all the variables resolved. The footprints field value gets the symbol's
1130 // resolved value when the PCB is updated from the schematic.
1131 if( symField
1132 && !symField->HasTextVars()
1133 && symField->GetShownText( &ref.GetSheetPath(), INTERNAL ) != fpFieldValue )
1134 {
1136 msg.Printf( _( "Change %s field '%s' value to '%s'." ),
1137 DescribeRef( ref.GetRef() ),
1138 EscapeHTML( symField->GetUntranslatedName() ),
1139 EscapeHTML( fpFieldValue ) );
1140
1141 if( !m_dryRun )
1142 symField->SetText( fpFieldValue );
1143
1144 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1145 }
1146
1147 // 2. New field has been added to footprint and needs to be added to symbol
1148 if( symField == nullptr )
1149 {
1151 msg.Printf( _( "Add %s field '%s' with value '%s'." ),
1152 DescribeRef( ref.GetRef() ),
1153 EscapeHTML( fpFieldName ),
1154 EscapeHTML( fpFieldValue ) );
1155
1156 if( !m_dryRun )
1157 {
1158 SCH_FIELD newField( symbol, FIELD_T::USER, fpFieldName );
1159 newField.SetText( fpFieldValue );
1160 newField.SetTextPos( symbol->GetPosition() );
1161 newField.SetVisible( false ); // Don't clutter up the schematic
1162 symbol->AddField( newField );
1163 }
1164
1165 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1166 }
1167 }
1168
1169 // 3. Existing field has been deleted from footprint and needs to be deleted from symbol
1170 // Check all symbol fields for existence in the footprint field map.
1171 // Collect names first to avoid iterator invalidation when removing fields.
1172 std::vector<wxString> fieldsToDelete;
1173
1174 for( SCH_FIELD& field : symbol->GetFields() )
1175 {
1176 if( field.IsMandatory() )
1177 continue;
1178
1179 if( fpData.m_fieldsMap.find( field.GetUntranslatedName() ) == fpData.m_fieldsMap.end() )
1180 {
1182 msg.Printf( _( "Delete %s field '%s.'" ),
1183 DescribeRef( ref.GetRef() ),
1184 EscapeHTML( field.GetName() ) );
1185
1186 fieldsToDelete.push_back( field.GetName() );
1187 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1188 }
1189 }
1190
1191 if( !m_dryRun )
1192 {
1193 for( const wxString& fieldName : fieldsToDelete )
1194 symbol->RemoveField( fieldName );
1195 }
1196 }
1197
1198 if( symbol->GetFlags() & SKIP_STRUCT )
1199 symbol->ClearFlags( SKIP_STRUCT );
1200
1201 unitSwapItems.erase( &item );
1202
1203 // TODO: back-annotate netclass changes?
1204 }
1205
1206 hold.reset();
1207
1208 if( !m_dryRun )
1209 {
1210 m_frame->RecalculateConnections( &commit, NO_CLEANUP );
1211 m_frame->UpdateNetHighlightStatus();
1212
1213 commit.Push( _( "Update Schematic from PCB" ) );
1214 }
1215}
1216
1217
1219{
1221
1222 // Initial orientation from the pin
1223 switch( aPin->GetLibPin()->GetOrientation() )
1224 {
1225 default:
1226 case PIN_ORIENTATION::PIN_RIGHT: spin = SPIN_STYLE::LEFT; break;
1227 case PIN_ORIENTATION::PIN_UP: spin = SPIN_STYLE::BOTTOM; break;
1228 case PIN_ORIENTATION::PIN_DOWN: spin = SPIN_STYLE::UP; break;
1229 case PIN_ORIENTATION::PIN_LEFT: spin = SPIN_STYLE::RIGHT; break;
1230 }
1231
1232 // Reorient based on the actual symbol orientation now
1233 struct ORIENT
1234 {
1235 int flag;
1236 int n_rots;
1237 int mirror_x;
1238 int mirror_y;
1239 }
1240 orientations[] =
1241 {
1242 { SYM_ORIENT_0, 0, 0, 0 },
1243 { SYM_ORIENT_90, 1, 0, 0 },
1244 { SYM_ORIENT_180, 2, 0, 0 },
1245 { SYM_ORIENT_270, 3, 0, 0 },
1246 { SYM_MIRROR_X + SYM_ORIENT_0, 0, 1, 0 },
1247 { SYM_MIRROR_X + SYM_ORIENT_90, 1, 1, 0 },
1248 { SYM_MIRROR_Y, 0, 0, 1 },
1249 { SYM_MIRROR_X + SYM_ORIENT_270, 3, 1, 0 },
1250 { SYM_MIRROR_Y + SYM_ORIENT_0, 0, 0, 1 },
1251 { SYM_MIRROR_Y + SYM_ORIENT_90, 1, 0, 1 },
1252 { SYM_MIRROR_Y + SYM_ORIENT_180, 2, 0, 1 },
1253 { SYM_MIRROR_Y + SYM_ORIENT_270, 3, 0, 1 }
1254 };
1255
1256 ORIENT o = orientations[ 0 ];
1257
1258 const SCH_SYMBOL* parentSymbol = static_cast<const SCH_SYMBOL*>( aPin->GetParentSymbol() );
1259
1260 if( !parentSymbol )
1261 return spin;
1262
1263 int symbolOrientation = parentSymbol->GetOrientation();
1264
1265 for( const ORIENT& i : orientations )
1266 {
1267 if( i.flag == symbolOrientation )
1268 {
1269 o = i;
1270 break;
1271 }
1272 }
1273
1274 for( int i = 0; i < o.n_rots; i++ )
1275 spin = spin.RotateCCW();
1276
1277 if( o.mirror_x )
1278 spin = spin.MirrorX();
1279
1280 if( o.mirror_y )
1281 spin = spin.MirrorY();
1282
1283 return spin;
1284}
1285
1286
1287void addConnections( SCH_ITEM* aItem, const SCH_SHEET_PATH& aSheetPath, std::set<SCH_ITEM*>& connectedItems )
1288{
1289 if( !connectedItems.insert( aItem ).second )
1290 return;
1291
1292 std::vector<SCH_ITEM*> neighbors;
1293 SCHEMATIC* schematic = aItem->Schematic();
1294
1295 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine && schematic )
1296 {
1297 if( const auto connection = schematic->Connectivity().Connection( aItem->m_Uuid, aSheetPath.PathRef() ) )
1298 neighbors = connection->ConnectedItems();
1299 }
1300 else
1301 {
1302 neighbors = aItem->ConnectedItems( aSheetPath );
1303 }
1304
1305 for( SCH_ITEM* connectedItem : neighbors )
1306 addConnections( connectedItem, aSheetPath, connectedItems );
1307}
1308
1309
1310std::set<wxString> BACK_ANNOTATE::applyPinSwaps( SCH_SYMBOL* aSymbol, const SCH_REFERENCE& aReference,
1311 const PCB_FP_DATA& aFpData, SCH_COMMIT* aCommit )
1312{
1313 // Tracks pin numbers that we end up swapping so that the caller can skip any
1314 // duplicate label-only handling for those pins.
1315 std::set<wxString> swappedPins;
1316
1317 if( !aSymbol )
1318 return swappedPins;
1319
1320 SCH_SCREEN* screen = aReference.GetSheetPath().LastScreen();
1321
1322 if( !screen )
1323 return swappedPins;
1324
1325 wxCHECK( m_frame, swappedPins );
1326
1327 // Used to build the list of schematic pins whose current net assignment does not match the PCB.
1328 struct PIN_CHANGE
1329 {
1330 SCH_PIN* pin;
1331 wxString pinNumber;
1332 wxString currentNet;
1333 wxString targetNet;
1334 };
1335
1336 std::vector<PIN_CHANGE> mismatches;
1337
1338 // Helper map that lets us find all pins currently on a given net.
1339 std::map<wxString, std::vector<size_t>> pinsByCurrentNet;
1340
1341 // Build the mismatch list by inspecting each footprint pin that differs from the schematic.
1342 for( const std::pair<const wxString, wxString>& entry : aFpData.m_pinMap )
1343 {
1344 const wxString& pinNumber = entry.first;
1345 const wxString& desiredNet = entry.second;
1346
1347 SCH_PIN* pin = aSymbol->GetPin( pinNumber );
1348
1349 // Ignore power pins and anything marked as non-connectable. Power pins can map to
1350 // hidden/global references, e.g. implicit power connections on logic symbols.
1351 // KiCad pins are currently always connectable, but the extra guard keeps the
1352 // logic robust if alternate pin types (e.g. explicit mechanical/NC pins)
1353 // ever start reporting false.
1354 if( !pin || pin->IsPower() || !pin->IsConnectable() )
1355 continue;
1356
1357 wxString currentNet =
1358 pin->GetConnectionName( &aReference.GetSheetPath(), false, true ).value_or( wxString() );
1359
1360 if( desiredNet.IsEmpty() || currentNet.IsEmpty() )
1361 continue;
1362
1363 if( desiredNet == currentNet )
1364 continue;
1365
1366 size_t idx = mismatches.size();
1367 mismatches.push_back( { pin, pinNumber, currentNet, desiredNet } );
1368 pinsByCurrentNet[currentNet].push_back( idx );
1369 }
1370
1371 if( mismatches.size() < 2 )
1372 return swappedPins;
1373
1374 // Track which mismatch entries we have already consumed, and the underlying pin objects
1375 // we still need to clean up wiring around once the geometry swap is done.
1376 std::vector<bool> handled( mismatches.size(), false );
1377 std::vector<SCH_PIN*> swappedPinObjects;
1378 bool swappedLibPins = false;
1379 wxString msg;
1380
1381 bool allowPinSwaps = false;
1382 wxString currentProjectName = m_frame->Prj().GetProjectName();
1383
1384 if( m_frame->eeconfig() )
1385 allowPinSwaps = m_frame->eeconfig()->m_Input.allow_unconstrained_pin_swaps;
1386
1387 std::set<wxString> sharedSheetPaths;
1388 std::set<wxString> sharedProjectNames;
1389 bool sharedSheetSymbol = SymbolHasSheetInstances( *aSymbol, currentProjectName,
1390 &sharedSheetPaths, &sharedProjectNames );
1391
1392 std::set<wxString> friendlySheetNames;
1393
1394 if( sharedSheetSymbol && !sharedSheetPaths.empty() )
1395 friendlySheetNames = GetSheetNamesFromPaths( sharedSheetPaths, m_frame->Schematic() );
1396
1397 // Check each mismatch and try to find a partner whose desired net matches our current net
1398 // (i.e. the two pins have been swapped on the PCB).
1399 for( size_t i = 0; i < mismatches.size(); ++i )
1400 {
1401 // Skip entries already handled by a previous successful swap.
1402 if( handled[i] )
1403 continue;
1404
1405 PIN_CHANGE& change = mismatches[i];
1406
1407 // Find candidate pins whose current net equals the net we want to move this pin to.
1408 auto range = pinsByCurrentNet.find( change.targetNet );
1409
1410 // Nobody currently on the desired net, so there’s no reciprocal swap to apply.
1411 if( range == pinsByCurrentNet.end() )
1412 continue;
1413
1414 // Track the best partner index in case we discover a reciprocal mismatch below.
1415 size_t partnerIdx = std::numeric_limits<size_t>::max();
1416
1417 // Examine every pin that presently lives on the net we want to move to.
1418 for( size_t candidateIdx : range->second )
1419 {
1420 if( candidateIdx == i || handled[candidateIdx] )
1421 continue;
1422
1423 PIN_CHANGE& candidate = mismatches[candidateIdx];
1424
1425 // Potential swap partner must want to move to our current net, i.e. the PCB swapped the
1426 // two nets between these pins.
1427 if( candidate.targetNet == change.currentNet )
1428 {
1429 partnerIdx = candidateIdx;
1430 break;
1431 }
1432 }
1433
1434 // No viable partner found; either there was no reciprocal net mismatch or it was already
1435 // consumed. Leave this entry for label-based handling.
1436 if( partnerIdx == std::numeric_limits<size_t>::max() )
1437 continue;
1438
1439 PIN_CHANGE& partner = mismatches[partnerIdx];
1440
1441 // Sanity check: both pins must belong to the same schematic symbol before we swap geometry;
1442 // this prevents us from moving pin outlines between different units of a multi-unit symbol.
1443 if( change.pin->GetParentSymbol() != partner.pin->GetParentSymbol() )
1444 continue;
1445
1446 if( !allowPinSwaps || sharedSheetSymbol )
1447 {
1448 if( !sharedProjectNames.empty() )
1449 {
1450 std::vector<wxString> otherProjects;
1451
1452 for( const wxString& name : sharedProjectNames )
1453 {
1454 if( !currentProjectName.IsEmpty() && name.IsSameAs( currentProjectName ) )
1455 continue;
1456
1457 otherProjects.push_back( name );
1458 }
1459
1460 wxString projects = AccumulateDescriptions( otherProjects );
1461
1462 if( projects.IsEmpty() )
1463 {
1464 msg.Printf( _( "Would swap %s pins %s and %s to match PCB, but the symbol is shared across other projects." ),
1465 DescribeRef( aReference.GetRef() ),
1466 EscapeHTML( change.pin->GetShownNumber() ),
1467 EscapeHTML( partner.pin->GetShownNumber() ) );
1468 }
1469 else
1470 {
1471 msg.Printf( _( "Would swap %s pins %s and %s to match PCB, but the symbol is shared across other "
1472 "projects (%s)." ),
1473 aReference.GetRef(), EscapeHTML( change.pin->GetShownNumber() ),
1474 EscapeHTML( partner.pin->GetShownNumber() ), projects );
1475 }
1476 }
1477 else if( !friendlySheetNames.empty() )
1478 {
1479 wxString sheets = AccumulateDescriptions( friendlySheetNames );
1480
1481 msg.Printf( _( "Would swap %s pins %s and %s to match PCB, but the symbol is used by multiple sheet "
1482 "instances (%s)." ),
1483 DescribeRef( aReference.GetRef() ),
1484 EscapeHTML( change.pin->GetShownNumber() ),
1485 EscapeHTML( partner.pin->GetShownNumber() ), sheets );
1486 }
1487 else if( sharedSheetSymbol )
1488 {
1489 msg.Printf( _( "Would swap %s pins %s and %s to match PCB, but the symbol is shared." ),
1490 DescribeRef( aReference.GetRef() ),
1491 EscapeHTML( change.pin->GetShownNumber() ),
1492 EscapeHTML( partner.pin->GetShownNumber() ) );
1493 }
1494 else
1495 {
1496 msg.Printf( _( "Would swap %s pins %s and %s to match PCB, but unconstrained pin swaps are disabled in "
1497 "the schematic preferences." ),
1498 DescribeRef( aReference.GetRef() ),
1499 EscapeHTML( change.pin->GetShownNumber() ),
1500 EscapeHTML( partner.pin->GetShownNumber() ) );
1501 }
1502 m_reporter.ReportHead( msg, RPT_SEVERITY_INFO );
1503
1504 handled[i] = true;
1505 handled[partnerIdx] = true;
1506 continue;
1507 }
1508
1509 if( !m_dryRun )
1510 {
1511 wxCHECK2( aCommit, continue );
1512
1513 // Record the two pins in the commit and physically swap their local geometry.
1514 aCommit->Modify( change.pin, screen, RECURSE_MODE::RECURSE );
1515 aCommit->Modify( partner.pin, screen, RECURSE_MODE::RECURSE );
1516
1517 swappedLibPins |= SwapPinGeometry( change.pin, partner.pin );
1518 }
1519
1520 // Don’t pick either entry again for another pairing.
1521 handled[i] = true;
1522 handled[partnerIdx] = true;
1523
1524 // Remember which pin numbers we touched so the caller can suppress duplicate work.
1525 swappedPins.insert( change.pinNumber );
1526 swappedPins.insert( partner.pinNumber );
1527 swappedPinObjects.push_back( change.pin );
1528 swappedPinObjects.push_back( partner.pin );
1529
1531
1532 msg.Printf( _( "Swap %s pins %s and %s to match PCB." ),
1533 DescribeRef( aReference.GetRef() ),
1534 EscapeHTML( change.pin->GetShownNumber() ),
1535 EscapeHTML( partner.pin->GetShownNumber() ) );
1536 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1537 }
1538
1539 // Nothing left to do if we didn't find a valid swap pair when we were in dry-run mode.
1540 if( swappedPinObjects.empty() )
1541 return swappedPins;
1542
1543 if( !m_dryRun )
1544 {
1545 if( swappedLibPins )
1546 aSymbol->UpdatePins();
1547
1548 m_frame->UpdateItem( aSymbol, false, true );
1549
1550 if( TOOL_MANAGER* toolMgr = m_frame->GetToolManager() )
1551 {
1552 if( SCH_LINE_WIRE_BUS_TOOL* lwbTool = toolMgr->GetTool<SCH_LINE_WIRE_BUS_TOOL>() )
1553 {
1554 SCH_SELECTION cleanupSelection( screen );
1555
1556 // Make sure we tidy up any wires connected to the pins whose geometry just moved.
1557 for( SCH_PIN* swappedPin : swappedPinObjects )
1558 cleanupSelection.Add( swappedPin );
1559
1560 lwbTool->TrimOverLappingWires( aCommit, &cleanupSelection );
1561 lwbTool->AddJunctionsIfNeeded( aCommit, &cleanupSelection );
1562 }
1563 }
1564
1565 m_frame->Schematic().CleanUp( aCommit );
1566 }
1567
1568 return swappedPins;
1569}
1570
1571
1572void BACK_ANNOTATE::processNetNameChange( SCH_COMMIT* aCommit, const wxString& aRef, SCH_PIN* aPin,
1573 const SCH_SHEET_PATH& aSheet,
1574 const wxString& aOldName, const wxString& aNewName )
1575{
1576 wxString msg;
1577
1578 // Find a physically-connected driver. We can't use the SCH_CONNECTION's m_driver because
1579 // it has already been resolved by merging subgraphs with the same label, etc., and our
1580 // name change may cause that resolution to change.
1581
1582 std::set<SCH_ITEM*> connectedItems;
1583 SCH_ITEM* driver = nullptr;
1585
1586 addConnections( aPin, aSheet, connectedItems );
1587
1588 for( SCH_ITEM* item : connectedItems )
1589 {
1591
1592 if( priority > driverPriority )
1593 {
1594 driver = item;
1595 driverPriority = priority;
1596 }
1597 }
1598
1599 switch( driver->Type() )
1600 {
1601 case SCH_LABEL_T:
1602 case SCH_GLOBAL_LABEL_T:
1603 case SCH_HIER_LABEL_T:
1604 case SCH_SHEET_PIN_T:
1606
1607 msg.Printf( _( "Change %s pin %s net label from '%s' to '%s'." ),
1608 DescribeRef( aRef ),
1609 EscapeHTML( aPin->GetShownNumber() ),
1610 EscapeHTML( aOldName ),
1611 EscapeHTML( aNewName ) );
1612
1613 if( !m_dryRun )
1614 {
1615 aCommit->Modify( driver, aSheet.LastScreen() );
1616 static_cast<SCH_LABEL_BASE*>( driver )->SetText( aNewName );
1617 }
1618
1619 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1620 break;
1621
1622 case SCH_PIN_T:
1623 if( static_cast<SCH_PIN*>( driver )->IsPower() )
1624 {
1625 msg.Printf( _( "Net %s cannot be changed to %s because it is driven by a power pin." ),
1626 EscapeHTML( aOldName ),
1627 EscapeHTML( aNewName ) );
1628
1629 m_reporter.ReportHead( msg, RPT_SEVERITY_ERROR );
1630 break;
1631 }
1632
1633 // The physical connection walk could not find a label driver. This can happen when
1634 // a label sits in the middle of an unsplit wire. Fall back to the connection graph's
1635 // resolved driver which handles this case through subgraph merging.
1636 {
1637 SCH_ITEM* resolvedDriver = nullptr;
1638 SCH_SHEET_PATH driverSheet;
1640 SCHEMATIC& schematic = m_frame->Schematic();
1641
1642 if( ADVANCED_CFG::GetCfg().m_ConnectivityEngine )
1643 {
1644 const auto net = schematic.Connectivity().GetSubgraphForItem( aPin->m_Uuid, aSheet.PathRef() );
1645 const auto path = net ? schematic.Hierarchy().GetSheetPathByKIIDPath( net->Sheet() )
1646 : std::optional<SCH_SHEET_PATH>();
1647
1648 if( path && net->Driver() )
1649 {
1650 resolvedDriver = net->Driver();
1651 driverSheet = *path;
1652 resolvedPriority = CONNECTION_SUBGRAPH::GetDriverPriority( resolvedDriver );
1653 }
1654 }
1655 else if( CONNECTION_GRAPH* connGraph = schematic.ConnectionGraph() )
1656 {
1657 CONNECTION_SUBGRAPH* sg = connGraph->GetSubgraphForItem( aPin );
1658
1659 if( sg && sg->GetDriver() )
1660 {
1661 resolvedDriver = const_cast<SCH_ITEM*>( sg->GetDriver() );
1662 driverSheet = sg->GetSheet();
1663 resolvedPriority = sg->GetDriverPriority();
1664 }
1665 }
1666
1667 if( resolvedDriver && resolvedPriority >= CONNECTION_SUBGRAPH::PRIORITY::LOCAL_LABEL )
1668 {
1670 msg.Printf( _( "Change %s pin %s net label from '%s' to '%s'." ), DescribeRef( aRef ),
1671 EscapeHTML( aPin->GetShownNumber() ), EscapeHTML( aOldName ), EscapeHTML( aNewName ) );
1672
1673 if( !m_dryRun )
1674 {
1675 if( resolvedDriver->Type() == SCH_PIN_T )
1676 {
1677 SCH_PIN* powerPin = static_cast<SCH_PIN*>( resolvedDriver );
1678 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( powerPin->GetParentSymbol() );
1679
1680 aCommit->Modify( symbol, driverSheet.LastScreen() );
1681 symbol->GetField( FIELD_T::VALUE )->SetText( aNewName );
1682 }
1683 else
1684 {
1685 aCommit->Modify( resolvedDriver, driverSheet.LastScreen() );
1686 static_cast<SCH_LABEL_BASE*>( resolvedDriver )->SetText( aNewName );
1687 }
1688 }
1689
1690 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1691 break;
1692 }
1693 }
1694
1696 msg.Printf( _( "Add label '%s' to %s pin %s net." ),
1697 EscapeHTML( aNewName ),
1698 DescribeRef( aRef ),
1699 EscapeHTML( aPin->GetShownNumber() ) );
1700
1701 if( !m_dryRun )
1702 {
1703 SCHEMATIC_SETTINGS& settings = m_frame->Schematic().Settings();
1704 SCH_LABEL* label = new SCH_LABEL( driver->GetPosition(), aNewName );
1705 label->SetParent( &m_frame->Schematic() );
1706 label->SetTextSize( VECTOR2I( settings.m_DefaultTextSize, settings.m_DefaultTextSize ) );
1707 label->SetSpinStyle( orientLabel( static_cast<SCH_PIN*>( driver ) ) );
1708 label->SetFlags( IS_NEW );
1709
1710 SCH_SCREEN* screen = aSheet.LastScreen();
1711 aCommit->Add( label, screen );
1712 }
1713
1714 m_reporter.ReportHead( msg, RPT_SEVERITY_ACTION );
1715 break;
1716
1717 default:
1718 break;
1719 }
1720}
const char * name
std::vector< BACKANNOTATE_REF > ResolveBackannotatedRefs(const std::vector< std::pair< const SCH_REFERENCE *, wxString > > &aRequests, bool aShareBases)
Turn the references footprints carry into the base references of their schematic instances.
bool CollectBackannotatePcbNets(const SCH_SYMBOL &aSymbol, const SCH_SHEET_PATH &aSheetPath, const wxString &aVariantName, const std::map< wxString, wxString > &aPcbNetsByPad, std::map< wxString, wxString > &aPcbNetsByLogicalPin)
Append this unit's PCB nets to a map keyed by logical pin number, resolving pin-to-pad mappings.
static std::vector< wxString > netsInUnitOrder(const std::vector< wxString > &aPins, const std::map< wxString, wxString > &aNetByPin)
void addConnections(SCH_ITEM *aItem, const SCH_SHEET_PATH &aSheetPath, std::set< SCH_ITEM * > &connectedItems)
static SPIN_STYLE orientLabel(SCH_PIN *aPin)
BACKANNOTATE_UNIT_SWAP_PLAN PlanBackannotateUnitSwaps(const std::vector< BACKANNOTATE_UNIT_SWAP_CANDIDATE > &aCandidates, const std::map< wxString, wxString > &aPcbPinMap)
Compute a pure unit-swap plan from schematic-side unit definitions and PCB nets keyed by logical pin ...
std::vector< BACKANNOTATE_REF > ResolveBackannotatedRefs(const std::vector< std::pair< const SCH_REFERENCE *, wxString > > &aRequests, bool aShareBases)
Turn the references footprints carry into the base references of their schematic instances.
bool CollectBackannotatePcbNets(const SCH_SYMBOL &aSymbol, const SCH_SHEET_PATH &aSheetPath, const wxString &aVariantName, const std::map< wxString, wxString > &aPcbNetsByPad, std::map< wxString, wxString > &aPcbNetsByLogicalPin)
Append this unit's PCB nets to a map keyed by logical pin number, resolving pin-to-pad mappings.
BACKANNOTATE_UNIT_SWAP_PLAN PlanBackannotateUnitSwaps(const std::vector< BACKANNOTATE_UNIT_SWAP_CANDIDATE > &aCandidates, const std::map< wxString, wxString > &aPcbPinMap)
Compute a pure unit-swap plan from schematic-side unit definitions and PCB nets keyed by logical pin ...
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
bool BackAnnotateSymbols(const std::string &aNetlist)
Run back annotation algorithm.
SCH_MULTI_UNIT_REFERENCE_MAP m_multiUnitsRefs
std::deque< CHANGELIST_ITEM > m_changelist
std::pair< SCH_REFERENCE, std::shared_ptr< PCB_FP_DATA > > CHANGELIST_ITEM
bool m_processReferences
bool m_processFootprints
bool m_processOtherFields
void getPcbModulesFromString(const std::string &aPayload)
Parse netlist sent over KiWay express mail interface and fill m_pcbFootprints.
SCH_EDIT_FRAME * m_frame
void checkForUnusedSymbols()
Check if some symbols are not represented in PCB footprints and vice versa.
SCH_REFERENCE_LIST m_refs
bool FetchNetlistFromPCB(std::string &aNetlist)
Get netlist from the Pcbnew.
PCB_FOOTPRINTS_MAP m_pcbFootprints
REPORTER & m_reporter
bool m_processAttributes
BACK_ANNOTATE(SCH_EDIT_FRAME *aFrame, REPORTER &aReporter, bool aRelinkFootprints, bool aProcessFootprints, bool aProcessValues, bool aProcessReferences, bool aProcessNetNames, bool aProcessAttributes, bool aProcessOtherFields, bool aPreferUnitSwaps, bool aPreferPinSwaps, bool aDryRun)
std::set< wxString > applyPinSwaps(SCH_SYMBOL *aSymbol, const SCH_REFERENCE &aReference, const PCB_FP_DATA &aFpData, SCH_COMMIT *aCommit)
Handle footprint pad net swaps with symbol pin swaps where possible.
void processNetNameChange(SCH_COMMIT *aCommit, const wxString &aRef, SCH_PIN *aPin, const SCH_SHEET_PATH &aSheet, const wxString &aOldName, const wxString &aNewName)
bool m_matchByReference
void getChangeList()
Create changelist.
void PushNewLinksToPCB()
void applyChangelist()
Apply changelist to the schematic.
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
Calculate the connectivity of a schematic and generate netlists.
A subgraph is a set of items that are electrically connected on a single sheet.
const SCH_ITEM * GetDriver() const
static PRIORITY GetDriverPriority(SCH_ITEM *aDriver)
Return the priority (higher is more important) of a candidate driver.
const SCH_SHEET_PATH & GetSheet() const
Implement a lexical analyzer for the SPECCTRA DSN file format.
Definition dsnlexer.h:75
virtual VECTOR2I GetPosition() const
Definition eda_item.h:348
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
EDA_ITEM_FLAGS GetFlags() const
Definition eda_item.h:167
virtual void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true)
Definition eda_text.cpp:513
virtual void SetTextPos(const VECTOR2I &aPoint)
Definition eda_text.cpp:557
bool HasTextVars() const
Indicates the ShownText has text var references which need to be processed.
Definition eda_text.h:139
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
A wxFrame capable of the OpenProjectFiles function, meaning it can load a portion of a KiCad project.
virtual bool OpenProjectFiles(const std::vector< wxString > &aFileList, int aCtl=0)
Open a project or set of files given by aFileList.
Define a library symbol object.
Definition lib_symbol.h:114
std::vector< UNIT_PIN_INFO > GetUnitPinInfo() const
Return pin-number lists for each unit, ordered consistently for gate swapping.
static REPORTER & GetInstance()
Definition reporter.cpp:207
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & ReportHead(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Places the report at the beginning of the list for objects that support ordering.
Definition reporter.h:130
These are loaded from Eeschema settings but then overwritten by the project settings.
Holds all the data relating to one schematic.
Definition schematic.h:155
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_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
SCH_CONNECTIVITY::FACADE & Connectivity() const
Definition schematic.h:411
CONNECTION_GRAPH * ConnectionGraph() const
Definition schematic.h:414
Commit for the schematic and symbol editors.
Definition sch_commit.h:54
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
std::optional< NET_VIEW > GetSubgraphForItem(const KIID &aItem, const KIID_PATH &aPath) const
std::optional< ITEM_VIEW > Connection(const KIID &aItem, const KIID_PATH &aPath) const
Schematic editor (Eeschema) main window.
wxString GetUntranslatedName() const
Get the untranslated field name for storage, variable look-up, etc.
wxString GetShownText(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, const wxString &aVariantName=wxEmptyString, int aDepth=0) const
void SetText(const wxString &aText) override
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
const SYMBOL * GetParentSymbol() const
Definition sch_item.cpp:350
SCHEMATIC * Schematic() const
Search the item hierarchy to find a SCHEMATIC.
Definition sch_item.cpp:302
const std::vector< SCH_ITEM * > & ConnectedItems(const SCH_SHEET_PATH &aPath) const
Retrieve the set of items connected to this item on the given sheet.
Definition sch_item.cpp:766
int GetUnit() const
Definition sch_item.h:243
virtual void SetSpinStyle(SPIN_STYLE aSpinStyle)
Tool responsible for drawing/placing items (symbols, wires, buses, labels, etc.)
SCH_PIN * GetLibPin() const
Definition sch_pin.h:109
PIN_ORIENTATION GetOrientation() const
Definition sch_pin.cpp:389
const wxString & GetShownNumber() const
Definition sch_pin.cpp:711
A helper to define a symbol's reference designator in a schematic.
const SCH_SHEET_PATH & GetSheetPath() const
wxString GetComposedRef() const
Return the reference as shown on this sheet path, with its sheet suffix.
const wxString GetFootprint() const
SCH_SYMBOL * GetSymbol() const
wxString GetRef() const
const wxString GetValue() const
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.
void GetMultiUnitSymbols(SCH_MULTI_UNIT_REFERENCE_MAP &aRefList, SYMBOL_FILTER aSymbolFilter) const
Add a SCH_REFERENCE_LIST object to aRefList for each same-reference set of multi-unit parts in the li...
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...
SCH_SCREEN * LastScreen()
const KIID_PATH & PathRef() const
Borrow the cached path until this sheet path is modified or destroyed.
Schematic symbol object.
Definition sch_symbol.h:76
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
virtual void SetDNP(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
void RemoveField(const wxString &aFieldName)
Remove a user field from the symbol.
void SetExcludedFromSim(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from simulation flag.
std::vector< const SCH_PIN * > GetPins(const SCH_SHEET_PATH *aSheet) const
Retrieve a list of the SCH_PINs for the given sheet path.
bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
void UpdatePins()
Updates the cache of SCH_PIN objects for each pin.
void SetRef(const SCH_SHEET_PATH *aSheet, const wxString &aReference)
Set the base reference for the given sheet path for this symbol.
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
void SetFootprintFieldText(const wxString &aFootprint)
VECTOR2I GetPosition() const override
Definition sch_symbol.h:958
void SetExcludedFromPosFiles(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
void SetUserRef(const SCH_SHEET_PATH &aSheet, const wxString &aBase)
Set a base reference chosen by the user on aSheet.
void SetValueFieldText(const wxString &aValue, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString)
bool GetExcludedFromPosFiles(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
SCH_FIELD * AddField(const SCH_FIELD &aField)
Add a field to the symbol.
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
int GetUnitSelection(const SCH_SHEET_PATH *aSheet) const
Return the instance-specific unit selection for the given sheet path.
SCH_PIN * GetPin(const wxString &number) const
Find a symbol pin by number.
int GetOrientation() const override
Get the display symbol orientation.
void SetExcludedFromBOM(bool aEnable, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from schematic bill of materials flag.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
virtual bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flag.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
virtual void Add(EDA_ITEM *aItem)
A null aItem is ignored; the selection never holds null members.
Definition selection.cpp:38
Spin style for labels of all kinds on schematics.
Definition sch_label.h:38
SPIN_STYLE MirrorX()
Mirror the label spin style across the X axis or simply swaps up and bottom.
SPIN_STYLE MirrorY()
Mirror the label spin style across the Y axis or simply swaps left and right.
SPIN_STYLE RotateCCW()
Master controller class:
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
wxString DescribeRef(const wxString &aRef)
Returns a user-visible HTML string describing a footprint reference designator.
Definition common.cpp:508
@ INTERNAL
Definition common.h:96
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
#define _(s)
@ RECURSE
Definition eda_item.h:51
@ NO_RECURSE
Definition eda_item.h:52
#define IS_NEW
New item, just created.
#define SKIP_STRUCT
flag indicating that the structure should be ignored
@ FRAME_PCB_EDITOR
Definition frame_type.h:38
@ MAIL_PCB_UPDATE_LINKS
Definition mail_type.h:48
@ MAIL_PCB_GET_NETLIST
Definition mail_type.h:47
static std::vector< PENDING_PROPERTY > plan(const EDA_ITEM &aSource, const EDA_ITEM &aTarget, const std::set< wxString > &aEnabledKeys)
Target properties to write, paired with values read off the source.
@ PIN_UP
The pin extends upwards from the connection point: Probably on the bottom side of the symbol.
Definition pin_type.h:123
@ PIN_RIGHT
The pin extends rightwards from the connection point.
Definition pin_type.h:107
@ PIN_LEFT
The pin extends leftwards from the connection point: Probably on the right side of the symbol.
Definition pin_type.h:114
@ PIN_DOWN
The pin extends downwards from the connection: Probably on the top side of the symbol.
Definition pin_type.h:131
void Scan(PTREE *aTree, DSNLEXER *aLexer)
Fill an empty PTREE with information from a KiCad s-expression stream.
Definition ptree.cpp:80
boost::property_tree::ptree PTREE
Definition ptree.h:48
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
@ RPT_SEVERITY_ACTION
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
@ SYMBOL_FILTER_NON_POWER
std::set< wxString > GetSheetNamesFromPaths(const std::set< wxString > &aSheetPaths, const SCHEMATIC &aSchematic)
Get human-readable sheet names from a set of sheet paths, e.g.
bool SwapPinGeometry(SCH_PIN *aFirst, SCH_PIN *aSecond)
Swap the positions/lengths/etc.
bool SymbolHasSheetInstances(const SCH_SYMBOL &aSymbol, const wxString &aCurrentProject, std::set< wxString > *aSheetPaths, std::set< wxString > *aProjectNames)
Returns true when the given symbol has instances, e.g.
@ NO_CLEANUP
Definition schematic.h:99
wxString EscapeHTML(const wxString &aString)
Return a new wxString escaped for embedding in HTML.
std::vector< wxString > ExpandStackedPinNotation(const wxString &aPinName, bool *aValid)
Expand stacked pin notation like [1,2,3], [1-4], [A1-A4], or [AA1-AA3,AB4,CD12-CD14] into individual ...
wxString From_UTF8(const char *cstring)
void AccumulateDescriptions(wxString &aDesc, const T &aItemCollection)
Build a comma-separated list from a collection of wxStrings.
wxString m_base
Base reference the instance takes, when m_error is empty.
std::vector< wxString > m_unitPinNumbers
std::map< wxString, wxString > m_schNetsByPin
Container for Pcbnew footprint data.
std::map< wxString, wxString > m_pinMap
std::map< wxString, wxString > m_fieldsMap
@ SYM_ORIENT_270
Definition symbol.h:39
@ SYM_MIRROR_Y
Definition symbol.h:41
@ SYM_ORIENT_180
Definition symbol.h:38
@ SYM_MIRROR_X
Definition symbol.h:40
@ SYM_ORIENT_90
Definition symbol.h:37
@ SYM_ORIENT_0
Definition symbol.h:36
wxString GetDefaultFieldName(FIELD_T aFieldId, TRANSLATION aTranslation)
Return a default symbol field name for a mandatory field type.
@ USER
The field ID hasn't been set yet; field is invalid.
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
@ UNTRANSLATED
std::string path
KIBIS_PIN * partner
KIBIS_PIN * pin
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
wxString result
Test unit parsing edge cases and error handling.
#define kv
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCH_SHEET_PIN_T
Definition typeinfo.h:170
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_PIN_T
Definition typeinfo.h:149
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.