KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_io_altium.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 Thomas Pointhuber <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <algorithm>
22#include <map>
23#include <memory>
24#include <optional>
25#include <set>
26
27#include "altium_parser_sch.h"
28#include <io/io_utils.h>
34
35#include <progress_reporter.h>
36#include <schematic.h>
37#include <project_sch.h>
41
42#include <lib_id.h>
43#include <sch_pin.h>
44#include <sch_bitmap.h>
45#include <sch_bus_entry.h>
46#include <connection_graph.h>
47#include <sch_connection.h>
48#include <sch_symbol.h>
49#include <sch_junction.h>
50#include <sch_line.h>
51#include <sch_shape.h>
52#include <sch_no_connect.h>
53#include <sch_screen.h>
54#include <sch_label.h>
55#include <sch_sheet.h>
56#include <sch_sheet_pin.h>
57#include <sch_textbox.h>
58
59#include <bezier_curves.h>
60#include <compoundfilereader.h>
61#include <font/fontconfig.h>
62#include <reporter.h>
63#include <geometry/ellipse.h>
65#include <string_utils.h>
66#include <sch_edit_frame.h>
68#include <wx/log.h>
69#include <wx/dir.h>
70#include <wx/mstream.h>
71#include <wx/zstream.h>
72#include <wx/wfstream.h>
73#include <magic_enum.hpp>
74#include "sch_io_altium.h"
75
76
77// Harness port object itself does not contain color information about itself
78// It seems altium is drawing harness ports using these colors
79#define HARNESS_PORT_COLOR_DEFAULT_BACKGROUND COLOR4D( 0.92941176470588238, \
80 0.94901960784313721, \
81 0.98431372549019602, 1.0 )
82
83#define HARNESS_PORT_COLOR_DEFAULT_OUTLINE COLOR4D( 0.56078431372549020, \
84 0.61960784313725492, \
85 0.78823529411764703, 1.0 )
86
87
88// Pure label/name transforms shared with the QA suite; see AltiumWrapBusLabel and
89// AltiumDeriveSheetName below.
90wxString AltiumWrapBusLabel( const wxString& aText );
91wxString AltiumDeriveSheetName( const wxString& aFilename, const std::set<wxString>& aExistingNames );
92
93
94// Normalized parse-stack key so a cycle through a dotted relative or differently-cased path
95// still matches
96static wxString AltiumParseKey( const wxFileName& aFileName )
97{
98 wxFileName fn = aFileName;
99 fn.Normalize( wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS | wxPATH_NORM_TILDE | wxPATH_NORM_CASE );
100 return fn.GetFullPath();
101}
102
103
104// Ref-counted RAII entry in m_parsingFiles so a block holds every sibling member open and a
105// member cross-referencing a sibling or itself reads as recursion
107{
108 PARSE_FILE_GUARD( SCH_IO_ALTIUM* aOwner, const wxString& aKey ) :
109 PARSE_FILE_GUARD( aOwner, std::vector<wxString>{ aKey } )
110 {
111 }
112
113 PARSE_FILE_GUARD( SCH_IO_ALTIUM* aOwner, std::vector<wxString> aKeys ) :
114 m_owner( aOwner ), m_keys( std::move( aKeys ) )
115 {
116 for( const wxString& key : m_keys )
117 m_owner->m_parsingFiles[key]++;
118 }
119
121 {
122 for( const wxString& key : m_keys )
123 {
124 auto it = m_owner->m_parsingFiles.find( key );
125
126 if( it != m_owner->m_parsingFiles.end() && --it->second <= 0 )
127 m_owner->m_parsingFiles.erase( it );
128 }
129 }
130
133
135 std::vector<wxString> m_keys;
136};
137
138
139static const VECTOR2I GetRelativePosition( const VECTOR2I& aPosition, const SCH_SYMBOL* aSymbol )
140{
141 TRANSFORM t = aSymbol->GetTransform().InverseTransform();
142 return t.TransformCoordinate( aPosition - aSymbol->GetPosition() );
143}
144
145
146static COLOR4D GetColorFromInt( int color )
147{
148 int red = color & 0x0000FF;
149 int green = ( color & 0x00FF00 ) >> 8;
150 int blue = ( color & 0xFF0000 ) >> 16;
151
152 return COLOR4D().FromCSSRGBA( red, green, blue, 1.0 );
153}
154
155
167
168
169static void SetSchShapeLine( const ASCH_BORDER_INTERFACE& elem, SCH_SHAPE* shape )
170{
172 GetColorFromInt( elem.Color ) ) );
173}
174
175static void SetSchShapeFillAndColor( const ASCH_FILL_INTERFACE& elem, SCH_SHAPE* shape )
176{
177
178 if( !elem.IsSolid )
179 {
181 }
182 else
183 {
185 shape->SetFillColor( GetColorFromInt( elem.AreaColor ) );
186 }
187
188 // Fixup small circles that had their widths set to 0
189 if( shape->GetShape() == SHAPE_T::CIRCLE && shape->GetStroke().GetWidth() == 0
190 && shape->GetRadius() <= schIUScale.MilsToIU( 10 ) )
191 {
193 }
194}
195
196
197static void SetLibShapeLine( const ASCH_BORDER_INTERFACE& elem, SCH_SHAPE* shape,
198 ALTIUM_SCH_RECORD aType )
199{
200 COLOR4D default_color;
201 COLOR4D alt_default_color = COLOR4D( PUREBLUE ); // PUREBLUE is used for many objects, so if
202 // it is used, we will assume that it should
203 // blend with the others
204 STROKE_PARAMS stroke;
205 stroke.SetColor( GetColorFromInt( elem.Color ) );
207
208 switch( aType )
209 {
210 case ALTIUM_SCH_RECORD::ARC: default_color = COLOR4D( PUREBLUE ); break;
211 case ALTIUM_SCH_RECORD::BEZIER: default_color = COLOR4D( PURERED ); break;
212 case ALTIUM_SCH_RECORD::ELLIPSE: default_color = COLOR4D( PUREBLUE ); break;
213 case ALTIUM_SCH_RECORD::ELLIPTICAL_ARC: default_color = COLOR4D( PUREBLUE ); break;
214 case ALTIUM_SCH_RECORD::LINE: default_color = COLOR4D( PUREBLUE ); break;
215 case ALTIUM_SCH_RECORD::POLYGON: default_color = COLOR4D( PUREBLUE ); break;
216 case ALTIUM_SCH_RECORD::POLYLINE: default_color = COLOR4D( BLACK ); break;
217 case ALTIUM_SCH_RECORD::RECTANGLE: default_color = COLOR4D( 0.5, 0, 0, 1.0 ); break;
218 case ALTIUM_SCH_RECORD::ROUND_RECTANGLE: default_color = COLOR4D( PUREBLUE ); break;
219 default: default_color = COLOR4D( PUREBLUE ); break;
220 }
221
222 if( stroke.GetColor() == default_color || stroke.GetColor() == alt_default_color )
224
225 // In Altium libraries, you cannot change the width of the pins. So, to match pin width,
226 // if the line width of other elements is the default pin width (10 mil), we set the width
227 // to the KiCad default pin width ( represented by 0 )
228 if( elem.LineWidth == 2540 )
229 stroke.SetWidth( 0 );
230 else
231 stroke.SetWidth( elem.LineWidth );
232
233 shape->SetStroke( stroke );
234}
235
237 ALTIUM_SCH_RECORD aType, int aStrokeColor )
238{
239 COLOR4D bgcolor = GetColorFromInt( elem.AreaColor );
240 COLOR4D default_bgcolor;
241
242 switch (aType)
243 {
245 default_bgcolor = GetColorFromInt( 11599871 ); // Light Yellow
246 break;
247 default:
248 default_bgcolor = GetColorFromInt( 12632256 ); // Grey
249 break;
250 }
251
252 if( elem.IsTransparent )
253 bgcolor = bgcolor.WithAlpha( 0.5 );
254
255 if( !elem.IsSolid )
256 {
258 }
259 else if( elem.AreaColor == aStrokeColor )
260 {
261 bgcolor = shape->GetStroke().GetColor();
262
264 }
265 else if( bgcolor.WithAlpha( 1.0 ) == default_bgcolor )
266 {
268 }
269 else
270 {
272 }
273
274 shape->SetFillColor( bgcolor );
275
276 if( elem.AreaColor == aStrokeColor
277 && shape->GetStroke().GetWidth() == schIUScale.MilsToIU( 1 ) )
278 {
279 STROKE_PARAMS stroke = shape->GetStroke();
280 stroke.SetWidth( -1 );
281 shape->SetStroke( stroke );
282 }
283
284 // Fixup small circles that had their widths set to 0
285 if( shape->GetShape() == SHAPE_T::CIRCLE && shape->GetStroke().GetWidth() == 0
286 && shape->GetRadius() <= schIUScale.MilsToIU( 10 ) )
287 {
289 }
290}
291
292
294 SCH_IO( wxS( "Altium" ) )
295{
296 m_isIntLib = false;
297 m_rootSheet = nullptr;
298 m_schematic = nullptr;
301
303}
304
305
307{
308 for( auto& [libName, lib] : m_libCache )
309 {
310 for( auto& [name, symbol] : lib )
311 delete symbol;
312 }
313}
314
315
317{
318 return 0;
319}
320
321
322bool SCH_IO_ALTIUM::isBinaryFile( const wxString& aFileName )
323{
324 // Compound File Binary Format header
326}
327
328
329bool SCH_IO_ALTIUM::isASCIIFile( const wxString& aFileName )
330{
331 // ASCII file format
332 return IO_UTILS::fileStartsWithPrefix( aFileName, wxS( "|HEADER=" ), false );
333}
334
335
336bool SCH_IO_ALTIUM::checkFileHeader( const wxString& aFileName )
337{
338 return isBinaryFile( aFileName ) || isASCIIFile( aFileName );
339}
340
341
342bool SCH_IO_ALTIUM::CanReadSchematicFile( const wxString& aFileName ) const
343{
344 if( !SCH_IO::CanReadSchematicFile( aFileName ) )
345 return false;
346
347 return checkFileHeader( aFileName );
348}
349
350
351bool SCH_IO_ALTIUM::CanReadLibrary( const wxString& aFileName ) const
352{
353 if( !SCH_IO::CanReadLibrary( aFileName ) )
354 return false;
355
356 return checkFileHeader( aFileName );
357}
358
359
361{
362 std::vector<SCH_PIN*> pins;
363
364 if( aSymbol->Type() == SCH_SYMBOL_T )
365 pins = static_cast<SCH_SYMBOL*>( aSymbol )->GetPins( nullptr );
366 else if( aSymbol->Type() == LIB_SYMBOL_T )
367 pins = static_cast<LIB_SYMBOL*>( aSymbol )->GetGraphicalPins( 0, 0 );
368
369
370 bool names_visible = false;
371 bool numbers_visible = false;
372
373 for( SCH_PIN* pin : pins )
374 {
375 if( pin->GetNameTextSize() > 0 && !pin->GetName().empty() )
376 names_visible = true;
377
378 if( pin->GetNumberTextSize() > 0 && !pin->GetNumber().empty() )
379 numbers_visible = true;
380 }
381
382 if( !names_visible )
383 {
384 for( SCH_PIN* pin : pins )
385 pin->SetNameTextSize( schIUScale.MilsToIU( DEFAULT_PINNAME_SIZE ) );
386
387 aSymbol->SetShowPinNames( false );
388 }
389
390 if( !numbers_visible )
391 {
392 for( SCH_PIN* pin : pins )
393 pin->SetNumberTextSize( schIUScale.MilsToIU( DEFAULT_PINNUM_SIZE ) );
394
395 aSymbol->SetShowPinNumbers( false );
396 }
397}
398
399
401{
402 if( m_libName.IsEmpty() )
403 {
404 // Try to come up with a meaningful name
405 m_libName = m_schematic->Project().GetProjectName();
406
407 if( m_libName.IsEmpty() )
408 {
409 wxFileName fn( m_rootSheet->GetFileName() );
410 m_libName = fn.GetName();
411 }
412
413 if( m_libName.IsEmpty() )
414 m_libName = "noname";
415
416 m_libName += "-altium-import";
418 }
419
420 return m_libName;
421}
422
423
425{
426 wxFileName fn( m_schematic->Project().GetProjectPath(), getLibName(),
428
429 return fn;
430}
431
432
433SCH_SHEET* SCH_IO_ALTIUM::LoadSchematicProject( SCHEMATIC* aSchematic, const std::map<std::string, UTF8>* aProperties )
434{
435 int x = 1;
436 int y = 1;
437 int page = 1;
438
439 std::map<wxString, SCH_SHEET*> sheets;
440 wxFileName project( aProperties->at( "project_file" ) );
441
442 for( auto& [key, filestring] : *aProperties )
443 {
444 if( key.starts_with( "sch" ) )
445 m_projectDocuments.emplace_back( filestring );
446 }
447
448 for( auto& [ key, filestring] : *aProperties )
449 {
450 if( !key.starts_with( "sch" ) )
451 continue;
452
453 wxFileName fn( filestring );
454
455 // Check if this file was already loaded as a subsheet of another sheet.
456 // This can happen when the project file lists sheets in an order where a parent
457 // sheet is processed before its subsheets. We need to handle potential case
458 // differences in filenames (e.g., LVDS.SCHDOC vs LVDS.SchDoc).
459 // The sources are compared, as a sheet file can take a suffix its source does not have
460 if( std::ranges::any_of( m_parsedFiles,
461 [&]( const wxString& aParsed )
462 {
463 return aParsed.IsSameAs( AltiumParseKey( fn ), false );
464 } ) )
465 {
466 continue;
467 }
468
469 VECTOR2I pos = VECTOR2I( x * schIUScale.MilsToIU( 1000 ),
470 y * schIUScale.MilsToIU( 1000 ) );
471
472 std::unique_ptr<SCH_SHEET> sheet = std::make_unique<SCH_SHEET>( m_rootSheet, pos );
473 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
474 sheet->SetScreen( screen );
475
476 // The file uuid becomes the top-level sheet uuid on load, so instance paths must start with it
477 sheet->SyncUuidToScreen();
478
479 wxFileName kicad_fn( claimSheetFile( fn.GetName() ) );
480
481 // Sheet uses relative filename, screen uses full path
482 sheet->SetFileName( kicad_fn.GetFullName() );
483 screen->SetFileName( kicad_fn.GetFullPath() );
484
485 wxCHECK2( sheet && screen, continue );
486
487 wxString pageNo = wxString::Format( wxT( "%d" ), page++ );
488
489 m_sheetPath.push_back( sheet.get() );
490
491 // Parse from the original Altium file location
492 ParseAltiumSch( fn.GetFullPath() );
493
494 // A parent read later shows this screen rather than a second copy, so the cleanup below finds both
495 m_loadedScreens.emplace( std::vector<wxString>{ AltiumParseKey( fn ) }, screen );
496
497 // Sheets created here won't have names set by ParseSheetName (which only applies
498 // to sheet symbols within a parent). Derive a name from the Altium filename.
499 if( sheet->GetName().Trim().empty() )
500 {
501 std::set<wxString> existingNames;
502
503 for( auto& [path, existing] : sheets )
504 existingNames.insert( existing->GetName() );
505
506 sheet->SetName( AltiumDeriveSheetName( fn.GetFullPath(), existingNames ) );
507 }
508
509 m_sheetPath.SetPageNumber( pageNo );
510 m_sheetPath.pop_back();
511
512 SCH_SCREEN* currentScreen = m_rootSheet->GetScreen();
513
514 wxCHECK2( currentScreen, continue );
515
516 sheet->SetParent( m_sheetPath.Last() );
517 SCH_SHEET* sheetPtr = sheet.release();
518 currentScreen->Append( sheetPtr );
519
520 sheets[AltiumParseKey( fn ).Lower()] = sheetPtr;
521
522 x += 2;
523
524 if( x > 10 ) // Start next row of sheets.
525 {
526 x = 1;
527 y += 2;
528 }
529 }
530
531 // If any of the sheets in the project is a subsheet, then remove the sheet from the root sheet.
532 // The root sheet only contains sheets that are not referenced by any other sheet in a
533 // pseudo-flat structure.
534 for( auto& [ sourceKey, sheet ] : sheets )
535 {
536 if( m_subsheetFiles.contains( sourceKey ) )
537 getCurrentScreen()->Remove( sheet );
538 }
539
540 return m_rootSheet;
541}
542
543
544SCH_SHEET* SCH_IO_ALTIUM::LoadSchematicFile( const wxString& aFileName, SCHEMATIC* aSchematic,
545 SCH_SHEET* aAppendToMe,
546 const std::map<std::string, UTF8>* aProperties )
547{
548 wxCHECK( ( !aFileName.IsEmpty() || !aProperties->empty() ) && aSchematic, nullptr );
549
550 wxFileName fileName( aFileName );
551 fileName.SetExt( FILEEXT::KiCadSchematicFileExtension );
552 m_schematic = aSchematic;
553
554 // Importer may be reused so reset per-import state or freed pointers leak into the new hierarchy
555 m_parsingFiles.clear();
556 m_loadedScreens.clear();
557 m_missingScreens.clear();
558 m_projectDocuments.clear();
559 m_sheetFiles.clear();
560 m_parsedFiles.clear();
561 m_subsheetFiles.clear();
562 m_rootSheetFile.clear();
563 m_sheetSpecialStrings.clear();
564 m_unsetSheetParams.clear();
565 m_sheets.clear();
567 m_rootFilepath.clear();
568
569 // The root, or the first sheet of a project, is saved as the project's schematic
570 if( !m_schematic->Project().GetProjectName().IsEmpty() )
571 {
572 m_rootSheetFile = wxFileName( m_schematic->Project().GetProjectPath(), m_schematic->Project().GetProjectName(),
574 }
575
576 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
578
579 // Delete on exception, if I own m_rootSheet, according to aAppendToMe
580 std::unique_ptr<SCH_SHEET> deleter( aAppendToMe ? nullptr : m_rootSheet );
581
582 if( aAppendToMe )
583 {
584 wxCHECK_MSG( aSchematic->IsValid(), nullptr, "Can't append to a schematic with no root!" );
585 m_rootSheet = aAppendToMe;
586
587 // The appended sheets must not take a file the host schematic already saves to
588 SCH_SCREENS hostScreens( aSchematic->Root() );
589
590 for( SCH_SCREEN* screen = hostScreens.GetFirst(); screen; screen = hostScreens.GetNext() )
591 {
592 wxFileName saved( screen->GetFileName() );
594 m_sheetFiles.insert( saved.GetFullPath().Lower() );
595 }
596 }
597 else
598 {
599 m_rootSheet = new SCH_SHEET( aSchematic );
600 m_rootSheet->SetFileName( fileName.GetFullPath() );
601
602 // For project imports (empty filename), the root sheet becomes the virtual root
603 // container. Don't call SetTopLevelSheets yet - that will happen after
604 // LoadSchematicProject populates the sheet hierarchy.
605 if( aFileName.empty() )
606 {
607 const_cast<KIID&>( m_rootSheet->m_Uuid ) = niluuid;
608 }
609 else
610 {
611 // For single-file imports, set as top-level sheet immediately and assign
612 // a placeholder page number that will be updated if we find a pageNumber record.
613 aSchematic->SetTopLevelSheets( { m_rootSheet } );
614
615 SCH_SHEET_PATH sheetpath;
616 sheetpath.push_back( m_rootSheet );
617 sheetpath.SetPageNumber( "#" );
618 }
619 }
620
621 if( !m_rootSheet->GetScreen() )
622 {
623 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
624 screen->SetFileName( aFileName );
625 m_rootSheet->SetScreen( screen );
626
627 // For single-file import, use the screen's UUID for the root sheet
628 if( !aFileName.empty() )
629 m_rootSheet->SyncUuidToScreen();
630 }
631
632 m_sheetPath.push_back( m_rootSheet );
633
634 SCH_SCREEN* rootScreen = m_rootSheet->GetScreen();
635 wxCHECK( rootScreen, nullptr );
636
637 SCH_SHEET_INSTANCE sheetInstance;
638
639 sheetInstance.m_Path = m_sheetPath.Path();
640 sheetInstance.m_PageNumber = wxT( "#" );
641
642 rootScreen->m_sheetInstances.emplace_back( sheetInstance );
643
644 if( aFileName.empty() )
645 LoadSchematicProject( aSchematic, aProperties );
646 else
647 ParseAltiumSch( aFileName );
648
649 if( aFileName.empty() )
650 {
651 std::vector<SCH_SHEET*> topLevelSheets;
652
653 for( SCH_ITEM* item : rootScreen->Items().OfType( SCH_SHEET_T ) )
654 {
655 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
656
657 // Skip the temporary root sheet itself if it somehow ended up in its own screen
658 if( sheet != m_rootSheet )
659 topLevelSheets.push_back( sheet );
660 }
661
662 // Remove sheets from the temporary root screen before transferring ownership
663 // to the schematic. Otherwise the screen destructor will delete them.
664 for( SCH_SHEET* sheet : topLevelSheets )
665 rootScreen->Remove( sheet );
666
667 if( !topLevelSheets.empty() )
668 aSchematic->SetTopLevelSheets( topLevelSheets );
669
670 // Convert hierarchical labels to global labels on top-level sheets.
671 // Top-level sheets have no parent, so hierarchical labels don't make sense.
672 for( SCH_SHEET* sheet : topLevelSheets )
673 {
674 SCH_SCREEN* screen = sheet->GetScreen();
675
676 if( !screen )
677 continue;
678
679 std::vector<SCH_HIERLABEL*> hierLabels;
680
681 for( SCH_ITEM* item : screen->Items().OfType( SCH_HIER_LABEL_T ) )
682 hierLabels.push_back( static_cast<SCH_HIERLABEL*>( item ) );
683
684 for( SCH_HIERLABEL* hierLabel : hierLabels )
685 {
686 SCH_GLOBALLABEL* globalLabel = new SCH_GLOBALLABEL( hierLabel->GetPosition(),
687 hierLabel->GetText() );
688 globalLabel->SetShape( hierLabel->GetShape() );
689 globalLabel->SetSpinStyle( hierLabel->GetSpinStyle() );
690 globalLabel->GetField( FIELD_T::INTERSHEET_REFS )->SetVisible( false );
691
692 screen->Remove( hierLabel );
693 screen->Append( globalLabel );
694 delete hierLabel;
695 }
696 }
697
698 m_rootSheet = &aSchematic->Root();
699 }
700
701 if( !aAppendToMe )
703
704 if( m_reporter )
705 {
706 for( auto& [msg, severity] : m_errorMessages )
707 m_reporter->Report( msg, severity );
708 }
709
710 m_errorMessages.clear();
711
712 if( aProperties && aProperties->count( "project_file" ) )
713 {
715 ParseAltiumProjectParameters( aProperties->at( "project_file" ) ) );
716 }
717
718 // anything still undefined has no value, which Altium shows as nothing, and a sheet parameter that
719 // Altium leaves as "*" is undefined unless the project gives it a value
720 for( const wxString& name : m_sheetSpecialStrings )
721 m_schematic->Project().GetTextVars().emplace( name, wxString() );
722
723 for( const wxString& name : m_unsetSheetParams )
724 m_schematic->Project().GetTextVars().emplace( name, wxString() );
725
726 SCH_SCREENS allSheets( m_rootSheet );
727
728 // a Comment naming a parameter the component lacks shows empty in Altium
729 std::map<SCH_SYMBOL*, bool> resolves;
730
732 {
733 SCH_SCREEN* screen = path.LastScreen();
734
735 if( !screen )
736 continue;
737
738 for( SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
739 {
740 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
741 const wxString& text = symbol->GetField( FIELD_T::VALUE )->GetText();
742
743 // only a Comment that is nothing but one variable reference
744 if( !text.StartsWith( wxS( "${" ) ) || !text.EndsWith( wxS( "}" ) )
745 || text.find( '}', 2 ) != text.length() - 1 || text.find( wxS( "${" ), 2 ) != wxString::npos )
746 {
747 continue;
748 }
749
750 wxString name = text.Mid( 2, text.length() - 3 );
751 bool known = m_schematic->Project().GetTextVars().count( name ) > 0;
752
753 for( const SCH_FIELD& field : symbol->GetFields() )
754 known |= field.GetName().IsSameAs( name, false );
755
756 known |= symbol->ResolveTextVar( &path, &name, wxEmptyString );
757 resolves[symbol] |= known;
758 }
759 }
760
761 for( const auto& [symbol, known] : resolves )
762 {
763 if( !known )
764 symbol->GetField( FIELD_T::VALUE )->SetText( wxEmptyString );
765 }
766
767 // symbols carry their own definitions, so a library that lacks them is not an error worth reporting
768 allSheets.UpdateSymbolLinks();
769 allSheets.ClearEditFlags();
770
771 // Apply Altium project variants to schematic symbols
772 if( aProperties && aProperties->count( "project_file" ) )
773 {
774 const wxString& projectFile = aProperties->at( "project_file" );
775
776 auto variants = ParseAltiumProjectVariants( projectFile );
777
778 if( !variants.empty() )
779 {
780 // Build lookups keyed by both UniqueId and designator. UniqueId is preferred
781 // because repeated-channel designs can have multiple components sharing a
782 // designator but with distinct UniqueIds.
783 using ENTRY_LIST =
784 std::vector<std::pair<wxString, const ALTIUM_VARIANT_ENTRY*>>;
785
786 std::map<wxString, ENTRY_LIST> variantsByUid;
787 std::map<wxString, ENTRY_LIST> variantsByDesignator;
788
789 for( const ALTIUM_PROJECT_VARIANT& pv : variants )
790 {
791 m_schematic->AddVariant( pv.name );
792
793 if( !pv.description.empty() && pv.description != pv.name )
794 m_schematic->SetVariantDescription( pv.name, pv.description );
795
796 for( const ALTIUM_VARIANT_ENTRY& entry : pv.variations )
797 {
798 if( !entry.uniqueId.empty() )
799 variantsByUid[entry.uniqueId].push_back( { pv.name, &entry } );
800
801 variantsByDesignator[entry.designator].push_back( { pv.name, &entry } );
802 }
803 }
804
805 SCH_SHEET_LIST sheetList( m_rootSheet );
806
807 for( const SCH_SHEET_PATH& path : sheetList )
808 {
809 SCH_SCREEN* screen = path.LastScreen();
810
811 if( !screen )
812 continue;
813
814 for( SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
815 {
816 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
817
818 ENTRY_LIST applicable;
819
820 const ENTRY_LIST* uidEntries = nullptr;
821 auto symUidIt = m_altiumSymbolToUid.find( symbol );
822
823 if( symUidIt != m_altiumSymbolToUid.end() )
824 {
825 auto varIt = variantsByUid.find( symUidIt->second );
826
827 if( varIt != variantsByUid.end() )
828 uidEntries = &varIt->second;
829 }
830
831 if( uidEntries && uidEntries->size() == 1 )
832 {
833 applicable = *uidEntries;
834 }
835 else if( uidEntries )
836 {
837 // A unique id shared by several variations (repeated channels) is
838 // ambiguous; disambiguate with the per-channel designator.
839 wxString ref = symbol->GetRef( &path );
840
841 for( const auto& namedEntry : *uidEntries )
842 {
843 if( namedEntry.second->designator == ref )
844 applicable.push_back( namedEntry );
845 }
846 }
847 else
848 {
849 wxString ref = symbol->GetRef( &path );
850 auto varIt = variantsByDesignator.find( ref );
851
852 if( varIt != variantsByDesignator.end() )
853 applicable = varIt->second;
854 }
855
856 if( applicable.empty() )
857 continue;
858
859 for( const auto& [variantName, entry] : applicable )
860 {
861 SCH_SYMBOL_VARIANT variant( variantName );
862 variant.InitializeAttributes( *symbol );
863
864 if( entry->kind == 1 )
865 {
866 variant.m_DNP = true;
867 variant.m_ExcludedFromBOM = true;
868 variant.m_ExcludedFromPosFiles = true;
869 }
870 else if( entry->kind == 0 )
871 {
872 for( const auto& [key, value] : entry->alternateFields )
873 {
874 if( key.CmpNoCase( wxS( "LibReference" ) ) == 0 )
875 variant.m_Fields[wxS( "Value" )] = value;
876 else if( key.CmpNoCase( wxS( "Description" ) ) == 0 )
877 variant.m_Fields[wxS( "Description" )] = value;
878 else if( key.CmpNoCase( wxS( "Footprint" ) ) == 0 )
879 variant.m_Fields[wxS( "Footprint" )] = value;
880 }
881 }
882
883 symbol->AddVariant( path, variant );
884 }
885 }
886 }
887 }
888 }
889
890 if( aProperties && aProperties->count( "project_file" )
891 && !AltiumPowerPortNamesTakePriority( aProperties->at( "project_file" ) ) )
892 {
894 }
895
896 // Set up the default netclass wire & bus width based on imported wires & buses.
897 //
898
899 int minWireWidth = std::numeric_limits<int>::max();
900 int minBusWidth = std::numeric_limits<int>::max();
901
902 for( SCH_SCREEN* screen = allSheets.GetFirst(); screen != nullptr; screen = allSheets.GetNext() )
903 {
904 std::vector<SCH_MARKER*> markers;
905
906 for( SCH_ITEM* item : screen->Items().OfType( SCH_LINE_T ) )
907 {
908 SCH_LINE* line = static_cast<SCH_LINE*>( item );
909
910 if( line->IsWire() && line->GetLineWidth() > 0 )
911 minWireWidth = std::min( minWireWidth, line->GetLineWidth() );
912
913 if( line->IsBus() && line->GetLineWidth() > 0 )
914 minBusWidth = std::min( minBusWidth, line->GetLineWidth() );
915 }
916 }
917
918 std::shared_ptr<NET_SETTINGS>& netSettings = m_schematic->Project().GetProjectFile().NetSettings();
919
920 if( minWireWidth < std::numeric_limits<int>::max() )
921 netSettings->GetDefaultNetclass()->SetWireWidth( minWireWidth );
922
923 if( minBusWidth < std::numeric_limits<int>::max() )
924 netSettings->GetDefaultNetclass()->SetBusWidth( minBusWidth );
925
926 return m_rootSheet;
927}
928
929
931{
932 return m_sheetPath.LastScreen();
933}
934
935
940
941
943{
944 SCH_SCREEN* screen = getCurrentScreen();
945 wxCHECK( screen, /* void */ );
946
947 std::vector<SCH_LINE*> busLines;
948 std::map<VECTOR2I, std::vector<SCH_LINE*>> busLineMap;
949
950 for( SCH_ITEM* elem : screen->Items().OfType( SCH_LINE_T) )
951 {
952 SCH_LINE* line = static_cast<SCH_LINE*>( elem );
953
954 if( line->IsBus() )
955 {
956 busLines.push_back( line );
957 busLineMap[ line->GetStartPoint() ].push_back( line );
958 busLineMap[ line->GetEndPoint() ].push_back( line );
959 }
960 }
961
962 std::function<SCH_LABEL*(VECTOR2I, std::set<SCH_LINE*>&)> walkBusLine =
963 [&]( const VECTOR2I& aStart, std::set<SCH_LINE*>& aVisited ) -> SCH_LABEL*
964 {
965 auto it = busLineMap.find( aStart );
966
967 if( it == busLineMap.end() )
968 return nullptr;
969
970 for( SCH_LINE* line : it->second )
971 {
972 // Skip lines we've already checked to avoid cycles
973 if( aVisited.count( line ) )
974 continue;
975
976 aVisited.insert( line );
977
978 for( SCH_ITEM* elem : screen->Items().Overlapping( SCH_LABEL_T, line->GetBoundingBox() ) )
979 {
980 SCH_LABEL* label = static_cast<SCH_LABEL*>( elem );
981
982 if( line->HitTest( label->GetPosition() ) )
983 return label;
984 }
985
986 SCH_LABEL* result = walkBusLine( KIGEOM::GetOtherEnd( line->GetSeg(), aStart ), aVisited );
987
988 if( result )
989 return result;
990 }
991
992 return nullptr;
993 };
994
995 for( auto& [_, harness] : m_altiumHarnesses )
996 {
997 std::shared_ptr<BUS_ALIAS> alias = std::make_shared<BUS_ALIAS>();
998 alias->SetName( harness.m_name );
999
1000 for( HARNESS::HARNESS_PORT& port : harness.m_ports )
1001 alias->AddMember( port.m_name );
1002
1003 screen->AddBusAlias( alias );
1004
1005 VECTOR2I pos;
1006 BOX2I box( harness.m_location, harness.m_size );
1007 SCH_LINE* busLine = nullptr;
1008
1009 for( SCH_ITEM* elem : screen->Items().Overlapping( SCH_LINE_T, box ) )
1010 {
1011 SCH_LINE* line = static_cast<SCH_LINE*>( elem );
1012
1013 if( !line->IsBus() )
1014 continue;
1015
1016 busLine = line;
1017
1018 for( const VECTOR2I& pt : line->GetConnectionPoints() )
1019 {
1020 if( box.Contains( pt ) )
1021 {
1022 pos = pt;
1023 break;
1024 }
1025 }
1026 }
1027
1028 if( !busLine )
1029 {
1030 for( SCH_ITEM* elem : screen->Items().Overlapping( SCH_HIER_LABEL_T, box ) )
1031 {
1032 SCH_HIERLABEL* label = static_cast<SCH_HIERLABEL*>( elem );
1033
1034 pos = label->GetPosition();
1035 VECTOR2I center = box.GetCenter();
1036 int delta_x = center.x - pos.x;
1037 int delta_y = center.y - pos.y;
1038
1039 if( std::abs( delta_x ) > std::abs( delta_y ) )
1040 {
1041 busLine = new SCH_LINE( pos, SCH_LAYER_ID::LAYER_BUS );
1042 busLine->SetEndPoint( VECTOR2I( center.x, pos.y ) );
1043 busLine->SetFlags( IS_NEW );
1044 screen->Append( busLine );
1045 }
1046 else
1047 {
1048 busLine = new SCH_LINE( pos, SCH_LAYER_ID::LAYER_BUS );
1049 busLine->SetEndPoint( VECTOR2I( pos.x, center.y ) );
1050 busLine->SetFlags( IS_NEW );
1051 screen->Append( busLine );
1052 }
1053
1054 break;
1055 }
1056 }
1057
1058 if( !busLine )
1059 continue;
1060
1061 std::set<SCH_LINE*> visited;
1062 SCH_LABEL* label = walkBusLine( pos, visited );
1063
1064 // Altium supports two different naming conventions for harnesses. If there is a specific
1065 // harness name, then the nets inside the harness will be named harnessname.netname.
1066 // However, if there is no harness name, the nets will be named just netname.
1067
1068 // KiCad bus labels need some special handling to be recognized as bus labels
1069 if( label && !label->GetText().StartsWith( wxT( "{" ) ) )
1070 label->SetText( label->GetText() + wxT( "{" ) + harness.m_name + wxT( "}" ) );
1071
1072 if( !label )
1073 {
1074 label = new SCH_LABEL( busLine->GetStartPoint(), wxT( "{" ) + harness.m_name + wxT( "}" ) );
1076
1077 if( busLine->GetEndPoint().x < busLine->GetStartPoint().x )
1079 else
1081
1082 screen->Append( label );
1083 }
1084
1085 if( harness.m_ports.empty() )
1086 continue;
1087
1088 // Draw the bus line from the individual ports to the harness
1089
1090 bool isVertical = true;
1091
1092 if( harness.m_ports.size() > 1 )
1093 {
1094 VECTOR2I first = harness.m_ports.front().m_location;
1095 VECTOR2I last = harness.m_ports.back().m_location;
1096
1097 if( first.y == last.y )
1098 isVertical = false;
1099 }
1100
1101 if( isVertical )
1102 {
1103 VECTOR2I bottom = harness.m_ports.front().m_entryLocation;
1104 VECTOR2I top = harness.m_ports.front().m_entryLocation;
1105 int delta_space = EDA_UNIT_UTILS::Mils2IU( schIUScale, 100 );
1106
1107 for( HARNESS::HARNESS_PORT& port : harness.m_ports )
1108 {
1109 if( port.m_entryLocation.y > bottom.y )
1110 bottom = port.m_entryLocation;
1111
1112 if( port.m_entryLocation.y < top.y )
1113 top = port.m_entryLocation;
1114 }
1115
1116 VECTOR2I last_pt;
1117 SCH_LINE* line = new SCH_LINE( bottom, SCH_LAYER_ID::LAYER_BUS );
1118 line->SetStartPoint( bottom );
1119 line->SetEndPoint( top );
1120 line->SetLineWidth( busLine->GetLineWidth() );
1121 line->SetLineColor( busLine->GetLineColor() );
1122 screen->Append( line );
1123
1124 last_pt = ( busLine->GetStartPoint() - line->GetEndPoint() ).SquaredEuclideanNorm() <
1125 ( busLine->GetStartPoint() - line->GetStartPoint() ).SquaredEuclideanNorm()
1126 ? line->GetEndPoint()
1127 : line->GetStartPoint();
1128
1129 // If the busline is not on the save y coordinate as the bus/wire connectors, add a short
1130 // hop to bring the bus down to the level of the connectors
1131 if( last_pt.y != busLine->GetStartPoint().y )
1132 {
1133 line = new SCH_LINE( last_pt, SCH_LAYER_ID::LAYER_BUS );
1134 line->SetStartPoint( last_pt );
1135
1136 if( alg::signbit( busLine->GetStartPoint().x - last_pt.x ) )
1137 line->SetEndPoint( last_pt + VECTOR2I( -delta_space, 0 ) );
1138 else
1139 line->SetEndPoint( last_pt + VECTOR2I( delta_space, 0 ) );
1140
1141 line->SetLineWidth( busLine->GetLineWidth() );
1142 line->SetLineColor( busLine->GetLineColor() );
1143 screen->Append( line );
1144 last_pt = line->GetEndPoint();
1145
1146 line = new SCH_LINE( last_pt, SCH_LAYER_ID::LAYER_BUS );
1147 line->SetStartPoint( last_pt );
1148 line->SetEndPoint( last_pt + VECTOR2I( 0, busLine->GetStartPoint().y - last_pt.y ) );
1149 line->SetLineWidth( busLine->GetLineWidth() );
1150 line->SetLineColor( busLine->GetLineColor() );
1151 screen->Append( line );
1152 last_pt = line->GetEndPoint();
1153 }
1154
1155 line = new SCH_LINE( last_pt, SCH_LAYER_ID::LAYER_BUS );
1156 line->SetStartPoint( last_pt );
1157 line->SetEndPoint( busLine->GetStartPoint() );
1158 line->SetLineWidth( busLine->GetLineWidth() );
1159 line->SetLineColor( busLine->GetLineColor() );
1160 screen->Append( line );
1161 }
1162 }
1163}
1164
1165
1166wxString AltiumWrapBusLabel( const wxString& aText )
1167{
1168 // Altium marks bus membership by geometry alone (a scalar label placed on a bus line);
1169 // KiCad needs the same label expressed as a single-member bus group to make the
1170 // connection. Already-formatted bus labels are left untouched.
1171 if( SCH_CONNECTION::IsBusLabel( aText ) )
1172 return aText;
1173
1174 // Spaces and commas separate members inside a bus group, so a multi-word net name would
1175 // otherwise fan out into several members. Quote such names so the bus-group reader in
1176 // NET_SETTINGS::ParseBusGroup keeps the whole name as a single member.
1177 if( aText.Contains( wxT( " " ) ) || aText.Contains( wxT( "," ) ) )
1178 return wxT( "{\"" ) + EscapeString( aText, CTX_QUOTED_STR ) + wxT( "\"}" );
1179
1180 return wxT( "{" ) + aText + wxT( "}" );
1181}
1182
1183
1184wxString AltiumDeriveSheetName( const wxString& aFilename, const std::set<wxString>& aExistingNames )
1185{
1186 wxString baseName = wxFileName( aFilename ).GetName();
1187 baseName.Replace( wxT( "/" ), wxT( "_" ) );
1188
1189 if( baseName.Trim().empty() )
1190 baseName = wxT( "Sheet" );
1191
1192 wxString sheetName = baseName;
1193
1194 for( int ii = 1; aExistingNames.count( sheetName ); ++ii )
1195 sheetName = baseName + wxString::Format( wxT( "_%d" ), ii );
1196
1197 return sheetName;
1198}
1199
1200
1202{
1203 SCH_SCREEN* screen = getCurrentScreen();
1204 wxCHECK( screen, /* void */ );
1205
1206 bool hasBusLines = false;
1207
1208 for( SCH_ITEM* item : screen->Items().OfType( SCH_LINE_T ) )
1209 {
1210 SCH_LINE* line = static_cast<SCH_LINE*>( item );
1211
1212 if( line->IsBus() )
1213 {
1214 hasBusLines = true;
1215 break;
1216 }
1217 }
1218
1219 if( !hasBusLines )
1220 return;
1221
1222 // Collect labels that need wrapping, then modify them after iteration to avoid
1223 // modifying the R-tree during traversal.
1224 std::vector<SCH_LABEL*> labelsToWrap;
1225
1226 for( SCH_ITEM* item : screen->Items().OfType( SCH_LABEL_T ) )
1227 {
1228 SCH_LABEL* label = static_cast<SCH_LABEL*>( item );
1229
1230 if( SCH_CONNECTION::IsBusLabel( label->GetText() ) )
1231 continue;
1232
1233 for( SCH_ITEM* busItem : screen->Items().Overlapping( SCH_LINE_T, label->GetBoundingBox() ) )
1234 {
1235 SCH_LINE* busLine = static_cast<SCH_LINE*>( busItem );
1236
1237 if( busLine->IsBus() && busLine->HitTest( label->GetPosition() ) )
1238 {
1239 labelsToWrap.push_back( label );
1240 break;
1241 }
1242 }
1243 }
1244
1245 for( SCH_LABEL* label : labelsToWrap )
1246 label->SetText( AltiumWrapBusLabel( label->GetText() ) );
1247}
1248
1249
1251{
1252 SCH_SCREEN* screen = getCurrentScreen();
1253 wxCHECK( screen, /* void */ );
1254
1255 std::set<wxString> existingNames;
1256
1257 for( SCH_ITEM* item : screen->Items().OfType( SCH_SHEET_T ) )
1258 {
1259 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
1260
1261 if( !sheet->GetName().Trim().empty() )
1262 existingNames.insert( sheet->GetName() );
1263 }
1264
1265 for( auto& [idx, sheet] : m_sheets )
1266 {
1267 if( !sheet->GetName().Trim().empty() )
1268 continue;
1269
1270 SCH_FIELD* filenameField = sheet->GetField( FIELD_T::SHEET_FILENAME );
1271 wxString filename = filenameField ? filenameField->GetText() : wxString();
1272 wxString sheetName = AltiumDeriveSheetName( filename, existingNames );
1273
1274 sheet->SetName( sheetName );
1275 existingNames.insert( sheetName );
1276 }
1277}
1278
1279
1280wxFileName SCH_IO_ALTIUM::ResolveSheetFileName( const wxString& aParentPath,
1281 const wxString& aSheetFileName ) const
1282{
1283 wxString sheetFileName = aSheetFileName;
1284 sheetFileName.Replace( wxS( "\\" ), wxS( "/" ) );
1285
1286 wxFileName loadAltiumFileName( sheetFileName );
1287 loadAltiumFileName.MakeAbsolute( aParentPath );
1288
1289 if( loadAltiumFileName.IsFileReadable() )
1290 return loadAltiumFileName;
1291
1292 if( !loadAltiumFileName.HasExt() )
1293 {
1294 wxFileName withExt( loadAltiumFileName );
1295 withExt.SetExt( wxT( "SchDoc" ) );
1296
1297 if( withExt.IsFileReadable() )
1298 return withExt;
1299 }
1300
1301 bool extensionless = !loadAltiumFileName.HasExt();
1302
1303 wxArrayString files;
1304 wxDir::GetAllFiles( loadAltiumFileName.GetPath(), &files, wxEmptyString, wxDIR_FILES | wxDIR_HIDDEN );
1305
1306 for( const wxString& candidate : files )
1307 {
1308 wxFileName candidateFname( candidate );
1309
1310 if( candidateFname.GetFullName().IsSameAs( loadAltiumFileName.GetFullName(), false )
1311 || ( extensionless
1312 && !loadAltiumFileName.GetName().empty()
1313 && candidateFname.GetName().IsSameAs( loadAltiumFileName.GetName(), false )
1314 && candidateFname.GetExt().IsSameAs( wxT( "SchDoc" ), false ) ) )
1315 {
1316 return candidateFname;
1317 }
1318 }
1319
1320 // Altium finds a sheet symbol's file among the project documents by name, wherever either is
1321 for( const wxFileName& document : m_projectDocuments )
1322 {
1323 if( document.IsFileReadable()
1324 && ( document.GetFullName().IsSameAs( loadAltiumFileName.GetFullName(), false )
1325 || ( extensionless && document.GetName().IsSameAs( loadAltiumFileName.GetName(), false ) ) ) )
1326 {
1327 return document;
1328 }
1329 }
1330
1331 return loadAltiumFileName;
1332}
1333
1334
1336{
1337 wxCHECK( m_schematic, /* void */ );
1338
1339 m_schematic->RefreshHierarchy();
1340
1341 SCH_SHEET_LIST sheetList = m_schematic->Hierarchy();
1342 std::map<wxString, std::vector<SCH_SHEET_PATH>> pathsByFile;
1343
1344 for( const SCH_SHEET_PATH& sheetPath : sheetList )
1345 {
1346 if( sheetPath.size() < 2 || !sheetPath.LastScreen() )
1347 continue;
1348
1349 wxString sheetFileName = sheetPath.Last()->GetFileName().Lower();
1350
1351 if( sheetFileName.IsEmpty() )
1352 continue;
1353
1354 SCH_SHEET_PATH parentPath = sheetPath;
1355 parentPath.pop_back();
1356
1357 pathsByFile[parentPath.Path().AsString() + wxT( "|" ) + sheetFileName]
1358 .push_back( sheetPath );
1359 }
1360
1361 // Channels of one file share a screen, where each suffix must be unique
1362 std::map<wxString, std::set<wxString>> suffixesByFile;
1363 bool suffixed = false;
1364
1365 for( auto& [groupKey, sheetPaths] : pathsByFile )
1366 {
1367 if( sheetPaths.size() < 2 )
1368 continue;
1369
1370 std::sort( sheetPaths.begin(), sheetPaths.end(),
1371 []( const SCH_SHEET_PATH& aFirst, const SCH_SHEET_PATH& aSecond )
1372 {
1373 const VECTOR2I& firstPos = aFirst.Last()->GetPosition();
1374 const VECTOR2I& secondPos = aSecond.Last()->GetPosition();
1375
1376 if( firstPos.y != secondPos.y )
1377 return firstPos.y < secondPos.y;
1378
1379 return firstPos.x < secondPos.x;
1380 } );
1381
1382 long basePage = 0;
1383
1384 for( const SCH_SHEET_PATH& sheetPath : sheetPaths )
1385 {
1386 long page = 0;
1387
1388 if( sheetPath.GetPageNumber().ToLong( &page ) && page > 0 )
1389 basePage = basePage == 0 ? page : std::min( basePage, page );
1390 }
1391
1392 if( basePage == 0 )
1393 {
1394 wxString nextPage = sheetList.GetNextPageNumber();
1395 nextPage.ToLong( &basePage );
1396 }
1397
1398 if( basePage == 0 )
1399 basePage = 1;
1400
1401 for( size_t ii = 0; ii < sheetPaths.size(); ++ii )
1402 {
1403 SCH_SHEET_PATH& sheetPath = sheetPaths[ii];
1404 SCH_SHEET* sheet = sheetPath.Last();
1405
1406 sheetPath.SetPageNumber( wxString::Format( wxT( "%ld" ), basePage + (long) ii ) );
1407
1408 // Altium names a channel's parts after its sheet, as R1_CH2, so the channels share one base
1409 wxString channel = wxT( "_" ) + sheet->GetName();
1410
1411 for( const wxString reserved : { wxT( " " ), wxT( "?" ), wxT( "," ) } )
1412 channel.Replace( reserved, wxT( "_" ) );
1413
1414 std::set<wxString>& used = suffixesByFile[sheet->GetFileName().Lower()];
1415 wxString suffix = channel;
1416
1417 for( int n = 2; !used.insert( suffix ).second; ++n )
1418 suffix = wxString::Format( wxT( "%s_%d" ), channel, n );
1419
1420 SCH_FIELD* suffixField = sheet->GetField( FIELD_T::SHEET_REF_SUFFIX );
1421
1422 if( !suffixField )
1423 suffixField = sheet->AddField( SCH_FIELD( sheet, FIELD_T::SHEET_REF_SUFFIX ) );
1424
1425 suffixField->SetText( suffix );
1426 suffixField->SetVisible( false );
1427 suffixed = true;
1428
1429 for( SCH_ITEM* item : sheetPath.LastScreen()->Items().OfType( SCH_SYMBOL_T ) )
1430 {
1431 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
1432 wxString baseRef = symbol->GetField( FIELD_T::REFERENCE )->GetText();
1433
1434 if( baseRef.StartsWith( wxT( "#" ) ) )
1435 {
1436 symbol->AddSheetPathReferenceEntryIfMissing( sheetPath.Path() );
1437 continue;
1438 }
1439
1440 if( !baseRef.IsEmpty() )
1441 symbol->SetRef( &sheetPath, baseRef );
1442 }
1443 }
1444 }
1445
1446 m_schematic->RefreshHierarchy();
1447
1448 // Suffix annotation stops at any other reused sheet whose instances share a suffix
1449 if( suffixed )
1450 {
1451 // The collision scan reads suffixes through the suffix numbering gate, so turn it on first
1452 m_schematic->Settings().m_AnnotateReusedSheetSuffixes = true;
1453
1454 if( !m_schematic->RefSuffixCollisions( true ).empty() )
1455 m_schematic->Settings().m_AnnotateReusedSheetSuffixes = false;
1456 }
1457}
1458
1459
1460// Net code of every connected item on every sheet, a promoted label standing in for its original
1461using ITEM_NET_CODES = std::map<std::pair<KIID_PATH, const SCH_ITEM*>, int>;
1462
1464 const std::map<const SCH_ITEM*, const SCH_ITEM*>& aOriginals )
1465{
1466 ITEM_NET_CODES codes;
1467
1468 for( const auto& [key, subgraphs] : aGraph.GetNetMap() )
1469 {
1470 for( const CONNECTION_SUBGRAPH* subgraph : subgraphs )
1471 {
1472 for( const SCH_ITEM* item : subgraph->GetItems() )
1473 {
1474 auto original = aOriginals.find( item );
1475
1476 codes[{ subgraph->GetSheet().Path(), original != aOriginals.end() ? original->second : item }] =
1477 key.Netcode;
1478 }
1479 }
1480 }
1481
1482 return codes;
1483}
1484
1485
1486static bool sameNets( const ITEM_NET_CODES& aBefore, const ITEM_NET_CODES& aAfter )
1487{
1488 if( aBefore.size() != aAfter.size() )
1489 return false;
1490
1491 std::map<int, int> forward;
1492 std::map<int, int> backward;
1493
1494 for( const auto& [pin, code] : aBefore )
1495 {
1496 auto it = aAfter.find( pin );
1497
1498 if( it == aAfter.end() )
1499 return false;
1500
1501 if( forward.emplace( code, it->second ).first->second != it->second
1502 || backward.emplace( it->second, code ).first->second != code )
1503 {
1504 return false;
1505 }
1506 }
1507
1508 return true;
1509}
1510
1511
1513{
1514 SCH_SHEET_LIST hierarchy = m_schematic->Hierarchy();
1515 CONNECTION_GRAPH* graph = m_schematic->ConnectionGraph();
1516
1517 graph->Recalculate( hierarchy, true );
1518
1519 struct NET_IDENTIFIERS
1520 {
1521 wxString name;
1522 bool hasGlobalLabel = false;
1523 bool hasGlobalPower = false;
1524 std::set<wxString> labelNames;
1525 std::set<SCH_LABEL*> labels;
1526 };
1527
1528 std::map<int, NET_IDENTIFIERS> nets;
1529 std::map<wxString, std::set<int>> globalNameNets;
1530 std::map<SCH_LABEL*, std::set<int>> labelNets;
1531
1532 for( const auto& [key, subgraphs] : graph->GetNetMap() )
1533 {
1534 NET_IDENTIFIERS& net = nets[key.Netcode];
1535 net.name = key.Name;
1536
1537 for( CONNECTION_SUBGRAPH* subgraph : subgraphs )
1538 {
1539 for( SCH_ITEM* item : subgraph->GetItems() )
1540 {
1541 if( item->Type() == SCH_GLOBAL_LABEL_T )
1542 {
1543 net.hasGlobalLabel = true;
1544 globalNameNets[subgraph->GetNameForDriver( item )].insert( key.Netcode );
1545 }
1546 else if( item->Type() == SCH_PIN_T && static_cast<SCH_PIN*>( item )->IsGlobalPower() )
1547 {
1548 net.hasGlobalPower = true;
1549 globalNameNets[subgraph->GetNameForDriver( item )].insert( key.Netcode );
1550 }
1551 else if( item->Type() == SCH_LABEL_T
1552 && !wxString( static_cast<SCH_LABEL*>( item )->GetText() ).Trim().IsEmpty() )
1553 {
1554 SCH_LABEL* label = static_cast<SCH_LABEL*>( item );
1555
1556 net.labelNames.insert( label->GetText() );
1557 net.labels.insert( label );
1558 labelNets[label].insert( key.Netcode );
1559 }
1560 }
1561 }
1562 }
1563
1564 std::map<wxString, std::vector<int>> candidates;
1565
1566 for( const auto& [code, net] : nets )
1567 {
1568 // Altium's choice among several labels on one net is undocumented, so leave those alone
1569 if( net.hasGlobalLabel || !net.hasGlobalPower || net.labelNames.size() != 1 )
1570 continue;
1571
1572 const wxString& text = *net.labelNames.begin();
1573 wxString name = EscapeString( text, CTX_NETNAME );
1574
1575 if( name == net.name || text.Contains( wxS( "${" ) ) )
1576 continue;
1577
1578 // A global label joins every global net of its name
1579 if( auto it = globalNameNets.find( name );
1580 it != globalNameNets.end()
1581 && std::any_of( it->second.begin(), it->second.end(),
1582 [code]( int aCode )
1583 {
1584 return aCode != code;
1585 } ) )
1586 {
1587 continue;
1588 }
1589
1590 // A label on a screen shared by several instances must sit on this net in all of them
1591 if( std::all_of( net.labels.begin(), net.labels.end(),
1592 [&]( SCH_LABEL* aLabel )
1593 {
1594 return labelNets[aLabel].size() == 1;
1595 } ) )
1596 {
1597 candidates[name].push_back( code );
1598 }
1599 }
1600
1601 std::vector<std::pair<SCH_LABEL*, SCH_GLOBALLABEL*>> converted;
1602 std::vector<wxString> promoted;
1603
1604 for( const auto& [name, codes] : candidates )
1605 {
1606 // Two power nets labelled alike would merge once the label is global
1607 if( codes.size() != 1 )
1608 continue;
1609
1610 promoted.push_back( name );
1611
1612 for( SCH_LABEL* label : nets[codes.front()].labels )
1613 {
1614 SCH_GLOBALLABEL* globalLabel = new SCH_GLOBALLABEL( label->GetPosition(), label->GetText() );
1615
1617 globalLabel->SetAttributes( *label, false );
1618 globalLabel->SetSpinStyle( label->GetSpinStyle() );
1619 globalLabel->GetField( FIELD_T::INTERSHEET_REFS )->SetVisible( false );
1620
1621 // Same mirroring as the change-label-type tool so the text keeps its side
1622 if( label->GetSpinStyle() == SPIN_STYLE::SPIN::UP
1623 || label->GetSpinStyle() == SPIN_STYLE::SPIN::BOTTOM )
1624 {
1625 globalLabel->MirrorVertically( label->GetPosition().y );
1626 }
1627 else
1628 {
1629 globalLabel->MirrorHorizontally( label->GetPosition().x );
1630 }
1631
1632 converted.emplace_back( label, globalLabel );
1633 }
1634 }
1635
1636 if( converted.empty() )
1637 return;
1638
1639 auto screenOf = []( SCH_ITEM* aItem )
1640 {
1641 return static_cast<SCH_SCREEN*>( aItem->GetParent() );
1642 };
1643
1644 std::map<const SCH_ITEM*, const SCH_ITEM*> originals;
1645
1646 for( const auto& [label, globalLabel] : converted )
1647 originals[globalLabel] = label;
1648
1649 ITEM_NET_CODES before = itemNetCodes( *graph, {} );
1650
1651 for( auto& [label, globalLabel] : converted )
1652 {
1653 SCH_SCREEN* screen = screenOf( label );
1654 screen->Remove( label );
1655 screen->Append( globalLabel );
1656 }
1657
1658 graph->Recalculate( hierarchy, true );
1659
1660 if( sameNets( before, itemNetCodes( *graph, originals ) ) )
1661 {
1662 for( auto& [label, globalLabel] : converted )
1663 delete label;
1664
1665 if( m_reporter )
1666 {
1667 for( const wxString& name : promoted )
1668 {
1669 m_reporter->Report( wxString::Format( _( "Net label '%s' made global so it names its net "
1670 "ahead of the power port, as in Altium." ),
1671 UnescapeString( name ) ),
1673 }
1674 }
1675
1676 return;
1677 }
1678
1679 for( auto& [label, globalLabel] : converted )
1680 {
1681 SCH_SCREEN* screen = screenOf( globalLabel );
1682 screen->Remove( globalLabel );
1683 screen->Append( label );
1684 delete globalLabel;
1685 }
1686
1687 graph->Recalculate( hierarchy, true );
1688
1689 if( m_reporter )
1690 m_reporter->Report( wxS( "Net labels kept local, a global label would have changed connectivity" ),
1692}
1693
1694
1695void SCH_IO_ALTIUM::ParseAltiumSch( const wxString& aFileName )
1696{
1697 // Load path may be different from the project path.
1698 wxFileName parentFileName( aFileName );
1699
1700 // Mark on the parse stack so a sheet referencing an ancestor or itself reads as recursion
1701 PARSE_FILE_GUARD selfGuard( this, AltiumParseKey( parentFileName ) );
1702 m_parsedFiles.insert( AltiumParseKey( parentFileName ) );
1703
1704 // Fresh per-file owner-index map so a stale entry from a pruned sheet is not dereferenced
1705 // map insert keeps a dangling entry rather than replacing it
1706 m_sheets.clear();
1707
1708 if( m_rootFilepath.IsEmpty() )
1709 m_rootFilepath = parentFileName.GetPath();
1710
1711 if( m_progressReporter )
1712 {
1713 wxFileName relative = parentFileName;
1714 relative.MakeRelativeTo( m_rootFilepath );
1715
1716 m_progressReporter->Report( wxString::Format( _( "Importing %s" ), relative.GetFullPath() ) );
1717
1718 if( !m_progressReporter->KeepRefreshing() )
1720 }
1721
1722 if( isBinaryFile( aFileName ) )
1723 {
1724 ALTIUM_COMPOUND_FILE altiumSchFile( aFileName );
1725
1726 try
1727 {
1728 ParseStorage( altiumSchFile ); // we need this before parsing the FileHeader
1729 ParseFileHeader( altiumSchFile );
1730
1731 // Parse "Additional" because sheet is set up during "FileHeader" parsing.
1732 ParseAdditional( altiumSchFile );
1733 }
1734 catch( const CFB::CFBException& exception )
1735 {
1736 THROW_IO_ERROR( exception.what() );
1737 }
1738 catch( const std::exception& exc )
1739 {
1740 THROW_IO_ERROR( wxString::Format( _( "Error parsing Altium schematic: %s" ), exc.what() ) );
1741 }
1742 }
1743 else // ASCII
1744 {
1745 ParseASCIISchematic( aFileName );
1746 }
1747
1748 SCH_SCREEN* currentScreen = getCurrentScreen();
1749 wxCHECK( currentScreen, /* void */ );
1750
1751 // Descend the hierarchy. One symbol may list several semicolon-separated files (pages of a
1752 // multi-page block) merged into one screen; refs to a parse-stack file are cycles pruned later
1753 std::vector<SCH_SHEET*> cyclicSheets;
1754
1755 for( SCH_ITEM* item : currentScreen->Items().OfType( SCH_SHEET_T ) )
1756 {
1757 SCH_SHEET* sheet = dynamic_cast<SCH_SHEET*>( item );
1758
1759 wxCHECK2( sheet, continue );
1760
1761 // Already given a screen by an earlier member pass
1762 if( sheet->GetScreen() )
1763 continue;
1764
1765 wxArrayString tokens = wxSplit( sheet->GetFileName(), ';' );
1766 std::vector<wxFileName> members;
1767 std::set<wxString> memberKeySet;
1768 bool skippedForRecursion = false;
1769
1770 for( wxString token : tokens )
1771 {
1772 token.Trim( true ).Trim( false );
1773
1774 if( token.IsEmpty() )
1775 continue;
1776
1777 wxFileName resolved = ResolveSheetFileName( parentFileName.GetPath(), token );
1778
1779 if( resolved.GetFullName().IsEmpty() || !resolved.IsFileReadable() )
1780 continue;
1781
1782 wxString key = AltiumParseKey( resolved );
1783
1784 if( m_parsingFiles.count( key ) )
1785 {
1786 skippedForRecursion = true;
1787 continue;
1788 }
1789
1790 // Dedup so a page listed twice is not parsed and tiled twice
1791 if( memberKeySet.insert( key ).second )
1792 members.push_back( resolved );
1793 }
1794
1795 if( members.empty() )
1796 {
1797 // Only parse-stack files means a cross-page or self reference to prune
1798 // otherwise an unresolved Altium signal harness
1799 if( skippedForRecursion )
1800 {
1801 cyclicSheets.push_back( sheet );
1802 }
1803 else
1804 {
1805 wxString missingFile;
1806
1807 for( wxString token : tokens )
1808 {
1809 if( !token.Trim( true ).Trim( false ).IsEmpty() )
1810 {
1811 missingFile = token;
1812 break;
1813 }
1814 }
1815
1816 if( missingFile.IsEmpty() )
1817 {
1818 m_errorMessages.emplace( wxString::Format( _( "The file name for sheet %s is undefined, "
1819 "this is probably an Altium signal harness "
1820 "that got converted to a sheet." ),
1821 sheet->GetName() ),
1823 }
1824 else
1825 {
1826 m_errorMessages.emplace( wxString::Format( _( "The file %s of sheet %s was not found; the "
1827 "sheet is empty." ),
1828 missingFile, sheet->GetName() ),
1830 }
1831
1832 attachEmptySheetScreen( sheet, missingFile );
1833 }
1834
1835 continue;
1836 }
1837
1838 // Repeated channels save one file so they must share one screen. Keyed on the sources, as
1839 // distinct sources can share a destination name, and set only once parsed so no ancestor matches
1840 std::vector<wxString> loadKey;
1841
1842 for( const wxFileName& member : members )
1843 {
1844 loadKey.push_back( AltiumParseKey( member ) );
1845 m_subsheetFiles.insert( loadKey.back().Lower() );
1846 }
1847
1848 SCH_SCREEN* loadedScreen = nullptr;
1849
1850 if( auto it = m_loadedScreens.find( loadKey ); it != m_loadedScreens.end() )
1851 loadedScreen = it->second;
1852
1853 if( loadedScreen )
1854 {
1855 sheet->SetScreen( loadedScreen );
1856 sheet->SetFileName( wxFileName( loadedScreen->GetFileName() ).GetFullName() );
1857
1858 // Sub-sheets already loaded
1859 continue;
1860 }
1861
1862 sheet->SetScreen( new SCH_SCREEN( m_schematic ) );
1863 SCH_SCREEN* screen = sheet->GetScreen();
1864
1865 wxCHECK2( screen, continue );
1866
1867 if( sheet->GetName().Trim().empty() )
1868 {
1869 std::set<wxString> sheetNames;
1870
1871 for( EDA_ITEM* otherItem : currentScreen->Items().OfType( SCH_SHEET_T ) )
1872 sheetNames.insert( static_cast<SCH_SHEET*>( otherItem )->GetName() );
1873
1874 sheet->SetName( AltiumDeriveSheetName( members[0].GetFullName(), sheetNames ) );
1875 }
1876
1877 // Hold every block member on the parse stack so a page cross-referencing a sibling or
1878 // itself reads as recursion below
1879 PARSE_FILE_GUARD blockGuard( this,
1880 std::vector<wxString>( memberKeySet.begin(),
1881 memberKeySet.end() ) );
1882
1883 m_sheetPath.push_back( sheet );
1884
1885 std::optional<int> nextPageTop;
1886
1887 for( const wxFileName& member : members )
1888 {
1889 std::set<const SCH_ITEM*> before;
1890
1891 for( SCH_ITEM* screenItem : screen->Items() )
1892 before.insert( screenItem );
1893
1894 ParseAltiumSch( member.GetFullPath() );
1895
1896 std::vector<SCH_ITEM*> added;
1897 BOX2I addedBox;
1898
1899 for( SCH_ITEM* screenItem : screen->Items() )
1900 {
1901 if( !before.count( screenItem ) )
1902 {
1903 added.push_back( screenItem );
1904 addedBox.Merge( screenItem->GetBoundingBox() );
1905 }
1906 }
1907
1908 if( added.empty() )
1909 continue;
1910
1911 // Tile each later page below the merged ones so shared source coordinates do not overlap
1912 if( nextPageTop )
1913 {
1914 VECTOR2I shift( 0, *nextPageTop - addedBox.GetTop() );
1915
1916 for( SCH_ITEM* addedItem : added )
1917 {
1918 addedItem->Move( shift );
1919 screen->Update( addedItem );
1920 }
1921
1922 addedBox.Offset( shift );
1923 }
1924
1925 nextPageTop = addedBox.GetBottom() + schIUScale.MilsToIU( 500 );
1926 }
1927
1928 m_sheetPath.pop_back();
1929
1930 wxFileName claimed( claimSheetFile( members[0].GetName() ) );
1931
1932 sheet->SetFileName( claimed.GetFullName() );
1933 screen->SetFileName( claimed.GetFullPath() );
1934 m_loadedScreens.emplace( std::move( loadKey ), screen );
1935 }
1936
1937 pruneCyclicSheets( cyclicSheets, currentScreen );
1938}
1939
1940
1941void SCH_IO_ALTIUM::attachEmptySheetScreen( SCH_SHEET* aSheet, const wxString& aMissingFile )
1942{
1943 wxString stem = aMissingFile;
1944 stem.Replace( wxS( "\\" ), wxS( "/" ) );
1945 stem = stem.IsEmpty() ? aSheet->GetName() : wxFileName( stem ).GetName();
1946 ReplaceIllegalFileNameChars( stem, '_' );
1947
1948 if( stem.IsEmpty() )
1949 stem = aSheet->m_Uuid.AsString();
1950
1951 // A screen with no file name is saved as ".kicad_sch", which every such sheet would then share
1952 wxFileName missing( m_schematic->Project().GetProjectPath(), stem, FILEEXT::KiCadSchematicFileExtension );
1953
1954 if( auto it = m_missingScreens.find( missing.GetFullPath() ); it != m_missingScreens.end() )
1955 {
1956 aSheet->SetScreen( it->second );
1957 }
1958 else
1959 {
1960 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
1961
1962 aSheet->SetScreen( screen );
1963 screen->SetFileName( claimSheetFile( stem ) );
1964 m_missingScreens.emplace( missing.GetFullPath(), screen );
1965 }
1966
1967 aSheet->SetFileName( wxFileName( aSheet->GetScreen()->GetFileName() ).GetFullName() );
1968}
1969
1970
1971wxString SCH_IO_ALTIUM::claimSheetFile( const wxString& aStem )
1972{
1973 wxFileName fn( m_schematic->Project().GetProjectPath(), aStem, FILEEXT::KiCadSchematicFileExtension );
1974
1975 for( int n = 1; fn.GetFullPath().IsSameAs( m_rootSheetFile, false )
1976 || !m_sheetFiles.insert( fn.GetFullPath().Lower() ).second;
1977 n++ )
1978 {
1979 fn.SetName( wxString::Format( wxS( "%s_%d" ), aStem, n ) );
1980 }
1981
1982 return fn.GetFullPath();
1983}
1984
1985
1986void SCH_IO_ALTIUM::pruneCyclicSheets( const std::vector<SCH_SHEET*>& aCyclicSheets,
1987 SCH_SCREEN* aScreen )
1988{
1989 SCH_SCREEN* rootScreen = m_rootSheet->GetScreen();
1990
1991 for( SCH_SHEET* sheet : aCyclicSheets )
1992 {
1993 // Deleting the sheet drops its pins leaving wires dangling. Replace each pin with a hier
1994 // label at its location so the wire connects by name to the merged page port
1995 for( SCH_SHEET_PIN* pin : sheet->GetPins() )
1996 {
1997 SCH_HIERLABEL* label = new SCH_HIERLABEL( pin->GetPosition(), pin->GetText() );
1998
1999 label->SetShape( pin->GetShape() );
2000 label->SetSpinStyle( pin->GetSpinStyle() );
2001 aScreen->Append( label );
2002 }
2003
2004 // Drop the sheet-instance record on the root screen
2005 if( rootScreen )
2006 {
2007 std::erase_if( rootScreen->m_sheetInstances,
2008 [&]( const SCH_SHEET_INSTANCE& aInstance )
2009 {
2010 return !aInstance.m_Path.empty()
2011 && aInstance.m_Path.back() == sheet->m_Uuid;
2012 } );
2013 }
2014
2015 aScreen->DeleteItem( sheet );
2016 }
2017}
2018
2019
2021{
2022 const CFB::COMPOUND_FILE_ENTRY* file = aAltiumSchFile.FindStream( { "Storage" } );
2023
2024 if( file == nullptr )
2025 return;
2026
2027 ALTIUM_BINARY_PARSER reader( aAltiumSchFile, file );
2028
2029 std::map<wxString, wxString> properties = reader.ReadProperties();
2030 ALTIUM_PROPS_UTILS::ReadString( properties, "HEADER", "" );
2031 int weight = ALTIUM_PROPS_UTILS::ReadInt( properties, "WEIGHT", 0 );
2032
2033 if( weight < 0 )
2034 THROW_IO_ERROR( "Storage weight is negative!" );
2035
2036 for( int i = 0; i < weight; i++ )
2037 m_altiumStorage.emplace_back( reader );
2038
2039 if( reader.HasParsingError() )
2040 THROW_IO_ERROR( "stream was not parsed correctly!" );
2041
2042 // TODO pointhi: is it possible to have multiple headers in one Storage file? Otherwise
2043 // throw IO Error.
2044 if( reader.GetRemainingBytes() != 0 )
2045 {
2046 m_errorMessages.emplace( wxString::Format( _( "Storage file not fully parsed (%d bytes remaining)." ),
2047 reader.GetRemainingBytes() ),
2049 }
2050}
2051
2052
2054{
2055 wxString streamName = wxS( "Additional" );
2056
2057 const CFB::COMPOUND_FILE_ENTRY* file =
2058 aAltiumSchFile.FindStream( { streamName.ToStdString() } );
2059
2060 if( file == nullptr )
2061 return;
2062
2063 ALTIUM_BINARY_PARSER reader( aAltiumSchFile, file );
2064
2065 if( reader.GetRemainingBytes() <= 0 )
2066 {
2067 THROW_IO_ERROR( "Additional section does not contain any data" );
2068 }
2069 else
2070 {
2071 std::map<wxString, wxString> properties = reader.ReadProperties();
2072
2073 int recordId = ALTIUM_PROPS_UTILS::ReadInt( properties, "RECORD", 0 );
2074 ALTIUM_SCH_RECORD record = static_cast<ALTIUM_SCH_RECORD>( recordId );
2075
2076 if( record != ALTIUM_SCH_RECORD::HEADER )
2077 THROW_IO_ERROR( "Header expected" );
2078 }
2079
2080 for( int index = 0; reader.GetRemainingBytes() > 0; index++ )
2081 {
2082 std::map<wxString, wxString> properties = reader.ReadProperties();
2083
2084 ParseRecord( index, properties, streamName );
2085 }
2086
2087 // Handle harness Ports
2088 for( const ASCH_PORT& port : m_altiumHarnessPortsCurrentSheet )
2089 ParseHarnessPort( port );
2090
2091 CreateAliases();
2092
2093 // Wrap any remaining net labels sitting on bus lines in curly braces
2095
2096 if( reader.HasParsingError() )
2097 THROW_IO_ERROR( "stream was not parsed correctly!" );
2098
2099 if( reader.GetRemainingBytes() != 0 )
2100 THROW_IO_ERROR( "stream is not fully parsed" );
2101
2102 m_altiumHarnesses.clear();
2104}
2105
2106
2108{
2109 wxString streamName = wxS( "FileHeader" );
2110
2111 const CFB::COMPOUND_FILE_ENTRY* file = aAltiumSchFile.FindStream( { streamName.ToStdString() } );
2112
2113 if( file == nullptr )
2114 THROW_IO_ERROR( "FileHeader not found" );
2115
2116 ALTIUM_BINARY_PARSER reader( aAltiumSchFile, file );
2117
2118 if( reader.GetRemainingBytes() <= 0 )
2119 {
2120 THROW_IO_ERROR( "FileHeader does not contain any data" );
2121 }
2122 else
2123 {
2124 std::map<wxString, wxString> properties = reader.ReadProperties();
2125
2126 wxString libtype = ALTIUM_PROPS_UTILS::ReadString( properties, "HEADER", "" );
2127
2128 if( libtype.CmpNoCase( "Protel for Windows - Schematic Capture Binary File Version 5.0" ) )
2129 THROW_IO_ERROR( _( "Expected Altium Schematic file version 5.0" ) );
2130 }
2131
2132 // Prepare some local variables
2133 wxCHECK( m_altiumPortsCurrentSheet.empty(), /* void */ );
2134 wxCHECK( !m_currentTitleBlock, /* void */ );
2135
2136 m_currentTitleBlock = std::make_unique<TITLE_BLOCK>();
2137
2138 // index is required to resolve OWNERINDEX
2139 for( int index = 0; reader.GetRemainingBytes() > 0; index++ )
2140 {
2141 std::map<wxString, wxString> properties = reader.ReadProperties();
2142
2143 ParseRecord( index, properties, streamName );
2144 }
2145
2146 if( reader.HasParsingError() )
2147 THROW_IO_ERROR( "stream was not parsed correctly!" );
2148
2149 if( reader.GetRemainingBytes() != 0 )
2150 THROW_IO_ERROR( "stream is not fully parsed" );
2151
2152 // assign LIB_SYMBOL -> COMPONENT
2153 for( std::pair<const int, SCH_SYMBOL*>& symbol : m_symbols )
2154 {
2155 auto libSymbolIt = m_libSymbols.find( symbol.first );
2156
2157 if( libSymbolIt == m_libSymbols.end() )
2158 THROW_IO_ERROR( "every symbol should have a symbol attached" );
2159
2160 fixupSymbolPinNameNumbers( symbol.second );
2161 fixupSymbolPinNameNumbers( libSymbolIt->second );
2162
2163 symbol.second->SetLibSymbol( libSymbolIt->second );
2164 }
2165
2166 SCH_SCREEN* screen = getCurrentScreen();
2167 wxCHECK( screen, /* void */ );
2168
2169 // Handle title blocks
2171 m_currentTitleBlock.reset();
2172
2173 // Handle Ports
2174 for( const ASCH_PORT& port : m_altiumPortsCurrentSheet )
2175 ParsePort( port );
2176
2177 // Bus labels are wrapped in ParseAdditional() after CreateAliases() has had a chance to
2178 // append harness suffixes; doing it here would prematurely mark labels as bus groups.
2179
2180 // Assign default names to any sheet symbols that didn't get a SHEET_NAME record
2182
2184 m_altiumComponents.clear();
2185 m_altiumTemplates.clear();
2187
2188 m_symbols.clear();
2189 m_libSymbols.clear();
2190
2191 // Otherwise we cannot save the imported sheet?
2192 SCH_SHEET* sheet = getCurrentSheet();
2193
2194 wxCHECK( sheet, /* void */ );
2195
2196 sheet->SetModified();
2197}
2198
2199
2200void SCH_IO_ALTIUM::ParseASCIISchematic( const wxString& aFileName )
2201{
2202 // Read storage content first
2203 {
2204 ALTIUM_ASCII_PARSER storageReader( aFileName );
2205
2206 while( storageReader.CanRead() )
2207 {
2208 std::map<wxString, wxString> properties = storageReader.ReadProperties();
2209
2210 // Binary data
2211 if( properties.find( wxS( "BINARY" ) ) != properties.end() )
2212 m_altiumStorage.emplace_back( properties );
2213 }
2214 }
2215
2216 // Read other data
2217 ALTIUM_ASCII_PARSER reader( aFileName );
2218
2219 if( !reader.CanRead() )
2220 {
2221 THROW_IO_ERROR( "FileHeader does not contain any data" );
2222 }
2223 else
2224 {
2225 std::map<wxString, wxString> properties = reader.ReadProperties();
2226
2227 wxString libtype = ALTIUM_PROPS_UTILS::ReadString( properties, "HEADER", "" );
2228
2229 if( libtype.CmpNoCase( "Protel for Windows - Schematic Capture Ascii File Version 5.0" ) )
2230 THROW_IO_ERROR( _( "Expected Altium Schematic file version 5.0" ) );
2231 }
2232
2233 // Prepare some local variables
2234 wxCHECK( m_altiumPortsCurrentSheet.empty(), /* void */ );
2235 wxCHECK( !m_currentTitleBlock, /* void */ );
2236
2237 m_currentTitleBlock = std::make_unique<TITLE_BLOCK>();
2238
2239 // index is required to resolve OWNERINDEX
2240 int index = 0;
2241
2242 while( reader.CanRead() )
2243 {
2244 std::map<wxString, wxString> properties = reader.ReadProperties();
2245
2246 // Reset index at headers
2247 if( properties.find( wxS( "HEADER" ) ) != properties.end() )
2248 {
2249 index = 0;
2250 continue;
2251 }
2252
2253 if( properties.find( wxS( "RECORD" ) ) != properties.end() )
2254 ParseRecord( index, properties, aFileName );
2255
2256 index++;
2257 }
2258
2259 if( reader.HasParsingError() )
2260 THROW_IO_ERROR( "stream was not parsed correctly!" );
2261
2262 if( reader.CanRead() )
2263 THROW_IO_ERROR( "stream is not fully parsed" );
2264
2265 // assign LIB_SYMBOL -> COMPONENT
2266 for( std::pair<const int, SCH_SYMBOL*>& symbol : m_symbols )
2267 {
2268 auto libSymbolIt = m_libSymbols.find( symbol.first );
2269
2270 if( libSymbolIt == m_libSymbols.end() )
2271 THROW_IO_ERROR( "every symbol should have a symbol attached" );
2272
2273 fixupSymbolPinNameNumbers( symbol.second );
2274 fixupSymbolPinNameNumbers( libSymbolIt->second );
2275
2276 symbol.second->SetLibSymbol( libSymbolIt->second );
2277 }
2278
2279 SCH_SCREEN* screen = getCurrentScreen();
2280 wxCHECK( screen, /* void */ );
2281
2282 // Handle title blocks
2284 m_currentTitleBlock.reset();
2285
2286 // Handle harness Ports
2287 for( const ASCH_PORT& port : m_altiumHarnessPortsCurrentSheet )
2288 ParseHarnessPort( port );
2289
2290 // Handle Ports
2291 for( const ASCH_PORT& port : m_altiumPortsCurrentSheet )
2292 ParsePort( port );
2293
2294 // Add the aliases used for harnesses
2295 CreateAliases();
2296
2297 // Wrap net labels sitting on bus lines in curly braces so KiCad recognizes them
2299
2300 // Assign default names to any sheet symbols that didn't get a SHEET_NAME record
2302
2303 m_altiumHarnesses.clear();
2305 m_altiumComponents.clear();
2306 m_altiumTemplates.clear();
2308
2309 m_symbols.clear();
2310 m_libSymbols.clear();
2311
2312 // Otherwise we cannot save the imported sheet?
2313 SCH_SHEET* sheet = getCurrentSheet();
2314
2315 wxCHECK( sheet, /* void */ );
2316
2317 sheet->SetModified();
2318}
2319
2320
2321void SCH_IO_ALTIUM::ParseRecord( int index, std::map<wxString, wxString>& properties,
2322 const wxString& aSectionName )
2323{
2324 int recordId = ALTIUM_PROPS_UTILS::ReadInt( properties, "RECORD", -1 );
2325 ALTIUM_SCH_RECORD record = static_cast<ALTIUM_SCH_RECORD>( recordId );
2326
2327 // see: https://github.com/vadmium/python-altium/blob/master/format.md
2328 switch( record )
2329 {
2330 // FileHeader section
2331
2333 THROW_IO_ERROR( "Header already parsed" );
2334
2336 ParseComponent( index, properties );
2337 break;
2338
2340 ParsePin( properties );
2341 break;
2342
2344 m_errorMessages.emplace( _( "Record 'IEEE_SYMBOL' not handled." ), RPT_SEVERITY_INFO );
2345 break;
2346
2348 ParseLabel( properties );
2349 break;
2350
2352 ParseBezier( properties );
2353 break;
2354
2356 ParsePolyline( properties );
2357 break;
2358
2360 ParsePolygon( properties );
2361 break;
2362
2364 ParseEllipse( properties );
2365 break;
2366
2368 ParsePieChart( properties );
2369 break;
2370
2372 ParseRoundRectangle( properties );
2373 break;
2374
2377 ParseArc( properties );
2378 break;
2379
2381 ParseLine( properties );
2382 break;
2383
2385 ParseRectangle( properties );
2386 break;
2387
2389 ParseSheetSymbol( index, properties );
2390 break;
2391
2393 ParseSheetEntry( properties );
2394 break;
2395
2397 ParsePowerPort( properties );
2398 break;
2399
2401 // Ports are parsed after the sheet was parsed
2402 // This is required because we need all electrical connection points before placing.
2403 m_altiumPortsCurrentSheet.emplace_back( properties );
2404 break;
2405
2407 ParseNoERC( properties );
2408 break;
2409
2411 ParseNetLabel( properties );
2412 break;
2413
2415 ParseBus( properties );
2416 break;
2417
2419 ParseWire( properties );
2420 break;
2421
2423 ParseTextFrame( properties );
2424 break;
2425
2427 ParseJunction( properties );
2428 break;
2429
2431 ParseImage( properties );
2432 break;
2433
2435 ParseSheet( properties );
2436 break;
2437
2439 ParseSheetName( properties );
2440 break;
2441
2443 ParseFileName( properties );
2444 break;
2445
2447 ParseDesignator( properties );
2448 break;
2449
2451 ParseBusEntry( properties );
2452 break;
2453
2455 ParseTemplate( index, properties );
2456 break;
2457
2459 ParseParameter( properties );
2460 break;
2461
2463 m_errorMessages.emplace( _( "Parameter Set not currently supported." ), RPT_SEVERITY_ERROR );
2464 break;
2465
2467 ParseImplementationList( index, properties );
2468 break;
2469
2471 ParseImplementation( properties );
2472 break;
2473
2475 break;
2476
2478 break;
2479
2481 break;
2482
2484 ParseNote( properties );
2485 break;
2486
2488 m_errorMessages.emplace( _( "Compile mask not currently supported." ), RPT_SEVERITY_ERROR );
2489 break;
2490
2492 break;
2493
2494 // Additional section
2495
2497 ParseHarnessConnector( index, properties );
2498 break;
2499
2501 ParseHarnessEntry( properties );
2502 break;
2503
2505 ParseHarnessType( properties );
2506 break;
2507
2509 ParseSignalHarness( properties );
2510 break;
2511
2513 m_errorMessages.emplace( _( "Blanket not currently supported." ), RPT_SEVERITY_ERROR );
2514 break;
2515
2516 default:
2517 m_errorMessages.emplace(
2518 wxString::Format( _( "Unknown or unexpected record id %d found in %s." ), recordId,
2519 aSectionName ),
2521 break;
2522 }
2523
2525}
2526
2527
2528
2529const ASCH_STORAGE_FILE* SCH_IO_ALTIUM::GetFileFromStorage( const wxString& aFilename ) const
2530{
2531 const ASCH_STORAGE_FILE* nonExactMatch = nullptr;
2532
2533 for( const ASCH_STORAGE_FILE& file : m_altiumStorage )
2534 {
2535 if( file.filename.IsSameAs( aFilename ) )
2536 return &file;
2537
2538 if( file.filename.EndsWith( aFilename ) )
2539 nonExactMatch = &file;
2540 }
2541
2542 return nonExactMatch;
2543}
2544
2545
2546void SCH_IO_ALTIUM::ParseComponent( int aIndex, const std::map<wxString, wxString>& aProperties )
2547{
2548 SCH_SHEET* currentSheet = m_sheetPath.Last();
2549 wxCHECK( currentSheet, /* void */ );
2550
2551 wxString sheetName = currentSheet->GetName();
2552
2553 if( sheetName.IsEmpty() )
2554 sheetName = wxT( "root" );
2555
2556 ASCH_SYMBOL altiumSymbol( aProperties );
2557
2558 if( m_altiumComponents.count( aIndex ) )
2559 {
2560 const ASCH_SYMBOL& currentSymbol = m_altiumComponents.at( aIndex );
2561
2562 m_errorMessages.emplace( wxString::Format( _( "Symbol '%s' in sheet '%s' at index %d "
2563 "replaced with symbol \"%s\"." ),
2564 currentSymbol.libreference,
2565 sheetName,
2566 aIndex,
2567 altiumSymbol.libreference ),
2569 }
2570
2571 auto pair = m_altiumComponents.insert( { aIndex, altiumSymbol } );
2572 const ASCH_SYMBOL& elem = pair.first->second;
2573
2574 wxString name;
2575 LIB_ID libId;
2576
2577 if( !elem.sourcelibraryname.IsEmpty() && !elem.libreference.IsEmpty() )
2578 {
2579 // The part comes from an Altium library that project import registers in the symbol
2580 // library table, so address it by its real library id and let the placement transform
2581 // ride on the SCH_SYMBOL rather than baking it into a unique name. Altium stores Windows
2582 // paths, so split the source library name accordingly.
2583 name = elem.libreference;
2584 libId = AltiumToKiCadLibID( wxFileName( elem.sourcelibraryname, wxPATH_WIN ).GetName(),
2585 name );
2586 }
2587 else
2588 {
2589 // TODO: this is a hack until we correctly apply all transformations to every element
2590 name = wxString::Format( "%s_%d%s_%s_%s",
2591 sheetName,
2592 elem.orientation,
2593 elem.isMirrored ? "_mirrored" : "",
2594 elem.libreference,
2595 elem.sourcelibraryname );
2596
2597 libId = AltiumToKiCadLibID( getLibName(), name );
2598 }
2599
2600 LIB_SYMBOL* ksymbol = new LIB_SYMBOL( wxEmptyString );
2601 ksymbol->SetName( name );
2602 ksymbol->SetDescription( elem.componentdescription );
2603 ksymbol->SetLibId( libId );
2604
2605 // Altium PARTCOUNT is one more than the actual unit count. The property may be missing
2606 // (defaults to 0) or otherwise nonsensical, so clamp to a minimum of 1 unit.
2607 ksymbol->SetUnitCount( std::max( 1, elem.partcount - 1 ), true );
2608
2609 if( elem.displaymodecount > 1 )
2610 {
2611 std::vector<wxString> bodyStyleNames;
2612
2613 for( int i = 0; i < elem.displaymodecount; i++ )
2614 bodyStyleNames.push_back( wxString::Format( "Display %d", i + 1 ) );
2615
2616 ksymbol->SetBodyStyleNames( bodyStyleNames );
2617 }
2618
2619 m_libSymbols.insert( { aIndex, ksymbol } );
2620
2621 // each component has its own symbol for now
2622 SCH_SYMBOL* symbol = new SCH_SYMBOL();
2623
2624 symbol->SetPosition( elem.location + m_sheetOffset );
2625
2626 for( SCH_FIELD& field : symbol->GetFields() )
2627 field.SetVisible( false );
2628
2630
2631 // Altium encodes symbol rotation as quarter turns CCW, matching KiCad's SYM_ORIENT_* angles
2632 // one for one. The stored value must equal the Altium angle so a later "Update Symbols from
2633 // Library" against a canonical upright symbol does not rotate the placement.
2634 switch( elem.orientation )
2635 {
2640 default: break;
2641 }
2642
2643 if( elem.isMirrored )
2645
2646 symbol->SetOrientation( orientation );
2647
2648 symbol->SetLibId( libId );
2649
2650 if( ksymbol->GetUnitCount() > 1 )
2651 symbol->SetUnit( std::max( 1, elem.currentpartid ) );
2652 else
2653 symbol->SetUnit( 1 );
2654
2655 if( elem.displaymodecount > 1 )
2656 symbol->SetBodyStyle( elem.displaymode + 1 );
2657
2659
2660 SCH_SCREEN* screen = getCurrentScreen();
2661 wxCHECK( screen, /* void */ );
2662
2663 screen->Append( symbol );
2664
2665 m_symbols.insert( { aIndex, symbol } );
2666
2667 if( !elem.uniqueid.empty() )
2668 m_altiumSymbolToUid[symbol] = elem.uniqueid;
2669}
2670
2671
2672void SCH_IO_ALTIUM::ParseTemplate( int aIndex, const std::map<wxString, wxString>& aProperties )
2673{
2674 SCH_SHEET* currentSheet = m_sheetPath.Last();
2675 wxCHECK( currentSheet, /* void */ );
2676
2677 wxString sheetName = currentSheet->GetName();
2678
2679 if( sheetName.IsEmpty() )
2680 sheetName = wxT( "root" );
2681
2682 ASCH_TEMPLATE altiumTemplate( aProperties );
2683
2684 // Extract base name from path
2685 wxString baseName = altiumTemplate.filename.AfterLast( '\\' ).BeforeLast( '.' );
2686
2687 if( baseName.IsEmpty() )
2688 baseName = wxS( "Template" );
2689
2690 m_altiumTemplates.insert( { aIndex, altiumTemplate } );
2691 // No need to create a symbol - graphics is put on the sheet
2692}
2693
2694
2695void SCH_IO_ALTIUM::ParsePin( const std::map<wxString, wxString>& aProperties,
2696 std::vector<LIB_SYMBOL*>& aSymbol )
2697{
2698 ASCH_PIN elem( aProperties );
2699
2700 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
2701 SCH_SYMBOL* schSymbol = nullptr;
2702
2703 if( !symbol )
2704 {
2705 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
2706
2707 if( libSymbolIt == m_libSymbols.end() )
2708 {
2709 // TODO: e.g. can depend on Template (RECORD=39
2710 m_errorMessages.emplace( wxString::Format( wxT( "Pin's owner (%d) not found." ),
2711 elem.ownerindex ),
2713 return;
2714 }
2715
2716 schSymbol = m_symbols.at( libSymbolIt->first );
2717 symbol = libSymbolIt->second;
2718 }
2719
2720 SCH_PIN* pin = new SCH_PIN( symbol );
2721
2722 // Make sure that these are visible when initializing the symbol
2723 // This may be overriden by the file data but not by the pin defaults
2724 pin->SetNameTextSize( schIUScale.MilsToIU( DEFAULT_PINNAME_SIZE ) );
2725 pin->SetNumberTextSize( schIUScale.MilsToIU( DEFAULT_PINNUM_SIZE ) );
2726
2727 symbol->AddDrawItem( pin, false );
2728
2729 pin->SetUnit( std::max( 0, elem.ownerpartid ) );
2730
2731 if( symbol->GetBodyStyleCount() > 1 )
2732 {
2733 if( !aSymbol.empty() )
2734 {
2735 pin->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
2736 }
2737 else
2738 {
2739 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
2740
2741 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
2742 pin->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
2743 }
2744 }
2745
2746 pin->SetName( AltiumPinNamesToKiCad( elem.name ) );
2747 pin->SetNumber( AltiumPinDesignatorToKiCad( elem.designator ) );
2748 pin->SetLength( elem.pinlength );
2749
2750 if( elem.hidden )
2751 pin->SetVisible( false );
2752
2753 if( !elem.showDesignator )
2754 pin->SetNumberTextSize( 0 );
2755
2756 if( !elem.showPinName )
2757 pin->SetNameTextSize( 0 );
2758
2759 // Altium gives the pin body end location (elem.location) and the pre-computed
2760 // electrical connection point (elem.kicadLocation) which accounts for pin length
2761 // with combined integer+fractional arithmetic to avoid rounding errors.
2762 VECTOR2I bodyEnd = elem.location;
2763 VECTOR2I pinLocation = elem.kicadLocation;
2764
2765 switch( elem.orientation )
2766 {
2768 pin->SetOrientation( PIN_ORIENTATION::PIN_LEFT );
2769 break;
2770
2772 pin->SetOrientation( PIN_ORIENTATION::PIN_DOWN );
2773 break;
2774
2776 pin->SetOrientation( PIN_ORIENTATION::PIN_RIGHT );
2777 break;
2778
2780 pin->SetOrientation( PIN_ORIENTATION::PIN_UP );
2781 break;
2782
2783 default:
2784 m_errorMessages.emplace( _( "Pin has unexpected orientation." ), RPT_SEVERITY_WARNING );
2785 break;
2786 }
2787
2788 if( schSymbol )
2789 {
2790 // Both points are in absolute schematic coordinates. Transform them to library-local
2791 // space, then derive the pin orientation from the resulting direction vector.
2792 pinLocation = GetRelativePosition( pinLocation + m_sheetOffset, schSymbol );
2793 bodyEnd = GetRelativePosition( bodyEnd + m_sheetOffset, schSymbol );
2794
2795 VECTOR2I dir = bodyEnd - pinLocation;
2796
2797 if( std::abs( dir.x ) >= std::abs( dir.y ) )
2798 pin->SetOrientation( dir.x > 0 ? PIN_ORIENTATION::PIN_RIGHT : PIN_ORIENTATION::PIN_LEFT );
2799 else
2800 pin->SetOrientation( dir.y > 0 ? PIN_ORIENTATION::PIN_DOWN : PIN_ORIENTATION::PIN_UP );
2801 }
2802
2803 pin->SetPosition( pinLocation );
2804
2805 switch( elem.electrical )
2806 {
2809 break;
2810
2812 pin->SetType( ELECTRICAL_PINTYPE::PT_BIDI );
2813 break;
2814
2817 break;
2818
2821 break;
2822
2825 break;
2826
2829 break;
2830
2833 break;
2834
2837 break;
2838
2840 default:
2842 m_errorMessages.emplace( _( "Pin has unexpected electrical type." ), RPT_SEVERITY_WARNING );
2843 break;
2844 }
2845
2847 m_errorMessages.emplace( _( "Pin has unexpected outer edge type." ), RPT_SEVERITY_WARNING );
2848
2850 m_errorMessages.emplace( _( "Pin has unexpected inner edge type." ), RPT_SEVERITY_WARNING );
2851
2853 {
2854 switch( elem.symbolInnerEdge )
2855 {
2858 break;
2859
2860 default:
2861 pin->SetShape( GRAPHIC_PINSHAPE::INVERTED );
2862 break;
2863 }
2864 }
2866 {
2867 switch( elem.symbolInnerEdge )
2868 {
2870 pin->SetShape( GRAPHIC_PINSHAPE::CLOCK_LOW );
2871 break;
2872
2873 default:
2874 pin->SetShape( GRAPHIC_PINSHAPE::INPUT_LOW );
2875 break;
2876 }
2877 }
2879 {
2880 pin->SetShape( GRAPHIC_PINSHAPE::OUTPUT_LOW );
2881 }
2882 else
2883 {
2884 switch( elem.symbolInnerEdge )
2885 {
2887 pin->SetShape( GRAPHIC_PINSHAPE::CLOCK );
2888 break;
2889
2890 default:
2891 pin->SetShape( GRAPHIC_PINSHAPE::LINE ); // nothing to do
2892 break;
2893 }
2894 }
2895}
2896
2897
2900{
2901 int vjustify, hjustify;
2903
2904 switch( justification )
2905 {
2906 default:
2911 vjustify = GR_TEXT_V_ALIGN_BOTTOM;
2912 break;
2913
2917 vjustify = GR_TEXT_V_ALIGN_CENTER;
2918 break;
2919
2923 vjustify = GR_TEXT_V_ALIGN_TOP;
2924 break;
2925 }
2926
2927 switch( justification )
2928 {
2929 default:
2934 hjustify = GR_TEXT_H_ALIGN_LEFT;
2935 break;
2936
2940 hjustify = GR_TEXT_H_ALIGN_CENTER;
2941 break;
2942
2946 hjustify = GR_TEXT_H_ALIGN_RIGHT;
2947 break;
2948 }
2949
2950 switch( orientation )
2951 {
2953 angle = ANGLE_HORIZONTAL;
2954 break;
2955
2957 hjustify *= -1;
2958 angle = ANGLE_HORIZONTAL;
2959 break;
2960
2962 angle = ANGLE_VERTICAL;
2963 break;
2964
2966 hjustify *= -1;
2967 angle = ANGLE_VERTICAL;
2968 break;
2969 }
2970
2971 text->SetVertJustify( static_cast<GR_TEXT_V_ALIGN_T>( vjustify ) );
2972 text->SetHorizJustify( static_cast<GR_TEXT_H_ALIGN_T>( hjustify ) );
2973 text->SetTextAngle( angle );
2974}
2975
2976
2977// Altium text orientation and justification are in absolute (page) coordinates. KiCad stores
2978// field text properties relative to the parent symbol and applies the symbol's transform at
2979// render time. This function adjusts the field's stored text angle and justification to
2980// compensate for the symbol's orientation so that the final rendered appearance matches the
2981// original Altium layout.
2982//
2983// The compensation follows the same logic as SCH_FIELD::Rotate() but applied in the
2984// inverse direction to undo the symbol's rotation effect on text properties.
2986{
2987 bool isHorizontal = aField->GetTextAngle().IsHorizontal();
2988
2989 // Altium orientation 0 (RIGHTWARDS) maps to KiCad SYM_ORIENT_0 (identity). No rotation
2990 // compensation needed.
2991
2992 // Altium orientation 1 (UPWARDS) maps to KiCad SYM_ORIENT_90 (CCW). To compensate,
2993 // apply CW 90-degree rotation to text properties. Per SCH_FIELD::Rotate(), CW rotation
2994 // of horizontal text flips justification; CW rotation of vertical text does not.
2995 if( aSymbol.orientation == 1 )
2996 {
2997 if( isHorizontal )
2998 {
2999 aField->SetHorizJustify(
3000 static_cast<GR_TEXT_H_ALIGN_T>( -aField->GetHorizJustify() ) );
3001 }
3002
3003 aField->SetTextAngle( isHorizontal ? ANGLE_VERTICAL : ANGLE_HORIZONTAL );
3004 }
3005 // Altium orientation 2 (LEFTWARDS) maps to KiCad SYM_ORIENT_180 (two CCW rotations). The
3006 // transform [-1,0,0,-1] negates both X and Y, flipping horizontal justification. Apply
3007 // one correction for the full 180 degrees regardless of text angle.
3008 else if( aSymbol.orientation == 2 )
3009 {
3010 aField->SetHorizJustify(
3011 static_cast<GR_TEXT_H_ALIGN_T>( -aField->GetHorizJustify() ) );
3012 }
3013 // Altium orientation 3 (DOWNWARDS) maps to KiCad SYM_ORIENT_270 (CW). To compensate,
3014 // apply CCW 90-degree rotation to text properties. Per SCH_FIELD::Rotate(), CCW rotation
3015 // of vertical text flips justification; CCW rotation of horizontal text does not.
3016 else if( aSymbol.orientation == 3 )
3017 {
3018 if( !isHorizontal )
3019 {
3020 aField->SetHorizJustify(
3021 static_cast<GR_TEXT_H_ALIGN_T>( -aField->GetHorizJustify() ) );
3022 }
3023
3024 aField->SetTextAngle( isHorizontal ? ANGLE_VERTICAL : ANGLE_HORIZONTAL );
3025 }
3026
3027 // Mirror-Y in KiCad negates the X component of the bounding box, which effectively
3028 // flips horizontal justification. Compensate so the rendered text matches Altium.
3029 if( aSymbol.isMirrored )
3030 {
3031 aField->SetHorizJustify(
3032 static_cast<GR_TEXT_H_ALIGN_T>( -aField->GetHorizJustify() ) );
3033 }
3034}
3035
3036
3037// Altium text in symbols uses absolute orientation, but KiCad applies the symbol's transform
3038// to library body items via OrientAndMirrorSymbolItems at render time. This function pre-
3039// compensates the stored text angle and justification so that after the render-time transform,
3040// the final appearance matches the original Altium layout. Position is not adjusted here
3041// since GetRelativePosition already handles the positional component.
3043{
3044 int nRenderRotations = aSymbol.orientation % 4;
3045
3046 // Undo mirror first (reverse of render-time application order).
3047 // MirrorHorizontally on LAYER_DEVICE text flips H-justify when horizontal
3048 // and V-justify when vertical.
3049 if( aSymbol.isMirrored )
3050 {
3051 if( aText->GetTextAngle().IsHorizontal() )
3052 aText->FlipHJustify();
3053 else
3054 aText->SetVertJustify( static_cast<GR_TEXT_V_ALIGN_T>( -aText->GetVertJustify() ) );
3055 }
3056
3057 // The render pipeline applies Rotate90(false) N times; undo with N inverse rotations.
3058 for( int i = 0; i < nRenderRotations; i++ )
3059 aText->Rotate90( true );
3060}
3061
3062
3064{
3065 // No component assigned -> Put on sheet
3066 if( aOwnerindex == ALTIUM_COMPONENT_NONE )
3067 return true;
3068
3069 // For a template -> Put on sheet so we can resolve variables
3070 if( m_altiumTemplates.find( aOwnerindex ) != m_altiumTemplates.end() )
3071 return true;
3072
3073 return false;
3074}
3075
3076
3077void SCH_IO_ALTIUM::ParseLabel( const std::map<wxString, wxString>& aProperties,
3078 std::vector<LIB_SYMBOL*>& aSymbol, std::vector<int>& aFontSizes )
3079{
3080 ASCH_LABEL elem( aProperties );
3081
3082 // TODO: fill in replacements from variant, sheet and project
3083 static const std::map<wxString, wxString> variableMap = {
3084 { "SHEETNUMBER", "#" },
3085 { "SHEETTOTAL", "##" },
3086 { "TITLE", "TITLE" }, // including 1:1 maps makes it easier
3087 { "REVISION", "REVISION" }, // to see that the list is complete
3088 { "DATE", "ISSUE_DATE" },
3089 { "CURRENTDATE", "CURRENT_DATE" },
3090 { "CURRENTTIME", "CURRENT_TIME_LOCALE" },
3091 { "COMPANYNAME", "COMPANY" },
3092 { "DOCUMENTNAME", "FILENAME" },
3093 { "DOCUMENTFULLPATHANDNAME", "FILEPATH" },
3094 { "PROJECTNAME", "PROJECTNAME" },
3095 };
3096
3097 std::set<wxString> unmapped;
3098 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap, &unmapped );
3099
3100 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3101 {
3102 SCH_TEXT* textItem = new SCH_TEXT( elem.location + m_sheetOffset, kicadText );
3103
3104 // a name outside the map is Altium's own, KiCad cannot resolve it
3105 std::set<wxString> kicadNames;
3106
3107 for( const auto& [altiumName, kicadName] : variableMap )
3108 kicadNames.insert( kicadName );
3109
3110 for( const wxString& name : unmapped )
3111 {
3112 if( !kicadNames.count( name ) )
3113 m_sheetSpecialStrings.insert( name );
3114 }
3115
3116 SetTextPositioning( textItem, elem.justification, elem.orientation );
3117
3118 size_t fontId = static_cast<int>( elem.fontId );
3119
3120 if( m_altiumSheet && fontId > 0 && fontId <= m_altiumSheet->fonts.size() )
3121 {
3122 const ASCH_SHEET_FONT& font = m_altiumSheet->fonts.at( fontId - 1 );
3123 textItem->SetTextSize( { font.Size / 2, font.Size / 2 } );
3124
3125 // Must come after SetTextSize()
3126 textItem->SetBold( font.Bold );
3127 textItem->SetItalic( font.Italic );
3128 }
3129
3130 textItem->SetFlags( IS_NEW );
3131
3132 SCH_SCREEN* screen = getCurrentScreen();
3133 wxCHECK( screen, /* void */ );
3134
3135 screen->Append( textItem );
3136 }
3137 else
3138 {
3139 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3140 SCH_SYMBOL* schsym = nullptr;
3141
3142 if( !symbol )
3143 {
3144 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3145
3146 if( libSymbolIt == m_libSymbols.end() )
3147 {
3148 // TODO: e.g. can depend on Template (RECORD=39
3149 m_errorMessages.emplace( wxString::Format( wxT( "Label's owner (%d) not found." ), elem.ownerindex ),
3151 return;
3152 }
3153
3154 symbol = libSymbolIt->second;
3155 schsym = m_symbols.at( libSymbolIt->first );
3156 }
3157
3158 VECTOR2I pos = elem.location;
3159 SCH_TEXT* textItem = new SCH_TEXT( { 0, 0 }, kicadText, LAYER_DEVICE );
3160 symbol->AddDrawItem( textItem, false );
3161
3162 if( symbol->GetBodyStyleCount() > 1 )
3163 {
3164 if( !aSymbol.empty() )
3165 {
3166 textItem->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3167 }
3168 else
3169 {
3170 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3171
3172 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3173 textItem->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3174 }
3175 }
3176
3178 if( schsym )
3179 pos = GetRelativePosition( elem.location + m_sheetOffset, schsym );
3180
3181 textItem->SetPosition( pos );
3182 textItem->SetUnit( std::max( 0, elem.ownerpartid ) );
3183 SetTextPositioning( textItem, elem.justification, elem.orientation );
3184
3185 if( schsym )
3186 {
3187 const auto& altiumSymIt = m_altiumComponents.find( elem.ownerindex );
3188
3189 if( altiumSymIt != m_altiumComponents.end() )
3190 AdjustTextForSymbolOrientation( textItem, altiumSymIt->second );
3191 }
3192
3193 size_t fontId = elem.fontId;
3194
3195 if( m_altiumSheet && fontId > 0 && fontId <= m_altiumSheet->fonts.size() )
3196 {
3197 const ASCH_SHEET_FONT& font = m_altiumSheet->fonts.at( fontId - 1 );
3198 textItem->SetTextSize( { font.Size / 2, font.Size / 2 } );
3199
3200 // Must come after SetTextSize()
3201 textItem->SetBold( font.Bold );
3202 textItem->SetItalic( font.Italic );
3203 }
3204 else if( fontId > 0 && fontId <= aFontSizes.size() )
3205 {
3206 int size = aFontSizes[fontId - 1];
3207 textItem->SetTextSize( { size, size } );
3208 }
3209 }
3210}
3211
3212
3213void SCH_IO_ALTIUM::ParseTextFrame( const std::map<wxString, wxString>& aProperties,
3214 std::vector<LIB_SYMBOL*>& aSymbol, std::vector<int>& aFontSizes )
3215{
3216 ASCH_TEXT_FRAME elem( aProperties );
3217
3218 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3219 AddTextBox( &elem );
3220 else
3221 AddLibTextBox( &elem, aSymbol, aFontSizes );
3222}
3223
3224
3225void SCH_IO_ALTIUM::ParseNote( const std::map<wxString, wxString>& aProperties )
3226{
3227 ASCH_NOTE elem( aProperties );
3228 AddTextBox( static_cast<ASCH_TEXT_FRAME*>( &elem ) );
3229
3230 // TODO: need some sort of property system for storing author....
3231}
3232
3233
3235{
3236 SCH_TEXTBOX* textBox = new SCH_TEXTBOX();
3237
3238 VECTOR2I sheetTopRight = aElem->TopRight + m_sheetOffset;
3239 VECTOR2I sheetBottomLeft = aElem->BottomLeft +m_sheetOffset;
3240
3241 textBox->SetStart( sheetTopRight );
3242 textBox->SetEnd( sheetBottomLeft );
3243
3244 textBox->SetText( AltiumEscapeTextVars( aElem->Text ) );
3245
3246 textBox->SetFillColor( GetColorFromInt( aElem->AreaColor ) );
3247
3248 if( aElem->isSolid)
3250 else
3251 textBox->SetFilled( false );
3252
3253 if( aElem->ShowBorder )
3255 else
3257
3258 switch( aElem->Alignment )
3259 {
3260 default:
3263 break;
3266 break;
3269 break;
3270 }
3271
3272 size_t fontId = static_cast<int>( aElem->FontID );
3273
3274 if( m_altiumSheet && fontId > 0 && fontId <= m_altiumSheet->fonts.size() )
3275 {
3276 const ASCH_SHEET_FONT& font = m_altiumSheet->fonts.at( fontId - 1 );
3277 textBox->SetTextSize( { font.Size / 2, font.Size / 2 } );
3278
3279 // Must come after SetTextSize()
3280 textBox->SetBold( font.Bold );
3281 textBox->SetItalic( font.Italic );
3282 //textBox->SetFont( //how to set font, we have a font name here: ( font.fontname );
3283 }
3284
3285 textBox->SetFlags( IS_NEW );
3286
3287 SCH_SCREEN* screen = getCurrentScreen();
3288 wxCHECK( screen, /* void */ );
3289
3290 screen->Append( textBox );
3291}
3292
3293
3294void SCH_IO_ALTIUM::AddLibTextBox( const ASCH_TEXT_FRAME *aElem, std::vector<LIB_SYMBOL*>& aSymbol,
3295 std::vector<int>& aFontSizes )
3296{
3297 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3298 SCH_SYMBOL* schsym = nullptr;
3299
3300 if( !symbol )
3301 {
3302 const auto& libSymbolIt = m_libSymbols.find( aElem->ownerindex );
3303
3304 if( libSymbolIt == m_libSymbols.end() )
3305 {
3306 // TODO: e.g. can depend on Template (RECORD=39
3307 m_errorMessages.emplace( wxString::Format( wxT( "Label's owner (%d) not found." ), aElem->ownerindex ),
3309 return;
3310 }
3311
3312 symbol = libSymbolIt->second;
3313 schsym = m_symbols.at( libSymbolIt->first );
3314 }
3315
3316 SCH_TEXTBOX* textBox = new SCH_TEXTBOX( LAYER_DEVICE );
3317
3318 textBox->SetUnit( std::max( 0, aElem->ownerpartid ) );
3319 symbol->AddDrawItem( textBox, false );
3320
3321 if( symbol->GetBodyStyleCount() > 1 )
3322 {
3323 if( !aSymbol.empty() )
3324 {
3325 textBox->SetBodyStyle( aElem->ownerpartdisplaymode + 1 );
3326 }
3327 else
3328 {
3329 const auto& compIt = m_altiumComponents.find( aElem->ownerindex );
3330
3331 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3332 textBox->SetBodyStyle( aElem->ownerpartdisplaymode + 1 );
3333 }
3334 }
3335
3337 if( !schsym )
3338 {
3339 textBox->SetStart( aElem->TopRight );
3340 textBox->SetEnd( aElem->BottomLeft );
3341 }
3342 else
3343 {
3344 textBox->SetStart( GetRelativePosition( aElem->TopRight + m_sheetOffset, schsym ) );
3345 textBox->SetEnd( GetRelativePosition( aElem->BottomLeft + m_sheetOffset, schsym ) );
3346 }
3347
3348 textBox->SetText( AltiumEscapeTextVars( aElem->Text ) );
3349
3350 textBox->SetFillColor( GetColorFromInt( aElem->AreaColor ) );
3351
3352 if( aElem->isSolid)
3354 else
3355 textBox->SetFilled( false );
3356
3357 if( aElem->ShowBorder )
3359 else
3360 textBox->SetStroke( STROKE_PARAMS( -1 ) );
3361
3362 switch( aElem->Alignment )
3363 {
3364 default:
3367 break;
3370 break;
3373 break;
3374 }
3375
3376 if( aElem->FontID > 0 && aElem->FontID <= static_cast<int>( aFontSizes.size() ) )
3377 {
3378 int size = aFontSizes[aElem->FontID - 1];
3379 textBox->SetTextSize( { size, size } );
3380 }
3381}
3382
3383
3384void SCH_IO_ALTIUM::ParseBezier( const std::map<wxString, wxString>& aProperties,
3385 std::vector<LIB_SYMBOL*>& aSymbol )
3386{
3387 ASCH_BEZIER elem( aProperties );
3388
3389 if( elem.points.size() < 2 )
3390 {
3391 m_errorMessages.emplace( wxString::Format( _( "Bezier has %d control points. At least 2 are expected." ),
3392 static_cast<int>( elem.points.size() ) ),
3394 return;
3395 }
3396
3397 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3398 {
3399 SCH_SCREEN* currentScreen = getCurrentScreen();
3400 wxCHECK( currentScreen, /* void */ );
3401
3402 for( size_t i = 0; i + 1 < elem.points.size(); i += 3 )
3403 {
3404 if( i + 2 == elem.points.size() )
3405 {
3406 // special case: single line
3407 SCH_LINE* line = new SCH_LINE( elem.points.at( i ) + m_sheetOffset,
3409
3410 line->SetEndPoint( elem.points.at( i + 1 ) + m_sheetOffset );
3412
3413 line->SetFlags( IS_NEW );
3414
3415 currentScreen->Append( line );
3416 }
3417 else
3418 {
3419 // simulate Bezier using line segments
3420 std::vector<VECTOR2I> bezierPoints;
3421 std::vector<VECTOR2I> polyPoints;
3422
3423 for( size_t j = i; j < elem.points.size() && j < i + 4; j++ )
3424 bezierPoints.push_back( elem.points.at( j ) );
3425
3426 BEZIER_POLY converter( bezierPoints );
3427 converter.GetPoly( polyPoints );
3428
3429 for( size_t k = 0; k + 1 < polyPoints.size(); k++ )
3430 {
3431 SCH_LINE* line = new SCH_LINE( polyPoints.at( k ) + m_sheetOffset,
3433
3434 line->SetEndPoint( polyPoints.at( k + 1 ) + m_sheetOffset );
3436
3437 line->SetFlags( IS_NEW );
3438 currentScreen->Append( line );
3439 }
3440 }
3441 }
3442 }
3443 else
3444 {
3445 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3446 SCH_SYMBOL* schsym = nullptr;
3447
3448 if( !symbol )
3449 {
3450 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3451
3452 if( libSymbolIt == m_libSymbols.end() )
3453 {
3454 // TODO: e.g. can depend on Template (RECORD=39
3455 m_errorMessages.emplace( wxString::Format( wxT( "Bezier's owner (%d) not found." ),
3456 elem.ownerindex ),
3458 return;
3459 }
3460
3461 symbol = libSymbolIt->second;
3462 schsym = m_symbols.at( libSymbolIt->first );
3463 }
3464
3465 int bodyStyle = 0;
3466
3467 if( symbol->GetBodyStyleCount() > 1 )
3468 {
3469 if( !aSymbol.empty() )
3470 {
3471 bodyStyle = elem.ownerpartdisplaymode + 1;
3472 }
3473 else
3474 {
3475 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3476
3477 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3478 bodyStyle = elem.ownerpartdisplaymode + 1;
3479 }
3480 }
3481
3482 for( size_t i = 0; i + 1 < elem.points.size(); i += 3 )
3483 {
3484 if( i + 2 == elem.points.size() )
3485 {
3486 // special case: single line
3488 symbol->AddDrawItem( line, false );
3489
3490 line->SetUnit( std::max( 0, elem.ownerpartid ) );
3491
3492 if( bodyStyle > 0 )
3493 line->SetBodyStyle( bodyStyle );
3494
3495 for( size_t j = i; j < elem.points.size() && j < i + 2; j++ )
3496 {
3497 VECTOR2I pos = elem.points.at( j );
3498
3499 if( schsym )
3500 pos = GetRelativePosition( pos + m_sheetOffset, schsym );
3501
3502 line->AddPoint( pos );
3503 }
3504
3506 }
3507 else if( i + 3 == elem.points.size() )
3508 {
3509 // TODO: special case of a single line with an extra point?
3510 // I haven't a clue what this is all about, but the sample document we have in
3511 // https://gitlab.com/kicad/code/kicad/-/issues/8974 responds best by treating it
3512 // as another single line special case.
3514 symbol->AddDrawItem( line, false );
3515
3516 line->SetUnit( std::max( 0, elem.ownerpartid ) );
3517
3518 if( bodyStyle > 0 )
3519 line->SetBodyStyle( bodyStyle );
3520
3521 for( size_t j = i; j < elem.points.size() && j < i + 2; j++ )
3522 {
3523 VECTOR2I pos = elem.points.at( j );
3524
3525 if( schsym )
3526 pos = GetRelativePosition( pos + m_sheetOffset, schsym );
3527
3528 line->AddPoint( pos );
3529 }
3530
3532 }
3533 else
3534 {
3535 // Bezier always has exactly 4 control points
3537 symbol->AddDrawItem( bezier, false );
3538
3539 bezier->SetUnit( std::max( 0, elem.ownerpartid ) );
3540
3541 if( bodyStyle > 0 )
3542 bezier->SetBodyStyle( bodyStyle );
3543
3544 for( size_t j = i; j < elem.points.size() && j < i + 4; j++ )
3545 {
3546 VECTOR2I pos = elem.points.at( j );
3547
3548 if( schsym )
3549 pos = GetRelativePosition( pos + m_sheetOffset, schsym );
3550
3551 switch( j - i )
3552 {
3553 case 0: bezier->SetStart( pos ); break;
3554 case 1: bezier->SetBezierC1( pos ); break;
3555 case 2: bezier->SetBezierC2( pos ); break;
3556 case 3: bezier->SetEnd( pos ); break;
3557 default: break; // Can't get here but silence warnings
3558 }
3559 }
3560
3563 }
3564 }
3565 }
3566}
3567
3568
3569void SCH_IO_ALTIUM::ParsePolyline( const std::map<wxString, wxString>& aProperties,
3570 std::vector<LIB_SYMBOL*>& aSymbol )
3571{
3572 ASCH_POLYLINE elem( aProperties );
3573
3574 if( elem.Points.size() < 2 )
3575 return;
3576
3577 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3578 {
3579 SCH_SCREEN* screen = getCurrentScreen();
3580 wxCHECK( screen, /* void */ );
3581
3582 for( size_t i = 1; i < elem.Points.size(); i++ )
3583 {
3584 SCH_LINE* line = new SCH_LINE;
3585
3586 line->SetStartPoint( elem.Points[i - 1] + m_sheetOffset );
3587 line->SetEndPoint( elem.Points[i] + m_sheetOffset );
3588
3590 GetColorFromInt( elem.Color ) ) );
3591
3592 line->SetFlags( IS_NEW );
3593
3594 screen->Append( line );
3595 }
3596 }
3597 else
3598 {
3599 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3600 SCH_SYMBOL* schsym = nullptr;
3601
3602 if( !symbol )
3603 {
3604 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3605
3606 if( libSymbolIt == m_libSymbols.end() )
3607 {
3608 // TODO: e.g. can depend on Template (RECORD=39
3609 m_errorMessages.emplace( wxString::Format( wxT( "Polyline's owner (%d) not found." ),
3610 elem.ownerindex ),
3612 return;
3613 }
3614
3615 symbol = libSymbolIt->second;
3616 schsym = m_symbols.at( libSymbolIt->first );
3617 }
3618
3620 symbol->AddDrawItem( line, false );
3621
3622 line->SetUnit( std::max( 0, elem.ownerpartid ) );
3623
3624 if( symbol->GetBodyStyleCount() > 1 )
3625 {
3626 if( !aSymbol.empty() )
3627 {
3628 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3629 }
3630 else
3631 {
3632 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3633
3634 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3635 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3636 }
3637 }
3638
3639 for( VECTOR2I point : elem.Points )
3640 {
3641 if( schsym )
3642 point = GetRelativePosition( point + m_sheetOffset, schsym );
3643
3644 line->AddPoint( point );
3645 }
3646
3648 STROKE_PARAMS stroke = line->GetStroke();
3649 stroke.SetLineStyle( GetPlotDashType( elem.LineStyle ) );
3650
3651 line->SetStroke( stroke );
3652 }
3653}
3654
3655
3656void SCH_IO_ALTIUM::ParsePolygon( const std::map<wxString, wxString>& aProperties,
3657 std::vector<LIB_SYMBOL*>& aSymbol )
3658{
3659 ASCH_POLYGON elem( aProperties );
3660
3661 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3662 {
3663 SCH_SCREEN* screen = getCurrentScreen();
3664 wxCHECK( screen, /* void */ );
3665
3666 SCH_SHAPE* poly = new SCH_SHAPE( SHAPE_T::POLY );
3667
3668 for( VECTOR2I& point : elem.points )
3669 poly->AddPoint( point + m_sheetOffset );
3670 poly->AddPoint( elem.points.front() + m_sheetOffset );
3671
3672 SetSchShapeLine( elem, poly );
3673 SetSchShapeFillAndColor( elem, poly );
3674 poly->SetFlags( IS_NEW );
3675
3676 screen->Append( poly );
3677 }
3678 else
3679 {
3680 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3681 SCH_SYMBOL* schsym = nullptr;
3682
3683 if( !symbol )
3684 {
3685 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3686
3687 if( libSymbolIt == m_libSymbols.end() )
3688 {
3689 // TODO: e.g. can depend on Template (RECORD=39
3690 m_errorMessages.emplace( wxString::Format( wxT( "Polygon's owner (%d) not found." ),
3691 elem.ownerindex ),
3693 return;
3694 }
3695
3696 symbol = libSymbolIt->second;
3697 schsym = m_symbols.at( libSymbolIt->first );
3698 }
3699
3701
3702 symbol->AddDrawItem( line, false );
3703 line->SetUnit( std::max( 0, elem.ownerpartid ) );
3704
3705 if( symbol->GetBodyStyleCount() > 1 )
3706 {
3707 if( !aSymbol.empty() )
3708 {
3709 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3710 }
3711 else
3712 {
3713 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3714
3715 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3716 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3717 }
3718 }
3719
3720 for( VECTOR2I point : elem.points )
3721 {
3722 if( schsym )
3723 point = GetRelativePosition( point + m_sheetOffset, schsym );
3724
3725 line->AddPoint( point );
3726 }
3727
3728 VECTOR2I point = elem.points.front();
3729
3730 if( schsym )
3731 point = GetRelativePosition( elem.points.front() + m_sheetOffset, schsym );
3732
3733 line->AddPoint( point );
3734
3737
3738 if( line->GetFillColor() == line->GetStroke().GetColor()
3739 && line->GetFillMode() != FILL_T::NO_FILL )
3740 {
3741 STROKE_PARAMS stroke = line->GetStroke();
3742 stroke.SetWidth( -1 );
3743 line->SetStroke( stroke );
3744 }
3745 }
3746}
3747
3748
3749void SCH_IO_ALTIUM::ParseRoundRectangle( const std::map<wxString, wxString>& aProperties,
3750 std::vector<LIB_SYMBOL*>& aSymbol )
3751{
3752 ASCH_ROUND_RECTANGLE elem( aProperties );
3753
3754 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3755 {
3756 SCH_SCREEN* screen = getCurrentScreen();
3757 wxCHECK( screen, /* void */ );
3758
3759 // TODO: misses rounded edges
3761
3762 rect->SetPosition( elem.TopRight + m_sheetOffset );
3763 rect->SetEnd( elem.BottomLeft + m_sheetOffset );
3764 SetSchShapeLine( elem, rect );
3766 rect->SetFlags( IS_NEW );
3767
3768 screen->Append( rect );
3769 }
3770 else
3771 {
3772 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3773 SCH_SYMBOL* schsym = nullptr;
3774
3775 if( !symbol )
3776 {
3777 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3778
3779 if( libSymbolIt == m_libSymbols.end() )
3780 {
3781 // TODO: e.g. can depend on Template (RECORD=39
3782 m_errorMessages.emplace( wxString::Format( wxT( "Rounded rectangle's owner (%d) not found." ),
3783 elem.ownerindex ),
3785 return;
3786 }
3787
3788 symbol = libSymbolIt->second;
3789 schsym = m_symbols.at( libSymbolIt->first );
3790 }
3791
3792 SCH_SHAPE* rect = nullptr;
3793
3794 int width = std::abs( elem.TopRight.x - elem.BottomLeft.x );
3795 int height = std::abs( elem.TopRight.y - elem.BottomLeft.y );
3796
3797 // If it is a circle, make it a circle
3798 if( std::abs( elem.CornerRadius.x ) >= width / 2
3799 && std::abs( elem.CornerRadius.y ) >= height / 2 )
3800 {
3802
3803 VECTOR2I center = ( elem.TopRight + elem.BottomLeft ) / 2;
3804 int radius = std::min( width / 2, height / 2 );
3805
3806 if( schsym )
3808
3809 rect->SetPosition( center );
3810 rect->SetEnd( VECTOR2I( rect->GetPosition().x + radius, rect->GetPosition().y ) );
3811 }
3812 else
3813 {
3815
3816 if( !schsym )
3817 {
3818 rect->SetPosition( elem.TopRight );
3819 rect->SetEnd( elem.BottomLeft );
3820 }
3821 else
3822 {
3823 rect->SetPosition( GetRelativePosition( elem.TopRight + m_sheetOffset, schsym ) );
3824 rect->SetEnd( GetRelativePosition( elem.BottomLeft + m_sheetOffset, schsym ) );
3825 }
3826
3827 rect->Normalize();
3828 }
3829
3832
3833 symbol->AddDrawItem( rect, false );
3834 rect->SetUnit( std::max( 0, elem.ownerpartid ) );
3835
3836 if( symbol->GetBodyStyleCount() > 1 )
3837 {
3838 if( !aSymbol.empty() )
3839 {
3840 rect->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3841 }
3842 else
3843 {
3844 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3845
3846 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3847 rect->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
3848 }
3849 }
3850 }
3851}
3852
3853
3854void SCH_IO_ALTIUM::ParseArc( const std::map<wxString, wxString>& aProperties,
3855 std::vector<LIB_SYMBOL*>& aSymbol )
3856{
3857 ASCH_ARC elem( aProperties );
3858
3859 int arc_radius = elem.m_Radius;
3860 VECTOR2I center = elem.m_Center;
3861 EDA_ANGLE startAngle( elem.m_EndAngle, DEGREES_T );
3862 EDA_ANGLE endAngle( elem.m_StartAngle, DEGREES_T );
3863 VECTOR2I startOffset = KiROUND( arc_radius * startAngle.Cos(), -( arc_radius * startAngle.Sin() ) );
3864 VECTOR2I endOffset = KiROUND( arc_radius * endAngle.Cos(), -( arc_radius * endAngle.Sin() ) );
3865
3866 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3867 {
3868 SCH_SCREEN* currentScreen = getCurrentScreen();
3869 wxCHECK( currentScreen, /* void */ );
3870
3871 if( elem.m_StartAngle == 0 && ( elem.m_EndAngle == 0 || elem.m_EndAngle == 360 ) )
3872 {
3874
3875 circle->SetPosition( elem.m_Center + m_sheetOffset );
3876 circle->SetEnd( circle->GetPosition() + VECTOR2I( arc_radius, 0 ) );
3877
3878 SetSchShapeLine( elem, circle );
3880
3881 currentScreen->Append( circle );
3882 }
3883 else
3884 {
3885 SCH_SHAPE* arc = new SCH_SHAPE( SHAPE_T::ARC );
3886
3887 arc->SetCenter( elem.m_Center + m_sheetOffset );
3888 arc->SetStart( elem.m_Center + startOffset + m_sheetOffset );
3889 arc->SetEnd( elem.m_Center + endOffset + m_sheetOffset );
3890
3891 SetSchShapeLine( elem, arc );
3892 SetSchShapeFillAndColor( elem, arc );
3893
3894 currentScreen->Append( arc );
3895 }
3896 }
3897 else
3898 {
3899 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
3900 SCH_SYMBOL* schsym = nullptr;
3901
3902 if( !symbol )
3903 {
3904 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
3905
3906 if( libSymbolIt == m_libSymbols.end() )
3907 {
3908 // TODO: e.g. can depend on Template (RECORD=39
3909 m_errorMessages.emplace( wxString::Format( wxT( "Arc's owner (%d) not found." ), elem.ownerindex ),
3911 return;
3912 }
3913
3914 symbol = libSymbolIt->second;
3915 schsym = m_symbols.at( libSymbolIt->first );
3916 }
3917
3918 int bodyStyle = 0;
3919
3920 if( symbol->GetBodyStyleCount() > 1 )
3921 {
3922 if( !aSymbol.empty() )
3923 {
3924 bodyStyle = elem.ownerpartdisplaymode + 1;
3925 }
3926 else
3927 {
3928 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
3929
3930 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
3931 bodyStyle = elem.ownerpartdisplaymode + 1;
3932 }
3933 }
3934
3935 if( elem.m_StartAngle == 0 && ( elem.m_EndAngle == 0 || elem.m_EndAngle == 360 ) )
3936 {
3938 symbol->AddDrawItem( circle, false );
3939
3940 circle->SetUnit( std::max( 0, elem.ownerpartid ) );
3941
3942 if( bodyStyle > 0 )
3943 circle->SetBodyStyle( bodyStyle );
3944
3945 if( schsym )
3947
3948 circle->SetPosition( center );
3949
3950 circle->SetEnd( circle->GetPosition() + VECTOR2I( arc_radius, 0 ) );
3953 }
3954 else
3955 {
3957 symbol->AddDrawItem( arc, false );
3958 arc->SetUnit( std::max( 0, elem.ownerpartid ) );
3959
3960 if( bodyStyle > 0 )
3961 arc->SetBodyStyle( bodyStyle );
3962
3963 if( schsym )
3964 {
3966 startOffset = GetRelativePosition( elem.m_Center + startOffset + m_sheetOffset, schsym )
3967 - center;
3968 endOffset = GetRelativePosition( elem.m_Center + endOffset + m_sheetOffset, schsym )
3969 - center;
3970 }
3971
3972 arc->SetCenter( center );
3973 arc->SetStart( center + startOffset );
3974 arc->SetEnd( center + endOffset );
3975
3978 }
3979 }
3980}
3981
3982
3983void SCH_IO_ALTIUM::ParseEllipticalArc( const std::map<wxString, wxString>& aProperties,
3984 std::vector<LIB_SYMBOL*>& aSymbol )
3985{
3986 ASCH_ARC elem( aProperties );
3987
3988 if( elem.m_Radius == elem.m_SecondaryRadius && elem.m_StartAngle == 0
3989 && ( elem.m_EndAngle == 0 || elem.m_EndAngle == 360 ) )
3990 {
3991 ParseCircle( aProperties, aSymbol );
3992 return;
3993 }
3994
3995 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
3996 {
3997 SCH_SCREEN* currentScreen = getCurrentScreen();
3998 wxCHECK( currentScreen, /* void */ );
3999
4000 ELLIPSE<int> ellipse( elem.m_Center + m_sheetOffset, elem.m_Radius,
4003 EDA_ANGLE( elem.m_EndAngle, DEGREES_T ) );
4004 std::vector<BEZIER<int>> beziers;
4005
4006 TransformEllipseToBeziers( ellipse, beziers );
4007
4008 for( const BEZIER<int>& bezier : beziers )
4009 {
4010 SCH_SHAPE* schbezier = new SCH_SHAPE( SHAPE_T::BEZIER );
4011 schbezier->SetStart( bezier.Start );
4012 schbezier->SetBezierC1( bezier.C1 );
4013 schbezier->SetBezierC2( bezier.C2 );
4014 schbezier->SetEnd( bezier.End );
4015 schbezier->SetStroke( STROKE_PARAMS( elem.LineWidth, LINE_STYLE::SOLID ) );
4017
4018 currentScreen->Append( schbezier );
4019 }
4020 }
4021 else
4022 {
4023 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4024 SCH_SYMBOL* schsym = nullptr;
4025
4026 if( !symbol )
4027 {
4028 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4029
4030 if( libSymbolIt == m_libSymbols.end() )
4031 {
4032 // TODO: e.g. can depend on Template (RECORD=39
4033 m_errorMessages.emplace( wxString::Format( wxT( "Elliptical Arc's owner (%d) not found." ),
4034 elem.ownerindex ),
4036 return;
4037 }
4038
4039 symbol = libSymbolIt->second;
4040 schsym = m_symbols.at( libSymbolIt->first );
4041 }
4042
4043 int bodyStyle = 0;
4044
4045 if( symbol->GetBodyStyleCount() > 1 )
4046 {
4047 if( !aSymbol.empty() )
4048 {
4049 bodyStyle = elem.ownerpartdisplaymode + 1;
4050 }
4051 else
4052 {
4053 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4054
4055 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4056 bodyStyle = elem.ownerpartdisplaymode + 1;
4057 }
4058 }
4059
4060 ELLIPSE<int> ellipse( elem.m_Center, elem.m_Radius,
4063 EDA_ANGLE( elem.m_EndAngle, DEGREES_T ) );
4064 std::vector<BEZIER<int>> beziers;
4065
4066 TransformEllipseToBeziers( ellipse, beziers );
4067
4068 for( const BEZIER<int>& bezier : beziers )
4069 {
4070 SCH_SHAPE* schbezier = new SCH_SHAPE( SHAPE_T::BEZIER, LAYER_DEVICE );
4071 symbol->AddDrawItem( schbezier, false );
4072
4073 schbezier->SetUnit( std::max( 0, elem.ownerpartid ) );
4074
4075 if( bodyStyle > 0 )
4076 schbezier->SetBodyStyle( bodyStyle );
4077
4078 if( schsym )
4079 {
4080 schbezier->SetStart( GetRelativePosition( bezier.Start + m_sheetOffset, schsym ) );
4081 schbezier->SetBezierC1( GetRelativePosition( bezier.C1 + m_sheetOffset, schsym ) );
4082 schbezier->SetBezierC2( GetRelativePosition( bezier.C2 + m_sheetOffset, schsym ) );
4083 schbezier->SetEnd( GetRelativePosition( bezier.End + m_sheetOffset, schsym ) );
4084 }
4085 else
4086 {
4087 schbezier->SetStart( bezier.Start );
4088 schbezier->SetBezierC1( bezier.C1 );
4089 schbezier->SetBezierC2( bezier.C2 );
4090 schbezier->SetEnd( bezier.End );
4091 }
4092
4095 }
4096 }
4097}
4098
4099
4100void SCH_IO_ALTIUM::ParsePieChart( const std::map<wxString, wxString>& aProperties,
4101 std::vector<LIB_SYMBOL*>& aSymbol )
4102{
4103 ParseArc( aProperties, aSymbol );
4104
4105 ASCH_PIECHART elem( aProperties );
4106
4107 int arc_radius = elem.m_Radius;
4108 VECTOR2I center = elem.m_Center;
4109 EDA_ANGLE startAngle( elem.m_EndAngle, DEGREES_T );
4110 EDA_ANGLE endAngle( elem.m_StartAngle, DEGREES_T );
4111 VECTOR2I startOffset = KiROUND( arc_radius * startAngle.Cos(), -( arc_radius * startAngle.Sin() ) );
4112 VECTOR2I endOffset = KiROUND( arc_radius * endAngle.Cos(), -( arc_radius * endAngle.Sin() ) );
4113
4114 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
4115 {
4116 SCH_SCREEN* screen = getCurrentScreen();
4117 wxCHECK( screen, /* void */ );
4118
4119 // close polygon
4121 line->SetEndPoint( center + startOffset + m_sheetOffset );
4123
4124 line->SetFlags( IS_NEW );
4125 screen->Append( line );
4126
4128 line->SetEndPoint( center + endOffset + m_sheetOffset );
4130
4131 line->SetFlags( IS_NEW );
4132 screen->Append( line );
4133 }
4134 else
4135 {
4136 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4137 SCH_SYMBOL* schsym = nullptr;
4138
4139 if( !symbol )
4140 {
4141 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4142
4143 if( libSymbolIt == m_libSymbols.end() )
4144 {
4145 // TODO: e.g. can depend on Template (RECORD=39
4146 m_errorMessages.emplace( wxString::Format( wxT( "Piechart's owner (%d) not found." ),
4147 elem.ownerindex ),
4149 return;
4150 }
4151
4152 symbol = libSymbolIt->second;
4153 schsym = m_symbols.at( libSymbolIt->first );
4154 }
4155
4157 symbol->AddDrawItem( line, false );
4158
4159 line->SetUnit( std::max( 0, elem.ownerpartid ) );
4160
4161 if( symbol->GetBodyStyleCount() > 1 )
4162 {
4163 if( !aSymbol.empty() )
4164 {
4165 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4166 }
4167 else
4168 {
4169 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4170
4171 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4172 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4173 }
4174 }
4175
4176 if( !schsym )
4177 {
4178 line->AddPoint( center + startOffset );
4179 line->AddPoint( center );
4180 line->AddPoint( center + endOffset );
4181 }
4182 else
4183 {
4184 line->AddPoint( GetRelativePosition( center + startOffset + m_sheetOffset, schsym ) );
4185 line->AddPoint( GetRelativePosition( center + m_sheetOffset, schsym ) );
4186 line->AddPoint( GetRelativePosition( center + endOffset + m_sheetOffset, schsym ) );
4187 }
4188
4190 }
4191}
4192
4193
4194void SCH_IO_ALTIUM::ParseEllipse( const std::map<wxString, wxString>& aProperties,
4195 std::vector<LIB_SYMBOL*>& aSymbol )
4196{
4197 ASCH_ELLIPSE elem( aProperties );
4198
4199 if( elem.Radius == elem.SecondaryRadius )
4200 {
4201 ParseCircle( aProperties, aSymbol );
4202 return;
4203 }
4204
4205 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
4206 {
4207 SCH_SCREEN* screen = getCurrentScreen();
4208 wxCHECK( screen, /* void */ );
4209
4210 COLOR4D fillColor = GetColorFromInt( elem.AreaColor );
4211
4212 if( elem.IsTransparent )
4213 fillColor = fillColor.WithAlpha( 0.5 );
4214
4216
4217 ELLIPSE<int> ellipse( elem.Center + m_sheetOffset, elem.Radius,
4218 KiROUND( elem.SecondaryRadius ), ANGLE_0 );
4219
4220 std::vector<BEZIER<int>> beziers;
4221 std::vector<VECTOR2I> polyPoints;
4222
4223 TransformEllipseToBeziers( ellipse, beziers );
4224
4225 for( const BEZIER<int>& bezier : beziers )
4226 {
4227 SCH_SHAPE* schbezier = new SCH_SHAPE( SHAPE_T::BEZIER );
4228 schbezier->SetStart( bezier.Start );
4229 schbezier->SetBezierC1( bezier.C1 );
4230 schbezier->SetBezierC2( bezier.C2 );
4231 schbezier->SetEnd( bezier.End );
4232 schbezier->SetStroke( STROKE_PARAMS( elem.LineWidth, LINE_STYLE::SOLID ) );
4233 schbezier->SetFillColor( fillColor );
4234 schbezier->SetFillMode( fillMode );
4235
4237 screen->Append( schbezier );
4238
4239 polyPoints.push_back( bezier.Start );
4240 }
4241
4242 if( fillMode != FILL_T::NO_FILL )
4243 {
4244 SCH_SHAPE* schpoly = new SCH_SHAPE( SHAPE_T::POLY );
4245 schpoly->SetFillColor( fillColor );
4246 schpoly->SetFillMode( fillMode );
4247 schpoly->SetWidth( -1 );
4248
4249 for( const VECTOR2I& point : polyPoints )
4250 schpoly->AddPoint( point );
4251
4252 schpoly->AddPoint( polyPoints[0] );
4253
4254 screen->Append( schpoly );
4255 }
4256 }
4257 else
4258 {
4259 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4260 SCH_SYMBOL* schsym = nullptr;
4261
4262 if( !symbol )
4263 {
4264 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4265
4266 if( libSymbolIt == m_libSymbols.end() )
4267 {
4268 // TODO: e.g. can depend on Template (RECORD=39
4269 m_errorMessages.emplace( wxString::Format( wxT( "Ellipse's owner (%d) not found." ), elem.ownerindex ),
4271 return;
4272 }
4273
4274 symbol = libSymbolIt->second;
4275 schsym = m_symbols.at( libSymbolIt->first );
4276 }
4277
4278 int bodyStyle = 0;
4279
4280 if( symbol->GetBodyStyleCount() > 1 )
4281 {
4282 if( !aSymbol.empty() )
4283 {
4284 bodyStyle = elem.ownerpartdisplaymode + 1;
4285 }
4286 else
4287 {
4288 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4289
4290 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4291 bodyStyle = elem.ownerpartdisplaymode + 1;
4292 }
4293 }
4294
4295 ELLIPSE<int> ellipse( elem.Center, elem.Radius, KiROUND( elem.SecondaryRadius ),
4296 ANGLE_0 );
4297
4298 std::vector<BEZIER<int>> beziers;
4299 std::vector<VECTOR2I> polyPoints;
4300
4301 TransformEllipseToBeziers( ellipse, beziers );
4302
4303 for( const BEZIER<int>& bezier : beziers )
4304 {
4305 SCH_SHAPE* libbezier = new SCH_SHAPE( SHAPE_T::BEZIER, LAYER_DEVICE );
4306 symbol->AddDrawItem( libbezier, false );
4307 libbezier->SetUnit( std::max( 0, elem.ownerpartid ) );
4308
4309 if( bodyStyle > 0 )
4310 libbezier->SetBodyStyle( bodyStyle );
4311
4312 if( !schsym )
4313 {
4314 libbezier->SetStart( bezier.Start );
4315 libbezier->SetBezierC1( bezier.C1 );
4316 libbezier->SetBezierC2( bezier.C2 );
4317 libbezier->SetEnd( bezier.End );
4318 }
4319 else
4320 {
4321 libbezier->SetStart( GetRelativePosition( bezier.Start + m_sheetOffset, schsym ) );
4322 libbezier->SetBezierC1( GetRelativePosition( bezier.C1 + m_sheetOffset, schsym ) );
4323 libbezier->SetBezierC2( GetRelativePosition( bezier.C2 + m_sheetOffset, schsym ) );
4324 libbezier->SetEnd( GetRelativePosition( bezier.End + m_sheetOffset, schsym ) );
4325 }
4326
4327 SetLibShapeLine( elem, libbezier, ALTIUM_SCH_RECORD::ELLIPSE );
4330
4331 polyPoints.push_back( libbezier->GetStart() );
4332 }
4333
4334 // A series of beziers won't fill the center, so if this is meant to be fully filled,
4335 // Add a polygon to fill the center
4336 if( elem.IsSolid )
4337 {
4338 SCH_SHAPE* libline = new SCH_SHAPE( SHAPE_T::POLY, LAYER_DEVICE );
4339 symbol->AddDrawItem( libline, false );
4340 libline->SetUnit( std::max( 0, elem.ownerpartid ) );
4341
4342 if( bodyStyle > 0 )
4343 libline->SetBodyStyle( bodyStyle );
4344
4345 for( const VECTOR2I& point : polyPoints )
4346 libline->AddPoint( point );
4347
4348 libline->AddPoint( polyPoints[0] );
4349
4350 libline->SetWidth( -1 );
4352 }
4353 }
4354}
4355
4356
4357void SCH_IO_ALTIUM::ParseCircle( const std::map<wxString, wxString>& aProperties,
4358 std::vector<LIB_SYMBOL*>& aSymbol )
4359{
4360 ASCH_ELLIPSE elem( aProperties );
4361
4362 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
4363 {
4364 SCH_SCREEN* screen = getCurrentScreen();
4365 wxCHECK( screen, /* void */ );
4366
4368
4369 circle->SetPosition( elem.Center + m_sheetOffset );
4370 circle->SetEnd( circle->GetPosition() + VECTOR2I( elem.Radius, 0 ) );
4371 circle->SetStroke( STROKE_PARAMS( 1, LINE_STYLE::SOLID ) );
4372
4373 circle->SetFillColor( GetColorFromInt( elem.AreaColor ) );
4374
4375 if( elem.IsSolid )
4376 circle->SetFillMode( FILL_T::FILLED_WITH_COLOR );
4377 else
4378 circle->SetFilled( false );
4379
4380 screen->Append( circle );
4381 }
4382 else
4383 {
4384 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4385 SCH_SYMBOL* schsym = nullptr;
4386
4387 if( !symbol )
4388 {
4389 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4390
4391 if( libSymbolIt == m_libSymbols.end() )
4392 {
4393 // TODO: e.g. can depend on Template (RECORD=39
4394 m_errorMessages.emplace( wxString::Format( wxT( "Ellipse's owner (%d) not found." ), elem.ownerindex ),
4396 return;
4397 }
4398
4399 symbol = libSymbolIt->second;
4400 schsym = m_symbols.at( libSymbolIt->first );
4401 }
4402
4403 VECTOR2I center = elem.Center;
4405 symbol->AddDrawItem( circle, false );
4406
4407 circle->SetUnit( std::max( 0, elem.ownerpartid ) );
4408
4409 if( symbol->GetBodyStyleCount() > 1 )
4410 {
4411 if( !aSymbol.empty() )
4412 {
4413 circle->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4414 }
4415 else
4416 {
4417 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4418
4419 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4420 circle->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4421 }
4422 }
4423
4424 if( schsym )
4426
4427 circle->SetPosition( center );
4428 circle->SetEnd( circle->GetPosition() + VECTOR2I( elem.Radius, 0 ) );
4429
4432 }
4433}
4434
4435
4436void SCH_IO_ALTIUM::ParseLine( const std::map<wxString, wxString>& aProperties,
4437 std::vector<LIB_SYMBOL*>& aSymbol )
4438{
4439 ASCH_LINE elem( aProperties );
4440
4441 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
4442 {
4443 SCH_SCREEN* screen = getCurrentScreen();
4444 wxCHECK( screen, /* void */ );
4445
4446 // close polygon
4448 line->SetEndPoint( elem.point2 + m_sheetOffset );
4450 GetColorFromInt( elem.Color ) ) );
4451
4452 line->SetFlags( IS_NEW );
4453 screen->Append( line );
4454 }
4455 else
4456 {
4457 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4458 SCH_SYMBOL* schsym = nullptr;
4459
4460 if( !symbol )
4461 {
4462 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4463
4464 if( libSymbolIt == m_libSymbols.end() )
4465 {
4466 // TODO: e.g. can depend on Template (RECORD=39
4467 m_errorMessages.emplace( wxString::Format( wxT( "Line's owner (%d) not found." ), elem.ownerindex ),
4469 return;
4470 }
4471
4472 symbol = libSymbolIt->second;
4473 schsym = m_symbols.at( libSymbolIt->first );
4474 }
4475
4477 symbol->AddDrawItem( line, false );
4478
4479 line->SetUnit( std::max( 0, elem.ownerpartid ) );
4480
4481 if( symbol->GetBodyStyleCount() > 1 )
4482 {
4483 if( !aSymbol.empty() )
4484 {
4485 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4486 }
4487 else
4488 {
4489 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4490
4491 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4492 line->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4493 }
4494 }
4495
4496 if( !schsym )
4497 {
4498 line->AddPoint( elem.point1 );
4499 line->AddPoint( elem.point2 );
4500 }
4501 else
4502 {
4503 line->AddPoint( GetRelativePosition( elem.point1 + m_sheetOffset, schsym ) );
4504 line->AddPoint( GetRelativePosition( elem.point2 + m_sheetOffset, schsym ) );
4505 }
4506
4508 line->SetLineStyle( GetPlotDashType( elem.LineStyle ) );
4509 }
4510}
4511
4512
4513void SCH_IO_ALTIUM::ParseSignalHarness( const std::map<wxString, wxString>& aProperties )
4514{
4515 ASCH_SIGNAL_HARNESS elem( aProperties );
4516
4517 if( ShouldPutItemOnSheet( elem.ownerindex ) )
4518 {
4519 SCH_SCREEN* screen = getCurrentScreen();
4520 wxCHECK( screen, /* void */ );
4521
4522 for( size_t ii = 0; ii < elem.points.size() - 1; ii++ )
4523 {
4525 line->SetEndPoint( elem.points[ii + 1] + m_sheetOffset );
4527
4528 line->SetFlags( IS_NEW );
4529 screen->Append( line );
4530 }
4531 }
4532 else
4533 {
4534 // No clue if this situation can ever exist
4535 m_errorMessages.emplace( wxT( "Signal harness, belonging to the part is not currently supported." ),
4537 }
4538}
4539
4540
4541void SCH_IO_ALTIUM::ParseHarnessConnector( int aIndex, const std::map<wxString,
4542 wxString>& aProperties )
4543{
4544 ASCH_HARNESS_CONNECTOR elem( aProperties );
4545
4546 if( ShouldPutItemOnSheet( elem.ownerindex ) )
4547 {
4549 auto [it, _] = m_altiumHarnesses.insert( { m_harnessEntryParent, HARNESS()} );
4550
4551 HARNESS& harness = it->second;
4552 HARNESS::HARNESS_PORT& port = harness.m_entry;
4553 harness.m_location = elem.m_location + m_sheetOffset;
4554 harness.m_size = elem.m_size;
4555
4556 VECTOR2I pos = elem.m_location + m_sheetOffset;
4557 VECTOR2I size = elem.m_size;
4558
4559 switch( elem.m_harnessConnectorSide )
4560 {
4561 default:
4563 port.m_location = { pos.x, pos.y + elem.m_primaryConnectionPosition };
4564 break;
4566 port.m_location = { pos.x + size.x, pos.y + elem.m_primaryConnectionPosition };
4567 break;
4569 port.m_location = { pos.x + elem.m_primaryConnectionPosition, pos.y };
4570 break;
4572 port.m_location = { pos.x + elem.m_primaryConnectionPosition, pos.y + size.y };
4573 break;
4574 }
4575 }
4576 else
4577 {
4578 // I have no clue if this situation can ever exist
4579 m_errorMessages.emplace( wxT( "Harness connector, belonging to the part is not currently supported." ),
4581 }
4582}
4583
4584
4585void SCH_IO_ALTIUM::ParseHarnessEntry( const std::map<wxString, wxString>& aProperties )
4586{
4587 ASCH_HARNESS_ENTRY elem( aProperties );
4588
4589 auto harnessIt = m_altiumHarnesses.find( m_harnessEntryParent );
4590
4591 if( harnessIt == m_altiumHarnesses.end() )
4592 {
4593 m_errorMessages.emplace( wxString::Format( wxT( "Harness entry's parent (%d) not found." ),
4596 return;
4597 }
4598
4599 HARNESS& harness = harnessIt->second;
4601 port.m_name = elem.Name;
4602 port.m_harnessConnectorSide = elem.Side;
4604
4605 VECTOR2I pos = harness.m_location;
4606 VECTOR2I size = harness.m_size;
4607 int quadrant = 1;
4608
4609 switch( elem.Side )
4610 {
4611 default:
4613 port.m_location = { pos.x, pos.y + elem.DistanceFromTop };
4614 break;
4616 quadrant = 4;
4617 port.m_location = { pos.x + size.x, pos.y + elem.DistanceFromTop };
4618 break;
4620 port.m_location = { pos.x + elem.DistanceFromTop, pos.y };
4621 break;
4623 quadrant = 2;
4624 port.m_location = { pos.x + elem.DistanceFromTop, pos.y + size.y };
4625 break;
4626 }
4627
4628
4629 SCH_SCREEN* screen = getCurrentScreen();
4630 wxCHECK( screen, /* void */ );
4631
4632 SCH_BUS_WIRE_ENTRY* entry = new SCH_BUS_WIRE_ENTRY( port.m_location, quadrant );
4633 port.m_entryLocation = entry->GetPosition() + entry->GetSize();
4634 entry->SetFlags( IS_NEW );
4635 screen->Append( entry );
4636 harness.m_ports.emplace_back( port );
4637}
4638
4639
4640void SCH_IO_ALTIUM::ParseHarnessType( const std::map<wxString, wxString>& aProperties )
4641{
4642 ASCH_HARNESS_TYPE elem( aProperties );
4643
4644 auto harnessIt = m_altiumHarnesses.find( m_harnessEntryParent );
4645
4646 if( harnessIt == m_altiumHarnesses.end() )
4647 {
4648 m_errorMessages.emplace( wxString::Format( wxT( "Harness type's parent (%d) not found." ),
4651 return;
4652 }
4653
4654 // TODO: fill in replacements from variant, sheet and project
4655 static const std::map<wxString, wxString> variableMap = {
4656 };
4657
4658 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.Text, variableMap );
4659
4660 HARNESS& harness = harnessIt->second;
4661 harness.m_name = kicadText;
4662}
4663
4664
4665void SCH_IO_ALTIUM::ParseRectangle( const std::map<wxString, wxString>& aProperties,
4666 std::vector<LIB_SYMBOL*>& aSymbol )
4667{
4668 ASCH_RECTANGLE elem( aProperties );
4669
4670 VECTOR2I sheetTopRight = elem.TopRight + m_sheetOffset;
4671 VECTOR2I sheetBottomLeft = elem.BottomLeft + m_sheetOffset;
4672
4673 if( aSymbol.empty() && ShouldPutItemOnSheet( elem.ownerindex ) )
4674 {
4675 SCH_SCREEN* screen = getCurrentScreen();
4676 wxCHECK( screen, /* void */ );
4677
4679
4680 rect->SetPosition( sheetTopRight );
4681 rect->SetEnd( sheetBottomLeft );
4682 SetSchShapeLine( elem, rect );
4684 rect->SetFlags( IS_NEW );
4685
4686 screen->Append( rect );
4687 }
4688 else
4689 {
4690 LIB_SYMBOL* symbol = aSymbol.empty() ? nullptr : aSymbol[0];
4691 SCH_SYMBOL* schsym = nullptr;
4692
4693 if( !symbol )
4694 {
4695 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
4696
4697 if( libSymbolIt == m_libSymbols.end() )
4698 {
4699 // TODO: e.g. can depend on Template (RECORD=39
4700 m_errorMessages.emplace( wxString::Format( wxT( "Rectangle's owner (%d) not found." ),
4701 elem.ownerindex ),
4703 return;
4704 }
4705
4706 symbol = libSymbolIt->second;
4707 schsym = m_symbols.at( libSymbolIt->first );
4708 }
4709
4711 symbol->AddDrawItem( rect, false );
4712
4713 rect->SetUnit( std::max( 0, elem.ownerpartid ) );
4714
4715 if( symbol->GetBodyStyleCount() > 1 )
4716 {
4717 if( !aSymbol.empty() )
4718 {
4719 rect->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4720 }
4721 else
4722 {
4723 const auto& compIt = m_altiumComponents.find( elem.ownerindex );
4724
4725 if( compIt != m_altiumComponents.end() && compIt->second.displaymodecount > 1 )
4726 rect->SetBodyStyle( elem.ownerpartdisplaymode + 1 );
4727 }
4728 }
4729
4730 if( !schsym )
4731 {
4732 rect->SetPosition( sheetTopRight );
4733 rect->SetEnd( sheetBottomLeft );
4734 }
4735 else
4736 {
4737 rect->SetPosition( GetRelativePosition( sheetTopRight, schsym ) );
4738 rect->SetEnd( GetRelativePosition( sheetBottomLeft, schsym ) );
4739 }
4740
4743 }
4744}
4745
4746
4747void SCH_IO_ALTIUM::ParseSheetSymbol( int aIndex, const std::map<wxString, wxString>& aProperties )
4748{
4749 ASCH_SHEET_SYMBOL elem( aProperties );
4750
4751 SCH_SHEET* sheet = new SCH_SHEET( getCurrentSheet(), elem.location + m_sheetOffset, elem.size );
4752
4753 sheet->SetBorderColor( GetColorFromInt( elem.color ) );
4754
4755 if( elem.isSolid )
4757
4758 sheet->SetFlags( IS_NEW );
4759
4760 SCH_SCREEN* currentScreen = getCurrentScreen();
4761 wxCHECK( currentScreen, /* void */ );
4762 currentScreen->Append( sheet );
4763
4764 SCH_SHEET_PATH sheetpath = m_sheetPath;
4765 sheetpath.push_back( sheet );
4766
4767 // We'll update later if we find a pageNumber record for it.
4768 sheetpath.SetPageNumber( "#" );
4769
4770 SCH_SCREEN* rootScreen = m_rootSheet->GetScreen();
4771 wxCHECK( rootScreen, /* void */ );
4772
4773 SCH_SHEET_INSTANCE sheetInstance;
4774
4775 sheetInstance.m_Path = sheetpath.Path();
4776 sheetInstance.m_PageNumber = wxT( "#" );
4777
4778 rootScreen->m_sheetInstances.emplace_back( sheetInstance );
4779 m_sheets.insert( { aIndex, sheet } );
4780}
4781
4782
4783void SCH_IO_ALTIUM::ParseSheetEntry( const std::map<wxString, wxString>& aProperties )
4784{
4785 ASCH_SHEET_ENTRY elem( aProperties );
4786
4787 const auto& sheetIt = m_sheets.find( elem.ownerindex );
4788
4789 if( sheetIt == m_sheets.end() )
4790 {
4791 m_errorMessages.emplace( wxString::Format( wxT( "Sheet entry's owner (%d) not found." ), elem.ownerindex ),
4793 return;
4794 }
4795
4796 SCH_SHEET_PIN* sheetPin = new SCH_SHEET_PIN( sheetIt->second );
4797 sheetIt->second->AddPin( sheetPin );
4798
4799 wxString pinName = elem.name;
4800
4801 if( !elem.harnessType.IsEmpty() )
4802 pinName += wxT( "{" ) + elem.harnessType + wxT( "}" );
4803
4804 sheetPin->SetText( pinName );
4806 //sheetPin->SetSpinStyle( getSpinStyle( term.OrientAngle, false ) );
4807 //sheetPin->SetPosition( getKiCadPoint( term.Position ) );
4808
4809 VECTOR2I pos = sheetIt->second->GetPosition();
4810 VECTOR2I size = sheetIt->second->GetSize();
4811
4812 switch( elem.side )
4813 {
4814 default:
4816 sheetPin->SetPosition( { pos.x, pos.y + elem.distanceFromTop } );
4817 sheetPin->SetSpinStyle( SPIN_STYLE::LEFT );
4818 sheetPin->SetSide( SHEET_SIDE::LEFT );
4819 break;
4820
4822 sheetPin->SetPosition( { pos.x + size.x, pos.y + elem.distanceFromTop } );
4823 sheetPin->SetSpinStyle( SPIN_STYLE::RIGHT );
4824 sheetPin->SetSide( SHEET_SIDE::RIGHT );
4825 break;
4826
4828 sheetPin->SetPosition( { pos.x + elem.distanceFromTop, pos.y } );
4829 sheetPin->SetSpinStyle( SPIN_STYLE::UP );
4830 sheetPin->SetSide( SHEET_SIDE::TOP );
4831 break;
4832
4834 sheetPin->SetPosition( { pos.x + elem.distanceFromTop, pos.y + size.y } );
4835 sheetPin->SetSpinStyle( SPIN_STYLE::BOTTOM );
4836 sheetPin->SetSide( SHEET_SIDE::BOTTOM );
4837 break;
4838 }
4839
4840 switch( elem.iotype )
4841 {
4842 default:
4845 break;
4846
4849 break;
4850
4853 break;
4854
4857 break;
4858 }
4859}
4860
4861
4863 REPORTER* aReporter )
4864{
4866 {
4868 line1->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4869 line1->AddPoint( { 0, 0 } );
4870 line1->AddPoint( { 0, schIUScale.MilsToIU( 50 ) } );
4871 aKsymbol->AddDrawItem( line1, false );
4872
4873 if( aStyle == ASCH_POWER_PORT_STYLE::CIRCLE )
4874 {
4876 circle->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 5 ), LINE_STYLE::SOLID ) );
4877 circle->SetPosition( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 75 ) } );
4878 circle->SetEnd( circle->GetPosition() + VECTOR2I( schIUScale.MilsToIU( 25 ), 0 ) );
4879 aKsymbol->AddDrawItem( circle, false );
4880 }
4881 else
4882 {
4884 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4885 line2->AddPoint( { schIUScale.MilsToIU( -25 ), schIUScale.MilsToIU( 50 ) } );
4886 line2->AddPoint( { schIUScale.MilsToIU( 25 ), schIUScale.MilsToIU( 50 ) } );
4887 line2->AddPoint( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 100 ) } );
4888 line2->AddPoint( { schIUScale.MilsToIU( -25 ), schIUScale.MilsToIU( 50 ) } );
4889 aKsymbol->AddDrawItem( line2, false );
4890 }
4891
4892 return { 0, schIUScale.MilsToIU( 150 ) };
4893 }
4894 else if( aStyle == ASCH_POWER_PORT_STYLE::WAVE )
4895 {
4897 line->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4898 line->AddPoint( { 0, 0 } );
4899 line->AddPoint( { 0, schIUScale.MilsToIU( 72 ) } );
4900 aKsymbol->AddDrawItem( line, false );
4901
4903 bezier->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 5 ), LINE_STYLE::SOLID ) );
4904 bezier->SetStart( { schIUScale.MilsToIU( 30 ), schIUScale.MilsToIU( 50 ) } );
4905 bezier->SetBezierC1( { schIUScale.MilsToIU( 30 ), schIUScale.MilsToIU( 87 ) } );
4906 bezier->SetBezierC2( { schIUScale.MilsToIU( -30 ), schIUScale.MilsToIU( 63 ) } );
4907 bezier->SetEnd( { schIUScale.MilsToIU( -30 ), schIUScale.MilsToIU( 100 ) } );
4908 aKsymbol->AddDrawItem( bezier, false );
4909
4910 return { 0, schIUScale.MilsToIU( 150 ) };
4911 }
4912 else if( aStyle == ASCH_POWER_PORT_STYLE::POWER_GROUND
4914 || aStyle == ASCH_POWER_PORT_STYLE::EARTH
4916 {
4918 line1->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4919 line1->AddPoint( { 0, 0 } );
4920 line1->AddPoint( { 0, schIUScale.MilsToIU( 100 ) } );
4921 aKsymbol->AddDrawItem( line1, false );
4922
4924 {
4926 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4927 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 100 ) } );
4928 line2->AddPoint( { schIUScale.MilsToIU( 100 ), schIUScale.MilsToIU( 100 ) } );
4929 aKsymbol->AddDrawItem( line2, false );
4930
4932 line3->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4933 line3->AddPoint( { schIUScale.MilsToIU( -70 ), schIUScale.MilsToIU( 130 ) } );
4934 line3->AddPoint( { schIUScale.MilsToIU( 70 ), schIUScale.MilsToIU( 130 ) } );
4935 aKsymbol->AddDrawItem( line3, false );
4936
4938 line4->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4939 line4->AddPoint( { schIUScale.MilsToIU( -40 ), schIUScale.MilsToIU( 160 ) } );
4940 line4->AddPoint( { schIUScale.MilsToIU( 40 ), schIUScale.MilsToIU( 160 ) } );
4941 aKsymbol->AddDrawItem( line4, false );
4942
4944 line5->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4945 line5->AddPoint( { schIUScale.MilsToIU( -10 ), schIUScale.MilsToIU( 190 ) } );
4946 line5->AddPoint( { schIUScale.MilsToIU( 10 ), schIUScale.MilsToIU( 190 ) } );
4947 aKsymbol->AddDrawItem( line5, false );
4948 }
4949 else if( aStyle == ASCH_POWER_PORT_STYLE::SIGNAL_GROUND )
4950 {
4952 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4953 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 100 ) } );
4954 line2->AddPoint( { schIUScale.MilsToIU( 100 ), schIUScale.MilsToIU( 100 ) } );
4955 line2->AddPoint( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 200 ) } );
4956 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 100 ) } );
4957 aKsymbol->AddDrawItem( line2, false );
4958 }
4959 else if( aStyle == ASCH_POWER_PORT_STYLE::EARTH )
4960 {
4962 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4963 line2->AddPoint( { schIUScale.MilsToIU( -150 ), schIUScale.MilsToIU( 200 ) } );
4964 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 100 ) } );
4965 line2->AddPoint( { schIUScale.MilsToIU( 100 ), schIUScale.MilsToIU( 100 ) } );
4966 line2->AddPoint( { schIUScale.MilsToIU( 50 ), schIUScale.MilsToIU( 200 ) } );
4967 aKsymbol->AddDrawItem( line2, false );
4968
4970 line3->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4971 line3->AddPoint( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 100 ) } );
4972 line3->AddPoint( { schIUScale.MilsToIU( -50 ), schIUScale.MilsToIU( 200 ) } );
4973 aKsymbol->AddDrawItem( line3, false );
4974 }
4975 else // ASCH_POWER_PORT_STYLE::GOST_ARROW
4976 {
4978 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4979 line2->AddPoint( { schIUScale.MilsToIU( -25 ), schIUScale.MilsToIU( 50 ) } );
4980 line2->AddPoint( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 100 ) } );
4981 line2->AddPoint( { schIUScale.MilsToIU( 25 ), schIUScale.MilsToIU( 50 ) } );
4982 aKsymbol->AddDrawItem( line2, false );
4983
4984 return { 0, schIUScale.MilsToIU( 150 ) }; // special case
4985 }
4986
4987 return { 0, schIUScale.MilsToIU( 250 ) };
4988 }
4991 {
4993 line1->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
4994 line1->AddPoint( { 0, 0 } );
4995 line1->AddPoint( { 0, schIUScale.MilsToIU( 160 ) } );
4996 aKsymbol->AddDrawItem( line1, false );
4997
4999 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5000 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 160 ) } );
5001 line2->AddPoint( { schIUScale.MilsToIU( 100 ), schIUScale.MilsToIU( 160 ) } );
5002 aKsymbol->AddDrawItem( line2, false );
5003
5005 line3->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5006 line3->AddPoint( { schIUScale.MilsToIU( -60 ), schIUScale.MilsToIU( 200 ) } );
5007 line3->AddPoint( { schIUScale.MilsToIU( 60 ), schIUScale.MilsToIU( 200 ) } );
5008 aKsymbol->AddDrawItem( line3, false );
5009
5011 line4->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5012 line4->AddPoint( { schIUScale.MilsToIU( -20 ), schIUScale.MilsToIU( 240 ) } );
5013 line4->AddPoint( { schIUScale.MilsToIU( 20 ), schIUScale.MilsToIU( 240 ) } );
5014 aKsymbol->AddDrawItem( line4, false );
5015
5017 return { 0, schIUScale.MilsToIU( -300 ) };
5018
5020 circle->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5021 circle->SetPosition( { schIUScale.MilsToIU( 0 ), schIUScale.MilsToIU( 160 ) } );
5022 circle->SetEnd( circle->GetPosition() + VECTOR2I( schIUScale.MilsToIU( 120 ), 0 ) );
5023 aKsymbol->AddDrawItem( circle, false );
5024
5025 return { 0, schIUScale.MilsToIU( 350 ) };
5026 }
5027 else if( aStyle == ASCH_POWER_PORT_STYLE::GOST_BAR )
5028 {
5030 line1->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5031 line1->AddPoint( { 0, 0 } );
5032 line1->AddPoint( { 0, schIUScale.MilsToIU( 200 ) } );
5033 aKsymbol->AddDrawItem( line1, false );
5034
5036 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5037 line2->AddPoint( { schIUScale.MilsToIU( -100 ), schIUScale.MilsToIU( 200 ) } );
5038 line2->AddPoint( { schIUScale.MilsToIU( 100 ), schIUScale.MilsToIU( 200 ) } );
5039 aKsymbol->AddDrawItem( line2, false );
5040
5041 return { 0, schIUScale.MilsToIU( 250 ) };
5042 }
5043 else
5044 {
5045 if( aStyle != ASCH_POWER_PORT_STYLE::BAR )
5046 {
5047 aReporter->Report( _( "Power Port with unknown style imported as 'Bar' type." ),
5049 }
5050
5052 line1->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5053 line1->AddPoint( { 0, 0 } );
5054 line1->AddPoint( { 0, schIUScale.MilsToIU( 100 ) } );
5055 aKsymbol->AddDrawItem( line1, false );
5056
5058 line2->SetStroke( STROKE_PARAMS( schIUScale.MilsToIU( 10 ), LINE_STYLE::SOLID ) );
5059 line2->AddPoint( { schIUScale.MilsToIU( -50 ), schIUScale.MilsToIU( 100 ) } );
5060 line2->AddPoint( { schIUScale.MilsToIU( 50 ), schIUScale.MilsToIU( 100 ) } );
5061 aKsymbol->AddDrawItem( line2, false );
5062
5063 return { 0, schIUScale.MilsToIU( 150 ) };
5064 }
5065}
5066
5067
5068void SCH_IO_ALTIUM::ParsePowerPort( const std::map<wxString, wxString>& aProperties )
5069{
5070 ASCH_POWER_PORT elem( aProperties );
5071
5072 // TODO: fill in replacements from variant, sheet and project
5073 static const std::map<wxString, wxString> variableMap = {
5074 };
5075
5076 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap );
5077
5078 wxString symName( kicadText );
5079 std::string styleName( magic_enum::enum_name<ASCH_POWER_PORT_STYLE>( elem.style ) );
5080
5081 if( !styleName.empty() )
5082 symName << '_' << styleName;
5083
5084 LIB_ID libId = AltiumToKiCadLibID( getLibName(), symName );
5085 LIB_SYMBOL* libSymbol = nullptr;
5086
5087 const auto& powerSymbolIt = m_powerSymbols.find( symName );
5088
5089 if( powerSymbolIt != m_powerSymbols.end() )
5090 {
5091 libSymbol = powerSymbolIt->second; // cache hit
5092 }
5093 else
5094 {
5095 libSymbol = new LIB_SYMBOL( wxEmptyString );
5096 libSymbol->SetGlobalPower();
5097 libSymbol->SetName( symName );
5098 libSymbol->GetReferenceField().SetText( "#PWR" );
5099 libSymbol->GetReferenceField().SetVisible( false );
5100 libSymbol->GetValueField().SetText( kicadText );
5101 libSymbol->GetValueField().SetVisible( true );
5102 libSymbol->SetDescription( wxString::Format( _( "Power symbol creates a global label with name '%s'" ),
5103 elem.text ) );
5104 libSymbol->SetKeyWords( "power-flag" );
5105 libSymbol->SetLibId( libId );
5106
5107 // generate graphic
5108 SCH_PIN* pin = new SCH_PIN( libSymbol );
5109 libSymbol->AddDrawItem( pin, false );
5110
5111 pin->SetName( kicadText );
5112 pin->SetPosition( { 0, 0 } );
5113 pin->SetLength( 0 );
5115 pin->SetVisible( false );
5116
5117 VECTOR2I valueFieldPos = HelperGeneratePowerPortGraphics( libSymbol, elem.style, m_reporter );
5118
5119 libSymbol->GetValueField().SetPosition( valueFieldPos );
5120
5121 // this has to be done after parsing the LIB_SYMBOL!
5122 m_powerSymbols.insert( { symName, libSymbol } );
5123 }
5124
5125 SCH_SCREEN* screen = getCurrentScreen();
5126 wxCHECK( screen, /* void */ );
5127
5128 SCH_SYMBOL* symbol = new SCH_SYMBOL();
5129 symbol->SetRef( &m_sheetPath, "#PWR?" );
5130 symbol->GetField( FIELD_T::REFERENCE )->SetVisible( false );
5131 symbol->SetValueFieldText( kicadText );
5132 symbol->SetLibId( libId );
5133 symbol->SetLibSymbol( new LIB_SYMBOL( *libSymbol ) );
5134
5135 SCH_FIELD* valueField = symbol->GetField( FIELD_T::VALUE );
5136 valueField->SetVisible( elem.showNetName );
5137 valueField->SetPosition( libSymbol->GetValueField().GetPosition() );
5138
5139 symbol->SetPosition( elem.location + m_sheetOffset );
5140
5141 switch( elem.orientation )
5142 {
5145 valueField->SetTextAngle( ANGLE_VERTICAL );
5147 break;
5148
5151 valueField->SetTextAngle( ANGLE_HORIZONTAL );
5153 break;
5154
5157 valueField->SetTextAngle( ANGLE_VERTICAL );
5159 break;
5160
5163 valueField->SetTextAngle( ANGLE_HORIZONTAL );
5165 break;
5166
5167 default:
5168 m_errorMessages.emplace( _( "Pin has unexpected orientation." ), RPT_SEVERITY_WARNING );
5169 break;
5170 }
5171
5172 screen->Append( symbol );
5173}
5174
5175
5177{
5178 ParsePortHelper( aElem );
5179}
5180
5181
5183{
5184 if( !aElem.HarnessType.IsEmpty() )
5185 {
5186 // Parse harness ports after "Additional" compound section is parsed
5187 m_altiumHarnessPortsCurrentSheet.emplace_back( aElem );
5188 return;
5189 }
5190
5191 ParsePortHelper( aElem );
5192}
5193
5194
5196{
5197 VECTOR2I start = aElem.Location + m_sheetOffset;
5198 VECTOR2I end = start;
5199
5200 switch( aElem.Style )
5201 {
5202 default:
5207 end.x += aElem.Width;
5208 break;
5209
5214 end.y -= aElem.Width;
5215 break;
5216 }
5217
5218 // Check which connection points exists in the schematic
5219 SCH_SCREEN* screen = getCurrentScreen();
5220 wxCHECK( screen, /* void */ );
5221
5222 bool startIsWireTerminal = screen->IsTerminalPoint( start, LAYER_WIRE );
5223 bool startIsBusTerminal = screen->IsTerminalPoint( start, LAYER_BUS );
5224
5225 bool endIsWireTerminal = screen->IsTerminalPoint( end, LAYER_WIRE );
5226 bool endIsBusTerminal = screen->IsTerminalPoint( end, LAYER_BUS );
5227
5228 // check if any of the points is a terminal point
5229 // TODO: there seems a problem to detect approximated connections towards component pins?
5230 bool connectionFound = startIsWireTerminal
5231 || startIsBusTerminal
5232 || endIsWireTerminal
5233 || endIsBusTerminal;
5234
5235 if( !connectionFound )
5236 {
5237 for( auto& [ _, harness ] : m_altiumHarnesses )
5238 {
5239 if( harness.m_name.CmpNoCase( aElem.HarnessType ) != 0 )
5240 continue;
5241
5242 BOX2I bbox( harness.m_location, harness.m_size );
5243 bbox.Inflate( 10 );
5244
5245 if( bbox.Contains( start ) )
5246 {
5247 startIsBusTerminal = true;
5248 connectionFound = true;
5249 break;
5250 }
5251
5252 if( bbox.Contains( end ) )
5253 {
5254 endIsBusTerminal = true;
5255 connectionFound = true;
5256 break;
5257 }
5258 }
5259
5260 if( !connectionFound )
5261 {
5262 m_errorMessages.emplace( wxString::Format( _( "Port %s has no connections." ), aElem.Name ),
5264 }
5265 }
5266
5267 // Select label position. In case both match, we will add a line later.
5268 VECTOR2I position = ( startIsWireTerminal || startIsBusTerminal ) ? start : end;
5269 SCH_LABEL_BASE* label;
5270
5271 wxString labelName = aElem.Name;
5272
5273 if( !aElem.HarnessType.IsEmpty() )
5274 labelName += wxT( "{" ) + aElem.HarnessType + wxT( "}" );
5275
5276 // TODO: detect correct label type depending on sheet settings, etc.
5277#if 1 // Set to 1 to use SCH_HIERLABEL label, 0 to use SCH_GLOBALLABEL
5278 {
5279 label = new SCH_HIERLABEL( position, labelName );
5280 }
5281#else
5282 label = new SCH_GLOBALLABEL( position, labelName );
5283
5284 // Default "Sheet References" field should be hidden, at least for now
5285 label->GetField( INTERSHEET_REFS )->SetVisible( false );
5286#endif
5287
5288 switch( aElem.IOtype )
5289 {
5290 default:
5295 }
5296
5297 switch( aElem.Style )
5298 {
5299 default:
5304 if( ( startIsWireTerminal || startIsBusTerminal ) )
5306 else
5308
5309 break;
5310
5315 if( ( startIsWireTerminal || startIsBusTerminal ) )
5316 label->SetSpinStyle( SPIN_STYLE::UP );
5317 else
5319
5320 break;
5321 }
5322
5323 label->AutoplaceFields( screen, AUTOPLACE_AUTO );
5324 label->SetFlags( IS_NEW );
5325
5326 screen->Append( label );
5327
5328 // This is a hack, for the case both connection points are valid: add a small wire
5329 if( ( startIsWireTerminal && endIsWireTerminal ) )
5330 {
5331 SCH_LINE* wire = new SCH_LINE( start, SCH_LAYER_ID::LAYER_WIRE );
5332 wire->SetEndPoint( end );
5333 wire->SetLineWidth( schIUScale.MilsToIU( 2 ) );
5334 wire->SetFlags( IS_NEW );
5335 screen->Append( wire );
5336 }
5337 else if( startIsBusTerminal && endIsBusTerminal )
5338 {
5339 SCH_LINE* wire = new SCH_LINE( start, SCH_LAYER_ID::LAYER_BUS );
5340 wire->SetEndPoint( end );
5341 wire->SetLineWidth( schIUScale.MilsToIU( 2 ) );
5342 wire->SetFlags( IS_NEW );
5343 screen->Append( wire );
5344 }
5345}
5346
5347
5348void SCH_IO_ALTIUM::ParseNoERC( const std::map<wxString, wxString>& aProperties )
5349{
5350 ASCH_NO_ERC elem( aProperties );
5351
5352 SCH_SCREEN* screen = getCurrentScreen();
5353 wxCHECK( screen, /* void */ );
5354
5355 // Only the generic cross means unconnected, a specific No ERC just waives selected violations
5356 if( elem.isActive && elem.suppressAll )
5357 {
5358 SCH_NO_CONNECT* noConnect = new SCH_NO_CONNECT( elem.location + m_sheetOffset );
5359
5360 noConnect->SetFlags( IS_NEW );
5361 screen->Append( noConnect );
5362 }
5363}
5364
5365
5366void SCH_IO_ALTIUM::ParseNetLabel( const std::map<wxString, wxString>& aProperties )
5367{
5368 ASCH_NET_LABEL elem( aProperties );
5369
5370 // TODO: fill in replacements from variant, sheet and project
5371 static const std::map<wxString, wxString> variableMap = {
5372 };
5373
5374 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap );
5375
5376 SCH_LABEL* label = new SCH_LABEL( elem.location + m_sheetOffset, kicadText );
5377
5378 SCH_SCREEN* screen = getCurrentScreen();
5379 wxCHECK( screen, /* void */ );
5380
5381 SetTextPositioning( label, elem.justification, elem.orientation );
5382
5383 label->SetFlags( IS_NEW );
5384 screen->Append( label );
5385}
5386
5387
5388void SCH_IO_ALTIUM::ParseBus( const std::map<wxString, wxString>& aProperties )
5389{
5390 ASCH_BUS elem( aProperties );
5391
5392 SCH_SCREEN* screen = getCurrentScreen();
5393 wxCHECK( screen, /* void */ );
5394
5395 for( size_t i = 0; i + 1 < elem.points.size(); i++ )
5396 {
5397 SCH_LINE* bus = new SCH_LINE( elem.points.at( i ) + m_sheetOffset, SCH_LAYER_ID::LAYER_BUS );
5398 bus->SetEndPoint( elem.points.at( i + 1 ) + m_sheetOffset );
5399 bus->SetLineWidth( elem.lineWidth );
5400
5401 bus->SetFlags( IS_NEW );
5402 screen->Append( bus );
5403 }
5404}
5405
5406
5407void SCH_IO_ALTIUM::ParseWire( const std::map<wxString, wxString>& aProperties )
5408{
5409 ASCH_WIRE elem( aProperties );
5410
5411 SCH_SCREEN* screen = getCurrentScreen();
5412 wxCHECK( screen, /* void */ );
5413
5414 for( size_t i = 0; i + 1 < elem.points.size(); i++ )
5415 {
5416 SCH_LINE* wire = new SCH_LINE( elem.points.at( i ) + m_sheetOffset, SCH_LAYER_ID::LAYER_WIRE );
5417 wire->SetEndPoint( elem.points.at( i + 1 ) + m_sheetOffset );
5418 // wire->SetLineWidth( elem.lineWidth );
5419
5420 wire->SetFlags( IS_NEW );
5421 screen->Append( wire );
5422 }
5423}
5424
5425
5426void SCH_IO_ALTIUM::ParseJunction( const std::map<wxString, wxString>& aProperties )
5427{
5428 SCH_SCREEN* screen = getCurrentScreen();
5429 wxCHECK( screen, /* void */ );
5430
5431 ASCH_JUNCTION elem( aProperties );
5432
5433 SCH_JUNCTION* junction = new SCH_JUNCTION( elem.location + m_sheetOffset );
5434
5435 junction->SetFlags( IS_NEW );
5436 screen->Append( junction );
5437}
5438
5439
5440void SCH_IO_ALTIUM::ParseImage( const std::map<wxString, wxString>& aProperties )
5441{
5442 ASCH_IMAGE elem( aProperties );
5443
5444 const auto& component = m_altiumComponents.find( elem.ownerindex );
5445
5446 //Hide the image if it is owned by a component but the part id do not match
5447 if( component != m_altiumComponents.end()
5448 && component->second.currentpartid != elem.ownerpartid )
5449 return;
5450
5451 VECTOR2I center = ( elem.location + elem.corner ) / 2 + m_sheetOffset;
5452 std::unique_ptr<SCH_BITMAP> bitmap = std::make_unique<SCH_BITMAP>( center );
5453 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
5454
5455 SCH_SCREEN* screen = getCurrentScreen();
5456 wxCHECK( screen, /* void */ );
5457
5458 if( elem.embedimage )
5459 {
5460 const ASCH_STORAGE_FILE* storageFile = GetFileFromStorage( elem.filename );
5461
5462 if( !storageFile )
5463 {
5464 m_errorMessages.emplace( wxString::Format( _( "Embedded file '%s' not found in storage." ),
5465 elem.filename ),
5467 return;
5468 }
5469
5470 wxString storagePath = wxFileName::CreateTempFileName( "kicad_import_" );
5471
5472 // As wxZlibInputStream is not seekable, we need to write a temporary file
5473 wxMemoryInputStream fileStream( storageFile->data.data(), storageFile->data.size() );
5474 wxZlibInputStream zlibInputStream( fileStream );
5475 wxFFileOutputStream outputStream( storagePath );
5476 outputStream.Write( zlibInputStream );
5477
5478 // wxFFileOutputStream::IsOk() reports the closed stream as not-ok, so capture the write
5479 // result before closing.
5480 const bool writeOk = outputStream.IsOk();
5481 const bool closeOk = outputStream.Close();
5482
5483 if( storagePath.IsEmpty() || !writeOk || !closeOk )
5484 {
5485 m_errorMessages.emplace( wxString::Format( _( "Could not write a temporary file while extracting the "
5486 "embedded image '%s'." ),
5487 elem.filename ),
5489
5490 if( !storagePath.IsEmpty() )
5491 wxRemoveFile( storagePath );
5492
5493 return;
5494 }
5495
5496 bool readOk;
5497
5498 {
5499 // wxImage emits its own log spam on a failed read; we report our own errors instead.
5500 wxLogNull noLog;
5501 readOk = refImage.ReadImageFile( storagePath );
5502 }
5503
5504 if( !readOk )
5505 {
5506 m_errorMessages.emplace( wxString::Format( _( "Failed to read embedded image '%s'. The image data may "
5507 "be corrupt or in an unsupported format." ),
5508 elem.filename ),
5510 wxRemoveFile( storagePath );
5511 return;
5512 }
5513
5514 // Remove temporary file
5515 wxRemoveFile( storagePath );
5516 }
5517 else
5518 {
5519 if( !wxFileExists( elem.filename ) )
5520 {
5521 m_errorMessages.emplace( wxString::Format( _( "Could not find image file '%s'. The file path may be "
5522 "specific to a different operating system." ),
5523 elem.filename ),
5525 return;
5526 }
5527
5528 bool readOk;
5529
5530 {
5531 wxLogNull noLog;
5532 readOk = refImage.ReadImageFile( elem.filename );
5533 }
5534
5535 if( !readOk )
5536 {
5537 m_errorMessages.emplace( wxString::Format( _( "Failed to read image file '%s'. The image may be "
5538 "corrupt or in an unsupported format." ),
5539 elem.filename ),
5541 return;
5542 }
5543 }
5544
5545 // we only support one scale, thus we need to select one in case it does not keep aspect ratio
5546 const VECTOR2I currentImageSize = refImage.GetSize();
5547 const VECTOR2I expectedImageSize = elem.location - elem.corner;
5548 const double scaleX = std::abs( static_cast<double>( expectedImageSize.x ) / currentImageSize.x );
5549 const double scaleY = std::abs( static_cast<double>( expectedImageSize.y ) / currentImageSize.y );
5550 refImage.SetImageScale( std::min( scaleX, scaleY ) );
5551
5552 bitmap->SetFlags( IS_NEW );
5553 screen->Append( bitmap.release() );
5554}
5555
5556
5557void SCH_IO_ALTIUM::ParseSheet( const std::map<wxString, wxString>& aProperties )
5558{
5559 m_altiumSheet = std::make_unique<ASCH_SHEET>( aProperties );
5560
5561 SCH_SCREEN* screen = getCurrentScreen();
5562 wxCHECK( screen, /* void */ );
5563
5564 PAGE_INFO pageInfo;
5565
5566 bool isPortrait = m_altiumSheet->sheetOrientation == ASCH_SHEET_WORKSPACEORIENTATION::PORTRAIT;
5567
5568 if( m_altiumSheet->useCustomSheet )
5569 {
5570 PAGE_INFO::SetCustomWidthMils( schIUScale.IUToMils( m_altiumSheet->customSize.x ) );
5571 PAGE_INFO::SetCustomHeightMils( schIUScale.IUToMils( m_altiumSheet->customSize.y ) );
5572 pageInfo.SetType( PAGE_SIZE_TYPE::User, isPortrait );
5573 }
5574 else
5575 {
5576 switch( m_altiumSheet->sheetSize )
5577 {
5578 default:
5579 case ASCH_SHEET_SIZE::A4: pageInfo.SetType( "A4", isPortrait ); break;
5580 case ASCH_SHEET_SIZE::A3: pageInfo.SetType( "A3", isPortrait ); break;
5581 case ASCH_SHEET_SIZE::A2: pageInfo.SetType( "A2", isPortrait ); break;
5582 case ASCH_SHEET_SIZE::A1: pageInfo.SetType( "A1", isPortrait ); break;
5583 case ASCH_SHEET_SIZE::A0: pageInfo.SetType( "A0", isPortrait ); break;
5584 case ASCH_SHEET_SIZE::A: pageInfo.SetType( "A", isPortrait ); break;
5585 case ASCH_SHEET_SIZE::B: pageInfo.SetType( "B", isPortrait ); break;
5586 case ASCH_SHEET_SIZE::C: pageInfo.SetType( "C", isPortrait ); break;
5587 case ASCH_SHEET_SIZE::D: pageInfo.SetType( "D", isPortrait ); break;
5588 case ASCH_SHEET_SIZE::E: pageInfo.SetType( "E", isPortrait ); break;
5589 case ASCH_SHEET_SIZE::LETTER: pageInfo.SetType( "USLetter", isPortrait ); break;
5590 case ASCH_SHEET_SIZE::LEGAL: pageInfo.SetType( "USLegal", isPortrait ); break;
5591 case ASCH_SHEET_SIZE::TABLOID: pageInfo.SetType( "A3", isPortrait ); break;
5592 case ASCH_SHEET_SIZE::ORCAD_A: pageInfo.SetType( "A", isPortrait ); break;
5593 case ASCH_SHEET_SIZE::ORCAD_B: pageInfo.SetType( "B", isPortrait ); break;
5594 case ASCH_SHEET_SIZE::ORCAD_C: pageInfo.SetType( "C", isPortrait ); break;
5595 case ASCH_SHEET_SIZE::ORCAD_D: pageInfo.SetType( "D", isPortrait ); break;
5596 case ASCH_SHEET_SIZE::ORCAD_E: pageInfo.SetType( "E", isPortrait ); break;
5597 }
5598 }
5599
5600 screen->SetPageSettings( pageInfo );
5601
5602 // Altium anchors its snap grid at the sheet origin, which the Y flip maps to the page bottom
5603 // ISO heights are not whole mils, so truncate to a grid step rather than flip past the page
5604 const int gridPitch = m_schematic->Settings().m_ConnectionGridSize;
5605 const int pageHeight = pageInfo.GetHeightIU( schIUScale.IU_PER_MILS );
5606
5607 m_sheetOffset = { 0, ( pageHeight / gridPitch ) * gridPitch };
5608}
5609
5610
5611void SCH_IO_ALTIUM::ParseSheetName( const std::map<wxString, wxString>& aProperties )
5612{
5613 ASCH_SHEET_NAME elem( aProperties );
5614 SCH_SCREEN* currentScreen = getCurrentScreen();
5615
5616 // TODO: fill in replacements from variant, sheet and project
5617 static const std::map<wxString, wxString> variableMap = {
5618 };
5619
5620 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap );
5621
5622 wxCHECK( currentScreen, /* void */ );
5623
5624 const auto& sheetIt = m_sheets.find( elem.ownerindex );
5625
5626 if( sheetIt == m_sheets.end() )
5627 {
5628 m_errorMessages.emplace( wxString::Format( wxT( "Sheetname's owner (%d) not found." ), elem.ownerindex ),
5630 return;
5631 }
5632
5633 wxString baseName = kicadText;
5634 baseName.Replace( wxT( "/" ), wxT( "_" ) );
5635
5636 wxString sheetName = baseName;
5637 std::set<wxString> sheetNames;
5638
5639 for( EDA_ITEM* item : currentScreen->Items().OfType( SCH_SHEET_T ) )
5640 {
5641 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
5642 sheetNames.insert( sheet->GetName() );
5643 }
5644
5645 for( int ii = 1; ; ++ii )
5646 {
5647 if( sheetNames.find( sheetName ) == sheetNames.end() )
5648 break;
5649
5650 sheetName = baseName + wxString::Format( wxT( "_%d" ), ii );
5651 }
5652
5653 SCH_FIELD* sheetNameField = sheetIt->second->GetField( FIELD_T::SHEET_NAME );
5654
5655 sheetNameField->SetPosition( elem.location + m_sheetOffset );
5656 sheetNameField->SetText( sheetName );
5657 sheetNameField->SetVisible( !elem.isHidden );
5659}
5660
5661
5662void SCH_IO_ALTIUM::ParseFileName( const std::map<wxString, wxString>& aProperties )
5663{
5664 ASCH_FILE_NAME elem( aProperties );
5665
5666 const auto& sheetIt = m_sheets.find( elem.ownerindex );
5667
5668 if( sheetIt == m_sheets.end() )
5669 {
5670 m_errorMessages.emplace( wxString::Format( wxT( "Filename's owner (%d) not found." ), elem.ownerindex ),
5672 return;
5673 }
5674
5675 SCH_FIELD* filenameField = sheetIt->second->GetField( FIELD_T::SHEET_FILENAME );
5676
5677 filenameField->SetPosition( elem.location + m_sheetOffset );
5678
5679 // Keep the filename of the Altium file until after the file is actually loaded.
5680 filenameField->SetText( elem.text );
5681 filenameField->SetVisible( !elem.isHidden );
5683}
5684
5685
5686void SCH_IO_ALTIUM::ParseDesignator( const std::map<wxString, wxString>& aProperties )
5687{
5688 ASCH_DESIGNATOR elem( aProperties );
5689 wxString escapedRef = AltiumEscapeTextVars( elem.text );
5690 bool emptyRef = escapedRef.IsEmpty();
5691
5692 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
5693
5694 if( libSymbolIt == m_libSymbols.end() )
5695 {
5696 // TODO: e.g. can depend on Template (RECORD=39
5697 m_errorMessages.emplace( wxString::Format( wxT( "Designator's owner (%d) not found." ), elem.ownerindex ),
5699 return;
5700 }
5701
5702 SCH_SYMBOL* symbol = m_symbols.at( libSymbolIt->first );
5703 SCH_SHEET_PATH sheetpath;
5704
5705 SCH_SCREEN* screen = getCurrentScreen();
5706 wxCHECK( screen, /* void */ );
5707
5708 // Graphics symbols have no reference. '#GRAPHIC' allows them to not have footprint associated.
5709 // Note: not all unnamed imported symbols are necessarily graphics.
5710 symbol->SetRef( &m_sheetPath, emptyRef ? wxString( wxS( "#GRAPHIC" ) ) : escapedRef );
5711
5712 // I am not sure value and ref should be invisible just because emptyRef is true
5713 // I have examples with this criteria fully incorrect.
5714 bool visible = !emptyRef;
5715
5716 symbol->GetField( FIELD_T::VALUE )->SetVisible( visible );
5717
5718 SCH_FIELD* field = symbol->GetField( FIELD_T::REFERENCE );
5719 field->SetVisible( visible );
5720 field->SetPosition( elem.location + m_sheetOffset );
5721 SetTextPositioning( field, elem.justification, elem.orientation );
5722
5723 const auto& altiumSymIt = m_altiumComponents.find( elem.ownerindex );
5724
5725 if( altiumSymIt != m_altiumComponents.end() )
5726 AdjustFieldForSymbolOrientation( field, altiumSymIt->second );
5727}
5728
5729
5730void SCH_IO_ALTIUM::ParseLibDesignator( const std::map<wxString, wxString>& aProperties,
5731 std::vector<LIB_SYMBOL*>& aSymbols, std::vector<int>& aFontSizes )
5732{
5733 ASCH_DESIGNATOR elem( aProperties );
5734 wxString escapedRef = AltiumEscapeTextVars( elem.text );
5735 bool emptyRef = escapedRef.IsEmpty();
5736
5737 if( elem.ownerpartdisplaymode != 0 )
5738 return;
5739
5740 for( LIB_SYMBOL* symbol : aSymbols )
5741 {
5742 SCH_FIELD& refField = symbol->GetReferenceField();
5743
5744 if( emptyRef )
5745 refField.SetText( wxT( "X" ) );
5746 else
5747 refField.SetText( escapedRef.BeforeLast( '?' ) ); // remove the '?' at the end for KiCad-style
5748
5749 refField.SetPosition( elem.location );
5750 SetTextPositioning( &refField, elem.justification, elem.orientation );
5751
5752 if( elem.fontId > 0 && elem.fontId <= static_cast<int>( aFontSizes.size() ) )
5753 {
5754 int size = aFontSizes[elem.fontId - 1];
5755 refField.SetTextSize( { size, size } );
5756 }
5757 }
5758}
5759
5760
5761void SCH_IO_ALTIUM::ParseBusEntry( const std::map<wxString, wxString>& aProperties )
5762{
5763 ASCH_BUS_ENTRY elem( aProperties );
5764
5765 SCH_SCREEN* screen = getCurrentScreen();
5766 wxCHECK( screen, /* void */ );
5767
5768 SCH_BUS_WIRE_ENTRY* busWireEntry = new SCH_BUS_WIRE_ENTRY( elem.location + m_sheetOffset );
5769
5770 VECTOR2I vector = elem.corner - elem.location;
5771 busWireEntry->SetSize( { vector.x, vector.y } );
5772
5773 busWireEntry->SetFlags( IS_NEW );
5774 screen->Append( busWireEntry );
5775}
5776
5777
5778void SCH_IO_ALTIUM::ParseParameter( const std::map<wxString, wxString>& aProperties )
5779{
5780 ASCH_PARAMETER elem( aProperties );
5781
5782 // TODO: fill in replacements from variant, sheet and project
5783 static const std::map<wxString, wxString> variableMap = {
5784 { "COMMENT", "VALUE" },
5785 { "VALUE", "ALTIUM_VALUE" },
5786 };
5787
5788 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap );
5789
5790 if( elem.ownerindex <= 0 )
5791 {
5792 // This is some sheet parameter
5793 wxString paramName = elem.name.Upper();
5794
5795 // an unset parameter still names a variable, which resolves to nothing
5796 if( kicadText == "*" )
5797 {
5798 if( paramName != "SHEETNUMBER"
5799 && paramName != "TITLE"
5800 && paramName != "REVISION"
5801 && paramName != "DATE"
5802 && paramName != "COMPANYNAME" )
5803 {
5804 m_unsetSheetParams.insert( paramName );
5805 }
5806
5807 return;
5808 }
5809
5810 if( paramName == "SHEETNUMBER" )
5811 {
5812 m_sheetPath.SetPageNumber( kicadText );
5813 }
5814 else if( paramName == "TITLE" )
5815 {
5816 m_currentTitleBlock->SetTitle( kicadText );
5817 }
5818 else if( paramName == "REVISION" )
5819 {
5820 m_currentTitleBlock->SetRevision( kicadText );
5821 }
5822 else if( paramName == "DATE" )
5823 {
5824 m_currentTitleBlock->SetDate( kicadText );
5825 }
5826 else if( paramName == "COMPANYNAME" )
5827 {
5828 m_currentTitleBlock->SetCompany( kicadText );
5829 }
5830 else
5831 {
5832 m_schematic->Project().GetTextVars()[ paramName ] = kicadText;
5833 }
5834 }
5835 else
5836 {
5837 const auto& libSymbolIt = m_libSymbols.find( elem.ownerindex );
5838
5839 if( libSymbolIt == m_libSymbols.end() )
5840 {
5841 // TODO: e.g. can depend on Template (RECORD=39
5842 return;
5843 }
5844
5845 SCH_SYMBOL* symbol = m_symbols.at( libSymbolIt->first );
5846 SCH_FIELD* field = nullptr;
5847 wxString upperName = elem.name.Upper();
5848
5849 if( upperName == "COMMENT" )
5850 {
5851 field = symbol->GetField( FIELD_T::VALUE );
5852 }
5853 else
5854 {
5855 wxString fieldName = elem.name.Upper();
5856
5857 if( fieldName.IsEmpty() )
5858 {
5859 int disambiguate = 1;
5860
5861 while( 1 )
5862 {
5863 fieldName = wxString::Format( "ALTIUM_UNNAMED_%d", disambiguate++ );
5864
5865 if( !symbol->GetField( fieldName ) )
5866 break;
5867 }
5868 }
5869 else if( fieldName == "VALUE" )
5870 {
5871 fieldName = "ALTIUM_VALUE";
5872 }
5873
5874 field = symbol->AddField( SCH_FIELD( symbol, FIELD_T::USER, fieldName ) );
5875 }
5876
5877 field->SetText( kicadText );
5878 field->SetPosition( elem.location + m_sheetOffset );
5879 field->SetVisible( !elem.isHidden );
5880 field->SetNameShown( elem.isShowName );
5881 SetTextPositioning( field, elem.justification, elem.orientation );
5882
5883 const auto& altiumSymIt = m_altiumComponents.find( elem.ownerindex );
5884
5885 if( altiumSymIt != m_altiumComponents.end() )
5886 AdjustFieldForSymbolOrientation( field, altiumSymIt->second );
5887 }
5888}
5889
5890
5891void SCH_IO_ALTIUM::ParseLibParameter( const std::map<wxString, wxString>& aProperties,
5892 std::vector<LIB_SYMBOL*>& aSymbol, std::vector<int>& aFontSizes )
5893{
5894 ASCH_PARAMETER elem( aProperties );
5895
5896 if( elem.ownerpartdisplaymode != 0 )
5897 return;
5898
5899 // Part ID 1 is the current library part.
5900 // Part ID ALTIUM_COMPONENT_NONE(-1) means all parts
5901 // If a parameter is assigned to a specific element such as a pin, we will need to handle it here.
5902 // TODO: Handle HIDDENNETNAME property (others?)
5903 if( elem.ownerpartid != 1 && elem.ownerpartid != ALTIUM_COMPONENT_NONE )
5904 return;
5905
5906 // If ownerindex is populated, this is parameter belongs to a subelement (e.g. pin).
5907 // Ignore for now.
5908 // TODO: Update this when KiCad supports parameters for any object
5909 if( elem.ownerindex != ALTIUM_COMPONENT_NONE )
5910 return;
5911
5912 // N.B. We do not keep the Altium "VALUE" variable here because we don't have a way to assign variables
5913 // to specific symbols
5914 std::map<wxString, wxString> variableMap = {
5915 { "COMMENT", "VALUE" },
5916 };
5917
5918 for( LIB_SYMBOL* libSymbol : aSymbol )
5919 {
5920 SCH_FIELD* field = nullptr;
5921 wxString upperName = elem.name.Upper();
5922
5923 if( upperName == "COMMENT" )
5924 {
5925 field = &libSymbol->GetValueField();
5926 }
5927 else
5928 {
5929 wxString fieldNameStem = elem.name;
5930 wxString fieldName = fieldNameStem;
5931 int disambiguate = 1;
5932
5933 if( fieldName.IsEmpty() )
5934 {
5935 fieldNameStem = "ALTIUM_UNNAMED";
5936 fieldName = "ALTIUM_UNNAMED_1";
5937 disambiguate = 2;
5938 }
5939 else if( upperName == "VALUE" )
5940 {
5941 fieldNameStem = "ALTIUM_VALUE";
5942 fieldName = "ALTIUM_VALUE";
5943 }
5944
5945 // Avoid adding duplicate fields
5946 while( libSymbol->GetField( fieldName ) )
5947 fieldName = wxString::Format( "%s_%d", fieldNameStem, disambiguate++ );
5948
5949 SCH_FIELD* new_field = new SCH_FIELD( libSymbol, FIELD_T::USER, fieldName );
5950 libSymbol->AddField( new_field );
5951 field = new_field;
5952 }
5953
5954 wxString kicadText = AltiumSchSpecialStringsToKiCadVariables( elem.text, variableMap );
5955 field->SetText( kicadText );
5956
5957 field->SetTextPos( elem.location );
5958 SetTextPositioning( field, elem.justification, elem.orientation );
5959 field->SetVisible( !elem.isHidden );
5960
5961 if( elem.fontId > 0 && elem.fontId <= static_cast<int>( aFontSizes.size() ) )
5962 {
5963 int size = aFontSizes[elem.fontId - 1];
5964 field->SetTextSize( { size, size } );
5965 }
5966 else
5967 {
5968 int size = schIUScale.MilsToIU( DEFAULT_TEXT_SIZE );
5969 field->SetTextSize( { size, size } );
5970 }
5971
5972 }
5973}
5974
5975
5976void SCH_IO_ALTIUM::ParseImplementationList( int aIndex, const std::map<wxString, wxString>& aProperties )
5977{
5978 ASCH_IMPLEMENTATION_LIST elem( aProperties );
5979
5980 m_altiumImplementationList.emplace( aIndex, elem.ownerindex );
5981}
5982
5983
5984void SCH_IO_ALTIUM::ParseImplementation( const std::map<wxString, wxString>& aProperties,
5985 std::vector<LIB_SYMBOL*>& aSymbol )
5986{
5987 ASCH_IMPLEMENTATION elem( aProperties );
5988
5989 if( elem.type != wxS( "PCBLIB" ) )
5990 return;
5991
5992 // For schematic files, we need to check if the model is current.
5993 if( aSymbol.size() == 0 && !elem.isCurrent )
5994 return;
5995
5996 // For IntLibs we want to use the same lib name for footprints. Otherwise the model data
5997 // file names the source PcbLib as a Windows path; take its base name so the footprint id
5998 // matches the nickname project import registers in the footprint library table.
5999 wxString libName = m_isIntLib ? m_libName : wxFileName( elem.libname, wxPATH_WIN ).GetName();
6000
6001 wxArrayString fpFilters;
6002 fpFilters.Add( wxString::Format( wxS( "*%s*" ), elem.name ) );
6003
6004 // Parse the footprint fields for the library symbol
6005 if( !aSymbol.empty() )
6006 {
6007 for( LIB_SYMBOL* symbol : aSymbol )
6008 {
6009 LIB_ID fpLibId = AltiumToKiCadLibID( libName, elem.name );
6010
6011 symbol->SetFPFilters( fpFilters );
6012 symbol->GetField( FIELD_T::FOOTPRINT )->SetText( fpLibId.Format() );
6013 }
6014
6015 return;
6016 }
6017
6018 const auto& implementationOwnerIt = m_altiumImplementationList.find( elem.ownerindex );
6019
6020 if( implementationOwnerIt == m_altiumImplementationList.end() )
6021 {
6022 m_errorMessages.emplace( wxString::Format( wxT( "Implementation's owner (%d) not found." ), elem.ownerindex ),
6024 return;
6025 }
6026
6027 const auto& libSymbolIt = m_libSymbols.find( implementationOwnerIt->second );
6028
6029 if( libSymbolIt == m_libSymbols.end() )
6030 {
6031 m_errorMessages.emplace( wxString::Format( wxT( "Footprint's owner (%d) not found." ),
6032 implementationOwnerIt->second ),
6034 return;
6035 }
6036
6037 LIB_ID fpLibId = AltiumToKiCadLibID( libName, elem.name );
6038
6039 libSymbolIt->second->SetFPFilters( fpFilters ); // TODO: not ideal as we overwrite it
6040
6041 SCH_SYMBOL* symbol = m_symbols.at( libSymbolIt->first );
6042
6043 symbol->SetFootprintFieldText( fpLibId.Format() );
6044}
6045
6046
6047
6048std::vector<LIB_SYMBOL*> SCH_IO_ALTIUM::ParseLibComponent( const std::map<wxString, wxString>& aProperties )
6049{
6050 ASCH_SYMBOL elem( aProperties );
6051
6052 LIB_SYMBOL* symbol = new LIB_SYMBOL( wxEmptyString );
6053 symbol->SetName( elem.libreference );
6054
6055 LIB_ID libId = AltiumToKiCadLibID( getLibName(), symbol->GetName() );
6056 symbol->SetDescription( elem.componentdescription );
6057 symbol->SetLibId( libId );
6058
6059 // Altium PARTCOUNT is one more than the actual unit count. The property may be missing
6060 // (defaults to 0) or otherwise nonsensical, so clamp to a minimum of 1 unit.
6061 symbol->SetUnitCount( std::max( 1, elem.partcount - 1 ), true );
6062
6063 if( elem.displaymodecount > 1 )
6064 {
6065 std::vector<wxString> bodyStyleNames;
6066
6067 for( int i = 0; i < elem.displaymodecount; i++ )
6068 bodyStyleNames.push_back( wxString::Format( "Display %d", i + 1 ) );
6069
6070 symbol->SetBodyStyleNames( bodyStyleNames );
6071 }
6072
6073 return { symbol };
6074}
6075
6076
6079{
6081 std::vector<int> fontSizes;
6082 struct SYMBOL_PIN_FRAC
6083 {
6084 int x_frac;
6085 int y_frac;
6086 int len_frac;
6087 };
6088
6089 ParseLibHeader( aAltiumLibFile, fontSizes );
6090
6091 std::map<wxString, ALTIUM_SYMBOL_DATA> syms = aAltiumLibFile.GetLibSymbols( nullptr );
6092
6093 for( auto& [name, entry] : syms )
6094 {
6095 if( m_reporter )
6096 m_reporter->Report( wxString::Format( _( "Converting symbol '%s'" ), name ), RPT_SEVERITY_ACTION );
6097
6098 std::map<int, SYMBOL_PIN_FRAC> pinFracs;
6099
6100 if( entry.m_pinsFrac )
6101 {
6102 auto parse_binary_pin_frac =
6103 [&]( const std::string& binaryData ) -> std::map<wxString, wxString>
6104 {
6105 std::map<wxString, wxString> result;
6106 ALTIUM_COMPRESSED_READER cmpreader( binaryData );
6107
6108 std::pair<int, std::string*> pinFracData = cmpreader.ReadCompressedString();
6109
6110 ALTIUM_BINARY_READER binreader( *pinFracData.second );
6111 SYMBOL_PIN_FRAC pinFrac;
6112
6113 pinFrac.x_frac = binreader.ReadInt32();
6114 pinFrac.y_frac = binreader.ReadInt32();
6115 pinFrac.len_frac = binreader.ReadInt32();
6116 pinFracs.insert( { pinFracData.first, pinFrac } );
6117
6118 return result;
6119 };
6120
6121 ALTIUM_BINARY_PARSER reader( aAltiumLibFile, entry.m_pinsFrac );
6122
6123 while( reader.GetRemainingBytes() > 0 )
6124 reader.ReadProperties( parse_binary_pin_frac );
6125 }
6126
6127 ALTIUM_BINARY_PARSER reader( aAltiumLibFile, entry.m_symbol );
6128 std::vector<LIB_SYMBOL*> symbols;
6129 int pin_index = 0;
6130
6131 if( reader.GetRemainingBytes() <= 0 )
6132 THROW_IO_ERROR( "LibSymbol does not contain any data" );
6133
6134 {
6135 std::map<wxString, wxString> properties = reader.ReadProperties();
6136 int recordId = ALTIUM_PROPS_UTILS::ReadInt( properties, "RECORD", 0 );
6137 ALTIUM_SCH_RECORD record = static_cast<ALTIUM_SCH_RECORD>( recordId );
6138
6139 if( record != ALTIUM_SCH_RECORD::COMPONENT )
6140 THROW_IO_ERROR( "LibSymbol does not start with COMPONENT record" );
6141
6142 symbols = ParseLibComponent( properties );
6143 }
6144
6145 auto handleBinaryPinLambda =
6146 [&]( const std::string& binaryData ) -> std::map<wxString, wxString>
6147 {
6148 std::map<wxString, wxString> result;
6149
6150 ALTIUM_BINARY_READER binreader( binaryData );
6151
6152 int32_t recordId = binreader.ReadInt32();
6153
6154 if( recordId != static_cast<int32_t>( ALTIUM_SCH_RECORD::PIN ) )
6155 THROW_IO_ERROR( "Binary record missing PIN record" );
6156
6157 result["RECORD"] = wxString::Format( "%d", recordId );
6158 binreader.ReadByte(); // unknown
6159 result["OWNERPARTID"] = wxString::Format( "%d", binreader.ReadInt16() );
6160 result["OWNERPARTDISPLAYMODE"] = wxString::Format( "%d", binreader.ReadByte() );
6161 result["SYMBOL_INNEREDGE"] = wxString::Format( "%d", binreader.ReadByte() );
6162 result["SYMBOL_OUTEREDGE"] = wxString::Format( "%d", binreader.ReadByte() );
6163 result["SYMBOL_INNER"] = wxString::Format( "%d", binreader.ReadByte() );
6164 result["SYMBOL_OUTER"] = wxString::Format( "%d", binreader.ReadByte() );
6165 result["TEXT"] = binreader.ReadShortPascalString();
6166 binreader.ReadByte(); // unknown
6167 result["ELECTRICAL"] = wxString::Format( "%d", binreader.ReadByte() );
6168 result["PINCONGLOMERATE"] = wxString::Format( "%d", binreader.ReadByte() );
6169 result["PINLENGTH"] = wxString::Format( "%d", binreader.ReadInt16() );
6170 result["LOCATION.X"] = wxString::Format( "%d", binreader.ReadInt16() );
6171 result["LOCATION.Y"] = wxString::Format( "%d", binreader.ReadInt16() );
6172 result["COLOR"] = wxString::Format( "%d", binreader.ReadInt32() );
6173 result["NAME"] = binreader.ReadShortPascalString();
6174 result["DESIGNATOR"] = binreader.ReadShortPascalString();
6175 result["SWAPIDGROUP"] = binreader.ReadShortPascalString();
6176
6177 if( auto it = pinFracs.find( pin_index ); it != pinFracs.end() )
6178 {
6179 result["LOCATION.X_FRAC"] = wxString::Format( "%d", it->second.x_frac );
6180 result["LOCATION.Y_FRAC"] = wxString::Format( "%d", it->second.y_frac );
6181 result["PINLENGTH_FRAC"] = wxString::Format( "%d", it->second.len_frac );
6182 }
6183
6184 std::string partSeq = binreader.ReadShortPascalString(); // This is 'part|&|seq'
6185 std::vector<std::string> partSeqSplit = split( partSeq, "|" );
6186
6187 if( partSeqSplit.size() == 3 )
6188 {
6189 result["PART"] = partSeqSplit[0];
6190 result["SEQ"] = partSeqSplit[2];
6191 }
6192
6193 return result;
6194 };
6195
6196 while( reader.GetRemainingBytes() > 0 )
6197 {
6198 std::map<wxString, wxString> properties = reader.ReadProperties( handleBinaryPinLambda );
6199
6200 if( properties.empty() )
6201 continue;
6202
6203 int recordId = ALTIUM_PROPS_UTILS::ReadInt( properties, "RECORD", 0 );
6204 ALTIUM_SCH_RECORD record = static_cast<ALTIUM_SCH_RECORD>( recordId );
6205
6206 switch( record )
6207 {
6209 ParsePin( properties, symbols );
6210 pin_index++;
6211 break;
6212
6213 case ALTIUM_SCH_RECORD::LABEL: ParseLabel( properties, symbols, fontSizes ); break;
6214 case ALTIUM_SCH_RECORD::BEZIER: ParseBezier( properties, symbols ); break;
6215 case ALTIUM_SCH_RECORD::POLYLINE: ParsePolyline( properties, symbols ); break;
6216 case ALTIUM_SCH_RECORD::POLYGON: ParsePolygon( properties, symbols ); break;
6217 case ALTIUM_SCH_RECORD::ELLIPSE: ParseEllipse( properties, symbols ); break;
6218 case ALTIUM_SCH_RECORD::PIECHART: ParsePieChart( properties, symbols ); break;
6219 case ALTIUM_SCH_RECORD::ROUND_RECTANGLE: ParseRoundRectangle( properties, symbols ); break;
6220 case ALTIUM_SCH_RECORD::ELLIPTICAL_ARC: ParseEllipticalArc( properties, symbols ); break;
6221 case ALTIUM_SCH_RECORD::ARC: ParseArc( properties, symbols ); break;
6222 case ALTIUM_SCH_RECORD::LINE: ParseLine( properties, symbols ); break;
6223 case ALTIUM_SCH_RECORD::RECTANGLE: ParseRectangle( properties, symbols ); break;
6224 case ALTIUM_SCH_RECORD::DESIGNATOR: ParseLibDesignator( properties, symbols, fontSizes ); break;
6225 case ALTIUM_SCH_RECORD::PARAMETER: ParseLibParameter( properties, symbols, fontSizes ); break;
6226 case ALTIUM_SCH_RECORD::TEXT_FRAME: ParseTextFrame( properties, symbols, fontSizes ); break;
6227 case ALTIUM_SCH_RECORD::IMPLEMENTATION: ParseImplementation( properties, symbols ); break;
6228
6230 break;
6231
6234 break;
6235
6237 // TODO: add support for these. They are just drawn symbols, so we can probably hardcode
6238 break;
6239
6241 // TODO: Handle images once libedit supports them
6242 break;
6243
6245 // Nothing for now. TODO: Figure out how implementation lists are generated in libs
6246 break;
6247
6248 default:
6249 m_errorMessages.emplace( wxString::Format( _( "Unknown or unexpected record id %d found in %s." ),
6250 recordId,
6251 symbols[0]->GetName() ),
6253 break;
6254 }
6255 }
6256
6257 if( reader.HasParsingError() )
6258 THROW_IO_ERROR( wxT( "stream was not parsed correctly!" ) );
6259
6260 if( reader.GetRemainingBytes() != 0 )
6261 THROW_IO_ERROR( wxT( "stream is not fully parsed" ) );
6262
6263 LIB_SYMBOL* symbol = symbols[0];
6264 symbol->FixupDrawItems();
6265 fixupSymbolPinNameNumbers( symbol );
6266
6267 SCH_FIELD& valField = symbol->GetValueField();
6268
6269 if( valField.GetText().IsEmpty() )
6270 valField.SetText( name );
6271
6272 symbol->SetName( name );
6273 ret[name] = symbol;
6274 }
6275
6276 if( m_reporter )
6277 {
6278 for( const auto& [msg, severity] : m_errorMessages )
6279 m_reporter->Report( msg, severity );
6280 }
6281
6282 m_errorMessages.clear();
6283
6284 return ret;
6285}
6286
6287
6288long long SCH_IO_ALTIUM::getLibraryTimestamp( const wxString& aLibraryPath ) const
6289{
6290 wxFileName fn( aLibraryPath );
6291
6292 if( fn.IsFileReadable() && fn.GetModificationTime().IsValid() )
6293 return fn.GetModificationTime().GetValue().GetValue();
6294 else
6295 return 0;
6296}
6297
6298
6299void SCH_IO_ALTIUM::ensureLoadedLibrary( const wxString& aLibraryPath,
6300 const std::map<std::string, UTF8>* aProperties )
6301{
6302 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
6303 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
6304
6305 if( m_libCache.count( aLibraryPath ) )
6306 {
6307 wxCHECK( m_timestamps.count( aLibraryPath ), /*void*/ );
6308
6309 if( m_timestamps.at( aLibraryPath ) == getLibraryTimestamp( aLibraryPath ) )
6310 return;
6311 }
6312
6313 std::vector<std::unique_ptr<ALTIUM_COMPOUND_FILE>> compoundFiles;
6314
6315 wxFileName fileName( aLibraryPath );
6316 m_libName = fileName.GetName();
6317
6318 try
6319 {
6320 if( aLibraryPath.Lower().EndsWith( wxS( ".schlib" ) ) )
6321 {
6322 m_isIntLib = false;
6323
6324 compoundFiles.push_back( std::make_unique<ALTIUM_COMPOUND_FILE>( aLibraryPath ) );
6325 }
6326 else if( aLibraryPath.Lower().EndsWith( wxS( ".intlib" ) ) )
6327 {
6328 m_isIntLib = true;
6329
6330 std::unique_ptr<ALTIUM_COMPOUND_FILE> intCom = std::make_unique<ALTIUM_COMPOUND_FILE>( aLibraryPath );
6331
6332 std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*> schLibFiles = intCom->EnumDir( L"SchLib" );
6333
6334 for( const auto& [schLibName, cfe] : schLibFiles )
6335 {
6336 std::unique_ptr<ALTIUM_COMPOUND_FILE> decodedStream = std::make_unique<ALTIUM_COMPOUND_FILE>();
6337
6338 if( intCom->DecodeIntLibStream( *cfe, decodedStream.get() ) )
6339 compoundFiles.emplace_back( std::move( decodedStream ) );
6340 }
6341 }
6342
6343 CASE_INSENSITIVE_MAP<LIB_SYMBOL*>& cacheMapRef = m_libCache[aLibraryPath];
6344
6345 for( const std::unique_ptr<ALTIUM_COMPOUND_FILE>& altiumSchFilePtr : compoundFiles )
6346 {
6347 CASE_INSENSITIVE_MAP<LIB_SYMBOL*> parsed = ParseLibFile( *altiumSchFilePtr );
6348 cacheMapRef.insert( parsed.begin(), parsed.end() );
6349 }
6350
6351 m_timestamps[aLibraryPath] = getLibraryTimestamp( aLibraryPath );
6352 }
6353 catch( const CFB::CFBException& exception )
6354 {
6355 THROW_IO_ERROR( exception.what() );
6356 }
6357 catch( const std::exception& exc )
6358 {
6359 THROW_IO_ERRORF( _( "Error parsing Altium library: %s" ), exc.what() );
6360 }
6361}
6362
6363
6365 std::vector<int>& aFontSizes )
6366{
6367 const CFB::COMPOUND_FILE_ENTRY* file = aAltiumSchFile.FindStream( { "FileHeader" } );
6368
6369 if( file == nullptr )
6370 THROW_IO_ERROR( wxT( "FileHeader not found" ) );
6371
6372 ALTIUM_BINARY_PARSER reader( aAltiumSchFile, file );
6373
6374 if( reader.GetRemainingBytes() <= 0 )
6375 THROW_IO_ERROR( wxT( "FileHeader does not contain any data" ) );
6376
6377 std::map<wxString, wxString> properties = reader.ReadProperties();
6378
6379 wxString libtype = ALTIUM_PROPS_UTILS::ReadString( properties, "HEADER", "" );
6380
6381 if( libtype.CmpNoCase( "Protel for Windows - Schematic Library Editor Binary File Version 5.0" ) )
6382 THROW_IO_ERROR( _( "Expected Altium Schematic Library file version 5.0" ) );
6383
6384 for( auto& [key, value] : properties )
6385 {
6386 wxString upperKey = key.Upper();
6387 wxString remaining;
6388
6389 if( upperKey.StartsWith( "SIZE", &remaining ) )
6390 {
6391 if( !remaining.empty() )
6392 {
6393 int ind = wxAtoi( remaining );
6394
6395 if( ind < 1 )
6396 continue;
6397
6398 if( static_cast<int>( aFontSizes.size() ) < ind )
6399 aFontSizes.resize( ind );
6400
6401 // Altium stores in pt. 1 pt = 1/72 inch. 1 mil = 1/1000 inch.
6402 int scaled = schIUScale.MilsToIU( wxAtoi( value ) * 72.0 / 10.0 );
6403 aFontSizes[ind - 1] = scaled;
6404 }
6405 }
6406 }
6407}
6408
6409
6410void SCH_IO_ALTIUM::doEnumerateSymbolLib( const wxString& aLibraryPath,
6411 const std::map<std::string, UTF8>* aProperties,
6412 std::function<void(const wxString&, LIB_SYMBOL*)> aInserter )
6413{
6414 ensureLoadedLibrary( aLibraryPath, aProperties );
6415
6416 bool powerSymbolsOnly = ( aProperties &&
6417 aProperties->contains( SYMBOL_LIBRARY_ADAPTER::PropPowerSymsOnly ) );
6418
6419 auto it = m_libCache.find( aLibraryPath );
6420
6421 if( it != m_libCache.end() )
6422 {
6423 for( auto& [libnameStr, libSymbol] : it->second )
6424 {
6425 if( powerSymbolsOnly && !libSymbol->IsPower() )
6426 continue;
6427
6428 aInserter( libnameStr, libSymbol );
6429 }
6430 }
6431}
6432
6433
6434void SCH_IO_ALTIUM::EnumerateSymbolLib( wxArrayString& aSymbolNameList, const wxString& aLibraryPath,
6435 const std::map<std::string, UTF8>* aProperties )
6436{
6437 doEnumerateSymbolLib( aLibraryPath, aProperties,
6438 [&]( const wxString& aStr, LIB_SYMBOL* )
6439 {
6440 aSymbolNameList.Add( aStr );
6441 } );
6442}
6443
6444
6445void SCH_IO_ALTIUM::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
6446 const wxString& aLibraryPath,
6447 const std::map<std::string, UTF8>* aProperties )
6448{
6449 doEnumerateSymbolLib( aLibraryPath, aProperties,
6450 [&]( const wxString&, LIB_SYMBOL* aSymbol )
6451 {
6452 aSymbolList.emplace_back( aSymbol );
6453 } );
6454}
6455
6456
6457LIB_SYMBOL* SCH_IO_ALTIUM::LoadSymbol( const wxString& aLibraryPath, const wxString& aAliasName,
6458 const std::map<std::string, UTF8>* aProperties )
6459{
6460 ensureLoadedLibrary( aLibraryPath, aProperties );
6461
6462 auto it = m_libCache.find( aLibraryPath );
6463
6464 if( it != m_libCache.end() )
6465 {
6466 auto it2 = it->second.find( aAliasName );
6467
6468 if( it2 != it->second.end() )
6469 return it2->second;
6470 }
6471
6472 return nullptr;
6473}
int blue
int red
int green
int index
const char * name
ALTIUM_SCH_RECORD
ASCH_RECORD_ORIENTATION
const int ALTIUM_COMPONENT_NONE
ASCH_LABEL_JUSTIFICATION
ASCH_POLYLINE_LINESTYLE
ASCH_POWER_PORT_STYLE
wxString AltiumPinDesignatorToKiCad(const wxString &aDesignator)
Convert an Altium pin designator string to the equivalent KiCad pin number.
wxString AltiumSchSpecialStringsToKiCadVariables(const wxString &aString, const std::map< wxString, wxString > &aOverrides, std::set< wxString > *aUnmapped)
Convert the special strings in Altium schematic text to KiCad variables.
wxString AltiumEscapeTextVars(const wxString &aText)
Escape the KiCad variables and expressions in literal Altium text, which Altium shows as typed.
wxString AltiumPinNamesToKiCad(wxString &aString)
LIB_ID AltiumToKiCadLibID(const wxString &aLibName, const wxString &aLibReference)
std::vector< ALTIUM_PROJECT_VARIANT > ParseAltiumProjectVariants(const wxString &aPrjPcbPath)
Parse all [ProjectVariantN] sections from an Altium .PrjPcb project file.
std::map< wxString, wxString > ParseAltiumProjectParameters(const wxString &aPrjPcbPath)
Parse all [ParameterN] sections from an Altium .PrjPcb project file.
bool AltiumPowerPortNamesTakePriority(const wxString &aPrjPcbPath)
Read the project's Power Port Names Take Priority netlist option.
void ApplyAltiumProjectParametersToProject(PROJECT *aProject, const std::map< wxString, wxString > &aParameters)
Register Altium project parameters as KiCad project text variables so that imported board text refere...
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
constexpr double ARC_LOW_DEF_MM
Definition base_units.h:134
void TransformEllipseToBeziers(const ELLIPSE< T > &aEllipse, std::vector< BEZIER< T > > &aBeziers)
Transforms an ellipse or elliptical arc into a set of quadratic Bezier curves that approximate it.
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
std::map< wxString, ValueType, DETAIL::CASE_INSENSITIVE_COMPARER > CASE_INSENSITIVE_MAP
std::map< wxString, wxString > ReadProperties()
std::map< wxString, wxString > ReadProperties(std::function< std::map< wxString, wxString >(const std::string &)> handleBinaryData=[](const std::string &) { return std::map< wxString, wxString >();})
std::string ReadShortPascalString()
std::map< wxString, ALTIUM_SYMBOL_DATA > GetLibSymbols(const CFB::COMPOUND_FILE_ENTRY *aStart) const
const CFB::COMPOUND_FILE_ENTRY * FindStream(const std::vector< std::string > &aStreamPath) const
std::pair< int, std::string * > ReadCompressedString()
static int ReadInt(const std::map< wxString, wxString > &aProps, const wxString &aKey, int aDefault)
static wxString ReadString(const std::map< wxString, wxString > &aProps, const wxString &aKey, const wxString &aDefault)
Bezier curves to polygon converter.
void GetPoly(std::vector< VECTOR2I > &aOutput, int aMaxError=10)
Convert a Bezier curve to a polygon.
Generic cubic Bezier representation.
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:556
constexpr BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition box2.h:597
constexpr const Vec GetCenter() const
Definition box2.h:233
constexpr bool Contains(const Vec &aPoint) const
Definition box2.h:171
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr void Offset(coord_type dx, coord_type dy)
Definition box2.h:262
constexpr coord_type GetBottom() const
Definition box2.h:225
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:400
Calculate the connectivity of a schematic and generate netlists.
const NET_MAP & GetNetMap() const
void Recalculate(const SCH_SHEET_LIST &aSheetList, bool aUnconditional=false, std::function< void(SCH_ITEM *)> *aChangedItemHandler=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr)
Update the connection graph for the given list of sheets.
A subgraph is a set of items that are electrically connected on a single sheet.
double Sin() const
Definition eda_angle.h:177
bool IsHorizontal() const
Definition eda_angle.h:141
double Cos() const
Definition eda_angle.h:196
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
void SetModified()
Definition eda_item.cpp:270
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
virtual void SetEnd(const VECTOR2I &aEnd)
Definition eda_shape.h:338
virtual void SetCenter(const VECTOR2I &aCenter)
FILL_T GetFillMode() const
Definition eda_shape.h:151
void SetLineStyle(const LINE_STYLE aStyle)
int GetRadius() const
SHAPE_T GetShape() const
Definition eda_shape.h:178
virtual void SetBezierC2(const VECTOR2I &aPt)
Definition eda_shape.h:376
virtual void SetBezierC1(const VECTOR2I &aPt)
Definition eda_shape.h:373
void SetFillColor(const COLOR4D &aColor)
Definition eda_shape.h:163
void RebuildBezierToSegmentsPointsList(int aMaxError)
Rebuild the m_bezierPoints vertex list that approximate the Bezier curve by a list of segments.
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
COLOR4D GetFillColor() const
Definition eda_shape.h:162
virtual void SetWidth(int aWidth)
void SetFillMode(FILL_T aFill)
virtual void SetStart(const VECTOR2I &aStart)
Definition eda_shape.h:288
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true)
Definition eda_text.cpp:513
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual void SetTextPos(const VECTOR2I &aPoint)
Definition eda_text.cpp:557
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:395
void SetVertJustify(GR_TEXT_V_ALIGN_T aType)
Definition eda_text.cpp:379
GR_TEXT_H_ALIGN_T GetHorizJustify() const
Definition eda_text.h:239
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
void FlipHJustify()
Definition eda_text.h:247
virtual EDA_ANGLE GetTextAngle() const
Definition eda_text.h:178
void SetBold(bool aBold)
Set the text to be bold - this will also update the font if needed.
Definition eda_text.cpp:311
GR_TEXT_V_ALIGN_T GetVertJustify() const
Definition eda_text.h:242
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition eda_text.cpp:269
void SetItalic(bool aItalic)
Set the text to be italic - this will also update the font if needed.
Definition eda_text.cpp:291
void SetHorizJustify(GR_TEXT_H_ALIGN_T aType)
Definition eda_text.cpp:371
EE_TYPE Overlapping(const BOX2I &aRect) const
Definition sch_rtree.h:253
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
Plain ellipse / elliptical-arc data.
Definition ellipse.h:32
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:385
const wxString & GetName() const
Return a brief hard coded name for this IO interface.
Definition io_base.h:79
REPORTER * m_reporter
Reporter to log errors/warnings to, may be nullptr.
Definition io_base.h:264
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition io_base.h:267
virtual bool CanReadLibrary(const wxString &aFileName) const
Checks if this IO object can read the specified library file/directory.
Definition io_base.cpp:71
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
COLOR4D WithAlpha(double aAlpha) const
Return a color with the same color, but the given alpha.
Definition color4d.h:309
COLOR4D & FromCSSRGBA(int aRed, int aGreen, int aBlue, double aAlpha=1.0)
Initialize the color from a RGBA value with 0-255 red/green/blue and 0-1 alpha.
Definition color4d.cpp:596
wxString AsString() const
Definition kiid.cpp:423
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
UTF8 Format() const
Definition lib_id.cpp:132
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
Define a library symbol object.
Definition lib_symbol.h:114
void SetGlobalPower()
void FixupDrawItems()
This function finds the filled draw items that are covering up smaller draw items and replaces their ...
void SetBodyStyleNames(const std::vector< wxString > &aBodyStyleNames)
Definition lib_symbol.h:915
wxString GetName() const override
Definition lib_symbol.h:183
void SetUnitCount(int aCount, bool aDuplicateDrawItems)
Set the units per symbol count.
void SetDescription(const wxString &aDescription)
Set the Description field text value.
void SetKeyWords(const wxString &aKeyWords)
SCH_FIELD & GetValueField()
Definition lib_symbol.h:449
int GetBodyStyleCount() const override
The body styles are a property of the drawings, which a derived symbol inherits from its root symbol ...
int GetUnitCount() const override
void SetLibId(const LIB_ID &aLibId)
void AddDrawItem(SCH_ITEM *aItem, bool aSort=true)
Add a new draw aItem to the draw object list and sort according to aSort.
virtual void SetName(const wxString &aName)
SCH_FIELD & GetReferenceField()
Definition lib_symbol.h:453
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:351
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
int GetHeightIU(double aIUScale) const
Get the page height in IU.
Definition page_info.h:163
bool SetType(PAGE_SIZE_TYPE aPageSize, bool aIsPortrait=false)
Set the name of the page type and also the sizes and margins commonly associated with that type name.
static void SetCustomWidthMils(double aWidthInMils)
Set the width of Custom page in mils for any custom page constructed or made via SetType() after maki...
static void SetCustomHeightMils(double aHeightInMils)
Set the height of Custom page in mils for any custom page constructed or made via SetType() after mak...
A REFERENCE_IMAGE is a wrapper around a BITMAP_IMAGE that is displayed in an editor as a reference fo...
bool ReadImageFile(const wxString &aFullFilename)
Read and store an image file.
VECTOR2I GetSize() const
void SetImageScale(double aScale)
Set the image "zoom" value.
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
Holds all the data relating to one schematic.
Definition schematic.h:155
bool IsValid() const
A simple test if the schematic is loaded, not a complete one.
Definition schematic.h:384
void SetTopLevelSheets(const std::vector< SCH_SHEET * > &aSheets)
Replace the top level sheets, rebuilding the hierarchy and connectivity around them.
SCH_SHEET & Root() const
Definition schematic.h:282
VECTOR2I GetSize() const
void SetSize(const VECTOR2I &aSize)
VECTOR2I GetPosition() const override
Class for a wire to bus entry.
static bool IsBusLabel(const wxString &aLabel)
Test if aLabel has a bus notation.
VECTOR2I GetPosition() const override
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
void SetPosition(const VECTOR2I &aPosition) override
void SetText(const wxString &aText) override
void SetNameShown(bool aShown=true)
Definition sch_field.h:226
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this label.
void SetSpinStyle(SPIN_STYLE aSpinStyle) override
void SetSpinStyle(SPIN_STYLE aSpinStyle) override
void ParseFileHeader(const ALTIUM_COMPOUND_FILE &aAltiumSchFile)
std::vector< wxFileName > m_projectDocuments
void ParseSignalHarness(const std::map< wxString, wxString > &aProperties)
std::map< int, ASCH_TEMPLATE > m_altiumTemplates
void ParseLibDesignator(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbols=nullsym, std::vector< int > &aFontSize=nullint)
std::map< int, ASCH_SYMBOL > m_altiumComponents
void ParsePort(const ASCH_PORT &aElem)
void ParseNote(const std::map< wxString, wxString > &aProperties)
std::map< std::vector< wxString >, SCH_SCREEN * > m_loadedScreens
void ParseAltiumSch(const wxString &aFileName)
std::vector< ASCH_PORT > m_altiumPortsCurrentSheet
void ParseSheetName(const std::map< wxString, wxString > &aProperties)
void ParseBusEntry(const std::map< wxString, wxString > &aProperties)
wxFileName ResolveSheetFileName(const wxString &aParentPath, const wxString &aSheetFileName) const
SCH_SHEET * getCurrentSheet()
void ParseStorage(const ALTIUM_COMPOUND_FILE &aAltiumSchFile)
std::map< wxString, LIB_SYMBOL * > m_powerSymbols
void ParseBus(const std::map< wxString, wxString > &aProperties)
void ParseFileName(const std::map< wxString, wxString > &aProperties)
static bool isASCIIFile(const wxString &aFileName)
wxString m_libName
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...
std::map< int, SCH_SHEET * > m_sheets
void ParseLibHeader(const ALTIUM_COMPOUND_FILE &aAltiumSchFile, std::vector< int > &aFontSizes)
void ParseHarnessPort(const ASCH_PORT &aElem)
void ParseRoundRectangle(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void pruneCyclicSheets(const std::vector< SCH_SHEET * > &aCyclicSheets, SCH_SCREEN *aScreen)
Remove sheet symbols referencing a parse-stack file (an unrepresentable cycle), converting their pins...
int GetModifyHash() const override
Return the modification hash from the library cache.
std::map< wxString, CASE_INSENSITIVE_MAP< LIB_SYMBOL * > > m_libCache
std::map< int, int > m_altiumImplementationList
void attachEmptySheetScreen(SCH_SHEET *aSheet, const wxString &aMissingFile)
Give a sheet whose source file is missing an empty screen with a file of its own; aMissingFile is emp...
std::map< wxString, SCH_SCREEN * > m_missingScreens
void ParseTextFrame(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym, std::vector< int > &aFontSize=nullint)
void ParsePolygon(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void fixupSymbolPinNameNumbers(SYMBOL *aSymbol)
VECTOR2I m_sheetOffset
void EnsureSheetSymbolNames()
void ParseRecord(int index, std::map< wxString, wxString > &properties, const wxString &aSectionName)
std::vector< ASCH_PORT > m_altiumHarnessPortsCurrentSheet
void ParseDesignator(const std::map< wxString, wxString > &aProperties)
int m_harnessOwnerIndexOffset
void ParsePortHelper(const ASCH_PORT &aElem)
std::set< wxString > m_subsheetFiles
static bool checkFileHeader(const wxString &aFileName)
long long getLibraryTimestamp(const wxString &aLibraryPath) const
void ParseSheetEntry(const std::map< wxString, wxString > &aProperties)
SCH_SHEET * m_rootSheet
static bool isBinaryFile(const wxString &aFileName)
void ParseHarnessType(const std::map< wxString, wxString > &aProperties)
wxString m_rootFilepath
void ParseJunction(const std::map< wxString, wxString > &aProperties)
SCHEMATIC * m_schematic
wxString m_rootSheetFile
void ParseLibParameter(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym, std::vector< int > &aFontSize=nullint)
std::set< wxString > m_parsedFiles
void ParseASCIISchematic(const wxString &aFileName)
void ParsePolyline(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
std::unique_ptr< ASCH_SHEET > m_altiumSheet
void ParseComponent(int aIndex, const std::map< wxString, wxString > &aProperties)
std::unique_ptr< TITLE_BLOCK > m_currentTitleBlock
SCH_SHEET * LoadSchematicProject(SCHEMATIC *aSchematic, const std::map< std::string, UTF8 > *aProperties)
void ParseImage(const std::map< wxString, wxString > &aProperties)
void ParseArc(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void ParseNetLabel(const std::map< wxString, wxString > &aProperties)
void ParseNoERC(const std::map< wxString, wxString > &aProperties)
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,...
std::unordered_map< wxString, SEVERITY > m_errorMessages
std::map< wxString, int > m_parsingFiles
void ParseImplementationList(int aIndex, const std::map< wxString, wxString > &aProperties)
std::vector< LIB_SYMBOL * > ParseLibComponent(const std::map< wxString, wxString > &aProperties)
void ParseSheet(const std::map< wxString, wxString > &aProperties)
void ParseParameter(const std::map< wxString, wxString > &aProperties)
bool ShouldPutItemOnSheet(int aOwnerindex)
void NormalizeRepeatedSheetInstances()
void AddLibTextBox(const ASCH_TEXT_FRAME *aElem, std::vector< LIB_SYMBOL * > &aSymbol=nullsym, std::vector< int > &aFontSize=nullint)
bool CanReadSchematicFile(const wxString &aFileName) const override
Checks if this SCH_IO can read the specified schematic file.
void ParsePieChart(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void ParseEllipticalArc(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
std::map< int, HARNESS > m_altiumHarnesses
void ParseEllipse(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
std::set< wxString > m_sheetSpecialStrings
void ParseWire(const std::map< wxString, wxString > &aProperties)
void ParseHarnessEntry(const std::map< wxString, wxString > &aProperties)
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.
void ParseImplementation(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void ParseTemplate(int aIndex, const std::map< wxString, wxString > &aProperties)
void ParseAdditional(const ALTIUM_COMPOUND_FILE &aAltiumSchFile)
friend struct PARSE_FILE_GUARD
std::set< wxString > m_sheetFiles
std::set< wxString > m_unsetSheetParams
void AddTextBox(const ASCH_TEXT_FRAME *aElem)
void ParsePowerPort(const std::map< wxString, wxString > &aProperties)
bool CanReadLibrary(const wxString &aFileName) const override
Checks if this IO object can read the specified library file/directory.
std::map< const SCH_SYMBOL *, wxString > m_altiumSymbolToUid
const ASCH_STORAGE_FILE * GetFileFromStorage(const wxString &aFilename) const
void ParseRectangle(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void doEnumerateSymbolLib(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties, std::function< void(const wxString &, LIB_SYMBOL *)> aInserter)
wxString getLibName()
void NameNetsAfterNetLabels()
Name power nets after their net labels, as Altium does unless Power Port Names Take Priority is set.
std::vector< ASCH_STORAGE_FILE > m_altiumStorage
SCH_SHEET_PATH m_sheetPath
void PostProcessBusLabels()
wxString claimSheetFile(const wxString &aStem)
Claim a file in the project folder for a sheet screen that neither the root nor another sheet holds,...
void ParseLabel(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym, std::vector< int > &aFontSize=nullint)
CASE_INSENSITIVE_MAP< LIB_SYMBOL * > ParseLibFile(const ALTIUM_COMPOUND_FILE &aAltiumSchFile)
void ParseBezier(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void ParseLine(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
void ParseCircle(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
std::map< int, SCH_SYMBOL * > m_symbols
void ParseSheetSymbol(int aIndex, const std::map< wxString, wxString > &aProperties)
std::map< wxString, long long > m_timestamps
wxFileName getLibFileName()
SCH_SCREEN * getCurrentScreen()
void ParsePin(const std::map< wxString, wxString > &aProperties, std::vector< LIB_SYMBOL * > &aSymbol=nullsym)
std::map< int, LIB_SYMBOL * > m_libSymbols
void ParseHarnessConnector(int aIndex, const std::map< wxString, wxString > &aProperties)
void ensureLoadedLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties)
virtual bool CanReadSchematicFile(const wxString &aFileName) const
Checks if this SCH_IO can read the specified schematic file.
Definition sch_io.cpp:47
SCH_IO(const wxString &aName)
Definition sch_io.h:406
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
virtual void SetBodyStyle(int aBodyStyle)
Definition sch_item.h:252
virtual void SetUnit(int aUnit)
Definition sch_item.h:242
void MirrorHorizontally(int aCenter) override
Mirror item horizontally about aCenter.
void SetShape(LABEL_FLAG_SHAPE aShape)
Definition sch_label.h:179
const BOX2I GetBoundingBox() const override
Return the bounding box of the label including its fields.
void MirrorVertically(int aCenter) override
Mirror item vertically about aCenter.
void AutoplaceFields(SCH_SCREEN *aScreen, AUTOPLACE_ALGO aAlgo) override
virtual void SetSpinStyle(SPIN_STYLE aSpinStyle)
Segment description base class to describe items which have 2 end points (track, wire,...
Definition sch_line.h:39
void SetStartPoint(const VECTOR2I &aPosition)
Definition sch_line.h:137
bool HitTest(const VECTOR2I &aPosition, int aAccuracy=0) const override
Test if aPosition is inside or on the boundary of this item.
Definition sch_line.cpp:910
std::vector< VECTOR2I > GetConnectionPoints() const override
Add all the connection points for this item to aPoints.
Definition sch_line.cpp:811
bool IsWire() const
Return true if the line is a wire.
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
Definition sch_line.cpp:318
void SetLineWidth(const int aSize)
Definition sch_line.cpp:440
VECTOR2I GetEndPoint() const
Definition sch_line.h:145
VECTOR2I GetStartPoint() const
Definition sch_line.h:136
SEG GetSeg() const
Get the geometric aspect of the wire as a SEG.
Definition sch_line.h:155
bool IsBus() const
Return true if the line is a bus.
virtual void SetStroke(const STROKE_PARAMS &aStroke) override
Definition sch_line.h:199
int GetLineWidth() const
Definition sch_line.h:195
KIGFX::COLOR4D GetLineColor() const
Return COLOR4D::UNSPECIFIED if a custom color hasn't been set for this line.
Definition sch_line.cpp:398
void SetLineColor(const KIGFX::COLOR4D &aColor)
Definition sch_line.cpp:374
void SetEndPoint(const VECTOR2I &aPosition)
Definition sch_line.h:146
bool IsGlobalPower() const
Return whether this pin forms a global power connection: i.e., is part of a power symbol and of type ...
Definition sch_pin.cpp:484
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
SCH_SCREEN * GetNext()
void UpdateSymbolLinks(REPORTER *aReporter=nullptr)
Initialize the LIB_SYMBOL reference for each SCH_SYMBOL found in the full schematic.
SCH_SCREEN * GetFirst()
void ClearEditFlags()
std::vector< SCH_SHEET_INSTANCE > m_sheetInstances
Definition sch_screen.h:804
void SetTitleBlock(const TITLE_BLOCK &aTitleBlock)
Definition sch_screen.h:171
void Append(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
void AddBusAlias(std::shared_ptr< BUS_ALIAS > aAlias)
Add a bus alias definition.
void SetPageSettings(const PAGE_INFO &aPageSettings)
Definition sch_screen.h:145
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
const wxString & GetFileName() const
Definition sch_screen.h:157
bool IsTerminalPoint(const VECTOR2I &aPosition, int aLayer) const
Test if aPosition is a connection point on aLayer.
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
bool Remove(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Remove aItem from the schematic associated with this screen.
void Update(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Refresh a changed item in the tree and invalidate connectivity.
void DeleteItem(SCH_ITEM *aItem)
Remove aItem from the linked list and deletes the object.
void SetFilled(bool aFilled) override
void SetStroke(const STROKE_PARAMS &aStroke) override
void AddPoint(const VECTOR2I &aPosition)
STROKE_PARAMS GetStroke() const override
Definition sch_shape.h:59
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
wxString GetNextPageNumber() const
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
KIID_PATH Path() const
Get the sheet path as an KIID_PATH.
SCH_SCREEN * LastScreen()
void SetPageNumber(const wxString &aPageNumber)
Set the sheet instance user definable page number.
SCH_SHEET * Last() const
Return a pointer to the last SCH_SHEET of the list.
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.
void SetPosition(const VECTOR2I &aPosition) override
void SetSide(SHEET_SIDE aEdge)
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
void SetBorderColor(KIGFX::COLOR4D aColor)
Definition sch_sheet.h:196
void SetFileName(const wxString &aFilename)
Definition sch_sheet.h:434
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this sheet.
wxString GetName() const
Definition sch_sheet.h:150
void SetBackgroundColor(KIGFX::COLOR4D aColor)
Definition sch_sheet.h:199
void SetName(const wxString &aName)
Definition sch_sheet.h:185
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
SCH_FIELD * AddField(const SCH_FIELD &aField)
Add aFieldName to the list of fields.
Variant information for a schematic symbol.
void InitializeAttributes(const SCH_SYMBOL &aSymbol)
Schematic symbol object.
Definition sch_symbol.h:76
void SetLibId(const LIB_ID &aName)
void SetPosition(const VECTOR2I &aPosition) override
Definition sch_symbol.h:959
void SetBodyStyle(int aBodyStyle) override
bool AddSheetPathReferenceEntryIfMissing(const KIID_PATH &aSheetPath)
Add an instance to the alternate references list (m_instances), if this entry does not already exist.
void SetRef(const SCH_SHEET_PATH *aSheet, const wxString &aReference)
Set the base reference for the given sheet path for this symbol.
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
void SetOrientation(int aOrientation)
Compute the new transform matrix based on aOrientation for the symbol which is applied to the current...
void SetFootprintFieldText(const wxString &aFootprint)
VECTOR2I GetPosition() const override
Definition sch_symbol.h:958
bool ResolveTextVar(const SCH_SHEET_PATH *aPath, wxString *token, int aDepth=0) const
Resolve any references to system tokens supported by the symbol.
void SetValueFieldText(const wxString &aValue, const SCH_SHEET_PATH *aInstance=nullptr, const wxString &aVariantName=wxEmptyString)
void AddVariant(const SCH_SHEET_PATH &aInstance, const SCH_SYMBOL_VARIANT &aVariant)
SCH_FIELD * AddField(const SCH_FIELD &aField)
Add a field to the symbol.
void SetLibSymbol(LIB_SYMBOL *aLibSymbol)
Set this schematic symbol library symbol reference to aLibSymbol.
const wxString GetRef(const SCH_SHEET_PATH *aSheet, bool aIncludeUnit=false) const override
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
VECTOR2I GetPosition() const override
Definition sch_text.h:143
virtual void Rotate90(bool aClockwise)
Definition sch_text.cpp:257
void SetPosition(const VECTOR2I &aPosition) override
Definition sch_text.h:144
Simple container to manage line stroke parameters.
int GetWidth() const
void SetLineStyle(LINE_STYLE aLineStyle)
void SetWidth(int aWidth)
void SetColor(const KIGFX::COLOR4D &aColor)
KIGFX::COLOR4D GetColor() const
static const char * PropPowerSymsOnly
A base class for LIB_SYMBOL and SCH_SYMBOL.
Definition symbol.h:60
virtual void SetShowPinNumbers(bool aShow)
Set or clear the pin number visibility flag.
Definition symbol.h:174
const TRANSFORM & GetTransform() const
Definition symbol.h:247
virtual void SetShowPinNames(bool aShow)
Set or clear the pin name visibility flag.
Definition symbol.h:168
for transforming drawing coordinates for a wxDC device context.
Definition transform.h:42
TRANSFORM InverseTransform() const
Calculate the Inverse mirror/rotation transform.
Definition transform.cpp:55
VECTOR2I TransformCoordinate(const VECTOR2I &aPoint) const
Calculate a new coordinate according to the mirror/rotation transform.
Definition transform.cpp:40
wxString wx_str() const
Definition utf8.cpp:41
bool m_ExcludedFromBOM
std::map< wxString, wxString > m_Fields
bool m_ExcludedFromPosFiles
constexpr extended_type SquaredEuclideanNorm() const
Compute the squared euclidean norm of the vector, which is defined as (x ** 2 + y ** 2).
Definition vector2d.h:312
static REPORTER & GetInstance()
Definition reporter.cpp:324
@ PURERED
Definition color4d.h:67
@ PUREBLUE
Definition color4d.h:64
@ BLACK
Definition color4d.h:40
#define DEFAULT_PINNUM_SIZE
The default pin number size when creating pins(can be changed in preference menu)
#define DEFAULT_PINNAME_SIZE
The default pin name size when creating pins(can be changed in preference menu)
#define DEFAULT_TEXT_SIZE
The default text size in mils. (can be changed in preference menu)
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE ANGLE_VERTICAL
Definition eda_angle.h:469
static constexpr EDA_ANGLE ANGLE_HORIZONTAL
Definition eda_angle.h:468
FILL_T
Definition eda_fill.h:29
@ FILLED_WITH_COLOR
Definition eda_fill.h:33
@ NO_FILL
Definition eda_fill.h:30
@ FILLED_WITH_BG_BODYCOLOR
Definition eda_fill.h:32
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
#define IS_NEW
New item, just created.
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
#define THROW_IO_CANCELLED()
static const std::string KiCadSchematicFileExtension
static const std::string KiCadSymbolLibFileExtension
KIID niluuid(0)
@ LAYER_DEVICE
Definition layer_ids.h:497
@ LAYER_WIRE
Definition layer_ids.h:483
@ LAYER_NOTES
Definition layer_ids.h:498
@ LAYER_BUS
Definition layer_ids.h:484
constexpr int Mils2IU(const EDA_IU_SCALE &aIuScale, int mils)
Definition eda_units.h:169
bool fileStartsWithPrefix(const wxString &aFilePath, const wxString &aPrefix, bool aIgnoreWhitespace)
Check if a file starts with a defined string.
Definition io_utils.cpp:33
const std::vector< uint8_t > COMPOUND_FILE_HEADER
Definition io_utils.cpp:30
bool fileHasBinaryHeader(const wxString &aFilePath, const std::vector< uint8_t > &aHeader, size_t aOffset)
Check if a file starts with a defined binary header.
Definition io_utils.cpp:60
const VECTOR2I & GetOtherEnd(const SEG &aSeg, const VECTOR2I &aPoint)
Get the end point of the segment that is not the given point.
bool signbit(T v)
Integral version of std::signbit that works all compilers.
Definition kicad_algo.h:172
STL namespace.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
@ PT_INPUT
usual pin input: must be connected
Definition pin_type.h:33
@ PT_OUTPUT
usual output
Definition pin_type.h:34
@ PT_TRISTATE
tri state bus pin
Definition pin_type.h:36
@ PT_BIDI
input or output (like port for a microprocessor)
Definition pin_type.h:35
@ PT_OPENEMITTER
pin type open emitter
Definition pin_type.h:45
@ PT_OPENCOLLECTOR
pin type open collector
Definition pin_type.h:44
@ PT_POWER_IN
power input (GND, VCC for ICs). Must be connected to a power output.
Definition pin_type.h:42
@ PT_UNSPECIFIED
unknown electrical properties: creates always a warning when connected
Definition pin_type.h:41
@ PT_PASSIVE
pin for passive symbols: must be connected, and can be connected to any pin.
Definition pin_type.h:39
@ PIN_UP
The pin extends upwards from the connection point: Probably on the bottom side of the symbol.
Definition pin_type.h:123
@ PIN_RIGHT
The pin extends rightwards from the connection point.
Definition pin_type.h:107
@ PIN_LEFT
The pin extends leftwards from the connection point: Probably on the right side of the symbol.
Definition pin_type.h:114
@ PIN_DOWN
The pin extends downwards from the connection: Probably on the top side of the symbol.
Definition pin_type.h:131
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_DEBUG
@ RPT_SEVERITY_INFO
@ RPT_SEVERITY_ACTION
static COLOR4D GetColorFromInt(int color)
static ITEM_NET_CODES itemNetCodes(const CONNECTION_GRAPH &aGraph, const std::map< const SCH_ITEM *, const SCH_ITEM * > &aOriginals)
static void SetLibShapeFillAndColor(const ASCH_FILL_INTERFACE &elem, SCH_SHAPE *shape, ALTIUM_SCH_RECORD aType, int aStrokeColor)
VECTOR2I HelperGeneratePowerPortGraphics(LIB_SYMBOL *aKsymbol, ASCH_POWER_PORT_STYLE aStyle, REPORTER *aReporter)
static void SetSchShapeLine(const ASCH_BORDER_INTERFACE &elem, SCH_SHAPE *shape)
static const VECTOR2I GetRelativePosition(const VECTOR2I &aPosition, const SCH_SYMBOL *aSymbol)
static void SetLibShapeLine(const ASCH_BORDER_INTERFACE &elem, SCH_SHAPE *shape, ALTIUM_SCH_RECORD aType)
static wxString AltiumParseKey(const wxFileName &aFileName)
void AdjustTextForSymbolOrientation(SCH_TEXT *aText, const ASCH_SYMBOL &aSymbol)
static LINE_STYLE GetPlotDashType(const ASCH_POLYLINE_LINESTYLE linestyle)
static void SetSchShapeFillAndColor(const ASCH_FILL_INTERFACE &elem, SCH_SHAPE *shape)
void AdjustFieldForSymbolOrientation(SCH_FIELD *aField, const ASCH_SYMBOL &aSymbol)
wxString AltiumDeriveSheetName(const wxString &aFilename, const std::set< wxString > &aExistingNames)
static bool sameNets(const ITEM_NET_CODES &aBefore, const ITEM_NET_CODES &aAfter)
wxString AltiumWrapBusLabel(const wxString &aText)
std::map< std::pair< KIID_PATH, const SCH_ITEM * >, int > ITEM_NET_CODES
void SetTextPositioning(EDA_TEXT *text, ASCH_LABEL_JUSTIFICATION justification, ASCH_RECORD_ORIENTATION orientation)
@ AUTOPLACE_AUTO
Definition sch_item.h:75
@ L_BIDI
Definition sch_label.h:100
@ L_UNSPECIFIED
Definition sch_label.h:102
@ L_OUTPUT
Definition sch_label.h:99
@ L_INPUT
Definition sch_label.h:98
Utility functions for working with shapes.
wxString UnescapeString(const wxString &aSource)
bool ReplaceIllegalFileNameChars(std::string &aName, int aReplaceChar)
Checks aName for illegal file name characters.
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_QUOTED_STR
@ CTX_NETNAME
static std::vector< std::string > split(const std::string &aStr, const std::string &aDelim)
Split the input string into a vector of output strings.
LINE_STYLE
Dashed line types.
A project-level assembly variant parsed from an Altium .PrjPcb file.
A single component variation within an Altium project variant.
wxString uniqueId
wxString designator
double m_StartAngle
VECTOR2I m_Center
std::vector< VECTOR2I > points
VECTOR2I corner
VECTOR2I location
std::vector< VECTOR2I > points
ASCH_LABEL_JUSTIFICATION justification
ASCH_RECORD_ORIENTATION orientation
ASCH_RECORD_ORIENTATION orientation
ASCH_SHEET_ENTRY_SIDE m_harnessConnectorSide
int DistanceFromTop
ASCH_SHEET_ENTRY_SIDE Side
wxString Name
ASCH_RECORD_ORIENTATION orientation
ASCH_LABEL_JUSTIFICATION justification
ASCH_POLYLINE_LINESTYLE LineStyle
ASCH_LABEL_JUSTIFICATION justification
ASCH_RECORD_ORIENTATION orientation
ASCH_RECORD_ORIENTATION orientation
ASCH_LABEL_JUSTIFICATION justification
VECTOR2I location
ASCH_PIN_SYMBOL::PTYPE symbolOuterEdge
VECTOR2I kicadLocation
wxString designator
ASCH_PIN_ELECTRICAL electrical
ASCH_PIN_SYMBOL::PTYPE symbolInnerEdge
ASCH_RECORD_ORIENTATION orientation
std::vector< VECTOR2I > points
ASCH_POLYLINE_LINESTYLE LineStyle
std::vector< VECTOR2I > Points
VECTOR2I Location
ASCH_PORT_IOTYPE IOtype
wxString HarnessType
ASCH_PORT_STYLE Style
ASCH_POWER_PORT_STYLE style
ASCH_RECORD_ORIENTATION orientation
wxString name
int distanceFromTop
ASCH_SHEET_ENTRY_SIDE side
ASCH_PORT_IOTYPE iotype
wxString harnessType
ASCH_RECORD_ORIENTATION orientation
std::vector< VECTOR2I > points
std::vector< char > data
wxString componentdescription
wxString libreference
wxString sourcelibraryname
ASCH_TEXT_FRAME_ALIGNMENT Alignment
std::vector< VECTOR2I > points
ASCH_SHEET_ENTRY_SIDE m_harnessConnectorSide
VECTOR2I m_location
std::vector< HARNESS_PORT > m_ports
HARNESS_PORT m_entry
wxString m_name
VECTOR2I m_size
SCH_IO_ALTIUM * m_owner
PARSE_FILE_GUARD(SCH_IO_ALTIUM *aOwner, std::vector< wxString > aKeys)
PARSE_FILE_GUARD & operator=(const PARSE_FILE_GUARD &)=delete
std::vector< wxString > m_keys
PARSE_FILE_GUARD(SCH_IO_ALTIUM *aOwner, const wxString &aKey)
PARSE_FILE_GUARD(const PARSE_FILE_GUARD &)=delete
A simple container for sheet instance information.
@ SYM_ORIENT_270
Definition symbol.h:39
@ SYM_MIRROR_Y
Definition symbol.h:41
@ SYM_ORIENT_180
Definition symbol.h:38
@ SYM_ORIENT_90
Definition symbol.h:37
@ SYM_ORIENT_0
Definition symbol.h:36
@ USER
The field ID hasn't been set yet; field is invalid.
@ INTERSHEET_REFS
Global label cross-reference page numbers.
@ DESCRIPTION
Field Description of part, i.e. "1/4W 1% Metal Film Resistor".
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ SHEET_REF_SUFFIX
Optional sheet field appended to the references of the sheet's symbols.
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
static EDA_ORIENTATION orientation(double d)
std::string path
KIBIS top(path, &reporter)
KIBIS_PIN * pin
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
VECTOR2I center
int radius
VECTOR2I end
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
wxString result
Test unit parsing edge cases and error handling.
GR_TEXT_H_ALIGN_T
This is API surface mapped to common.types.HorizontalAlignment.
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
GR_TEXT_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
@ SCH_LINE_T
Definition typeinfo.h:159
@ LIB_SYMBOL_T
Definition typeinfo.h:144
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_LABEL_T
Definition typeinfo.h:163
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_HIER_LABEL_T
Definition typeinfo.h:165
@ SCH_GLOBAL_LABEL_T
Definition typeinfo.h:164
@ SCH_PIN_T
Definition typeinfo.h:149
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
Definition of file extensions used in Kicad.