KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_io_kicad_sexpr.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) 2020 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * @author Wayne Stambaugh <[email protected]>
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#include <algorithm>
24
25#include <fmt/format.h>
26#include <magic_enum.hpp>
27
28#include <wx/dir.h>
29#include <wx/log.h>
30#include <wx/mstream.h>
31
32#include <base_units.h>
33#include <bitmap_base.h>
34#include <common.h> // ExpandTextVars
35#include <core/leak_at_exit.h>
37#include <build_version.h>
38#include <sch_selection.h>
39#include <font/fontconfig.h>
42#include <progress_reporter.h>
43#include <schematic.h>
44#include <schematic_lexer.h>
45#include <sch_bitmap.h>
46#include <sch_bus_entry.h>
47#include <sch_edit_frame.h> // SYMBOL_ORIENTATION_T
48#include <sch_group.h>
53#include <sch_junction.h>
54#include <sch_line.h>
55#include <sch_no_connect.h>
56#include <sch_pin.h>
57#include <sch_rule_area.h>
58#include <sch_screen.h>
59#include <sch_shape.h>
60#include <sch_netchain.h>
61#include <sch_sheet.h>
62#include <sch_sheet_pin.h>
63#include <sch_symbol.h>
64#include <sch_table.h>
65#include <sch_tablecell.h>
66#include <sch_text.h>
67#include <sch_textbox.h>
68#include <string_utils.h>
69#include <trace_helpers.h>
70#include <reporter.h>
71#include <connection_graph.h>
72
73using namespace TSCHEMATIC_T;
74
75
76#define SCH_PARSE_ERROR( text, reader, pos ) \
77 THROW_PARSE_ERROR( text, reader.GetSource(), reader.Line(), \
78 reader.LineNumber(), pos - reader.Line() )
79
80
81SCH_IO_KICAD_SEXPR::SCH_IO_KICAD_SEXPR() : SCH_IO( wxS( "Eeschema s-expression" ) )
82{
83 init( nullptr );
84}
85
86
94
95
97 const std::map<std::string, UTF8>* aProperties )
98{
99 if( m_schematic != aSchematic )
100 m_loadedRootSheets.clear();
101
102 m_version = 0;
103 m_appending = false;
104 m_sheetLoad = aProperties && aProperties->count( "hierarchical_sheet_load" );
105 m_rootSheet = nullptr;
106 m_schematic = aSchematic;
107 m_cache = nullptr;
108 m_out = nullptr;
109}
110
111
112SCH_SHEET* SCH_IO_KICAD_SEXPR::LoadSchematicFile( const wxString& aFileName, SCHEMATIC* aSchematic,
113 SCH_SHEET* aAppendToMe,
114 const std::map<std::string, UTF8>* aProperties )
115{
116 wxASSERT( !aFileName || aSchematic != nullptr );
117
118 SCH_SHEET* sheet;
119
120 wxFileName fn = aFileName;
121
122 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
124
125 // Unfortunately child sheet file names the legacy schematic file format are not fully
126 // qualified and are always appended to the project path. The aFileName attribute must
127 // always be an absolute path so the project path can be used for load child sheet files.
128 wxASSERT( fn.IsAbsolute() );
129
130 if( aAppendToMe )
131 {
132 wxLogTrace( traceSchPlugin, "Append \"%s\" to sheet \"%s\".",
133 aFileName, aAppendToMe->GetFileName() );
134
135 wxFileName normedFn = aAppendToMe->GetFileName();
136
137 if( !normedFn.IsAbsolute() )
138 {
139 if( aFileName.Right( normedFn.GetFullPath().Length() ) == normedFn.GetFullPath() )
140 m_path = aFileName.Left( aFileName.Length() - normedFn.GetFullPath().Length() );
141 }
142
143 if( m_path.IsEmpty() )
144 m_path = aSchematic->Project().GetProjectPath();
145
146 wxLogTrace( traceSchPlugin, "Normalized append path \"%s\".", m_path );
147 }
148 else
149 {
150 m_path = aSchematic->Project().GetProjectPath();
151 }
152
153 m_currentPath.push( m_path );
154 init( aSchematic, aProperties );
155 m_appending = aAppendToMe != nullptr;
156
157 if( aAppendToMe == nullptr )
158 {
159 // Clean up any allocated memory if an exception occurs loading the schematic.
160 std::unique_ptr<SCH_SHEET> newSheet = std::make_unique<SCH_SHEET>( aSchematic );
161
162 wxFileName relPath( aFileName );
163
164 // Do not use wxPATH_UNIX as option in MakeRelativeTo(). It can create incorrect
165 // relative paths on Windows, because paths have a disk identifier (C:, D: ...)
166 relPath.MakeRelativeTo( aSchematic->Project().GetProjectPath() );
167
168 newSheet->SetFileName( relPath.GetFullPath() );
169 m_rootSheet = newSheet.get();
170 loadHierarchy( SCH_SHEET_PATH(), newSheet.get() );
171
172 // A sheet load must keep another project's instances intact, so only its copies are stripped
173 if( !m_sheetLoad )
174 SCH_SHEET_LIST( newSheet.get() ).StripRefSuffixes();
175
176 // If we got here, the schematic loaded successfully.
177 sheet = newSheet.release();
178 m_rootSheet = nullptr; // Quiet Coverity warning.
179 m_loadedRootSheets.push_back( sheet );
180 }
181 else
182 {
183 wxCHECK_MSG( aSchematic->IsValid(), nullptr, "Can't append to a schematic with no root!" );
184 m_rootSheet = &aSchematic->Root();
185 sheet = aAppendToMe;
186 loadHierarchy( SCH_SHEET_PATH(), sheet );
187 }
188
189 wxASSERT( m_currentPath.size() == 1 ); // only the project path should remain
190
191 m_currentPath.pop(); // Clear the path stack for next call to Load
192
193 return sheet;
194}
195
196
197// Everything below this comment is recursive. Modify with care.
198
199void SCH_IO_KICAD_SEXPR::loadHierarchy( const SCH_SHEET_PATH& aParentSheetPath, SCH_SHEET* aSheet )
200{
201 m_currentSheetPath.push_back( aSheet );
202
203 SCH_SCREEN* screen = nullptr;
204
205 if( !aSheet->GetScreen() )
206 {
207 // SCH_SCREEN objects store the full path and file name where the SCH_SHEET object only
208 // stores the file name and extension. Add the project path to the file name and
209 // extension to compare when calling SCH_SHEET::SearchHierarchy().
210 // Resolve text variables in the filename. The field keeps the raw text for portability.
211 wxFileName fileName = m_schematic ? ExpandTextVars( aSheet->GetFileName(), &m_schematic->Project(), INTERNAL )
212 : aSheet->GetFileName();
213
214 if( !fileName.IsAbsolute() )
215 fileName.MakeAbsolute( m_currentPath.top() );
216
217 // Save the current path so that it gets restored when descending and ascending the
218 // sheet hierarchy which allows for sheet schematic files to be nested in folders
219 // relative to the last path a schematic was loaded from.
220 wxLogTrace( traceSchPlugin, "Saving path '%s'", m_currentPath.top() );
221 m_currentPath.push( fileName.GetPath() );
222 wxLogTrace( traceSchPlugin, "Current path '%s'", m_currentPath.top() );
223 wxLogTrace( traceSchPlugin, "Loading '%s'", fileName.GetFullPath() );
224
225 SCH_SHEET_PATH ancestorSheetPath = aParentSheetPath;
226
227 while( !ancestorSheetPath.empty() )
228 {
229 if( ancestorSheetPath.LastScreen()->GetFileName() == fileName.GetFullPath() )
230 {
231 if( !m_error.IsEmpty() )
232 m_error += "\n";
233
234 m_error += wxString::Format( _( "Could not load sheet '%s' because it already "
235 "appears as a direct ancestor in the schematic "
236 "hierarchy." ),
237 fileName.GetFullPath() );
238
239 fileName = wxEmptyString;
240
241 break;
242 }
243
244 ancestorSheetPath.pop_back();
245 }
246
247 if( ancestorSheetPath.empty() )
248 {
249 // Existing schematics could be either in the root sheet path or the current sheet
250 // load path so we have to check both.
251 if( !m_rootSheet->SearchHierarchy( fileName.GetFullPath(), &screen ) )
252 m_currentSheetPath.at( 0 )->SearchHierarchy( fileName.GetFullPath(), &screen );
253
254 // When loading multiple top-level sheets that reference the same sub-sheet file,
255 // the screen may have already been loaded by a previous top-level sheet.
256 if( !screen )
257 {
258 for( SCH_SHEET* prevRoot : m_loadedRootSheets )
259 {
260 if( prevRoot->SearchHierarchy( fileName.GetFullPath(), &screen ) )
261 break;
262 }
263 }
264 }
265
266 if( screen )
267 {
268 aSheet->SetScreen( screen );
269 aSheet->GetScreen()->SetParent( m_schematic );
270 // Do not need to load the sub-sheets - this has already been done.
271 }
272 else
273 {
274 aSheet->SetScreen( new SCH_SCREEN( m_schematic ) );
275 aSheet->GetScreen()->SetFileName( fileName.GetFullPath() );
276
277 try
278 {
279 loadFile( fileName.GetFullPath(), aSheet );
280 }
281 catch( const IO_ERROR& ioe )
282 {
283 // If there is a problem loading the root sheet, there is no recovery.
284 if( aSheet == m_rootSheet )
285 throw;
286
287 // For all subsheets, queue up the error message for the caller.
288 if( !m_error.IsEmpty() )
289 m_error += "\n";
290
291 m_error += ioe.What();
292 }
293
294 if( fileName.FileExists() )
295 {
296 aSheet->GetScreen()->SetFileReadOnly( !fileName.IsFileWritable() );
297 aSheet->GetScreen()->SetFileExists( true );
298 }
299 else
300 {
301 aSheet->GetScreen()->SetFileReadOnly( !fileName.IsDirWritable() );
302 aSheet->GetScreen()->SetFileExists( false );
303 }
304
305 SCH_SHEET_PATH currentSheetPath = aParentSheetPath;
306 currentSheetPath.push_back( aSheet );
307
308 // This was moved out of the try{} block so that any sheet definitions that
309 // the plugin fully parsed before the exception was raised will be loaded.
310 for( SCH_ITEM* aItem : aSheet->GetScreen()->Items().OfType( SCH_SHEET_T ) )
311 {
312 wxCHECK2( aItem->Type() == SCH_SHEET_T, /* do nothing */ );
313 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( aItem );
314
315 // Recursion starts here.
316 loadHierarchy( currentSheetPath, sheet );
317 }
318 }
319
320 m_currentPath.pop();
321 wxLogTrace( traceSchPlugin, "Restoring path \"%s\"", m_currentPath.top() );
322 }
323
324 m_currentSheetPath.pop_back();
325}
326
327
328void SCH_IO_KICAD_SEXPR::loadFile( const wxString& aFileName, SCH_SHEET* aSheet )
329{
330 FILE_LINE_READER reader( aFileName );
331
332 size_t lineCount = 0;
333
335 {
336 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
337
338 if( !m_progressReporter->KeepRefreshing() )
340
341 while( reader.ReadLine() )
342 lineCount++;
343
344 reader.Rewind();
345 }
346
347 SCH_IO_KICAD_SEXPR_PARSER parser( &reader, m_progressReporter, lineCount, m_rootSheet,
349
350 parser.ParseSchematic( aSheet );
351
352 // Net chains live at the root-sheet level. Sub-sheet parses always produce empty maps,
353 // so applying them would wipe the chains restored from the root file.
354 if( m_schematic && m_schematic->ConnectionGraph() && aSheet == m_rootSheet )
355 {
356 m_schematic->ConnectionGraph()->SetNetChainNetClassOverrides( parser.GetNetChainNetClasses() );
357 m_schematic->ConnectionGraph()->SetNetChainColorOverrides( parser.GetNetChainColors() );
358
359 std::map<wxString, CONNECTION_GRAPH::CHAIN_TERMINAL_REFS> termRefs;
360
361 for( const auto& [name, terms] : parser.GetNetChainTerminalRefs() )
362 {
363 termRefs[name] = { { terms.first.refDes, terms.first.pinNum }, { terms.second.refDes, terms.second.pinNum } };
364 }
365
366 m_schematic->ConnectionGraph()->SetNetChainTerminalRefOverrides( termRefs );
367 m_schematic->ConnectionGraph()->SetNetChainMemberNetOverrides( parser.GetNetChainMemberNets() );
368 }
369}
370
371
372void SCH_IO_KICAD_SEXPR::LoadContent( LINE_READER& aReader, SCH_SHEET* aSheet, int aFileVersion )
373{
374 wxCHECK( aSheet, /* void */ );
375
376 SCH_IO_KICAD_SEXPR_PARSER parser( &aReader );
377
378 parser.ParseSchematic( aSheet, true, aFileVersion );
379
380 if( m_schematic && m_schematic->ConnectionGraph() && aSheet == m_rootSheet )
381 {
382 m_schematic->ConnectionGraph()->SetNetChainNetClassOverrides( parser.GetNetChainNetClasses() );
383 m_schematic->ConnectionGraph()->SetNetChainColorOverrides( parser.GetNetChainColors() );
384
385 std::map<wxString, CONNECTION_GRAPH::CHAIN_TERMINAL_REFS> termRefs;
386
387 for( const auto& [name, terms] : parser.GetNetChainTerminalRefs() )
388 {
389 termRefs[name] = { { terms.first.refDes, terms.first.pinNum }, { terms.second.refDes, terms.second.pinNum } };
390 }
391
392 m_schematic->ConnectionGraph()->SetNetChainTerminalRefOverrides( termRefs );
393 m_schematic->ConnectionGraph()->SetNetChainMemberNetOverrides( parser.GetNetChainMemberNets() );
394 }
395}
396
397
398void SCH_IO_KICAD_SEXPR::SaveSchematicFile( const wxString& aFileName, SCH_SHEET* aSheet, SCHEMATIC* aSchematic,
399 const std::map<std::string, UTF8>* aProperties )
400{
401 wxCHECK_RET( aSheet != nullptr, "NULL SCH_SHEET object." );
402 wxCHECK_RET( !aFileName.IsEmpty(), "No schematic file name defined." );
403 wxCHECK_RET( aSheet->GetScreen(), "Sheet has no screen." );
404
405 wxString sanityResult = aSheet->GetScreen()->GroupsSanityCheck();
406
407 if( sanityResult != wxEmptyString && m_queryUserCallback )
408 {
409 if( !m_queryUserCallback( _( "Internal Group Data Error" ), wxICON_ERROR,
410 wxString::Format( _( "Error validating group structure: %s\n\n"
411 "Please report this bug." ),
412 sanityResult ),
413 _( "Save Anyway" ) ) )
414 {
415 return;
416 }
417 }
418
419 wxFileName fn = aFileName;
420
421 // File names should be absolute. Don't assume everything relative to the project path
422 // works properly.
423 wxASSERT( fn.IsAbsolute() );
424
425 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( fn.GetFullPath() );
426 FormatSchematicToFormatter( &formatter, aSheet, aSchematic, aProperties );
427 formatter.Finish();
428
429 aSheet->GetScreen()->SetFileExists( true );
430}
431
432
434 SCHEMATIC* aSchematic,
435 const std::map<std::string, UTF8>* aProperties )
436{
437 wxCHECK_RET( aSheet != nullptr, "NULL SCH_SHEET object." );
438
439 init( aSchematic, aProperties );
440
441 m_out = aOut;
442
443 Format( aSheet );
444
445 m_out = nullptr;
446}
447
448
450{
451 wxCHECK_RET( aSheet != nullptr, "NULL SCH_SHEET* object." );
452 wxCHECK_RET( m_schematic != nullptr, "NULL SCHEMATIC* object." );
453
454 SCH_SHEET_LIST sheets = m_schematic->Hierarchy();
455 SCH_SCREEN* screen = aSheet->GetScreen();
456
457 wxCHECK( screen, /* void */ );
458
459 // If we've requested to embed the fonts in the schematic, do so.
460 // Otherwise, clear the embedded fonts from the schematic. Embedded
461 // fonts will be used if available
462 if( m_schematic->GetAreFontsEmbedded() )
463 m_schematic->EmbedFonts();
464 else
465 m_schematic->GetEmbeddedFiles()->ClearEmbeddedFonts();
466
467 m_out->Print( "(kicad_sch (version %d) (generator \"eeschema\") (generator_version %s)",
469
471
472 screen->GetPageSettings().Format( m_out );
473 screen->GetTitleBlock().Format( m_out );
474
475 // Variant alternates are not placed on the sheet, so include them here to keep the file self-contained
476 for( SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
477 screen->IncludeVariantSymbols( *static_cast<SCH_SYMBOL*>( item ) );
478
479 // Save cache library.
480 m_out->Print( "(lib_symbols" );
481
482 for( const auto& [ libItemName, libSymbol ] : screen->GetLibSymbols() )
483 SCH_IO_KICAD_SEXPR_LIB_CACHE::SaveSymbol( libSymbol, *m_out, libItemName );
484
485 m_out->Print( ")" );
486
487 // Enforce item ordering
488 auto cmp =
489 []( const SCH_ITEM* a, const SCH_ITEM* b )
490 {
491 if( a->Type() != b->Type() )
492 return a->Type() < b->Type();
493
494 return a->m_Uuid < b->m_Uuid;
495 };
496
497 std::multiset<SCH_ITEM*, decltype( cmp )> save_map( cmp );
498
499 for( SCH_ITEM* item : screen->Items() )
500 {
501 // Markers are not saved, so keep them from being considered below
502 if( item->Type() != SCH_MARKER_T )
503 save_map.insert( item );
504 }
505
506 for( SCH_ITEM* item : save_map )
507 {
508 switch( item->Type() )
509 {
510 case SCH_SYMBOL_T:
511 saveSymbol( static_cast<SCH_SYMBOL*>( item ), *m_schematic, sheets, false );
512 break;
513
514 case SCH_BITMAP_T:
515 saveBitmap( static_cast<SCH_BITMAP&>( *item ) );
516 break;
517
518 case SCH_SHEET_T:
519 saveSheet( static_cast<SCH_SHEET*>( item ), sheets );
520 break;
521
522 case SCH_JUNCTION_T:
523 saveJunction( static_cast<SCH_JUNCTION*>( item ) );
524 break;
525
526 case SCH_NO_CONNECT_T:
527 saveNoConnect( static_cast<SCH_NO_CONNECT*>( item ) );
528 break;
529
532 saveBusEntry( static_cast<SCH_BUS_ENTRY_BASE*>( item ) );
533 break;
534
535 case SCH_LINE_T:
536 saveLine( static_cast<SCH_LINE*>( item ) );
537 break;
538
539 case SCH_SHAPE_T:
540 saveShape( static_cast<SCH_SHAPE*>( item ) );
541 break;
542
543 case SCH_RULE_AREA_T:
544 saveRuleArea( static_cast<SCH_RULE_AREA*>( item ) );
545 break;
546
547 case SCH_TEXT_T:
548 case SCH_LABEL_T:
550 case SCH_HIER_LABEL_T:
552 saveText( static_cast<SCH_TEXT*>( item ) );
553 break;
554
555 case SCH_TEXTBOX_T:
556 saveTextBox( static_cast<SCH_TEXTBOX*>( item ) );
557 break;
558
559 case SCH_TABLE_T:
560 saveTable( static_cast<SCH_TABLE*>( item ) );
561 break;
562
563 case SCH_GROUP_T:
564 saveGroup( static_cast<SCH_GROUP*>( item ) );
565 break;
566
567 default:
568 wxASSERT( "Unexpected schematic object type in SCH_IO_KICAD_SEXPR::Format()" );
569 }
570 }
571
572 // Net chains are schematic-wide state, so they must be written
573 // by exactly one sheet file. Anchor the write to the schematic's first top-level sheet to
574 // match the embedded files convention below.
575 if( m_schematic->GetTopLevelSheet( 0 ) == aSheet )
576 {
577 m_schematic->NetChains().RefreshTerminalReferences();
578
579 for( const auto& sigPtr : m_schematic->NetChains().GetCommittedNetChains() )
580 {
581 if( !sigPtr )
582 continue;
583
584 const SCH_NETCHAIN& sig = *sigPtr;
585
586 if( sig.GetTerminalRefDes( 0 ).IsEmpty() || sig.GetTerminalRefDes( 1 ).IsEmpty() )
587 continue;
588
589 m_out->Print( "(net_chain %s", m_out->Quotew( sig.GetName() ).c_str() );
590
591 m_out->Print( " (from %s %s)", m_out->Quotew( sig.GetTerminalRefDes( 0 ) ).c_str(),
592 m_out->Quotew( sig.GetTerminalPinNum( 0 ) ).c_str() );
593 m_out->Print( " (to %s %s)", m_out->Quotew( sig.GetTerminalRefDes( 1 ) ).c_str(),
594 m_out->Quotew( sig.GetTerminalPinNum( 1 ) ).c_str() );
595
596 if( !sig.GetNetClass().IsEmpty() )
597 m_out->Print( " (net_class %s)", m_out->Quotew( sig.GetNetClass() ).c_str() );
598
600 {
601 const KIGFX::COLOR4D& c = sig.GetColor();
602 m_out->Print( " (color %d %d %d %s)",
603 KiROUND( c.r * 255.0 ),
604 KiROUND( c.g * 255.0 ),
605 KiROUND( c.b * 255.0 ),
606 FormatDouble2Str( c.a ).c_str() );
607 }
608
609 // Synthetic subgraph names are not stable across runs, so they are
610 // skipped when persisting the member-net list.
611 std::vector<wxString> persistableNets;
612
613 for( const wxString& n : sig.GetNets() )
614 {
616 persistableNets.push_back( n );
617 }
618
619 if( !persistableNets.empty() )
620 {
621 m_out->Print( " (nets" );
622
623 for( const wxString& n : persistableNets )
624 m_out->Print( " %s", m_out->Quotew( n ).c_str() );
625
626 m_out->Print( ")" );
627 }
628
629 m_out->Print( ")" );
630 }
631 }
632
633 if( aSheet->HasRootInstance() )
634 {
635 std::vector< SCH_SHEET_INSTANCE> instances;
636
637 instances.emplace_back( aSheet->GetRootInstance() );
638 saveInstances( instances );
639 }
640
641 // Embedded fonts and files belong to the schematic, not to any individual sheet, so they
642 // must round-trip independently of per-sheet root-instance bookkeeping (which can legitimately
643 // be missing for some top-level sheets in flat hierarchies). Anchor the write to the
644 // schematic's first top-level sheet so a single, predictable file owns the data.
645 if( m_schematic->GetTopLevelSheet( 0 ) == aSheet )
646 {
647 KICAD_FORMAT::FormatBool( m_out, "embedded_fonts", m_schematic->GetAreFontsEmbedded() );
648
649 if( !m_schematic->GetEmbeddedFiles()->IsEmpty() )
650 m_schematic->WriteEmbeddedFiles( *m_out, true );
651 }
652
653 m_out->Print( ")" );
654}
655
656
657void SCH_IO_KICAD_SEXPR::Format( SCH_SELECTION* aSelection, SCH_SHEET_PATH* aSelectionPath,
658 SCHEMATIC& aSchematic, OUTPUTFORMATTER* aFormatter,
659 bool aForClipboard )
660{
661 wxCHECK( aSelection && aSelectionPath && aFormatter, /* void */ );
662
663 SCH_SHEET_LIST sheets = aSchematic.Hierarchy();
664
665 m_schematic = &aSchematic;
666 m_out = aFormatter;
667
668 std::map<wxString, LIB_SYMBOL*> libSymbols;
669 SCH_SCREEN* screen = aSelectionPath->LastScreen();
670 std::set<SCH_TABLE*> promotedTables;
671
672 for( EDA_ITEM* item : *aSelection )
673 {
674 if( item->Type() != SCH_SYMBOL_T )
675 continue;
676
677 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
678
679 wxString libSymbolLookup = symbol->GetLibId().Format().wx_str();
680
681 if( !symbol->UseLibIdLookup() )
682 libSymbolLookup = symbol->GetSchSymbolLibraryName();
683
684 auto it = screen->GetLibSymbols().find( libSymbolLookup );
685
686 if( it != screen->GetLibSymbols().end() )
687 libSymbols[ libSymbolLookup ] = it->second;
688
689 screen->IncludeVariantSymbols( *symbol );
690
691 for( const LIB_ID& alternate : symbol->GetVariantSymbolOverrides() )
692 {
693 wxString key = alternate.Format().wx_str();
694
695 if( auto altIt = screen->GetLibSymbols().find( key ); altIt != screen->GetLibSymbols().end() )
696 libSymbols[key] = altIt->second;
697 }
698 }
699
700 if( !libSymbols.empty() )
701 {
702 m_out->Print( "(lib_symbols" );
703
704 for( const auto& [name, libSymbol] : libSymbols )
706
707 m_out->Print( ")" );
708 }
709
710 for( EDA_ITEM* edaItem : *aSelection )
711 {
712 if( !edaItem->IsSCH_ITEM() )
713 continue;
714
715 SCH_ITEM* item = static_cast<SCH_ITEM*>( edaItem );
716
717 switch( item->Type() )
718 {
719 case SCH_SYMBOL_T:
720 saveSymbol( static_cast<SCH_SYMBOL*>( item ), aSchematic, sheets, aForClipboard, aSelectionPath );
721 break;
722
723 case SCH_BITMAP_T:
724 saveBitmap( static_cast<SCH_BITMAP&>( *item ) );
725 break;
726
727 case SCH_SHEET_T:
728 saveSheet( static_cast<SCH_SHEET*>( item ), sheets );
729 break;
730
731 case SCH_JUNCTION_T:
732 saveJunction( static_cast<SCH_JUNCTION*>( item ) );
733 break;
734
735 case SCH_NO_CONNECT_T:
736 saveNoConnect( static_cast<SCH_NO_CONNECT*>( item ) );
737 break;
738
741 saveBusEntry( static_cast<SCH_BUS_ENTRY_BASE*>( item ) );
742 break;
743
744 case SCH_LINE_T:
745 saveLine( static_cast<SCH_LINE*>( item ) );
746 break;
747
748 case SCH_SHAPE_T:
749 saveShape( static_cast<SCH_SHAPE*>( item ) );
750 break;
751
752 case SCH_RULE_AREA_T:
753 saveRuleArea( static_cast<SCH_RULE_AREA*>( item ) );
754 break;
755
756 case SCH_TEXT_T:
757 case SCH_LABEL_T:
759 case SCH_HIER_LABEL_T:
761 saveText( static_cast<SCH_TEXT*>( item ) );
762 break;
763
764 case SCH_TEXTBOX_T:
765 saveTextBox( static_cast<SCH_TEXTBOX*>( item ) );
766 break;
767
768 case SCH_TABLECELL_T:
769 {
770 SCH_TABLE* table = static_cast<SCH_TABLE*>( item->GetParent() );
771
772 if( promotedTables.count( table ) )
773 break;
774
775 table->SetFlags( SKIP_STRUCT );
776 saveTable( table );
777 table->ClearFlags( SKIP_STRUCT );
778 promotedTables.insert( table );
779 break;
780 }
781
782 case SCH_TABLE_T:
783 item->ClearFlags( SKIP_STRUCT );
784 saveTable( static_cast<SCH_TABLE*>( item ) );
785 break;
786
787 case SCH_GROUP_T:
788 saveGroup( static_cast<SCH_GROUP*>( item ) );
789 break;
790
791 default:
792 wxASSERT( "Unexpected schematic object type in SCH_IO_KICAD_SEXPR::Format()" );
793 }
794 }
795}
796
797
799{
800 if( aOverride.IsDefault() )
801 return;
802
803 const char* mode = "library_default";
804
805 switch( aOverride.m_Mode )
806 {
807 case PIN_MAP_OVERRIDE_MODE::USE_LIBRARY_DEFAULT: mode = "library_default"; break;
808 case PIN_MAP_OVERRIDE_MODE::USE_NAMED_MAP: mode = "named_map"; break;
809 case PIN_MAP_OVERRIDE_MODE::FORCE_IDENTITY: mode = "identity"; break;
810 case PIN_MAP_OVERRIDE_MODE::DELEGATE_TO_UNIT_1: mode = "delegate"; break;
811 }
812
813 aOut->Print( "(pin_map_override (mode %s)", mode );
814
815 if( aOverride.m_Mode == PIN_MAP_OVERRIDE_MODE::USE_NAMED_MAP && !aOverride.m_ActiveMapName.IsEmpty() )
816 aOut->Print( "(map %s)", aOut->Quotew( aOverride.m_ActiveMapName ).c_str() );
817
818 for( const PIN_MAP_ENTRY& edit : aOverride.m_Edits )
819 {
820 aOut->Print( "(edit %s %s)", aOut->Quotew( edit.m_PinNumber ).c_str(),
821 aOut->Quotew( edit.m_PadNumber ).c_str() );
822 }
823
824 aOut->Print( ")" );
825}
826
827
828void SCH_IO_KICAD_SEXPR::saveSymbol( SCH_SYMBOL* aSymbol, const SCHEMATIC& aSchematic,
829 const SCH_SHEET_LIST& aSheetList, bool aForClipboard,
830 const SCH_SHEET_PATH* aRelativePath )
831{
832 wxCHECK_RET( aSymbol != nullptr && m_out != nullptr, "" );
833
834 std::string libName;
835
836 wxString symbol_name = aSymbol->GetLibId().Format();
837
838 if( symbol_name.size() )
839 {
840 libName = toUTFTildaText( symbol_name );
841 }
842 else
843 {
844 libName = "_NONAME_";
845 }
846
847 EDA_ANGLE angle;
848 int orientation = aSymbol->GetOrientation() & ~( SYM_MIRROR_X | SYM_MIRROR_Y );
849
851 angle = ANGLE_90;
852 else if( orientation == SYM_ORIENT_180 )
853 angle = ANGLE_180;
854 else if( orientation == SYM_ORIENT_270 )
855 angle = ANGLE_270;
856 else
857 angle = ANGLE_0;
858
859 m_out->Print( "(symbol" );
860
861 if( !aSymbol->UseLibIdLookup() )
862 {
863 m_out->Print( "(lib_name %s)",
864 m_out->Quotew( aSymbol->GetSchSymbolLibraryName() ).c_str() );
865 }
866
867 m_out->Print( "(lib_id %s) (at %s %s %s)",
868 m_out->Quotew( aSymbol->GetLibId().Format().wx_str() ).c_str(),
870 aSymbol->GetPosition().x ).c_str(),
872 aSymbol->GetPosition().y ).c_str(),
873 EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
874
875 bool mirrorX = aSymbol->GetOrientation() & SYM_MIRROR_X;
876 bool mirrorY = aSymbol->GetOrientation() & SYM_MIRROR_Y;
877
878 if( mirrorX || mirrorY )
879 {
880 m_out->Print( "(mirror %s %s)",
881 mirrorX ? "x" : "",
882 mirrorY ? "y" : "" );
883 }
884
885 // The symbol unit is always set to the ordianal instance regardless of the current sheet
886 // instance to prevent file churn.
887 SCH_SYMBOL_INSTANCE ordinalInstance;
888
889 ordinalInstance.m_Reference = aSymbol->GetPrefix();
890
891 const SCH_SCREEN* parentScreen = static_cast<const SCH_SCREEN*>( aSymbol->GetParent() );
892
893 wxASSERT( parentScreen );
894
895 if( parentScreen && m_schematic )
896 {
897 std::optional<SCH_SHEET_PATH> ordinalPath =
898 m_schematic->Hierarchy().GetOrdinalPath( parentScreen );
899
900 // Design blocks are saved from a temporary sheet & screen which will not be found in
901 // the schematic, and will therefore have no ordinal path.
902 // wxASSERT( ordinalPath );
903
904 if( ordinalPath )
905 aSymbol->GetInstance( ordinalInstance, ordinalPath->Path() );
906 else if( aSymbol->GetInstances().size() )
907 ordinalInstance = aSymbol->GetInstances()[0];
908 }
909
910 int unit = ordinalInstance.m_Unit;
911
912 if( aForClipboard && aRelativePath )
913 {
914 SCH_SYMBOL_INSTANCE unitInstance;
915
916 if( aSymbol->GetInstance( unitInstance, aRelativePath->Path() ) )
917 unit = unitInstance.m_Unit;
918 }
919
920 m_out->Print( "(unit %d)", unit );
921 m_out->Print( "(body_style %d)", aSymbol->GetBodyStyle() );
922
923 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aSymbol->GetExcludedFromSim() );
924 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aSymbol->GetExcludedFromBOM() );
925 KICAD_FORMAT::FormatBool( m_out, "on_board", !aSymbol->GetExcludedFromBoard() );
926 KICAD_FORMAT::FormatBool( m_out, "in_pos_files", !aSymbol->GetExcludedFromPosFiles() );
927 KICAD_FORMAT::FormatBool( m_out, "dnp", aSymbol->GetDNP() );
929 // Persist passthrough mode as enum string for tri-state support, but omit when DEFAULT
930 // to avoid file churn and keep files compact/back-compatible.
932 {
933 using magic_enum::enum_name;
934 std::string name = std::string( enum_name( aSymbol->GetPassthroughMode() ) );
935 // enum names are UPPER_CASE; write lowercase tokens
936 std::transform( name.begin(), name.end(), name.begin(), []( unsigned char c ){ return (char) std::tolower( c ); } );
937 m_out->Print( "(passthrough %s)", name.c_str() );
938 }
939
940 if( aSymbol->IsLocked() )
941 KICAD_FORMAT::FormatBool( m_out, "locked", true );
942
943 AUTOPLACE_ALGO fieldsAutoplaced = aSymbol->GetFieldsAutoplaced();
944
945 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
946 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
947
949
950 std::vector<SCH_FIELD*> orderedFields;
951 aSymbol->GetFields( orderedFields, false );
952
953 for( SCH_FIELD* field : orderedFields )
954 {
955 FIELD_T id = field->GetId();
956 wxString value = field->GetText();
957
958 if( !aForClipboard && aSymbol->GetInstances().size() )
959 {
960 // The instance fields are always set to the default instance regardless of the
961 // sheet instance to prevent file churn.
962 if( id == FIELD_T::REFERENCE )
963 field->SetText( ordinalInstance.m_Reference );
964 }
965 else if( aForClipboard && aSymbol->GetInstances().size() && aRelativePath
966 && ( id == FIELD_T::REFERENCE ) )
967 {
968 SCH_SYMBOL_INSTANCE instance;
969
970 if( aSymbol->GetInstance( instance, aRelativePath->Path() ) )
971 field->SetText( instance.m_Reference );
972 }
973
974 try
975 {
976 saveField( field );
977 }
978 catch( ... )
979 {
980 // Restore the changed field text on write error.
981 if( id == FIELD_T::REFERENCE )
982 field->SetText( value );
983
984 throw;
985 }
986
987 if( id == FIELD_T::REFERENCE )
988 field->SetText( value );
989 }
990
991 for( const std::unique_ptr<SCH_PIN>& pin : aSymbol->GetRawPins() )
992 {
993 m_out->Print( "(pin %s", m_out->Quotew( pin->GetNumber() ).c_str() );
996
997 // There was a bug introduced somewhere in the original alternated pin code that would
998 // set the alternate pin to the default pin name which caused a number of library symbol
999 // comparison issues. Clearing the alternate pin resolves this issue.
1000 if( pin->GetAlt().IsEmpty() || ( pin->GetAlt() == pin->GetBaseName() ) )
1001 {
1002 m_out->Print( ")" );
1003 }
1004 else
1005 {
1006 m_out->Print( "(alternate %s))", m_out->Quotew( pin->GetAlt() ).c_str() );
1007 }
1008 }
1009
1010 if( !aSymbol->GetInstances().empty() )
1011 {
1012 std::map<KIID, std::vector<SCH_SYMBOL_INSTANCE>> projectInstances;
1013
1014 m_out->Print( "(instances" );
1015
1016 wxString projectName;
1017
1018 for( const SCH_SYMBOL_INSTANCE& inst : aSymbol->GetInstances() )
1019 {
1020 // During a check-point save, the symbol might not yet have instance data. Just skip
1021 // it; don't assert.
1022 if( inst.m_Path.empty() )
1023 continue;
1024
1025 // If the instance data is part of this design but no longer has an associated sheet
1026 // path, don't save it. This prevents large amounts of orphaned instance data for the
1027 // current project from accumulating in the schematic files.
1028 KIID_PATH pathToCheck = aSchematic.NormalizeInstancePath( inst.m_Path );
1029
1030 // The autosave timer serializes a live schematic whose symbol instances a concurrent
1031 // edit can leave transiently pathless, so a size-checked source can still copy empty
1032 // here. Indexing an empty path dereferences null (Sentry KICAD-173B), so skip it.
1033 if( pathToCheck.empty() )
1034 continue;
1035
1036 bool belongsToThisProject = aSchematic.IsInstancePathInProject( pathToCheck );
1037
1038 bool isOrphaned = belongsToThisProject && !aSheetList.GetSheetPathByKIIDPath( pathToCheck );
1039
1040 // Keep all instance data when copying to the clipboard. They may be needed on paste.
1041 if( !aForClipboard && isOrphaned )
1042 continue;
1043
1044 // Group by project - use the first real sheet KIID (after stripping virtual root)
1045 KIID projectKey = pathToCheck[0];
1046 auto it = projectInstances.find( projectKey );
1047
1048 if( it == projectInstances.end() )
1049 projectInstances[ projectKey ] = { inst };
1050 else
1051 it->second.emplace_back( inst );
1052 }
1053
1054 for( auto& [uuid, instances] : projectInstances )
1055 {
1056 wxCHECK2( instances.size(), continue );
1057
1058 // Sort project instances by KIID_PATH.
1059 std::sort( instances.begin(), instances.end(),
1060 []( SCH_SYMBOL_INSTANCE& aLhs, SCH_SYMBOL_INSTANCE& aRhs )
1061 {
1062 return aLhs.m_Path < aRhs.m_Path;
1063 } );
1064
1065 if( aSchematic.IsTopLevelSheetUuid( uuid ) )
1066 projectName = m_schematic->Project().GetProjectName();
1067 else
1068 projectName = instances[0].m_ProjectName;
1069
1070 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
1071
1072 for( const SCH_SYMBOL_INSTANCE& instance : instances )
1073 {
1074 wxString path;
1075 KIID_PATH tmp = instance.m_Path;
1076
1077 if( aForClipboard && aRelativePath )
1078 tmp.MakeRelativeTo( aRelativePath->Path() );
1079
1080 path = tmp.AsString();
1081
1082 wxString reference = instance.m_Reference;
1083
1084 // Older readers show the file's reference as is, so it carries the suffix
1085 if( m_schematic && !aForClipboard && !reference.EndsWith( wxS( "?" ) ) )
1086 reference += m_schematic->GetRefSuffix( instance.m_Path );
1087
1088 m_out->Print( "(path %s (reference %s) (unit %d)",
1089 m_out->Quotew( path ).c_str(),
1090 m_out->Quotew( reference ).c_str(),
1091 instance.m_Unit );
1092
1093 if( !instance.m_Variants.empty() )
1094 {
1095 for( const auto&[name, variant] : instance.m_Variants )
1096 {
1097 // A variant without differentials resolves identically to no variant,
1098 // writing it only keeps deleted variants alive across sessions.
1099 if( !variant.HasDifferentials( *aSymbol ) )
1100 continue;
1101
1102 m_out->Print( "(variant (name %s)", m_out->Quotew( name ).c_str() );
1103
1104 if( variant.m_DNP != aSymbol->GetDNP() )
1105 KICAD_FORMAT::FormatBool( m_out, "dnp", variant.m_DNP );
1106
1107 if( variant.m_ExcludedFromSim != aSymbol->GetExcludedFromSim() )
1108 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", variant.m_ExcludedFromSim );
1109
1110 if( variant.m_ExcludedFromBOM != aSymbol->GetExcludedFromBOM() )
1111 KICAD_FORMAT::FormatBool( m_out, "in_bom", !variant.m_ExcludedFromBOM );
1112
1113 if( variant.m_ExcludedFromBoard != aSymbol->GetExcludedFromBoard() )
1114 KICAD_FORMAT::FormatBool( m_out, "on_board", !variant.m_ExcludedFromBoard );
1115
1116 if( variant.m_ExcludedFromPosFiles != aSymbol->GetExcludedFromPosFiles() )
1117 KICAD_FORMAT::FormatBool( m_out, "in_pos_files", !variant.m_ExcludedFromPosFiles );
1118
1119 for( const auto&[fname, fvalue] : variant.m_Fields )
1120 {
1121 m_out->Print( "(field (name %s) (value %s))",
1122 m_out->Quotew( fname ).c_str(), m_out->Quotew( fvalue ).c_str() );
1123 }
1124
1125 if( variant.m_SymbolOverride )
1126 {
1127 m_out->Print( "(symbol_override %s)",
1128 m_out->Quotew( variant.m_SymbolOverride->Format().wx_str() ).c_str() );
1129 }
1130
1131 formatPinMapOverride( m_out, variant.m_PinMapOverride );
1132
1133 m_out->Print( ")" ); // Closes `variant` token.
1134 }
1135 }
1136
1137 m_out->Print( ")" ); // Closes `path` token.
1138 }
1139
1140 m_out->Print( ")" ); // Closes `project`.
1141 }
1142
1143 m_out->Print( ")" ); // Closes `instances`.
1144 }
1145
1147 m_out->Print( ")" ); // Closes `symbol`.
1148}
1149
1150
1152{
1153 wxCHECK_RET( aField != nullptr && m_out != nullptr, "" );
1154
1155 // Always write the untranslated name. SCH_FIELD::GetUntranslatedName() returns the
1156 // untranslated mandatory-field token, the untranslated directive-label token ("Netclass"),
1157 // or the user-supplied name. Using GetName() here would emit the translated form for label
1158 // fields, which broke cross-language collaboration (issue #24403).
1159 wxString fieldName = aField->GetUntranslatedName();
1160
1161 m_out->Print( "(property %s %s %s (at %s %s %s)",
1162 aField->IsPrivate() ? "private" : "",
1163 m_out->Quotew( fieldName ).c_str(),
1164 m_out->Quotew( aField->GetText() ).c_str(),
1166 aField->GetPosition().x ).c_str(),
1168 aField->GetPosition().y ).c_str(),
1169 EDA_UNIT_UTILS::FormatAngle( aField->GetTextAngle() ).c_str() );
1170
1171 if( !aField->IsVisible() )
1172 KICAD_FORMAT::FormatBool( m_out, "hide", true );
1173
1174 KICAD_FORMAT::FormatBool( m_out, "show_name", aField->IsNameShown() );
1175
1176 KICAD_FORMAT::FormatBool( m_out, "do_not_autoplace", !aField->CanAutoplace() );
1177
1178 if( !aField->IsDefaultFormatting()
1179 || ( aField->GetTextHeight() != schIUScale.MilsToIU( DEFAULT_SIZE_TEXT ) ) )
1180 {
1181 aField->Format( m_out, 0 );
1182 }
1183
1185 m_out->Print( ")" ); // Closes `property` token
1186}
1187
1188
1190{
1191 wxCHECK_RET( m_out != nullptr, "" );
1192
1193 const REFERENCE_IMAGE& refImage = aBitmap.GetReferenceImage();
1194 const BITMAP_BASE& bitmapBase = refImage.GetImage();
1195
1196 const wxImage* image = bitmapBase.GetImageData();
1197
1198 wxCHECK_RET( image != nullptr, "wxImage* is NULL" );
1199
1200 m_out->Print( "(image (at %s %s)",
1202 refImage.GetPosition().x ).c_str(),
1204 refImage.GetPosition().y ).c_str() );
1205
1206 if( !refImage.GetOrientation().IsZero() )
1207 m_out->Print( "(rotate %s)", EDA_UNIT_UTILS::FormatAngle( refImage.GetOrientation() ).c_str() );
1208
1209 double scale = refImage.GetImageScale();
1210
1211 // 20230121 or older file format versions assumed 300 image PPI at load/save.
1212 // Let's keep compatibility by changing image scale.
1213 if( SEXPR_SCHEMATIC_FILE_VERSION <= 20230121 )
1214 scale = scale * 300.0 / bitmapBase.GetPPI();
1215
1216 if( scale != 1.0 )
1217 m_out->Print( "%s", fmt::format("(scale {:g})", refImage.GetImageScale()).c_str() );
1218
1219 if( refImage.GetOpacity() < 1.0 )
1220 m_out->Print( "%s", fmt::format( "(opacity {:g})", refImage.GetOpacity() ).c_str() );
1221
1223
1224 if( aBitmap.IsLocked() )
1225 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1226
1227 wxMemoryOutputStream stream;
1228 bitmapBase.SaveImageData( stream );
1229
1230 KICAD_FORMAT::FormatStreamData( *m_out, *stream.GetOutputStreamBuffer() );
1231
1233 m_out->Print( ")" ); // Closes image token.
1234}
1235
1236
1238{
1239 wxCHECK_RET( aSheet != nullptr && m_out != nullptr, "" );
1240
1241 m_out->Print( "(sheet (at %s %s) (size %s %s)",
1243 aSheet->GetPosition().x ).c_str(),
1245 aSheet->GetPosition().y ).c_str(),
1247 aSheet->GetSize().x ).c_str(),
1249 aSheet->GetSize().y ).c_str() );
1250
1251 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aSheet->GetExcludedFromSim() );
1252 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aSheet->GetExcludedFromBOM() );
1253 KICAD_FORMAT::FormatBool( m_out, "on_board", !aSheet->GetExcludedFromBoard() );
1254 KICAD_FORMAT::FormatBool( m_out, "dnp", aSheet->GetDNP() );
1255
1256 if( aSheet->IsLocked() )
1257 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1258
1259 AUTOPLACE_ALGO fieldsAutoplaced = aSheet->GetFieldsAutoplaced();
1260
1261 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1262 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1263
1264 STROKE_PARAMS stroke( aSheet->GetBorderWidth(), LINE_STYLE::SOLID, aSheet->GetBorderColor() );
1265
1266 stroke.SetWidth( aSheet->GetBorderWidth() );
1267 stroke.Format( m_out, schIUScale );
1268
1269 m_out->Print( "(fill (color %d %d %d %s))",
1270 KiROUND( aSheet->GetBackgroundColor().r * 255.0 ),
1271 KiROUND( aSheet->GetBackgroundColor().g * 255.0 ),
1272 KiROUND( aSheet->GetBackgroundColor().b * 255.0 ),
1273 FormatDouble2Str( aSheet->GetBackgroundColor().a ).c_str() );
1274
1276
1277 for( SCH_FIELD& field : aSheet->GetFields() )
1278 {
1279 // An empty suffix is the same as none, so designs without suffixes do not churn
1280 if( field.GetId() == FIELD_T::SHEET_REF_SUFFIX && field.GetText().IsEmpty() )
1281 continue;
1282
1283 saveField( &field );
1284 }
1285
1286 for( const SCH_SHEET_PIN* pin : aSheet->GetPins() )
1287 {
1288 m_out->Print( "(pin %s %s (at %s %s %s)",
1289 EscapedUTF8( pin->GetText() ).c_str(),
1290 getSheetPinShapeToken( pin->GetShape() ),
1292 pin->GetPosition().x ).c_str(),
1294 pin->GetPosition().y ).c_str(),
1295 EDA_UNIT_UTILS::FormatAngle( getSheetPinAngle( pin->GetSide() ) ).c_str() );
1296
1298
1299 pin->Format( m_out, 0 );
1301
1302 m_out->Print( ")" ); // Closes pin token.
1303 }
1304
1305 // Save all sheet instances here except the root sheet instance.
1306 std::vector< SCH_SHEET_INSTANCE > sheetInstances = aSheet->GetInstances();
1307
1308 auto it = sheetInstances.begin();
1309
1310 while( it != sheetInstances.end() )
1311 {
1312 if( it->m_Path.size() == 0 )
1313 it = sheetInstances.erase( it );
1314 else
1315 it++;
1316 }
1317
1318 if( !sheetInstances.empty() )
1319 {
1320 m_out->Print( "(instances" );
1321
1322 KIID lastProjectUuid;
1323 bool inProjectClause = false;
1324
1325 for( size_t i = 0; i < sheetInstances.size(); i++ )
1326 {
1327 // If the instance data is part of this design but no longer has an associated sheet
1328 // path, don't save it. This prevents large amounts of orphaned instance data for the
1329 // current project from accumulating in the schematic files.
1330 //
1331 // Keep all instance data when copying to the clipboard. It may be needed on paste.
1332 bool belongsToThisProject = m_schematic->IsInstancePathInProject( sheetInstances[i].m_Path );
1333
1334 if( belongsToThisProject && !aSheetList.GetSheetPathByKIIDPath( sheetInstances[i].m_Path, false ) )
1335 {
1336 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1337 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1338 {
1339 m_out->Print( ")" ); // Closes `project` token.
1340 inProjectClause = false;
1341 }
1342
1343 continue;
1344 }
1345
1346 if( lastProjectUuid != sheetInstances[i].m_Path[0] )
1347 {
1348 wxString projectName;
1349
1350 if( belongsToThisProject )
1351 projectName = m_schematic->Project().GetProjectName();
1352 else
1353 projectName = sheetInstances[i].m_ProjectName;
1354
1355 lastProjectUuid = sheetInstances[i].m_Path[0];
1356 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
1357 inProjectClause = true;
1358 }
1359
1360 wxString path = sheetInstances[i].m_Path.AsString();
1361
1362 m_out->Print( "(path %s (page %s)",
1363 m_out->Quotew( path ).c_str(),
1364 m_out->Quotew( sheetInstances[i].m_PageNumber ).c_str() );
1365
1366 if( !sheetInstances[i].m_Variants.empty() )
1367 {
1368 for( const auto&[name, variant] : sheetInstances[i].m_Variants )
1369 {
1370 // A variant without differentials resolves identically to no variant,
1371 // writing it only keeps deleted variants alive across sessions.
1372 if( !variant.HasDifferentials( *aSheet ) )
1373 continue;
1374
1375 m_out->Print( "(variant (name %s)", m_out->Quotew( name ).c_str() );
1376
1377 if( variant.m_DNP != aSheet->GetDNP() )
1378 KICAD_FORMAT::FormatBool( m_out, "dnp", variant.m_DNP );
1379
1380 if( variant.m_ExcludedFromSim != aSheet->GetExcludedFromSim() )
1381 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", variant.m_ExcludedFromSim );
1382
1383 if( variant.m_ExcludedFromBOM != aSheet->GetExcludedFromBOM() )
1384 KICAD_FORMAT::FormatBool( m_out, "in_bom", !variant.m_ExcludedFromBOM );
1385
1386 for( const auto&[fname, fvalue] : variant.m_Fields )
1387 {
1388 m_out->Print( "(field (name %s) (value %s))",
1389 m_out->Quotew( fname ).c_str(), m_out->Quotew( fvalue ).c_str() );
1390 }
1391
1392 m_out->Print( ")" ); // Closes `variant` token.
1393 }
1394 }
1395
1396 m_out->Print( ")" ); // Closes `path` token.
1397
1398 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1399 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1400 {
1401 m_out->Print( ")" ); // Closes `project` token.
1402 inProjectClause = false;
1403 }
1404 }
1405
1406 m_out->Print( ")" ); // Closes `instances` token.
1407 }
1408
1410 m_out->Print( ")" ); // Closes sheet token.
1411}
1412
1413
1415{
1416 wxCHECK_RET( aJunction != nullptr && m_out != nullptr, "" );
1417
1418 m_out->Print( "(junction (at %s %s) (diameter %s) (color %d %d %d %s)",
1420 aJunction->GetPosition().x ).c_str(),
1422 aJunction->GetPosition().y ).c_str(),
1424 aJunction->GetDiameter() ).c_str(),
1425 KiROUND( aJunction->GetColor().r * 255.0 ),
1426 KiROUND( aJunction->GetColor().g * 255.0 ),
1427 KiROUND( aJunction->GetColor().b * 255.0 ),
1428 FormatDouble2Str( aJunction->GetColor().a ).c_str() );
1429
1430 KICAD_FORMAT::FormatUuid( m_out, aJunction->m_Uuid );
1431
1432 if( aJunction->IsLocked() )
1433 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1434
1436 m_out->Print( ")" );
1437}
1438
1439
1441{
1442 wxCHECK_RET( aNoConnect != nullptr && m_out != nullptr, "" );
1443
1444 m_out->Print( "(no_connect (at %s %s)",
1446 aNoConnect->GetPosition().x ).c_str(),
1448 aNoConnect->GetPosition().y ).c_str() );
1449
1450 KICAD_FORMAT::FormatUuid( m_out, aNoConnect->m_Uuid );
1451
1452 if( aNoConnect->IsLocked() )
1453 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1454
1456 m_out->Print( ")" );
1457}
1458
1459
1461{
1462 wxCHECK_RET( aBusEntry != nullptr && m_out != nullptr, "" );
1463
1464 // Bus to bus entries are converted to bus line segments.
1465 if( aBusEntry->GetClass() == "SCH_BUS_BUS_ENTRY" )
1466 {
1467 SCH_LINE busEntryLine( aBusEntry->GetPosition(), LAYER_BUS );
1468
1469 busEntryLine.SetEndPoint( aBusEntry->GetEnd() );
1470 saveLine( &busEntryLine );
1471 return;
1472 }
1473
1474 m_out->Print( "(bus_entry (at %s %s) (size %s %s)",
1476 aBusEntry->GetPosition().x ).c_str(),
1478 aBusEntry->GetPosition().y ).c_str(),
1480 aBusEntry->GetSize().x ).c_str(),
1482 aBusEntry->GetSize().y ).c_str() );
1483
1484 aBusEntry->GetStroke().Format( m_out, schIUScale );
1485 KICAD_FORMAT::FormatUuid( m_out, aBusEntry->m_Uuid );
1486
1487 if( aBusEntry->IsLocked() )
1488 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1489
1491 m_out->Print( ")" );
1492}
1493
1494
1496{
1497 wxCHECK_RET( aShape != nullptr && m_out != nullptr, "" );
1498
1499 // Rule areas handle locked at their own level via saveRuleArea(), so don't duplicate it
1500 // inside the shape sub-expression.
1501 bool writeLocked = aShape->Type() != SCH_RULE_AREA_T && aShape->IsLocked();
1502
1503 switch( aShape->GetShape() )
1504 {
1505 case SHAPE_T::ARC:
1506 formatArc( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1507 aShape->GetFillColor(), false, aShape->m_Uuid, writeLocked );
1508 break;
1509
1510 case SHAPE_T::CIRCLE:
1511 formatCircle( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1512 aShape->GetFillColor(), false, aShape->m_Uuid, writeLocked );
1513 break;
1514
1515 case SHAPE_T::RECTANGLE:
1516 formatRect( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1517 aShape->GetFillColor(), false, aShape->m_Uuid, writeLocked );
1518 break;
1519
1520 case SHAPE_T::BEZIER:
1521 formatBezier( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1522 aShape->GetFillColor(), false, aShape->m_Uuid, writeLocked );
1523 break;
1524
1525 case SHAPE_T::POLY:
1526 formatPoly( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1527 aShape->GetFillColor(), false, aShape->m_Uuid, writeLocked );
1528 break;
1529
1530 case SHAPE_T::ELLIPSE:
1531 formatEllipse( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(), aShape->GetFillColor(), false,
1532 aShape->m_Uuid, writeLocked );
1533 break;
1534
1536 formatEllipseArc( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(), aShape->GetFillColor(),
1537 false, aShape->m_Uuid, writeLocked );
1538 break;
1539
1540 default:
1542 }
1543}
1544
1545
1547{
1548 wxCHECK_RET( aRuleArea != nullptr && m_out != nullptr, "" );
1549
1550 m_out->Print( "(rule_area " );
1551
1552 if( aRuleArea->IsLocked() )
1553 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1554
1555 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aRuleArea->GetExcludedFromSim() );
1556 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aRuleArea->GetExcludedFromBOM() );
1557 KICAD_FORMAT::FormatBool( m_out, "on_board", !aRuleArea->GetExcludedFromBoard() );
1558 KICAD_FORMAT::FormatBool( m_out, "dnp", aRuleArea->GetDNP() );
1559
1560 saveShape( aRuleArea );
1561
1563 m_out->Print( ")" );
1564}
1565
1566
1568{
1569 wxCHECK_RET( aLine != nullptr && m_out != nullptr, "" );
1570
1571 wxString lineType;
1572
1573 STROKE_PARAMS line_stroke = aLine->GetStroke();
1574
1575 switch( aLine->GetLayer() )
1576 {
1577 case LAYER_BUS: lineType = "bus"; break;
1578 case LAYER_WIRE: lineType = "wire"; break;
1579 case LAYER_NOTES: lineType = "polyline"; break;
1580 default:
1581 UNIMPLEMENTED_FOR( LayerName( aLine->GetLayer() ) );
1582 }
1583
1584 m_out->Print( "(%s (pts (xy %s %s) (xy %s %s))",
1585 TO_UTF8( lineType ),
1587 aLine->GetStartPoint().x ).c_str(),
1589 aLine->GetStartPoint().y ).c_str(),
1591 aLine->GetEndPoint().x ).c_str(),
1593 aLine->GetEndPoint().y ).c_str() );
1594
1595 line_stroke.Format( m_out, schIUScale );
1596
1597 if( aLine->GetLayer() == LAYER_NOTES )
1598 {
1599 aLine->GetStartEnding().Format( m_out, schIUScale, "start_shape" );
1600 aLine->GetEndEnding().Format( m_out, schIUScale, "end_shape" );
1601 }
1602
1604
1605 if( aLine->IsLocked() )
1606 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1607
1609 m_out->Print( ")" );
1610}
1611
1612
1614{
1615 wxCHECK_RET( aText != nullptr && m_out != nullptr, "" );
1616
1617 // Note: label is nullptr SCH_TEXT, but not for SCH_LABEL_XXX,
1618 SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( aText );
1619
1620 m_out->Print( "(%s %s",
1621 getTextTypeToken( aText->Type() ),
1622 m_out->Quotew( aText->GetText() ).c_str() );
1623
1624 if( aText->Type() == SCH_TEXT_T )
1625 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aText->GetExcludedFromSim() );
1626
1627 if( aText->Type() == SCH_DIRECTIVE_LABEL_T )
1628 {
1629 SCH_DIRECTIVE_LABEL* flag = static_cast<SCH_DIRECTIVE_LABEL*>( aText );
1630
1631 m_out->Print( "(length %s)",
1633 flag->GetPinLength() ).c_str() );
1634 }
1635
1636 EDA_ANGLE angle = aText->GetTextAngle();
1637
1638 if( label )
1639 {
1640 if( label->Type() == SCH_GLOBAL_LABEL_T
1641 || label->Type() == SCH_HIER_LABEL_T
1642 || label->Type() == SCH_DIRECTIVE_LABEL_T )
1643 {
1644 m_out->Print( "(shape %s)", getSheetPinShapeToken( label->GetShape() ) );
1645 }
1646
1647 // The angle of the text is always 0 or 90 degrees for readibility reasons,
1648 // but the item itself can have more rotation (-90 and 180 deg)
1649 switch( label->GetSpinStyle() )
1650 {
1651 default:
1652 case SPIN_STYLE::LEFT: angle += ANGLE_180; break;
1653 case SPIN_STYLE::UP: break;
1654 case SPIN_STYLE::RIGHT: break;
1655 case SPIN_STYLE::BOTTOM: angle += ANGLE_180; break;
1656 }
1657 }
1658
1659 m_out->Print( "(at %s %s %s)",
1661 aText->GetPosition().x ).c_str(),
1663 aText->GetPosition().y ).c_str(),
1664 EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
1665
1666 if( label && !label->GetFields().empty() )
1667 {
1668 AUTOPLACE_ALGO fieldsAutoplaced = label->GetFieldsAutoplaced();
1669
1670 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1671 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1672 }
1673
1674 aText->EDA_TEXT::Format( m_out, 0 );
1676
1677 if( aText->IsLocked() )
1678 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1679
1680 if( label )
1681 {
1682 for( SCH_FIELD& field : label->GetFields() )
1683 saveField( &field );
1684 }
1685
1687 m_out->Print( ")" ); // Closes text token.
1688}
1689
1690
1692{
1693 wxCHECK_RET( aTextBox != nullptr && m_out != nullptr, "" );
1694
1695 m_out->Print( "(%s %s",
1696 aTextBox->Type() == SCH_TABLECELL_T ? "table_cell" : "text_box",
1697 m_out->Quotew( aTextBox->GetText() ).c_str() );
1698
1699 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aTextBox->GetExcludedFromSim() );
1700
1701 VECTOR2I pos = aTextBox->GetStart();
1702 VECTOR2I size = aTextBox->GetEnd() - pos;
1703
1704 m_out->Print( "(at %s %s %s) (size %s %s) (margins %s %s %s %s)",
1707 EDA_UNIT_UTILS::FormatAngle( aTextBox->GetTextAngle() ).c_str(),
1714
1715 if( SCH_TABLECELL* cell = dynamic_cast<SCH_TABLECELL*>( aTextBox ) )
1716 m_out->Print( "(span %d %d)", cell->GetColSpan(), cell->GetRowSpan() );
1717
1718 if( aTextBox->Type() != SCH_TABLECELL_T )
1719 aTextBox->GetStroke().Format( m_out, schIUScale );
1720
1721 formatFill( m_out, aTextBox->GetFillMode(), aTextBox->GetFillColor() );
1722 aTextBox->EDA_TEXT::Format( m_out, 0 );
1724
1725 if( aTextBox->IsLocked() )
1726 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1727
1729 m_out->Print( ")" );
1730}
1731
1732
1734{
1735 if( aTable->GetFlags() & SKIP_STRUCT )
1736 {
1737 aTable = static_cast<SCH_TABLE*>( aTable->Clone() );
1738
1739 int minCol = aTable->GetColCount();
1740 int maxCol = -1;
1741 int minRow = aTable->GetRowCount();
1742 int maxRow = -1;
1743
1744 for( int row = 0; row < aTable->GetRowCount(); ++row )
1745 {
1746 for( int col = 0; col < aTable->GetColCount(); ++col )
1747 {
1748 SCH_TABLECELL* cell = aTable->GetCell( row, col );
1749
1750 if( cell->IsSelected() )
1751 {
1752 minRow = std::min( minRow, row );
1753 maxRow = std::max( maxRow, row );
1754 minCol = std::min( minCol, col );
1755 maxCol = std::max( maxCol, col );
1756 }
1757 else
1758 {
1759 cell->SetFlags( STRUCT_DELETED );
1760 }
1761 }
1762 }
1763
1764 wxCHECK_MSG( maxCol >= minCol && maxRow >= minRow, /*void*/, wxT( "No selected cells!" ) );
1765
1766 int destRow = 0;
1767
1768 for( int row = minRow; row <= maxRow; row++ )
1769 aTable->SetRowHeight( destRow++, aTable->GetRowHeight( row ) );
1770
1771 int destCol = 0;
1772
1773 for( int col = minCol; col <= maxCol; col++ )
1774 aTable->SetColWidth( destCol++, aTable->GetColWidth( col ) );
1775
1776 aTable->DeleteMarkedCells();
1777 aTable->SetColCount( ( maxCol - minCol ) + 1 );
1778 }
1779
1780 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
1781
1782 m_out->Print( "(table (column_count %d)", aTable->GetColCount() );
1783
1784 m_out->Print( "(border" );
1785 KICAD_FORMAT::FormatBool( m_out, "external", aTable->StrokeExternal() );
1787
1788 if( aTable->StrokeExternal() || aTable->StrokeHeaderSeparator() )
1789 aTable->GetBorderStroke().Format( m_out, schIUScale );
1790
1791 m_out->Print( ")" ); // Close `border` token.
1792
1793 m_out->Print( "(separators" );
1794 KICAD_FORMAT::FormatBool( m_out, "rows", aTable->StrokeRows() );
1795 KICAD_FORMAT::FormatBool( m_out, "cols", aTable->StrokeColumns() );
1796
1797 if( aTable->StrokeRows() || aTable->StrokeColumns() )
1799
1800 m_out->Print( ")" ); // Close `separators` token.
1801
1802 m_out->Print( "(column_widths" );
1803
1804 for( int col = 0; col < aTable->GetColCount(); ++col )
1805 {
1806 m_out->Print( " %s",
1807 EDA_UNIT_UTILS::FormatInternalUnits( schIUScale, aTable->GetColWidth( col ) ).c_str() );
1808 }
1809
1810 m_out->Print( ")" );
1811
1812 m_out->Print( "(row_heights" );
1813
1814 for( int row = 0; row < aTable->GetRowCount(); ++row )
1815 {
1816 m_out->Print( " %s",
1817 EDA_UNIT_UTILS::FormatInternalUnits( schIUScale, aTable->GetRowHeight( row ) ).c_str() );
1818 }
1819
1820 m_out->Print( ")" );
1821
1823
1824 if( aTable->IsLocked() )
1825 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1826
1827 m_out->Print( "(cells" );
1828
1829 for( SCH_TABLECELL* cell : aTable->GetCells() )
1830 saveTextBox( cell );
1831
1832 m_out->Print( ")" ); // Close `cells` token.
1833
1835 m_out->Print( ")" ); // Close `table` token.
1836
1837 if( aTable->GetFlags() & SKIP_STRUCT )
1838 delete aTable;
1839}
1840
1841
1843{
1844 // Don't write empty groups
1845 if( aGroup->GetItems().empty() )
1846 return;
1847
1848 m_out->Print( "(group %s", m_out->Quotew( aGroup->GetName() ).c_str() );
1849
1851
1852 if( aGroup->IsLocked() )
1853 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1854
1855 if( aGroup->HasDesignBlockLink() )
1856 m_out->Print( "(lib_id \"%s\")", aGroup->GetDesignBlockLibId().Format().c_str() );
1857
1858 wxArrayString memberIds;
1859
1860 for( EDA_ITEM* member : aGroup->GetItems() )
1861 memberIds.Add( member->m_Uuid.AsString() );
1862
1863 memberIds.Sort();
1864
1865 m_out->Print( "(members" );
1866
1867 for( const wxString& memberId : memberIds )
1868 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
1869
1870 m_out->Print( ")" ); // Close `members` token.
1871
1873 m_out->Print( ")" ); // Close `group` token.
1874}
1875
1876
1877void SCH_IO_KICAD_SEXPR::saveInstances( const std::vector<SCH_SHEET_INSTANCE>& aInstances )
1878{
1879 if( aInstances.size() )
1880 {
1881 m_out->Print( "(sheet_instances" );
1882
1883 for( const SCH_SHEET_INSTANCE& instance : aInstances )
1884 {
1885 wxString path = instance.m_Path.AsString();
1886
1887 if( path.IsEmpty() )
1888 path = wxT( "/" ); // Root path
1889
1890 m_out->Print( "(path %s (page %s))",
1891 m_out->Quotew( path ).c_str(),
1892 m_out->Quotew( instance.m_PageNumber ).c_str() );
1893 }
1894
1895 m_out->Print( ")" ); // Close sheet instances token.
1896 }
1897}
1898
1899
1900void SCH_IO_KICAD_SEXPR::cacheLib( const wxString& aLibraryFileName,
1901 const std::map<std::string, UTF8>* aProperties )
1902{
1903 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
1904 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
1905
1906 if( !m_cache || !m_cache->IsFile( aLibraryFileName ) || m_cache->IsFileChanged() )
1907 {
1908 int oldModifyHash = 1;
1909 bool isNewCache = false;
1910
1911 if( m_cache )
1912 oldModifyHash = m_cache->m_modHash;
1913 else
1914 isNewCache = true;
1915
1916 // a spectacular episode in memory management:
1917 delete m_cache;
1918 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryFileName );
1919
1920 if( !isBuffering( aProperties ) || ( isNewCache && m_cache->isLibraryPathValid() ) )
1921 {
1922 m_cache->Load();
1923 m_cache->m_modHash = oldModifyHash + 1;
1924 }
1925 }
1926}
1927
1928
1929bool SCH_IO_KICAD_SEXPR::isBuffering( const std::map<std::string, UTF8>* aProperties )
1930{
1931 return ( aProperties && aProperties->contains( SCH_IO_KICAD_SEXPR::PropBuffering ) );
1932}
1933
1934
1936{
1937 if( m_cache )
1938 return m_cache->GetModifyHash();
1939
1940 // If the cache hasn't been loaded, it hasn't been modified.
1941 return 0;
1942}
1943
1944
1945void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( wxArrayString& aSymbolNameList,
1946 const wxString& aLibraryPath,
1947 const std::map<std::string, UTF8>* aProperties )
1948{
1949 bool powerSymbolsOnly = ( aProperties && aProperties->contains( SYMBOL_LIBRARY_ADAPTER::PropPowerSymsOnly ) );
1950
1951 cacheLib( aLibraryPath, aProperties );
1952
1953 if( !isBuffering( aProperties ) && !m_cache->isLibraryPathValid() )
1954 THROW_IO_ERRORF( _( "Library '%s' not found." ), aLibraryPath );
1955
1956 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1957
1958 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1959 {
1960 if( !powerSymbolsOnly || it->second->IsPower() )
1961 aSymbolNameList.Add( it->first );
1962 }
1963}
1964
1965
1966void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
1967 const wxString& aLibraryPath,
1968 const std::map<std::string, UTF8>* aProperties )
1969{
1970 bool powerSymbolsOnly = ( aProperties && aProperties->contains( SYMBOL_LIBRARY_ADAPTER::PropPowerSymsOnly ) );
1971
1972 cacheLib( aLibraryPath, aProperties );
1973
1974 if( !isBuffering( aProperties ) && !m_cache->isLibraryPathValid() )
1975 THROW_IO_ERRORF( _( "Library '%s' not found." ), aLibraryPath );
1976
1977 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1978
1979 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1980 {
1981 if( !powerSymbolsOnly || it->second->IsPower() )
1982 aSymbolList.push_back( it->second );
1983 }
1984}
1985
1986
1987LIB_SYMBOL* SCH_IO_KICAD_SEXPR::LoadSymbol( const wxString& aLibraryPath,
1988 const wxString& aSymbolName,
1989 const std::map<std::string, UTF8>* aProperties )
1990{
1991 cacheLib( aLibraryPath, aProperties );
1992
1993 LIB_SYMBOL_MAP::const_iterator it = m_cache->m_symbols.find( aSymbolName );
1994
1995 // We no longer escape '/' in symbol names, but we used to.
1996 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( '/' ) )
1997 it = m_cache->m_symbols.find( EscapeString( aSymbolName, CTX_LEGACY_LIBID ) );
1998
1999 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( wxT( "{slash}" ) ) )
2000 {
2001 wxString unescaped = aSymbolName;
2002 unescaped.Replace( wxT( "{slash}" ), wxT( "/" ) );
2003 it = m_cache->m_symbols.find( unescaped );
2004 }
2005
2006 if( it == m_cache->m_symbols.end() )
2007 return nullptr;
2008
2009 return it->second;
2010}
2011
2012
2013void SCH_IO_KICAD_SEXPR::SaveSymbol( const wxString& aLibraryPath, std::unique_ptr<LIB_SYMBOL> aSymbol,
2014 const std::map<std::string, UTF8>* aProperties )
2015{
2016 cacheLib( aLibraryPath, aProperties );
2017
2018 m_cache->AddSymbol( std::move( aSymbol ) );
2019
2020 if( !isBuffering( aProperties ) )
2021 m_cache->Save();
2022}
2023
2024
2025void SCH_IO_KICAD_SEXPR::DeleteSymbol( const wxString& aLibraryPath, const wxString& aSymbolName,
2026 const std::map<std::string, UTF8>* aProperties )
2027{
2028 cacheLib( aLibraryPath, aProperties );
2029
2030 m_cache->DeleteSymbol( aSymbolName );
2031
2032 if( !isBuffering( aProperties ) )
2033 m_cache->Save();
2034}
2035
2036
2037void SCH_IO_KICAD_SEXPR::CreateLibrary( const wxString& aLibraryPath,
2038 const std::map<std::string, UTF8>* aProperties )
2039{
2040 wxFileName fn( aLibraryPath );
2041
2042 // Normalize the path: if it's a directory on the filesystem, ensure fn is marked as a
2043 // directory so that IsDir() checks work correctly. wxFileName::IsDir() only checks if
2044 // the path string ends with a separator, not if the path is actually a directory.
2045 if( !fn.IsDir() && wxFileName::DirExists( fn.GetFullPath() ) )
2046 fn.AssignDir( fn.GetFullPath() );
2047
2048 if( !fn.IsDir() && fn.FileExists() )
2049 THROW_IO_ERRORF( _( "Symbol library file '%s' already exists." ), fn.GetFullPath() );
2050
2051 if( fn.IsDir() && fn.DirExists() )
2052 THROW_IO_ERRORF( _( "Symbol library path '%s' already exists." ), fn.GetPath() );
2053
2054 delete m_cache;
2055 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
2056 m_cache->SetModified();
2057 m_cache->Save();
2058 m_cache->Load(); // update m_writable and m_timestamp
2059}
2060
2061
2062bool SCH_IO_KICAD_SEXPR::DeleteLibrary( const wxString& aLibraryPath,
2063 const std::map<std::string, UTF8>* aProperties )
2064{
2065 wxFileName fn = aLibraryPath;
2066
2067 // Normalize the path: if it's a directory on the filesystem, ensure fn is marked as a
2068 // directory so that IsDir() checks work correctly.
2069 if( !fn.IsDir() && wxFileName::DirExists( fn.GetFullPath() ) )
2070 fn.AssignDir( fn.GetFullPath() );
2071
2072 if( !fn.FileExists() && !fn.DirExists() )
2073 return false;
2074
2075 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
2076 // we don't want that. we want bare metal portability with no UI here.
2077 if( !fn.IsDir() )
2078 {
2079 if( wxRemove( aLibraryPath ) )
2080 THROW_IO_ERRORF( _( "Symbol library file '%s' cannot be deleted." ), aLibraryPath.GetData() );
2081 }
2082 else
2083 {
2084 // This may be overly agressive. Perhaps in the future we should remove all of the *.kicad_sym
2085 // files and only delete the folder if it's empty.
2086 if( !fn.Rmdir( wxPATH_RMDIR_RECURSIVE ) )
2087 THROW_IO_ERRORF( _( "Symbol library folder '%s' cannot be deleted." ), fn.GetPath() );
2088 }
2089
2090 if( m_cache && m_cache->IsFile( aLibraryPath ) )
2091 {
2092 delete m_cache;
2093 m_cache = nullptr;
2094 }
2095
2096 return true;
2097}
2098
2099
2100void SCH_IO_KICAD_SEXPR::SaveLibrary( const wxString& aLibraryPath, const std::map<std::string, UTF8>* aProperties )
2101{
2102 if( !m_cache )
2103 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
2104
2105 wxString oldFileName = m_cache->GetFileName();
2106
2107 if( !m_cache->IsFile( aLibraryPath ) )
2108 m_cache->SetFileName( aLibraryPath );
2109
2110 // This is a forced save.
2111 m_cache->SetModified();
2112 m_cache->Save();
2113
2114 m_cache->SetFileName( oldFileName );
2115}
2116
2117
2118bool SCH_IO_KICAD_SEXPR::CanReadLibrary( const wxString& aLibraryPath ) const
2119{
2120 // Check if the path is a directory containing at least one .kicad_sym file
2121 if( wxFileName::DirExists( aLibraryPath ) )
2122 {
2123 wxDir dir( aLibraryPath );
2124
2125 if( dir.IsOpened() )
2126 {
2127 wxString filename;
2128 wxString filespec = wxT( "*." ) + wxString( FILEEXT::KiCadSymbolLibFileExtension );
2129
2130 if( dir.GetFirst( &filename, filespec, wxDIR_FILES ) )
2131 return true;
2132 }
2133
2134 return false;
2135 }
2136
2137 // Check for proper extension
2138 if( !SCH_IO::CanReadLibrary( aLibraryPath ) )
2139 return false;
2140
2141 // Above just checks for proper extension; now check that it actually exists
2142 wxFileName fn( aLibraryPath );
2143 return fn.IsOk() && fn.FileExists();
2144}
2145
2146
2147bool SCH_IO_KICAD_SEXPR::IsLibraryWritable( const wxString& aLibraryPath )
2148{
2149 wxFileName fn( aLibraryPath );
2150
2151 if( fn.FileExists() )
2152 return fn.IsFileWritable();
2153
2154 return fn.IsDirWritable();
2155}
2156
2157
2158void SCH_IO_KICAD_SEXPR::GetAvailableSymbolFields( std::vector<wxString>& aNames )
2159{
2160 if( !m_cache )
2161 return;
2162
2163 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
2164
2165 std::set<wxString> fieldNames;
2166
2167 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
2168 {
2169 std::map<wxString, wxString> chooserFields;
2170 it->second->GetChooserFields( chooserFields );
2171
2172 for( const auto& [name, value] : chooserFields )
2173 fieldNames.insert( name );
2174 }
2175
2176 std::copy( fieldNames.begin(), fieldNames.end(), std::back_inserter( aNames ) );
2177}
2178
2179
2180void SCH_IO_KICAD_SEXPR::GetDefaultSymbolFields( std::vector<wxString>& aNames )
2181{
2182 GetAvailableSymbolFields( aNames );
2183}
2184
2185
2186std::vector<LIB_SYMBOL*> SCH_IO_KICAD_SEXPR::ParseLibSymbols( std::string& aSymbolText, std::string aSource,
2187 int aFileVersion )
2188{
2189 LIB_SYMBOL* newSymbol = nullptr;
2190 LIB_SYMBOL_MAP map;
2191
2192 std::vector<LIB_SYMBOL*> newSymbols;
2193 std::unique_ptr<STRING_LINE_READER> reader = std::make_unique<STRING_LINE_READER>( aSymbolText,
2194 aSource );
2195
2196 do
2197 {
2198 SCH_IO_KICAD_SEXPR_PARSER parser( reader.get() );
2199
2200 newSymbol = parser.ParseSymbol( map, aFileVersion );
2201
2202 if( newSymbol )
2203 newSymbols.emplace_back( newSymbol );
2204
2205 reader.reset( new STRING_LINE_READER( *reader ) );
2206 }
2207 while( newSymbol );
2208
2209 return newSymbols;
2210}
2211
2212
2214{
2215 SCH_IO_KICAD_SEXPR_LIB_CACHE::SaveSymbol( symbol, formatter );
2216}
2217
2218
2219const char* SCH_IO_KICAD_SEXPR::PropBuffering = "buffering";
const char * name
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
This class handle bitmap images in KiCad.
Definition bitmap_base.h:47
bool SaveImageData(wxOutputStream &aOutStream) const
Write the bitmap data to aOutStream.
int GetPPI() const
wxImage * GetImageData()
Definition bitmap_base.h:66
bool IsZero() const
Definition eda_angle.h:135
const LIB_ID & GetDesignBlockLibId() const
Definition eda_group.h:102
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:78
wxString GetName() const
Definition eda_group.h:75
bool HasDesignBlockLink() const
Definition eda_group.h:99
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
bool IsSelected() const
Definition eda_item.h:134
EDA_ITEM * GetParent() const
Definition eda_item.h:112
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
EDA_ITEM_FLAGS GetFlags() const
Definition eda_item.h:167
FILL_T GetFillMode() const
Definition eda_shape.h:151
SHAPE_T GetShape() const
Definition eda_shape.h:178
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
COLOR4D GetFillColor() const
Definition eda_shape.h:162
wxString SHAPE_T_asString() const
bool IsDefaultFormatting() const
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual bool IsVisible() const
Definition eda_text.h:226
virtual int GetTextHeight() const
Definition eda_text.h:307
virtual void Format(OUTPUTFORMATTER *aFormatter, int aControlBits) const
Output the object to aFormatter in s-expression form.
virtual EDA_ANGLE GetTextAngle() const
Definition eda_text.h:178
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
A LINE_READER that reads from an open file.
Definition richio.h:157
void Rewind()
Rewind the file and resets the line number back to zero.
Definition richio.h:206
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:202
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:385
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition io_base.h:267
virtual bool CanReadLibrary(const wxString &aFileName) const
Checks if this IO object can read the specified library file/directory.
Definition io_base.cpp:71
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:101
double r
Red component.
Definition color4d.h:391
double g
Green component.
Definition color4d.h:392
double a
Alpha component.
Definition color4d.h:394
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:400
double b
Blue component.
Definition color4d.h:393
bool MakeRelativeTo(const KIID_PATH &aPath)
Definition kiid.cpp:378
wxString AsString() const
Definition kiid.cpp:423
Definition kiid.h:46
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
UTF8 Format() const
Definition lib_id.cpp:132
Define a library symbol object.
Definition lib_symbol.h:114
void Format(OUTPUTFORMATTER *aOut, const EDA_IU_SCALE &aIuScale, const char *aToken) const
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition richio.h:65
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:351
An interface used to output 8 bit text in a convenient way.
Definition richio.h:294
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:505
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:432
void Format(OUTPUTFORMATTER *aFormatter) const
Output the page class to aFormatter in s-expression form.
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:710
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
A REFERENCE_IMAGE is a wrapper around a BITMAP_IMAGE that is displayed in an editor as a reference fo...
EDA_ANGLE GetOrientation() const
VECTOR2I GetPosition() const
double GetOpacity() const
const BITMAP_BASE & GetImage() const
Get the underlying image.
double GetImageScale() const
Holds all the data relating to one schematic.
Definition schematic.h:155
bool IsTopLevelSheetUuid(const KIID &aUuid) const
Check if a UUID names one of this schematic's top level sheets.
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
PROJECT & Project() const
Return a reference to the project this schematic is part of.
Definition schematic.h:177
bool IsValid() const
A simple test if the schematic is loaded, not a complete one.
Definition schematic.h:384
SCH_SHEET & Root() const
Definition schematic.h:282
KIID_PATH NormalizeInstancePath(const KIID_PATH &aPath) const
Strip the leading virtual root from a stored instance path, which SCH_SHEET_PATH::Path() omits but st...
bool IsInstancePathInProject(const KIID_PATH &aPath) const
Test whether an instance path is rooted in this schematic's top level sheets.
Object to handle a bitmap image that can be inserted in a schematic.
Definition sch_bitmap.h:36
REFERENCE_IMAGE & GetReferenceImage()
Definition sch_bitmap.h:50
Base class for a bus or wire entry.
VECTOR2I GetSize() const
VECTOR2I GetPosition() const override
virtual STROKE_PARAMS GetStroke() const override
VECTOR2I GetEnd() const
VECTOR2I GetPosition() const override
bool IsNameShown() const
Definition sch_field.h:225
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
wxString GetUntranslatedName() const
Get the untranslated field name for storage, variable look-up, etc.
bool CanAutoplace() const
Definition sch_field.h:236
A set of SCH_ITEMs (i.e., without duplicates).
Definition sch_group.h:48
A cache assistant for the KiCad s-expression symbol libraries.
static void SaveSymbol(LIB_SYMBOL *aSymbol, OUTPUTFORMATTER &aFormatter, const wxString &aLibName=wxEmptyString, bool aIncludeData=true)
Object to parser s-expression symbol library and schematic file formats.
const std::map< wxString, wxString > & GetNetChainNetClasses() const
const std::map< wxString, COLOR4D > & GetNetChainColors() const
void ParseSchematic(SCH_SHEET *aSheet, bool aIsCopyableOnly=false, int aFileVersion=SEXPR_SCHEMATIC_FILE_VERSION)
Parse the internal LINE_READER object into aSheet.
const std::map< wxString, CHAIN_TERMINALS > & GetNetChainTerminalRefs() const
LIB_SYMBOL * ParseSymbol(LIB_SYMBOL_MAP &aSymbolLibMap, int aFileVersion=SEXPR_SYMBOL_LIB_FILE_VERSION)
Parse internal LINE_READER object into symbols and return all found.
const std::map< wxString, std::set< wxString > > & GetNetChainMemberNets() const
wxString m_path
Root project path for loading child sheets.
void GetDefaultSymbolFields(std::vector< wxString > &aNames) override
Retrieves a list of (custom) field names that should be shown by default for this library in the symb...
void saveShape(SCH_SHAPE *aShape)
void SaveSchematicFile(const wxString &aFileName, SCH_SHEET *aSheet, SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aSchematic to a storage file in a format that this SCH_IO implementation knows about,...
void SaveLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
SCH_SHEET_PATH m_currentSheetPath
void saveGroup(SCH_GROUP *aGroup)
void LoadContent(LINE_READER &aReader, SCH_SHEET *aSheet, int aVersion=SEXPR_SCHEMATIC_FILE_VERSION)
void EnumerateSymbolLib(wxArrayString &aSymbolNameList, const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Populate a list of LIB_SYMBOL alias names contained within the library aLibraryPath.
void FormatSchematicToFormatter(OUTPUTFORMATTER *aOut, SCH_SHEET *aSheet, SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties=nullptr)
Serialize a schematic sheet to an OUTPUTFORMATTER without file I/O or Prettify.
bool m_appending
Schematic load append status.
std::vector< SCH_SHEET * > m_loadedRootSheets
Root sheets from previous LoadSchematicFile() calls, enabling screen reuse across top-level sheets th...
int m_version
Version of file being loaded.
void loadFile(const wxString &aFileName, SCH_SHEET *aSheet)
static void FormatLibSymbol(LIB_SYMBOL *aPart, OUTPUTFORMATTER &aFormatter)
void DeleteSymbol(const wxString &aLibraryPath, const wxString &aSymbolName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete the entire LIB_SYMBOL associated with aAliasName from the library aLibraryPath.
void loadHierarchy(const SCH_SHEET_PATH &aParentSheetPath, SCH_SHEET *aSheet)
static std::vector< LIB_SYMBOL * > ParseLibSymbols(std::string &aSymbolText, std::string aSource, int aFileVersion=SEXPR_SCHEMATIC_FILE_VERSION)
OUTPUTFORMATTER * m_out
The formatter for saving SCH_SCREEN objects.
SCH_SHEET * LoadSchematicFile(const wxString &aFileName, SCHEMATIC *aSchematic, SCH_SHEET *aAppendToMe=nullptr, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load information from some input file format that this SCH_IO implementation knows about,...
LIB_SYMBOL * LoadSymbol(const wxString &aLibraryPath, const wxString &aAliasName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a LIB_SYMBOL object having aPartName from the aLibraryPath containing a library format that this...
wxString m_error
For throwing exceptions or errors on partial loads.
void saveInstances(const std::vector< SCH_SHEET_INSTANCE > &aSheets)
bool isBuffering(const std::map< std::string, UTF8 > *aProperties)
static const char * PropBuffering
The property used internally by the plugin to enable cache buffering which prevents the library file ...
SCH_SHEET * m_rootSheet
The root sheet of the schematic being loaded.
void cacheLib(const wxString &aLibraryFileName, const std::map< std::string, UTF8 > *aProperties)
void saveRuleArea(SCH_RULE_AREA *aRuleArea)
void saveField(SCH_FIELD *aField)
SCH_IO_KICAD_SEXPR_LIB_CACHE * m_cache
void Format(SCH_SHEET *aSheet)
bool IsLibraryWritable(const wxString &aLibraryPath) override
Return true if the library at aLibraryPath is writable.
void init(SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties=nullptr)
initialize PLUGIN like a constructor would.
bool DeleteLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete an existing library and returns true, or if library does not exist returns false,...
void saveBitmap(const SCH_BITMAP &aBitmap)
void saveText(SCH_TEXT *aText)
void saveSheet(SCH_SHEET *aSheet, const SCH_SHEET_LIST &aSheetList)
SCHEMATIC * m_schematic
init() reads this before assigning it.
int GetModifyHash() const override
Return the modification hash from the library cache.
bool m_sheetLoad
Loading a sheet into an open schematic.
bool CanReadLibrary(const wxString &aLibraryPath) const override
Checks if this IO object can read the specified library file/directory.
void saveLine(SCH_LINE *aLine)
void saveNoConnect(SCH_NO_CONNECT *aNoConnect)
void saveTable(SCH_TABLE *aTable)
std::stack< wxString > m_currentPath
Stack to maintain nested sheet paths.
void CreateLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Create a new empty library at aLibraryPath empty.
void SaveSymbol(const wxString &aLibraryPath, std::unique_ptr< LIB_SYMBOL > aSymbol, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aSymbol to an existing library located at aLibraryPath.
void saveJunction(SCH_JUNCTION *aJunction)
std::function< bool(wxString aTitle, int aIcon, wxString aMsg, wxString aAction)> m_queryUserCallback
void saveTextBox(SCH_TEXTBOX *aText)
void saveSymbol(SCH_SYMBOL *aSymbol, const SCHEMATIC &aSchematic, const SCH_SHEET_LIST &aSheetList, bool aForClipboard, const SCH_SHEET_PATH *aRelativePath=nullptr)
void saveBusEntry(SCH_BUS_ENTRY_BASE *aBusEntry)
void GetAvailableSymbolFields(std::vector< wxString > &aNames) override
Retrieves a list of (custom) field names that are present on symbols in this library.
SCH_IO(const wxString &aName)
Definition sch_io.h:406
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
int GetBodyStyle() const
Definition sch_item.h:253
bool IsLocked() const override
Definition sch_item.cpp:179
bool IsPrivate() const
Definition sch_item.h:259
SCH_LAYER_ID GetLayer() const
Return the layer this item is on.
Definition sch_item.h:353
AUTOPLACE_ALGO GetFieldsAutoplaced() const
Return whether the fields have been automatically placed.
Definition sch_item.h:678
wxString GetClass() const override
Return the class name.
Definition sch_item.h:180
int GetDiameter() const
VECTOR2I GetPosition() const override
KIGFX::COLOR4D GetColor() const
SPIN_STYLE GetSpinStyle() const
LABEL_FLAG_SHAPE GetShape() const
Definition sch_label.h:178
std::vector< SCH_FIELD > & GetFields()
Definition sch_label.h:210
Segment description base class to describe items which have 2 end points (track, wire,...
Definition sch_line.h:39
virtual STROKE_PARAMS GetStroke() const override
Definition sch_line.h:198
const LINE_ENDING & GetEndEnding() const
Definition sch_line.h:204
VECTOR2I GetEndPoint() const
Definition sch_line.h:145
VECTOR2I GetStartPoint() const
Definition sch_line.h:136
const LINE_ENDING & GetStartEnding() const
Definition sch_line.h:201
void SetEndPoint(const VECTOR2I &aPosition)
Definition sch_line.h:146
A net chain is a collection of nets that are connected together through passive components.
const std::set< wxString > & GetNets() const
const wxString & GetNetClass() const
const KIGFX::COLOR4D & GetColor() const
const wxString & GetName() const
const wxString & GetTerminalRefDes(int aIdx) const
static bool IsPersistableNet(const wxString &aNet)
Synthetic keys do not survive a reload, so only named nets are written out.
const wxString & GetTerminalPinNum(int aIdx) const
VECTOR2I GetPosition() const override
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flag.
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
const PAGE_INFO & GetPageSettings() const
Definition sch_screen.h:144
const std::map< wxString, LIB_SYMBOL * > & GetLibSymbols() const
Fetch a list of unique LIB_SYMBOL object pointers required to properly render each SCH_SYMBOL in this...
Definition sch_screen.h:565
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
const wxString & GetFileName() const
Definition sch_screen.h:157
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
TITLE_BLOCK & GetTitleBlock()
Definition sch_screen.h:168
wxString GroupsSanityCheck(bool repair=false)
Consistency check of internal m_groups structure.
KIID m_uuid
A unique identifier for each schematic file.
Definition sch_screen.h:812
void SetFileReadOnly(bool aIsReadOnly)
Definition sch_screen.h:159
void IncludeVariantSymbols(const SCH_SYMBOL &aSymbol, bool aRefresh=false)
Include the alternate symbols that aSymbol's variants select in the library symbols.
void SetFileExists(bool aFileExists)
Definition sch_screen.h:162
STROKE_PARAMS GetStroke() const override
Definition sch_shape.h:59
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
std::optional< SCH_SHEET_PATH > GetSheetPathByKIIDPath(const KIID_PATH &aPath, bool aIncludeLastSheet=true) const
Finds a SCH_SHEET_PATH that matches the provided KIID_PATH.
void StripRefSuffixes()
Recover the base references from the composed references a file stores.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
bool empty() const
Forwarded method from std::vector.
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
SCH_SCREEN * LastScreen()
void push_back(SCH_SHEET *aSheet)
Forwarded method from std::vector.
void pop_back()
Forwarded method from std::vector.
Define a sheet pin (label) used in sheets to create hierarchical schematics.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
bool HasRootInstance() const
Check to see if this sheet has a root sheet instance.
std::vector< SCH_FIELD > & GetFields()
Return a reference to the vector holding the sheet's fields.
Definition sch_sheet.h:93
bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
VECTOR2I GetSize() const
Definition sch_sheet.h:189
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
VECTOR2I GetPosition() const override
Definition sch_sheet.h:548
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
const SCH_SHEET_INSTANCE & GetRootInstance() const
Return the root sheet instance data.
KIGFX::COLOR4D GetBorderColor() const
Definition sch_sheet.h:195
bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flags.
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition sch_sheet.h:519
int GetBorderWidth() const
Definition sch_sheet.h:192
std::vector< SCH_SHEET_PIN * > & GetPins()
Definition sch_sheet.h:285
const std::vector< SCH_SHEET_INSTANCE > & GetInstances() const
Definition sch_sheet.h:563
KIGFX::COLOR4D GetBackgroundColor() const
Definition sch_sheet.h:198
Schematic symbol object.
Definition sch_symbol.h:76
PASSTHROUGH_MODE GetPassthroughMode() const
Definition sch_symbol.h:918
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
std::vector< std::unique_ptr< SCH_PIN > > & GetRawPins()
Definition sch_symbol.h:715
const std::vector< SCH_SYMBOL_INSTANCE > & GetInstances() const
Definition sch_symbol.h:136
bool UseLibIdLookup() const
Definition sch_symbol.h:183
std::vector< LIB_ID > GetVariantSymbolOverrides() const
wxString GetSchSymbolLibraryName() const
PIN_MAP_INSTANCE_OVERRIDE GetPinMapOverride(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const
bool GetExcludedFromBOM(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
VECTOR2I GetPosition() const override
Definition sch_symbol.h:958
const LIB_ID & GetLibId() const override
Definition sch_symbol.h:166
bool GetExcludedFromPosFiles(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
bool GetInstance(SCH_SYMBOL_INSTANCE &aInstance, const KIID_PATH &aSheetPath, bool aTestFromEnd=false) const
bool GetExcludedFromBoard(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
int GetOrientation() const override
Get the display symbol orientation.
virtual bool GetDNP(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Set or clear the 'Do Not Populate' flag.
wxString GetPrefix() const
Definition sch_symbol.h:241
void SetRowHeight(int aRow, int aHeight)
Definition sch_table.h:138
const STROKE_PARAMS & GetSeparatorsStroke() const
Definition sch_table.h:76
void SetColCount(int aCount)
Definition sch_table.h:118
bool StrokeExternal() const
Definition sch_table.h:52
int GetRowHeight(int aRow) const
Definition sch_table.h:140
void SetColWidth(int aCol, int aWidth)
Definition sch_table.h:128
std::vector< SCH_TABLECELL * > GetCells() const
Definition sch_table.h:158
int GetColWidth(int aCol) const
Definition sch_table.h:130
const STROKE_PARAMS & GetBorderStroke() const
Definition sch_table.h:58
int GetColCount() const
Definition sch_table.h:119
bool StrokeHeaderSeparator() const
Definition sch_table.h:55
void DeleteMarkedCells()
Definition sch_table.h:183
SCH_TABLECELL * GetCell(int aRow, int aCol) const
Definition sch_table.h:148
bool StrokeColumns() const
Definition sch_table.h:98
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
Definition sch_table.h:232
bool StrokeRows() const
Definition sch_table.h:101
int GetRowCount() const
Definition sch_table.h:121
int GetMarginBottom() const
Definition sch_textbox.h:82
int GetMarginLeft() const
Definition sch_textbox.h:79
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
int GetMarginRight() const
Definition sch_textbox.h:81
int GetMarginTop() const
Definition sch_textbox.h:80
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition sch_text.h:86
VECTOR2I GetPosition() const override
Definition sch_text.h:143
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition richio.h:225
Simple container to manage line stroke parameters.
void SetWidth(int aWidth)
void Format(OUTPUTFORMATTER *out, const EDA_IU_SCALE &aIuScale) const
static const char * PropPowerSymsOnly
virtual void Format(OUTPUTFORMATTER *aFormatter) const
Output the object to aFormatter in s-expression form.
const char * c_str() const
Definition utf8.h:104
wxString wx_str() const
Definition utf8.cpp:41
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
Definition common.cpp:60
@ INTERNAL
Definition common.h:96
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
static constexpr EDA_ANGLE ANGLE_270
Definition eda_angle.h:477
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:476
#define STRUCT_DELETED
flag indication structures to be erased
#define SKIP_STRUCT
flag indicating that the structure should be ignored
@ ELLIPSE
Definition eda_shape.h:63
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ ELLIPSE_ARC
Definition eda_shape.h:64
#define DEFAULT_SIZE_TEXT
This is the "default-of-the-default" hardcoded text size; individual application define their own def...
Definition eda_text.h:84
#define THROW_IO_ERRORF(msg,...)
#define THROW_IO_CANCELLED()
static const std::string KiCadSymbolLibFileExtension
const wxChar *const traceSchPlugin
Flag to enable legacy schematic plugin debug output.
wxString LayerName(int aLayer)
Returns the default display name for a given layer.
Definition layer_id.cpp:31
@ LAYER_WIRE
Definition layer_ids.h:483
@ LAYER_NOTES
Definition layer_ids.h:498
@ LAYER_BUS
Definition layer_ids.h:484
Utilities for intentionally "leaking" memory at program exit.
#define LSAN_IGNORE(ptr)
#define UNIMPLEMENTED_FOR(type)
Definition macros.h:92
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 FormatCustomProperties(OUTPUTFORMATTER *aOut, const EDA_ITEM &aItem)
Writes the item's custom properties as a series of (custom_property "key" "value")
void FormatUuid(OUTPUTFORMATTER *aOut, const KIID &aUuid)
void FormatStreamData(OUTPUTFORMATTER &aOut, const wxStreamBuffer &aStream)
Write binary data to the formatter as base 64 encoded string.
void FormatBool(OUTPUTFORMATTER *aOut, const wxString &aKey, bool aValue)
Writes a boolean to the formatter, in the style (aKey [yes|no])
#define SEXPR_SCHEMATIC_FILE_VERSION
Schematic file version.
Class to handle a set of SCH_ITEMs.
static void formatPinMapOverride(OUTPUTFORMATTER *aOut, const PIN_MAP_INSTANCE_OVERRIDE &aOverride)
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 formatEllipseArc(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aEllipseArc, 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)
const char * getSheetPinShapeToken(LABEL_FLAG_SHAPE aShape)
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 * getTextTypeToken(KICAD_T 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 formatEllipse(OUTPUTFORMATTER *aFormatter, EDA_SHAPE *aEllipse, 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)
EDA_ANGLE getSheetPinAngle(SHEET_SIDE aSide)
void formatFill(OUTPUTFORMATTER *aFormatter, FILL_T aFillMode, const COLOR4D &aFillColor)
Fill token formatting helper.
AUTOPLACE_ALGO
Definition sch_item.h:73
@ AUTOPLACE_MANUAL
Definition sch_item.h:76
@ AUTOPLACE_AUTO
Definition sch_item.h:75
std::string toUTFTildaText(const wxString &txt)
Convert a wxString to UTF8 and replace any control characters with a ~, where a control character is ...
static wxString projectKey(const wxString &aFullPath)
const int scale
std::string FormatDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 This function is intended in...
std::string EscapedUTF8(const wxString &aString)
Return an 8 bit UTF8 string given aString in Unicode form.
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
@ CTX_LEGACY_LIBID
One symbol-pin to footprint-pad mapping inside a PIN_MAP.
Definition pin_map.h:42
Per-instance override of the active pin map and a sparse delta on top.
Definition pin_map.h:200
std::vector< PIN_MAP_ENTRY > m_Edits
Definition pin_map.h:203
bool IsDefault() const
Definition pin_map.h:210
PIN_MAP_OVERRIDE_MODE m_Mode
Definition pin_map.h:201
A simple container for sheet instance information.
A simple container for schematic symbol instance information.
@ SYM_ORIENT_270
Definition symbol.h:39
@ SYM_MIRROR_Y
Definition symbol.h:41
@ SYM_ORIENT_180
Definition symbol.h:38
@ SYM_MIRROR_X
Definition symbol.h:40
@ SYM_ORIENT_90
Definition symbol.h:37
std::map< wxString, LIB_SYMBOL *, LibSymbolMapSort > LIB_SYMBOL_MAP
Symbol library map sorted by the symbol name.
FIELD_T
The set of all field indices assuming an array like sequence that a SCH_COMPONENT or LIB_PART can hol...
@ SHEET_REF_SUFFIX
Optional sheet field appended to the references of the sheet's symbols.
@ REFERENCE
Field Reference of part, i.e. "IC21".
const std::string table
static EDA_ORIENTATION orientation(double d)
std::string path
KIBIS_PIN * pin
wxLogTrace helper definitions.
@ SCH_GROUP_T
Definition typeinfo.h:169
@ SCH_TABLE_T
Definition typeinfo.h:161
@ SCH_LINE_T
Definition typeinfo.h:159
@ SCH_NO_CONNECT_T
Definition typeinfo.h:156
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_TABLECELL_T
Definition typeinfo.h:162
@ SCH_DIRECTIVE_LABEL_T
Definition typeinfo.h:167
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_MARKER_T
Definition typeinfo.h:154
@ SCH_SHAPE_T
Definition typeinfo.h:145
@ SCH_RULE_AREA_T
Definition typeinfo.h:166
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCH_BUS_BUS_ENTRY_T
Definition typeinfo.h:158
@ SCH_TEXT_T
Definition typeinfo.h:147
@ SCH_BUS_WIRE_ENTRY_T
Definition typeinfo.h:157
@ SCH_BITMAP_T
Definition typeinfo.h:160
@ SCH_TEXTBOX_T
Definition typeinfo.h:148
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_JUNCTION_T
Definition typeinfo.h:155
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.