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#include <set>
24
25#include <wx/log.h>
26#include <wx/dir.h>
27
28#include <base_units.h>
29#include <build_version.h>
30#include <common.h>
31#include <sch_shape.h>
32#include <lib_symbol.h>
33#include <sch_textbox.h>
34#include <macros.h>
35#include <richio.h>
39#include <string_utils.h>
40#include <trace_helpers.h>
42
43
44SCH_IO_KICAD_SEXPR_LIB_CACHE::SCH_IO_KICAD_SEXPR_LIB_CACHE( const wxString& aFullPathAndFileName ) :
45 SCH_IO_LIB_CACHE( aFullPathAndFileName )
46{
48}
49
50
54
55
57{
58 // Normalize the path: if it's a directory on the filesystem, ensure m_libFileName
59 // is marked as a directory so that IsDir() checks work correctly throughout the code.
60 // wxFileName::IsDir() only checks if the path string ends with a separator, not if
61 // the path is actually a directory on the filesystem.
62 if( !m_libFileName.IsDir() && wxFileName::DirExists( m_libFileName.GetFullPath() ) )
63 m_libFileName.AssignDir( m_libFileName.GetFullPath() );
64
65 if( !isLibraryPathValid() )
66 {
67 THROW_IO_ERROR( wxString::Format( _( "Library '%s' not found." ), m_libFileName.GetFullPath() ) );
68 }
69
70 wxCHECK_RET( m_libFileName.IsAbsolute(),
71 wxString::Format( "Cannot use relative file paths in sexpr plugin to "
72 "open library '%s'.", m_libFileName.GetFullPath() ) );
73
74 if( !m_libFileName.IsDir() )
75 {
76 wxLogTrace( traceSchLegacyPlugin, "Loading sexpr symbol library file '%s'",
77 m_libFileName.GetFullPath() );
78
79 FILE_LINE_READER reader( m_libFileName.GetFullPath() );
80
81 SCH_IO_KICAD_SEXPR_PARSER parser( &reader );
82
83 parser.ParseLib( m_symbols );
84
88
89 // Check if there were any parse warnings (symbols that failed to parse).
90 // If so, mark the library as having parse errors and throw to notify the user.
91 // The library has loaded all valid symbols, but saving would lose the bad ones.
92 const std::vector<wxString>& warnings = parser.GetParseWarnings();
93
94 if( !warnings.empty() )
95 {
96 SetParseError( true );
97
98 wxString errorMsg = wxString::Format(
99 _( "Library '%s' loaded with errors:\n\n" ), m_libFileName.GetFullPath() );
100
101 for( const wxString& warning : warnings )
102 errorMsg += warning + wxT( "\n\n" );
103
104 errorMsg += _( "The library cannot be saved until these errors are fixed manually." );
105
106 THROW_IO_ERROR( errorMsg );
107 }
108 }
109 else
110 {
111 wxString libFileName;
112
113 wxLogTrace( traceSchLegacyPlugin, "Loading sexpr symbol library folder '%s'", m_libFileName.GetPath() );
114
115 // Clear source file tracking for fresh load
116 m_symbolSourceFiles.clear();
117
118 wxFileName tmp( m_libFileName.GetPath(), wxS( "dummy" ), wxString( FILEEXT::KiCadSymbolLibFileExtension ) );
119 wxDir dir( m_libFileName.GetPath() );
120 wxString fileSpec = wxS( "*." ) + wxString( FILEEXT::KiCadSymbolLibFileExtension );
121
122 if( dir.GetFirst( &libFileName, fileSpec ) )
123 {
124 wxString errorCache;
125
126 do
127 {
128 tmp.SetFullName( libFileName );
129 wxString sourceFilePath = tmp.GetFullPath();
130
131 // Track symbol pointers before parsing so we can detect which were replaced.
132 // When the parser encounters a duplicate name, it overwrites the existing
133 // symbol, so we need to update source tracking for those symbols too.
134 std::map<wxString, LIB_SYMBOL*> existingPtrs;
135
136 for( const auto& [ name, symbol ] : m_symbols )
137 existingPtrs[ name ] = symbol;
138
139 try
140 {
141 FILE_LINE_READER reader( sourceFilePath );
142 SCH_IO_KICAD_SEXPR_PARSER parser( &reader );
143
144 parser.ParseLib( m_symbols );
146
147 // Update source tracking for all symbols that came from this file.
148 // This includes both new symbols and symbols that were overwritten
149 // (when a duplicate name existed in a previously loaded file).
150 for( const auto& [ name, symbol ] : m_symbols )
151 {
152 auto it = existingPtrs.find( name );
153
154 if( it == existingPtrs.end() )
155 {
156 // New symbol from this file
157 m_symbolSourceFiles[ name ] = sourceFilePath;
158 }
159 else if( it->second != symbol )
160 {
161 // Symbol pointer changed - this file overwrote the previous version.
162 // Update tracking so we save to this file (the one whose version
163 // is actually in memory).
164 m_symbolSourceFiles[ name ] = sourceFilePath;
165 }
166 }
167
168 // Collect any parse warnings from this file
169 for( const wxString& warning : parser.GetParseWarnings() )
170 {
171 SetParseError( true );
172
173 if( !errorCache.IsEmpty() )
174 errorCache += wxT( "\n\n" );
175
176 errorCache += warning;
177 }
178 }
179 catch( const IO_ERROR& ioe )
180 {
181 // Mark that we had a parse error - saving would lose symbols
182 SetParseError( true );
183
184 if( !errorCache.IsEmpty() )
185 errorCache += wxT( "\n\n" );
186
187 errorCache += wxString::Format( _( "Unable to read file '%s'" ) + '\n', sourceFilePath );
188 errorCache += ioe.What();
189 }
190 } while( dir.GetNext( &libFileName ) );
191
192 if( !errorCache.IsEmpty() )
193 {
194 errorCache += _( "\n\nThe library cannot be saved until these errors are fixed manually." );
195 THROW_IO_ERROR( errorCache );
196 }
197 }
198
201 }
202
203 // Remember the file modification time of library file when the cache snapshot was made,
204 // so that in a networked environment we will reload the cache as needed.
206}
207
208
209void SCH_IO_KICAD_SEXPR_LIB_CACHE::Save( const std::optional<bool>& aOpt )
210{
211 if( !m_isModified )
212 return;
213
214 // If the library had a parse error during loading, we cannot safely save it.
215 // Only symbols before the parse error were loaded, so saving would permanently
216 // lose all symbols after the error point. See issue #22241.
217 if( HasParseError() )
218 {
219 THROW_IO_ERROR( wxString::Format(
220 _( "Cannot save library '%s' because it had a parse error during loading.\n\n"
221 "Saving would permanently lose symbols that could not be loaded.\n"
222 "Please fix the library file manually before saving." ),
223 m_libFileName.GetFullPath() ) );
224 }
225
226 // Write through symlinks, don't replace them.
227 wxFileName fn = GetRealFile();
228
229 // Normalize the path: if it's a directory on the filesystem, ensure fn is marked as a
230 // directory so that IsDir() checks work correctly.
231 if( !fn.IsDir() && wxFileName::DirExists( fn.GetFullPath() ) )
232 fn.AssignDir( fn.GetFullPath() );
233
234 if( !fn.IsDir() )
235 {
236 auto formatter = std::make_unique<PRETTIFIED_FILE_OUTPUTFORMATTER>( fn.GetFullPath() );
237
238 formatLibraryHeader( *formatter.get() );
239
240 std::vector<LIB_SYMBOL*> orderedSymbols;
241
242 for( const auto& [ name, symbol ] : m_symbols )
243 {
244 if( symbol )
245 orderedSymbols.push_back( symbol );
246 }
247
248 // Library must be ordered by inheritance depth.
249 std::sort( orderedSymbols.begin(), orderedSymbols.end(),
250 []( const LIB_SYMBOL* aLhs, const LIB_SYMBOL* aRhs )
251 {
252 unsigned int lhDepth = aLhs->GetInheritanceDepth();
253 unsigned int rhDepth = aRhs->GetInheritanceDepth();
254
255 if( lhDepth == rhDepth )
256 return aLhs->GetName() < aRhs->GetName();
257
258 return lhDepth < rhDepth;
259 } );
260
261 for( LIB_SYMBOL* symbol : orderedSymbols )
262 SaveSymbol( symbol, *formatter.get() );
263
264 formatter->Print( ")" );
265 formatter.reset();
266 }
267 else
268 {
269 if( !fn.DirExists() )
270 {
271 if( !fn.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
272 THROW_IO_ERROR( wxString::Format( _( "Cannot create symbol library path '%s'." ), fn.GetPath() ) );
273 }
274
275 // Group symbols by their source file to preserve multi-symbol files
276 std::map<wxString, std::vector<LIB_SYMBOL*>> symbolsByFile;
277
278 for( const auto& [ name, symbol ] : m_symbols )
279 {
280 auto it = m_symbolSourceFiles.find( name );
281
282 if( it != m_symbolSourceFiles.end() )
283 {
284 // Symbol has a known source file - group it with others from that file
285 symbolsByFile[ it->second ].push_back( symbol );
286 }
287 else
288 {
289 // New symbol without source file - create individual file
290 wxFileName saveFn( fn );
291 saveFn.SetName( EscapeString( name, CTX_FILENAME ) );
293
294 symbolsByFile[ saveFn.GetFullPath() ].push_back( symbol );
295 }
296 }
297
298 // Sort each file's symbols by inheritance depth
299 auto sortByInheritance = []( LIB_SYMBOL* aLhs, LIB_SYMBOL* aRhs )
300 {
301 unsigned int lhDepth = aLhs->GetInheritanceDepth();
302 unsigned int rhDepth = aRhs->GetInheritanceDepth();
303
304 if( lhDepth == rhDepth )
305 return aLhs->GetName() < aRhs->GetName();
306
307 return lhDepth < rhDepth;
308 };
309
310 // Write each file
311 for( auto& [ filePath, symbols ] : symbolsByFile )
312 {
313 wxFileName oldFn = filePath;
314
315 if( oldFn.GetPath() != m_libFileName.GetPath() )
316 oldFn.SetPath( m_libFileName.GetPath() );
317
318 std::sort( symbols.begin(), symbols.end(), sortByInheritance );
319
320 auto formatter = std::make_unique<PRETTIFIED_FILE_OUTPUTFORMATTER>( oldFn.GetFullPath() );
321
322 formatLibraryHeader( *formatter.get() );
323
324 for( LIB_SYMBOL* symbol : symbols )
325 SaveSymbol( symbol, *formatter.get() );
326
327 formatter->Print( ")" );
328 formatter.reset();
329
330 // Update source file tracking for new symbols
331 for( LIB_SYMBOL* symbol : symbols )
332 m_symbolSourceFiles[ symbol->GetName() ] = filePath;
333 }
334 }
335
337 m_isModified = false;
338}
339
340
342 const wxString& aLibName, bool aIncludeData )
343{
344 wxCHECK_RET( aSymbol, "Invalid LIB_SYMBOL pointer." );
345
346 // If we've requested to embed the fonts in the symbol, do so.
347 // Otherwise, clear the embedded fonts from the symbol. Embedded
348 // fonts will be used if available
349 if( aSymbol->GetAreFontsEmbedded() )
350 aSymbol->EmbedFonts();
351 else
353
354 std::vector<SCH_FIELD*> orderedFields;
355 std::string name = aFormatter.Quotew( aSymbol->GetLibId().GetLibItemName().wx_str() );
356 std::string unitName = aSymbol->GetLibId().GetLibItemName();
357
358 if( !aLibName.IsEmpty() )
359 {
360 name = aFormatter.Quotew( aLibName );
361
362 LIB_ID unitId;
363
364 wxCHECK2( unitId.Parse( aLibName ) < 0, /* do nothing */ );
365
366 unitName = unitId.GetLibItemName();
367 }
368
369 if( aSymbol->IsRoot() )
370 {
371 aFormatter.Print( "(symbol %s", name.c_str() );
372
373 if( aSymbol->IsGlobalPower() )
374 aFormatter.Print( "(power global)" );
375 else if( aSymbol->IsLocalPower() )
376 aFormatter.Print( "(power local)" );
377
378 // TODO: add uuid token here.
379
380 // TODO: add anchor position token here.
381
382 if( aSymbol->IsMultiBodyStyle() )
383 {
384 aFormatter.Print( "(body_styles " );
385
386 if( aSymbol->HasDeMorganBodyStyles() )
387 {
388 aFormatter.Print( "demorgan" );
389 }
390 else
391 {
392 for( const wxString& bodyStyle : aSymbol->GetBodyStyleNames() )
393 aFormatter.Print( "%s ", aFormatter.Quotew( bodyStyle ).c_str() );
394 }
395
396 aFormatter.Print( ")" );
397 }
398
399 if( !aSymbol->GetShowPinNumbers() )
400 aFormatter.Print( "(pin_numbers (hide yes))" );
401
402 if( aSymbol->GetPinNameOffset() != schIUScale.MilsToIU( DEFAULT_PIN_NAME_OFFSET )
403 || !aSymbol->GetShowPinNames() )
404 {
405 aFormatter.Print( "(pin_names" );
406
407 if( aSymbol->GetPinNameOffset() != schIUScale.MilsToIU( DEFAULT_PIN_NAME_OFFSET ) )
408 {
409 aFormatter.Print( "(offset %s)",
411 aSymbol->GetPinNameOffset() ).c_str() );
412 }
413
414 if( !aSymbol->GetShowPinNames() )
415 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
416
417 aFormatter.Print( ")" );
418 }
419
420 KICAD_FORMAT::FormatBool( &aFormatter, "exclude_from_sim", aSymbol->GetExcludedFromSim() );
421 KICAD_FORMAT::FormatBool( &aFormatter, "in_bom", !aSymbol->GetExcludedFromBOM() );
422 KICAD_FORMAT::FormatBool( &aFormatter, "on_board", !aSymbol->GetExcludedFromBoard() );
423 KICAD_FORMAT::FormatBool( &aFormatter, "in_pos_files", !aSymbol->GetExcludedFromPosFiles() );
424
425 KICAD_FORMAT::FormatBool( &aFormatter, "duplicate_pin_numbers_are_jumpers",
427
428 const std::vector<std::set<wxString>>& jumperGroups = aSymbol->JumperPinGroups();
429
430 if( !jumperGroups.empty() )
431 {
432 aFormatter.Print( "(jumper_pin_groups" );
433
434 for( const std::set<wxString>& group : jumperGroups )
435 {
436 aFormatter.Print( "(" );
437
438 for( const wxString& padName : group )
439 aFormatter.Print( "%s ", aFormatter.Quotew( padName ).c_str() );
440
441 aFormatter.Print( ")" );
442 }
443
444 aFormatter.Print( ")" );
445 }
446
447 // TODO: add atomic token here.
448
449 // TODO: add required token here."
450
451 aSymbol->GetFields( orderedFields );
452
453 for( SCH_FIELD* field : orderedFields )
454 saveField( field, aFormatter );
455
456 // @todo At some point in the future the lock status (all units interchangeable) should
457 // be set deterministically. For now a custom lock property is used to preserve the
458 // locked flag state.
459 if( aSymbol->UnitsLocked() )
460 {
461 SCH_FIELD locked( nullptr, FIELD_T::USER, "ki_locked" );
462 saveField( &locked, aFormatter );
463 }
464
465 saveDcmInfoAsFields( aSymbol, aFormatter );
466
467 // Save the draw items grouped by units.
468 std::vector<LIB_SYMBOL_UNIT> units = aSymbol->GetUnitDrawItems();
469 std::sort( units.begin(), units.end(),
470 []( const LIB_SYMBOL_UNIT& a, const LIB_SYMBOL_UNIT& b )
471 {
472 if( a.m_unit == b.m_unit )
473 return a.m_bodyStyle < b.m_bodyStyle;
474
475 return a.m_unit < b.m_unit;
476 } );
477
478 for( const LIB_SYMBOL_UNIT& unit : units )
479 {
480 // Add quotes and escape chars like ") to the UTF8 unitName string
481 name = aFormatter.Quotes( unitName );
482 name.pop_back(); // Remove last char: the quote ending the string.
483
484 aFormatter.Print( "(symbol %s_%d_%d\"",
485 name.c_str(),
486 unit.m_unit,
487 unit.m_bodyStyle );
488
489 // if the unit has a display name, write that
490 if( aSymbol->GetUnitDisplayNames().contains( unit.m_unit ) )
491 {
492 name = aSymbol->GetUnitDisplayNames().at( unit.m_unit );
493 aFormatter.Print( "(unit_name %s)", aFormatter.Quotes( name ).c_str() );
494 }
495
496 // Enforce item ordering
497 auto cmp =
498 []( const SCH_ITEM* a, const SCH_ITEM* b )
499 {
500 return *a < *b;
501 };
502
503 std::multiset<SCH_ITEM*, decltype( cmp )> save_map( cmp );
504
505 for( SCH_ITEM* item : unit.m_items )
506 save_map.insert( item );
507
508 for( SCH_ITEM* item : save_map )
509 saveSymbolDrawItem( item, aFormatter );
510
511 aFormatter.Print( ")" );
512 }
513
514 KICAD_FORMAT::FormatBool( &aFormatter, "embedded_fonts", aSymbol->GetAreFontsEmbedded() );
515
516 if( !aSymbol->EmbeddedFileMap().empty() )
517 aSymbol->WriteEmbeddedFiles( aFormatter, aIncludeData );
518 }
519 else
520 {
521 std::shared_ptr<LIB_SYMBOL> parent = aSymbol->GetParent().lock();
522
523 wxASSERT( parent );
524
525 aFormatter.Print( "(symbol %s (extends %s)",
526 name.c_str(),
527 aFormatter.Quotew( parent->GetName() ).c_str() );
528
529 aSymbol->GetFields( orderedFields );
530
531 for( SCH_FIELD* field : orderedFields )
532 saveField( field, aFormatter );
533
534 saveDcmInfoAsFields( aSymbol, aFormatter );
535
536 KICAD_FORMAT::FormatBool( &aFormatter, "embedded_fonts", aSymbol->GetAreFontsEmbedded() );
537
538 if( !aSymbol->EmbeddedFileMap().empty() )
539 aSymbol->WriteEmbeddedFiles( aFormatter, aIncludeData );
540 }
541
542 aFormatter.Print( ")" );
543}
544
545
547 OUTPUTFORMATTER& aFormatter )
548{
549 wxCHECK_RET( aSymbol, "Invalid LIB_SYMBOL pointer." );
550
551 if( !aSymbol->GetKeyWords().IsEmpty() )
552 {
553 SCH_FIELD keywords( nullptr, FIELD_T::USER, wxString( "ki_keywords" ) );
554 keywords.SetVisible( false );
555 keywords.SetText( aSymbol->GetKeyWords() );
556 saveField( &keywords, aFormatter );
557 }
558
559 wxArrayString fpFilters = aSymbol->GetFPFilters();
560
561 if( !fpFilters.IsEmpty() )
562 {
563 wxString tmp;
564
565 for( const wxString& filter : fpFilters )
566 {
567 // Spaces are not handled in fp filter names so escape spaces if any
568 wxString curr_filter = EscapeString( filter, ESCAPE_CONTEXT::CTX_NO_SPACE );
569
570 if( tmp.IsEmpty() )
571 tmp = curr_filter;
572 else
573 tmp += " " + curr_filter;
574 }
575
576 SCH_FIELD description( nullptr, FIELD_T::USER, wxString( "ki_fp_filters" ) );
577 description.SetVisible( false );
578 description.SetText( tmp );
579 saveField( &description, aFormatter );
580 }
581}
582
583
585{
586 wxCHECK_RET( aItem, "Invalid SCH_ITEM pointer." );
587
588 switch( aItem->Type() )
589 {
590 case SCH_SHAPE_T:
591 {
592 SCH_SHAPE* shape = static_cast<SCH_SHAPE*>( aItem );
593 STROKE_PARAMS stroke = shape->GetStroke();
594 FILL_T fillMode = shape->GetFillMode();
595 COLOR4D fillColor = shape->GetFillColor();
596 bool isPrivate = shape->IsPrivate();
597
598 switch( shape->GetShape() )
599 {
600 case SHAPE_T::ARC:
601 formatArc( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
602 break;
603
604 case SHAPE_T::CIRCLE:
605 formatCircle( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
606 break;
607
609 formatRect( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
610 break;
611
612 case SHAPE_T::BEZIER:
613 formatBezier(&aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
614 break;
615
616 case SHAPE_T::POLY:
617 formatPoly( &aFormatter, shape, isPrivate, stroke, fillMode, fillColor, true );
618 break;
619
620 default:
622 }
623
624 break;
625 }
626
627 case SCH_PIN_T:
628 savePin( static_cast<SCH_PIN*>( aItem ), aFormatter );
629 break;
630
631 case SCH_TEXT_T:
632 saveText( static_cast<SCH_TEXT*>( aItem ), aFormatter );
633 break;
634
635 case SCH_TEXTBOX_T:
636 saveTextBox( static_cast<SCH_TEXTBOX*>( aItem ), aFormatter );
637 break;
638
639 default:
640 UNIMPLEMENTED_FOR( aItem->GetClass() );
641 }
642}
643
644
646{
647 wxCHECK_RET( aField && aField->Type() == SCH_FIELD_T, "Invalid SCH_FIELD object." );
648
649 wxString fieldName = aField->GetName();
650
651 if( aField->IsMandatory() )
652 fieldName = GetCanonicalFieldName( aField->GetId() );
653
654 aFormatter.Print( "(property %s %s %s (at %s %s %s)",
655 aField->IsPrivate() ? "private" : "",
656 aFormatter.Quotew( fieldName ).c_str(),
657 aFormatter.Quotew( aField->GetText() ).c_str(),
659 aField->GetPosition().x ).c_str(),
661 -aField->GetPosition().y ).c_str(),
662 fmt::format( "{:g}", aField->GetTextAngle().AsDegrees() ).c_str() );
663
664 KICAD_FORMAT::FormatBool( &aFormatter, "show_name", aField->IsNameShown() );
665
666 KICAD_FORMAT::FormatBool( &aFormatter, "do_not_autoplace", !aField->CanAutoplace() );
667
668 if( !aField->IsVisible() )
669 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
670
671 aField->Format( &aFormatter, 0 );
672 aFormatter.Print( ")" );
673}
674
675
677{
678 wxCHECK_RET( aPin && aPin->Type() == SCH_PIN_T, "Invalid SCH_PIN object." );
679
680 aPin->ClearFlags( IS_CHANGED );
681
682 aFormatter.Print( "(pin %s %s (at %s %s %s) (length %s)",
684 getPinShapeToken( aPin->GetShape() ),
686 aPin->GetPosition().x ).c_str(),
688 -aPin->GetPosition().y ).c_str(),
691 aPin->GetLength() ).c_str() );
692
693 if( !aPin->IsVisible() )
694 KICAD_FORMAT::FormatBool( &aFormatter, "hide", true );
695
696 // This follows the EDA_TEXT effects formatting for future expansion.
697 aFormatter.Print( "(name %s (effects (font (size %s %s))))",
698 aFormatter.Quotew( aPin->GetName() ).c_str(),
700 aPin->GetNameTextSize() ).c_str(),
702 aPin->GetNameTextSize() ).c_str() );
703
704 aFormatter.Print( "(number %s (effects (font (size %s %s))))",
705 aFormatter.Quotew( aPin->GetNumber() ).c_str(),
707 aPin->GetNumberTextSize() ).c_str(),
709 aPin->GetNumberTextSize() ).c_str() );
710
711
712 for( const std::pair<const wxString, SCH_PIN::ALT>& alt : aPin->GetAlternates() )
713 {
714 // There was a bug somewhere in the alternate pin code that allowed pin alternates with no
715 // name to be saved in library symbols. This strips any invalid alternates just in case
716 // that code resurfaces.
717 if( alt.second.m_Name.IsEmpty() )
718 continue;
719
720 aFormatter.Print( "(alternate %s %s %s)",
721 aFormatter.Quotew( alt.second.m_Name ).c_str(),
722 getPinElectricalTypeToken( alt.second.m_Type ),
723 getPinShapeToken( alt.second.m_Shape ) );
724 }
725
726 aFormatter.Print( ")" );
727}
728
729
731{
732 wxCHECK_RET( aText && aText->Type() == SCH_TEXT_T, "Invalid SCH_TEXT object." );
733
734 aFormatter.Print( "(text %s %s (at %s %s %d)",
735 aText->IsPrivate() ? "private" : "",
736 aFormatter.Quotew( aText->GetText() ).c_str(),
738 aText->GetPosition().x ).c_str(),
740 -aText->GetPosition().y ).c_str(),
741 aText->GetTextAngle().AsTenthsOfADegree() );
742
743 aText->EDA_TEXT::Format( &aFormatter, 0 );
744 aFormatter.Print( ")" );
745}
746
747
749{
750 wxCHECK_RET( aTextBox && aTextBox->Type() == SCH_TEXTBOX_T, "Invalid SCH_TEXTBOX object." );
751
752 aFormatter.Print( "(text_box %s %s",
753 aTextBox->IsPrivate() ? "private" : "",
754 aFormatter.Quotew( aTextBox->GetText() ).c_str() );
755
756 VECTOR2I pos = aTextBox->GetStart();
757 VECTOR2I size = aTextBox->GetEnd() - pos;
758
759 aFormatter.Print( "(at %s %s %s) (size %s %s) (margins %s %s %s %s)",
762 EDA_UNIT_UTILS::FormatAngle( aTextBox->GetTextAngle() ).c_str(),
769
770 aTextBox->GetStroke().Format( &aFormatter, schIUScale );
771 formatFill( &aFormatter, aTextBox->GetFillMode(), aTextBox->GetFillColor() );
772 aTextBox->EDA_TEXT::Format( &aFormatter, 0 );
773 aFormatter.Print( ")" );
774}
775
776
777void SCH_IO_KICAD_SEXPR_LIB_CACHE::DeleteSymbol( const wxString& aSymbolName )
778{
779 LIB_SYMBOL_MAP::iterator it = m_symbols.find( aSymbolName );
780
781 if( it == m_symbols.end() )
782 THROW_IO_ERROR( wxString::Format( _( "library %s does not contain a symbol named %s" ),
783 m_libFileName.GetFullName(), aSymbolName ) );
784
785 LIB_SYMBOL* symbol = it->second;
786
787 if( symbol->IsRoot() )
788 {
789 LIB_SYMBOL* rootSymbol = symbol;
790
791 // Remove the root symbol and all its children.
792 m_symbols.erase( it );
793
794 LIB_SYMBOL_MAP::iterator it1 = m_symbols.begin();
795
796 while( it1 != m_symbols.end() )
797 {
798 if( it1->second->IsDerived()
799 && it1->second->GetParent().lock() == rootSymbol->SharedPtr() )
800 {
801 delete it1->second;
802 it1 = m_symbols.erase( it1 );
803 }
804 else
805 {
806 it1++;
807 }
808 }
809
810 delete rootSymbol;
811 }
812 else
813 {
814 // Just remove the alias.
815 m_symbols.erase( it );
816 delete symbol;
817 }
818
820 m_isModified = true;
821}
822
823
825{
826 for( auto& [name, symbol] : m_symbols )
827 {
828 if( symbol->GetParentName().IsEmpty() )
829 continue;
830
831 auto it = m_symbols.find( symbol->GetParentName() );
832
833 if( it == m_symbols.end() )
834 {
835 wxString error;
836
837 error.Printf( _( "No parent for extended symbol %s found in library '%s'" ),
838 name.c_str(), m_libFileName.GetFullPath() );
839 THROW_IO_ERROR( error );
840 }
841
842 symbol->SetParent( it->second );
843 }
844}
845
846
848{
849 aFormatter.Print( "(kicad_symbol_lib (version %d) (generator \"kicad_symbol_editor\") "
850 "(generator_version \"%s\")",
852 GetMajorMinorVersion().c_str().AsChar() );
853}
854
855
857{
858 if( !m_libFileName.IsDir() )
859 return m_libFileName.FileExists();
860 else
861 return m_libFileName.DirExists();
862}
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:112
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:151
FILL_T GetFillMode() const
Definition eda_shape.h:154
SHAPE_T GetShape() const
Definition eda_shape.h:181
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:228
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:186
COLOR4D GetFillColor() const
Definition eda_shape.h:165
wxString SHAPE_T_asString() const
const EDA_ANGLE & GetTextAngle() const
Definition eda_text.h:158
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:109
virtual bool IsVisible() const
Definition eda_text.h:198
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:370
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:152
wxString GetKeyWords() const override
Definition lib_symbol.h:179
std::weak_ptr< LIB_SYMBOL > & GetParent()
Definition lib_symbol.h:114
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:287
bool IsRoot() const override
For symbols derived from other symbols, IsRoot() indicates no derivation.
Definition lib_symbol.h:199
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:750
bool IsMultiBodyStyle() const override
Definition lib_symbol.h:774
wxString GetName() const override
Definition lib_symbol.h:145
bool IsLocalPower() const override
wxArrayString GetFPFilters() const
Definition lib_symbol.h:211
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:92
const std::vector< wxString > & GetBodyStyleNames() const
Definition lib_symbol.h:787
bool HasDeMorganBodyStyles() const override
Definition lib_symbol.h:784
EMBEDDED_FILES * GetEmbeddedFiles() override
bool IsGlobalPower() const override
unsigned GetInheritanceDepth() const
Get the number of parents for this symbol.
bool GetDuplicatePinNumbersAreJumpers() const
Definition lib_symbol.h:753
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:760
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:213
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:123
FIELD_T GetId() const
Definition sch_field.h:127
wxString GetName(bool aUseDefaultName=true) const
Return the field name (not translated).
bool CanAutoplace() const
Definition sch_field.h:224
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()
std::map< wxString, wxString > m_symbolSourceFiles
For folder-based libraries, track which source file each symbol was loaded from.
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:168
bool IsPrivate() const
Definition sch_item.h:254
wxString GetClass() const override
Return the class name.
Definition sch_item.h:178
int GetNumberTextSize() const
Definition sch_pin.cpp:683
int GetLength() const
Definition sch_pin.cpp:297
const std::map< wxString, ALT > & GetAlternates() const
Definition sch_pin.h:160
bool IsVisible() const
Definition sch_pin.cpp:389
const wxString & GetName() const
Definition sch_pin.cpp:403
PIN_ORIENTATION GetOrientation() const
Definition sch_pin.cpp:262
VECTOR2I GetPosition() const override
Definition sch_pin.cpp:254
int GetNameTextSize() const
Definition sch_pin.cpp:657
const wxString & GetNumber() const
Definition sch_pin.h:124
GRAPHIC_PINSHAPE GetShape() const
Definition sch_pin.cpp:276
ELECTRICAL_PINTYPE GetType() const
Definition sch_pin.cpp:311
STROKE_PARAMS GetStroke() const override
Definition sch_shape.h:58
int GetMarginBottom() const
Definition sch_textbox.h:73
int GetMarginLeft() const
Definition sch_textbox.h:70
int GetMarginRight() const
Definition sch_textbox.h:72
int GetMarginTop() const
Definition sch_textbox.h:71
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:48
FILL_T
Definition eda_shape.h:58
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, bool aLocked)
void formatCircle(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aCircle, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid, bool aLocked)
void formatRect(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aRect, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid, bool aLocked)
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, bool aLocked)
void formatPoly(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aPolyLine, bool aIsPrivate, const STROKE_PARAMS &aStroke, FILL_T aFillMode, const COLOR4D &aFillColor, bool aInvertY, const KIID &aUuid, bool aLocked)
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:151
@ SCH_SHAPE_T
Definition typeinfo.h:150
@ SCH_TEXT_T
Definition typeinfo.h:152
@ SCH_TEXTBOX_T
Definition typeinfo.h:153
@ SCH_PIN_T
Definition typeinfo.h:154
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:687