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