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