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// 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 AUTOPLACE_ALGO fieldsAutoplaced = aSymbol->GetFieldsAutoplaced();
738
739 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
740 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
741
743
745
746 for( SCH_FIELD& field : aSymbol->GetFields() )
747 {
748 int id = field.GetId();
749 wxString value = field.GetText();
750
751 if( !aForClipboard && aSymbol->GetInstances().size() )
752 {
753 // The instance fields are always set to the default instance regardless of the
754 // sheet instance to prevent file churn.
755 if( id == REFERENCE_FIELD )
756 {
757 field.SetText( ordinalInstance.m_Reference );
758 }
759 else if( id == VALUE_FIELD )
760 {
761 field.SetText( aSymbol->GetField( VALUE_FIELD )->GetText() );
762 }
763 else if( id == FOOTPRINT_FIELD )
764 {
765 field.SetText( aSymbol->GetField( FOOTPRINT_FIELD )->GetText() );
766 }
767 }
768 else if( aForClipboard && aSymbol->GetInstances().size() && aRelativePath
769 && ( id == REFERENCE_FIELD ) )
770 {
771 SCH_SYMBOL_INSTANCE instance;
772
773 if( aSymbol->GetInstance( instance, aRelativePath->Path() ) )
774 field.SetText( instance.m_Reference );
775 }
776
777 try
778 {
779 saveField( &field );
780 }
781 catch( ... )
782 {
783 // Restore the changed field text on write error.
784 if( id == REFERENCE_FIELD || id == VALUE_FIELD || id == FOOTPRINT_FIELD )
785 field.SetText( value );
786
787 throw;
788 }
789
790 if( id == REFERENCE_FIELD || id == VALUE_FIELD || id == FOOTPRINT_FIELD )
791 field.SetText( value );
792 }
793
794 for( const std::unique_ptr<SCH_PIN>& pin : aSymbol->GetRawPins() )
795 {
796 if( pin->GetAlt().IsEmpty() )
797 {
798 m_out->Print( "(pin %s", m_out->Quotew( pin->GetNumber() ).c_str() );
800 m_out->Print( ")" );
801 }
802 else
803 {
804 m_out->Print( "(pin %s", m_out->Quotew( pin->GetNumber() ).c_str() );
806 m_out->Print( "(alternate %s))", m_out->Quotew( pin->GetAlt() ).c_str() );
807 }
808 }
809
810 if( !aSymbol->GetInstances().empty() )
811 {
812 std::map<KIID, std::vector<SCH_SYMBOL_INSTANCE>> projectInstances;
813
814 m_out->Print( "(instances" );
815
816 wxString projectName;
817 KIID rootSheetUuid = aSchematic.Root().m_Uuid;
818
819 for( const SCH_SYMBOL_INSTANCE& inst : aSymbol->GetInstances() )
820 {
821 // Zero length KIID_PATH objects are not valid and will cause a crash below.
822 wxCHECK2( inst.m_Path.size(), continue );
823
824 // If the instance data is part of this design but no longer has an associated sheet
825 // path, don't save it. This prevents large amounts of orphaned instance data for the
826 // current project from accumulating in the schematic files.
827 bool isOrphaned = ( inst.m_Path[0] == rootSheetUuid )
828 && !aSheetList.GetSheetPathByKIIDPath( inst.m_Path );
829
830 // Keep all instance data when copying to the clipboard. They may be needed on paste.
831 if( !aForClipboard && isOrphaned )
832 continue;
833
834 auto it = projectInstances.find( inst.m_Path[0] );
835
836 if( it == projectInstances.end() )
837 projectInstances[ inst.m_Path[0] ] = { inst };
838 else
839 it->second.emplace_back( inst );
840 }
841
842 for( auto& [uuid, instances] : projectInstances )
843 {
844 wxCHECK2( instances.size(), continue );
845
846 // Sort project instances by KIID_PATH.
847 std::sort( instances.begin(), instances.end(),
849 {
850 return aLhs.m_Path < aRhs.m_Path;
851 } );
852
853 projectName = instances[0].m_ProjectName;
854
855 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
856
857 for( const SCH_SYMBOL_INSTANCE& instance : instances )
858 {
859 wxString path;
860 KIID_PATH tmp = instance.m_Path;
861
862 if( aForClipboard && aRelativePath )
863 tmp.MakeRelativeTo( aRelativePath->Path() );
864
865 path = tmp.AsString();
866
867 m_out->Print( "(path %s (reference %s) (unit %d))",
868 m_out->Quotew( path ).c_str(),
869 m_out->Quotew( instance.m_Reference ).c_str(),
870 instance.m_Unit );
871 }
872
873 m_out->Print( ")" ); // Closes `project`.
874 }
875
876 m_out->Print( ")" ); // Closes `instances`.
877 }
878
879 m_out->Print( ")" ); // Closes `symbol`.
880}
881
882
884{
885 wxCHECK_RET( aField != nullptr && m_out != nullptr, "" );
886
887 wxString fieldName = aField->GetCanonicalName();
888 // For some reason (bug in legacy parser?) the field ID for non-mandatory fields is -1 so
889 // check for this in order to correctly use the field name.
890
891 if( aField->GetId() == -1 /* undefined ID */ )
892 {
893 // Replace the default name built by GetCanonicalName() by
894 // the field name if exists
895 if( !aField->GetName().IsEmpty() )
896 fieldName = aField->GetName();
897
898 aField->SetId( m_nextFreeFieldId );
900 }
901 else if( aField->GetId() >= m_nextFreeFieldId )
902 {
903 m_nextFreeFieldId = aField->GetId() + 1;
904 }
905
906 m_out->Print( "(property %s %s %s (at %s %s %s)",
907 aField->IsPrivate() ? "private" : "",
908 m_out->Quotew( fieldName ).c_str(),
909 m_out->Quotew( aField->GetText() ).c_str(),
911 aField->GetPosition().x ).c_str(),
913 aField->GetPosition().y ).c_str(),
914 EDA_UNIT_UTILS::FormatAngle( aField->GetTextAngle() ).c_str() );
915
916 if( aField->IsNameShown() )
917 KICAD_FORMAT::FormatBool( m_out, "show_name", true );
918
919 if( !aField->CanAutoplace() )
920 KICAD_FORMAT::FormatBool( m_out, "do_not_autoplace", true );
921
922 if( !aField->IsDefaultFormatting()
923 || ( aField->GetTextHeight() != schIUScale.MilsToIU( DEFAULT_SIZE_TEXT ) ) )
924 {
925 aField->Format( m_out, 0 );
926 }
927
928 m_out->Print( ")" ); // Closes `property` token
929}
930
931
933{
934 wxCHECK_RET( m_out != nullptr, "" );
935
936 const REFERENCE_IMAGE& refImage = aBitmap.GetReferenceImage();
937 const BITMAP_BASE& bitmapBase = refImage.GetImage();
938
939 const wxImage* image = bitmapBase.GetImageData();
940
941 wxCHECK_RET( image != nullptr, "wxImage* is NULL" );
942
943 m_out->Print( "(image (at %s %s)",
945 refImage.GetPosition().x ).c_str(),
947 refImage.GetPosition().y ).c_str() );
948
949 double scale = refImage.GetImageScale();
950
951 // 20230121 or older file format versions assumed 300 image PPI at load/save.
952 // Let's keep compatibility by changing image scale.
953 if( SEXPR_SCHEMATIC_FILE_VERSION <= 20230121 )
954 scale = scale * 300.0 / bitmapBase.GetPPI();
955
956 if( scale != 1.0 )
957 m_out->Print( "(scale %g)", scale );
958
960
961 m_out->Print( "(data" );
962
963 wxString out = wxBase64Encode( bitmapBase.GetImageDataBuffer() );
964
965 // Apparently the MIME standard character width for base64 encoding is 76 (unconfirmed)
966 // so use it in a vein attempt to be standard like.
967#define MIME_BASE64_LENGTH 76
968
969 size_t first = 0;
970
971 while( first < out.Length() )
972 {
973 m_out->Print( "\n\"%s\"", TO_UTF8( out( first, MIME_BASE64_LENGTH ) ) );
974 first += MIME_BASE64_LENGTH;
975 }
976
977 m_out->Print( ")" ); // Closes data token.
978 m_out->Print( ")" ); // Closes image token.
979}
980
981
983{
984 wxCHECK_RET( aSheet != nullptr && m_out != nullptr, "" );
985
986 m_out->Print( "(sheet (at %s %s) (size %s %s)",
988 aSheet->GetPosition().x ).c_str(),
990 aSheet->GetPosition().y ).c_str(),
992 aSheet->GetSize().x ).c_str(),
994 aSheet->GetSize().y ).c_str() );
995
996 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aSheet->GetExcludedFromSim() );
997 KICAD_FORMAT::FormatBool( m_out, "in_bom", !aSheet->GetExcludedFromBOM() );
998 KICAD_FORMAT::FormatBool( m_out, "on_board", !aSheet->GetExcludedFromBoard() );
999 KICAD_FORMAT::FormatBool( m_out, "dnp", aSheet->GetDNP() );
1000
1001 AUTOPLACE_ALGO fieldsAutoplaced = aSheet->GetFieldsAutoplaced();
1002
1003 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1004 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1005
1006 STROKE_PARAMS stroke( aSheet->GetBorderWidth(), LINE_STYLE::SOLID, aSheet->GetBorderColor() );
1007
1008 stroke.SetWidth( aSheet->GetBorderWidth() );
1009 stroke.Format( m_out, schIUScale );
1010
1011 m_out->Print( "(fill (color %d %d %d %0.4f))",
1012 KiROUND( aSheet->GetBackgroundColor().r * 255.0 ),
1013 KiROUND( aSheet->GetBackgroundColor().g * 255.0 ),
1014 KiROUND( aSheet->GetBackgroundColor().b * 255.0 ),
1015 aSheet->GetBackgroundColor().a );
1016
1018
1020
1021 for( SCH_FIELD& field : aSheet->GetFields() )
1022 saveField( &field );
1023
1024 for( const SCH_SHEET_PIN* pin : aSheet->GetPins() )
1025 {
1026 m_out->Print( "(pin %s %s (at %s %s %s)",
1027 EscapedUTF8( pin->GetText() ).c_str(),
1028 getSheetPinShapeToken( pin->GetShape() ),
1030 pin->GetPosition().x ).c_str(),
1032 pin->GetPosition().y ).c_str(),
1033 EDA_UNIT_UTILS::FormatAngle( getSheetPinAngle( pin->GetSide() ) ).c_str() );
1034
1036
1037 pin->Format( m_out, 0 );
1038
1039 m_out->Print( ")" ); // Closes pin token.
1040 }
1041
1042 // Save all sheet instances here except the root sheet instance.
1043 std::vector< SCH_SHEET_INSTANCE > sheetInstances = aSheet->GetInstances();
1044
1045 auto it = sheetInstances.begin();
1046
1047 while( it != sheetInstances.end() )
1048 {
1049 if( it->m_Path.size() == 0 )
1050 it = sheetInstances.erase( it );
1051 else
1052 it++;
1053 }
1054
1055 if( !sheetInstances.empty() )
1056 {
1057 m_out->Print( "(instances" );
1058
1059 KIID lastProjectUuid;
1060 KIID rootSheetUuid = m_schematic->Root().m_Uuid;
1061 bool inProjectClause = false;
1062
1063 for( size_t i = 0; i < sheetInstances.size(); i++ )
1064 {
1065 // If the instance data is part of this design but no longer has an associated sheet
1066 // path, don't save it. This prevents large amounts of orphaned instance data for the
1067 // current project from accumulating in the schematic files.
1068 //
1069 // Keep all instance data when copying to the clipboard. It may be needed on paste.
1070 if( ( sheetInstances[i].m_Path[0] == rootSheetUuid )
1071 && !aSheetList.GetSheetPathByKIIDPath( sheetInstances[i].m_Path, false ) )
1072 {
1073 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1074 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1075 {
1076 m_out->Print( ")" ); // Closes `project` token.
1077 inProjectClause = false;
1078 }
1079
1080 continue;
1081 }
1082
1083 if( lastProjectUuid != sheetInstances[i].m_Path[0] )
1084 {
1085 wxString projectName;
1086
1087 if( sheetInstances[i].m_Path[0] == rootSheetUuid )
1088 projectName = m_schematic->Prj().GetProjectName();
1089 else
1090 projectName = sheetInstances[i].m_ProjectName;
1091
1092 lastProjectUuid = sheetInstances[i].m_Path[0];
1093 m_out->Print( "(project %s", m_out->Quotew( projectName ).c_str() );
1094 inProjectClause = true;
1095 }
1096
1097 wxString path = sheetInstances[i].m_Path.AsString();
1098
1099 m_out->Print( "(path %s (page %s))",
1100 m_out->Quotew( path ).c_str(),
1101 m_out->Quotew( sheetInstances[i].m_PageNumber ).c_str() );
1102
1103 if( inProjectClause && ( ( i + 1 == sheetInstances.size() )
1104 || lastProjectUuid != sheetInstances[i+1].m_Path[0] ) )
1105 {
1106 m_out->Print( ")" ); // Closes `project` token.
1107 inProjectClause = false;
1108 }
1109 }
1110
1111 m_out->Print( ")" ); // Closes `instances` token.
1112 }
1113
1114 m_out->Print( ")" ); // Closes sheet token.
1115}
1116
1117
1119{
1120 wxCHECK_RET( aJunction != nullptr && m_out != nullptr, "" );
1121
1122 m_out->Print( "(junction (at %s %s) (diameter %s) (color %d %d %d %s)",
1124 aJunction->GetPosition().x ).c_str(),
1126 aJunction->GetPosition().y ).c_str(),
1128 aJunction->GetDiameter() ).c_str(),
1129 KiROUND( aJunction->GetColor().r * 255.0 ),
1130 KiROUND( aJunction->GetColor().g * 255.0 ),
1131 KiROUND( aJunction->GetColor().b * 255.0 ),
1132 FormatDouble2Str( aJunction->GetColor().a ).c_str() );
1133
1134 KICAD_FORMAT::FormatUuid( m_out, aJunction->m_Uuid );
1135 m_out->Print( ")" );
1136}
1137
1138
1140{
1141 wxCHECK_RET( aNoConnect != nullptr && m_out != nullptr, "" );
1142
1143 m_out->Print( "(no_connect (at %s %s)",
1145 aNoConnect->GetPosition().x ).c_str(),
1147 aNoConnect->GetPosition().y ).c_str() );
1148
1149 KICAD_FORMAT::FormatUuid( m_out, aNoConnect->m_Uuid );
1150 m_out->Print( ")" );
1151}
1152
1153
1155{
1156 wxCHECK_RET( aBusEntry != nullptr && m_out != nullptr, "" );
1157
1158 // Bus to bus entries are converted to bus line segments.
1159 if( aBusEntry->GetClass() == "SCH_BUS_BUS_ENTRY" )
1160 {
1161 SCH_LINE busEntryLine( aBusEntry->GetPosition(), LAYER_BUS );
1162
1163 busEntryLine.SetEndPoint( aBusEntry->GetEnd() );
1164 saveLine( &busEntryLine );
1165 return;
1166 }
1167
1168 m_out->Print( "(bus_entry (at %s %s) (size %s %s)",
1170 aBusEntry->GetPosition().x ).c_str(),
1172 aBusEntry->GetPosition().y ).c_str(),
1174 aBusEntry->GetSize().x ).c_str(),
1176 aBusEntry->GetSize().y ).c_str() );
1177
1178 aBusEntry->GetStroke().Format( m_out, schIUScale );
1179 KICAD_FORMAT::FormatUuid( m_out, aBusEntry->m_Uuid );
1180 m_out->Print( ")" );
1181}
1182
1183
1185{
1186 wxCHECK_RET( aShape != nullptr && m_out != nullptr, "" );
1187
1188 switch( aShape->GetShape() )
1189 {
1190 case SHAPE_T::ARC:
1191 formatArc( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1192 aShape->GetFillColor(), false, aShape->m_Uuid );
1193 break;
1194
1195 case SHAPE_T::CIRCLE:
1196 formatCircle( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1197 aShape->GetFillColor(), false, aShape->m_Uuid );
1198 break;
1199
1200 case SHAPE_T::RECTANGLE:
1201 formatRect( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1202 aShape->GetFillColor(), false, aShape->m_Uuid );
1203 break;
1204
1205 case SHAPE_T::BEZIER:
1206 formatBezier( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1207 aShape->GetFillColor(), false, aShape->m_Uuid );
1208 break;
1209
1210 case SHAPE_T::POLY:
1211 formatPoly( m_out, aShape, false, aShape->GetStroke(), aShape->GetFillMode(),
1212 aShape->GetFillColor(), false, aShape->m_Uuid );
1213 break;
1214
1215 default:
1217 }
1218}
1219
1220
1222{
1223 wxCHECK_RET( aRuleArea != nullptr && m_out != nullptr, "" );
1224
1225 m_out->Print( "(rule_area " );
1226 saveShape( aRuleArea );
1227 m_out->Print( ")" );
1228}
1229
1230
1232{
1233 wxCHECK_RET( aLine != nullptr && m_out != nullptr, "" );
1234
1235 wxString lineType;
1236
1237 STROKE_PARAMS line_stroke = aLine->GetStroke();
1238
1239 switch( aLine->GetLayer() )
1240 {
1241 case LAYER_BUS: lineType = "bus"; break;
1242 case LAYER_WIRE: lineType = "wire"; break;
1243 case LAYER_NOTES: lineType = "polyline"; break;
1244 default:
1245 UNIMPLEMENTED_FOR( LayerName( aLine->GetLayer() ) );
1246 }
1247
1248 m_out->Print( "(%s (pts (xy %s %s) (xy %s %s))",
1249 TO_UTF8( lineType ),
1251 aLine->GetStartPoint().x ).c_str(),
1253 aLine->GetStartPoint().y ).c_str(),
1255 aLine->GetEndPoint().x ).c_str(),
1257 aLine->GetEndPoint().y ).c_str() );
1258
1259 line_stroke.Format( m_out, schIUScale );
1261 m_out->Print( ")" );
1262}
1263
1264
1266{
1267 wxCHECK_RET( aText != nullptr && m_out != nullptr, "" );
1268
1269 // Note: label is nullptr SCH_TEXT, but not for SCH_LABEL_XXX,
1270 SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( aText );
1271
1272 m_out->Print( "(%s %s",
1273 getTextTypeToken( aText->Type() ),
1274 m_out->Quotew( aText->GetText() ).c_str() );
1275
1276 if( aText->Type() == SCH_TEXT_T )
1277 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aText->GetExcludedFromSim() );
1278
1279 if( aText->Type() == SCH_DIRECTIVE_LABEL_T )
1280 {
1281 SCH_DIRECTIVE_LABEL* flag = static_cast<SCH_DIRECTIVE_LABEL*>( aText );
1282
1283 m_out->Print( "(length %s)",
1285 flag->GetPinLength() ).c_str() );
1286 }
1287
1288 EDA_ANGLE angle = aText->GetTextAngle();
1289
1290 if( label )
1291 {
1292 if( label->Type() == SCH_GLOBAL_LABEL_T
1293 || label->Type() == SCH_HIER_LABEL_T
1294 || label->Type() == SCH_DIRECTIVE_LABEL_T )
1295 {
1296 m_out->Print( "(shape %s)", getSheetPinShapeToken( label->GetShape() ) );
1297 }
1298
1299 // The angle of the text is always 0 or 90 degrees for readibility reasons,
1300 // but the item itself can have more rotation (-90 and 180 deg)
1301 switch( label->GetSpinStyle() )
1302 {
1303 default:
1304 case SPIN_STYLE::LEFT: angle += ANGLE_180; break;
1305 case SPIN_STYLE::UP: break;
1306 case SPIN_STYLE::RIGHT: break;
1307 case SPIN_STYLE::BOTTOM: angle += ANGLE_180; break;
1308 }
1309 }
1310
1311 m_out->Print( "(at %s %s %s)",
1313 aText->GetPosition().x ).c_str(),
1315 aText->GetPosition().y ).c_str(),
1316 EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
1317
1318 if( label && !label->GetFields().empty() )
1319 {
1320 AUTOPLACE_ALGO fieldsAutoplaced = label->GetFieldsAutoplaced();
1321
1322 if( fieldsAutoplaced == AUTOPLACE_AUTO || fieldsAutoplaced == AUTOPLACE_MANUAL )
1323 KICAD_FORMAT::FormatBool( m_out, "fields_autoplaced", true );
1324 }
1325
1326 aText->EDA_TEXT::Format( m_out, 0 );
1328
1329 if( label )
1330 {
1331 for( SCH_FIELD& field : label->GetFields() )
1332 saveField( &field );
1333 }
1334
1335 m_out->Print( ")" ); // Closes text token.
1336}
1337
1338
1340{
1341 wxCHECK_RET( aTextBox != nullptr && m_out != nullptr, "" );
1342
1343 m_out->Print( "(%s %s",
1344 aTextBox->Type() == SCH_TABLECELL_T ? "table_cell" : "text_box",
1345 m_out->Quotew( aTextBox->GetText() ).c_str() );
1346
1347 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", aTextBox->GetExcludedFromSim() );
1348
1349 VECTOR2I pos = aTextBox->GetStart();
1350 VECTOR2I size = aTextBox->GetEnd() - pos;
1351
1352 m_out->Print( "(at %s %s %s) (size %s %s) (margins %s %s %s %s)",
1355 EDA_UNIT_UTILS::FormatAngle( aTextBox->GetTextAngle() ).c_str(),
1362
1363 if( SCH_TABLECELL* cell = dynamic_cast<SCH_TABLECELL*>( aTextBox ) )
1364 m_out->Print( "(span %d %d)", cell->GetColSpan(), cell->GetRowSpan() );
1365
1366 if( aTextBox->Type() != SCH_TABLECELL_T )
1367 aTextBox->GetStroke().Format( m_out, schIUScale );
1368
1369 formatFill( m_out, aTextBox->GetFillMode(), aTextBox->GetFillColor() );
1370 aTextBox->EDA_TEXT::Format( m_out, 0 );
1372 m_out->Print( ")" );
1373}
1374
1375
1377{
1378 if( aTable->GetFlags() & SKIP_STRUCT )
1379 {
1380 aTable = static_cast<SCH_TABLE*>( aTable->Clone() );
1381
1382 int minCol = aTable->GetColCount();
1383 int maxCol = -1;
1384 int minRow = aTable->GetRowCount();
1385 int maxRow = -1;
1386
1387 for( int row = 0; row < aTable->GetRowCount(); ++row )
1388 {
1389 for( int col = 0; col < aTable->GetColCount(); ++col )
1390 {
1391 SCH_TABLECELL* cell = aTable->GetCell( row, col );
1392
1393 if( cell->IsSelected() )
1394 {
1395 minRow = std::min( minRow, row );
1396 maxRow = std::max( maxRow, row );
1397 minCol = std::min( minCol, col );
1398 maxCol = std::max( maxCol, col );
1399 }
1400 else
1401 {
1402 cell->SetFlags( STRUCT_DELETED );
1403 }
1404 }
1405 }
1406
1407 wxCHECK_MSG( maxCol >= minCol && maxRow >= minRow, /*void*/, wxT( "No selected cells!" ) );
1408
1409 int destRow = 0;
1410
1411 for( int row = minRow; row <= maxRow; row++ )
1412 aTable->SetRowHeight( destRow++, aTable->GetRowHeight( row ) );
1413
1414 int destCol = 0;
1415
1416 for( int col = minCol; col <= maxCol; col++ )
1417 aTable->SetColWidth( destCol++, aTable->GetColWidth( col ) );
1418
1419 aTable->DeleteMarkedCells();
1420 aTable->SetColCount( ( maxCol - minCol ) + 1 );
1421 }
1422
1423 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
1424
1425 m_out->Print( "(table (column_count %d)", aTable->GetColCount() );
1426
1427 m_out->Print( "(border" );
1428 KICAD_FORMAT::FormatBool( m_out, "external", aTable->StrokeExternal() );
1429 KICAD_FORMAT::FormatBool( m_out, "header", aTable->StrokeHeader() );
1430
1431 if( aTable->StrokeExternal() || aTable->StrokeHeader() )
1432 aTable->GetBorderStroke().Format( m_out, schIUScale );
1433
1434 m_out->Print( ")" ); // Close `border` token.
1435
1436 m_out->Print( "(separators" );
1437 KICAD_FORMAT::FormatBool( m_out, "rows", aTable->StrokeRows() );
1438 KICAD_FORMAT::FormatBool( m_out, "cols", aTable->StrokeColumns() );
1439
1440 if( aTable->StrokeRows() || aTable->StrokeColumns() )
1442
1443 m_out->Print( ")" ); // Close `separators` token.
1444
1445 m_out->Print( "(column_widths" );
1446
1447 for( int col = 0; col < aTable->GetColCount(); ++col )
1448 {
1449 m_out->Print( " %s",
1451 aTable->GetColWidth( col ) ).c_str() );
1452 }
1453
1454 m_out->Print( ")" );
1455
1456 m_out->Print( "(row_heights" );
1457
1458 for( int row = 0; row < aTable->GetRowCount(); ++row )
1459 {
1460 m_out->Print( " %s",
1462 aTable->GetRowHeight( row ) ).c_str() );
1463 }
1464
1465 m_out->Print( ")" );
1466
1467 m_out->Print( "(cells" );
1468
1469 for( SCH_TABLECELL* cell : aTable->GetCells() )
1470 saveTextBox( cell );
1471
1472 m_out->Print( ")" ); // Close `cells` token.
1473 m_out->Print( ")" ); // Close `table` token.
1474
1475 if( aTable->GetFlags() & SKIP_STRUCT )
1476 delete aTable;
1477}
1478
1479
1480void SCH_IO_KICAD_SEXPR::saveBusAlias( std::shared_ptr<BUS_ALIAS> aAlias )
1481{
1482 wxCHECK_RET( aAlias != nullptr, "BUS_ALIAS* is NULL" );
1483
1484 wxString members;
1485
1486 for( const wxString& member : aAlias->Members() )
1487 {
1488 if( !members.IsEmpty() )
1489 members += wxS( " " );
1490
1491 members += m_out->Quotew( member );
1492 }
1493
1494 m_out->Print( "(bus_alias %s (members %s))",
1495 m_out->Quotew( aAlias->GetName() ).c_str(),
1496 TO_UTF8( members ) );
1497}
1498
1499
1500void SCH_IO_KICAD_SEXPR::saveInstances( const std::vector<SCH_SHEET_INSTANCE>& aInstances )
1501{
1502 if( aInstances.size() )
1503 {
1504 m_out->Print( "(sheet_instances" );
1505
1506 for( const SCH_SHEET_INSTANCE& instance : aInstances )
1507 {
1508 wxString path = instance.m_Path.AsString();
1509
1510 if( path.IsEmpty() )
1511 path = wxT( "/" ); // Root path
1512
1513 m_out->Print( "(path %s (page %s))",
1514 m_out->Quotew( path ).c_str(),
1515 m_out->Quotew( instance.m_PageNumber ).c_str() );
1516 }
1517
1518 m_out->Print( ")" ); // Close sheet instances token.
1519 }
1520}
1521
1522
1523void SCH_IO_KICAD_SEXPR::cacheLib( const wxString& aLibraryFileName,
1524 const std::map<std::string, UTF8>* aProperties )
1525{
1526 // Suppress font substitution warnings
1528
1529 if( !m_cache || !m_cache->IsFile( aLibraryFileName ) || m_cache->IsFileChanged() )
1530 {
1531 // a spectacular episode in memory management:
1532 delete m_cache;
1533 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryFileName );
1534
1535 if( !isBuffering( aProperties ) )
1536 m_cache->Load();
1537 }
1538}
1539
1540
1541bool SCH_IO_KICAD_SEXPR::isBuffering( const std::map<std::string, UTF8>* aProperties )
1542{
1543 return ( aProperties && aProperties->contains( SCH_IO_KICAD_SEXPR::PropBuffering ) );
1544}
1545
1546
1548{
1549 if( m_cache )
1550 return m_cache->GetModifyHash();
1551
1552 // If the cache hasn't been loaded, it hasn't been modified.
1553 return 0;
1554}
1555
1556
1557void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( wxArrayString& aSymbolNameList,
1558 const wxString& aLibraryPath,
1559 const std::map<std::string, UTF8>* aProperties )
1560{
1561 LOCALE_IO toggle; // toggles on, then off, the C locale.
1562
1563 bool powerSymbolsOnly = ( aProperties &&
1564 aProperties->find( SYMBOL_LIB_TABLE::PropPowerSymsOnly ) != aProperties->end() );
1565
1566 cacheLib( aLibraryPath, aProperties );
1567
1568 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1569
1570 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1571 {
1572 if( !powerSymbolsOnly || it->second->IsPower() )
1573 aSymbolNameList.Add( it->first );
1574 }
1575}
1576
1577
1578void SCH_IO_KICAD_SEXPR::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
1579 const wxString& aLibraryPath,
1580 const std::map<std::string, UTF8>* aProperties )
1581{
1582 LOCALE_IO toggle; // toggles on, then off, the C locale.
1583
1584 bool powerSymbolsOnly = ( aProperties &&
1585 aProperties->find( SYMBOL_LIB_TABLE::PropPowerSymsOnly ) != aProperties->end() );
1586
1587 cacheLib( aLibraryPath, aProperties );
1588
1589 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1590
1591 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1592 {
1593 if( !powerSymbolsOnly || it->second->IsPower() )
1594 aSymbolList.push_back( it->second );
1595 }
1596}
1597
1598
1599LIB_SYMBOL* SCH_IO_KICAD_SEXPR::LoadSymbol( const wxString& aLibraryPath,
1600 const wxString& aSymbolName,
1601 const std::map<std::string, UTF8>* aProperties )
1602{
1603 LOCALE_IO toggle; // toggles on, then off, the C locale.
1604
1605 cacheLib( aLibraryPath, aProperties );
1606
1607 LIB_SYMBOL_MAP::const_iterator it = m_cache->m_symbols.find( aSymbolName );
1608
1609 // We no longer escape '/' in symbol names, but we used to.
1610 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( '/' ) )
1611 it = m_cache->m_symbols.find( EscapeString( aSymbolName, CTX_LEGACY_LIBID ) );
1612
1613 if( it == m_cache->m_symbols.end() && aSymbolName.Contains( wxT( "{slash}" ) ) )
1614 {
1615 wxString unescaped = aSymbolName;
1616 unescaped.Replace( wxT( "{slash}" ), wxT( "/" ) );
1617 it = m_cache->m_symbols.find( unescaped );
1618 }
1619
1620 if( it == m_cache->m_symbols.end() )
1621 return nullptr;
1622
1623 return it->second;
1624}
1625
1626
1627void SCH_IO_KICAD_SEXPR::SaveSymbol( const wxString& aLibraryPath, const LIB_SYMBOL* aSymbol,
1628 const std::map<std::string, UTF8>* aProperties )
1629{
1630 LOCALE_IO toggle; // toggles on, then off, the C locale.
1631
1632 cacheLib( aLibraryPath, aProperties );
1633
1634 m_cache->AddSymbol( aSymbol );
1635
1636 if( !isBuffering( aProperties ) )
1637 m_cache->Save();
1638}
1639
1640
1641void SCH_IO_KICAD_SEXPR::DeleteSymbol( const wxString& aLibraryPath, const wxString& aSymbolName,
1642 const std::map<std::string, UTF8>* aProperties )
1643{
1644 LOCALE_IO toggle; // toggles on, then off, the C locale.
1645
1646 cacheLib( aLibraryPath, aProperties );
1647
1648 m_cache->DeleteSymbol( aSymbolName );
1649
1650 if( !isBuffering( aProperties ) )
1651 m_cache->Save();
1652}
1653
1654
1655void SCH_IO_KICAD_SEXPR::CreateLibrary( const wxString& aLibraryPath,
1656 const std::map<std::string, UTF8>* aProperties )
1657{
1658 if( wxFileExists( aLibraryPath ) )
1659 {
1660 THROW_IO_ERROR( wxString::Format( _( "Symbol library '%s' already exists." ),
1661 aLibraryPath.GetData() ) );
1662 }
1663
1664 LOCALE_IO toggle;
1665
1666 delete m_cache;
1667 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
1669 m_cache->Save();
1670 m_cache->Load(); // update m_writable and m_mod_time
1671}
1672
1673
1674bool SCH_IO_KICAD_SEXPR::DeleteLibrary( const wxString& aLibraryPath,
1675 const std::map<std::string, UTF8>* aProperties )
1676{
1677 wxFileName fn = aLibraryPath;
1678
1679 if( !fn.FileExists() )
1680 return false;
1681
1682 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
1683 // we don't want that. we want bare metal portability with no UI here.
1684 if( wxRemove( aLibraryPath ) )
1685 {
1686 THROW_IO_ERROR( wxString::Format( _( "Symbol library '%s' cannot be deleted." ),
1687 aLibraryPath.GetData() ) );
1688 }
1689
1690 if( m_cache && m_cache->IsFile( aLibraryPath ) )
1691 {
1692 delete m_cache;
1693 m_cache = nullptr;
1694 }
1695
1696 return true;
1697}
1698
1699
1700void SCH_IO_KICAD_SEXPR::SaveLibrary( const wxString& aLibraryPath,
1701 const std::map<std::string, UTF8>* aProperties )
1702{
1703 if( !m_cache )
1704 m_cache = new SCH_IO_KICAD_SEXPR_LIB_CACHE( aLibraryPath );
1705
1706 wxString oldFileName = m_cache->GetFileName();
1707
1708 if( !m_cache->IsFile( aLibraryPath ) )
1709 {
1710 m_cache->SetFileName( aLibraryPath );
1711 }
1712
1713 // This is a forced save.
1715 m_cache->Save();
1716 m_cache->SetFileName( oldFileName );
1717}
1718
1719
1720bool SCH_IO_KICAD_SEXPR::IsLibraryWritable( const wxString& aLibraryPath )
1721{
1722 wxFileName fn( aLibraryPath );
1723
1724 if( fn.FileExists() )
1725 return fn.IsFileWritable();
1726
1727 return fn.IsDirWritable();
1728}
1729
1730
1731void SCH_IO_KICAD_SEXPR::GetAvailableSymbolFields( std::vector<wxString>& aNames )
1732{
1733 if( !m_cache )
1734 return;
1735
1736 const LIB_SYMBOL_MAP& symbols = m_cache->m_symbols;
1737
1738 std::set<wxString> fieldNames;
1739
1740 for( LIB_SYMBOL_MAP::const_iterator it = symbols.begin(); it != symbols.end(); ++it )
1741 {
1742 std::vector<SCH_FIELD*> fields;
1743 it->second->GetFields( fields );
1744
1745 for( SCH_FIELD* field : fields )
1746 {
1747 if( field->IsMandatory() )
1748 continue;
1749
1750 // TODO(JE): enable configurability of this outside database libraries?
1751 // if( field->ShowInChooser() )
1752 fieldNames.insert( field->GetName() );
1753 }
1754 }
1755
1756 std::copy( fieldNames.begin(), fieldNames.end(), std::back_inserter( aNames ) );
1757}
1758
1759
1760void SCH_IO_KICAD_SEXPR::GetDefaultSymbolFields( std::vector<wxString>& aNames )
1761{
1762 GetAvailableSymbolFields( aNames );
1763}
1764
1765
1766std::vector<LIB_SYMBOL*> SCH_IO_KICAD_SEXPR::ParseLibSymbols( std::string& aSymbolText,
1767 std::string aSource,
1768 int aFileVersion )
1769{
1770 LOCALE_IO toggle; // toggles on, then off, the C locale.
1771 LIB_SYMBOL* newSymbol = nullptr;
1772 LIB_SYMBOL_MAP map;
1773
1774 std::vector<LIB_SYMBOL*> newSymbols;
1775 std::unique_ptr<STRING_LINE_READER> reader = std::make_unique<STRING_LINE_READER>( aSymbolText,
1776 aSource );
1777
1778 do
1779 {
1780 SCH_IO_KICAD_SEXPR_PARSER parser( reader.get() );
1781
1782 newSymbol = parser.ParseSymbol( map, aFileVersion );
1783
1784 if( newSymbol )
1785 newSymbols.emplace_back( newSymbol );
1786
1787 reader.reset( new STRING_LINE_READER( *reader ) );
1788 }
1789 while( newSymbol );
1790
1791 return newSymbols;
1792}
1793
1794
1796{
1797
1798 LOCALE_IO toggle; // toggles on, then off, the C locale.
1799 SCH_IO_KICAD_SEXPR_LIB_CACHE::SaveSymbol( symbol, formatter );
1800}
1801
1802
1803const 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:490
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:254
bool IsDefaultFormatting() const
Definition: eda_text.cpp:1037
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:1052
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()
Remove 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:246
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition: io_base.h:226
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:311
wxString AsString() const
Definition: kiid.cpp:356
Definition: kiid.h:49
UTF8 Format() const
Definition: lib_id.cpp:118
Define a library symbol object.
Definition: lib_symbol.h:84
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:545
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition: richio.cpp:460
void Format(OUTPUTFORMATTER *aFormatter) const
Output the page class to aFormatter in s-expression form.
Definition: page_info.cpp:275
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:146
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition: project.cpp:158
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:82
void EmbedFonts() override
Embed fonts in the schematic.
Definition: schematic.cpp:921
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:876
bool IsValid() const
A simple test if the schematic is loaded, not a complete one.
Definition: schematic.h:146
SCH_SHEET & Root() const
Definition: schematic.h:130
PROJECT & Prj() const override
Return a reference to the project this schematic is part of.
Definition: schematic.h:97
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:1485
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:1252
int GetId() const
Definition: sch_field.h:133
wxString GetName(bool aUseDefaultName=true) const
Return the field name (not translated).
Definition: sch_field.cpp:1227
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:167
int GetBodyStyle() const
Definition: sch_item.h:233
bool IsPrivate() const
Definition: sch_item.h:236
SCH_LAYER_ID GetLayer() const
Return the layer this item is on.
Definition: sch_item.h:282
AUTOPLACE_ALGO GetFieldsAutoplaced() const
Return whether the fields have been automatically placed.
Definition: sch_item.h:549
wxString GetClass() const override
Return the class name.
Definition: sch_item.h:177
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:331
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:189
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:375
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition: sch_sheet.h:305
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:92
bool GetExcludedFromBoard() const
Definition: sch_sheet.h:381
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:111
SCH_SCREEN * GetScreen() const
Definition: sch_sheet.h:109
VECTOR2I GetPosition() const override
Definition: sch_sheet.h:399
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
Definition: sch_sheet.cpp:172
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:117
bool GetExcludedFromSim() const override
Definition: sch_sheet.h:369
int GetBorderWidth() const
Definition: sch_sheet.h:114
std::vector< SCH_SHEET_PIN * > & GetPins()
Definition: sch_sheet.h:180
const std::vector< SCH_SHEET_INSTANCE > & GetInstances() const
Definition: sch_sheet.h:419
bool GetDNP() const
Set or clear the 'Do Not Populate' flaga.
Definition: sch_sheet.h:386
KIGFX::COLOR4D GetBackgroundColor() const
Definition: sch_sheet.h:120
Schematic symbol object.
Definition: sch_symbol.h:77
std::vector< std::unique_ptr< SCH_PIN > > & GetRawPins()
Definition: sch_symbol.h:644
const std::vector< SCH_SYMBOL_INSTANCE > & GetInstances() const
Definition: sch_symbol.h:136
bool UseLibIdLookup() const
Definition: sch_symbol.h:183
wxString GetSchSymbolLibraryName() const
Definition: sch_symbol.cpp:241
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) override
Populate a std::vector with SCH_FIELDs.
Definition: sch_symbol.cpp:953
SCH_FIELD * GetField(MANDATORY_FIELD_T aFieldType)
Return a mandatory field in this symbol.
Definition: sch_symbol.cpp:905
VECTOR2I GetPosition() const override
Definition: sch_symbol.h:774
const LIB_ID & GetLibId() const override
Definition: sch_symbol.h:166
bool GetInstance(SCH_SYMBOL_INSTANCE &aInstance, const KIID_PATH &aSheetPath, bool aTestFromEnd=false) const
Definition: sch_symbol.cpp:551
int GetOrientation() const override
Get the display symbol orientation.
wxString GetPrefix() const
Definition: sch_symbol.h:251
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:93
void SetWidth(int aWidth)
void Format(OUTPUTFORMATTER *out, const EDA_IU_SCALE &aIuScale) const
static const char * PropPowerSymsOnly
bool GetExcludedFromBoard() const
Definition: symbol.h:181
bool GetExcludedFromBOM() const
Definition: symbol.h:175
bool GetDNP() const
Set or clear the 'Do Not Populate' flag.
Definition: symbol.h:186
bool GetExcludedFromSim() const override
Definition: symbol.h:169
virtual void Format(OUTPUTFORMATTER *aFormatter) const
Output the object to aFormatter in s-expression form.
Definition: title_block.cpp:31
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:404
@ LAYER_NOTES
Definition: layer_ids.h:419
@ LAYER_BUS
Definition: layer_ids.h:405
#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:170
KICOMMON_API std::string FormatAngle(const EDA_ANGLE &aAngle)
Convert aAngle from board units to a string appropriate for writing to file.
Definition: eda_units.cpp:162
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.
AUTOPLACE_ALGO
Definition: sch_item.h:68
@ AUTOPLACE_MANUAL
Definition: sch_item.h:71
@ AUTOPLACE_AUTO
Definition: sch_item.h:70
@ 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
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.
@ 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
@ 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