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