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