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