KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_io_kicad_sexpr_lib_cache.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * @author Wayne Stambaugh <[email protected]>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <fmt/format.h>
23
24#include <wx/log.h>
25#include <wx/dir.h>
26
27#include <base_units.h>
28#include <build_version.h>
29#include <common.h>
30#include <sch_shape.h>
31#include <lib_symbol.h>
32#include <sch_textbox.h>
33#include <macros.h>
34#include <richio.h>
38#include <string_utils.h>
39#include <trace_helpers.h>
41
42
43SCH_IO_KICAD_SEXPR_LIB_CACHE::SCH_IO_KICAD_SEXPR_LIB_CACHE( const wxString& aFullPathAndFileName ) :
44 SCH_IO_LIB_CACHE( aFullPathAndFileName )
45{
47}
48
49
53
54
56{
57 if( !isLibraryPathValid() )
58 {
59 THROW_IO_ERROR( wxString::Format( _( "Library '%s' not found." ), m_libFileName.GetFullPath() ) );
60 }
61
62 wxCHECK_RET( m_libFileName.IsAbsolute(),
63 wxString::Format( "Cannot use relative file paths in sexpr plugin to "
64 "open library '%s'.", m_libFileName.GetFullPath() ) );
65
66 if( !m_libFileName.IsDir() )
67 {
68 wxLogTrace( traceSchLegacyPlugin, "Loading sexpr symbol library file '%s'",
69 m_libFileName.GetFullPath() );
70
71 FILE_LINE_READER reader( m_libFileName.GetFullPath() );
72
73 SCH_IO_KICAD_SEXPR_PARSER parser( &reader );
74
75 parser.ParseLib( m_symbols );
76
80
81 // Check if there were any parse warnings (symbols that failed to parse).
82 // If so, mark the library as having parse errors and throw to notify the user.
83 // The library has loaded all valid symbols, but saving would lose the bad ones.
84 const std::vector<wxString>& warnings = parser.GetParseWarnings();
85
86 if( !warnings.empty() )
87 {
88 SetParseError( true );
89
90 wxString errorMsg = wxString::Format(
91 _( "Library '%s' loaded with errors:\n\n" ), m_libFileName.GetFullPath() );
92
93 for( const wxString& warning : warnings )
94 errorMsg += warning + wxT( "\n\n" );
95
96 errorMsg += _( "The library cannot be saved until these errors are fixed manually." );
97
98 THROW_IO_ERROR( errorMsg );
99 }
100 }
101 else
102 {
103 wxString libFileName;
104
105 wxLogTrace( traceSchLegacyPlugin, "Loading sexpr symbol library folder '%s'", m_libFileName.GetPath() );
106
107 wxFileName tmp( m_libFileName.GetPath(), wxS( "dummy" ), wxString( FILEEXT::KiCadSymbolLibFileExtension ) );
108 wxDir dir( m_libFileName.GetPath() );
109 wxString fileSpec = wxS( "*." ) + wxString( FILEEXT::KiCadSymbolLibFileExtension );
110
111 if( dir.GetFirst( &libFileName, fileSpec ) )
112 {
113 wxString errorCache;
114
115 do
116 {
117 tmp.SetFullName( libFileName );
118
119 try
120 {
121 FILE_LINE_READER reader( tmp.GetFullPath() );
122 SCH_IO_KICAD_SEXPR_PARSER parser( &reader );
123
124 parser.ParseLib( m_symbols );
126
127 // Collect any parse warnings from this file
128 for( const wxString& warning : parser.GetParseWarnings() )
129 {
130 SetParseError( true );
131
132 if( !errorCache.IsEmpty() )
133 errorCache += wxT( "\n\n" );
134
135 errorCache += warning;
136 }
137 }
138 catch( const IO_ERROR& ioe )
139 {
140 // Mark that we had a parse error - saving would lose symbols
141 SetParseError( true );
142
143 if( !errorCache.IsEmpty() )
144 errorCache += wxT( "\n\n" );
145
146 errorCache += wxString::Format( _( "Unable to read file '%s'" ) + '\n', tmp.GetFullPath() );
147 errorCache += ioe.What();
148 }
149 } while( dir.GetNext( &libFileName ) );
150
151 if( !errorCache.IsEmpty() )
152 {
153 errorCache += _( "\n\nThe library cannot be saved until these errors are fixed manually." );
154 THROW_IO_ERROR( errorCache );
155 }
156 }
157
160 }
161
162 // Remember the file modification time of library file when the cache snapshot was made,
163 // so that in a networked environment we will reload the cache as needed.
165}
166
167
168void SCH_IO_KICAD_SEXPR_LIB_CACHE::Save( const std::optional<bool>& aOpt )
169{
170 if( !m_isModified )
171 return;
172
173 // If the library had a parse error during loading, we cannot safely save it.
174 // Only symbols before the parse error were loaded, so saving would permanently
175 // lose all symbols after the error point. See issue #22241.
176 if( HasParseError() )
177 {
178 THROW_IO_ERROR( wxString::Format(
179 _( "Cannot save library '%s' because it had a parse error during loading.\n\n"
180 "Saving would permanently lose symbols that could not be loaded.\n"
181 "Please fix the library file manually before saving." ),
182 m_libFileName.GetFullPath() ) );
183 }
184
185 // Write through symlinks, don't replace them.
186 wxFileName fn = GetRealFile();
187
188 if( !fn.IsDir() )
189 {
190 auto formatter = std::make_unique<PRETTIFIED_FILE_OUTPUTFORMATTER>( fn.GetFullPath() );
191
192 formatLibraryHeader( *formatter.get() );
193
194 std::vector<LIB_SYMBOL*> orderedSymbols;
195
196 for( const auto& [ name, symbol ] : m_symbols )
197 {
198 if( symbol )
199 orderedSymbols.push_back( symbol );
200 }
201
202 // Library must be ordered by inheritance depth.
203 std::sort( orderedSymbols.begin(), orderedSymbols.end(),
204 []( const LIB_SYMBOL* aLhs, const LIB_SYMBOL* aRhs )
205 {
206 unsigned int lhDepth = aLhs->GetInheritanceDepth();
207 unsigned int rhDepth = aRhs->GetInheritanceDepth();
208
209 if( lhDepth == rhDepth )
210 return aLhs->GetName() < aRhs->GetName();
211
212 return lhDepth < rhDepth;
213 } );
214
215 for( LIB_SYMBOL* symbol : orderedSymbols )
216 SaveSymbol( symbol, *formatter.get() );
217
218 formatter->Print( ")" );
219 formatter.reset();
220 }
221 else
222 {
223 if( !fn.DirExists() )
224 {
225 if( !fn.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
226 THROW_IO_ERROR( wxString::Format( _( "Cannot create symbol library path '%s'." ), fn.GetPath() ) );
227 }
228
229 for( const auto& [ name, symbol ] : m_symbols )
230 {
231 wxFileName saveFn( fn );
232 saveFn.SetName( EscapeString( name, CTX_FILENAME ) );
234
235 auto formatter = std::make_unique<PRETTIFIED_FILE_OUTPUTFORMATTER>( saveFn.GetFullPath() );
236
237 formatLibraryHeader( *formatter.get() );
238
239 SaveSymbol( symbol, *formatter.get() );
240
241 formatter->Print( ")" );
242 formatter.reset();
243 }
244 }
245
247 m_isModified = false;
248}
249
250
252 const wxString& aLibName, bool aIncludeData )
253{
254 wxCHECK_RET( aSymbol, "Invalid LIB_SYMBOL pointer." );
255
256 // If we've requested to embed the fonts in the symbol, do so.
257 // Otherwise, clear the embedded fonts from the symbol. Embedded
258 // fonts will be used if available
259 if( aSymbol->GetAreFontsEmbedded() )
260 aSymbol->EmbedFonts();
261 else
263
264 std::vector<SCH_FIELD*> orderedFields;
265 std::string name = aFormatter.Quotew( aSymbol->GetLibId().GetLibItemName().wx_str() );
266 std::string unitName = aSymbol->GetLibId().GetLibItemName();
267
268 if( !aLibName.IsEmpty() )
269 {
270 name = aFormatter.Quotew( aLibName );
271
272 LIB_ID unitId;
273
274 wxCHECK2( unitId.Parse( aLibName ) < 0, /* do nothing */ );
275
276 unitName = unitId.GetLibItemName();
277 }
278
279 if( aSymbol->IsRoot() )
280 {
281 aFormatter.Print( "(symbol %s", name.c_str() );
282
283 if( aSymbol->IsGlobalPower() )
284 aFormatter.Print( "(power global)" );
285 else if( aSymbol->IsLocalPower() )
286 aFormatter.Print( "(power local)" );
287
288 // TODO: add uuid token here.
289
290 // TODO: add anchor position token here.
291
292 if( aSymbol->IsMultiBodyStyle() )
293 {
294 aFormatter.Print( "(body_styles " );
295
296 if( aSymbol->HasDeMorganBodyStyles() )
297 {
298 aFormatter.Print( "demorgan" );
299 }
300 else
301 {
302 for( const wxString& bodyStyle : aSymbol->GetBodyStyleNames() )
303 aFormatter.Print( "%s ", aFormatter.Quotew( bodyStyle ).c_str() );
304 }
305
306 aFormatter.Print( ")" );
307 }
308
309 if( !aSymbol->GetShowPinNumbers() )
310 aFormatter.Print( "(pin_numbers (hide yes))" );
311
312 if( aSymbol->GetPinNameOffset() != schIUScale.MilsToIU( DEFAULT_PIN_NAME_OFFSET )
313 || !aSymbol->GetShowPinNames() )
314 {
315 aFormatter.Print( "(pin_names" );
316
317 if( aSymbol->GetPinNameOffset() != schIUScale.MilsToIU( DEFAULT_PIN_NAME_OFFSET ) )
318 {
319 aFormatter.Print( "(offset %s)",
321 aSymbol->GetPinNameOffset() ).c_str() );
322 }
323
324 if( !aSymbol->GetShowPinNames() )
325 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
326
327 aFormatter.Print( ")" );
328 }
329
330 KICAD_FORMAT::FormatBool( &aFormatter, "exclude_from_sim", aSymbol->GetExcludedFromSim() );
331 KICAD_FORMAT::FormatBool( &aFormatter, "in_bom", !aSymbol->GetExcludedFromBOM() );
332 KICAD_FORMAT::FormatBool( &aFormatter, "on_board", !aSymbol->GetExcludedFromBoard() );
333 KICAD_FORMAT::FormatBool( &aFormatter, "in_pos_files", !aSymbol->GetExcludedFromPosFiles() );
334
335 KICAD_FORMAT::FormatBool( &aFormatter, "duplicate_pin_numbers_are_jumpers",
337
338 const std::vector<std::set<wxString>>& jumperGroups = aSymbol->JumperPinGroups();
339
340 if( !jumperGroups.empty() )
341 {
342 aFormatter.Print( "(jumper_pin_groups" );
343
344 for( const std::set<wxString>& group : jumperGroups )
345 {
346 aFormatter.Print( "(" );
347
348 for( const wxString& padName : group )
349 aFormatter.Print( "%s ", aFormatter.Quotew( padName ).c_str() );
350
351 aFormatter.Print( ")" );
352 }
353
354 aFormatter.Print( ")" );
355 }
356
357 // TODO: add atomic token here.
358
359 // TODO: add required token here."
360
361 aSymbol->GetFields( orderedFields );
362
363 for( SCH_FIELD* field : orderedFields )
364 saveField( field, aFormatter );
365
366 // @todo At some point in the future the lock status (all units interchangeable) should
367 // be set deterministically. For now a custom lock property is used to preserve the
368 // locked flag state.
369 if( aSymbol->UnitsLocked() )
370 {
371 SCH_FIELD locked( nullptr, FIELD_T::USER, "ki_locked" );
372 saveField( &locked, aFormatter );
373 }
374
375 saveDcmInfoAsFields( aSymbol, aFormatter );
376
377 // Save the draw items grouped by units.
378 std::vector<LIB_SYMBOL_UNIT> units = aSymbol->GetUnitDrawItems();
379 std::sort( units.begin(), units.end(),
380 []( const LIB_SYMBOL_UNIT& a, const LIB_SYMBOL_UNIT& b )
381 {
382 if( a.m_unit == b.m_unit )
383 return a.m_bodyStyle < b.m_bodyStyle;
384
385 return a.m_unit < b.m_unit;
386 } );
387
388 for( const LIB_SYMBOL_UNIT& unit : units )
389 {
390 // Add quotes and escape chars like ") to the UTF8 unitName string
391 name = aFormatter.Quotes( unitName );
392 name.pop_back(); // Remove last char: the quote ending the string.
393
394 aFormatter.Print( "(symbol %s_%d_%d\"",
395 name.c_str(),
396 unit.m_unit,
397 unit.m_bodyStyle );
398
399 // if the unit has a display name, write that
400 if( aSymbol->GetUnitDisplayNames().contains( unit.m_unit ) )
401 {
402 name = aSymbol->GetUnitDisplayNames().at( unit.m_unit );
403 aFormatter.Print( "(unit_name %s)", aFormatter.Quotes( name ).c_str() );
404 }
405
406 // Enforce item ordering
407 auto cmp =
408 []( const SCH_ITEM* a, const SCH_ITEM* b )
409 {
410 return *a < *b;
411 };
412
413 std::multiset<SCH_ITEM*, decltype( cmp )> save_map( cmp );
414
415 for( SCH_ITEM* item : unit.m_items )
416 save_map.insert( item );
417
418 for( SCH_ITEM* item : save_map )
419 saveSymbolDrawItem( item, aFormatter );
420
421 aFormatter.Print( ")" );
422 }
423
424 KICAD_FORMAT::FormatBool( &aFormatter, "embedded_fonts", aSymbol->GetAreFontsEmbedded() );
425
426 if( !aSymbol->EmbeddedFileMap().empty() )
427 aSymbol->WriteEmbeddedFiles( aFormatter, aIncludeData );
428 }
429 else
430 {
431 std::shared_ptr<LIB_SYMBOL> parent = aSymbol->GetParent().lock();
432
433 wxASSERT( parent );
434
435 aFormatter.Print( "(symbol %s (extends %s)",
436 name.c_str(),
437 aFormatter.Quotew( parent->GetName() ).c_str() );
438
439 aSymbol->GetFields( orderedFields );
440
441 for( SCH_FIELD* field : orderedFields )
442 saveField( field, aFormatter );
443
444 saveDcmInfoAsFields( aSymbol, aFormatter );
445
446 KICAD_FORMAT::FormatBool( &aFormatter, "embedded_fonts", aSymbol->GetAreFontsEmbedded() );
447
448 if( !aSymbol->EmbeddedFileMap().empty() )
449 aSymbol->WriteEmbeddedFiles( aFormatter, aIncludeData );
450 }
451
452 aFormatter.Print( ")" );
453}
454
455
457 OUTPUTFORMATTER& aFormatter )
458{
459 wxCHECK_RET( aSymbol, "Invalid LIB_SYMBOL pointer." );
460
461 if( !aSymbol->GetKeyWords().IsEmpty() )
462 {
463 SCH_FIELD keywords( nullptr, FIELD_T::USER, wxString( "ki_keywords" ) );
464 keywords.SetVisible( false );
465 keywords.SetText( aSymbol->GetKeyWords() );
466 saveField( &keywords, aFormatter );
467 }
468
469 wxArrayString fpFilters = aSymbol->GetFPFilters();
470
471 if( !fpFilters.IsEmpty() )
472 {
473 wxString tmp;
474
475 for( const wxString& filter : fpFilters )
476 {
477 // Spaces are not handled in fp filter names so escape spaces if any
478 wxString curr_filter = EscapeString( filter, ESCAPE_CONTEXT::CTX_NO_SPACE );
479
480 if( tmp.IsEmpty() )
481 tmp = curr_filter;
482 else
483 tmp += " " + curr_filter;
484 }
485
486 SCH_FIELD description( nullptr, FIELD_T::USER, wxString( "ki_fp_filters" ) );
487 description.SetVisible( false );
488 description.SetText( tmp );
489 saveField( &description, aFormatter );
490 }
491}
492
493
495{
496 wxCHECK_RET( aItem, "Invalid SCH_ITEM pointer." );
497
498 switch( aItem->Type() )
499 {
500 case SCH_SHAPE_T:
501 {
502 SCH_SHAPE* shape = static_cast<SCH_SHAPE*>( aItem );
503 STROKE_PARAMS stroke = shape->GetStroke();
504 FILL_T fillMode = shape->GetFillMode();
505 COLOR4D fillColor = shape->GetFillColor();
506 bool isPrivate = shape->IsPrivate();
507
508 switch( shape->GetShape() )
509 {
510 case SHAPE_T::ARC:
511 formatArc( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
512 break;
513
514 case SHAPE_T::CIRCLE:
515 formatCircle( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
516 break;
517
519 formatRect( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
520 break;
521
522 case SHAPE_T::BEZIER:
523 formatBezier(&aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
524 break;
525
526 case SHAPE_T::POLY:
527 formatPoly( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
528 break;
529
530 default:
532 }
533
534 break;
535 }
536
537 case SCH_PIN_T:
538 savePin( static_cast<SCH_PIN*>( aItem ), aFormatter );
539 break;
540
541 case SCH_TEXT_T:
542 saveText( static_cast<SCH_TEXT*>( aItem ), aFormatter );
543 break;
544
545 case SCH_TEXTBOX_T:
546 saveTextBox( static_cast<SCH_TEXTBOX*>( aItem ), aFormatter );
547 break;
548
549 default:
550 UNIMPLEMENTED_FOR( aItem->GetClass() );
551 }
552}
553
554
556{
557 wxCHECK_RET( aField && aField->Type() == SCH_FIELD_T, "Invalid SCH_FIELD object." );
558
559 wxString fieldName = aField->GetName();
560
561 if( aField->IsMandatory() )
562 fieldName = GetCanonicalFieldName( aField->GetId() );
563
564 aFormatter.Print( "(property %s %s %s (at %s %s %s)",
565 aField->IsPrivate() ? "private" : "",
566 aFormatter.Quotew( fieldName ).c_str(),
567 aFormatter.Quotew( aField->GetText() ).c_str(),
569 aField->GetPosition().x ).c_str(),
571 -aField->GetPosition().y ).c_str(),
572 fmt::format( "{:g}", aField->GetTextAngle().AsDegrees() ).c_str() );
573
574 KICAD_FORMAT::FormatBool( &aFormatter, "show_name", aField->IsNameShown() );
575
576 KICAD_FORMAT::FormatBool( &aFormatter, "do_not_autoplace", !aField->CanAutoplace() );
577
578 if( !aField->IsVisible() )
579 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
580
581 aField->Format( &aFormatter, 0 );
582 aFormatter.Print( ")" );
583}
584
585
587{
588 wxCHECK_RET( aPin && aPin->Type() == SCH_PIN_T, "Invalid SCH_PIN object." );
589
590 aPin->ClearFlags( IS_CHANGED );
591
592 aFormatter.Print( "(pin %s %s (at %s %s %s) (length %s)",
594 getPinShapeToken( aPin->GetShape() ),
596 aPin->GetPosition().x ).c_str(),
598 -aPin->GetPosition().y ).c_str(),
601 aPin->GetLength() ).c_str() );
602
603 if( !aPin->IsVisible() )
604 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
605
606 // This follows the EDA_TEXT effects formatting for future expansion.
607 aFormatter.Print( "(name %s (effects (font (size %s %s))))",
608 aFormatter.Quotew( aPin->GetName() ).c_str(),
610 aPin->GetNameTextSize() ).c_str(),
612 aPin->GetNameTextSize() ).c_str() );
613
614 aFormatter.Print( "(number %s (effects (font (size %s %s))))",
615 aFormatter.Quotew( aPin->GetNumber() ).c_str(),
617 aPin->GetNumberTextSize() ).c_str(),
619 aPin->GetNumberTextSize() ).c_str() );
620
621
622 for( const std::pair<const wxString, SCH_PIN::ALT>& alt : aPin->GetAlternates() )
623 {
624 // There was a bug somewhere in the alternate pin code that allowed pin alternates with no
625 // name to be saved in library symbols. This strips any invalid alternates just in case
626 // that code resurfaces.
627 if( alt.second.m_Name.IsEmpty() )
628 continue;
629
630 aFormatter.Print( "(alternate %s %s %s)",
631 aFormatter.Quotew( alt.second.m_Name ).c_str(),
632 getPinElectricalTypeToken( alt.second.m_Type ),
633 getPinShapeToken( alt.second.m_Shape ) );
634 }
635
636 aFormatter.Print( ")" );
637}
638
639
641{
642 wxCHECK_RET( aText && aText->Type() == SCH_TEXT_T, "Invalid SCH_TEXT object." );
643
644 aFormatter.Print( "(text %s %s (at %s %s %d)",
645 aText->IsPrivate() ? "private" : "",
646 aFormatter.Quotew( aText->GetText() ).c_str(),
648 aText->GetPosition().x ).c_str(),
650 -aText->GetPosition().y ).c_str(),
651 aText->GetTextAngle().AsTenthsOfADegree() );
652
653 aText->EDA_TEXT::Format( &aFormatter, 0 );
654 aFormatter.Print( ")" );
655}
656
657
659{
660 wxCHECK_RET( aTextBox && aTextBox->Type() == SCH_TEXTBOX_T, "Invalid SCH_TEXTBOX object." );
661
662 aFormatter.Print( "(text_box %s %s",
663 aTextBox->IsPrivate() ? "private" : "",
664 aFormatter.Quotew( aTextBox->GetText() ).c_str() );
665
666 VECTOR2I pos = aTextBox->GetStart();
667 VECTOR2I size = aTextBox->GetEnd() - pos;
668
669 aFormatter.Print( "(at %s %s %s) (size %s %s) (margins %s %s %s %s)",
672 EDA_UNIT_UTILS::FormatAngle( aTextBox->GetTextAngle() ).c_str(),
679
680 aTextBox->GetStroke().Format( &aFormatter, schIUScale );
681 formatFill( &aFormatter, aTextBox->GetFillMode(), aTextBox->GetFillColor() );
682 aTextBox->EDA_TEXT::Format( &aFormatter, 0 );
683 aFormatter.Print( ")" );
684}
685
686
687void SCH_IO_KICAD_SEXPR_LIB_CACHE::DeleteSymbol( const wxString& aSymbolName )
688{
689 LIB_SYMBOL_MAP::iterator it = m_symbols.find( aSymbolName );
690
691 if( it == m_symbols.end() )
692 THROW_IO_ERROR( wxString::Format( _( "library %s does not contain a symbol named %s" ),
693 m_libFileName.GetFullName(), aSymbolName ) );
694
695 LIB_SYMBOL* symbol = it->second;
696
697 if( symbol->IsRoot() )
698 {
699 LIB_SYMBOL* rootSymbol = symbol;
700
701 // Remove the root symbol and all its children.
702 m_symbols.erase( it );
703
704 LIB_SYMBOL_MAP::iterator it1 = m_symbols.begin();
705
706 while( it1 != m_symbols.end() )
707 {
708 if( it1->second->IsDerived()
709 && it1->second->GetParent().lock() == rootSymbol->SharedPtr() )
710 {
711 delete it1->second;
712 it1 = m_symbols.erase( it1 );
713 }
714 else
715 {
716 it1++;
717 }
718 }
719
720 delete rootSymbol;
721 }
722 else
723 {
724 // Just remove the alias.
725 m_symbols.erase( it );
726 delete symbol;
727 }
728
730 m_isModified = true;
731}
732
733
735{
736 for( auto& [name, symbol] : m_symbols )
737 {
738 if( symbol->GetParentName().IsEmpty() )
739 continue;
740
741 auto it = m_symbols.find( symbol->GetParentName() );
742
743 if( it == m_symbols.end() )
744 {
745 wxString error;
746
747 error.Printf( _( "No parent for extended symbol %s found in library '%s'" ),
748 name.c_str(), m_libFileName.GetFullPath() );
749 THROW_IO_ERROR( error );
750 }
751
752 symbol->SetParent( it->second );
753 }
754}
755
756
758{
759 aFormatter.Print( "(kicad_symbol_lib (version %d) (generator \"kicad_symbol_editor\") "
760 "(generator_version \"%s\")",
762 GetMajorMinorVersion().c_str().AsChar() );
763}
764
765
767{
768 if( !m_libFileName.IsDir() )
769 return m_libFileName.FileExists();
770 else
771 return m_libFileName.DirExists();
772}
const char * name
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:114
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
int AsTenthsOfADegree() const
Definition eda_angle.h:118
double AsDegrees() const
Definition eda_angle.h:116
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:150
FILL_T GetFillMode() const
Definition eda_shape.h:142
SHAPE_T GetShape() const
Definition eda_shape.h:168
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:215
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:173
COLOR4D GetFillColor() const
Definition eda_shape.h:152
wxString SHAPE_T_asString() const
const EDA_ANGLE & GetTextAngle() const
Definition eda_text.h:147
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:98
virtual bool IsVisible() const
Definition eda_text.h:187
virtual void Format(OUTPUTFORMATTER *aFormatter, int aControlBits) const
Output the object to aFormatter in s-expression form.
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:395
void WriteEmbeddedFiles(OUTPUTFORMATTER &aOut, bool aWriteData) const
Output formatter for the embedded files.
void ClearEmbeddedFonts()
Remove all embedded fonts from the collection.
const std::map< wxString, EMBEDDED_FILE * > & EmbeddedFileMap() const
bool GetAreFontsEmbedded() const
A LINE_READER that reads from an open file.
Definition richio.h:158
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:105
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:49
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:52
const UTF8 & GetLibItemName() const
Definition lib_id.h:102
Define a library symbol object.
Definition lib_symbol.h:83
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:153
wxString GetKeyWords() const override
Definition lib_symbol.h:183
std::weak_ptr< LIB_SYMBOL > & GetParent()
Definition lib_symbol.h:115
void GetFields(std::vector< SCH_FIELD * > &aList, bool aVisibleOnly=false) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
bool UnitsLocked() const
Check whether symbol units are interchangeable.
Definition lib_symbol.h:288
bool IsRoot() const override
For symbols derived from other symbols, IsRoot() indicates no derivation.
Definition lib_symbol.h:203
std::vector< struct LIB_SYMBOL_UNIT > GetUnitDrawItems()
Return a list of SCH_ITEM objects separated by unit and convert number.
std::map< int, wxString > & GetUnitDisplayNames()
Definition lib_symbol.h:737
bool IsMultiBodyStyle() const override
Definition lib_symbol.h:761
bool IsLocalPower() const override
wxArrayString GetFPFilters() const
Definition lib_symbol.h:215
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:93
const std::vector< wxString > & GetBodyStyleNames() const
Definition lib_symbol.h:774
bool HasDeMorganBodyStyles() const override
Definition lib_symbol.h:771
EMBEDDED_FILES * GetEmbeddedFiles() override
bool IsGlobalPower() const override
bool GetDuplicatePinNumbersAreJumpers() const
Definition lib_symbol.h:740
std::vector< std::set< wxString > > & JumperPinGroups()
Each jumper pin group is a set of pin numbers that should be treated as internally connected.
Definition lib_symbol.h:747
void EmbedFonts() override
An interface used to output 8 bit text in a convenient way.
Definition richio.h:295
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:507
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:422
virtual std::string Quotes(const std::string &aWrapee) const
Check aWrapee input string for a need to be quoted (e.g.
Definition richio.cpp:468
bool IsMandatory() const
VECTOR2I GetPosition() const override
bool IsNameShown() const
Definition sch_field.h:208
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:118
FIELD_T GetId() const
Definition sch_field.h:122
wxString GetName(bool aUseDefaultName=true) const
Return the field name (not translated).
bool CanAutoplace() const
Definition sch_field.h:219
void SetText(const wxString &aText) override
static void saveSymbolDrawItem(SCH_ITEM *aItem, OUTPUTFORMATTER &aFormatter)
SCH_IO_KICAD_SEXPR_LIB_CACHE(const wxString &aLibraryPath)
static void saveDcmInfoAsFields(LIB_SYMBOL *aSymbol, OUTPUTFORMATTER &aFormatter)
static void SaveSymbol(LIB_SYMBOL *aSymbol, OUTPUTFORMATTER &aFormatter, const wxString &aLibName=wxEmptyString, bool aIncludeData=true)
static void saveTextBox(SCH_TEXTBOX *aTextBox, OUTPUTFORMATTER &aFormatter)
static void saveField(SCH_FIELD *aField, OUTPUTFORMATTER &aFormatter)
void formatLibraryHeader(OUTPUTFORMATTER &aFormatter)
void DeleteSymbol(const wxString &aName) override
static void savePin(SCH_PIN *aPin, OUTPUTFORMATTER &aFormatter)
static void saveText(SCH_TEXT *aText, OUTPUTFORMATTER &aFormatter)
void Save(const std::optional< bool > &aOpt=std::nullopt) override
Save the entire library to file m_libFileName;.
void updateParentSymbolLinks()
Update the parent symbol links for derived symbols.
Object to parser s-expression symbol library and schematic file formats.
const std::vector< wxString > & GetParseWarnings() const
Return any non-fatal parse warnings that occurred during parsing.
void ParseLib(LIB_SYMBOL_MAP &aSymbolLibMap)
void SetParseError(bool aHasError=true)
Set the parse error state.
bool HasParseError() const
LIB_SYMBOL_MAP m_symbols
wxFileName GetRealFile() const
long long GetLibModificationTime()
SCH_IO_LIB_CACHE(const wxString &aLibraryPath)
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:167
bool IsPrivate() const
Definition sch_item.h:253
wxString GetClass() const override
Return the class name.
Definition sch_item.h:177
int GetNumberTextSize() const
Definition sch_pin.cpp:679
int GetLength() const
Definition sch_pin.cpp:299
const std::map< wxString, ALT > & GetAlternates() const
Definition sch_pin.h:160
bool IsVisible() const
Definition sch_pin.cpp:387
const wxString & GetName() const
Definition sch_pin.cpp:401
PIN_ORIENTATION GetOrientation() const
Definition sch_pin.cpp:264
VECTOR2I GetPosition() const override
Definition sch_pin.cpp:256
int GetNameTextSize() const
Definition sch_pin.cpp:655
const wxString & GetNumber() const
Definition sch_pin.h:124
GRAPHIC_PINSHAPE GetShape() const
Definition sch_pin.cpp:278
ELECTRICAL_PINTYPE GetType() const
Definition sch_pin.cpp:313
STROKE_PARAMS GetStroke() const override
Definition sch_shape.h:58
int GetMarginBottom() const
Definition sch_textbox.h:66
int GetMarginLeft() const
Definition sch_textbox.h:63
int GetMarginRight() const
Definition sch_textbox.h:65
int GetMarginTop() const
Definition sch_textbox.h:64
VECTOR2I GetPosition() const override
Definition sch_text.h:147
Simple container to manage line stroke parameters.
void Format(OUTPUTFORMATTER *out, const EDA_IU_SCALE &aIuScale) const
bool GetExcludedFromPosFiles(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:231
int GetPinNameOffset() const
Definition symbol.h:163
virtual bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:201
virtual bool GetShowPinNames() const
Definition symbol.h:169
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:216
virtual bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition symbol.h:186
virtual bool GetShowPinNumbers() const
Definition symbol.h:175
wxString wx_str() const
Definition utf8.cpp:45
The common library.
#define DEFAULT_PIN_NAME_OFFSET
The intersheets references prefix string.
#define _(s)
#define IS_CHANGED
Item was edited, and modified.
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:46
FILL_T
Definition eda_shape.h:56
static const std::string KiCadSymbolLibFileExtension
const wxChar *const traceSchLegacyPlugin
Flag to enable legacy schematic plugin debug output.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
This file contains miscellaneous commonly used macros and functions.
#define UNIMPLEMENTED_FOR(type)
Definition macros.h:96
KICOMMON_API std::string FormatAngle(const EDA_ANGLE &aAngle)
Convert aAngle from board units to a string appropriate for writing to file.
KICOMMON_API std::string FormatInternalUnits(const EDA_IU_SCALE &aIuScale, int aValue, EDA_DATA_TYPE aDataType=EDA_DATA_TYPE::DISTANCE)
Converts aValue from internal units to a string appropriate for writing to file.
void FormatBool(OUTPUTFORMATTER *aOut, const wxString &aKey, bool aValue)
Writes a boolean to the formatter, in the style (aKey [yes|no])
#define SEXPR_SYMBOL_LIB_FILE_VERSION
This file contains the file format version information for the s-expression schematic and symbol libr...
EDA_ANGLE getPinAngle(PIN_ORIENTATION aOrientation)
void formatArc(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aArc, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid)
void formatCircle(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aCircle, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid)
const char * getPinElectricalTypeToken(ELECTRICAL_PINTYPE aType)
void formatBezier(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aBezier, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid)
void formatRect(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aRect, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid)
void formatPoly(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aPolyLine, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid)
void formatFill(OUTPUTFORMATTER *aFormatter, FILL_T aFillMode, const COLOR4D &aFillColor)
Fill token formatting helper.
const char * getPinShapeToken(GRAPHIC_PINSHAPE aShape)
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_FILENAME
@ CTX_NO_SPACE
@ USER
The field ID hasn't been set yet; field is invalid.
wxString GetCanonicalFieldName(FIELD_T aFieldType)
wxLogTrace helper definitions.
@ SCH_FIELD_T
Definition typeinfo.h:154
@ SCH_SHAPE_T
Definition typeinfo.h:153
@ SCH_TEXT_T
Definition typeinfo.h:155
@ SCH_TEXTBOX_T
Definition typeinfo.h:156
@ SCH_PIN_T
Definition typeinfo.h:157
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695