KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_reference_list.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) 1992-2018 jean-pierre Charras <jp.charras at wanadoo.fr>
5 * Copyright (C) 1992-2011 Wayne Stambaugh <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
26
27#include <sch_reference_list.h>
28#include <core/kicad_algo.h>
29
30#include <wx/regex.h>
31#include <algorithm>
32#include <map>
33#include <optional>
34#include <set>
35#include <vector>
36#include <unordered_set>
37
38#include <string_utils.h>
39#include <erc/erc_settings.h>
40#include <refdes_tracker.h>
41#include <sch_symbol.h>
42#include <schematic.h>
43#include <sch_edit_frame.h>
44
45
46void SCH_REFERENCE_LIST::RemoveItem( unsigned int aIndex )
47{
48 if( aIndex < m_flatList.size() )
49 m_flatList.erase( m_flatList.begin() + aIndex );
50}
51
52
54{
55 for( unsigned ii = 0; ii < GetCount(); ii++ )
56 {
57 if( m_flatList[ii].IsSameInstance( aItem ) )
58 return true;
59 }
60
61 return false;
62}
63
64
66{
67 for( unsigned ii = 0; ii < GetCount(); ii++ )
68 {
69 if( m_flatList[ii].IsSameInstance( aItem ) )
70 return &m_flatList[ii];
71 }
72
73 return nullptr;
74}
75
76
78{
79 int ii = item1.CompareRef( item2 );
80
81 if( ii == 0 )
82 ii = item1.m_sheetNum - item2.m_sheetNum;
83
84 if( ii == 0 )
85 ii = item1.m_symbolPos.x - item2.m_symbolPos.x;
86
87 if( ii == 0 )
88 ii = item1.m_symbolPos.y - item2.m_symbolPos.y;
89
90 if( ii == 0 )
91 return item1.m_symbolUuid < item2.m_symbolUuid; // ensure a deterministic sort
92 else
93 return ii < 0;
94}
95
96
98{
99 int ii = item1.CompareRef( item2 );
100
101 if( ii == 0 )
102 ii = item1.m_sheetNum - item2.m_sheetNum;
103
104 if( ii == 0 )
105 ii = item1.m_symbolPos.y - item2.m_symbolPos.y;
106
107 if( ii == 0 )
108 ii = item1.m_symbolPos.x - item2.m_symbolPos.x;
109
110 if( ii == 0 )
111 return item1.m_symbolUuid < item2.m_symbolUuid; // ensure a deterministic sort
112 else
113 return ii < 0;
114}
115
116
118 const SCH_REFERENCE& item2 )
119{
120 int ii = item1.CompareRef( item2 );
121
122 // Keeps each channel's units adjacent for the duplicate check
123 if( ii == 0 )
124 ii = item1.GetRefSuffix().Cmp( item2.GetRefSuffix() );
125
126 if( ii == 0 )
127 ii = item1.CompareValue( item2 );
128
129 if( ii == 0 )
130 ii = item1.m_unit - item2.m_unit;
131
132 if( ii == 0 )
133 ii = item1.m_sheetNum - item2.m_sheetNum;
134
135 if( ii == 0 )
136 ii = item1.m_symbolPos.x - item2.m_symbolPos.x;
137
138 if( ii == 0 )
139 ii = item1.m_symbolPos.y - item2.m_symbolPos.y;
140
141 if( ii == 0 )
142 return item1.m_symbolUuid < item2.m_symbolUuid; // ensure a deterministic sort
143 else
144 return ii < 0;
145}
146
147
149 const SCH_REFERENCE& item2 )
150{
151 int ii = StrNumCmp( item1.GetRef(), item2.GetRef(), CMP_T::CASE_SENSITIVE );
152
153 if( ii == 0 )
154 ii = item1.m_unit - item2.m_unit;
155
156 if( ii == 0 )
157 return item1.m_symbolUuid < item2.m_symbolUuid; // ensure a deterministic sort
158 else
159 return ii < 0;
160}
161
162
164 const SCH_REFERENCE& item2 )
165{
166 int ii = item1.m_sheetPath.Cmp( item2.m_sheetPath );
167
168 if( ii == 0 )
169 return item1.m_symbolUuid < item2.m_symbolUuid; // ensure a deterministic sort
170 else
171 return ii < 0;
172}
173
174
176{
177 return item1.m_rootSymbol < item2.m_rootSymbol;
178}
179
180
181int SCH_REFERENCE_LIST::FindRefByFullPath( const wxString& aFullPath ) const
182{
183 for( size_t i = 0; i < m_flatList.size(); ++i )
184 {
185 if( m_flatList[i].GetFullPath() == aFullPath )
186 return i;
187 }
188
189 return -1;
190}
191
192
193int SCH_REFERENCE_LIST::FindRef( const wxString& aRef ) const
194{
195 for( size_t i = 0; i < m_flatList.size(); ++i )
196 {
197 if( m_flatList[i].GetComposedRef() == aRef )
198 return i;
199 }
200
201 return -1;
202}
203
204
205void SCH_REFERENCE_LIST::GetRefsInUse( int aIndex, std::vector< int >& aIdList,
206 int aMinRefId ) const
207{
208 aIdList.clear();
209
210 for( const SCH_REFERENCE& ref : m_flatList )
211 {
212 // Don't add new references to the list as we will reannotate those
213 if( m_flatList[aIndex].CompareRef( ref ) == 0 && ref.m_numRef >= aMinRefId && !ref.m_isNew )
214 aIdList.push_back( ref.m_numRef );
215 }
216
217 std::sort( aIdList.begin(), aIdList.end() );
218
219 // Ensure each reference number appears only once. If there are symbols with
220 // multiple parts per package the same number will be stored for each part.
221 alg::remove_duplicates( aIdList );
222}
223
224
225std::vector<int> SCH_REFERENCE_LIST::GetPackageUnits( const SCH_REFERENCE& aRef ) const
226{
227 std::vector<int> unitsList;
228
229 // Always add this reference to the list
230 unitsList.push_back( aRef.m_unit );
231
232 for( const SCH_REFERENCE& ref : m_flatList )
233 {
234 if( ref.CompareValue( aRef ) != 0 )
235 continue;
236
237 if( ref.CompareLibId( aRef ) != 0 )
238 continue;
239
240 unitsList.push_back( ref.m_unit );
241 }
242
243 std::sort( unitsList.begin(), unitsList.end() );
244
245 // Ensure each reference number appears only once. If there are symbols with
246 // multiple parts per package the same number will be stored for each part.
247 alg::remove_duplicates( unitsList );
248
249 return unitsList;
250}
251
252
253static bool sharesReusedBase( const SCH_REFERENCE& aRef )
254{
255 const SCHEMATIC* schematic = aRef.GetSymbol()->Schematic();
256 return !schematic || !schematic->CopiesSelectDifferentUnits( aRef.GetSymbol() );
257}
258
259
260// A copy that keeps its own base can sit in another package than its siblings, so it keys apart
261static std::pair<const SCH_SYMBOL*, KIID_PATH> packageMemberKey( const SCH_REFERENCE& aRef )
262{
263 return { aRef.GetSymbol(), sharesReusedBase( aRef ) ? KIID_PATH() : aRef.GetSheetPath().Path() };
264}
265
266
268{
269 std::map<const SCH_SCREEN*, const SCH_SHEET_PATH*> firstPath;
270
271 for( const SCH_SHEET_PATH& path : aSheets )
272 firstPath.emplace( path.LastScreen(), &path );
273
274 SCH_REFERENCE_LIST representatives;
275 std::unordered_set<SCH_SYMBOL*> seen;
276
277 for( const SCH_REFERENCE& ref : m_flatList )
278 {
279 // Copies that select different units each annotate on their own path
280 if( !sharesReusedBase( ref ) )
281 {
282 representatives.AddItem( ref );
283 continue;
284 }
285
286 if( !seen.insert( ref.GetSymbol() ).second )
287 continue;
288
289 auto it = firstPath.find( ref.GetSheetPath().LastScreen() );
290
291 if( it == firstPath.end() || *it->second == ref.GetSheetPath() )
292 representatives.AddItem( ref );
293 else
294 it->second->AppendSymbol( representatives, ref.GetSymbol(), SYMBOL_FILTER_ALL, true );
295 }
296
297 m_flatList = std::move( representatives.m_flatList );
298}
299
300
303{
304 std::map<std::pair<const SCH_SYMBOL*, KIID_PATH>, size_t> indexOf;
305 std::vector<size_t> parent( m_flatList.size() );
306 std::set<size_t> locked;
307
308 for( size_t i = 0; i < m_flatList.size(); i++ )
309 {
310 indexOf[packageMemberKey( m_flatList[i] )] = i;
311 parent[i] = i;
312 }
313
314 auto root =
315 [&]( size_t aIndex )
316 {
317 while( parent[aIndex] != aIndex )
318 aIndex = parent[aIndex] = parent[parent[aIndex]];
319
320 return aIndex;
321 };
322
323 for( const auto& [key, group] : aLocked )
324 {
325 std::optional<size_t> first;
326
327 for( const SCH_REFERENCE& ref : group )
328 {
329 auto it = indexOf.find( packageMemberKey( ref ) );
330
331 if( it == indexOf.end() )
332 continue;
333
334 locked.insert( it->second );
335
336 if( first )
337 parent[root( it->second )] = root( *first );
338 else
339 first = it->second;
340 }
341 }
342
344
345 // The root index keeps two packages apart even when a duplicate gave them one composed ref
346 for( size_t index : locked )
347 {
348 const size_t group = root( index );
349 result[wxString::Format( wxS( "%s:%zu" ), m_flatList[group].GetComposedRef(), group )].AddItem(
350 m_flatList[index] );
351 }
352
353 return result;
354}
355
356
358 const SCH_MULTI_UNIT_REFERENCE_MAP& aLocked,
359 const SCH_SHEET_LIST& aSheets )
360{
361 std::map<std::pair<const SCH_SYMBOL*, KIID_PATH>, wxString> packageOf;
362 std::map<wxString, std::set<int>> packageUnits;
363 std::set<wxString> renumberedPackages;
364
365 for( const auto& [key, group] : aLocked )
366 {
367 for( const SCH_REFERENCE& ref : group )
368 {
369 packageOf[packageMemberKey( ref )] = key;
370 packageUnits[key].insert( ref.GetUnit() );
371
372 // Sharing would move all but one base onto destinations nobody checked
373 if( ref.GetRef() != group[0].GetRef() )
374 renumberedPackages.insert( key );
375 }
376 }
377
378 auto packageFor =
379 [&]( const SCH_REFERENCE& aRef ) -> const wxString*
380 {
381 auto it = packageOf.find( packageMemberKey( aRef ) );
382 return it == packageOf.end() ? nullptr : &it->second;
383 };
384
385 // Another part's unit can only join a package where the package leaves that unit free
386 auto joins =
387 [&]( const SCH_REFERENCE& aRef, const SCH_REFERENCE& aOther )
388 {
389 if( aOther.CompareLibId( aRef ) != 0 || aOther.CompareValue( aRef ) != 0 )
390 return false;
391
392 if( const wxString* package = packageFor( aRef ) )
393 return !packageUnits[*package].contains( aOther.GetUnit() );
394
395 return aOther.GetUnit() != aRef.GetUnit();
396 };
397
398 auto samePackage =
399 [&]( const SCH_REFERENCE& aRef, const SCH_REFERENCE& aOther )
400 {
401 const wxString* ref = packageFor( aRef );
402 const wxString* other = packageFor( aOther );
403
404 if( ref && other )
405 return *ref == *other;
406
407 return aOther.GetUnit() != aRef.GetUnit() && aOther.CompareLibId( aRef ) == 0
408 && aOther.CompareValue( aRef ) == 0;
409 };
410
411 std::multimap<wxString, const SCH_REFERENCE*> othersByBase;
412 std::multimap<wxString, const SCH_REFERENCE*> othersByComposed;
413 std::map<const SCH_SCREEN*, std::vector<const SCH_SHEET_PATH*>> pathsOf;
414
415 for( const SCH_REFERENCE& other : aOthers.m_flatList )
416 {
417 othersByBase.emplace( other.GetRef(), &other );
418 othersByComposed.emplace( other.GetComposedRef(), &other );
419 }
420
421 for( const SCH_SHEET_PATH& path : aSheets )
422 pathsOf[path.LastScreen()].push_back( &path );
423
424 // A shared base shows on every copy, while a copy keeping its own shows only there
425 // A multi-unit symbol shows its package's suffix, which can be another sheet's
426 auto suffixesFor =
427 [&]( const SCH_REFERENCE& aRef ) -> std::vector<wxString>
428 {
429 const SCH_SYMBOL* symbol = aRef.GetSymbol();
430 const SCHEMATIC* schematic = symbol->Schematic();
431 std::vector<wxString> result;
432
433 auto add =
434 [&]( const SCH_SHEET_PATH& aPath )
435 {
436 if( !schematic )
437 result.emplace_back();
438 else
439 result.push_back( schematic->GetPackageRefSuffix( symbol, aPath ) );
440 };
441
442 if( !sharesReusedBase( aRef ) )
443 {
444 add( aRef.GetSheetPath() );
445 return result;
446 }
447
448 for( const SCH_SHEET_PATH* path : pathsOf[aRef.GetSheetPath().LastScreen()] )
449 add( *path );
450
451 return result;
452 };
453
454 auto collides =
455 [&]( const SCH_REFERENCE& aRef, const std::vector<wxString>& aSuffixes )
456 {
457 auto blocks =
458 [&]( const std::multimap<wxString, const SCH_REFERENCE*>& aIndex, const wxString& aKey )
459 {
460 auto [begin, end] = aIndex.equal_range( aKey );
461
462 return std::any_of( begin, end,
463 [&]( const auto& aEntry )
464 {
465 return !joins( aRef, *aEntry.second );
466 } );
467 };
468
469 if( blocks( othersByBase, aRef.GetRef() ) )
470 return true;
471
472 // The suffix need not separate cleanly from the base, so compare what each instance will show
473 for( const wxString& suffix : aSuffixes )
474 {
475 if( blocks( othersByComposed, aRef.GetRef() + suffix ) )
476 return true;
477 }
478
479 return false;
480 };
481
482 std::set<const SCH_REFERENCE*> renumbered;
483 std::map<wxString, std::vector<const SCH_REFERENCE*>> holders;
484 std::map<wxString, std::vector<const SCH_REFERENCE*>> composedHolders;
485
486 for( const SCH_REFERENCE& ref : m_flatList )
487 {
488 const std::vector<wxString> suffixes = suffixesFor( ref );
489
490 auto clashes =
491 [&]( const std::vector<const SCH_REFERENCE*>& aHolders )
492 {
493 return !std::all_of( aHolders.begin(), aHolders.end(),
494 [&]( const SCH_REFERENCE* aHolder )
495 {
496 return samePackage( ref, *aHolder );
497 } );
498 };
499
500 bool conflict = collides( ref, suffixes ) || clashes( holders[ref.GetRef()] )
501 || std::any_of( suffixes.begin(), suffixes.end(),
502 [&]( const wxString& aSuffix )
503 {
504 return clashes( composedHolders[ref.GetRef() + aSuffix] );
505 } );
506
507 if( !conflict )
508 {
509 holders[ref.GetRef()].push_back( &ref );
510
511 for( const wxString& suffix : suffixes )
512 composedHolders[ref.GetRef() + suffix].push_back( &ref );
513 }
514 else if( const wxString* package = packageFor( ref ) )
515 renumberedPackages.insert( *package );
516 else
517 renumbered.insert( &ref );
518 }
519
520 for( SCH_REFERENCE& ref : m_flatList )
521 {
522 const wxString* package = packageFor( ref );
523
524 if( renumbered.contains( &ref ) || ( package && renumberedPackages.contains( *package ) ) )
525 ref.m_isNew = true;
526 }
527}
528
529
531 const SCH_REFERENCE& aRef, int aMinValue, const std::vector<int>& aRequiredUnits,
532 const std::map<const SCH_REFERENCE*, std::vector<SCH_REFERENCE>>& aDestinations,
533 const SCH_REFERENCE_LIST* aLocked ) const
534{
535 // Create a map of references indexed by reference number, only including those with the same
536 // reference prefix as aRef
537 std::map<int, std::vector<SCH_REFERENCE>> refNumberMap;
538
539 // Without required units the tracker only asks whether a number is taken, so skip the copies
540 const bool needUnits = std::ranges::any_of( aRequiredUnits, []( int aUnit ) { return aUnit >= 0; } );
541
542 for( const SCH_REFERENCE& ref : m_flatList )
543 {
544 // search only for the current reference prefix:
545 if( ref.CompareRef( aRef ) != 0 )
546 continue;
547
548 if( ref.m_isNew )
549 continue; // It will be reannotated
550
551 std::vector<SCH_REFERENCE>& numbered = refNumberMap[ref.m_numRef];
552
553 if( needUnits )
554 numbered.push_back( ref );
555 }
556
557 std::function<bool( int )> acceptNumber;
558
559 if( !aDestinations.empty() )
560 {
561 std::multimap<wxString, SCH_REFERENCE> occupied;
562 std::vector<SCH_REFERENCE> candidates;
563
564 for( const auto& [ref, destinations] : aDestinations )
565 {
566 if( ref == &aRef
567 || ( aLocked && ref->CompareRef( aRef ) == 0 && ref->CompareLibId( aRef ) == 0
568 && ref->CompareValue( aRef ) == 0 && aLocked->Contains( *ref ) ) )
569 {
570 candidates.insert( candidates.end(), destinations.begin(), destinations.end() );
571 }
572
573 if( ref->m_isNew || ref->m_numRef < 0 )
574 continue;
575
576 for( SCH_REFERENCE destination : destinations )
577 {
578 destination.SetUnit( ref->GetUnit() );
579
580 // Symbols still hold the old references until allocation finishes
581 wxString composed = ref->GetRef() + ref->GetRefNumber() + destination.m_refSuffix;
582 occupied.emplace( composed, std::move( destination ) );
583 }
584 }
585
586 acceptNumber = [&aRef, occupied = std::move( occupied ), candidates = std::move( candidates )]( int aNumber )
587 {
588 wxString base = aRef.GetRef() + aRef.formatRefStr( aNumber );
589
590 for( const SCH_REFERENCE& candidate : candidates )
591 {
592 auto [begin, end] = occupied.equal_range( base + candidate.m_refSuffix );
593
594 for( auto it = begin; it != end; ++it )
595 {
596 const SCH_REFERENCE& other = it->second;
597
598 if( other.GetUnit() == candidate.GetUnit() || other.CompareLibId( candidate ) != 0
599 || other.CompareValue( candidate ) != 0 )
600 {
601 return false;
602 }
603 }
604 }
605
606 return true;
607 };
608 }
609
610 return m_refDesTracker->GetNextRefDesForUnits( aRef, refNumberMap, aRequiredUnits, aMinValue, acceptNumber );
611}
612
613
614std::vector<SCH_SYMBOL_INSTANCE> SCH_REFERENCE_LIST::GetSymbolInstances() const
615{
616 std::vector<SCH_SYMBOL_INSTANCE> retval;
617
618 for( const SCH_REFERENCE& ref : m_flatList )
619 {
620 SCH_SYMBOL_INSTANCE instance;
621 instance.m_Path = ref.GetSheetPath().Path();
622 instance.m_Reference = ref.GetRef();
623 instance.m_Unit = ref.GetUnit();
624
625 retval.push_back( instance );
626 }
627
628 return retval;
629}
630
631
632// A helper function to build a full reference string of a SCH_REFERENCE item
633wxString buildFullReference( const SCH_REFERENCE& aItem, int aUnitNumber = -1 )
634{
635 wxString fullref;
636 fullref = aItem.GetRef() + aItem.GetRefNumber();
637
638 if( aUnitNumber < 0 )
639 fullref << ".." << aItem.GetUnit();
640 else
641 fullref << ".." << aUnitNumber;
642
643 return fullref;
644}
645
646
648 ANNOTATE_ALGO_T aAlgoOption,
649 int aStartNumber,
650 const SCH_REFERENCE_LIST& aAdditionalRefs,
651 bool aStartAtCurrent,
652 SCH_SHEET_LIST* aHierarchy )
653{
655
656 // All multi-unit symbols always locked to ensure consistent re-annotation
657 SCH_MULTI_UNIT_REFERENCE_MAP lockedSymbols;
658
659 for( size_t i = 0; i < GetCount(); i++ )
660 {
661 SCH_REFERENCE& ref = m_flatList[i];
662 wxString refstr = ref.GetSymbol()->GetRef( &ref.GetSheetPath() );
663
664 // Update sheet numbers based on the reference's sheet's position within the full
665 // hierarchy; we do this now before we annotate so annotation by sheet number * X
666 // works correctly.
667 if( aHierarchy )
668 {
669 SCH_SHEET_PATH* path = aHierarchy->FindSheetForPath( &ref.GetSheetPath() );
670 wxCHECK2_MSG( path, continue,
671 wxS( "Attempting to annotate item on sheet not part of the "
672 "hierarchy?" ) );
673
674 ref.SetSheetNumber( path->GetPageNumberAsInt() );
675 }
676
677 // Never lock unassigned references
678 if( refstr[refstr.Len() - 1] == '?' )
679 continue;
680
681 ref.m_isNew = true; // We want to reannotate all references
682
683 lockedSymbols[refstr].AddItem( ref );
684 }
685
686 AnnotateByOptions( aSortOption, aAlgoOption, aStartNumber, lockedSymbols, aAdditionalRefs,
687 aStartAtCurrent );
688}
689
690
691void SCH_REFERENCE_LIST::ReannotateDuplicates( const SCH_REFERENCE_LIST& aAdditionalReferences, ANNOTATE_ALGO_T aAlgoOption )
692{
693 ReannotateByOptions( UNSORTED, aAlgoOption, 0, aAdditionalReferences, true, nullptr );
694}
695
696
697void SCH_REFERENCE_LIST::AnnotateByOptions( ANNOTATE_ORDER_T aSortOption, ANNOTATE_ALGO_T aAlgoOption, int aStartNumber,
698 const SCH_MULTI_UNIT_REFERENCE_MAP& aLockedUnitMap,
699 const SCH_REFERENCE_LIST& aAdditionalRefs, bool aStartAtCurrent,
700 const SCH_SHEET_LIST* aSharedSheets )
701{
702 switch( aSortOption )
703 {
704 default:
707 }
708
709 bool useSheetNum;
710 int idStep;
711
712 switch( aAlgoOption )
713 {
714 default:
716 useSheetNum = false;
717 idStep = 1;
718 break;
719
721 useSheetNum = true;
722 idStep = 100;
723 aStartAtCurrent = false; // Not implemented for sheet # * 100
724 break;
725
727 useSheetNum = true;
728 idStep = 1000;
729 aStartAtCurrent = false; // Not implemented for sheet # * 1000
730 break;
731 }
732
733 Annotate( useSheetNum, idStep, aStartNumber, aLockedUnitMap, aAdditionalRefs, aStartAtCurrent, aSharedSheets );
734}
735
736
737void SCH_REFERENCE_LIST::Annotate( bool aUseSheetNum, int aSheetIntervalId, int aStartNumber,
738 const SCH_MULTI_UNIT_REFERENCE_MAP& aLockedUnitMap,
739 const SCH_REFERENCE_LIST& aAdditionalRefs, bool aStartAtCurrent,
740 const SCH_SHEET_LIST* aSharedSheets )
741{
742 if( !m_refDesTracker )
743 {
744 wxLogError( wxS( "No reference tracker set for SCH_REFERENCE_LIST::Annotate()" ) );
745 return;
746 }
747
748 if ( m_flatList.size() == 0 )
749 return;
750
751 size_t originalSize = GetCount();
752
753 // For multi units symbols, store the list of already used full references.
754 // The algorithm tries to allocate the new reference to symbols having the same
755 // old reference.
756 // This algo works fine as long as the previous annotation has no duplicates.
757 // But when a hierarchy is reannotated with this option, the previous annotation can
758 // have duplicate references, and obviously we must fix these duplicate.
759 // therefore do not try to allocate a full reference more than once when trying
760 // to keep this order of multi units.
761 // inUseRefs keep trace of previously allocated references
762 std::unordered_set<wxString> inUseRefs;
763
764 for( size_t i = 0; i < aAdditionalRefs.GetCount(); i++ )
765 {
766 SCH_REFERENCE additionalRef = aAdditionalRefs[i];
767 additionalRef.Split();
768
769 // Add the additional reference to the multi-unit set if annotated
770 if( !additionalRef.m_isNew )
771 inUseRefs.insert( buildFullReference( additionalRef ) );
772
773 // We don't want to reannotate the additional references even if not annotated
774 // so we change the m_isNew flag to be false after splitting
775 additionalRef.m_isNew = false;
776 AddItem( additionalRef ); //add to this container
777 }
778
779 std::map<const SCH_REFERENCE*, std::vector<SCH_REFERENCE>> destinations;
780
781 if( aSharedSheets )
782 {
783 for( size_t i = 0; i < m_flatList.size(); ++i )
784 {
785 const SCH_REFERENCE& ref = m_flatList[i];
786 std::vector<SCH_REFERENCE>& instances = destinations[&ref];
787
788 if( i < originalSize && sharesReusedBase( ref ) )
789 {
790 for( const SCH_SHEET_PATH& path : *aSharedSheets )
791 {
792 if( path.LastScreen() == ref.GetSheetPath().LastScreen() )
793 instances.emplace_back( ref.GetSymbol(), path );
794 }
795 }
796 else
797 {
798 instances.push_back( ref );
799 }
800 }
801 }
802
803 int LastReferenceNumber = 0;
804
805 /* calculate index of the first symbol with the same reference prefix
806 * than the current symbol. All symbols having the same reference
807 * prefix will receive a reference number with consecutive values:
808 * IC .. will be set to IC4, IC4, IC5 ...
809 */
810 unsigned first = 0;
811
812 // calculate the last used number for this reference prefix:
813 int minRefId;
814
815 // when using sheet number, ensure ref number >= sheet number* aSheetIntervalId
816 if( aUseSheetNum )
817 minRefId = m_flatList[first].m_sheetNum * aSheetIntervalId + 1;
818 else
819 minRefId = aStartNumber + 1;
820
821
822 for( unsigned ii = 0; ii < m_flatList.size(); ii++ )
823 {
824 auto& ref_unit = m_flatList[ii];
825
826 if( ref_unit.m_flag )
827 continue;
828
829 // Check whether this symbol is in aLockedUnitMap.
830 const SCH_REFERENCE_LIST* lockedList = nullptr;
831
832 for( const SCH_MULTI_UNIT_REFERENCE_MAP::value_type& pair : aLockedUnitMap )
833 {
834 unsigned n_refs = pair.second.GetCount();
835
836 for( unsigned thisRefI = 0; thisRefI < n_refs; ++thisRefI )
837 {
838 const SCH_REFERENCE &thisRef = pair.second[thisRefI];
839
840 if( thisRef.IsSameInstance( ref_unit ) )
841 {
842 lockedList = &pair.second;
843 break;
844 }
845 }
846
847 if( lockedList != nullptr )
848 break;
849 }
850
851 if( ( m_flatList[first].CompareRef( ref_unit ) != 0 )
852 || ( aUseSheetNum && ( m_flatList[first].m_sheetNum != ref_unit.m_sheetNum ) ) )
853 {
854 // New reference found: we need a new ref number for this reference
855 first = ii;
856
857 // when using sheet number, ensure ref number >= sheet number* aSheetIntervalId
858 if( aUseSheetNum )
859 minRefId = ref_unit.m_sheetNum * aSheetIntervalId + 1;
860 else
861 minRefId = aStartNumber + 1;
862 }
863
864 // Find references greater than current reference (unless not annotated)
865 if( aStartAtCurrent && ref_unit.m_numRef > 0 )
866 minRefId = ref_unit.m_numRef;
867
868 wxCHECK( ref_unit.GetLibPart(), /* void */ );
869
870 // Annotation of one part per package symbols (trivial case).
871 if( ref_unit.GetLibPart()->GetUnitCount() <= 1 )
872 {
873 if( ref_unit.m_isNew )
874 {
875 LastReferenceNumber = FindFirstUnusedReference( ref_unit, minRefId, {}, destinations );
876 ref_unit.m_numRef = LastReferenceNumber;
877 ref_unit.m_numRefStr = ref_unit.formatRefStr( LastReferenceNumber );
878 }
879
880 ref_unit.m_flag = 1;
881 ref_unit.m_isNew = false;
882 continue;
883 }
884
885 // If this symbol is in aLockedUnitMap, copy the annotation to all
886 // symbols that are not it
887 if( lockedList != nullptr )
888 {
889 unsigned n_refs = lockedList->GetCount();
890 std::vector<int> units = lockedList->GetPackageUnits( ref_unit );
891
892 if( ref_unit.m_isNew )
893 {
894 LastReferenceNumber = FindFirstUnusedReference( ref_unit, minRefId, units, destinations, lockedList );
895 ref_unit.m_numRef = LastReferenceNumber;
896 ref_unit.m_numRefStr = ref_unit.formatRefStr( LastReferenceNumber );
897 ref_unit.m_isNew = false;
898 ref_unit.m_flag = 1;
899 }
900
901 for( unsigned lockedRefI = 0; lockedRefI < n_refs; ++lockedRefI )
902 {
903 const SCH_REFERENCE& lockedRef = ( *lockedList )[lockedRefI];
904
905 if( lockedRef.IsSameInstance( ref_unit ) )
906 {
907 // This is the symbol we're currently annotating. Hold the unit!
908 ref_unit.m_unit = lockedRef.m_unit;
909
910 // lock this new full reference
911 inUseRefs.insert( buildFullReference( ref_unit ) );
912 }
913
914 if( lockedRef.CompareValue( ref_unit ) != 0 )
915 continue;
916
917 if( lockedRef.CompareLibId( ref_unit ) != 0 )
918 continue;
919
920 // Find the matching symbol
921 for( unsigned jj = ii + 1; jj < m_flatList.size(); jj++ )
922 {
923 if( !lockedRef.IsSameInstance( m_flatList[jj] ) )
924 continue;
925
926 // A merged reused-sheet group can mix prefixes, and the number is only free for this one
927 if( m_flatList[jj].CompareRef( ref_unit ) != 0 )
928 continue;
929
930 wxString ref_candidate = buildFullReference( ref_unit, lockedRef.m_unit );
931
932 // propagate the new reference and unit selection to the "old" symbol,
933 // if this new full reference is not already used (can happens when initial
934 // multiunits symbols have duplicate references)
935 if( inUseRefs.find( ref_candidate ) == inUseRefs.end() )
936 {
937 m_flatList[jj].m_numRef = ref_unit.m_numRef;
938 m_flatList[jj].m_numRefStr = ref_unit.m_numRefStr;
939 m_flatList[jj].m_isNew = false;
940 m_flatList[jj].m_flag = 1;
941
942 // lock this new full reference
943 inUseRefs.insert( ref_candidate );
944 break;
945 }
946 }
947 }
948 }
949 else if( ref_unit.m_isNew )
950 {
951 // Reference belonging to multi-unit symbol that has not yet been annotated. We don't
952 // know what group this might belong to, so just find the first unused reference for
953 // this specific unit. The other units will be annotated in the following passes.
954 std::vector<int> units = { ref_unit.GetUnit() };
955 LastReferenceNumber = FindFirstUnusedReference( ref_unit, minRefId, units, destinations );
956 ref_unit.m_numRef = LastReferenceNumber;
957 ref_unit.m_numRefStr = ref_unit.formatRefStr( LastReferenceNumber );
958 ref_unit.m_isNew = false;
959 ref_unit.m_flag = 1;
960 }
961 }
962
963 // Remove aAdditionalRefs references
964 m_flatList.erase( m_flatList.begin() + originalSize, m_flatList.end() );
965
966 wxASSERT( originalSize == GetCount() ); // Make sure we didn't make a mistake
967}
968
969
971{
972 int error = 0;
973 wxString tmp;
974 wxString tmp2;
975 wxString msg;
976
978
979 // Split reference designators into name (prefix) and number: IC1 becomes IC, and 1.
981
982 // count not yet annotated items or annotation error.
983 for( unsigned ii = 0; ii < m_flatList.size(); ii++ )
984 {
985 msg.Empty();
986 tmp.Empty();
987
988 LIB_SYMBOL* libSymbol = m_flatList[ii].GetLibPart();
989
990 if( m_flatList[ii].m_isNew ) // Not yet annotated
991 {
992 if( m_flatList[ii].m_numRef >= 0 )
993 tmp << m_flatList[ii].m_numRefStr;
994 else
995 tmp = wxT( "?" );
996
997 if( ( m_flatList[ii].m_unit > 0 ) && ( m_flatList[ii].m_unit < 0x7FFFFFFF )
998 && libSymbol && libSymbol->GetUnitCount() > 1 )
999 {
1000 msg.Printf( _( "Item not annotated: %s%s (unit %d)" ),
1001 m_flatList[ii].GetRef(),
1002 tmp,
1003 m_flatList[ii].m_unit );
1004 }
1005 else
1006 {
1007 msg.Printf( _( "Item not annotated: %s%s" ), m_flatList[ii].GetRef(), tmp );
1008 }
1009
1010 aHandler( ERCE_UNANNOTATED, msg, &m_flatList[ii], nullptr );
1011 error++;
1012 break;
1013 }
1014
1015 // Error if unit number selected does not exist (greater than the number of units in
1016 // the symbol). This can happen if a symbol has changed in a library after a
1017 // previous annotation.
1018 if( libSymbol && std::max( libSymbol->GetUnitCount(), 1 ) < m_flatList[ii].m_unit )
1019 {
1020 if( m_flatList[ii].m_numRef >= 0 )
1021 tmp << m_flatList[ii].m_numRefStr;
1022 else
1023 tmp = wxT( "?" );
1024
1025 msg.Printf( _( "Error: symbol %s%s%s (unit %d) exceeds units defined (%d)" ),
1026 m_flatList[ii].GetRef(),
1027 tmp,
1028 m_flatList[ii].GetSymbol()->SubReference( m_flatList[ii].GetUnit() ),
1029 m_flatList[ii].m_unit,
1030 libSymbol->GetUnitCount() );
1031
1032 aHandler( ERCE_EXTRA_UNITS, msg, &m_flatList[ii], nullptr );
1033 error++;
1034 break;
1035 }
1036 }
1037
1038 auto sameBaseAndSuffix = []( const SCH_REFERENCE& aFirst, const SCH_REFERENCE& aSecond )
1039 {
1040 return aFirst.CompareRef( aSecond ) == 0 && aFirst.m_numRef == aSecond.m_numRef
1041 && aFirst.GetRefSuffix() == aSecond.GetRefSuffix();
1042 };
1043
1044 auto checkPackage = [&]( SCH_REFERENCE& first, SCH_REFERENCE& second )
1045 {
1046 msg.Empty();
1047 tmp.Empty();
1048 tmp2.Empty();
1049
1050 // Same reference found. If same unit, error!
1051 if( first.m_unit == second.m_unit )
1052 {
1053 if( first.m_numRef >= 0 )
1054 tmp << first.m_numRefStr;
1055 else
1056 tmp = wxT( "?" );
1057
1058 msg.Printf( _( "Duplicate items %s%s%s%s\n" ),
1059 first.GetRef(),
1060 tmp,
1061 first.GetLibPart() && first.GetLibPart()->GetUnitCount() > 1
1062 ? first.GetSymbol()->SubReference( first.GetUnit() )
1063 : wxString( wxT( "" ) ),
1064 first.GetRefSuffix() );
1065
1066 aHandler( ERCE_DUPLICATE_REFERENCE, msg, &first, &second );
1067 error++;
1068 return;
1069 }
1070
1071 /* Test error if units are different but number of parts per package
1072 * too high (ex U3 ( 1 part) and we find U3B this is an error) */
1073 if( first.GetLibPart() && second.GetLibPart()
1074 && first.GetLibPart()->GetUnitCount() != second.GetLibPart()->GetUnitCount() )
1075 {
1076 if( first.m_numRef >= 0 )
1077 tmp << first.m_numRefStr;
1078 else
1079 tmp = wxT( "?" );
1080
1081 if( second.m_numRef >= 0 )
1082 tmp2 << second.m_numRefStr;
1083 else
1084 tmp2 = wxT( "?" );
1085
1086 msg.Printf( _( "Differing unit counts for item %s%s%s%s and %s%s%s%s\n" ),
1087 first.GetRef(),
1088 tmp,
1089 first.GetSymbol()->SubReference( first.GetUnit() ),
1090 first.GetRefSuffix(),
1091 second.GetRef(),
1092 tmp2,
1093 first.GetSymbol()->SubReference( second.GetUnit() ),
1094 second.GetRefSuffix() );
1095
1096 aHandler( ERCE_DUPLICATE_REFERENCE, msg, &first, &second );
1097 error++;
1098 return;
1099 }
1100
1101 // Error if values are different between units, for the same reference
1102 if( first.CompareValue( second ) != 0 )
1103 {
1104 msg.Printf( _( "Different values for %s%d%s (%s) and %s%d%s (%s)" ),
1105 first.GetRef(),
1106 first.m_numRef,
1107 first.GetSymbol()->SubReference( first.GetUnit() ) + first.GetRefSuffix(),
1108 first.m_value,
1109 second.GetRef(),
1110 second.m_numRef,
1111 first.GetSymbol()->SubReference( second.GetUnit() ) + second.GetRefSuffix(),
1112 second.m_value );
1113
1114 aHandler( ERCE_DIFFERENT_UNIT_VALUE, msg, &first, &second );
1115 error++;
1116 }
1117 };
1118
1119 // count the duplicated elements (if all are annotated)
1120 for( size_t ii = 1; ii < m_flatList.size(); ++ii )
1121 {
1122 if( sameBaseAndSuffix( m_flatList[ii - 1], m_flatList[ii] ) )
1123 checkPackage( m_flatList[ii - 1], m_flatList[ii] );
1124 }
1125
1126 // Different base and suffix splits can identify the same complete package reference
1127 std::map<wxString, std::map<int, SCH_REFERENCE*>> composed;
1128
1129 for( SCH_REFERENCE& ref : m_flatList )
1130 {
1131 if( ref.m_isNew )
1132 continue;
1133
1134 auto& units = composed[ref.GetRef() + ref.m_numRefStr + ref.GetRefSuffix()];
1135 auto first = units.find( ref.m_unit );
1136
1137 if( first == units.end() )
1138 first = units.begin();
1139
1140 // The loop above already checked units with the same base and suffix
1141 if( first != units.end() && !sameBaseAndSuffix( *first->second, ref ) )
1142 checkPackage( *first->second, ref );
1143
1144 units.emplace( ref.m_unit, &ref );
1145 }
1146
1147 return error;
1148}
1149
1150
1152{
1153 wxASSERT( aSymbol != nullptr );
1154
1155 m_rootSymbol = aSymbol;
1156
1157 // Ensure the symbol has instance data for the current sheet path so that the unit selection
1158 // remains consistent even when loading a sheet without symbol instance records (for example
1159 // when editing a subsheet directly).
1160 SCH_SYMBOL_INSTANCE instance;
1161
1162 if( !aSymbol->GetInstance( instance, aSheetPath.Path(), false ) )
1163 {
1164 instance.m_Path = aSheetPath.Path();
1165 instance.m_Reference = aSymbol->GetBaseRef( &aSheetPath );
1166
1167 if( instance.m_Reference.IsEmpty() )
1168 instance.m_Reference = aSymbol->GetField( FIELD_T::REFERENCE )->GetText();
1169
1170 instance.m_Unit = aSymbol->GetUnit();
1171 aSymbol->AddHierarchicalReference( instance );
1172 }
1173
1174 m_unit = aSymbol->GetUnitSelection( &aSheetPath );
1175 m_footprint = aSymbol->GetFootprintFieldText( &aSheetPath, RESOLVED );
1176 m_sheetPath = aSheetPath;
1177 m_isNew = false;
1178 m_flag = 0;
1179 m_symbolUuid = aSymbol->m_Uuid;
1180 m_symbolPos = aSymbol->GetPosition();
1181 m_sheetNum = 0;
1182
1183 if( aSymbol->GetBaseRef( &aSheetPath ).IsEmpty() )
1184 aSymbol->SetRef( &aSheetPath, wxT( "DefRef?" ) );
1185
1186 wxString ref = aSymbol->GetBaseRef( &aSheetPath );
1187 SetRef( ref );
1188
1189 // A unit of a package spanning sheets composes with the package's suffix, which keeps its units together
1190 if( const SCHEMATIC* schematic = aSymbol->Schematic() )
1191 m_refSuffix = schematic->GetPackageRefSuffix( aSymbol, aSheetPath );
1192
1193 m_numRef = -1;
1194
1195 // Unresolved so building a reference list never re-enters text resolution
1196 wxString value = aSymbol->GetValue( &aSheetPath, RAW_VALUE );
1197
1198 if( value.IsEmpty() )
1199 value = wxT( "~" );
1200
1201 m_value = std::move( value );
1202}
1203
1204
1206{
1207 wxString ref = GetRef();
1208
1209 if( IsSplit() )
1210 {
1211 if( !m_numRefStr.IsEmpty() )
1212 ref += m_numRefStr;
1213 else
1214 ref << m_numRef;
1215 }
1216
1217 if( GetSymbol()->GetUnitCount() > 1 )
1218 ref += GetSymbol()->SubReference( GetUnit() );
1219
1220 // A unit shows its own sheet's suffix even when its package composes with another
1221 if( const SCHEMATIC* schematic = m_rootSymbol->Schematic(); schematic && hasRef() )
1222 schematic->AppendRefSuffix( ref, m_sheetPath );
1223
1224 return ref;
1225}
1226
1227
1229{
1230 if( m_numRef < 0 )
1231 m_ref += '?';
1232 else
1233 m_ref = TO_UTF8( GetRef() << GetRefNumber() );
1234
1235 m_rootSymbol->SetRef( &m_sheetPath, From_UTF8( m_ref.c_str() ) );
1236 m_rootSymbol->SetUnit( m_unit );
1237 m_rootSymbol->SetUnitSelection( &m_sheetPath, m_unit );
1238}
1239
1240
1242{
1243 wxCHECK( m_rootSymbol && m_rootSymbol->GetLibSymbolRef()
1244 && !m_rootSymbol->GetRef( &m_sheetPath ).IsEmpty(), false );
1245
1246 return m_rootSymbol->GetLibSymbolRef()->IsPower()
1247 || m_rootSymbol->GetRef( &m_sheetPath )[0] == wxUniChar( '#' );
1248}
1249
1250
1252{
1253 std::string refText = GetRefStr();
1254
1255 m_numRef = -1;
1256 m_numRefStr.Clear();
1257
1258 int ll = refText.length() - 1;
1259
1260 if( refText[ll] == '?' )
1261 {
1262 m_isNew = true;
1263
1264 refText.erase( ll ); // delete last char
1265
1266 SetRefStr( refText );
1267 }
1268 else if( isdigit( refText[ll] ) == 0 )
1269 {
1270 m_isNew = true;
1271 }
1272 else
1273 {
1274 while( ll >= 0 )
1275 {
1276 if( (refText[ll] <= ' ' ) || isdigit( refText[ll] ) )
1277 {
1278 ll--;
1279 }
1280 else
1281 {
1282 if( isdigit( refText[ll + 1] ) )
1283 {
1284 // null terminated C string into cp
1285 const char* cp = refText.c_str() + ll + 1;
1286
1287 m_numRef = atoi( cp );
1288 }
1289
1290 m_numRefStr = std::string( refText, ll + 1 );
1291 refText.erase( ll + 1 );
1292 break;
1293 }
1294 }
1295
1296 SetRefStr( refText );
1297 }
1298}
1299
1300
1302{
1303 if( m_ref.IsEmpty() )
1304 return false;
1305
1306 const wxUniChar last = m_ref.Last();
1307
1308 return last == '?' || ( last >= '0' && last <= '9' );
1309}
1310
1311
1312bool SCH_REFERENCE::GetSymbolDNP( const wxString& aVariant ) const
1313{
1314 wxCHECK( m_rootSymbol, false );
1315
1316 return m_rootSymbol->GetDNP( &m_sheetPath, aVariant );
1317}
1318
1319
1320bool SCH_REFERENCE::GetSymbolExcludedFromBOM( const wxString& aVariant ) const
1321{
1322 wxCHECK( m_rootSymbol, false );
1323
1324 return m_rootSymbol->GetExcludedFromBOM( &m_sheetPath, aVariant );
1325}
1326
1327
1328bool SCH_REFERENCE::GetSymbolExcludedFromSim( const wxString& aVariant ) const
1329{
1330 wxCHECK( m_rootSymbol, false );
1331
1332 return m_rootSymbol->GetExcludedFromSim( &m_sheetPath, aVariant );
1333}
1334
1335
1337{
1338 wxCHECK( m_rootSymbol, false );
1339
1340 return m_rootSymbol->GetExcludedFromBoard();
1341}
1342
1343
1344bool SCH_REFERENCE::GetSymbolExcludedFromPosFiles( const wxString& aVariant ) const
1345{
1346 wxCHECK( m_rootSymbol, false );
1347
1348 return m_rootSymbol->GetExcludedFromPosFiles( &m_sheetPath, aVariant );
1349}
1350
1351
1352wxString SCH_REFERENCE::formatRefStr( int aNumber ) const
1353{
1354 // To avoid a risk of duplicate, for power symbols the ref number is 0nnn instead of nnn.
1355 // Just because sometimes only power symbols are annotated
1356 if( GetSymbol() && GetLibPart() && GetLibPart()->IsPower() )
1357 return wxString::Format( "0%d", aNumber );
1358
1359 return wxString::Format( "%d", aNumber );
1360}
1361
1362
1363void SCH_REFERENCE::SetSymbolDNP( bool aEnable, const wxString& aVariant )
1364{
1365 wxCHECK( m_rootSymbol, /* void */ );
1366
1367 m_rootSymbol->SetDNP( aEnable, &m_sheetPath, aVariant );
1368}
1369
1370
1371void SCH_REFERENCE::SetSymbolExcludedFromBOM( bool aEnable, const wxString& aVariant )
1372{
1373 wxCHECK( m_rootSymbol, /* void */ );
1374
1375 m_rootSymbol->SetExcludedFromBOM( aEnable, &m_sheetPath, aVariant );
1376}
1377
1378
1379void SCH_REFERENCE::SetSymbolExcludedFromSim( bool aEnable, const wxString& aVariant )
1380{
1381 wxCHECK( m_rootSymbol, /* void */ );
1382
1383 m_rootSymbol->SetExcludedFromSim( aEnable, &m_sheetPath, aVariant );
1384}
1385
1386
1388{
1389 wxCHECK( m_rootSymbol, /* void */ );
1390
1391 m_rootSymbol->SetExcludedFromBoard( aEnable );
1392}
1393
1394
1395void SCH_REFERENCE::SetSymbolExcludedFromPosFiles( bool aEnable, const wxString& aVariant )
1396{
1397 wxCHECK( m_rootSymbol, /* void */ );
1398
1399 m_rootSymbol->SetExcludedFromPosFiles( aEnable, &m_sheetPath, aVariant );
1400}
1401
1402
1403#if defined( DEBUG )
1404void SCH_REFERENCE_LIST::Show( const char* aPrefix )
1405{
1406 printf( "%s\n", aPrefix );
1407
1408 for( unsigned i = 0; i < m_flatList.size(); ++i )
1409 {
1410 SCH_REFERENCE& schref = m_flatList[i];
1411
1412 printf( " [%-2d] ref:%-8s num:%-3d lib_part:%s\n", i, schref.m_ref.ToStdString().c_str(),
1413 schref.m_numRef, TO_UTF8( schref.GetLibPart()->GetName() ) );
1414 }
1415}
1416#endif
1417
1418
1419void AnnotateNewSymbol( SCH_SYMBOL* aSymbol, const std::vector<SCH_SHEET_PATH>& aPaths,
1420 SCH_REFERENCE_LIST& aExistingRefs, const SCHEMATIC_SETTINGS& aSettings,
1421 SCH_SHEET_LIST* aHierarchy )
1422{
1423 std::optional<wxString> sharedBase;
1424 std::vector<wxString> pathSuffixes;
1425 std::multimap<wxString, size_t> composedInUse;
1426 bool share = aSettings.m_AnnotateReusedSheetSuffixes;
1427
1428 for( const SCH_SHEET_PATH& path : aPaths )
1429 {
1430 wxString suffix = path.ComposeRefSuffix();
1431
1432 // Paths that compose alike cannot share a base, which full annotation refuses outright
1433 if( std::ranges::find( pathSuffixes, suffix ) != pathSuffixes.end() )
1434 share = false;
1435
1436 pathSuffixes.push_back( std::move( suffix ) );
1437 }
1438
1439 if( share )
1440 {
1441 for( size_t ii = 0; ii < aExistingRefs.GetCount(); ii++ )
1442 {
1443 if( aExistingRefs[ii].GetSymbol() != aSymbol )
1444 composedInUse.emplace( aExistingRefs[ii].GetComposedRef(), ii );
1445 }
1446 }
1447
1448 // A free base can compose to a reference held elsewhere, as R1 on _M2 meets a root R1_M2
1449 // A free unit of the same part is no collision, since the allocator shares those on purpose
1450 auto composesTaken =
1451 [&]( const wxString& aBase, int aUnit )
1452 {
1453 for( size_t ii = 0; ii < aPaths.size(); ii++ )
1454 {
1455 // Values can resolve per path, so each destination compares its own
1456 SCH_REFERENCE newRef( aSymbol, aPaths[ii] );
1457 newRef.SetUnit( aUnit );
1458
1459 auto [begin, end] = composedInUse.equal_range( aBase + pathSuffixes[ii] );
1460
1461 for( auto it = begin; it != end; ++it )
1462 {
1463 const SCH_REFERENCE& other = aExistingRefs[it->second];
1464
1465 if( other.GetUnit() == aUnit || other.CompareLibId( newRef ) != 0
1466 || other.CompareValue( newRef ) != 0 )
1467 {
1468 return true;
1469 }
1470 }
1471 }
1472
1473 return false;
1474 };
1475
1476 for( const SCH_SHEET_PATH& path : aPaths )
1477 {
1478 if( sharedBase )
1479 {
1480 aSymbol->SetRef( &path, *sharedBase );
1481 aExistingRefs.AddItem( SCH_REFERENCE( aSymbol, path ) );
1482 continue;
1483 }
1484
1485 std::optional<SCH_REFERENCE_LIST> reserved;
1486 SCH_REFERENCE_LIST refs;
1487 std::set<wxString> tried;
1488
1489 for( ;; )
1490 {
1491 refs = SCH_REFERENCE_LIST();
1492 refs.AddItem( SCH_REFERENCE( aSymbol, path ) );
1493 refs.SetRefDesTracker( aSettings.m_refDesTracker );
1496 reserved ? *reserved : aExistingRefs, false, aHierarchy );
1497 refs.UpdateAnnotation();
1498
1499 // Power symbols keep a number per sheet, as annotation never shares them
1500 if( !share || refs[0].AlwaysAnnotate() )
1501 break;
1502
1503 sharedBase = aSymbol->GetBaseRef( &path );
1504
1505 // A base offered twice means the reservation did not hold, so stop rather than spin
1506 if( !tried.insert( *sharedBase ).second || !composesTaken( *sharedBase, refs[0].GetUnit() ) )
1507 break;
1508
1509 // Copy only when a retry must reserve the base it rejected
1510 if( !reserved )
1511 reserved = aExistingRefs;
1512
1513 reserved->AddItem( refs[0] );
1514 }
1515
1516 for( size_t ii = 0; ii < refs.GetCount(); ii++ )
1517 aExistingRefs.AddItem( refs[ii] );
1518 }
1519}
1520
1521
1522std::optional<std::pair<SCH_SHEET_PATH, SCH_SHEET_PATH>> FindRefSuffixCollision( const SCH_REFERENCE_LIST& aRefs,
1523 const SCHEMATIC& aSchematic )
1524{
1525 if( !aSchematic.Settings().m_AnnotateReusedSheetSuffixes )
1526 return std::nullopt;
1527
1528 std::set<const SCH_SCREEN*> screensInScope;
1529
1530 for( const SCH_REFERENCE& ref : aRefs )
1531 screensInScope.insert( ref.GetSheetPath().LastScreen() );
1532
1533 for( const std::pair<SCH_SHEET_PATH, SCH_SHEET_PATH>& collision : aSchematic.RefSuffixCollisions( true ) )
1534 {
1535 if( screensInScope.contains( collision.first.LastScreen() ) )
1536 return collision;
1537 }
1538
1539 return std::nullopt;
1540}
1541
1542
1544{
1545 std::erase_if( aLocked,
1546 []( const auto& aEntry )
1547 {
1548 std::set<int> seenUnits;
1549
1550 for( const SCH_REFERENCE& ref : aEntry.second )
1551 {
1552 if( !seenUnits.insert( ref.GetUnit() ).second )
1553 return true;
1554 }
1555
1556 return false;
1557 } );
1558}
1559
1560
1561std::set<const SCH_SCREEN*> AnnotateReferences( SCH_REFERENCE_LIST& aRefs, SCH_MULTI_UNIT_REFERENCE_MAP aLocked,
1562 const SCHEMATIC& aSchematic, ANNOTATE_SCOPE_T aScope,
1563 ANNOTATE_ORDER_T aSortOption, ANNOTATE_ALGO_T aAlgoOption,
1564 int aStartNumber, bool aResetAnnotation,
1565 const std::function<void( SCH_REFERENCE& )>& aBeforeAnnotate )
1566{
1567 const SCH_SHEET_LIST sheets = aSchematic.Hierarchy();
1568 const bool suffixMode = aSchematic.Settings().m_AnnotateReusedSheetSuffixes;
1569
1570 // A group holding one unit twice gets fresh assignments when resetting
1571 if( aResetAnnotation )
1572 removeUnitConflicts( aLocked );
1573
1574 if( suffixMode )
1575 {
1576 aRefs.UseReusedSheetRepresentatives( sheets );
1577
1578 // Merging can join two symbols on one unit even when annotation is kept
1579 aLocked = aRefs.LockedForRepresentatives( aLocked );
1580 removeUnitConflicts( aLocked );
1581 }
1582
1583 // Remove annotation only updates the "new" flag to indicate to the algorithm
1584 // that these references must be reannotated, but keeps the original reference
1585 // so that we can reannotate multi-unit symbols together.
1586 if( aResetAnnotation )
1587 aRefs.RemoveAnnotation();
1588
1589 // Build additional list of references to be used during reannotation
1590 // to avoid duplicate designators (no additional references when annotating
1591 // the full schematic)
1592 SCH_REFERENCE_LIST additionalRefs;
1593
1594 if( aScope != ANNOTATE_ALL )
1595 {
1596 SCH_REFERENCE_LIST allRefs;
1597 std::unordered_set<SCH_SYMBOL*> annotatedSymbols;
1598 sheets.GetSymbols( allRefs, SYMBOL_FILTER_NON_POWER );
1599
1600 // The other instances of a renumbered symbol take its new base, so their old one is free
1601 if( suffixMode )
1602 {
1603 for( const SCH_REFERENCE& ref : aRefs )
1604 {
1605 if( !aSchematic.CopiesSelectDifferentUnits( ref.GetSymbol() ) )
1606 annotatedSymbols.insert( ref.GetSymbol() );
1607 }
1608 }
1609
1610 for( const SCH_REFERENCE& ref : allRefs )
1611 {
1612 if( !annotatedSymbols.contains( ref.GetSymbol() ) && !aRefs.Contains( ref ) )
1613 additionalRefs.AddItem( ref );
1614 }
1615 }
1616
1617 if( suffixMode )
1618 aRefs.RenumberBasesUsedBy( additionalRefs, aLocked, sheets );
1619
1620 aRefs.SetRefDesTracker( aSchematic.Settings().m_refDesTracker );
1621
1622 // Break full symbol reference into name (prefix) and number:
1623 // example: IC1 become IC, and 1
1624 aRefs.SplitReferences();
1625 aRefs.AnnotateByOptions( aSortOption, aAlgoOption, aStartNumber, aLocked, additionalRefs, false,
1626 suffixMode ? &sheets : nullptr );
1627
1628 std::set<const SCH_SCREEN*> sharedScreens;
1629
1630 // Annotating changes references, so decide which copies share before any of them do
1631 const std::set<KIID> splitCopies = suffixMode ? aSchematic.SplitUnitSymbols() : std::set<KIID>();
1632
1633 for( SCH_REFERENCE& ref : aRefs )
1634 {
1635 if( aBeforeAnnotate )
1636 aBeforeAnnotate( ref );
1637
1638 ref.Annotate();
1639
1640 if( suffixMode && !splitCopies.contains( ref.GetSymbol()->m_Uuid )
1641 && sheets.ShareReusedSheetRef( ref.GetSymbol(), ref.GetSheetPath() ) > 0 )
1642 {
1643 sharedScreens.insert( ref.GetSheetPath().LastScreen() );
1644 }
1645 }
1646
1647 return sharedScreens;
1648}
int index
const KIID m_Uuid
Definition eda_item.h:599
Define a library symbol object.
Definition lib_symbol.h:114
wxString GetName() const override
Definition lib_symbol.h:183
int GetUnitCount() const override
These are loaded from Eeschema settings but then overwritten by the project settings.
std::shared_ptr< REFDES_TRACKER > m_refDesTracker
A list of previously used schematic reference designators.
Holds all the data relating to one schematic.
Definition schematic.h:155
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.
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_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
std::set< KIID > SplitUnitSymbols() const
Symbols whose copies select different units, for loops that change references as they go.
bool CopiesSelectDifferentUnits(const SCH_SYMBOL *aSymbol) const
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
SCHEMATIC * Schematic() const
Search the item hierarchy to find a SCHEMATIC.
Definition sch_item.cpp:302
int GetUnit() const
Definition sch_item.h:243
Container to create a flattened list of symbols because in a complex hierarchy, a symbol can be used ...
SCH_REFERENCE * FindItem(const SCH_REFERENCE &aItem)
SCH_MULTI_UNIT_REFERENCE_MAP LockedForRepresentatives(const SCH_MULTI_UNIT_REFERENCE_MAP &aLocked) const
Move locked multi-unit groups onto the representatives in this list.
void ReannotateByOptions(ANNOTATE_ORDER_T aSortOption, ANNOTATE_ALGO_T aAlgoOption, int aStartNumber, const SCH_REFERENCE_LIST &aAdditionalRefs, bool aStartAtCurrent, SCH_SHEET_LIST *aHierarchy)
Forces reannotation of the provided references.
static bool sortByRefAndValue(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
static bool sortBySymbolPtr(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
void RenumberBasesUsedBy(const SCH_REFERENCE_LIST &aOthers, const SCH_MULTI_UNIT_REFERENCE_MAP &aLocked, const SCH_SHEET_LIST &aSheets)
Mark unsplit references for renumbering where their kept base would collide once suffix mode copies i...
bool Contains(const SCH_REFERENCE &aItem) const
Return true if aItem exists in this list.
void SortByYCoordinate()
Sort the list of references by Y position.
void SetRefDesTracker(std::shared_ptr< REFDES_TRACKER > aTracker)
std::vector< int > GetPackageUnits(const SCH_REFERENCE &aRef) const
Return the units a locked package needs free when aRef is numbered, which are the units of every memb...
static bool sortByTimeStamp(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
void SortByXCoordinate()
Sort the list of references by X position.
static bool sortByXPosition(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
void AnnotateByOptions(enum ANNOTATE_ORDER_T aSortOption, enum ANNOTATE_ALGO_T aAlgoOption, int aStartNumber, const SCH_MULTI_UNIT_REFERENCE_MAP &aLockedUnitMap, const SCH_REFERENCE_LIST &aAdditionalRefs, bool aStartAtCurrent, const SCH_SHEET_LIST *aSharedSheets=nullptr)
Annotate the references by the provided options.
void UseReusedSheetRepresentatives(const SCH_SHEET_LIST &aSheets)
Replace the references of each reused sheet symbol with one reference on the first instance of its sh...
void SplitReferences()
Attempt to split all reference designators into a name (U) and number (1).
std::shared_ptr< REFDES_TRACKER > m_refDesTracker
A list of previously used reference designators.
void SortByRefAndValue()
Sort the list of references by value.
std::vector< SCH_REFERENCE > m_flatList
static bool sortByReferenceOnly(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
void GetRefsInUse(int aIndex, std::vector< int > &aIdList, int aMinRefId) const
Add all the reference designator numbers greater than aMinRefId to aIdList skipping the reference at ...
void Annotate(bool aUseSheetNum, int aSheetIntervalId, int aStartNumber, const SCH_MULTI_UNIT_REFERENCE_MAP &aLockedUnitMap, const SCH_REFERENCE_LIST &aAdditionalRefs, bool aStartAtCurrent=false, const SCH_SHEET_LIST *aSharedSheets=nullptr)
Set the reference designators in the list that have not been annotated.
int FindRef(const wxString &aRef) const
Search the list for a symbol with a given reference, as shown with its sheet suffix.
int FindFirstUnusedReference(const SCH_REFERENCE &aRef, int aMinValue, const std::vector< int > &aRequiredUnits, const std::map< const SCH_REFERENCE *, std::vector< SCH_REFERENCE > > &aDestinations={}, const SCH_REFERENCE_LIST *aLocked=nullptr) const
Return the first unused reference number from the properties given in aRef, ensuring all of the units...
int FindRefByFullPath(const wxString &aFullPath) const
Search the list for a symbol with the given KIID path (as string).
void RemoveAnnotation()
Treat all symbols in this list as non-annotated.
std::vector< SCH_SYMBOL_INSTANCE > GetSymbolInstances() const
void AddItem(const SCH_REFERENCE &aItem)
void RemoveItem(unsigned int aIndex)
Remove an item from the list of references.
void ReannotateDuplicates(const SCH_REFERENCE_LIST &aAdditionalReferences, ANNOTATE_ALGO_T aAlgoOption)
Convenience function for the Paste Unique functionality.
static bool sortByYPosition(const SCH_REFERENCE &item1, const SCH_REFERENCE &item2)
void UpdateAnnotation()
Update the symbol references for the schematic project (or the current sheet).
int CheckAnnotation(ANNOTATION_ERROR_HANDLER aErrorHandler)
Check for annotations errors.
A helper to define a symbol's reference designator in a schematic.
void SetSymbolExcludedFromBoard(bool aEnable)
const SCH_SHEET_PATH & GetSheetPath() const
void SetSymbolExcludedFromBOM(bool aEnable, const wxString &aVariant=wxEmptyString)
wxString GetComposedRef() const
Return the reference as shown on this sheet path, with its sheet suffix.
SCH_SYMBOL * m_rootSymbol
The symbol associated the reference object.
int m_unit
The unit number for symbol with multiple parts per package.
SCH_SHEET_PATH m_sheetPath
The sheet path for this reference.
wxString m_footprint
The footprint assigned.
const wxString & GetRefSuffix() const
Return the sheet suffix this reference composes with, or empty while it is unannotated.
wxString formatRefStr(int aNumber) const
wxString GetFullRef() const
Return reference name with unit and sheet suffix altogether, as in U12A_M4.
int CompareRef(const SCH_REFERENCE &item) const
wxString m_refSuffix
The suffix the board reference composes with.
void SetRef(const wxString &aReference)
bool AlwaysAnnotate() const
Verify the reference should always be automatically annotated.
wxString m_numRefStr
The numeric part in original string form (may have leading zeroes).
bool m_isNew
True if not yet annotated.
bool GetSymbolExcludedFromBOM(const wxString &aVariant=wxEmptyString) const
void SetUnit(int aUnit)
bool GetSymbolDNP(const wxString &aVariant=wxEmptyString) const
void Split()
Attempt to split the reference designator into a name (U) and number (1).
SCH_SYMBOL * GetSymbol() const
bool GetSymbolExcludedFromPosFiles(const wxString &aVariant=wxEmptyString) const
wxString m_ref
Symbol reference prefix, without number (for IC1, this is IC) )
void SetSymbolExcludedFromSim(bool aEnable, const wxString &aVariant=wxEmptyString)
wxString GetRef() const
int m_sheetNum
The sheet number for the reference.
void SetRefStr(const std::string &aReference)
bool IsSplitNeeded() const
Determine if this reference needs to be split or if it likely already has been.
int m_numRef
The numeric part of the reference designator.
bool GetSymbolExcludedFromBoard() const
LIB_SYMBOL * GetLibPart() const
void SetSheetNumber(int aSheetNumber)
const char * GetRefStr() const
bool IsSameInstance(const SCH_REFERENCE &other) const
Return whether this reference refers to the same symbol instance (symbol and sheet) as another.
int CompareLibId(const SCH_REFERENCE &item) const
KIID m_symbolUuid
UUID of the symbol.
bool GetSymbolExcludedFromSim(const wxString &aVariant=wxEmptyString) const
void SetSymbolExcludedFromPosFiles(bool aEnable, const wxString &aVariant=wxEmptyString)
bool hasRef() const
wxString m_value
The symbol value.
VECTOR2I m_symbolPos
The physical position of the symbol in schematic used to annotate by X or Y position.
wxString GetRefNumber() const
int CompareValue(const SCH_REFERENCE &item) const
void Annotate()
Update the annotation of the symbol according the current object state.
void SetSymbolDNP(bool aEnable, const wxString &aVariant=wxEmptyString)
bool IsSplit() const
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
int ShareReusedSheetRef(SCH_SYMBOL *aSymbol, const SCH_SHEET_PATH &aSource) const
Give every other instance of aSymbol's sheet the base reference and unit it has on aSource.
SCH_SHEET_PATH * FindSheetForPath(const SCH_SHEET_PATH *aPath)
Return a pointer to the first SCH_SHEET_PATH object (not necessarily the only one) matching the provi...
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...
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
SCH_SCREEN * LastScreen()
int Cmp(const SCH_SHEET_PATH &aSheetPathToTest) const
Compare if this is the same sheet path as aSheetPathToTest.
Schematic symbol object.
Definition sch_symbol.h:76
wxString SubReference(int aUnit, bool aAddSeparator=true) const
const wxString GetFootprintFieldText(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, const wxString &aVariantName=wxEmptyString) 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.
void AddHierarchicalReference(const KIID_PATH &aPath, const wxString &aRef, int aUnit)
Add a full hierarchical reference to this symbol.
VECTOR2I GetPosition() const override
Definition sch_symbol.h:958
bool GetInstance(SCH_SYMBOL_INSTANCE &aInstance, const KIID_PATH &aSheetPath, bool aTestFromEnd=false) const
const wxString GetValue(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, 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.
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.
@ RAW_VALUE
Definition common.h:98
@ RESOLVED
Definition common.h:97
#define _(s)
@ ERCE_UNANNOTATED
Symbol has not been annotated.
@ ERCE_DUPLICATE_REFERENCE
More than one symbol with the same reference.
@ ERCE_EXTRA_UNITS
Symbol has more units than are defined.
@ ERCE_DIFFERENT_UNIT_VALUE
Units of same symbol have different values.
void remove_duplicates(_Container &__c)
Deletes all duplicate values from __c.
Definition kicad_algo.h:157
static std::pair< const SCH_SYMBOL *, KIID_PATH > packageMemberKey(const SCH_REFERENCE &aRef)
wxString buildFullReference(const SCH_REFERENCE &aItem, int aUnitNumber=-1)
static void removeUnitConflicts(SCH_MULTI_UNIT_REFERENCE_MAP &aLocked)
static bool sharesReusedBase(const SCH_REFERENCE &aRef)
std::function< void(ERCE_T aType, const wxString &aMsg, SCH_REFERENCE *aItemA, SCH_REFERENCE *aItemB)> ANNOTATION_ERROR_HANDLER
Define a standard error handler for annotation errors.
ANNOTATE_ORDER_T
Schematic annotation order options.
@ UNSORTED
Annotate by position of symbol in the schematic sheet object list.
@ SORT_BY_X_POSITION
Annotate by X position from left to right.
@ SORT_BY_Y_POSITION
Annotate by Y position from top to bottom.
ANNOTATE_SCOPE_T
Schematic annotation scope options.
@ ANNOTATE_ALL
Annotate the full schematic.
ANNOTATE_ALGO_T
Schematic annotation type options.
@ SHEET_NUMBER_X_1000
Annotate using the first free reference number starting at the sheet number * 1000.
@ INCREMENTAL_BY_REF
Annotate incrementally using the first free reference number.
@ SHEET_NUMBER_X_100
Annotate using the first free reference number starting at the sheet number * 100.
void AnnotateNewSymbol(SCH_SYMBOL *aSymbol, const std::vector< SCH_SHEET_PATH > &aPaths, SCH_REFERENCE_LIST &aExistingRefs, const SCHEMATIC_SETTINGS &aSettings, SCH_SHEET_LIST *aHierarchy)
Annotate a newly placed symbol on each of aPaths in turn, avoiding aExistingRefs and adding the resul...
std::optional< std::pair< SCH_SHEET_PATH, SCH_SHEET_PATH > > FindRefSuffixCollision(const SCH_REFERENCE_LIST &aRefs, const SCHEMATIC &aSchematic)
Find two instances of a reused sheet that aRefs reaches and that compose the same reference suffix.
std::set< const SCH_SCREEN * > AnnotateReferences(SCH_REFERENCE_LIST &aRefs, SCH_MULTI_UNIT_REFERENCE_MAP aLocked, const SCHEMATIC &aSchematic, ANNOTATE_SCOPE_T aScope, ANNOTATE_ORDER_T aSortOption, ANNOTATE_ALGO_T aAlgoOption, int aStartNumber, bool aResetAnnotation, const std::function< void(SCH_REFERENCE &)> &aBeforeAnnotate={})
Annotate aRefs, the references in aScope, around every other symbol of aSchematic.
std::map< wxString, SCH_REFERENCE_LIST > SCH_MULTI_UNIT_REFERENCE_MAP
Container to map reference designators for multi-unit parts.
@ SYMBOL_FILTER_NON_POWER
@ SYMBOL_FILTER_ALL
int StrNumCmp(const wxString &aString1, const wxString &aString2, CMP_T aCaseSensitivity)
Compare two strings with alphanumerical content.
wxString From_UTF8(const char *cstring)
@ CASE_SENSITIVE
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
A simple container for schematic symbol instance information.
@ REFERENCE
Field Reference of part, i.e. "IC21".
std::string path
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.