KiCad PCB EDA Suite
Loading...
Searching...
No Matches
lib_symbol.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) 2004-2015 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 2022 CERN
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23
24#include "lib_symbol.h"
25
26#include <algorithm>
27#include <functional>
28#include <memory>
29#include <unordered_map>
30#include <unordered_set>
31
32#include <advanced_config.h>
33#include <font/outline_font.h>
34#include <jumper_group.h>
35#include <sch_draw_panel.h>
36#include <plotters/plotter.h>
37#include <sch_screen.h>
38#include <template_fieldnames.h>
39#include <transform.h>
41#include <sch_pin.h>
42#include <sch_render_settings.h>
43#include <sch_shape.h>
44#include <trace_helpers.h>
45#include <common.h>
46
47#include <api/api_enums.h>
48#include <api/api_sch_utils.h>
49#include <api/api_utils.h>
50#include <api/schematic/schematic_types.pb.h>
51
53
54// TODO(JE) remove m_library; shouldn't be needed with legacy remapping
56
57#include <properties/property.h>
59
60
68static std::shared_ptr<LIB_SYMBOL> GetSafeRootSymbol( const LIB_SYMBOL* aSymbol, const char* aCallerName )
69{
70 std::set<const LIB_SYMBOL*> visited;
71 visited.insert( aSymbol );
72
73 std::shared_ptr<LIB_SYMBOL> current = aSymbol->SharedPtr();
74 std::shared_ptr<LIB_SYMBOL> parent = aSymbol->GetParent().lock();
75
76 while( parent )
77 {
78 if( visited.count( parent.get() ) )
79 {
80 // Build chain description for logging
81 wxString chain = aSymbol->GetName();
82
83 for( const LIB_SYMBOL* sym : visited )
84 {
85 if( sym != aSymbol )
86 chain += wxT( " -> " ) + sym->GetName();
87 }
88
89 chain += wxT( " -> " ) + parent->GetName() + wxT( " (CYCLE)" );
90
91 wxLogTrace( traceSymbolInheritance,
92 wxT( "%s: Circular inheritance detected in symbol '%s' (lib: %s). Chain: %s" ),
93 aCallerName,
94 aSymbol->GetName(),
95 aSymbol->GetLibId().GetLibNickname().wx_str(),
96 chain );
97
98 // Return current (last valid symbol before cycle)
99 return current;
100 }
101
102 visited.insert( parent.get() );
103 current = parent;
104 parent = parent->GetParent().lock();
105 }
106
107 return current;
108}
109
110
111wxString LIB_SYMBOL::getShownDescription( RESOLUTION_CONTEXT aContext, int aDepth ) const
112{
113 wxString shownText = GetDescriptionField().GetShownText( aContext, aDepth );
114
115 if( shownText.IsEmpty() && IsDerived() )
116 {
117 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
118
119 if( root.get() != this )
120 shownText = root->GetDescriptionField().GetShownText( aContext, aDepth );
121 }
122
123 return shownText;
124}
125
126
127wxString LIB_SYMBOL::GetShownDescription( RESOLUTION_CONTEXT aContext, int aDepth ) const
128{
129 if( aContext == FOR_GUI )
130 {
131 if( m_cachesDirty )
133
135 }
136
137 return getShownDescription( aContext, aDepth );
138}
139
140
142{
143 m_cachesDirty = false;
144
145 //
146 // m_shownDescriptionCache
147 //
149
150 //
151 // m_chooserFieldsCache
152 //
153 m_chooserFieldsCache.clear();
154
155 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
156 {
157 const SCH_FIELD* field = static_cast<const SCH_FIELD*>( &item );
158
159 if( field->ShowInChooser() )
160 m_chooserFieldsCache[field->GetName()] = field->EDA_TEXT::GetShownText( FOR_GUI );
161 }
162
163 // If the user has a field named "Keywords", then prefer that. Otherwise add the KiCad
164 // keywords.
165 const wxString localizedKeywords = _( "Keywords" );
166
167 if( !m_chooserFieldsCache.contains( localizedKeywords ) )
168 m_chooserFieldsCache[localizedKeywords] = GetShownKeyWords( FOR_GUI );
169
170 //
171 // m_pinCountCache
172 //
173 m_pinCountCache = 0;
174
175 for( SCH_PIN* pin : GetGraphicalPins( 0 /* all units */, 1 /* single body style */ ) )
176 {
177 int pinCount = pin->GetStackedPinCount();
178 m_pinCountCache += pinCount;
179 }
180
181 //
182 // m_searchTermsCache
183 //
184 m_searchTermsCache.clear();
185 m_searchTermsCache.reserve( 6 );
186
187 // Order matters, see SEARCH_TERM_CACHE_INDEX
188 m_searchTermsCache.emplace_back( SEARCH_TERM( GetLibNickname(), 4 ) );
189 m_searchTermsCache.emplace_back( SEARCH_TERM( GetName(), 8, true ) );
190 m_searchTermsCache.emplace_back( SEARCH_TERM( GetLIB_ID().Format(), 16, true ) );
191
192 wxStringTokenizer keywordTokenizer( GetShownKeyWords( FOR_GUI ), " \t\r\n", wxTOKEN_STRTOK );
193
194 while( keywordTokenizer.HasMoreTokens() )
195 m_searchTermsCache.emplace_back( SEARCH_TERM( keywordTokenizer.GetNextToken(), 4 ) );
196
197 // Also include keywords as one long string, just in case
200
201 // Add relational term for unit count
202 m_searchTermsCache.emplace_back( SEARCH_TERM( wxString::Format( wxT( "units=%d" ), GetUnitCount() ), 1 ) );
203
204 wxString footprint = GetFootprint();
205
206 if( !footprint.IsEmpty() )
207 m_searchTermsCache.emplace_back( SEARCH_TERM( footprint, 1 ) );
208}
209
210
211void LIB_SYMBOL::SetDescription( const wxString& aDescription )
212{
213 GetDescriptionField().SetText( aDescription );
214 m_cachesDirty = true;
215}
216
217
218void LIB_SYMBOL::SetKeyWords( const wxString& aKeyWords )
219{
220 m_keyWords = aKeyWords;
221 m_cachesDirty = true;
222}
223
224
225wxString LIB_SYMBOL::GetShownKeyWords( RESOLUTION_CONTEXT aContext, int aDepth ) const
226{
227 if( aContext == RAW_VALUE )
228 return GetKeyWords();
229
230 wxString text = GetKeyWords();
231
232 std::function<bool( wxString* )> libSymbolResolver =
233 [&]( wxString* token ) -> bool
234 {
235 return ResolveTextVar( token, aDepth + 1 );
236 };
237
238 text = ResolveTextVars( text, &libSymbolResolver, aDepth );
239
240 return text;
241}
242
243
244std::vector<SEARCH_TERM>& LIB_SYMBOL::GetSearchTerms()
245{
246 if( m_cachesDirty )
248
249 return m_searchTermsCache;
250}
251
252
253void LIB_SYMBOL::GetChooserFields( std::map<wxString, wxString>& aColumnMap )
254{
255 if( m_cachesDirty )
257
258 aColumnMap = m_chooserFieldsCache;
259}
260
261
262bool operator<( const LIB_SYMBOL& aItem1, const LIB_SYMBOL& aItem2 )
263{
264 return aItem1.GetName() < aItem2.GetName();
265}
266
267
270{
271 void operator()( void const* ) const {}
272};
273
274
275LIB_SYMBOL::LIB_SYMBOL( const wxString& aName, LIB_SYMBOL* aParent, LEGACY_SYMBOL_LIB* aLibrary ) :
277 m_me( this, null_deleter() )
278{
279 m_lastModDate = 0;
280 m_unitCount = 1;
281 m_demorgan = false;
284 m_unitsLocked = false;
286 m_library = nullptr;
287
288 auto addField =
289 [&]( FIELD_T id, bool visible )
290 {
291 SCH_FIELD* field = new SCH_FIELD( this, id );
292 field->SetVisible( visible );
293 m_drawings[SCH_FIELD_T].push_back( field );
294 };
295
296 // construct only the mandatory fields
297 addField( FIELD_T::REFERENCE, true );
298 addField( FIELD_T::VALUE, true );
299 addField( FIELD_T::FOOTPRINT, false );
300 addField( FIELD_T::DATASHEET, false );
301 addField( FIELD_T::DESCRIPTION, false );
302
303 SetName( aName );
304 SetParent( aParent );
305 SetLib( aLibrary );
306
307 m_cachesDirty = true;
308}
309
310
311LIB_SYMBOL::LIB_SYMBOL( const LIB_SYMBOL& aSymbol, LEGACY_SYMBOL_LIB* aLibrary, bool aCopyEmbeddedFiles ) :
312 SYMBOL( aSymbol ),
313 EMBEDDED_FILES( aSymbol, aCopyEmbeddedFiles ),
314 m_me( this, null_deleter() )
315{
316 m_library = aLibrary;
317 m_name = aSymbol.m_name;
318 m_fpFilters = wxArrayString( aSymbol.m_fpFilters );
319 m_pinMaps = aSymbol.m_pinMaps;
321 m_unitCount = aSymbol.m_unitCount;
322 m_demorgan = aSymbol.m_demorgan;
325 m_options = aSymbol.m_options;
326 m_libId = aSymbol.m_libId;
327 m_keyWords = aSymbol.m_keyWords;
328
331
333 // Raw member, not the accessor, which would bake a root's body styles into a derived copy
335
337
338 for( const SCH_ITEM& oldItem : aSymbol.m_drawings )
339 {
340 if( ( oldItem.GetFlags() & ( IS_NEW | STRUCT_DELETED ) ) != 0 )
341 continue;
342
343 try
344 {
345 SCH_ITEM* newItem = (SCH_ITEM*) oldItem.Clone();
346 newItem->ClearSelected();
347 newItem->SetParent( this );
348 m_drawings.push_back( newItem );
349 }
350 catch( ... )
351 {
352 wxFAIL_MSG( "Failed to clone SCH_ITEM." );
353 return;
354 }
355 }
356
357 SetParent( aSymbol.m_parent.lock().get() );
358 m_cachesDirty = true;
359}
360
361
362void LIB_SYMBOL::Serialize( kiapi::schematic::types::SchematicSymbol& aOutput, bool aSkipPins ) const
363{
364 using namespace kiapi::common;
365 using namespace kiapi::schematic::types;
366
367 SchematicSymbol& def = aOutput;
368 def.Clear();
369 PackLibId( def.mutable_id(), m_libId );
370
371 SchematicSymbolType symbolType = SchematicSymbolType::SST_NORMAL;
372
373 if( IsGlobalPower() )
374 symbolType = SchematicSymbolType::SST_GLOBAL_POWER;
375 else if( IsLocalPower() )
376 symbolType = SchematicSymbolType::SST_LOCAL_POWER;
377
378 def.set_type( symbolType );
379
380 SchematicSymbolAttributes* attributes = def.mutable_attributes();
381 attributes->set_exclude_from_simulation( GetExcludedFromSim() );
382 attributes->set_exclude_from_bill_of_materials( GetExcludedFromBOM() );
383 attributes->set_exclude_from_board( GetExcludedFromBoard() );
384 attributes->set_exclude_from_position_files( GetExcludedFromPosFiles() );
385 attributes->set_do_not_populate( GetDNP() );
386
387 GetField( FIELD_T::REFERENCE )->Serialize( *def.mutable_reference_field(), schIUScale );
388 GetField( FIELD_T::VALUE )->Serialize( *def.mutable_value_field(), schIUScale );
389 GetField( FIELD_T::FOOTPRINT )->Serialize( *def.mutable_footprint_field(), schIUScale );
390 GetField( FIELD_T::DATASHEET )->Serialize( *def.mutable_datasheet_field(), schIUScale );
391 GetField( FIELD_T::DESCRIPTION )->Serialize( *def.mutable_description_field(), schIUScale );
392
393 for( const SCH_ITEM& drawItem : GetDrawItems() )
394 {
395 if( drawItem.Type() == SCH_FIELD_T && static_cast<const SCH_FIELD&>( drawItem ).IsMandatory() )
396 continue;
397
398 if( aSkipPins && drawItem.Type() == SCH_PIN_T )
399 continue;
400
401 SchematicSymbolChild* item = def.add_items();
402 item->mutable_unit()->set_unit( drawItem.GetUnit() );
403 item->mutable_body_style()->set_style( drawItem.GetBodyStyle() );
404 item->set_is_private( drawItem.IsPrivate() );
405 drawItem.Serialize( *item->mutable_item() );
406 }
407
408 def.set_unit_count( GetUnitCount() );
409
410 for( int bodyStyle = BODY_STYLE::BASE; bodyStyle <= GetBodyStyleCount(); ++bodyStyle )
411 def.add_body_style()->set_name( GetBodyStyleDescription( bodyStyle, false ).ToUTF8() );
412
413 def.set_keywords( GetKeyWords().ToUTF8() );
414
415 for( const wxString& filter : GetFPFilters() )
416 def.add_footprint_filters( filter.ToUTF8() );
417
418 JumperSettings* jumpers = def.mutable_jumpers();
419 jumpers->set_duplicate_names_are_jumpered( GetDuplicatePinNumbersAreJumpers() );
420
421 for( const JUMPER_GROUP& group : JumperPinGroups().GetAll() )
422 {
423 JumperGroup* jumperGroup = jumpers->add_groups();
424
425 for( const wxString& pinNumber : group.GetNames() )
426 jumperGroup->add_pin_numbers( pinNumber.ToUTF8() );
427 }
428
429 def.set_units_locked( UnitsLocked() );
430 def.set_embedded_fonts( GetAreFontsEmbedded() );
431 def.set_show_pin_numbers( GetShowPinNumbers() );
432 def.set_show_pin_names( GetShowPinNames() );
433 PackDistance( *def.mutable_pin_name_offset(), GetPinNameOffset(), schIUScale );
434
435 // Derived symbols are serialized flattened (the inherited drawings are resolved into
436 // items above), but the inheritance relationship itself is still worth reporting.
437 if( !m_parentName.IsEmpty() )
438 {
439 LIB_ID parentId = m_libId;
440 parentId.SetLibItemName( m_parentName );
441 PackLibId( def.mutable_extends(), parentId );
442 }
443
444 for( const auto& [unit, displayName] : GetUnitDisplayNames() )
445 {
446 SchematicUnitDisplayName* protoName = def.add_unit_display_names();
447 protoName->set_unit( unit );
448 protoName->set_name( displayName.ToUTF8() );
449 }
450
451 SymbolPinMaps* pinMaps = def.mutable_pin_maps();
452
454 {
455 AssociatedFootprint* a = pinMaps->add_associated_footprints();
456 PackLibId( a->mutable_footprint(), assoc.m_FootprintLibId );
457 a->set_map_name( assoc.m_MapName.ToUTF8() );
458 }
459
460 for( const PIN_MAP& map : GetEffectivePinMaps().GetAll() )
461 {
462 PinMap* m = pinMaps->add_pin_maps();
463 m->set_name( map.GetName().ToUTF8() );
464
465 for( const PIN_MAP_ENTRY& entry : map.GetEntries() )
466 {
467 PinMapEntry* e = m->add_entries();
468 e->set_pin_number( entry.m_PinNumber.ToUTF8() );
469 e->set_pad_number( entry.m_PadNumber.ToUTF8() );
470 }
471 }
472}
473
474
475void LIB_SYMBOL::Serialize( google::protobuf::Any& aContainer ) const
476{
477 kiapi::schematic::types::SchematicSymbol def;
478 Serialize( def );
479
480 if( !aContainer.PackFrom( def ) )
481 wxFAIL_MSG( wxT( "Failed to pack LIB_SYMBOL" ) );
482}
483
484
485bool LIB_SYMBOL::Deserialize( const kiapi::schematic::types::SchematicSymbol& aInput )
486{
487 using namespace kiapi::common;
488 using namespace kiapi::common::types;
489 using namespace kiapi::schematic::types;
490
491 const SchematicSymbol& def = aInput;
492
493 LIB_ID libId = UnpackLibId( def.id() );
494 SetLibId( libId );
495
496 switch( def.type() )
497 {
498 case SchematicSymbolType::SST_GLOBAL_POWER: SetGlobalPower(); break;
499 case SchematicSymbolType::SST_LOCAL_POWER: SetLocalPower(); break;
500 default: break;
501 }
502
503 if( def.has_attributes() )
504 {
505 SetExcludedFromSim( def.attributes().exclude_from_simulation() );
506 SetExcludedFromBOM( def.attributes().exclude_from_bill_of_materials() );
507 SetExcludedFromBoard( def.attributes().exclude_from_board() );
508 SetExcludedFromPosFiles( def.attributes().exclude_from_position_files() );
509 SetDNP( def.attributes().do_not_populate() );
510 }
511
512 GetField( FIELD_T::REFERENCE )->Deserialize( def.reference_field(), schIUScale );
513 GetField( FIELD_T::VALUE )->Deserialize( def.value_field(), schIUScale );
514 GetField( FIELD_T::FOOTPRINT )->Deserialize( def.footprint_field(), schIUScale );
515 GetField( FIELD_T::DATASHEET )->Deserialize( def.datasheet_field(), schIUScale );
516 GetField( FIELD_T::DESCRIPTION )->Deserialize( def.description_field(), schIUScale );
517
518 for( const SchematicSymbolChild& child : def.items() )
519 {
520 std::optional<KICAD_T> type = TypeNameFromAny( child.item() );
521
522 if( !type )
523 continue;
524
525 std::unique_ptr<EDA_ITEM> item = CreateItemForType( *type, this );
526
527 if( !item || !item->Deserialize( child.item() ) )
528 continue;
529
530 SCH_ITEM* schItem = static_cast<SCH_ITEM*>( item.release() );
531
532 if( child.has_unit() )
533 schItem->SetUnit( child.unit().unit() );
534
535 if( child.has_body_style() )
536 schItem->SetBodyStyle( child.body_style().style() );
537
538 schItem->SetLayer( LAYER_DEVICE );
539 schItem->SetPrivate( child.is_private() );
540 AddDrawItem( schItem, false );
541 }
542
543 if( def.unit_count() > 0 )
544 SetUnitCount( def.unit_count(), false );
545
546 if( def.body_style_size() > 0 )
547 {
548 std::vector<wxString> bodyStyleNames;
549
550 for( const SchematicBodyStyle& bodyStyle : def.body_style() )
551 bodyStyleNames.emplace_back( wxString::FromUTF8( bodyStyle.name() ) );
552
553 SetBodyStyleNames( bodyStyleNames );
554 SetBodyStyleCount( static_cast<int>( bodyStyleNames.size() ), false, false );
555 }
556
557 if( !def.keywords().empty() )
558 SetKeyWords( wxString::FromUTF8( def.keywords() ) );
559
560 if( def.footprint_filters_size() > 0 )
561 {
562 wxArrayString filters;
563
564 for( const std::string& filter : def.footprint_filters() )
565 filters.Add( wxString::FromUTF8( filter ) );
566
568 }
569
570 SetDuplicatePinNumbersAreJumpers( def.jumpers().duplicate_names_are_jumpered() );
571
572 JUMPER_GROUP_SET& jumperGroups = JumperPinGroups();
573 jumperGroups.Clear();
574
575 for( const JumperGroup& group : def.jumpers().groups() )
576 {
577 std::set<wxString> pinNumbers;
578
579 for( const std::string& pinNumber : group.pin_numbers() )
580 pinNumbers.insert( wxString::FromUTF8( pinNumber ) );
581
582 jumperGroups.Add( std::move( pinNumbers ) );
583 }
584
585 LockUnits( def.units_locked() );
586 SetAreFontsEmbedded( def.embedded_fonts() );
587
588 for( const SchematicUnitDisplayName& displayName : def.unit_display_names() )
589 GetUnitDisplayNames()[displayName.unit()] = wxString::FromUTF8( displayName.name() );
590
591 SetShowPinNumbers( def.show_pin_numbers() );
592 SetShowPinNames( def.show_pin_names() );
593
594 if( def.has_pin_name_offset() )
595 SetPinNameOffset( UnpackDistance( def.pin_name_offset(), schIUScale ) );
596
597 if( def.has_extends() )
598 SetParentName( wxString::FromUTF8( def.extends().entry_name() ) );
599
600 if( def.has_pin_maps() )
601 {
602 PIN_MAP_SET pinMapSet;
603
604 for( const PinMap& map : def.pin_maps().pin_maps() )
605 {
606 PIN_MAP pinMap( wxString::FromUTF8( map.name() ) );
607
608 for( const PinMapEntry& entry : map.entries() )
609 {
610 pinMap.SetEntry( wxString::FromUTF8( entry.pin_number() ), wxString::FromUTF8( entry.pad_number() ) );
611 }
612
613 pinMapSet.AddOrReplace( std::move( pinMap ) );
614 }
615
616 std::vector<ASSOCIATED_FOOTPRINT> associatedFootprints;
617
618 for( const AssociatedFootprint& footprint : def.pin_maps().associated_footprints() )
619 {
621 assoc.m_FootprintLibId = UnpackLibId( footprint.footprint() );
622 assoc.m_MapName = wxString::FromUTF8( footprint.map_name() );
623 associatedFootprints.push_back( std::move( assoc ) );
624 }
625
626 SetPinMaps( pinMapSet );
627 SetAssociatedFootprints( std::move( associatedFootprints ) );
628 }
629
630 m_cachesDirty = true;
631 return true;
632}
633
634
635bool LIB_SYMBOL::Deserialize( const google::protobuf::Any& aContainer )
636{
637 kiapi::schematic::types::SchematicSymbol def;
638
639 if( !aContainer.UnpackTo( &def ) )
640 return false;
641
642 return Deserialize( def );
643}
644
645
647{
648 if( &aSymbol == this )
649 return aSymbol;
650
651 SYMBOL::operator=( aSymbol );
652
653 m_library = aSymbol.m_library;
654 m_name = aSymbol.m_name;
655 m_fpFilters = wxArrayString( aSymbol.m_fpFilters );
656 m_pinMaps = aSymbol.m_pinMaps;
658 m_unitCount = aSymbol.m_unitCount;
659 m_demorgan = aSymbol.m_demorgan;
662 m_options = aSymbol.m_options;
663 m_libId = aSymbol.m_libId;
664 m_keyWords = aSymbol.m_keyWords;
665
668
670 // Raw member, not the accessor, which would bake a root's body styles into a derived copy
672
673 m_drawings.clear();
674
675 for( const SCH_ITEM& oldItem : aSymbol.m_drawings )
676 {
677 if( ( oldItem.GetFlags() & ( IS_NEW | STRUCT_DELETED ) ) != 0 )
678 continue;
679
680 SCH_ITEM* newItem = (SCH_ITEM*) oldItem.Clone();
681 newItem->SetParent( this );
682 m_drawings.push_back( newItem );
683 }
684
685 m_drawings.sort();
686
687 SetParent( aSymbol.m_parent.lock().get() );
688
689 EMBEDDED_FILES::operator=( aSymbol );
690
691 m_cachesDirty = true;
692
693 return *this;
694}
695
696
703{
704 static LIB_SYMBOL* symbol;
705
706 if( !symbol )
707 {
708 symbol = new LIB_SYMBOL( wxEmptyString );
709
711
712 square->SetPosition( VECTOR2I( schIUScale.MilsToIU( -200 ), schIUScale.MilsToIU( 200 ) ) );
713 square->SetEnd( VECTOR2I( schIUScale.MilsToIU( 200 ), schIUScale.MilsToIU( -200 ) ) );
714 symbol->AddDrawItem( square );
715
716 SCH_TEXT* text = new SCH_TEXT( { 0, 0 }, wxT( "??" ), LAYER_DEVICE );
717
718 text->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 150 ), schIUScale.MilsToIU( 150 ) ) );
719 symbol->AddDrawItem( text );
720 }
721
722 return symbol;
723}
724
725
727{
728 unsigned depth = 0;
729 std::set<const LIB_SYMBOL*> visited;
730 visited.insert( this );
731
732 std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock();
733
734 while( parent )
735 {
736 // Cycle detected - parent chain points back to an already visited symbol
737 if( visited.count( parent.get() ) )
738 {
739 wxLogTrace( traceSymbolInheritance,
740 wxT( "GetInheritanceDepth: Circular inheritance detected in symbol '%s' "
741 "(lib: %s)" ),
742 m_name, m_libId.GetLibNickname().wx_str() );
743 break;
744 }
745
746 visited.insert( parent.get() );
747 depth++;
748 parent = parent->m_parent.lock();
749 }
750
751 return depth;
752}
753
754
755std::shared_ptr<LIB_SYMBOL> LIB_SYMBOL::GetRootSymbol() const
756{
757 std::set<const LIB_SYMBOL*> visited;
758 visited.insert( this );
759
760 std::shared_ptr<LIB_SYMBOL> current = m_me;
761 std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock();
762
763 while( parent )
764 {
765 // Cycle detected - parent chain points back to an already visited symbol
766 if( visited.count( parent.get() ) )
767 {
768 wxLogTrace( traceSymbolInheritance,
769 wxT( "GetRootSymbol: Circular inheritance detected in symbol '%s' "
770 "(lib: %s)" ),
771 m_name, m_libId.GetLibNickname().wx_str() );
772 break;
773 }
774
775 visited.insert( parent.get() );
776 current = parent;
777 parent = parent->m_parent.lock();
778 }
779
780 return current;
781}
782
783
785{
786 if( IsDerived() )
787 {
788 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
789
790 if( root.get() != this )
791 return root->m_unitsLocked;
792 }
793
794 return m_unitsLocked;
795}
796
797
798wxString LIB_SYMBOL::GetUnitDisplayName( int aUnit, bool aLabel ) const
799{
800 const LIB_SYMBOL* owner = this;
801 std::shared_ptr<LIB_SYMBOL> root;
802
803 if( IsDerived() )
804 {
805 root = GetSafeRootSymbol( this, __FUNCTION__ );
806 owner = root.get();
807 }
808
809 if( owner->m_unitDisplayNames.contains( aUnit ) )
810 return owner->m_unitDisplayNames.at( aUnit );
811 else if( aLabel )
812 return wxString::Format( _( "Unit %s" ), LIB_SYMBOL::LetterSubReference( aUnit, 'A' ) );
813 else
814 return LIB_SYMBOL::LetterSubReference( aUnit, 'A' );
815}
816
817
818wxString LIB_SYMBOL::GetBodyStyleDescription( int aBodyStyle, bool aLabel ) const
819{
821 {
822 if( aBodyStyle == BODY_STYLE::DEMORGAN )
823 return aLabel ? _( "Alternate" ) : wxString( _HKI( "Alternate" ) );
824 else if( aBodyStyle == BODY_STYLE::BASE )
825 return aLabel ? _( "Standard" ) : wxString( _HKI( "Standard" ) );
826 }
827 else if( IsMultiBodyStyle() )
828 {
829 const std::vector<wxString>& names = GetBodyStyleNames();
830
831 // Draw items common to every body style carry a body style of 0
832 if( aBodyStyle >= BODY_STYLE::BASE && aBodyStyle <= (int) names.size() )
833 return names[aBodyStyle - 1];
834 }
835
836 return wxT( "?" );
837}
838
839
840void LIB_SYMBOL::SetName( const wxString& aName )
841{
842 m_name = aName;
843 m_libId.SetLibItemName( aName );
844
845 m_cachesDirty = true;
846}
847
848
849void LIB_SYMBOL::SetLibId( const LIB_ID& aLibId )
850{
851 m_libId = aLibId;
852
853 m_cachesDirty = true;
854}
855
856
858{
859 if( aParent )
860 {
861 // Prevent circular inheritance by checking if aParent is derived from this symbol
862 std::set<const LIB_SYMBOL*> visited;
863 visited.insert( this );
864
865 std::shared_ptr<LIB_SYMBOL> ancestor = aParent->SharedPtr();
866
867 while( ancestor )
868 {
869 if( visited.count( ancestor.get() ) )
870 {
871 wxLogTrace( traceSymbolInheritance, wxT( "SetParent: Rejecting parent '%s' for symbol '%s' "
872 "- would create circular inheritance (lib: %s)" ),
873 aParent->GetName(), m_name, m_libId.GetLibNickname().wx_str() );
874
875 // Don't set the parent - it would create circular inheritance
876 return;
877 }
878
879 visited.insert( ancestor.get() );
880 ancestor = ancestor->m_parent.lock();
881 }
882
883 m_parent = aParent->SharedPtr();
884
885 // Keep the recorded parent name in sync so serialization never has to dereference the live
886 // parent pointer (which can dangle, see SCH_IO_KICAD_SEXPR_LIB_CACHE::SaveSymbol).
887 m_parentName = aParent->GetName();
888 }
889 else
890 {
891 // Only drop the live pointer. The recorded parent name is left untouched so a derived
892 // symbol whose live parent has been lost can still be serialized by name.
893 m_parent.reset();
894 }
895
896 m_cachesDirty = true;
897}
898
899
901{
902 const SCH_FIELD* field = GetField( FIELD_T::FOOTPRINT );
903
904 if( !field )
905 return wxEmptyString;
906
907 // Placing a derived symbol inherits the parent's footprint the same way the description,
908 // keywords and filters do, so reporting none here disagrees with what lands on the schematic
909 if( field->GetText().IsEmpty() && IsDerived() )
910 {
911 if( std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock() )
912 return parent->GetFootprint();
913 }
914
915 return field->GetShownText( INTERNAL );
916}
917
918
919std::unique_ptr<LIB_SYMBOL> LIB_SYMBOL::Flatten() const
920{
921 std::unique_ptr<LIB_SYMBOL> retv;
922
923 if( IsDerived() )
924 {
925 // Build parent chain with cycle detection - collect from this symbol up to root
926 std::vector<const LIB_SYMBOL*> parentChain;
927 std::set<const LIB_SYMBOL*> visited;
928 visited.insert( this );
929
930 std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock();
931
932 wxCHECK_MSG( parent, retv, wxString::Format( "Parent of derived symbol '%s' undefined", m_name ) );
933
934 while( parent )
935 {
936 // Cycle detected - parent chain points back to an already visited symbol
937 if( visited.count( parent.get() ) )
938 {
939 wxLogTrace( traceSymbolInheritance,
940 wxT( "Flatten: Circular inheritance detected in symbol '%s' (lib: %s)" ),
941 m_name, m_libId.GetLibNickname().wx_str() );
942 break;
943 }
944
945 visited.insert( parent.get() );
946 parentChain.push_back( parent.get() );
947 parent = parent->m_parent.lock();
948 }
949
950 // Start with the root (last in chain) and work down
951 if( !parentChain.empty() )
952 {
953 retv = std::make_unique<LIB_SYMBOL>( *parentChain.back() );
954
955 // Apply each derived symbol's overrides from root down (skip the root itself)
956 for( int i = static_cast<int>( parentChain.size() ) - 2; i >= 0; --i )
957 {
958 const LIB_SYMBOL* derived = parentChain[i];
959
960 // Overwrite parent's mandatory fields for fields which are defined in derived.
961 for( FIELD_T fieldId : MANDATORY_FIELDS )
962 {
963 if( !derived->GetField( fieldId )->GetText().IsEmpty() )
964 *retv->GetField( fieldId ) = *derived->GetField( fieldId );
965 }
966
967 // Grab all the rest of derived symbol fields.
968 for( const SCH_ITEM& item : derived->m_drawings[SCH_FIELD_T] )
969 {
970 const SCH_FIELD* field = static_cast<const SCH_FIELD*>( &item );
971
972 if( field->IsMandatory() )
973 continue;
974
975 SCH_FIELD* newField = new SCH_FIELD( *field );
976 newField->SetParent( retv.get() );
977
978 SCH_FIELD* parentField = retv->GetField( field->GetName() );
979
980 if( !parentField )
981 {
982 retv->AddDrawItem( newField );
983 }
984 else
985 {
986 retv->RemoveDrawItem( parentField );
987 retv->AddDrawItem( newField );
988 }
989 }
990
991 if( !derived->m_keyWords.IsEmpty() )
992 retv->SetKeyWords( derived->m_keyWords );
993
994 if( !derived->m_fpFilters.IsEmpty() )
995 retv->SetFPFilters( derived->m_fpFilters );
996 }
997 }
998 else
999 {
1000 // Cycle detected at immediate parent level - just copy this symbol
1001 retv = std::make_unique<LIB_SYMBOL>( *this );
1002 retv->m_parent.reset();
1003 return retv;
1004 }
1005
1006 // Now apply this symbol's overrides (the original "this" symbol)
1007 retv->m_name = m_name;
1008 retv->SetLibId( m_libId );
1009
1010 // Overwrite parent's mandatory fields for fields which are defined in this.
1011 for( FIELD_T fieldId : MANDATORY_FIELDS )
1012 {
1013 if( !GetField( fieldId )->GetText().IsEmpty() )
1014 *retv->GetField( fieldId ) = *GetField( fieldId );
1015 }
1016
1017 // Grab all the rest of derived symbol fields.
1018 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
1019 {
1020 const SCH_FIELD* field = static_cast<const SCH_FIELD*>( &item );
1021
1022 // Mandatory fields were already resolved.
1023 if( field->IsMandatory() )
1024 continue;
1025
1026 SCH_FIELD* newField = new SCH_FIELD( *field );
1027 newField->SetParent( retv.get() );
1028
1029 SCH_FIELD* parentField = retv->GetField( field->GetName() );
1030
1031 if( !parentField ) // Derived symbol field does not exist in parent symbol.
1032 {
1033 retv->AddDrawItem( newField );
1034 }
1035 else // Derived symbol field overrides the parent symbol field.
1036 {
1037 retv->RemoveDrawItem( parentField );
1038 retv->AddDrawItem( newField );
1039 }
1040 }
1041
1042 // Use this symbol's keywords/filters if set, otherwise keep inherited ones
1043 if( !m_keyWords.IsEmpty() )
1044 retv->SetKeyWords( m_keyWords );
1045
1046 if( !m_fpFilters.IsEmpty() )
1047 retv->SetFPFilters( m_fpFilters );
1048
1049 // Copying the embedded files needs to go in the other direction. AddFile() silently
1050 // drops collisions, so the most relevant symbol ("this") must go first, followed by
1051 // parents up the chain to the root.
1052 {
1053 for( const auto& [name, file] : EmbeddedFileMap() )
1054 {
1056 retv->AddFile( newFile );
1057 }
1058
1059 for( const LIB_SYMBOL* ancestor : parentChain )
1060 {
1061 for( const auto& [name, file] : ancestor->EmbeddedFileMap() )
1062 {
1064 retv->AddFile( newFile );
1065 }
1066 }
1067 }
1068
1069 // Get excluded flags from the top-level parent (back of the chain). Derived symbols
1070 // aren't allowed to change the exclusion flags.
1071 if( !parentChain.empty() )
1072 {
1073 retv->SetExcludedFromSim( parentChain.back()->GetExcludedFromSim() );
1074 retv->SetExcludedFromBOM( parentChain.back()->GetExcludedFromBOM() );
1075 retv->SetExcludedFromBoard( parentChain.back()->GetExcludedFromBoard() );
1076 retv->SetExcludedFromPosFiles( parentChain.back()->GetExcludedFromPosFiles() );
1077 }
1078
1079 // Pin maps and associated footprints inherit as a coupled bundle; copy the resolved
1080 // effective bundle so the flattened symbol is self-contained.
1081 retv->m_pinMaps = GetEffectivePinMaps();
1082 retv->m_associatedFootprints = GetEffectiveAssociatedFootprints();
1083
1084 retv->m_cachesDirty = true;
1085 retv->m_parent.reset();
1086 }
1087 else
1088 {
1089 retv = std::make_unique<LIB_SYMBOL>( *this );
1090 }
1091
1092 return retv;
1093}
1094
1095
1097{
1098 m_library = aLibrary;
1099
1100 m_cachesDirty = true;
1101}
1102
1103
1104const wxString LIB_SYMBOL::GetLibraryName() const
1105{
1106 if( m_library )
1107 return m_library->GetName();
1108
1109 return m_libId.GetLibNickname();
1110}
1111
1112
1114{
1115 if( IsDerived() )
1116 {
1117 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1118
1119 if( root.get() != this )
1120 return root->IsLocalPower();
1121 }
1122
1123 return m_options == ENTRY_LOCAL_POWER;
1124}
1125
1126
1128{
1129 if( IsDerived() )
1130 {
1131 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1132
1133 if( root.get() != this )
1134 {
1135 root->SetLocalPower();
1136 return;
1137 }
1138 }
1139
1141
1142 m_cachesDirty = true;
1143}
1144
1145
1147{
1148 if( IsDerived() )
1149 {
1150 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1151
1152 if( root.get() != this )
1153 return root->IsGlobalPower();
1154 }
1155
1156 return m_options == ENTRY_GLOBAL_POWER;
1157}
1158
1159
1161{
1162 return IsLocalPower() || IsGlobalPower();
1163}
1164
1165
1167{
1168 if( IsDerived() )
1169 {
1170 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1171
1172 if( root.get() != this )
1173 {
1174 root->SetGlobalPower();
1175 return;
1176 }
1177 }
1178
1180
1181 m_cachesDirty = true;
1182}
1183
1184
1186{
1187 if( IsDerived() )
1188 {
1189 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1190
1191 if( root.get() != this )
1192 return root->IsNormal();
1193 }
1194
1195 return m_options == ENTRY_NORMAL;
1196}
1197
1198
1200{
1201 if( IsDerived() )
1202 {
1203 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1204
1205 if( root.get() != this )
1206 {
1207 root->SetNormal();
1208 return;
1209 }
1210 }
1211
1213
1214 m_cachesDirty = true;
1215}
1216
1217
1218wxString LIB_SYMBOL::LetterSubReference( int aUnit, wxChar aInitialLetter )
1219{
1220 // use letters as notation. To allow more than 26 units, the sub ref
1221 // use one letter if letter = A .. Z or a ... z, and 2 letters otherwise
1222 // first letter is expected to be 'A' or 'a' (i.e. 26 letters are available)
1223 int u;
1224 wxString suffix;
1225
1226 do
1227 {
1228 u = ( aUnit - 1 ) % 26;
1229 suffix = wxChar( aInitialLetter + u ) + suffix;
1230 aUnit = ( aUnit - u ) / 26;
1231 } while( aUnit > 0 );
1232
1233 return suffix;
1234}
1235
1236
1237bool LIB_SYMBOL::ResolveTextVar( wxString* token, int aDepth ) const
1238{
1239 wxString footprint;
1240
1241 for( const SCH_ITEM& item : m_drawings )
1242 {
1243 if( item.Type() == SCH_FIELD_T )
1244 {
1245 const SCH_FIELD& field = static_cast<const SCH_FIELD&>( item );
1246
1247 if( field.GetId() == FIELD_T::FOOTPRINT )
1248 footprint = field.GetShownText( nullptr, INTERNAL, wxEmptyString, aDepth + 1 );
1249
1250 if( token->IsSameAs( field.GetUntranslatedName().Upper() ) || token->IsSameAs( field.GetName(), false ) )
1251 {
1252 *token = field.GetShownText( nullptr, INTERNAL, wxEmptyString, aDepth + 1 );
1253 return true;
1254 }
1255 }
1256 }
1257
1258 // Consider missing simulation fields as empty, not un-resolved
1259 if( token->IsSameAs( wxT( "SIM.DEVICE" ) ) || token->IsSameAs( wxT( "SIM.TYPE" ) )
1260 || token->IsSameAs( wxT( "SIM.PINS" ) ) || token->IsSameAs( wxT( "SIM.PARAMS" ) )
1261 || token->IsSameAs( wxT( "SIM.LIBRARY" ) ) || token->IsSameAs( wxT( "SIM.NAME" ) ) )
1262 {
1263 *token = wxEmptyString;
1264 return true;
1265 }
1266
1267 if( token->IsSameAs( wxT( "FOOTPRINT_LIBRARY" ) ) )
1268 {
1269 wxArrayString parts = wxSplit( footprint, ':' );
1270
1271 if( parts.Count() > 0 )
1272 *token = parts[0];
1273 else
1274 *token = wxEmptyString;
1275
1276 return true;
1277 }
1278 else if( token->IsSameAs( wxT( "FOOTPRINT_NAME" ) ) )
1279 {
1280 wxArrayString parts = wxSplit( footprint, ':' );
1281
1282 if( parts.Count() > 1 )
1283 *token = parts[std::min( 1, (int) parts.size() - 1 )];
1284 else
1285 *token = wxEmptyString;
1286
1287 return true;
1288 }
1289 else if( token->IsSameAs( wxT( "SYMBOL_LIBRARY" ) ) )
1290 {
1291 *token = m_libId.GetUniStringLibNickname();
1292 return true;
1293 }
1294 else if( token->IsSameAs( wxT( "SYMBOL_NAME" ) ) )
1295 {
1296 *token = m_libId.GetUniStringLibItemName();
1297 return true;
1298 }
1299 else if( token->IsSameAs( wxT( "SYMBOL_PARENT" ) ) )
1300 {
1301 std::shared_ptr<LIB_SYMBOL> parent = GetParent().lock();
1302 *token = parent ? parent->GetName() : wxString();
1303 return true;
1304 }
1305 else if( token->IsSameAs( wxT( "SYMBOL_ROOT" ) ) )
1306 {
1307 std::shared_ptr<LIB_SYMBOL> root = GetRootSymbol();
1308 *token = root ? root->GetName() : GetName();
1309 return true;
1310 }
1311 else if( token->IsSameAs( wxT( "SYMBOL_DESCRIPTION" ) ) )
1312 {
1313 *token = GetShownDescription( INTERNAL, aDepth + 1 );
1314 return true;
1315 }
1316 else if( token->IsSameAs( wxT( "SYMBOL_KEYWORDS" ) ) )
1317 {
1318 *token = GetShownKeyWords( INTERNAL, aDepth + 1 );
1319 return true;
1320 }
1321 else if( token->IsSameAs( wxT( "SYMBOL_IS_POWER" ) ) )
1322 {
1323 *token = this->IsPower() ? wxString( wxS( "Power Symbol" ) ) : wxString( "" );
1324 return true;
1325 }
1326 else if( token->IsSameAs( wxT( "SYMBOL_IS_LOCAL_POWER" ) ) )
1327 {
1328 *token = this->IsLocalPower() ? wxString( wxS( "Local Power Symbol" ) ) : wxString( "" );
1329 return true;
1330 }
1331 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_BOM" ) ) )
1332 {
1333 *token = this->GetExcludedFromBOM() ? wxS( "Excluded from BOM" ) : wxEmptyString;
1334 return true;
1335 }
1336 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_BOARD" ) ) )
1337 {
1338 *token = this->GetExcludedFromBoard() ? wxS( "Excluded from board" ) : wxEmptyString;
1339 return true;
1340 }
1341 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_SIM" ) ) )
1342 {
1343 *token = this->GetExcludedFromSim() ? wxS( "Excluded from simulation" ) : wxEmptyString;
1344 return true;
1345 }
1346 else if( token->IsSameAs( wxT( "DNP" ) ) )
1347 {
1348 *token = this->GetDNP() ? wxS( "DNP" ) : wxEmptyString;
1349 return true;
1350 }
1351
1352 return false;
1353}
1354
1355
1356void LIB_SYMBOL::Plot( PLOTTER* aPlotter, bool aBackground, const SCH_PLOT_OPTS& aPlotOpts, int aUnit, int aBodyStyle,
1357 const VECTOR2I& aOffset, bool aDimmed )
1358{
1359 wxASSERT( aPlotter != nullptr );
1360
1361 SCH_RENDER_SETTINGS* renderSettings = getRenderSettings( aPlotter );
1362 COLOR4D color = renderSettings->GetLayerColor( LAYER_DEVICE );
1363 COLOR4D bg = renderSettings->GetBackgroundColor();
1364
1365 if( bg == COLOR4D::UNSPECIFIED || !aPlotter->GetColorMode() )
1366 bg = COLOR4D::WHITE;
1367
1368 if( color.m_text && Schematic() )
1369 color = COLOR4D( ResolveText( *color.m_text, &Schematic()->CurrentSheet() ) );
1370
1371 if( aDimmed )
1372 {
1373 color.Desaturate();
1374 color = color.Mix( bg, 0.5f );
1375 }
1376
1377 aPlotter->SetColor( color );
1378
1379 for( SCH_ITEM& item : m_drawings )
1380 {
1381 // Do not plot private items
1382 if( item.IsPrivate() )
1383 continue;
1384
1385 // LIB_FIELDs are not plotted here, because this plot function is used to plot schematic
1386 // items which have their own SCH_FIELDs
1387 if( item.Type() == SCH_FIELD_T )
1388 continue;
1389
1390 if( aUnit && item.m_unit && ( item.m_unit != aUnit ) )
1391 continue;
1392
1393 if( aBodyStyle && item.m_bodyStyle && ( item.m_bodyStyle != aBodyStyle ) )
1394 continue;
1395
1396 item.Plot( aPlotter, aBackground, aPlotOpts, aUnit, aBodyStyle, aOffset, aDimmed );
1397 }
1398}
1399
1400
1401void LIB_SYMBOL::PlotFields( PLOTTER* aPlotter, bool aBackground, const SCH_PLOT_OPTS& aPlotOpts, int aUnit,
1402 int aBodyStyle, const VECTOR2I& aOffset, bool aDimmed )
1403{
1404 wxASSERT( aPlotter != nullptr );
1405
1406 SCH_RENDER_SETTINGS* renderSettings = getRenderSettings( aPlotter );
1407 COLOR4D color = renderSettings->GetLayerColor( LAYER_FIELDS );
1408 COLOR4D bg = renderSettings->GetBackgroundColor();
1409
1410 if( bg == COLOR4D::UNSPECIFIED || !aPlotter->GetColorMode() )
1411 bg = COLOR4D::WHITE;
1412
1413 if( aDimmed )
1414 {
1415 color.Desaturate();
1416 color = color.Mix( bg, 0.5f );
1417 }
1418
1419 aPlotter->SetColor( color );
1420
1421 for( SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
1422 {
1423 SCH_FIELD& field = static_cast<SCH_FIELD&>( item );
1424
1425 if( !renderSettings->m_ShowHiddenFields && !field.IsVisible() )
1426 continue;
1427
1428 // The reference is a special case: we should change the basic text
1429 // to add '?' and the part id
1430 wxString tmp = field.GetText();
1431
1432 field.SetText( field.GetFullText( aUnit ) );
1433 item.Plot( aPlotter, aBackground, aPlotOpts, aUnit, aBodyStyle, aOffset, aDimmed );
1434
1435 field.SetText( tmp );
1436 }
1437}
1438
1439
1441{
1442 std::vector<SCH_SHAPE*> potential_top_items;
1443 std::vector<SCH_ITEM*> bottom_items;
1444
1445 for( SCH_ITEM& item : m_drawings )
1446 {
1447 if( item.Type() == SCH_SHAPE_T )
1448 {
1449 SCH_SHAPE& shape = static_cast<SCH_SHAPE&>( item );
1450
1451 if( shape.GetFillMode() == FILL_T::FILLED_WITH_COLOR )
1452 potential_top_items.push_back( &shape );
1453 else
1454 bottom_items.push_back( &item );
1455 }
1456 else
1457 {
1458 bottom_items.push_back( &item );
1459 }
1460 }
1461
1462 std::sort( potential_top_items.begin(), potential_top_items.end(),
1463 []( SCH_ITEM* a, SCH_ITEM* b )
1464 {
1465 return a->GetBoundingBox().GetArea() > b->GetBoundingBox().GetArea();
1466 } );
1467
1468 for( SCH_SHAPE* item : potential_top_items )
1469 {
1470 for( SCH_ITEM* bottom_item : bottom_items )
1471 {
1472 if( item->GetBoundingBox().Contains( bottom_item->GetBoundingBox() ) )
1473 {
1474 item->SetFillMode( FILL_T::FILLED_WITH_BG_BODYCOLOR );
1475 break;
1476 }
1477 }
1478 }
1479}
1480
1481
1483{
1484 wxASSERT( aItem != nullptr );
1485
1486 // none of the MANDATORY_FIELDS may be removed in RAM, but they may be
1487 // omitted when saving to disk.
1488 if( aItem->Type() == SCH_FIELD_T )
1489 {
1490 if( static_cast<SCH_FIELD*>( aItem )->IsMandatory() )
1491 return;
1492 }
1493
1494 LIB_ITEMS& items = m_drawings[aItem->Type()];
1495
1496 for( LIB_ITEMS::iterator i = items.begin(); i != items.end(); i++ )
1497 {
1498 if( &*i == aItem )
1499 {
1500 items.erase( i );
1501 m_cachesDirty = true;
1502 break;
1503 }
1504 }
1505}
1506
1507
1508void LIB_SYMBOL::AddDrawItem( SCH_ITEM* aItem, bool aSort )
1509{
1510 if( aItem )
1511 {
1512 aItem->SetParent( this );
1513
1514 m_drawings.push_back( aItem );
1515
1516 if( aSort )
1517 m_drawings.sort();
1518
1519 m_cachesDirty = true;
1520 }
1521}
1522
1523
1524std::vector<SCH_PIN*> LIB_SYMBOL::GetGraphicalPins( int aUnit, int aBodyStyle ) const
1525{
1526 if( IsDerived() )
1527 {
1528 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1529
1530 if( root.get() != this )
1531 return const_cast<const LIB_SYMBOL*>( root.get() )->GetGraphicalPins( aUnit, aBodyStyle );
1532 }
1533
1534 std::vector<SCH_PIN*> pins;
1535
1536 /* Notes:
1537 * when aUnit == 0: no unit filtering
1538 * when aBodyStyle == 0: no body style filtering
1539 * when m_unit == 0, the item is common to all units
1540 * when m_bodyStyle == 0, the item is common to all body styles
1541 */
1542
1543 for( const SCH_ITEM& item : m_drawings[SCH_PIN_T] )
1544 {
1545 // Unit filtering:
1546 if( aUnit && item.m_unit && ( item.m_unit != aUnit ) )
1547 continue;
1548
1549 // Body style filtering:
1550 if( aBodyStyle && item.m_bodyStyle && ( item.m_bodyStyle != aBodyStyle ) )
1551 continue;
1552
1553 pins.push_back( static_cast<SCH_PIN*>( const_cast<SCH_ITEM*>( &item ) ) );
1554 }
1555
1556 return pins;
1557}
1558
1559
1560std::vector<LIB_SYMBOL::UNIT_PIN_INFO> LIB_SYMBOL::GetUnitPinInfo() const
1561{
1562 std::vector<UNIT_PIN_INFO> units;
1563
1564 int unitCount = std::max( GetUnitCount(), 1 );
1565
1566 auto compareByPosition =
1567 []( const SCH_PIN* a, const SCH_PIN* b )
1568 {
1569 VECTOR2I positionA = a->GetPosition();
1570 VECTOR2I positionB = b->GetPosition();
1571
1572 if( positionA.x != positionB.x )
1573 return positionA.x < positionB.x;
1574
1575 return positionA.y < positionB.y;
1576 };
1577
1578 for( int unitIdx = 1; unitIdx <= unitCount; ++unitIdx )
1579 {
1580 UNIT_PIN_INFO unitInfo;
1581 unitInfo.m_unitName = GetUnitDisplayName( unitIdx, false );
1582
1583 std::vector<SCH_PIN*> pinList = GetGraphicalPins( unitIdx, 0 );
1584
1585 std::sort( pinList.begin(), pinList.end(), compareByPosition );
1586
1587 std::unordered_set<wxString> seenNumbers;
1588
1589 for( const SCH_PIN* basePin : pinList )
1590 {
1591 bool stackedValid = false;
1592 std::vector<wxString> expandedNumbers = basePin->GetStackedPinNumbers( &stackedValid );
1593
1594 if( stackedValid && !expandedNumbers.empty() )
1595 {
1596 for( const wxString& number : expandedNumbers )
1597 {
1598 if( seenNumbers.insert( number ).second )
1599 unitInfo.m_pinNumbers.push_back( number );
1600 }
1601
1602 continue;
1603 }
1604
1605 const wxString& number = basePin->GetNumber();
1606
1607 if( !number.IsEmpty() && seenNumbers.insert( number ).second )
1608 unitInfo.m_pinNumbers.push_back( number );
1609 }
1610
1611 units.push_back( std::move( unitInfo ) );
1612 }
1613
1614 return units;
1615}
1616
1617
1618std::vector<LIB_SYMBOL::LOGICAL_PIN> LIB_SYMBOL::GetLogicalPins( int aUnit, int aBodyStyle ) const
1619{
1620 std::vector<LOGICAL_PIN> out;
1621
1622 for( const SCH_PIN* pin : GetGraphicalPins( aUnit, aBodyStyle ) )
1623 {
1624 bool valid = false;
1625 std::vector<wxString> expanded = pin->GetStackedPinNumbers( &valid );
1626
1627 if( valid && !expanded.empty() )
1628 {
1629 for( const wxString& num : expanded )
1630 {
1631 out.push_back( LOGICAL_PIN{ pin, num } );
1632 wxLogTrace( traceStackedPins, "GetLogicalPins: base='%s' -> '%s'", pin->GetShownNumber(), num );
1633 }
1634 }
1635 else
1636 {
1637 out.push_back( LOGICAL_PIN{ pin, pin->GetShownNumber() } );
1638 wxLogTrace( traceStackedPins, "GetLogicalPins: base='%s' (no expansion)", pin->GetShownNumber() );
1639 }
1640 }
1641
1642 return out;
1643}
1644
1645
1647{
1648 if( m_cachesDirty )
1649 rebuildCaches();
1650
1651 return m_pinCountCache;
1652}
1653
1654
1655const SCH_PIN* LIB_SYMBOL::GetPin( const wxString& aNumber, int aUnit, int aBodyStyle ) const
1656{
1657 for( const SCH_PIN* pin : GetGraphicalPins( aUnit, aBodyStyle ) )
1658 {
1659 if( aNumber == pin->GetNumber() )
1660 return pin;
1661 }
1662
1663 return nullptr;
1664}
1665
1666
1667std::vector<SCH_PIN*> LIB_SYMBOL::GetPinsByNumber( const wxString& aNumber, int aUnit, int aBodyStyle )
1668{
1669 std::vector<SCH_PIN*> pins;
1670
1671 for( SCH_PIN* pin : GetGraphicalPins( aUnit, aBodyStyle ) )
1672 {
1673 if( aNumber == pin->GetNumber() )
1674 pins.push_back( pin );
1675 }
1676
1677 return pins;
1678}
1679
1680
1681bool LIB_SYMBOL::HasPinNumber( const wxString& aNumber ) const
1682{
1683 if( GetPin( aNumber ) )
1684 return true;
1685
1686 for( const SCH_PIN* pin : GetGraphicalPins( 0, 0 ) )
1687 {
1688 for( const wxString& logicalNumber : pin->GetStackedPinNumbers() )
1689 {
1690 if( aNumber == logicalNumber )
1691 return true;
1692 }
1693 }
1694
1695 return false;
1696}
1697
1698
1699bool LIB_SYMBOL::PinsConflictWith( const LIB_SYMBOL& aOtherPart, bool aTestNums, bool aTestNames, bool aTestType,
1700 bool aTestOrientation, bool aTestLength ) const
1701{
1702 for( const SCH_PIN* pin : GetGraphicalPins() )
1703 {
1704 wxASSERT( pin );
1705 bool foundMatch = false;
1706
1707 for( const SCH_PIN* otherPin : aOtherPart.GetGraphicalPins() )
1708 {
1709 wxASSERT( otherPin );
1710
1711 // Same unit?
1712 if( pin->GetUnit() != otherPin->GetUnit() )
1713 continue;
1714
1715 // Same body stype?
1716 if( pin->GetBodyStyle() != otherPin->GetBodyStyle() )
1717 continue;
1718
1719 // Same position?
1720 if( pin->GetPosition() != otherPin->GetPosition() )
1721 continue;
1722
1723 // Same number?
1724 if( aTestNums && ( pin->GetNumber() != otherPin->GetNumber() ) )
1725 continue;
1726
1727 // Same name?
1728 if( aTestNames && ( pin->GetName() != otherPin->GetName() ) )
1729 continue;
1730
1731 // Same electrical type?
1732 if( aTestType && ( pin->GetType() != otherPin->GetType() ) )
1733 continue;
1734
1735 // Same orientation?
1736 if( aTestOrientation && ( pin->GetOrientation() != otherPin->GetOrientation() ) )
1737 continue;
1738
1739 // Same length?
1740 if( aTestLength && ( pin->GetLength() != otherPin->GetLength() ) )
1741 continue;
1742
1743 foundMatch = true;
1744 break; // Match found so search is complete.
1745 }
1746
1747 if( !foundMatch )
1748 {
1749 // This means there was not an identical (according to the arguments)
1750 // pin at the same position in the other symbol.
1751 return true;
1752 }
1753 }
1754
1755 // The loop never gave up, so no conflicts were found.
1756 return false;
1757}
1758
1759const BOX2I LIB_SYMBOL::GetUnitBoundingBox( int aUnit, int aBodyStyle, bool aIgnoreHiddenFields,
1760 bool aIgnoreLabelsOnInvisiblePins ) const
1761{
1762 BOX2I bBox; // Start with a fresh BOX2I so the Merge algorithm works
1763
1764 if( IsDerived() )
1765 {
1766 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
1767
1768 if( root.get() != this )
1769 bBox = root->GetUnitBoundingBox( aUnit, aBodyStyle, aIgnoreHiddenFields, aIgnoreLabelsOnInvisiblePins );
1770 }
1771
1772 for( const SCH_ITEM& item : m_drawings )
1773 {
1774 if( item.m_unit > 0 && m_unitCount > 1 && aUnit > 0 && aUnit != item.m_unit )
1775 continue;
1776
1777 if( item.m_bodyStyle > 0 && aBodyStyle > 0 && aBodyStyle != item.m_bodyStyle )
1778 continue;
1779
1780 if( aIgnoreHiddenFields && item.Type() == SCH_FIELD_T )
1781 {
1782 if( !static_cast<const SCH_FIELD&>( item ).IsVisible() )
1783 continue;
1784 }
1785
1786 if( item.Type() == SCH_PIN_T && !aIgnoreLabelsOnInvisiblePins )
1787 {
1788 const SCH_PIN& pin = static_cast<const SCH_PIN&>( item );
1789 bBox.Merge( pin.GetBoundingBox( true, true, false ) );
1790 }
1791 else
1792 {
1793 bBox.Merge( item.GetBoundingBox() );
1794 }
1795 }
1796
1797 return bBox;
1798}
1799
1800
1801const BOX2I LIB_SYMBOL::GetBodyBoundingBox( int aUnit, int aBodyStyle, bool aIncludePins,
1802 bool aIncludePrivateItems ) const
1803{
1804 BOX2I bbox;
1805
1806 for( const SCH_ITEM& item : m_drawings )
1807 {
1808 if( item.m_unit > 0 && aUnit > 0 && aUnit != item.m_unit )
1809 continue;
1810
1811 if( item.m_bodyStyle > 0 && aBodyStyle > 0 && aBodyStyle != item.m_bodyStyle )
1812 continue;
1813
1814 if( item.IsPrivate() && !aIncludePrivateItems )
1815 continue;
1816
1817 if( item.Type() == SCH_FIELD_T )
1818 continue;
1819
1820 if( item.Type() == SCH_PIN_T )
1821 {
1822 const SCH_PIN& pin = static_cast<const SCH_PIN&>( item );
1823
1824 if( pin.IsVisible() )
1825 {
1826 // Note: the roots of the pins are always included for symbols that don't have
1827 // a well-defined body.
1828
1829 if( aIncludePins )
1830 bbox.Merge( pin.GetBoundingBox( false, false, false ) );
1831 else
1832 bbox.Merge( pin.GetPinRoot() );
1833 }
1834 }
1835 else
1836 {
1837 bbox.Merge( item.GetBoundingBox() );
1838 }
1839 }
1840
1841 return bbox;
1842}
1843
1844
1849
1850
1852{
1853 m_drawings[SCH_FIELD_T].clear();
1854 m_cachesDirty = true;
1855}
1856
1857
1859{
1860 AddDrawItem( aField );
1861}
1862
1863
1864void LIB_SYMBOL::SetFields( const std::vector<SCH_FIELD>& aFieldsList )
1865{
1867
1868 for( const SCH_FIELD& src : aFieldsList )
1869 {
1870 // drawings is a ptr_vector, new and copy an object on the heap.
1871 SCH_FIELD* field = new SCH_FIELD( src );
1872
1873 field->SetParent( this );
1874 m_drawings.push_back( field );
1875 }
1876
1877 m_drawings.sort();
1878 m_cachesDirty = true;
1879}
1880
1881
1882void LIB_SYMBOL::GetFields( std::vector<SCH_FIELD*>& aList, bool aVisibleOnly ) const
1883{
1884 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
1885 {
1886 const SCH_FIELD* field = static_cast<const SCH_FIELD*>( &item );
1887
1888 if( aVisibleOnly )
1889 {
1890 if( !field->IsVisible() || field->GetText().IsEmpty() )
1891 continue;
1892 }
1893
1894 aList.push_back( const_cast<SCH_FIELD*>( field ) );
1895 }
1896
1897 std::sort( aList.begin(), aList.end(),
1898 []( SCH_FIELD* lhs, SCH_FIELD* rhs )
1899 {
1900 return lhs->GetOrdinal() < rhs->GetOrdinal();
1901 } );
1902}
1903
1904
1905void LIB_SYMBOL::CopyFields( std::vector<SCH_FIELD>& aList )
1906{
1907 std::vector<SCH_FIELD*> orderedFields;
1908
1909 GetFields( orderedFields );
1910
1911 for( SCH_FIELD* field : orderedFields )
1912 aList.emplace_back( *field );
1913}
1914
1915
1917{
1918 std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock();
1919
1920 if( !parent )
1921 return;
1922
1923 std::unique_ptr<LIB_SYMBOL> flattenedParent = parent->Flatten();
1924
1925 auto selected =
1926 [&]( const wxString& aFieldName )
1927 {
1928 return aOptions.m_updateAllFields
1929 || aOptions.m_updateFields.count( aFieldName ) > 0;
1930 };
1931
1932 std::vector<SCH_FIELD> fieldsCopy;
1933 std::vector<SCH_FIELD> result;
1934 CopyFields( fieldsCopy );
1935
1936 for( SCH_FIELD& field : fieldsCopy )
1937 {
1938 bool copy = true;
1939 SCH_FIELD* parentField = nullptr;
1940
1941 if( selected( field.GetName() ) )
1942 {
1943 if( field.IsMandatory() )
1944 parentField = flattenedParent->GetField( field.GetId() );
1945 else
1946 parentField = flattenedParent->GetField( field.GetName() );
1947
1948 if( parentField )
1949 {
1950 bool resetText = parentField->GetText().IsEmpty() ? aOptions.m_resetEmptyText
1951 : aOptions.m_resetText;
1952
1953 if( resetText )
1954 field.SetText( parentField->GetText() );
1955
1956 if( aOptions.m_resetVisibility )
1957 {
1958 field.SetVisible( parentField->IsVisible() );
1959 field.SetNameShown( parentField->IsNameShown() );
1960 }
1961
1962 if( aOptions.m_resetEffects )
1963 {
1964 // SetAttributes() also overwrites the visible bit and position, so save
1965 // and restore them here.
1966 bool visible = field.IsVisible();
1967 VECTOR2I pos = field.GetPosition();
1968
1969 field.SetAttributes( *parentField );
1970
1971 field.SetVisible( visible );
1972 field.SetPosition( pos );
1973 }
1974
1975 if( aOptions.m_resetPositions )
1976 field.SetTextPos( parentField->GetTextPos() );
1977 }
1978 else if( aOptions.m_removeExtraFields )
1979 {
1980 copy = false;
1981 }
1982 }
1983
1984 if( copy )
1985 result.emplace_back( std::move( field ) );
1986 }
1987
1988 int nextOrdinal = GetNextFieldOrdinal();
1989 std::vector<SCH_FIELD*> parentFields;
1990
1991 flattenedParent->GetFields( parentFields );
1992
1993 for( SCH_FIELD* parentField : parentFields )
1994 {
1995 if( !selected( parentField->GetName() ) )
1996 continue;
1997
1998 if( !GetField( parentField->GetName() ) )
1999 {
2000 result.emplace_back( this, FIELD_T::USER );
2001 SCH_FIELD* newField = &result.back();
2002
2003 newField->SetName( parentField->GetUntranslatedName() );
2004 newField->SetText( parentField->GetText() );
2005 newField->SetAttributes( *parentField ); // Includes visible bit and position
2006 newField->SetOrdinal( nextOrdinal++, FIELD_T::USER );
2007 }
2008 }
2009
2010 SetFields( result );
2011}
2012
2013
2015{
2016 int ordinal = 42; // Arbitrarily larger than any mandatory FIELD_T id
2017
2018 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2019 ordinal = std::max( ordinal, static_cast<const SCH_FIELD*>( &item )->GetOrdinal() + 1 );
2020
2021 return ordinal;
2022}
2023
2024
2025const SCH_FIELD* LIB_SYMBOL::GetField( FIELD_T aFieldType ) const
2026{
2027 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2028 {
2029 const SCH_FIELD* field = static_cast<const SCH_FIELD*>( &item );
2030
2031 if( field->GetId() == aFieldType )
2032 return field;
2033 }
2034
2035 return nullptr;
2036}
2037
2038
2040{
2041 for( SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2042 {
2043 SCH_FIELD* field = static_cast<SCH_FIELD*>( &item );
2044
2045 if( field->GetId() == aFieldType )
2046 return field;
2047 }
2048
2049 return nullptr;
2050}
2051
2052
2053const SCH_FIELD* LIB_SYMBOL::GetField( const wxString& aFieldName ) const
2054{
2055 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2056 {
2057 const SCH_FIELD& field = static_cast<const SCH_FIELD&>( item );
2058
2059 if( field.GetName() == aFieldName )
2060 return &field;
2061 }
2062
2063 return nullptr;
2064}
2065
2066
2067SCH_FIELD* LIB_SYMBOL::GetField( const wxString& aFieldName )
2068{
2069 for( SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2070 {
2071 SCH_FIELD& field = static_cast<SCH_FIELD&>( item );
2072
2073 if( field.GetName() == aFieldName )
2074 return &field;
2075 }
2076
2077 return nullptr;
2078}
2079
2080
2082{
2083 for( SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2084 {
2085 SCH_FIELD& field = static_cast<SCH_FIELD&>( item );
2086
2087 if( field.GetUntranslatedName().IsSameAs( aFieldName, false ) )
2088 return &field;
2089 }
2090
2091 return nullptr;
2092}
2093
2094
2095const SCH_FIELD* LIB_SYMBOL::FindFieldCaseInsensitive( const wxString& aFieldName ) const
2096{
2097 for( const SCH_ITEM& item : m_drawings[SCH_FIELD_T] )
2098 {
2099 const SCH_FIELD& field = static_cast<const SCH_FIELD&>( item );
2100
2101 if( field.GetUntranslatedName().IsSameAs( aFieldName, false ) )
2102 return &field;
2103 }
2104
2105 return nullptr;
2106}
2107
2108
2110{
2111 const SCH_FIELD* field = GetField( FIELD_T::VALUE );
2112 wxASSERT( field != nullptr );
2113 return *field;
2114}
2115
2116
2118{
2119 const SCH_FIELD* field = GetField( FIELD_T::REFERENCE );
2120 wxASSERT( field != nullptr );
2121 return *field;
2122}
2123
2124
2126{
2127 const SCH_FIELD* field = GetField( FIELD_T::FOOTPRINT );
2128 wxASSERT( field != nullptr );
2129 return *field;
2130}
2131
2132
2134{
2135 const SCH_FIELD* field = GetField( FIELD_T::DATASHEET );
2136 wxASSERT( field != nullptr );
2137 return *field;
2138}
2139
2140
2142{
2143 const SCH_FIELD* field = GetField( FIELD_T::DESCRIPTION );
2144 wxASSERT( field != nullptr );
2145 return *field;
2146}
2147
2148
2150{
2151 wxString refDesignator = GetField( FIELD_T::REFERENCE )->GetText();
2152
2153 refDesignator.Replace( wxS( "~" ), wxS( " " ) );
2154
2155 wxString prefix = refDesignator;
2156
2157 while( prefix.Length() )
2158 {
2159 wxUniCharRef last = prefix.Last();
2160
2161 if( ( last >= '0' && last <= '9' ) || last == '?' || last == '*' )
2162 prefix.RemoveLast();
2163 else
2164 break;
2165 }
2166
2167 // Avoid a prefix containing trailing/leading spaces
2168 prefix.Trim( true );
2169 prefix.Trim( false );
2170
2171 return prefix;
2172}
2173
2174
2175void LIB_SYMBOL::RunOnChildren( const std::function<void( SCH_ITEM* )>& aFunction, RECURSE_MODE aMode )
2176{
2177 for( SCH_ITEM& item : m_drawings )
2178 aFunction( &item );
2179
2180 // We don't know what this did, so better to be safe than sorry
2181 m_cachesDirty = true;
2182}
2183
2184
2185void LIB_SYMBOL::Move( const VECTOR2I& aOffset )
2186{
2187 for( SCH_ITEM& item : m_drawings )
2188 item.Move( aOffset );
2189}
2190
2191
2192// Before V10 we didn't store the number of body styles in a symbol -- we just looked through all
2193// its drawings each time we wanted to know. This is now only used to set the count when a legacy
2194// symbol is first read. (Legacy symbols also didn't support arbitrary body styles, so the count
2195// is always 1 or 2, and when 2 it is always a De Morgan pair.)
2197{
2198 for( const SCH_ITEM& item : m_drawings )
2199 {
2200 if( item.m_bodyStyle > BODY_STYLE::BASE )
2201 return true;
2202 }
2203
2204 if( IsDerived() )
2205 {
2206 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
2207
2208 if( root.get() != this )
2209 return root->HasLegacyAlternateBodyStyle();
2210 }
2211
2212 return false;
2213}
2214
2215
2217{
2218 if( IsDerived() )
2219 {
2220 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
2221
2222 if( root.get() != this )
2223 return root->GetMaxPinNumber();
2224 }
2225
2226 int maxPinNumber = 0;
2227
2228 for( const SCH_ITEM& item : m_drawings[SCH_PIN_T] )
2229 {
2230 const SCH_PIN* pin = static_cast<const SCH_PIN*>( &item );
2231 long currentPinNumber = 0;
2232
2233 if( pin->GetNumber().ToLong( &currentPinNumber ) )
2234 maxPinNumber = std::max( maxPinNumber, (int) currentPinNumber );
2235 }
2236
2237 return maxPinNumber;
2238}
2239
2240
2242{
2244
2245 for( SCH_ITEM& item : m_drawings )
2246 item.ClearTempFlags();
2247}
2248
2249
2251{
2253
2254 for( SCH_ITEM& item : m_drawings )
2255 item.ClearEditFlags();
2256}
2257
2258
2259SCH_ITEM* LIB_SYMBOL::LocateDrawItem( int aUnit, int aBodyStyle, KICAD_T aType, const VECTOR2I& aPoint )
2260{
2261 for( SCH_ITEM& item : m_drawings )
2262 {
2263 if( ( aUnit && item.m_unit && aUnit != item.m_unit )
2264 || ( aBodyStyle && item.m_bodyStyle && aBodyStyle != item.m_bodyStyle )
2265 || ( item.Type() != aType && aType != TYPE_NOT_INIT ) )
2266 {
2267 continue;
2268 }
2269
2270 if( item.HitTest( aPoint ) )
2271 return &item;
2272 }
2273
2274 return nullptr;
2275}
2276
2277
2278SCH_ITEM* LIB_SYMBOL::LocateDrawItem( int aUnit, int aBodyStyle, KICAD_T aType, const VECTOR2I& aPoint,
2279 const TRANSFORM& aTransform )
2280{
2281 /* we use LocateDrawItem( int aUnit, int convert, KICAD_T type, const
2282 * VECTOR2I& pt ) to search items.
2283 * because this function uses DefaultTransform as orient/mirror matrix
2284 * we temporary copy aTransform in DefaultTransform
2285 */
2286 TRANSFORM transform = DefaultTransform;
2287 DefaultTransform = aTransform;
2288
2289 SCH_ITEM* item = LocateDrawItem( aUnit, aBodyStyle, aType, aPoint );
2290
2291 // Restore matrix
2292 DefaultTransform = transform;
2293
2294 return item;
2295}
2296
2297
2298INSPECT_RESULT LIB_SYMBOL::Visit( INSPECTOR aInspector, void* aTestData, const std::vector<KICAD_T>& aScanTypes )
2299{
2300 // The part itself is never inspected, only its children
2301 for( SCH_ITEM& item : m_drawings )
2302 {
2303 if( item.IsType( aScanTypes ) )
2304 {
2305 if( aInspector( &item, aTestData ) == INSPECT_RESULT::QUIT )
2306 return INSPECT_RESULT::QUIT;
2307 }
2308 }
2309
2311}
2312
2313
2314void LIB_SYMBOL::SetUnitCount( int aCount, bool aDuplicateDrawItems )
2315{
2316 // A LIB_SYMBOL must always have at least one unit. Passing a value less than 1 would
2317 // erase the mandatory fields (which all have m_unit == 0), leaving the symbol in a
2318 // broken state that crashes later when callers dereference GetReferenceField() etc.
2319 wxCHECK_RET( aCount >= 1, wxString::Format( wxT( "Invalid unit count %d, ignoring." ), aCount ) );
2320
2321 if( m_unitCount == aCount )
2322 return;
2323
2324 if( aCount < m_unitCount )
2325 {
2326 // Iterate each drawing-type bucket and erase items that belong to units > aCount.
2327 for( int type = LIB_ITEMS_CONTAINER::FIRST_TYPE; type <= LIB_ITEMS_CONTAINER::LAST_TYPE; ++type )
2328 {
2329 auto it = m_drawings.begin( type );
2330
2331 while( it != m_drawings.end( type ) )
2332 {
2333 if( it->m_unit > aCount )
2334 it = m_drawings.erase( it ); // returns next iterator
2335 else
2336 ++it;
2337 }
2338 }
2339 }
2340 else if( aDuplicateDrawItems )
2341 {
2342 int prevCount = m_unitCount;
2343
2344 // Temporary storage for new items, as adding new items directly to
2345 // m_drawings may cause the buffer reallocation which invalidates the
2346 // iterators
2347 std::vector<SCH_ITEM*> tmp;
2348
2349 for( SCH_ITEM& item : m_drawings )
2350 {
2351 if( item.m_unit != 1 )
2352 continue;
2353
2354 for( int j = prevCount + 1; j <= aCount; j++ )
2355 {
2356 SCH_ITEM* newItem = item.Duplicate( IGNORE_PARENT_GROUP );
2357 newItem->m_unit = j;
2358 tmp.push_back( newItem );
2359 }
2360 }
2361
2362 for( SCH_ITEM* item : tmp )
2363 m_drawings.push_back( item );
2364 }
2365
2366 m_drawings.sort();
2367 m_unitCount = aCount;
2368 m_cachesDirty = true;
2369}
2370
2371
2373{
2374 if( IsDerived() )
2375 {
2376 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
2377
2378 if( root.get() != this )
2379 return root->GetUnitCount();
2380 }
2381
2382 return m_unitCount;
2383}
2384
2385
2387{
2388 if( HasDeMorganBodyStyles() )
2389 return 2;
2390
2391 return std::max( 1, (int) GetBodyStyleNames().size() );
2392}
2393
2394
2396{
2397 if( IsDerived() )
2398 {
2399 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
2400
2401 if( root.get() != this )
2402 return root->m_demorgan;
2403 }
2404
2405 return m_demorgan;
2406}
2407
2408
2409const std::vector<wxString>& LIB_SYMBOL::GetBodyStyleNames() const
2410{
2411 if( IsDerived() )
2412 {
2413 std::shared_ptr<LIB_SYMBOL> root = GetSafeRootSymbol( this, __FUNCTION__ );
2414
2415 if( root.get() != this )
2416 return root->m_bodyStyleNames;
2417 }
2418
2419 return m_bodyStyleNames;
2420}
2421
2422
2423void LIB_SYMBOL::SetBodyStyleCount( int aCount, bool aDuplicateDrawItems, bool aDuplicatePins )
2424{
2425 wxCHECK_RET( aCount >= 1,
2426 wxString::Format( wxT( "Invalid body style count %d, ignoring." ), aCount ) );
2427
2428 int prevCount = GetBodyStyleCount();
2429
2430 // Populate the new body styles from the standard one
2431 if( prevCount < aCount && ( aDuplicateDrawItems || aDuplicatePins ) )
2432 {
2433 std::vector<SCH_ITEM*> tmp; // Adding to m_drawings while iterating it invalidates the iterator
2434
2435 for( SCH_ITEM& item : m_drawings )
2436 {
2437 if( item.Type() == SCH_PIN_T )
2438 {
2439 if( !aDuplicatePins )
2440 continue;
2441 }
2442 else
2443 {
2444 if( !aDuplicateDrawItems )
2445 continue;
2446 }
2447
2448 if( item.m_bodyStyle == BODY_STYLE::BASE )
2449 {
2450 for( int j = prevCount + 1; j <= aCount; j++ )
2451 {
2452 SCH_ITEM* newItem = item.Duplicate( IGNORE_PARENT_GROUP );
2453 newItem->m_bodyStyle = j;
2454 tmp.push_back( newItem );
2455 }
2456 }
2457 }
2458
2459 for( SCH_ITEM* item : tmp )
2460 m_drawings.push_back( item );
2461
2462 m_drawings.sort();
2463 }
2464
2465 // A caller that already cleared the De Morgan flag or the body style names reports a
2466 // previous count of 1, so the deletion cannot be conditional on the count dropping
2467 PruneBodyStyleDrawItems( aCount );
2468
2469 m_cachesDirty = true;
2470}
2471
2472
2473void LIB_SYMBOL::PruneBodyStyleDrawItems( int aBodyStyleCount )
2474{
2476
2477 while( i != m_drawings.end() )
2478 {
2479 if( i->m_bodyStyle > aBodyStyleCount )
2480 i = m_drawings.erase( i );
2481 else
2482 ++i;
2483 }
2484}
2485
2486
2487std::vector<SCH_ITEM*> LIB_SYMBOL::GetUnitDrawItems( int aUnit, int aBodyStyle )
2488{
2489 std::vector<SCH_ITEM*> unitItems;
2490
2491 for( SCH_ITEM& item : m_drawings )
2492 {
2493 if( item.Type() == SCH_FIELD_T )
2494 continue;
2495
2496 if( aUnit != ALL_UNITS
2497 && item.GetUnit() != ALL_UNITS
2498 && aUnit != item.GetUnit() )
2499 {
2500 continue;
2501 }
2502
2503 if( aBodyStyle != ALL_BODY_STYLES
2504 && item.GetBodyStyle() != ALL_BODY_STYLES
2505 && aBodyStyle != item.GetBodyStyle() )
2506 {
2507 continue;
2508 }
2509
2510 unitItems.push_back( &item );
2511 }
2512
2513 return unitItems;
2514}
2515
2516
2517std::vector<LIB_SYMBOL_UNIT> LIB_SYMBOL::GetUnitDrawItems()
2518{
2519 std::vector<LIB_SYMBOL_UNIT> units;
2520
2521 // Enforce writing out of all defined unit/body-style combinations
2522 for( int unit = 1; unit <= GetUnitCount(); unit++ )
2523 {
2524 for( int bodyStyle = 1; bodyStyle <= GetBodyStyleCount(); bodyStyle++ )
2525 {
2526 LIB_SYMBOL_UNIT record;
2527 record.m_unit = unit;
2528 record.m_bodyStyle = bodyStyle;
2529 units.push_back( std::move( record ) );
2530 }
2531 }
2532
2533 for( SCH_ITEM& item : m_drawings )
2534 {
2535 if( item.Type() == SCH_FIELD_T )
2536 continue;
2537
2538 int unit = item.GetUnit();
2539 int bodyStyle = item.GetBodyStyle();
2540
2541 auto it = std::find_if( units.begin(), units.end(),
2542 [unit, bodyStyle]( const LIB_SYMBOL_UNIT& a )
2543 {
2544 return a.m_unit == unit && a.m_bodyStyle == bodyStyle;
2545 } );
2546
2547 if( it == units.end() )
2548 {
2549 LIB_SYMBOL_UNIT record;
2550 record.m_unit = unit;
2551 record.m_bodyStyle = bodyStyle;
2552 it = units.insert( units.end(), std::move( record ) );
2553 }
2554
2555 it->m_items.push_back( &item );
2556 }
2557
2558 std::sort( units.begin(), units.end(),
2559 []( const LIB_SYMBOL_UNIT& a, const LIB_SYMBOL_UNIT& b )
2560 {
2561 if( a.m_unit == b.m_unit )
2562 return a.m_bodyStyle < b.m_bodyStyle;
2563
2564 return a.m_unit < b.m_unit;
2565 } );
2566
2567 return units;
2568}
2569
2570
2571#define REPORT( msg ) \
2572 { \
2573 if( aReporter ) \
2574 aReporter->Report( msg ); \
2575 }
2576
2577#define ITEM_DESC( item ) ( item )->GetItemDescription( &unitsProvider, false )
2578
2579
2587
2588
2589bool LIB_SYMBOL_ATTRIBUTES::Matches( const LIB_SYMBOL_ATTRIBUTES& aOther, int aCompareFlags ) const
2590{
2591 using FLAGS = SCH_ITEM::COMPARE_FLAGS;
2592
2593 if( options != aOther.options || unitCount != aOther.unitCount || footprintFilters != aOther.footprintFilters
2595 || keywords != aOther.keywords || pinNameOffset != aOther.pinNameOffset
2597 || bodyStyleNames != aOther.bodyStyleNames )
2598 {
2599 return false;
2600 }
2601
2602 if( ( aCompareFlags & FLAGS::PIN_VISIBILITIES )
2603 && ( showPinNames != aOther.showPinNames || showPinNumbers != aOther.showPinNumbers ) )
2604 {
2605 return false;
2606 }
2607
2608 return ( !( aCompareFlags & FLAGS::EXCLUDE_FROM_SIM ) || excludedFromSim == aOther.excludedFromSim )
2609 && ( !( aCompareFlags & FLAGS::EXCLUDE_FROM_BOM ) || excludedFromBOM == aOther.excludedFromBOM )
2610 && ( !( aCompareFlags & FLAGS::EXCLUDE_FROM_BOARD ) || excludedFromBoard == aOther.excludedFromBoard )
2611 && ( !( aCompareFlags & FLAGS::EXCLUDE_FROM_POS_FILES )
2613 && ( !( aCompareFlags & FLAGS::DNP ) || dnp == aOther.dnp );
2614}
2615
2616
2617int LIB_SYMBOL::Compare( const LIB_SYMBOL& aRhs, int aCompareFlags, REPORTER* aReporter ) const
2618{
2619 UNITS_PROVIDER unitsProvider( schIUScale, EDA_UNITS::MM );
2620
2621 if( m_me == aRhs.m_me )
2622 return 0;
2623
2624 int retv = 0;
2625
2626 if( aCompareFlags & COMPARE_FLAGS::IDENTITY )
2627 {
2628 if( int tmp = m_name.Cmp( aRhs.m_name ) )
2629 {
2630 retv = tmp;
2631 REPORT( _( "Name differs." ) );
2632
2633 if( !aReporter )
2634 return retv;
2635 }
2636
2637 if( int tmp = m_libId.compare( aRhs.m_libId ) )
2638 {
2639 retv = tmp;
2640 REPORT( _( "Library ID differs." ) );
2641
2642 if( !aReporter )
2643 return retv;
2644 }
2645
2646 if( m_parent.lock() < aRhs.m_parent.lock() )
2647 retv = -1;
2648 else if( m_parent.lock() > aRhs.m_parent.lock() )
2649 retv = 1;
2650
2651 if( retv )
2652 {
2653 REPORT( _( "Symbol parent differs." ) );
2654
2655 if( !aReporter )
2656 return retv;
2657 }
2658 }
2659
2660 if( m_options != aRhs.m_options )
2661 {
2662 retv = ( m_options == ENTRY_NORMAL ) ? -1 : 1;
2663 REPORT( _( "Power flag differs." ) );
2664
2665 if( !aReporter )
2666 return retv;
2667 }
2668
2669 if( int tmp = m_unitCount - aRhs.m_unitCount )
2670 {
2671 retv = tmp;
2672 REPORT( _( "Unit count differs." ) );
2673
2674 if( !aReporter )
2675 return retv;
2676 }
2677
2678 // Make sure shapes are sorted. No need with fields or pins as those are matched by id/name and number.
2679
2680 std::set<const SCH_ITEM*, SCH_ITEM::cmp_items> aShapes;
2681 std::set<const SCH_FIELD*> aFields;
2682 std::set<const SCH_PIN*> aPins;
2683
2684 for( auto it = m_drawings.begin(); it != m_drawings.end(); ++it )
2685 {
2686 if( it->Type() == SCH_SHAPE_T )
2687 aShapes.insert( &( *it ) );
2688 else if( it->Type() == SCH_FIELD_T )
2689 aFields.insert( static_cast<const SCH_FIELD*>( &( *it ) ) );
2690 else if( it->Type() == SCH_PIN_T )
2691 aPins.insert( static_cast<const SCH_PIN*>( &( *it ) ) );
2692 }
2693
2694 std::set<const SCH_ITEM*, SCH_ITEM::cmp_items> bShapes;
2695 std::set<const SCH_FIELD*> bFields;
2696 std::set<const SCH_PIN*> bPins;
2697
2698 for( auto it = aRhs.m_drawings.begin(); it != aRhs.m_drawings.end(); ++it )
2699 {
2700 if( it->Type() == SCH_SHAPE_T )
2701 bShapes.insert( &( *it ) );
2702 else if( it->Type() == SCH_FIELD_T )
2703 bFields.insert( static_cast<const SCH_FIELD*>( &( *it ) ) );
2704 else if( it->Type() == SCH_PIN_T )
2705 bPins.insert( static_cast<const SCH_PIN*>( &( *it ) ) );
2706 }
2707
2708 if( int tmp = static_cast<int>( aShapes.size() - bShapes.size() ) )
2709 {
2710 retv = tmp;
2711 REPORT( _( "Graphic item count differs." ) );
2712
2713 if( !aReporter )
2714 return retv;
2715 }
2716 else
2717 {
2718 for( auto aIt = aShapes.begin(), bIt = bShapes.begin(); aIt != aShapes.end(); aIt++, bIt++ )
2719 {
2720 if( int tmp2 = ( *aIt )->compare( *( *bIt ), aCompareFlags ) )
2721 {
2722 retv = tmp2;
2723 REPORT( wxString::Format( _( "Graphic item differs: %s; %s." ),
2724 ITEM_DESC( *aIt ),
2725 ITEM_DESC( *bIt ) ) );
2726
2727 if( !aReporter )
2728 return retv;
2729 }
2730 }
2731 }
2732
2733 for( const SCH_PIN* aPin : aPins )
2734 {
2735 const SCH_PIN* bPin = aRhs.GetPin( aPin->GetNumber(), aPin->GetUnit(), aPin->GetBodyStyle() );
2736
2737 if( !bPin )
2738 {
2739 retv = 1;
2740 REPORT( wxString::Format( _( "Extra pin in schematic symbol: %s." ), ITEM_DESC( aPin ) ) );
2741
2742 if( !aReporter )
2743 return retv;
2744 }
2745 else if( int tmp = static_cast<const SCH_ITEM*>( aPin )->compare( *bPin, aCompareFlags ) )
2746 {
2747 retv = tmp;
2748 REPORT( wxString::Format( _( "Pin %s differs: %s; %s" ),
2749 aPin->GetNumber(),
2750 ITEM_DESC( aPin ),
2751 ITEM_DESC( bPin ) ) );
2752
2753 if( !aReporter )
2754 return retv;
2755 }
2756 }
2757
2758 for( const SCH_PIN* bPin : bPins )
2759 {
2760 const SCH_PIN* aPin = GetPin( bPin->GetNumber(), bPin->GetUnit(), bPin->GetBodyStyle() );
2761
2762 if( !aPin )
2763 {
2764 retv = 1;
2765 REPORT( wxString::Format( _( "Missing pin in schematic symbol: %s." ), ITEM_DESC( bPin ) ) );
2766
2767 if( !aReporter )
2768 return retv;
2769 }
2770 }
2771
2772 for( const SCH_FIELD* aField : aFields )
2773 {
2774 const SCH_FIELD* bField = nullptr;
2775
2776 if( aField->IsMandatory() )
2777 bField = aRhs.GetField( aField->GetId() );
2778 else
2779 bField = aRhs.GetField( aField->GetName() );
2780
2781 if( !bField )
2782 {
2783 if( aCompareFlags & COMPARE_FLAGS::EXTRA_FIELDS )
2784 {
2785 retv = 1;
2786 REPORT( wxString::Format( _( "Extra field in schematic symbol: %s." ), aField->GetName( false ) ) );
2787
2788 if( !aReporter )
2789 return retv;
2790 }
2791 }
2792 else
2793 {
2794 if( ( aCompareFlags & COMPARE_FLAGS::FIELD_TEXT ) && aField->GetId() != FIELD_T::REFERENCE )
2795 {
2796 if( int tmp = aField->GetText().compare( bField->GetText() ) )
2797 {
2798 retv = tmp;
2799 REPORT( wxString::Format( _( "Field '%s' differs: %s; %s." ),
2800 aField->GetName( false ),
2801 aField->GetText(),
2802 bField->GetText() ) );
2803
2804 if( !aReporter )
2805 return retv;
2806 }
2807 }
2808
2809 if( aCompareFlags & COMPARE_FLAGS::FIELD_SIZE_AND_STYLE )
2810 {
2811 if( aField->GetFont() != bField->GetFont() )
2812 {
2813 retv = std::less<KIFONT::FONT*>{}( aField->GetFont(), bField->GetFont() ) ? -1 : 1;
2814 REPORT( wxString::Format( _( "Field '%s' fonts differ." ), aField->GetName( false ) ) );
2815
2816 if( !aReporter )
2817 return retv;
2818 }
2819
2820 if( aField->GetTextSize() != bField->GetTextSize() )
2821 {
2822 if( aField->GetTextSize().x != bField->GetTextSize().x )
2823 retv = aField->GetTextSize().x - bField->GetTextSize().x;
2824 else
2825 retv = aField->GetTextSize().y - bField->GetTextSize().y;
2826
2827 REPORT( wxString::Format( _( "Field '%s' text sizes differ." ), aField->GetName( false ) ) );
2828
2829 if( !aReporter )
2830 return retv;
2831 }
2832
2833 if( int tmp = aField->GetAttributes().Compare( bField->GetAttributes() ) )
2834 {
2835 retv = tmp;
2836 REPORT( wxString::Format( _( "Field '%s' text styles differ." ), aField->GetName( false ) ) );
2837
2838 if( !aReporter )
2839 return retv;
2840 }
2841 }
2842
2843 if( aCompareFlags & COMPARE_FLAGS::FIELD_VISIBILITY )
2844 {
2845 if( aField->IsVisible() != bField->IsVisible() )
2846 {
2847 retv = aField->IsVisible() ? 1 : -1;
2848 REPORT( wxString::Format( _( "Field '%s' visibility flags differ." ), aField->GetName( false ) ) );
2849
2850 if( !aReporter )
2851 return retv;
2852 }
2853
2854 if( aField->IsNameShown() != bField->IsNameShown() )
2855 {
2856 retv = aField->IsNameShown() ? 1 : -1;
2857 REPORT( wxString::Format( _( "Field '%s' name shown flags differ." ), aField->GetName( false ) ) );
2858
2859 if( !aReporter )
2860 return retv;
2861 }
2862 }
2863
2864 if( aField->IsPrivate() != bField->IsPrivate() )
2865 {
2866 retv = aField->IsPrivate() ? 1 : -1;
2867 REPORT( wxString::Format( _( "Field '%s' privacy flags differ." ), aField->GetName( false ) ) );
2868
2869 if( !aReporter )
2870 return retv;
2871 }
2872
2873 if( aCompareFlags & COMPARE_FLAGS::FIELD_POSITIONS )
2874 {
2875 if( aField->GetPosition() != bField->GetPosition() )
2876 {
2877 if( aField->GetPosition().x != bField->GetPosition().x )
2878 retv = aField->GetPosition().x - bField->GetPosition().x;
2879 else if( aField->GetPosition().y != bField->GetPosition().y )
2880 retv = aField->GetPosition().y - bField->GetPosition().y;
2881
2882 REPORT( wxString::Format( _( "Field '%s' positions differ." ), aField->GetName( false ) ) );
2883
2884 if( !aReporter )
2885 return retv;
2886 }
2887 }
2888 }
2889 }
2890
2891 if( aCompareFlags & COMPARE_FLAGS::MISSING_FIELDS )
2892 {
2893 for( const SCH_FIELD* bField : bFields )
2894 {
2895 const SCH_FIELD* aField = nullptr;
2896
2897 if( bField->IsMandatory() )
2898 aField = GetField( bField->GetId() );
2899 else
2900 aField = GetField( bField->GetName() );
2901
2902 if( !aField )
2903 {
2904 retv = 1;
2905 REPORT( wxString::Format( _( "Missing field in schematic symbol: %s." ), bField->GetName( false ) ) );
2906
2907 if( !aReporter )
2908 return retv;
2909 }
2910 }
2911 }
2912
2913 if( int tmp = static_cast<int>( m_fpFilters.GetCount() - aRhs.m_fpFilters.GetCount() ) )
2914 {
2915 retv = tmp;
2916 REPORT( _( "Footprint filter count differs." ) );
2917
2918 if( !aReporter )
2919 return retv;
2920 }
2921 else
2922 {
2923 for( size_t i = 0; i < m_fpFilters.GetCount(); i++ )
2924 {
2925 if( int tmp2 = m_fpFilters[i].Cmp( aRhs.m_fpFilters[i] ) )
2926 {
2927 retv = tmp2;
2928 REPORT( _( "Footprint filters differ." ) );
2929
2930 if( !aReporter )
2931 return retv;
2932 }
2933 }
2934 }
2935
2936 if( int tmp = static_cast<int>( m_pinMaps.GetAll().size() - aRhs.m_pinMaps.GetAll().size() ) )
2937 {
2938 retv = tmp;
2939 REPORT( _( "Pin map count differs." ) );
2940
2941 if( !aReporter )
2942 return retv;
2943 }
2944 else if( m_pinMaps != aRhs.m_pinMaps )
2945 {
2946 retv = 1;
2947 REPORT( _( "Pin maps differ." ) );
2948
2949 if( !aReporter )
2950 return retv;
2951 }
2952
2953 if( int tmp = static_cast<int>( m_associatedFootprints.size() - aRhs.m_associatedFootprints.size() ) )
2954 {
2955 retv = tmp;
2956 REPORT( _( "Associated footprint count differs." ) );
2957
2958 if( !aReporter )
2959 return retv;
2960 }
2962 {
2963 retv = 1;
2964 REPORT( _( "Associated footprints differ." ) );
2965
2966 if( !aReporter )
2967 return retv;
2968 }
2969
2970 if( int tmp = m_keyWords.Cmp( aRhs.m_keyWords ) )
2971 {
2972 retv = tmp;
2973 REPORT( _( "Symbol keywords differ." ) );
2974
2975 if( !aReporter )
2976 return retv;
2977 }
2978
2979 if( int tmp = m_pinNameOffset - aRhs.m_pinNameOffset )
2980 {
2981 retv = tmp;
2982 REPORT( _( "Symbol pin name offsets differ." ) );
2983
2984 if( !aReporter )
2985 return retv;
2986 }
2987
2988 if( aCompareFlags & COMPARE_FLAGS::PIN_VISIBILITIES )
2989 {
2990 if( m_showPinNames != aRhs.m_showPinNames )
2991 {
2992 retv = ( m_showPinNames ) ? 1 : -1;
2993 REPORT( _( "Show pin names settings differ." ) );
2994
2995 if( !aReporter )
2996 return retv;
2997 }
2998
3000 {
3001 retv = ( m_showPinNumbers ) ? 1 : -1;
3002 REPORT( _( "Show pin numbers settings differ." ) );
3003
3004 if( !aReporter )
3005 return retv;
3006 }
3007 }
3008
3009 if( aCompareFlags & COMPARE_FLAGS::EXCLUDE_FROM_SIM )
3010 {
3012 {
3013 retv = ( m_excludedFromSim ) ? -1 : 1;
3014 REPORT( _( "Exclude from simulation settings differ." ) );
3015
3016 if( !aReporter )
3017 return retv;
3018 }
3019 }
3020
3021 if( aCompareFlags & COMPARE_FLAGS::EXCLUDE_FROM_BOM )
3022 {
3024 {
3025 retv = ( m_excludedFromBOM ) ? -1 : 1;
3026 REPORT( _( "Exclude from bill of materials settings differ." ) );
3027
3028 if( !aReporter )
3029 return retv;
3030 }
3031 }
3032
3033 if( aCompareFlags & COMPARE_FLAGS::EXCLUDE_FROM_BOARD )
3034 {
3036 {
3037 retv = ( m_excludedFromBoard ) ? -1 : 1;
3038 REPORT( _( "Exclude from board settings differ." ) );
3039
3040 if( !aReporter )
3041 return retv;
3042 }
3043 }
3044
3045 if( aCompareFlags & COMPARE_FLAGS::DNP )
3046 {
3047 if( m_DNP != aRhs.m_DNP )
3048 {
3049 retv = ( m_DNP ) ? -1 : 1;
3050 REPORT( _( "Do not populate settings differ." ) );
3051
3052 if( !aReporter )
3053 return retv;
3054 }
3055 }
3056
3057 if( aCompareFlags & COMPARE_FLAGS::EXCLUDE_FROM_POS_FILES )
3058 {
3060 {
3061 retv = ( m_excludedFromPosFiles ) ? -1 : 1;
3062 REPORT( _( "Exclude from position files settings differ." ) );
3063
3064 if( !aReporter )
3065 return retv;
3066 }
3067 }
3068
3069 if( !aReporter )
3070 {
3071 if( m_unitsLocked != aRhs.m_unitsLocked )
3072 return ( m_unitsLocked ) ? 1 : -1;
3073
3074 // Compare unit display names...
3076 return -1;
3077 else if( m_unitDisplayNames > aRhs.m_unitDisplayNames )
3078 return 1;
3079
3080 // ... and body style names.
3082 return -1;
3083 else if( m_bodyStyleNames > aRhs.m_bodyStyleNames )
3084 return 1;
3085 }
3086
3087 return retv;
3088}
3089
3090
3091int LIB_SYMBOL::compare( const SCH_ITEM& aOther, int aCompareFlags ) const
3092{
3093 if( Type() != aOther.Type() )
3094 return Type() - aOther.Type();
3095
3096 const LIB_SYMBOL* tmp = static_cast<const LIB_SYMBOL*>( &aOther );
3097
3098 return Compare( *tmp, aCompareFlags );
3099}
3100
3101
3102double LIB_SYMBOL::Similarity( const SCH_ITEM& aOther ) const
3103{
3104 wxCHECK( aOther.Type() == LIB_SYMBOL_T, 0.0 );
3105
3106 const LIB_SYMBOL& other = static_cast<const LIB_SYMBOL&>( aOther );
3107 double similarity = 0.0;
3108 int totalItems = 0;
3109
3110 if( m_Uuid == aOther.m_Uuid )
3111 return 1.0;
3112
3113 for( const SCH_ITEM& item : m_drawings )
3114 {
3115 totalItems += 1;
3116 double max_similarity = 0.0;
3117
3118 for( const SCH_ITEM& otherItem : other.m_drawings )
3119 {
3120 double temp_similarity = item.Similarity( otherItem );
3121 max_similarity = std::max( max_similarity, temp_similarity );
3122
3123 if( max_similarity == 1.0 )
3124 break;
3125 }
3126
3127 similarity += max_similarity;
3128 }
3129
3130 for( const SCH_PIN* pin : GetGraphicalPins( 0, 0 ) )
3131 {
3132 totalItems += 1;
3133 double max_similarity = 0.0;
3134
3135 for( const SCH_PIN* otherPin : other.GetGraphicalPins( 0, 0 ) )
3136 {
3137 double temp_similarity = pin->Similarity( *otherPin );
3138 max_similarity = std::max( max_similarity, temp_similarity );
3139
3140 if( max_similarity == 1.0 )
3141 break;
3142 }
3143
3144 similarity += max_similarity;
3145 }
3146
3147 if( totalItems == 0 )
3148 similarity = 0.0;
3149 else
3150 similarity /= totalItems;
3151
3153 similarity *= 0.9;
3154
3156 similarity *= 0.9;
3157
3159 similarity *= 0.9;
3160
3162 similarity *= 0.9;
3163
3164 if( m_flags != other.m_flags )
3165 similarity *= 0.9;
3166
3167 if( m_unitCount != other.m_unitCount )
3168 similarity *= 0.5;
3169
3170 if( GetBodyStyleCount() != other.GetBodyStyleCount() )
3171 similarity *= 0.5;
3172 else if( m_bodyStyleNames != other.m_bodyStyleNames )
3173 similarity *= 0.9;
3174
3175 if( m_pinNameOffset != other.m_pinNameOffset )
3176 similarity *= 0.9;
3177
3178 if( m_showPinNames != other.m_showPinNames )
3179 similarity *= 0.9;
3180
3181 if( m_showPinNumbers != other.m_showPinNumbers )
3182 similarity *= 0.9;
3183
3184 return similarity;
3185}
3186
3187
3189{
3190 return static_cast<EMBEDDED_FILES*>( this );
3191}
3192
3193
3195{
3196 return static_cast<const EMBEDDED_FILES*>( this );
3197}
3198
3199
3200void LIB_SYMBOL::AppendParentEmbeddedFiles( std::vector<EMBEDDED_FILES*>& aStack ) const
3201{
3202 std::set<const LIB_SYMBOL*> visited;
3203 visited.insert( this );
3204
3205 std::vector<EMBEDDED_FILES*> ancestralEmbeddedFiles;
3206
3207 std::shared_ptr<LIB_SYMBOL> parent = m_parent.lock();
3208
3209 while( parent )
3210 {
3211 // Cycle detected - parent chain points back to an already visited symbol
3212 if( visited.count( parent.get() ) )
3213 {
3214 wxLogTrace( traceSymbolInheritance,
3215 wxT( "AppendParentEmbeddedFiles: Circular inheritance detected in symbol '%s' (lib: %s)" ),
3216 m_name, m_libId.GetLibNickname().wx_str() );
3217 break;
3218 }
3219
3220 visited.insert( parent.get() );
3221 ancestralEmbeddedFiles.push_back( parent->GetEmbeddedFiles() );
3222 parent = parent->GetParent().lock();
3223 }
3224
3225 // Embedded files stack goes from most-global to most-local
3226 for( EMBEDDED_FILES* files : std::ranges::reverse_view( ancestralEmbeddedFiles ) )
3227 aStack.push_back( files );
3228}
3229
3230
3231std::set<KIFONT::OUTLINE_FONT*> LIB_SYMBOL::GetFonts() const
3232{
3234
3235 std::set<KIFONT::OUTLINE_FONT*> fonts;
3236
3237 auto processFont =
3238 [&]( KIFONT::FONT* font )
3239 {
3240 if( font && !font->IsStroke() )
3241 {
3242 KIFONT::OUTLINE_FONT* outline = static_cast<KIFONT::OUTLINE_FONT*>( font );
3243 PERMISSION permission = outline->GetEmbeddingPermission();
3244
3245 if( permission == PERMISSION::EDITABLE || permission == PERMISSION::INSTALLABLE )
3246 fonts.insert( outline );
3247 }
3248 };
3249
3250 for( const SCH_ITEM& item : m_drawings )
3251 {
3252 // Use dynamic_cast to catch SCH_TEXTBOX, SCH_TABLECELL, etc.
3253 if( const SCH_TEXT* text = dynamic_cast<const SCH_TEXT*>( &item ) )
3254 processFont( text->GetFont() );
3255 else if( const SCH_FIELD* field = dynamic_cast<const SCH_FIELD*>( &item ) )
3256 processFont( field->GetFont() );
3257 }
3258
3259 return fonts;
3260}
3261
3262
3264{
3265 std::set<KIFONT::OUTLINE_FONT*> fonts = GetFonts();
3266
3267 for( KIFONT::OUTLINE_FONT* font : fonts )
3268 {
3269 auto file = GetEmbeddedFiles()->AddFile( font->GetFileName(), false );
3270
3271 if( !file )
3272 {
3273 wxLogTrace( "EMBED", "Failed to add font file: %s", font->GetFileName() );
3274 continue;
3275 }
3276
3278 }
3279}
3280
3281static struct LIB_SYMBOL_DESC
3282{
3284 {
3288
3289 const wxString groupFields = _HKI( "Fields" );
3290
3291 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Reference" ),
3293 groupFields );
3294 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Value" ),
3296 groupFields );
3297 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Footprint" ),
3299 groupFields );
3300 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Datasheet" ),
3302 groupFields );
3303 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Keywords" ),
3305 groupFields );
3306
3307 const wxString groupSymbolDef = _HKI( "Symbol Definition" );
3308
3309 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Define as Power Symbol" ),
3311 groupSymbolDef );
3312 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Define as Local Power Symbol" ),
3314 groupSymbolDef );
3315
3316 const wxString groupPinDisplay = _HKI( "Pin Display" );
3317
3318 propMgr.AddProperty( new PROPERTY<SYMBOL, bool>( _HKI( "Show Pin Number" ),
3320 groupPinDisplay );
3321 propMgr.AddProperty( new PROPERTY<SYMBOL, bool>( _HKI( "Show Pin Name" ),
3323 groupPinDisplay );
3324 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Place Pin Names Inside" ),
3326 groupPinDisplay );
3327 propMgr.AddProperty( new PROPERTY<SYMBOL, int>( _HKI( "Pin Name Position Offset" ),
3329 groupPinDisplay );
3330
3331 const wxString groupAttributes = _HKI( "Attributes" );
3332
3333 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Exclude from Simulation" ),
3335 groupAttributes );
3336 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Exclude from Board" ),
3338 groupAttributes );
3339 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Exclude from Bill of Materials" ),
3341 groupAttributes );
3342 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Exclude from Position Files" ),
3344 groupAttributes );
3345
3346 const wxString groupUnits = _HKI( "Units and Body Styles" );
3347
3348 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, int>( _HKI( "Number of Symbol Units" ),
3350 groupUnits );
3351 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, bool>( _HKI( "Units are Interchangeable" ),
3353 groupUnits );
3354
3355 auto multiBodyStyle =
3356 [=]( INSPECTABLE* aItem ) -> bool
3357 {
3358 if( LIB_SYMBOL* symbol = dynamic_cast<LIB_SYMBOL*>( aItem ) )
3359 return symbol->IsMultiBodyStyle();
3360
3361 return false;
3362 };
3363
3364 propMgr.AddProperty( new PROPERTY<LIB_SYMBOL, wxString>( _HKI( "Body Styles" ),
3366 groupUnits )
3367 .SetAvailableFunc( multiBodyStyle )
3368 .SetChoicesFunc( []( INSPECTABLE* aItem )
3369 {
3370 wxPGChoices choices;
3371
3372 if( LIB_SYMBOL* symbol = dynamic_cast<LIB_SYMBOL*>( aItem ) )
3373 {
3374 for( int ii = 1; ii <= symbol->GetBodyStyleCount(); ii++ )
3375 choices.Add( symbol->GetBodyStyleDescription( ii, false ) );
3376 }
3377
3378 return choices;
3379 } );
3380 }
const char * name
std::unique_ptr< EDA_ITEM > CreateItemForType(KICAD_T aType, EDA_ITEM *aContainer)
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
static double square(double x)
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition box2.h:597
static const COLOR4D WHITE
Definition color4d.h:403
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:400
virtual void ClearEditFlags()
Definition eda_item.h:178
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearSelected()
Definition eda_item.h:153
EDA_ITEM_FLAGS m_flags
Definition eda_item.h:608
virtual EDA_ITEM * Clone() const
Create a duplicate of this item with linked list members set to NULL.
Definition eda_item.cpp:288
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
EDA_ITEM_FLAGS GetFlags() const
Definition eda_item.h:167
virtual void ClearTempFlags()
Definition eda_item.h:191
FILL_T GetFillMode() const
Definition eda_shape.h:151
virtual VECTOR2I GetTextSize() const
Definition eda_text.h:301
virtual VECTOR2I GetTextPos() const
Definition eda_text.h:313
virtual bool IsVisible() const
Definition eda_text.h:226
KIFONT::FONT * GetFont() const
Definition eda_text.h:286
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:395
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:270
bool IsEmpty() const
EMBEDDED_FILES & operator=(EMBEDDED_FILES &&other) noexcept
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
const std::map< wxString, std::shared_ptr< EMBEDDED_FILE > > & EmbeddedFileMap() const
Provide an iterable view of the file collection.
EMBEDDED_FILES()=default
void SetAreFontsEmbedded(bool aEmbedFonts)
bool GetAreFontsEmbedded() const
Class that other classes need to inherit from, in order to be inspectable.
Definition inspectable.h:39
Represents an (ordered) list of JUMPER_GROUP objects.
void Add(JUMPER_GROUP aGroup)
Add a JUMPER_GROUP to the set.
Represents a group of jumper pins or pads, keyed by name.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
Implement outline font drawing.
EMBEDDING_PERMISSION GetEmbeddingPermission() const
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
std::shared_ptr< wxString > m_text
Definition color4d.h:397
COLOR4D & Desaturate()
Removes color (in HSL model)
Definition color4d.cpp:530
COLOR4D Mix(const COLOR4D &aColor, double aFactor) const
Return a color that is mixed with the input by a factor.
Definition color4d.h:293
const COLOR4D & GetLayerColor(int aLayer) const
Return the color used to draw a layer.
Object used to load, save, search, and otherwise manipulate symbol library files.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int SetLibItemName(const UTF8 &aLibItemName)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition lib_id.cpp:124
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
Define a library symbol object.
Definition lib_symbol.h:114
std::vector< SEARCH_TERM > & GetSearchTerms() override
LIB_ITEMS_CONTAINER m_drawings
SCH_FIELD & GetDescriptionField()
Definition lib_symbol.h:465
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:190
const BOX2I GetUnitBoundingBox(int aUnit, int aBodyStyle, bool aIgnoreHiddenFields=true, bool aIgnoreLabelsOnInvisiblePins=true) const
Get the bounding box for the symbol.
wxString GetKeyWords() const override
Definition lib_symbol.h:220
void SetGlobalPower()
std::weak_ptr< LIB_SYMBOL > & GetParent()
Definition lib_symbol.h:152
wxString GetBodyStyleProp() const override
Definition lib_symbol.h:600
LIBRENTRYOPTIONS m_options
Special symbol features such as POWER or NORMAL.
void rebuildCaches() const
int GetPinCount() const override
wxString GetRefProp() const
Definition lib_symbol.h:484
bool PinsConflictWith(const LIB_SYMBOL &aOtherSymbol, bool aTestNums, bool aTestNames, bool aTestType, bool aTestOrientation, bool aTestLength) const
Return true if this symbol's pins do not match another symbol's pins.
bool GetUnitsInterchangeableProp() const
Definition lib_symbol.h:590
wxString m_shownDescriptionCache
void GetFields(std::vector< SCH_FIELD * > &aList, bool aVisibleOnly=false) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
bool IsPower() const override
wxString GetPrefix()
bool m_cachesDirty
const std::vector< ASSOCIATED_FOOTPRINT > & GetEffectiveAssociatedFootprints() const
Definition lib_symbol.h:302
bool UnitsLocked() const
Check whether symbol units are interchangeable.
SCH_FIELD & GetDatasheetField()
Definition lib_symbol.h:461
void RefreshLibraryTreeCaches()
std::weak_ptr< LIB_SYMBOL > m_parent
Use for inherited symbols.
void SetExcludedFromBoardProp(bool aExclude)
Definition lib_symbol.h:629
std::vector< struct LIB_SYMBOL_UNIT > GetUnitDrawItems()
Return a list of SCH_ITEM objects separated by unit and convert number.
std::map< int, wxString > m_unitDisplayNames
void ClearTempFlags() override
Clears the status flag all draw objects in this symbol.
void Serialize(kiapi::schematic::types::SchematicSymbol &aOutput, bool aSkipPins=false) const
void SetKeywordsProp(const wxString &aKeywords)
Definition lib_symbol.h:533
bool IsDerived() const
Definition lib_symbol.h:241
std::map< int, wxString > & GetUnitDisplayNames()
Definition lib_symbol.h:883
void SetDuplicatePinNumbersAreJumpers(bool aEnabled)
Definition lib_symbol.h:887
bool m_demorgan
True if there are two body styles: normal and De Morgan If false, the body style count is taken from ...
const wxString GetLibraryName() const
void SetFields(const std::vector< SCH_FIELD > &aFieldsList)
Overwrite all the existing fields in this symbol with fields supplied in aFieldsList.
void SetExcludedFromPosFilesProp(bool aExclude)
Definition lib_symbol.h:637
void SetLib(LEGACY_SYMBOL_LIB *aLibrary)
bool GetPowerSymbolProp() const
Definition lib_symbol.h:539
bool IsMultiBodyStyle() const override
Definition lib_symbol.h:904
int GetMaxPinNumber() const
std::vector< SEARCH_TERM > m_searchTermsCache
JUMPER_GROUP_SET & JumperPinGroups()
Each jumper pin group is a set of pin numbers that should be treated as internally connected.
Definition lib_symbol.h:893
void Plot(PLOTTER *aPlotter, bool aBackground, const SCH_PLOT_OPTS &aPlotOpts, int aUnit, int aBodyStyle, const VECTOR2I &aOffset, bool aDimmed) override
Plot the item to aPlotter.
SCH_FIELD * GetField(const wxString &aFieldName)
Find a field within this symbol matching aFieldName; return nullptr if not found.
SCH_FIELD & GetFootprintField()
Definition lib_symbol.h:457
void SetAssociatedFootprints(std::vector< ASSOCIATED_FOOTPRINT > aList)
Definition lib_symbol.h:274
void FixupDrawItems()
This function finds the filled draw items that are covering up smaller draw items and replaces their ...
void SetBodyStyleNames(const std::vector< wxString > &aBodyStyleNames)
Definition lib_symbol.h:915
bool IsNormal() const override
wxString m_name
void SetUnitsInterchangeableProp(bool aInterchangeable)
Definition lib_symbol.h:595
std::set< KIFONT::OUTLINE_FONT * > GetFonts() const override
LEGACY_SYMBOL_LIB * m_library
bool GetExcludedFromPosFilesProp() const
Definition lib_symbol.h:635
SCH_FIELD * FindFieldCaseInsensitive(const wxString &aFieldName)
wxString m_keyWords
Search keywords.
SCH_ITEM * LocateDrawItem(int aUnit, int aBodyStyle, KICAD_T aType, const VECTOR2I &aPoint)
Locate a draw object.
static wxString LetterSubReference(int aUnit, wxChar aInitialLetter)
double Similarity(const SCH_ITEM &aSymbol) const override
Return a measure of similarity between this symbol and aSymbol.
static LIB_SYMBOL * GetDummy()
Return a dummy LIB_SYMBOL, used when one is missing in the schematic.
void PlotFields(PLOTTER *aPlotter, bool aBackground, const SCH_PLOT_OPTS &aPlotOpts, int aUnit, int aBodyStyle, const VECTOR2I &aOffset, bool aDimmed)
Plot symbol fields.
wxString GetDatasheetProp() const
Definition lib_symbol.h:517
void LockUnits(bool aLockUnits)
Set interchangeable the property for symbol units.
Definition lib_symbol.h:376
LIB_ITEMS_CONTAINER & GetDrawItems()
Return a reference to the draw item list.
Definition lib_symbol.h:845
std::shared_ptr< LIB_SYMBOL > GetRootSymbol() const
Get the parent symbol that does not have another parent.
void SetRefProp(const wxString &aRef)
Definition lib_symbol.h:489
void SetParent(LIB_SYMBOL *aParent=nullptr)
std::vector< UNIT_PIN_INFO > GetUnitPinInfo() const
Return pin-number lists for each unit, ordered consistently for gate swapping.
wxString GetName() const override
Definition lib_symbol.h:183
void SetUnitCount(int aCount, bool aDuplicateDrawItems)
Set the units per symbol count.
void SetDescription(const wxString &aDescription)
Set the Description field text value.
std::shared_ptr< LIB_SYMBOL > m_me
wxString GetValueProp() const
Definition lib_symbol.h:495
bool GetExcludedFromBOMProp() const
Definition lib_symbol.h:619
void SetKeyWords(const wxString &aKeyWords)
SCH_FIELD & GetValueField()
Definition lib_symbol.h:449
void deleteAllUserFields()
bool IsLocalPower() const override
LIB_SYMBOL(const wxString &aName, LIB_SYMBOL *aParent=nullptr, LEGACY_SYMBOL_LIB *aLibrary=nullptr)
int GetUnitProp() const
Definition lib_symbol.h:580
wxArrayString GetFPFilters() const
Definition lib_symbol.h:254
void RemoveDrawItem(SCH_ITEM *aItem)
Remove draw aItem from list.
void GetChooserFields(std::map< wxString, wxString > &aColumnMap) override
Retrieves a key/value map of the fields on this item that should be exposed to the library browser/ch...
bool HasLegacyAlternateBodyStyle() const
Before V10 we didn't store the number of body styles in a symbol – we just looked through all its dra...
std::shared_ptr< LIB_SYMBOL > SharedPtr() const
http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/sp_techniques.html#weak_without_shared.
Definition lib_symbol.h:125
bool GetPinNamesInsideProp() const
Definition lib_symbol.h:567
const std::vector< wxString > & GetBodyStyleNames() const
bool ResolveTextVar(wxString *aToken, int aDepth=0) const
Resolve any references to system tokens supported by the symbol.
void SetBodyStyleProp(const wxString &aBodyStyle) override
Definition lib_symbol.h:605
void SetPinMaps(const PIN_MAP_SET &aPinMaps)
Definition lib_symbol.h:270
timestamp_t m_lastModDate
void SetExcludedFromSimProp(bool aExclude)
Definition lib_symbol.h:613
bool GetExcludedFromBoardProp() const
Definition lib_symbol.h:627
wxString getShownDescription(RESOLUTION_CONTEXT aContext, int aDepth) const
LIB_ID m_libId
void SetLocalPower()
JUMPER_GROUP_SET m_jumperPinGroups
A list of jumper pin groups, each of which is a set of pin numbers that should be jumpered together (...
bool HasPinNumber(const wxString &aNumber) const
Return true if aNumber names a pin of this symbol, in any unit or body style.
void SetBodyStyleCount(int aCount, bool aDuplicateDrawItems, bool aDuplicatePins)
Set the number of body styles for the symbol.
wxString GetLibNickname() const override
Definition lib_symbol.h:196
void SetFootprintProp(const wxString &aFootprint)
Definition lib_symbol.h:511
std::vector< LOGICAL_PIN > GetLogicalPins(int aUnit, int aBodyStyle) const
Return all logical pins (expanded) filtered by unit/body.
bool HasDeMorganBodyStyles() const override
const LIB_SYMBOL & operator=(const LIB_SYMBOL &aSymbol)
bool m_unitsLocked
True if symbol has multiple units and changing one unit does not automatically change another unit.
wxArrayString m_fpFilters
List of suitable footprint names for the symbol (wild card names accepted).
void Move(const VECTOR2I &aOffset) override
Move the symbol aOffset.
void SetFPFilters(const wxArrayString &aFilters)
Definition lib_symbol.h:250
const PIN_MAP_SET & GetEffectivePinMaps() const
Definition lib_symbol.h:287
void CopyFields(std::vector< SCH_FIELD > &aList)
Create a copy of the SCH_FIELDs, sorted in ordinal order.
void RunOnChildren(const std::function< void(SCH_ITEM *)> &aFunction, RECURSE_MODE aMode) override
int compare(const SCH_ITEM &aOther, int aCompareFlags=~(COMPARE_FLAGS::UUID|COMPARE_FLAGS::UNIT)) const override
The library symbol specific sort order is as follows:
bool GetExcludedFromSimProp() const
Definition lib_symbol.h:611
int GetBodyStyleCount() const override
The body styles are a property of the drawings, which a derived symbol inherits from its root symbol ...
void SetDatasheetProp(const wxString &aDatasheet)
Definition lib_symbol.h:522
INSPECT_RESULT Visit(INSPECTOR inspector, void *testData, const std::vector< KICAD_T > &aScanTypes) override
May be re-implemented for each derived class in order to handle all the types given by its member dat...
wxString GetFootprint() const override
For items with footprint fields.
EMBEDDED_FILES * GetEmbeddedFiles() override
void SetPowerSymbolProp(bool aIsPower)
Definition lib_symbol.h:544
LIB_SYMBOL_ATTRIBUTES ComparisonAttributes() const
void SetExcludedFromBOMProp(bool aExclude)
Definition lib_symbol.h:621
int m_unitCount
Number of units (parts) per package.
void SyncFieldsFromParent(const LIB_FIELD_SYNC_OPTIONS &aOptions)
Reconcile this derived symbol's fields with those of its (flattened) parent.
wxString GetShownKeyWords(RESOLUTION_CONTEXT aContext, int aDepth=0) const override
bool IsGlobalPower() const override
wxString GetBodyStyleDescription(int aBodyStyle, bool aLabel) const override
unsigned GetInheritanceDepth() const
Get the number of parents for this symbol.
int GetUnitCount() const override
bool Deserialize(const kiapi::schematic::types::SchematicSymbol &aInput)
PIN_MAP_SET m_pinMaps
Named pin-to-pad maps owned by this symbol (issue #2282).
wxString GetKeywordsProp() const
Definition lib_symbol.h:528
std::vector< wxString > m_bodyStyleNames
void AppendParentEmbeddedFiles(std::vector< EMBEDDED_FILES * > &aStack) const
std::vector< SCH_PIN * > GetPinsByNumber(const wxString &aNumber, int aUnit=0, int aBodyStyle=0)
Return all pin objects with the requested pin aNumber.
std::unique_ptr< LIB_SYMBOL > Flatten() const
Return a flattened symbol inheritance to the caller.
BOX2I GetBodyBoundingBox() const override
Return a bounding box for the symbol body but not the pins or fields.
Definition lib_symbol.h:350
void SetValueProp(const wxString &aValue)
Definition lib_symbol.h:500
void SetParentName(const wxString &aParentName)
Definition lib_symbol.h:996
std::map< wxString, wxString > m_chooserFieldsCache
void SetLibId(const LIB_ID &aLibId)
void AddField(SCH_FIELD *aField)
Add a field.
void ClearEditFlags() override
int m_pinCountCache
bool GetLocalPowerSymbolProp() const
Definition lib_symbol.h:552
bool GetDuplicatePinNumbersAreJumpers() const
Definition lib_symbol.h:886
std::vector< SCH_PIN * > GetGraphicalPins(int aUnit=0, int aBodyStyle=0) const override
Graphical pins: Return schematic pin objects as drawn (unexpanded), filtered by unit/body.
LIB_ID GetLIB_ID() const override
Definition lib_symbol.h:185
std::vector< ASSOCIATED_FOOTPRINT > m_associatedFootprints
Footprints associated with this symbol, each tied to a named pin map.
const SCH_PIN * GetPin(const wxString &aNumber, int aUnit=0, int aBodyStyle=0) const
Return pin object with the requested pin aNumber.
bool m_duplicatePinNumbersAreJumpers
Flag that this symbol should automatically treat sets of two or more pins with the same number as jum...
void SetUnitProp(int aUnits)
Definition lib_symbol.h:585
wxString GetFootprintProp() const
Definition lib_symbol.h:506
void SetPinNamesInsideProp(bool aInside)
Definition lib_symbol.h:572
int Compare(const LIB_SYMBOL &aRhs, int aCompareFlags=~COMPARE_FLAGS::UNIT, REPORTER *aReporter=nullptr) const
Comparison test that can be used for operators.
void AddDrawItem(SCH_ITEM *aItem, bool aSort=true)
Add a new draw aItem to the draw object list and sort according to aSort.
wxString GetUnitDisplayName(int aUnit, bool aLabel) const override
Return the user-defined display name for aUnit for symbols with units.
wxString m_parentName
The name of the parent symbol or empty if root symbol.
void EmbedFonts() override
void SetLocalPowerSymbolProp(bool aIsLocalPower)
Definition lib_symbol.h:557
virtual void SetName(const wxString &aName)
void SetNormal()
void PruneBodyStyleDrawItems(int aBodyStyleCount)
Delete the draw items belonging to a body style beyond aBodyStyleCount.
SCH_FIELD & GetReferenceField()
Definition lib_symbol.h:453
wxString GetShownDescription(RESOLUTION_CONTEXT aContext, int aDepth=0) const override
int GetNextFieldOrdinal() const
Return the next ordinal for a user field for this symbol.
ITERATOR_BASE< SCH_ITEM, MULTIVECTOR< SCH_ITEM, FIRST_TYPE_VAL, LAST_TYPE_VAL >, typename ITEM_PTR_VECTOR::iterator > ITERATOR
ITERATOR end(int aType=UNDEFINED_TYPE)
ITERATOR begin(int aType=UNDEFINED_TYPE)
A symbol-owned ordered set of named pin maps.
Definition pin_map.h:124
const std::vector< PIN_MAP > & GetAll() const
Definition pin_map.h:139
void AddOrReplace(PIN_MAP aMap)
Insert aMap, replacing any existing entry with the same name.
Definition pin_map.cpp:113
A named pin map.
Definition pin_map.h:65
void SetEntry(const wxString &aPinNumber, const wxString &aPadNumber)
Set the pad number for a symbol pin.
Definition pin_map.cpp:59
Base plotter engine class.
Definition plotter.h:138
bool GetColorMode() const
Definition plotter.h:166
virtual void SetColor(const COLOR4D &color)=0
PROPERTY_BASE & SetChoicesFunc(std::function< wxPGChoices(INSPECTABLE *)> aFunc)
Definition property.h:289
PROPERTY_BASE & SetAvailableFunc(std::function< bool(INSPECTABLE *)> aFunc)
Set a callback function to determine whether an object provides this property.
Definition property.h:275
Provide class metadata.
void InheritsAfter(TYPE_ID aDerived, TYPE_ID aBase)
Declare an inheritance relationship between types.
static PROPERTY_MANAGER & Instance()
PROPERTY_BASE & AddProperty(PROPERTY_BASE *aProperty, const wxString &aGroup=wxEmptyString)
Register a property.
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
bool IsMandatory() const
wxString GetFullText(int unit=1) const
Return the text of a field.
VECTOR2I GetPosition() const override
bool IsNameShown() const
Definition sch_field.h:225
void SetOrdinal(int aOrdinal, FIELD_T aType)
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
FIELD_T GetId() const
Definition sch_field.h:143
wxString GetUntranslatedName() const
Get the untranslated field name for storage, variable look-up, etc.
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
wxString GetShownText(const SCH_SHEET_PATH *aPath, RESOLUTION_CONTEXT aContext, const wxString &aVariantName=wxEmptyString, int aDepth=0) const
wxString GetName(bool aUseDefaultName=true) const
Return the field name (not translated).
void SetName(const wxString &aName)
bool ShowInChooser() const
Definition sch_field.h:246
void SetText(const wxString &aText) override
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
virtual void SetBodyStyle(int aBodyStyle)
Definition sch_item.h:252
int m_unit
Definition sch_item.h:844
int m_bodyStyle
Definition sch_item.h:845
SCH_RENDER_SETTINGS * getRenderSettings(PLOTTER *aPlotter) const
Definition sch_item.cpp:46
void SetPrivate(bool aPrivate)
Definition sch_item.h:258
SCHEMATIC * Schematic() const
Search the item hierarchy to find a SCHEMATIC.
Definition sch_item.cpp:302
friend class LIB_SYMBOL
Definition sch_item.h:822
COMPARE_FLAGS
The list of flags used by various compare functions.
Definition sch_item.h:749
@ MISSING_FIELDS
Definition sch_item.h:753
@ EXCLUDE_FROM_BOARD
Definition sch_item.h:762
@ FIELD_VISIBILITY
Definition sch_item.h:756
@ EXCLUDE_FROM_POS_FILES
Definition sch_item.h:765
@ EXTRA_FIELDS
Definition sch_item.h:754
@ FIELD_SIZE_AND_STYLE
Definition sch_item.h:757
@ EXCLUDE_FROM_BOM
Definition sch_item.h:764
@ FIELD_TEXT
Definition sch_item.h:755
@ EXCLUDE_FROM_SIM
Definition sch_item.h:761
@ FIELD_POSITIONS
Definition sch_item.h:758
@ PIN_VISIBILITIES
Definition sch_item.h:759
bool IsPrivate() const
Definition sch_item.h:259
void SetLayer(SCH_LAYER_ID aLayer)
Definition sch_item.h:354
virtual void SetUnit(int aUnit)
Definition sch_item.h:242
SCH_ITEM(EDA_ITEM *aParent, KICAD_T aType, int aUnit=0, int aBodyStyle=0)
Definition sch_item.cpp:65
wxString ResolveText(const wxString &aText, const SCH_SHEET_PATH *aPath, int aDepth=0) const
Definition sch_item.cpp:464
VECTOR2I GetPosition() const override
Definition sch_pin.cpp:381
const KIGFX::COLOR4D & GetBackgroundColor() const override
Return current background color settings.
A base class for LIB_SYMBOL and SCH_SYMBOL.
Definition symbol.h:60
bool m_DNP
True if symbol is set to 'Do Not Populate'.
Definition symbol.h:278
bool GetExcludedFromPosFiles(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:231
void SetExcludedFromBoard(bool aExclude, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear exclude from board netlist flag.
Definition symbol.h:210
bool m_showPinNumbers
Definition symbol.h:272
bool m_excludedFromPosFiles
Definition symbol.h:277
SYMBOL(KICAD_T idType)
Definition symbol.h:62
bool m_excludedFromSim
Definition symbol.h:274
virtual bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flag.
Definition symbol.h:240
virtual void SetShowPinNumbers(bool aShow)
Set or clear the pin number visibility flag.
Definition symbol.h:174
bool m_showPinNames
Definition symbol.h:271
int GetPinNameOffset() const
Definition symbol.h:163
virtual void SetShowPinNames(bool aShow)
Set or clear the pin name visibility flag.
Definition symbol.h:168
bool m_excludedFromBOM
Definition symbol.h:275
virtual void SetExcludedFromSim(bool aExcludeFromSim, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from simulation flag.
Definition symbol.h:180
virtual bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:201
virtual void SetDNP(bool aDNP, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Definition symbol.h:242
bool m_excludedFromBoard
Definition symbol.h:276
virtual bool GetShowPinNames() const
Definition symbol.h:169
void SetPinNameOffset(int aOffset)
Set the offset in mils of the pin name text from the pin symbol.
Definition symbol.h:162
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:216
void SetExcludedFromPosFiles(bool aExclude, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear exclude from position files flag.
Definition symbol.h:225
virtual bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:186
SYMBOL & operator=(const SYMBOL &aItem)
Definition symbol.h:90
virtual bool GetShowPinNumbers() const
Definition symbol.h:175
virtual void SetExcludedFromBOM(bool aExcludeFromBOM, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) override
Set or clear the exclude from schematic bill of materials flag.
Definition symbol.h:195
int m_pinNameOffset
The offset in mils to draw the pin name.
Definition symbol.h:269
for transforming drawing coordinates for a wxDC device context.
Definition transform.h:42
wxString wx_str() const
Definition utf8.cpp:41
wxString ResolveTextVars(const wxString &aSource, const std::function< bool(wxString *)> *aResolver, int &aDepth)
Multi-pass text variable expansion and math expression evaluation.
Definition common.cpp:333
RESOLUTION_CONTEXT
Definition common.h:91
@ FOR_GUI
Definition common.h:93
@ RAW_VALUE
Definition common.h:98
@ INTERNAL
Definition common.h:96
#define DEFAULT_PIN_NAME_OFFSET
The offset of the pin name string from the end of the pin in mils.
static wxString displayName(const DATABASE_LIB_TABLE &aTable)
#define _(s)
@ FILLED_WITH_COLOR
Definition eda_fill.h:33
@ FILLED_WITH_BG_BODYCOLOR
Definition eda_fill.h:32
RECURSE_MODE
Definition eda_item.h:50
INSPECT_RESULT
Definition eda_item.h:44
const INSPECTOR_FUNC & INSPECTOR
std::function passed to nested users by ref, avoids copying std::function.
Definition eda_item.h:91
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
#define IS_NEW
New item, just created.
#define STRUCT_DELETED
flag indication structures to be erased
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
TRANSFORM DefaultTransform
Definition transform.cpp:28
const wxChar *const traceSymbolInheritance
Flag to enable tracing of circular symbol inheritance detection.
const wxChar *const traceStackedPins
Flag to enable debug output for stacked pins handling in symbol/pin code.
@ LAYER_DEVICE
Definition layer_ids.h:497
@ LAYER_FIELDS
Definition layer_ids.h:493
Definition for symbol library class.
#define REPORT(msg)
static std::shared_ptr< LIB_SYMBOL > GetSafeRootSymbol(const LIB_SYMBOL *aSymbol, const char *aCallerName)
Helper to safely get the root symbol, detecting and logging circular inheritance.
static struct LIB_SYMBOL_DESC _LIB_SYMBOL_DESC
bool operator<(const LIB_SYMBOL &aItem1, const LIB_SYMBOL &aItem2)
#define ITEM_DESC(item)
LIB_ITEMS_CONTAINER::ITEM_PTR_VECTOR LIB_ITEMS
Definition lib_symbol.h:60
@ ENTRY_LOCAL_POWER
@ ENTRY_GLOBAL_POWER
KICOMMON_API int UnpackDistance(const types::Distance &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API std::optional< KICAD_T > TypeNameFromAny(const google::protobuf::Any &aMessage)
Definition api_utils.cpp:50
KICOMMON_API void PackDistance(types::Distance &aOutput, int aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API void PackLibId(types::LibraryIdentifier *aOutput, const LIB_ID &aId)
KICOMMON_API LIB_ID UnpackLibId(const types::LibraryIdentifier &aId)
#define _HKI(x)
Definition page_info.cpp:40
static const std::vector< std::string > filters
Definition plugin.cpp:64
#define TYPE_HASH(x)
Macro to generate unique identifier for a type.
Definition property.h:74
@ PT_SIZE
Size expressed in distance units (mm/inch)
Definition property.h:63
#define REGISTER_TYPE(x)
Helper macro to map type hashes to names.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition ptree.cpp:194
@ BASE
Definition sch_item.h:64
@ DEMORGAN
Definition sch_item.h:65
A first-class footprint choice on a LIB_SYMBOL, tied to a named pin map.
Definition pin_map.h:159
LIB_ID m_FootprintLibId
Definition pin_map.h:160
Options controlling how a derived symbol's fields are reconciled with its parent.
Definition lib_symbol.h:80
bool m_removeExtraFields
Drop fields not present in the parent.
Definition lib_symbol.h:88
bool m_resetPositions
Copy parent field positions.
Definition lib_symbol.h:97
bool m_resetVisibility
Copy parent visibility and name-shown flags.
Definition lib_symbol.h:91
bool m_updateAllFields
Reconcile every field. When false only the names in m_updateFields are touched.
Definition lib_symbol.h:82
std::set< wxString > m_updateFields
Field names to reconcile when m_updateAllFields is false.
Definition lib_symbol.h:85
bool m_resetEffects
Copy parent text effects (font, justification, etc.) but keep local visibility/position.
Definition lib_symbol.h:94
bool m_resetEmptyText
Copy parent text even when the parent value is empty.
Definition lib_symbol.h:103
bool m_resetText
Copy parent text when the parent value is non-empty.
Definition lib_symbol.h:100
Logical pins: Return expanded logical pins based on stacked-pin notation.
Definition lib_symbol.h:717
std::vector< wxString > m_pinNumbers
Definition lib_symbol.h:731
bool Matches(const LIB_SYMBOL_ATTRIBUTES &aOther, int aCompareFlags) const
std::map< int, wxString > unitDisplayNames
std::vector< ASSOCIATED_FOOTPRINT > associatedFootprints
std::vector< wxString > bodyStyleNames
int m_bodyStyle
The alternate body style of the unit.
Definition lib_symbol.h:69
int m_unit
The unit number.
Definition lib_symbol.h:68
One symbol-pin to footprint-pad mapping inside a PIN_MAP.
Definition pin_map.h:42
A structure for storing weighted search terms.
http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/sp_techniques.html#weak_without_shared
void operator()(void const *) const
#define ALL_UNITS
Definition symbol.h:150
#define ALL_BODY_STYLES
Definition symbol.h:151
#define MANDATORY_FIELDS
FIELD_T
The set of all field indices assuming an array like sequence that a SCH_COMPONENT or LIB_PART can hol...
@ USER
The field ID hasn't been set yet; field is invalid.
@ DESCRIPTION
Field Description of part, i.e. "1/4W 1% Metal Film Resistor".
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ DATASHEET
name of datasheet
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
KIBIS_PIN * pin
const SHAPE_LINE_CHAIN chain
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
Definition typeinfo.h:70
@ LIB_SYMBOL_T
Definition typeinfo.h:144
@ TYPE_NOT_INIT
Definition typeinfo.h:73
@ SCH_FIELD_T
Definition typeinfo.h:146
@ SCH_SHAPE_T
Definition typeinfo.h:145
@ SCH_PIN_T
Definition typeinfo.h:149
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708