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>
36#include <progress_reporter.h>
37#include <schematic.h>
38#include <schematic_lexer.h>
39#include <sch_bitmap.h>
40#include <sch_bus_entry.h>
41#include <sch_edit_frame.h> // SYMBOL_ORIENTATION_T
42#include <sch_group.h>
47#include <sch_junction.h>
48#include <sch_line.h>
49#include <sch_no_connect.h>
50#include <sch_pin.h>
51#include <sch_rule_area.h>
52#include <sch_screen.h>
53#include <sch_shape.h>
54#include <sch_sheet.h>
55#include <sch_sheet_pin.h>
56#include <sch_symbol.h>
57#include <sch_table.h>
58#include <sch_tablecell.h>
59#include <sch_text.h>
60#include <sch_textbox.h>
61#include <string_utils.h>
62#include <symbol_lib_table.h> // for PropPowerSymsOnly definition.
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", ordinalInstance.m_DNP );
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 bool isOrphaned = ( inst.m_Path[0] == rootSheetUuid )
825 && !aSheetList.GetSheetPathByKIIDPath( inst.m_Path );
826
827 // Keep all instance data when copying to the clipboard. They may be needed on paste.
828 if( !aForClipboard && isOrphaned )
829 continue;
830
831 auto it = projectInstances.find( inst.m_Path[0] );
832
833 if( it == projectInstances.end() )
834 projectInstances[ inst.m_Path[0] ] = { inst };
835 else
836 it->second.emplace_back( inst );
837 }
838
839 for( auto& [uuid, instances] : projectInstances )
840 {
841 wxCHECK2( instances.size(), continue );
842
843 // Sort project instances by KIID_PATH.
844 std::sort( instances.begin(), instances.end(),
846 {
847 return aLhs.m_Path < aRhs.m_Path;
848 } );
849
850 projectName = instances[0].m_ProjectName;
851
852 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
853
854 for( const SCH_SYMBOL_INSTANCE& instance : instances )
855 {
856 wxString path;
857 KIID_PATH tmp = instance.m_Path;
858
859 if( aForClipboard && aRelativePath )
860 tmp.MakeRelativeTo( aRelativePath->Path() );
861
862 path = tmp.AsString();
863
864 m_out->Print( "(path %s (reference %s) (unit %d)",
865 m_out->Quotew( path ).c_str(),
866 m_out->Quotew( instance.m_Reference ).c_str(),
867 instance.m_Unit );
868
869 if( !instance.m_Variants.empty() )
870 {
871 for( const auto&[name, variant] : instance.m_Variants )
872 {
873 m_out->Print( "(variant (name %s)", m_out->Quotew( name ).c_str() );
874
875 if( variant.m_DNP != aSymbol->GetDNP() )
876 KICAD_FORMAT::FormatBool( m_out, "dnp", variant.m_DNP );
877
878 if( variant.m_ExcludedFromSim != aSymbol->GetExcludedFromSim() )
879 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", variant.m_ExcludedFromSim );
880
881 if( variant.m_ExcludedFromBOM != aSymbol->GetExcludedFromBOM() )
882 KICAD_FORMAT::FormatBool( m_out, "in_bom", variant.m_ExcludedFromBOM );
883
884 for( const auto&[fname, fvalue] : variant.m_Fields )
885 {
886 m_out->Print( "(field (name %s) (value %s))",
887 m_out->Quotew( fname ).c_str(), m_out->Quotew( fvalue ).c_str() );
888 }
889
890 m_out->Print( ")" ); // Closes `variant` token.
891 }
892 }
893
894 m_out->Print( ")" ); // Closes `path` token.
895 }
896
897 m_out->Print( ")" ); // Closes `project`.
898 }
899
900 m_out->Print( ")" ); // Closes `instances`.
901 }
902
903 m_out->Print( ")" ); // Closes `symbol`.
904}
905
906
908{
909 wxCHECK_RET( aField != nullptr && m_out != nullptr, "" );
910
911 wxString fieldName;
912
913 if( aField->IsMandatory() )
914 fieldName = aField->GetCanonicalName();
915 else
916 fieldName = aField->GetName();
917
918 m_out->Print( "(property %s %s %s (at %s %s %s)",
919 aField->IsPrivate() ? "private" : "",
920 m_out->Quotew( fieldName ).c_str(),
921 m_out->Quotew( aField->GetText() ).c_str(),
923 aField->GetPosition().x ).c_str(),
925 aField->GetPosition().y ).c_str(),
926 EDA_UNIT_UTILS::FormatAngle( aField->GetTextAngle() ).c_str() );
927
928 if( !aField->IsVisible() )
929 KICAD_FORMAT::FormatBool( m_out, "hide", true );
930
931 if( aField->IsNameShown() )
932 KICAD_FORMAT::FormatBool( m_out, "show_name", true );
933
934 if( !aField->CanAutoplace() )
935 KICAD_FORMAT::FormatBool( m_out, "do_not_autoplace", true );
936
937 if( !aField->IsDefaultFormatting()
938 || ( aField->GetTextHeight() != schIUScale.MilsToIU( DEFAULT_SIZE_TEXT ) ) )
939 {
940 aField->Format( m_out, 0 );
941 }
942
943 m_out->Print( ")" ); // Closes `property` token
944}
945
946
948{
949 wxCHECK_RET( m_out != nullptr, "" );
950
951 const REFERENCE_IMAGE& refImage = aBitmap.GetReferenceImage();
952 const BITMAP_BASE& bitmapBase = refImage.GetImage();
953
954 const wxImage* image = bitmapBase.GetImageData();
955
956 wxCHECK_RET( image != nullptr, "wxImage* is NULL" );
957
958 m_out->Print( "(image (at %s %s)",
960 refImage.GetPosition().x ).c_str(),
962 refImage.GetPosition().y ).c_str() );
963
964 double scale = refImage.GetImageScale();
965
966 // 20230121 or older file format versions assumed 300 image PPI at load/save.
967 // Let's keep compatibility by changing image scale.
968 if( SEXPR_SCHEMATIC_FILE_VERSION <= 20230121 )
969 scale = scale * 300.0 / bitmapBase.GetPPI();
970
971 if( scale != 1.0 )
972 m_out->Print( "%s", fmt::format("(scale {:g})", refImage.GetImageScale()).c_str() );
973
975
976 wxMemoryOutputStream stream;
977 bitmapBase.SaveImageData( stream );
978
979 KICAD_FORMAT::FormatStreamData( *m_out, *stream.GetOutputStreamBuffer() );
980
981 m_out->Print( ")" ); // Closes image token.
982}
983
984
986{
987 wxCHECK_RET( aSheet != nullptr && m_out != nullptr, "" );
988
989 m_out->Print( "(sheet (at %s %s) (size %s %s)",
991 aSheet->GetPosition().x ).c_str(),
993 aSheet->GetPosition().y ).c_str(),
995 aSheet->GetSize().x ).c_str(),
997 aSheet->GetSize().y ).c_str() );
998
999 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aSheet->GetExcludedFromSim() );
1000 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aSheet->GetExcludedFromBOM() );
1001 KICAD_FORMAT::FormatBool( m_out, "on_board", !aSheet->GetExcludedFromBoard() );
1002 KICAD_FORMAT::FormatBool( m_out, "dnp", aSheet->GetDNP() );
1003
1004 AUTOPLACE_ALGO fieldsAutoplaced = aSheet->GetFieldsAutoplaced();
1005
1006 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1007 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1008
1009 STROKE_PARAMS stroke( aSheet->GetBorderWidth(), LINE_STYLE::SOLID, aSheet->GetBorderColor() );
1010
1011 stroke.SetWidth( aSheet->GetBorderWidth() );
1012 stroke.Format( m_out, schIUScale );
1013
1014 m_out->Print( "(fill (color %d %d %d %s))",
1015 KiROUND( aSheet->GetBackgroundColor().r * 255.0 ),
1016 KiROUND( aSheet->GetBackgroundColor().g * 255.0 ),
1017 KiROUND( aSheet->GetBackgroundColor().b * 255.0 ),
1018 FormatDouble2Str( aSheet->GetBackgroundColor().a ).c_str() );
1019
1021
1022 for( SCH_FIELD& field : aSheet->GetFields() )
1023 saveField( &field );
1024
1025 for( const SCH_SHEET_PIN* pin : aSheet->GetPins() )
1026 {
1027 m_out->Print( "(pin %s %s (at %s %s %s)",
1028 EscapedUTF8( pin->GetText() ).c_str(),
1029 getSheetPinShapeToken( pin->GetShape() ),
1031 pin->GetPosition().x ).c_str(),
1033 pin->GetPosition().y ).c_str(),
1034 EDA_UNIT_UTILS::FormatAngle( getSheetPinAngle( pin->GetSide() ) ).c_str() );
1035
1037
1038 pin->Format( m_out, 0 );
1039
1040 m_out->Print( ")" ); // Closes pin token.
1041 }
1042
1043 // Save all sheet instances here except the root sheet instance.
1044 std::vector< SCH_SHEET_INSTANCE > sheetInstances = aSheet->GetInstances();
1045
1046 auto it = sheetInstances.begin();
1047
1048 while( it != sheetInstances.end() )
1049 {
1050 if( it->m_Path.size() == 0 )
1051 it = sheetInstances.erase( it );
1052 else
1053 it++;
1054 }
1055
1056 if( !sheetInstances.empty() )
1057 {
1058 m_out->Print( "(instances" );
1059
1060 KIID lastProjectUuid;
1061 KIID rootSheetUuid = m_schematic->Root().m_Uuid;
1062 bool inProjectClause = false;
1063
1064 for( size_t i = 0; i < sheetInstances.size(); i++ )
1065 {
1066 // If the instance data is part of this design but no longer has an associated sheet
1067 // path, don't save it. This prevents large amounts of orphaned instance data for the
1068 // current project from accumulating in the schematic files.
1069 //
1070 // Keep all instance data when copying to the clipboard. It may be needed on paste.
1071 if( ( sheetInstances[i].m_Path[0] == rootSheetUuid )
1072 && !aSheetList.GetSheetPathByKIIDPath( sheetInstances[i].m_Path, false ) )
1073 {
1074 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1075 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1076 {
1077 m_out->Print( ")" ); // Closes `project` token.
1078 inProjectClause = false;
1079 }
1080
1081 continue;
1082 }
1083
1084 if( lastProjectUuid != sheetInstances[i].m_Path[0] )
1085 {
1086 wxString projectName;
1087
1088 if( sheetInstances[i].m_Path[0] == rootSheetUuid )
1089 projectName = m_schematic->Project().GetProjectName();
1090 else
1091 projectName = sheetInstances[i].m_ProjectName;
1092
1093 lastProjectUuid = sheetInstances[i].m_Path[0];
1094 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
1095 inProjectClause = true;
1096 }
1097
1098 wxString path = sheetInstances[i].m_Path.AsString();
1099
1100 m_out->Print( "(path %s (page %s)",
1101 m_out->Quotew( path ).c_str(),
1102 m_out->Quotew( sheetInstances[i].m_PageNumber ).c_str() );
1103
1104 if( !sheetInstances[i].m_Variants.empty() )
1105 {
1106 for( const auto&[name, variant] : sheetInstances[i].m_Variants )
1107 {
1108 m_out->Print( "(variant (name %s)", m_out->Quotew( name ).c_str() );
1109
1110 if( variant.m_DNP != aSheet->GetDNP() )
1111 KICAD_FORMAT::FormatBool( m_out, "dnp", variant.m_DNP );
1112
1113 if( variant.m_ExcludedFromSim != aSheet->GetExcludedFromSim() )
1114 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", variant.m_ExcludedFromSim );
1115
1116 if( variant.m_ExcludedFromBOM != aSheet->GetExcludedFromBOM() )
1117 KICAD_FORMAT::FormatBool( m_out, "in_bom", variant.m_ExcludedFromBOM );
1118
1119 for( const auto&[fname, fvalue] : variant.m_Fields )
1120 {
1121 m_out->Print( "(field (name %s) (value %s))",
1122 m_out->Quotew( fname ).c_str(), m_out->Quotew( fvalue ).c_str() );
1123 }
1124
1125 m_out->Print( ")" ); // Closes `variant` token.
1126 }
1127 }
1128
1129 m_out->Print( ")" ); // Closes `path` token.
1130
1131 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1132 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1133 {
1134 m_out->Print( ")" ); // Closes `project` token.
1135 inProjectClause = false;
1136 }
1137 }
1138
1139 m_out->Print( ")" ); // Closes `instances` token.
1140 }
1141
1142 m_out->Print( ")" ); // Closes sheet token.
1143}
1144
1145
1147{
1148 wxCHECK_RET( aJunction != nullptr && m_out != nullptr, "" );
1149
1150 m_out->Print( "(junction (at %s %s) (diameter %s) (color %d %d %d %s)",
1152 aJunction->GetPosition().x ).c_str(),
1154 aJunction->GetPosition().y ).c_str(),
1156 aJunction->GetDiameter() ).c_str(),
1157 KiROUND( aJunction->GetColor().r * 255.0 ),
1158 KiROUND( aJunction->GetColor().g * 255.0 ),
1159 KiROUND( aJunction->GetColor().b * 255.0 ),
1160 FormatDouble2Str( aJunction->GetColor().a ).c_str() );
1161
1162 KICAD_FORMAT::FormatUuid( m_out, aJunction->m_Uuid );
1163 m_out->Print( ")" );
1164}
1165
1166
1168{
1169 wxCHECK_RET( aNoConnect != nullptr && m_out != nullptr, "" );
1170
1171 m_out->Print( "(no_connect (at %s %s)",
1173 aNoConnect->GetPosition().x ).c_str(),
1175 aNoConnect->GetPosition().y ).c_str() );
1176
1177 KICAD_FORMAT::FormatUuid( m_out, aNoConnect->m_Uuid );
1178 m_out->Print( ")" );
1179}
1180
1181
1183{
1184 wxCHECK_RET( aBusEntry != nullptr && m_out != nullptr, "" );
1185
1186 // Bus to bus entries are converted to bus line segments.
1187 if( aBusEntry->GetClass() == "SCH_BUS_BUS_ENTRY" )
1188 {
1189 SCH_LINE busEntryLine( aBusEntry->GetPosition(), LAYER_BUS );
1190
1191 busEntryLine.SetEndPoint( aBusEntry->GetEnd() );
1192 saveLine( &busEntryLine );
1193 return;
1194 }
1195
1196 m_out->Print( "(bus_entry (at %s %s) (size %s %s)",
1198 aBusEntry->GetPosition().x ).c_str(),
1200 aBusEntry->GetPosition().y ).c_str(),
1202 aBusEntry->GetSize().x ).c_str(),
1204 aBusEntry->GetSize().y ).c_str() );
1205
1206 aBusEntry->GetStroke().Format( m_out, schIUScale );
1207 KICAD_FORMAT::FormatUuid( m_out, aBusEntry->m_Uuid );
1208 m_out->Print( ")" );
1209}
1210
1211
1213{
1214 wxCHECK_RET( aShape != nullptr && m_out != nullptr, "" );
1215
1216 switch( aShape->GetShape() )
1217 {
1218 case SHAPE_T::ARC:
1219 formatArc( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1220 aShape->GetFillColor(), false, aShape->m_Uuid );
1221 break;
1222
1223 case SHAPE_T::CIRCLE:
1224 formatCircle( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1225 aShape->GetFillColor(), false, aShape->m_Uuid );
1226 break;
1227
1228 case SHAPE_T::RECTANGLE:
1229 formatRect( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1230 aShape->GetFillColor(), false, aShape->m_Uuid );
1231 break;
1232
1233 case SHAPE_T::BEZIER:
1234 formatBezier( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1235 aShape->GetFillColor(), false, aShape->m_Uuid );
1236 break;
1237
1238 case SHAPE_T::POLY:
1239 formatPoly( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1240 aShape->GetFillColor(), false, aShape->m_Uuid );
1241 break;
1242
1243 default:
1245 }
1246}
1247
1248
1250{
1251 wxCHECK_RET( aRuleArea != nullptr && m_out != nullptr, "" );
1252
1253 m_out->Print( "(rule_area " );
1254
1255 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aRuleArea->GetExcludedFromSim() );
1256 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aRuleArea->GetExcludedFromBOM() );
1257 KICAD_FORMAT::FormatBool( m_out, "on_board", !aRuleArea->GetExcludedFromBoard() );
1258 KICAD_FORMAT::FormatBool( m_out, "dnp", aRuleArea->GetDNP() );
1259
1260 saveShape( aRuleArea );
1261
1262 m_out->Print( ")" );
1263}
1264
1265
1267{
1268 wxCHECK_RET( aLine != nullptr && m_out != nullptr, "" );
1269
1270 wxString lineType;
1271
1272 STROKE_PARAMS line_stroke = aLine->GetStroke();
1273
1274 switch( aLine->GetLayer() )
1275 {
1276 case LAYER_BUS: lineType = "bus"; break;
1277 case LAYER_WIRE: lineType = "wire"; break;
1278 case LAYER_NOTES: lineType = "polyline"; break;
1279 default:
1280 UNIMPLEMENTED_FOR( LayerName( aLine->GetLayer() ) );
1281 }
1282
1283 m_out->Print( "(%s (pts (xy %s %s) (xy %s %s))",
1284 TO_UTF8( lineType ),
1286 aLine->GetStartPoint().x ).c_str(),
1288 aLine->GetStartPoint().y ).c_str(),
1290 aLine->GetEndPoint().x ).c_str(),
1292 aLine->GetEndPoint().y ).c_str() );
1293
1294 line_stroke.Format( m_out, schIUScale );
1296 m_out->Print( ")" );
1297}
1298
1299
1301{
1302 wxCHECK_RET( aText != nullptr && m_out != nullptr, "" );
1303
1304 // Note: label is nullptr SCH_TEXT, but not for SCH_LABEL_XXX,
1305 SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( aText );
1306
1307 m_out->Print( "(%s %s",
1308 getTextTypeToken( aText->Type() ),
1309 m_out->Quotew( aText->GetText() ).c_str() );
1310
1311 if( aText->Type() == SCH_TEXT_T )
1312 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aText->GetExcludedFromSim() );
1313
1314 if( aText->Type() == SCH_DIRECTIVE_LABEL_T )
1315 {
1316 SCH_DIRECTIVE_LABEL* flag = static_cast<SCH_DIRECTIVE_LABEL*>( aText );
1317
1318 m_out->Print( "(length %s)",
1320 flag->GetPinLength() ).c_str() );
1321 }
1322
1323 EDA_ANGLE angle = aText->GetTextAngle();
1324
1325 if( label )
1326 {
1327 if( label->Type() == SCH_GLOBAL_LABEL_T
1328 || label->Type() == SCH_HIER_LABEL_T
1329 || label->Type() == SCH_DIRECTIVE_LABEL_T )
1330 {
1331 m_out->Print( "(shape %s)", getSheetPinShapeToken( label->GetShape() ) );
1332 }
1333
1334 // The angle of the text is always 0 or 90 degrees for readibility reasons,
1335 // but the item itself can have more rotation (-90 and 180 deg)
1336 switch( label->GetSpinStyle() )
1337 {
1338 default:
1339 case SPIN_STYLE::LEFT: angle += ANGLE_180; break;
1340 case SPIN_STYLE::UP: break;
1341 case SPIN_STYLE::RIGHT: break;
1342 case SPIN_STYLE::BOTTOM: angle += ANGLE_180; break;
1343 }
1344 }
1345
1346 m_out->Print( "(at %s %s %s)",
1348 aText->GetPosition().x ).c_str(),
1350 aText->GetPosition().y ).c_str(),
1351 EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
1352
1353 if( label && !label->GetFields().empty() )
1354 {
1355 AUTOPLACE_ALGO fieldsAutoplaced = label->GetFieldsAutoplaced();
1356
1357 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1358 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1359 }
1360
1361 aText->EDA_TEXT::Format( m_out, 0 );
1363
1364 if( label )
1365 {
1366 for( SCH_FIELD& field : label->GetFields() )
1367 saveField( &field );
1368 }
1369
1370 m_out->Print( ")" ); // Closes text token.
1371}
1372
1373
1375{
1376 wxCHECK_RET( aTextBox != nullptr && m_out != nullptr, "" );
1377
1378 m_out->Print( "(%s %s",
1379 aTextBox->Type() == SCH_TABLECELL_T ? "table_cell" : "text_box",
1380 m_out->Quotew( aTextBox->GetText() ).c_str() );
1381
1382 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aTextBox->GetExcludedFromSim() );
1383
1384 VECTOR2I pos = aTextBox->GetStart();
1385 VECTOR2I size = aTextBox->GetEnd() - pos;
1386
1387 m_out->Print( "(at %s %s %s) (size %s %s) (margins %s %s %s %s)",
1390 EDA_UNIT_UTILS::FormatAngle( aTextBox->GetTextAngle() ).c_str(),
1397
1398 if( SCH_TABLECELL* cell = dynamic_cast<SCH_TABLECELL*>( aTextBox ) )
1399 m_out->Print( "(span %d %d)", cell->GetColSpan(), cell->GetRowSpan() );
1400
1401 if( aTextBox->Type() != SCH_TABLECELL_T )
1402 aTextBox->GetStroke().Format( m_out, schIUScale );
1403
1404 formatFill( m_out, aTextBox->GetFillMode(), aTextBox->GetFillColor() );
1405 aTextBox->EDA_TEXT::Format( m_out, 0 );
1407 m_out->Print( ")" );
1408}
1409
1410
1412{
1413 if( aTable->GetFlags() & SKIP_STRUCT )
1414 {
1415 aTable = static_cast<SCH_TABLE*>( aTable->Clone() );
1416
1417 int minCol = aTable->GetColCount();
1418 int maxCol = -1;
1419 int minRow = aTable->GetRowCount();
1420 int maxRow = -1;
1421
1422 for( int row = 0; row < aTable->GetRowCount(); ++row )
1423 {
1424 for( int col = 0; col < aTable->GetColCount(); ++col )
1425 {
1426 SCH_TABLECELL* cell = aTable->GetCell( row, col );
1427
1428 if( cell->IsSelected() )
1429 {
1430 minRow = std::min( minRow, row );
1431 maxRow = std::max( maxRow, row );
1432 minCol = std::min( minCol, col );
1433 maxCol = std::max( maxCol, col );
1434 }
1435 else
1436 {
1437 cell->SetFlags( STRUCT_DELETED );
1438 }
1439 }
1440 }
1441
1442 wxCHECK_MSG( maxCol >= minCol && maxRow >= minRow, /*void*/, wxT( "No selected cells!" ) );
1443
1444 int destRow = 0;
1445
1446 for( int row = minRow; row <= maxRow; row++ )
1447 aTable->SetRowHeight( destRow++, aTable->GetRowHeight( row ) );
1448
1449 int destCol = 0;
1450
1451 for( int col = minCol; col <= maxCol; col++ )
1452 aTable->SetColWidth( destCol++, aTable->GetColWidth( col ) );
1453
1454 aTable->DeleteMarkedCells();
1455 aTable->SetColCount( ( maxCol - minCol ) + 1 );
1456 }
1457
1458 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
1459
1460 m_out->Print( "(table (column_count %d)", aTable->GetColCount() );
1461
1462 m_out->Print( "(border" );
1463 KICAD_FORMAT::FormatBool( m_out, "external", aTable->StrokeExternal() );
1465
1466 if( aTable->StrokeExternal() || aTable->StrokeHeaderSeparator() )
1467 aTable->GetBorderStroke().Format( m_out, schIUScale );
1468
1469 m_out->Print( ")" ); // Close `border` token.
1470
1471 m_out->Print( "(separators" );
1472 KICAD_FORMAT::FormatBool( m_out, "rows", aTable->StrokeRows() );
1473 KICAD_FORMAT::FormatBool( m_out, "cols", aTable->StrokeColumns() );
1474
1475 if( aTable->StrokeRows() || aTable->StrokeColumns() )
1477
1478 m_out->Print( ")" ); // Close `separators` token.
1479
1480 m_out->Print( "(column_widths" );
1481
1482 for( int col = 0; col < aTable->GetColCount(); ++col )
1483 {
1484 m_out->Print( " %s",
1485 EDA_UNIT_UTILS::FormatInternalUnits( schIUScale, aTable->GetColWidth( col ) ).c_str() );
1486 }
1487
1488 m_out->Print( ")" );
1489
1490 m_out->Print( "(row_heights" );
1491
1492 for( int row = 0; row < aTable->GetRowCount(); ++row )
1493 {
1494 m_out->Print( " %s",
1495 EDA_UNIT_UTILS::FormatInternalUnits( schIUScale, aTable->GetRowHeight( row ) ).c_str() );
1496 }
1497
1498 m_out->Print( ")" );
1499
1501
1502 m_out->Print( "(cells" );
1503
1504 for( SCH_TABLECELL* cell : aTable->GetCells() )
1505 saveTextBox( cell );
1506
1507 m_out->Print( ")" ); // Close `cells` token.
1508 m_out->Print( ")" ); // Close `table` token.
1509
1510 if( aTable->GetFlags() & SKIP_STRUCT )
1511 delete aTable;
1512}
1513
1514
1516{
1517 // Don't write empty groups
1518 if( aGroup->GetItems().empty() )
1519 return;
1520
1521 m_out->Print( "(group %s", m_out->Quotew( aGroup->GetName() ).c_str() );
1522
1524
1525 if( aGroup->IsLocked() )
1526 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1527
1528 if( aGroup->HasDesignBlockLink() )
1529 m_out->Print( "(lib_id \"%s\")", aGroup->GetDesignBlockLibId().Format().c_str() );
1530
1531 wxArrayString memberIds;
1532
1533 for( EDA_ITEM* member : aGroup->GetItems() )
1534 memberIds.Add( member->m_Uuid.AsString() );
1535
1536 memberIds.Sort();
1537
1538 m_out->Print( "(members" );
1539
1540 for( const wxString& memberId : memberIds )
1541 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
1542
1543 m_out->Print( ")" ); // Close `members` token.
1544 m_out->Print( ")" ); // Close `group` token.
1545}
1546
1547
1548void SCH_IO_KICAD_SEXPR::saveInstances( const std::vector<SCH_SHEET_INSTANCE>& aInstances )
1549{
1550 if( aInstances.size() )
1551 {
1552 m_out->Print( "(sheet_instances" );
1553
1554 for( const SCH_SHEET_INSTANCE& instance : aInstances )
1555 {
1556 wxString path = instance.m_Path.AsString();
1557
1558 if( path.IsEmpty() )
1559 path = wxT( "/" ); // Root path
1560
1561 m_out->Print( "(path %s (page %s))",
1562 m_out->Quotew( path ).c_str(),
1563 m_out->Quotew( instance.m_PageNumber ).c_str() );
1564 }
1565
1566 m_out->Print( ")" ); // Close sheet instances token.
1567 }
1568}
1569
1570
1571void SCH_IO_KICAD_SEXPR::cacheLib( const wxString& aLibraryFileName,
1572 const std::map<std::string, UTF8>* aProperties )
1573{
1574 // Suppress font substitution warnings
1576
1577 if( !m_cache || !m_cache->IsFile( aLibraryFileName ) || m_cache->IsFileChanged() )
1578 {
1579 // a spectacular episode in memory management:
1580 delete m_cache;
1581 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryFileName );
1582
1583 if( !isBuffering( aProperties ) )
1584 m_cache->Load();
1585 }
1586}
1587
1588
1589bool SCH_IO_KICAD_SEXPR::isBuffering( const std::map<std::string, UTF8>* aProperties )
1590{
1591 return ( aProperties && aProperties->contains( SCH_IO_KICAD_SEXPR::PropBuffering ) );
1592}
1593
1594
1596{
1597 if( m_cache )
1598 return m_cache->GetModifyHash();
1599
1600 // If the cache hasn't been loaded, it hasn't been modified.
1601 return 0;
1602}
1603
1604
1605void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( wxArrayString& aSymbolNameList,
1606 const wxString& aLibraryPath,
1607 const std::map<std::string, UTF8>* aProperties )
1608{
1609 bool powerSymbolsOnly = ( aProperties && aProperties->contains( SYMBOL_LIB_TABLE::PropPowerSymsOnly ) );
1610
1611 cacheLib( aLibraryPath, aProperties );
1612
1613 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1614
1615 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1616 {
1617 if( !powerSymbolsOnly || it->second->IsPower() )
1618 aSymbolNameList.Add( it->first );
1619 }
1620}
1621
1622
1623void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
1624 const wxString& aLibraryPath,
1625 const std::map<std::string, UTF8>* aProperties )
1626{
1627 bool powerSymbolsOnly = ( aProperties && aProperties->contains( SYMBOL_LIB_TABLE::PropPowerSymsOnly ) );
1628
1629 cacheLib( aLibraryPath, aProperties );
1630
1631 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1632
1633 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1634 {
1635 if( !powerSymbolsOnly || it->second->IsPower() )
1636 aSymbolList.push_back( it->second );
1637 }
1638}
1639
1640
1641LIB_SYMBOL* SCH_IO_KICAD_SEXPR::LoadSymbol( const wxString& aLibraryPath,
1642 const wxString& aSymbolName,
1643 const std::map<std::string, UTF8>* aProperties )
1644{
1645 cacheLib( aLibraryPath, aProperties );
1646
1647 LIB_SYMBOL_MAP::const_iterator it = m_cache->m_symbols.find( aSymbolName );
1648
1649 // We no longer escape '/' in symbol names, but we used to.
1650 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( '/' ) )
1651 it = m_cache->m_symbols.find( EscapeString( aSymbolName, CTX_LEGACY_LIBID ) );
1652
1653 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( wxT( "{slash}" ) ) )
1654 {
1655 wxString unescaped = aSymbolName;
1656 unescaped.Replace( wxT( "{slash}" ), wxT( "/" ) );
1657 it = m_cache->m_symbols.find( unescaped );
1658 }
1659
1660 if( it == m_cache->m_symbols.end() )
1661 return nullptr;
1662
1663 return it->second;
1664}
1665
1666
1667void SCH_IO_KICAD_SEXPR::SaveSymbol( const wxString& aLibraryPath, const LIB_SYMBOL* aSymbol,
1668 const std::map<std::string, UTF8>* aProperties )
1669{
1670 cacheLib( aLibraryPath, aProperties );
1671
1672 m_cache->AddSymbol( aSymbol );
1673
1674 if( !isBuffering( aProperties ) )
1675 m_cache->Save();
1676}
1677
1678
1679void SCH_IO_KICAD_SEXPR::DeleteSymbol( const wxString& aLibraryPath, const wxString& aSymbolName,
1680 const std::map<std::string, UTF8>* aProperties )
1681{
1682 cacheLib( aLibraryPath, aProperties );
1683
1684 m_cache->DeleteSymbol( aSymbolName );
1685
1686 if( !isBuffering( aProperties ) )
1687 m_cache->Save();
1688}
1689
1690
1691void SCH_IO_KICAD_SEXPR::CreateLibrary( const wxString& aLibraryPath,
1692 const std::map<std::string, UTF8>* aProperties )
1693{
1694 if( wxFileExists( aLibraryPath ) )
1695 {
1696 THROW_IO_ERROR( wxString::Format( _( "Symbol library '%s' already exists." ),
1697 aLibraryPath.GetData() ) );
1698 }
1699
1700 delete m_cache;
1701 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
1702 m_cache->SetModified();
1703 m_cache->Save();
1704 m_cache->Load(); // update m_writable and m_timestamp
1705}
1706
1707
1708bool SCH_IO_KICAD_SEXPR::DeleteLibrary( const wxString& aLibraryPath,
1709 const std::map<std::string, UTF8>* aProperties )
1710{
1711 wxFileName fn = aLibraryPath;
1712
1713 if( !fn.FileExists() )
1714 return false;
1715
1716 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
1717 // we don't want that. we want bare metal portability with no UI here.
1718 if( wxRemove( aLibraryPath ) )
1719 {
1720 THROW_IO_ERROR( wxString::Format( _( "Symbol library '%s' cannot be deleted." ),
1721 aLibraryPath.GetData() ) );
1722 }
1723
1724 if( m_cache && m_cache->IsFile( aLibraryPath ) )
1725 {
1726 delete m_cache;
1727 m_cache = nullptr;
1728 }
1729
1730 return true;
1731}
1732
1733
1734void SCH_IO_KICAD_SEXPR::SaveLibrary( const wxString& aLibraryPath,
1735 const std::map<std::string, UTF8>* aProperties )
1736{
1737 if( !m_cache )
1738 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
1739
1740 wxString oldFileName = m_cache->GetFileName();
1741
1742 if( !m_cache->IsFile( aLibraryPath ) )
1743 m_cache->SetFileName( aLibraryPath );
1744
1745 // This is a forced save.
1746 m_cache->SetModified();
1747 m_cache->Save();
1748 m_cache->SetFileName( oldFileName );
1749}
1750
1751
1752bool SCH_IO_KICAD_SEXPR::CanReadLibrary( const wxString& aLibraryPath ) const
1753{
1754 if( !SCH_IO::CanReadLibrary( aLibraryPath ) )
1755 return false;
1756
1757 // Above just checks for proper extension; now check that it actually exists
1758
1759 wxFileName fn( aLibraryPath );
1760 return fn.IsOk() && fn.FileExists();
1761}
1762
1763
1764bool SCH_IO_KICAD_SEXPR::IsLibraryWritable( const wxString& aLibraryPath )
1765{
1766 wxFileName fn( aLibraryPath );
1767
1768 if( fn.FileExists() )
1769 return fn.IsFileWritable();
1770
1771 return fn.IsDirWritable();
1772}
1773
1774
1775void SCH_IO_KICAD_SEXPR::GetAvailableSymbolFields( std::vector<wxString>& aNames )
1776{
1777 if( !m_cache )
1778 return;
1779
1780 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1781
1782 std::set<wxString> fieldNames;
1783
1784 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1785 {
1786 std::vector<SCH_FIELD*> fields;
1787 it->second->GetFields( fields );
1788
1789 for( SCH_FIELD* field : fields )
1790 {
1791 if( field->IsMandatory() )
1792 continue;
1793
1794 // TODO(JE): enable configurability of this outside database libraries?
1795 // if( field->ShowInChooser() )
1796 fieldNames.insert( field->GetName() );
1797 }
1798 }
1799
1800 std::copy( fieldNames.begin(), fieldNames.end(), std::back_inserter( aNames ) );
1801}
1802
1803
1804void SCH_IO_KICAD_SEXPR::GetDefaultSymbolFields( std::vector<wxString>& aNames )
1805{
1806 GetAvailableSymbolFields( aNames );
1807}
1808
1809
1810std::vector<LIB_SYMBOL*> SCH_IO_KICAD_SEXPR::ParseLibSymbols( std::string& aSymbolText,
1811 std::string aSource,
1812 int aFileVersion )
1813{
1814 LIB_SYMBOL* newSymbol = nullptr;
1815 LIB_SYMBOL_MAP map;
1816
1817 std::vector<LIB_SYMBOL*> newSymbols;
1818 std::unique_ptr<STRING_LINE_READER> reader = std::make_unique<STRING_LINE_READER>( aSymbolText,
1819 aSource );
1820
1821 do
1822 {
1823 SCH_IO_KICAD_SEXPR_PARSER parser( reader.get() );
1824
1825 newSymbol = parser.ParseSymbol( map, aFileVersion );
1826
1827 if( newSymbol )
1828 newSymbols.emplace_back( newSymbol );
1829
1830 reader.reset( new STRING_LINE_READER( *reader ) );
1831 }
1832 while( newSymbol );
1833
1834 return newSymbols;
1835}
1836
1837
1839{
1840 SCH_IO_KICAD_SEXPR_LIB_CACHE::SaveSymbol( symbol, formatter );
1841}
1842
1843
1844const 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:185
void Rewind()
Rewind the file and resets the line number back to zero.
Definition richio.h:234
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:223
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:87
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition richio.h:93
An interface used to output 8 bit text in a convenient way.
Definition richio.h:322
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:162
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:156
SCH_SHEET & Root() const
Definition schematic.h:140
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:373
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:604
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:488
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:717
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:421
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:321
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:408
bool GetExcludedFromSim(const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString) const override
Definition sch_sheet.h:390
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:443
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:426
int GetBorderWidth() const
Definition sch_sheet.h:121
std::vector< SCH_SHEET_PIN * > & GetPins()
Definition sch_sheet.h:187
const std::vector< SCH_SHEET_INSTANCE > & GetInstances() const
Definition sch_sheet.h:458
KIGFX::COLOR4D GetBackgroundColor() const
Definition sch_sheet.h:127
Schematic symbol object.
Definition sch_symbol.h:75
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:630
const std::vector< SCH_SYMBOL_INSTANCE > & GetInstances() const
Definition sch_symbol.h:134
bool UseLibIdLookup() const
Definition sch_symbol.h:181
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:808
const LIB_ID & GetLibId() const override
Definition sch_symbol.h:164
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:235
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:253
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:206
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
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 FormatInternalUnits(const EDA_IU_SCALE &aIuScale, int aValue)
Converts aValue from internal units to a string appropriate for writing to file.
KICOMMON_API std::string FormatAngle(const EDA_ANGLE &aAngle)
Convert aAngle from board 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