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