KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_io_eagle.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) 2017 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * @author Alejandro GarcĂ­a Montoro <[email protected]>
8 * @author Maciej Suminski <[email protected]>
9 * @author Russell Oliver <[email protected]>
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation; either version 3
14 * of the License, or (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
26
27#include <algorithm>
28#include <memory>
29#include <fmt/format.h>
30#include <wx/filename.h>
31#include <wx/string.h>
32#include <wx/tokenzr.h>
33#include <wx/wfstream.h>
34#include <wx/txtstrm.h>
35#include <wx/mstream.h>
36#include <wx/xml/xml.h>
37
38#include <advanced_config.h>
39#include <font/fontconfig.h>
40#include <reporter.h>
43#include <lib_id.h>
44#include <progress_reporter.h>
45#include <project.h>
47#include <project_sch.h>
48#include <sch_bus_entry.h>
49#include <sch_edit_frame.h>
51#include <sch_junction.h>
52#include <sch_label.h>
53#include <sch_marker.h>
54#include <sch_pin.h>
55#include <sch_screen.h>
56#include <sch_shape.h>
57#include <sch_sheet.h>
58#include <sch_sheet_path.h>
59#include <sch_sheet_pin.h>
60#include <sch_symbol.h>
61#include <schematic.h>
62#include <string_utils.h>
65
66
67// Eagle schematic axes are aligned with x increasing left to right and Y increasing bottom to top
68// KiCad schematic axes are aligned with x increasing left to right and Y increasing top to bottom.
69
70using namespace std;
71
75static const std::map<wxString, ELECTRICAL_PINTYPE> pinDirectionsMap = {
76 { wxT( "sup" ), ELECTRICAL_PINTYPE::PT_POWER_IN },
77 { wxT( "pas" ), ELECTRICAL_PINTYPE::PT_PASSIVE },
78 { wxT( "out" ), ELECTRICAL_PINTYPE::PT_OUTPUT },
79 { wxT( "in" ), ELECTRICAL_PINTYPE::PT_INPUT },
80 { wxT( "nc" ), ELECTRICAL_PINTYPE::PT_NC },
81 { wxT( "io" ), ELECTRICAL_PINTYPE::PT_BIDI },
83 { wxT( "hiz" ), ELECTRICAL_PINTYPE::PT_TRISTATE },
84 { wxT( "pwr" ), ELECTRICAL_PINTYPE::PT_POWER_IN },
85};
86
87
89static BOX2I getSheetBbox( SCH_SHEET* aSheet )
90{
91 BOX2I bbox;
92
93 for( SCH_ITEM* item : aSheet->GetScreen()->Items() )
94 bbox.Merge( item->GetBoundingBox() );
95
96 return bbox;
97}
98
99
101static inline wxString extractNetName( const wxString& aPinName )
102{
103 return aPinName.BeforeFirst( '@' );
104}
105
106
108static bool isEagleAutoNetName( const wxString& aNetName )
109{
110 wxString number;
111
112 return aNetName.StartsWith( wxS( "N$" ), &number ) && !number.empty() && number.IsNumber();
113}
114
115
120
121
123{
124 SCH_SHEET* currentSheet = m_sheetPath.Last();
125 wxCHECK( currentSheet, nullptr );
126 return currentSheet->GetScreen();
127}
128
129
131{
132 if( m_libName.IsEmpty() )
133 {
134 // Try to come up with a meaningful name
135 m_libName = m_schematic->Project().GetProjectName();
136
137 if( m_libName.IsEmpty() )
138 {
139 wxFileName fn( m_rootSheet->GetFileName() );
140 m_libName = fn.GetName();
141 }
142
143 if( m_libName.IsEmpty() )
144 m_libName = wxT( "noname" );
145
146 m_libName += wxT( "-eagle-import" );
148 }
149
150 return m_libName;
151}
152
153
155{
156 wxFileName fn;
157
158 wxCHECK( m_schematic, fn );
159
160 fn.Assign( m_schematic->Project().GetProjectPath(), getLibName(),
162
163 return fn;
164}
165
166
167void SCH_IO_EAGLE::loadLayerDefs( const std::vector<std::unique_ptr<ELAYER>>& aLayers )
168{
169 // match layers based on their names
170 for( const std::unique_ptr<ELAYER>& elayer : aLayers )
171 {
188
189 switch ( elayer->number)
190 {
191 case 91:
192 m_layerMap[elayer->number] = LAYER_WIRE;
193 break;
194 case 92:
195 m_layerMap[elayer->number] = LAYER_BUS;
196 break;
197 case 97:
198 case 98:
199 m_layerMap[elayer->number] = LAYER_NOTES;
200 break;
201
202 default:
203 break;
204 }
205 }
206}
207
208
210{
211 auto it = m_layerMap.find( aEagleLayer );
212 return it == m_layerMap.end() ? LAYER_NOTES : it->second;
213}
214
215
216// Return the KiCad symbol orientation based on eagle rotation degrees.
218{
219 int roti = int( eagleDegrees );
220
221 switch( roti )
222 {
223 case 0: return SYM_ORIENT_0;
224 case 90: return SYM_ORIENT_90;
225 case 180: return SYM_ORIENT_180;
226 case 270: return SYM_ORIENT_270;
227
228 default:
229 wxASSERT_MSG( false, wxString::Format( wxT( "Unhandled orientation (%d degrees)" ),
230 roti ) );
231 return SYM_ORIENT_0;
232 }
233}
234
235
236// Calculate text alignment based on the given Eagle text alignment parameters.
237static void eagleToKicadAlignment( EDA_TEXT* aText, int aEagleAlignment, int aRelDegress,
238 bool aMirror, bool aSpin, int aAbsDegress )
239{
240 int align = aEagleAlignment;
241
242 if( aRelDegress == 90 )
243 {
245 }
246 else if( aRelDegress == 180 )
247 {
248 align = -align;
249 }
250 else if( aRelDegress == 270 )
251 {
253 align = -align;
254 }
255
256 if( aMirror == true )
257 {
258 if( aAbsDegress == 90 || aAbsDegress == 270 )
259 {
260 if( align == ETEXT::BOTTOM_RIGHT )
261 align = ETEXT::TOP_RIGHT;
262 else if( align == ETEXT::BOTTOM_LEFT )
263 align = ETEXT::TOP_LEFT;
264 else if( align == ETEXT::TOP_LEFT )
265 align = ETEXT::BOTTOM_LEFT;
266 else if( align == ETEXT::TOP_RIGHT )
267 align = ETEXT::BOTTOM_RIGHT;
268 }
269 else if( aAbsDegress == 0 || aAbsDegress == 180 )
270 {
271 if( align == ETEXT::BOTTOM_RIGHT )
272 align = ETEXT::BOTTOM_LEFT;
273 else if( align == ETEXT::BOTTOM_LEFT )
274 align = ETEXT::BOTTOM_RIGHT;
275 else if( align == ETEXT::TOP_LEFT )
276 align = ETEXT::TOP_RIGHT;
277 else if( align == ETEXT::TOP_RIGHT )
278 align = ETEXT::TOP_LEFT;
279 else if( align == ETEXT::CENTER_LEFT )
280 align = ETEXT::CENTER_RIGHT;
281 else if( align == ETEXT::CENTER_RIGHT )
282 align = ETEXT::CENTER_LEFT;
283 }
284 }
285
286 switch( align )
287 {
288 case ETEXT::CENTER:
291 break;
292
296 break;
297
301 break;
302
306 break;
307
308 case ETEXT::TOP_LEFT:
311 break;
312
313 case ETEXT::TOP_RIGHT:
316 break;
317
321 break;
322
326 break;
327
331 break;
332
333 default:
336 break;
337 }
338}
339
340
341SCH_IO_EAGLE::SCH_IO_EAGLE() : SCH_IO( wxS( "EAGLE" ) ),
342 m_rootSheet( nullptr ),
343 m_schematic( nullptr ),
344 m_sheetIndex( 1 )
345{
346}
347
348
352
353
355{
356 return 0;
357}
358
359
360SCH_SHEET* SCH_IO_EAGLE::LoadSchematicFile( const wxString& aFileName, SCHEMATIC* aSchematic,
361 SCH_SHEET* aAppendToMe,
362 const std::map<std::string, UTF8>* aProperties )
363{
364 wxASSERT( !aFileName || aSchematic != nullptr );
365
366 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
368
369 m_filename = aFileName;
370 m_schematic = aSchematic;
371
373 {
374 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
375
376 if( !m_progressReporter->KeepRefreshing() )
378 }
379
380 // Load the document
381 wxXmlDocument xmlDocument = loadXmlDocument( m_filename.GetFullPath() );
382
383 // Retrieve the root as current node
384 wxXmlNode* currentNode = xmlDocument.GetRoot();
385
387 m_progressReporter->SetNumPhases( static_cast<int>( GetNodeCount( currentNode ) ) );
388
389 wxFileName newFilename( m_filename );
390 newFilename.SetExt( FILEEXT::KiCadSchematicFileExtension );
391
392 // Owns the temporary VR for the non-append path so it is freed when this scope exits.
393 // The actual schematic VR will be created by SetTopLevelSheets() inside loadSchematic().
394 unique_ptr<SCH_SHEET> tempVROwner;
395
396 if( aAppendToMe )
397 {
398 wxCHECK_MSG( aSchematic->IsValid(), nullptr,
399 wxT( "Can't append to a schematic with no root!" ) );
400
401 m_rootSheet = &aSchematic->Root();
402
403 // We really should be passing the SCH_SHEET_PATH object to the aAppendToMe attribute
404 // instead of the SCH_SHEET. The full path is needed to properly generate instance
405 // data.
406 SCH_SHEET_LIST hierarchy( m_rootSheet );
407
408 for( const SCH_SHEET_PATH& sheetPath : hierarchy )
409 {
410 if( sheetPath.Last() == aAppendToMe )
411 {
412 m_sheetPath = sheetPath;
413 break;
414 }
415 }
416 }
417 else
418 {
419 // Create a temporary local VR used only to anchor m_sheetPath during loading.
420 // loadSchematic() will call SetTopLevelSheets() with the real Eagle pages, which
421 // creates the actual schematic VR and re-parents the pages to it.
422 tempVROwner = std::make_unique<SCH_SHEET>( aSchematic );
423 m_rootSheet = tempVROwner.get();
424 const_cast<KIID&>( m_rootSheet->m_Uuid ) = niluuid;
425 }
426
427 if( !m_rootSheet->GetScreen() )
428 {
429 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
430 screen->SetFileName( newFilename.GetFullPath() );
431 m_rootSheet->SetScreen( screen );
432
433 // Virtual root sheet UUID must be nil since all Eagle pages are loaded as subsheets.
434 const_cast<KIID&>( m_rootSheet->m_Uuid ) = niluuid;
435
436 // There is always at least a root sheet.
437 m_sheetPath.push_back( m_rootSheet );
438 }
439
441 LIBRARY_TABLE* table = adapter->ProjectTable().value_or( nullptr );
442 wxCHECK_MSG( table, nullptr, "Could not load symbol lib table." );
443
444 m_pi.reset( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
445
448 if( !table->HasRow( getLibName() ) )
449 {
450 // Create a new empty symbol library.
451 m_pi->CreateLibrary( getLibFileName().GetFullPath() );
452 wxString libTableUri = wxT( "${KIPRJMOD}/" ) + getLibFileName().GetFullName();
453
454 // Add the new library to the project symbol library table.
455 LIBRARY_TABLE_ROW& row = table->InsertRow();
456 row.SetNickname( getLibName() );
457 row.SetURI( libTableUri );
458 row.SetType( "KiCad" );
459
460 table->Save();
461
462 adapter->LoadOne( getLibName() );
463 }
464
465 try
466 {
467 m_eagleDoc = std::make_unique<EAGLE_DOC>( currentNode, this );
468 }
469 catch( const XML_PARSER_ERROR& exc )
470 {
471 THROW_IO_ERROR( exc.what() );
472 }
473
474 // If the attribute is found, store the Eagle version;
475 // otherwise, store the dummy "0.0" version.
476 m_version = ( m_eagleDoc->version.IsEmpty() ) ? wxString( wxS( "0.0" ) ) : m_eagleDoc->version;
477
478 // Load drawing
479 loadDrawing( m_eagleDoc->drawing );
480
481 if( !aAppendToMe )
482 m_rootSheet = &aSchematic->Root();
483
484 m_pi->SaveLibrary( getLibFileName().GetFullPath() );
485
486 // The project library was created empty and then cached by the adapter (LoadOne above)
487 // before any symbols were written to it. Reload it from disk now that SaveLibrary has
488 // populated the file, otherwise UpdateSymbolLinks resolves against the stale empty cache
489 // and every imported symbol is reported as missing.
491
492 SCH_SCREENS allSheets( m_rootSheet );
493 allSheets.UpdateSymbolLinks( &LOAD_INFO_REPORTER::GetInstance() ); // Update all symbol library links for all sheets.
494
495 return m_rootSheet;
496}
497
498
499void SCH_IO_EAGLE::EnumerateSymbolLib( wxArrayString& aSymbolNameList,
500 const wxString& aLibraryPath,
501 const std::map<std::string, UTF8>* aProperties )
502{
503 m_filename = aLibraryPath;
504 m_libName = m_filename.GetName();
505
506 ensureLoadedLibrary( aLibraryPath );
507
508 auto it = m_eagleLibs.find( m_libName );
509
510 if( it != m_eagleLibs.end() )
511 {
512 for( const auto& [symName, libSymbol] : it->second.KiCadSymbols )
513 aSymbolNameList.push_back( symName );
514 }
515}
516
517
518void SCH_IO_EAGLE::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
519 const wxString& aLibraryPath,
520 const std::map<std::string, UTF8>* aProperties )
521{
522 m_filename = aLibraryPath;
523 m_libName = m_filename.GetName();
524
525 ensureLoadedLibrary( aLibraryPath );
526
527 auto it = m_eagleLibs.find( m_libName );
528
529 if( it != m_eagleLibs.end() )
530 {
531 for( const auto& [symName, libSymbol] : it->second.KiCadSymbols )
532 aSymbolList.push_back( libSymbol.get() );
533 }
534}
535
536
537LIB_SYMBOL* SCH_IO_EAGLE::LoadSymbol( const wxString& aLibraryPath, const wxString& aAliasName,
538 const std::map<std::string, UTF8>* aProperties )
539{
540 m_filename = aLibraryPath;
541 m_libName = m_filename.GetName();
542
543 ensureLoadedLibrary( aLibraryPath );
544
545 auto it = m_eagleLibs.find( m_libName );
546
547 if( it != m_eagleLibs.end() )
548 {
549 auto it2 = it->second.KiCadSymbols.find( aAliasName );
550
551 if( it2 != it->second.KiCadSymbols.end() )
552 return it2->second.get();
553 }
554
555 return nullptr;
556}
557
558
559long long SCH_IO_EAGLE::getLibraryTimestamp( const wxString& aLibraryPath ) const
560{
561 wxFileName fn( aLibraryPath );
562
563 if( fn.IsFileReadable() && fn.GetModificationTime().IsValid() )
564 return fn.GetModificationTime().GetValue().GetValue();
565 else
566 return 0;
567}
568
569
570void SCH_IO_EAGLE::ensureLoadedLibrary( const wxString& aLibraryPath )
571{
572 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
573 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
574
575 if( m_eagleLibs.find( m_libName ) != m_eagleLibs.end() )
576 {
577 wxCHECK( m_timestamps.count( m_libName ), /*void*/ );
578
579 if( m_timestamps.at( m_libName ) == getLibraryTimestamp( aLibraryPath ) )
580 return;
581 }
582
584 {
585 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aLibraryPath ) );
586
587 if( !m_progressReporter->KeepRefreshing() )
589 }
590
591 // Load the document
592 wxXmlDocument xmlDocument = loadXmlDocument( m_filename.GetFullPath() );
593
594 // Retrieve the root as current node
595 std::unique_ptr<EAGLE_DOC> doc = std::make_unique<EAGLE_DOC>( xmlDocument.GetRoot(), this );
596
597 // If the attribute is found, store the Eagle version;
598 // otherwise, store the dummy "0.0" version.
599 m_version = ( doc->version.IsEmpty() ) ? wxString( wxS( "0.0" ) ) : doc->version;
600
601 // Load drawing
602 loadDrawing( doc->drawing );
603
604 // Remember timestamp
605 m_timestamps[m_libName] = getLibraryTimestamp( aLibraryPath );
606}
607
608
609wxXmlDocument SCH_IO_EAGLE::loadXmlDocument( const wxString& aFileName )
610{
611 wxXmlDocument xmlDocument;
612 wxFFileInputStream stream( m_filename.GetFullPath() );
613
614 if( !stream.IsOk() )
615 THROW_IO_ERRORF( _( "Unable to read file '%s'." ), m_filename.GetFullPath() );
616
617 // Pre-v6 schematics are a binary stream identified by a two-byte magic. Decode
618 // them into an XML-compatible DOM and adopt that tree, mirroring PCB_IO_EAGLE.
619 bool isBinary = EAGLE_BIN_PARSER::IsBinaryEagle( stream );
620
621 if( isBinary )
622 {
623 std::vector<uint8_t> bytes;
624 bytes.resize( static_cast<size_t>( stream.GetLength() ) );
625 stream.Read( bytes.data(), bytes.size() );
626
627 if( stream.LastRead() != bytes.size() )
628 THROW_IO_ERRORF( _( "Unable to read file '%s'." ), m_filename.GetFullPath() );
629
630 EAGLE_BIN_PARSER binParser;
631 std::unique_ptr<wxXmlDocument> binDocument = binParser.Parse( bytes );
632
633 xmlDocument.SetRoot( binDocument->DetachRoot() );
634 return xmlDocument;
635 }
636
637 // read first line to check for Eagle XML format file
638 wxTextInputStream text( stream );
639 wxString line = text.ReadLine();
640
641 if( !line.StartsWith( wxT( "<?xml" ) ) && !line.StartsWith( wxT( "<!--" ) )
642 && !line.StartsWith( wxT( "<eagle " ) ) )
643 {
644 THROW_IO_ERRORF( _( "'%s' is an Eagle binary-format file; only Eagle XML-format files can be imported." ),
645 m_filename.GetFullPath() );
646 }
647
648#if wxCHECK_VERSION( 3, 3, 0 )
649 wxXmlParseError err;
650
651 if( !xmlDocument.Load( stream, wxXMLDOC_NONE, &err ) )
652 {
653 if( err.message == wxS( "no element found" ) )
654 {
655 // Some files don't have the correct header, throwing off the xml parser
656 // So prepend the correct header
657 wxMemoryOutputStream memOutput;
658
659 wxString header;
660 header << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
661 header << "<!DOCTYPE eagle SYSTEM \"eagle.dtd\">\n";
662
663 wxScopedCharBuffer headerBuf = header.utf8_str();
664 memOutput.Write( headerBuf.data(), headerBuf.length() );
665
666 wxFFileInputStream stream2( m_filename.GetFullPath() );
667 memOutput.Write( stream2 );
668
669 wxMemoryInputStream memInput( memOutput );
670
671 if( !xmlDocument.Load( memInput, wxXMLDOC_NONE, &err ) )
672 {
673 THROW_IO_ERRORF( _( "Unable to read file '%s'." ), m_filename.GetFullPath() );
674 }
675 }
676 else
677 {
678 THROW_IO_ERRORF( _( "Unable to read file '%s'.\n'%s' at line %d, column %d, offset %d" ),
679 m_filename.GetFullPath(), err.message, err.line, err.column, err.offset );
680 }
681 }
682#else
683 if( !xmlDocument.Load( stream ) )
684 {
685 // Some files don't have the correct header, throwing off the xml parser
686 // So prepend the correct header
687 wxMemoryOutputStream memOutput;
688
689 wxString header;
690 header << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
691 header << "<!DOCTYPE eagle SYSTEM \"eagle.dtd\">\n";
692
693 wxScopedCharBuffer headerBuf = header.utf8_str();
694 memOutput.Write( headerBuf.data(), headerBuf.length() );
695
696 wxFFileInputStream stream2( m_filename.GetFullPath() );
697 memOutput.Write( stream2 );
698
699 wxMemoryInputStream memInput( memOutput );
700
701 if( !xmlDocument.Load( memInput ) )
702 THROW_IO_ERRORF( _( "Unable to read file '%s'." ), m_filename.GetFullPath() );
703 }
704#endif
705
706 return xmlDocument;
707}
708
709
710void SCH_IO_EAGLE::loadDrawing( const std::unique_ptr<EDRAWING>& aDrawing )
711{
712 wxCHECK( aDrawing, /* void */ );
713
714 loadLayerDefs( aDrawing->layers );
715
716 if( aDrawing->library )
717 {
719 elib.name = m_libName;
720
721 loadLibrary( &aDrawing->library.value(), &elib );
722 }
723
724 if( aDrawing->schematic )
725 loadSchematic( *aDrawing->schematic );
726}
727
728
729void SCH_IO_EAGLE::countNets( const ESCHEMATIC& aSchematic )
730{
731 for( const std::unique_ptr<ESHEET>& esheet : aSchematic.sheets )
732 {
733 for( const std::unique_ptr<ENET>& enet : esheet->nets )
734 {
735 wxString netName = enet->netname;
736
737 if( m_netCounts.count( netName ) )
738 m_netCounts[netName] = m_netCounts[netName] + 1;
739 else
740 m_netCounts[netName] = 1;
741 }
742 }
743
744 for( const auto& [modname, emodule] : aSchematic.modules )
745 {
746 for( const std::unique_ptr<ESHEET>& esheet : emodule->sheets )
747 {
748 for( const std::unique_ptr<ENET>& enet : esheet->nets )
749 {
750 wxString netName = enet->netname;
751
752 if( m_netCounts.count( netName ) )
753 m_netCounts[netName] = m_netCounts[netName] + 1;
754 else
755 m_netCounts[netName] = 1;
756 }
757 }
758 }
759}
760
761
763{
764 // Map all children into a readable dictionary
765 if( aSchematic.sheets.empty() )
766 return;
767
768 for( const auto& [name, variantDef] : aSchematic.variantdefs )
769 {
770 m_schematic->AddVariant( name );
771
772 if( variantDef->current.value_or( false ) )
773 m_schematic->SetCurrentVariant( name );
774 }
775
776 // N.B. Eagle parts are case-insensitive in matching but we keep the display case
777 for( const auto& [name, epart] : aSchematic.parts )
778 m_partlist[name.Upper()] = epart.get();
779
780 for( const auto& [modName, emodule] : aSchematic.modules )
781 {
782 for( const auto& [partName, epart] : emodule->parts )
783 m_partlist[partName.Upper()] = epart.get();
784 }
785
786 if( !aSchematic.libraries.empty() )
787 {
788 for( const auto& [libName, elibrary] : aSchematic.libraries )
789 {
790 EAGLE_LIBRARY* elib = &m_eagleLibs[elibrary->GetName()];
791 elib->name = elibrary->GetName();
792
793 loadLibrary( elibrary.get(), &m_eagleLibs[elibrary->GetName()] );
794 }
795
796 m_pi->SaveLibrary( getLibFileName().GetFullPath() );
797 }
798
799 // Count how many sheets each named net appears on. Used by the fallback-label path
800 // in loadSegments to decide whether to add an extra label on otherwise-unlabelled
801 // segments of nets that span multiple sheets.
802 countNets( aSchematic );
803
804 // Create all Eagle pages as top-level sheets (direct children of the virtual root).
805 // Collect them first so we can atomically replace any spurious default sheet created
806 // during schematic construction with exactly the set of real Eagle pages.
807 std::vector<SCH_SHEET*> eaglePages;
808 eaglePages.reserve( aSchematic.sheets.size() );
809
810 for( const std::unique_ptr<ESHEET>& esheet : aSchematic.sheets )
811 {
812 // Eagle schematics are never more than one sheet deep so the parent sheet is
813 // always the root sheet.
814 std::unique_ptr<SCH_SHEET> sheet = std::make_unique<SCH_SHEET>( m_rootSheet );
815 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
816 sheet->SetScreen( screen );
817
818 wxCHECK2( sheet && screen, continue );
819
820 wxString pageNo = wxString::Format( wxT( "%d" ), m_sheetIndex );
821
822 m_sheetPath.push_back( sheet.get() );
823 loadSheet( esheet );
824
825 m_sheetPath.SetPageNumber( pageNo );
826 m_sheetPath.pop_back();
827
828 eaglePages.push_back( sheet.release() );
829
830 m_sheetIndex++;
831 }
832
833 if( !eaglePages.empty() )
834 {
835 // In the append path m_rootSheet is already the schematic's VR. Use
836 // AddTopLevelSheet to avoid discarding sheets already in the target.
837 // In the fresh-import path m_rootSheet is a temporary local VR, so we use
838 // SetTopLevelSheets to atomically replace any spurious default sheet with
839 // exactly the Eagle pages.
840 if( m_rootSheet == &m_schematic->Root() )
841 {
842 for( SCH_SHEET* page : eaglePages )
843 m_schematic->AddTopLevelSheet( page );
844 }
845 else
846 {
847 m_schematic->SetTopLevelSheets( eaglePages );
848 }
849 }
850
851 // Handle the missing symbol units that need to be instantiated
852 // to create the missing implicit connections
853
854 // Calculate the already placed items bounding box and the page size to determine
855 // placement for the new symbols
856 SCH_SHEET* schematicRoot = &m_schematic->Root();
857
858 struct MISSING_UNIT_PLACEMENT
859 {
860 VECTOR2I pageSizeIU;
861 BOX2I sheetBbox;
862 VECTOR2I newCmpPosition;
863 int maxY;
864 SCH_SHEET_PATH sheetpath;
865 SCH_SCREEN* screen;
866 };
867
868 std::map<SCH_SCREEN*, MISSING_UNIT_PLACEMENT> placements;
869
870 for( auto& cmp : m_missingCmps )
871 {
872 const SCH_SYMBOL* origSymbol = cmp.second.cmp;
873
874 for( auto& unitEntry : cmp.second.units )
875 {
876 if( unitEntry.second == false )
877 continue; // unit has been already processed
878
879 // Instantiate the missing symbol unit
880 int unit = unitEntry.first;
881 const wxString reference = origSymbol->GetField( FIELD_T::REFERENCE )->GetText();
882 std::unique_ptr<SCH_SYMBOL> symbol( (SCH_SYMBOL*) origSymbol->Duplicate( IGNORE_PARENT_GROUP ) );
883
884 SCH_SCREEN* targetScreen = cmp.second.screen;
885
886 if( !targetScreen )
887 {
888 SCH_SHEET* fallbackSheet = m_schematic->GetTopLevelSheet( 0 );
889
890 if( fallbackSheet )
891 targetScreen = fallbackSheet->GetScreen();
892 else
893 targetScreen = schematicRoot->GetScreen();
894 }
895
896 auto placementIt = placements.find( targetScreen );
897
898 if( placementIt == placements.end() )
899 {
900 MISSING_UNIT_PLACEMENT placement;
901 placement.screen = targetScreen;
902 placement.pageSizeIU = targetScreen->GetPageSettings().GetSizeIU( schIUScale.IU_PER_MILS );
903 schematicRoot->LocatePathOfScreen( targetScreen, &placement.sheetpath );
904
905 SCH_SHEET* targetSheet = placement.sheetpath.Last();
906
907 if( targetSheet )
908 placement.sheetBbox = getSheetBbox( targetSheet );
909
910 placement.newCmpPosition = VECTOR2I( placement.sheetBbox.GetLeft(),
911 placement.sheetBbox.GetBottom() );
912 placement.maxY = placement.sheetBbox.GetY();
913 placementIt = placements.emplace( targetScreen, placement ).first;
914 }
915
916 MISSING_UNIT_PLACEMENT& placement = placementIt->second;
917
918 symbol->SetUnitSelection( &placement.sheetpath, unit );
919 symbol->SetUnit( unit );
920 symbol->SetOrientation( 0 );
921 symbol->AddHierarchicalReference( placement.sheetpath.Path(), reference, unit );
922
923 // Calculate the placement position
924 BOX2I cmpBbox = symbol->GetBoundingBox();
925 int posY = placement.newCmpPosition.y + cmpBbox.GetHeight();
926 symbol->SetPosition( VECTOR2I( placement.newCmpPosition.x, posY ) );
927 placement.newCmpPosition.x += cmpBbox.GetWidth();
928 placement.maxY = std::max( placement.maxY, posY );
929
930 if( placement.newCmpPosition.x >= placement.pageSizeIU.x ) // reached the page boundary?
931 placement.newCmpPosition = VECTOR2I( placement.sheetBbox.GetLeft(),
932 placement.maxY ); // then start a new row
933
934 // Add the global net labels to recreate the implicit connections
935 addImplicitConnections( symbol.get(), placement.screen, false );
936 placement.screen->Append( symbol.release() );
937 }
938 }
939
940 m_missingCmps.clear();
941}
942
943
944void SCH_IO_EAGLE::loadSheet( const std::unique_ptr<ESHEET>& aSheet )
945{
946 SCH_SHEET* sheet = getCurrentSheet();
947 SCH_SCREEN* screen = getCurrentScreen();
948
949 wxCHECK( sheet && screen, /* void */ );
950
951 if( m_modules.empty() )
952 {
953 std::string filename;
954
955 filename = wxString::Format( wxT( "%s_%d" ), m_filename.GetName(), m_sheetIndex );
956
957 if( aSheet->description )
958 sheet->SetName( aSheet->description.value().text );
959 else
960 sheet->SetName( filename );
961
962 ReplaceIllegalFileNameChars( filename );
963 replace( filename.begin(), filename.end(), ' ', '_' );
964
965 // Use the project directory so saved pages land alongside the project file,
966 // not in the Eagle source directory.
967 wxFileName fn;
968 fn.SetPath( m_schematic->Project().GetProjectPath() );
969 fn.SetName( filename );
971
972 sheet->SetFileName( fn.GetFullName() );
973 screen->SetFileName( fn.GetFullPath() );
974 }
975
976 for( const auto& [name, moduleinst] : aSheet->moduleinsts )
977 loadModuleInstance( moduleinst );
978
979 sheet->AutoplaceFields( screen, AUTOPLACE_AUTO );
980
981 if( aSheet->plain )
982 {
983 for( const std::unique_ptr<EPOLYGON>& epoly : aSheet->plain->polygons )
984 {
985 if( SCH_SHAPE* shape = loadPolyLine( epoly ) )
986 screen->Append( shape );
987 }
988
989 for( const std::unique_ptr<EWIRE>& ewire : aSheet->plain->wires )
990 {
991 SEG endpoints;
992 screen->Append( loadWire( ewire, endpoints ) );
993 }
994
995 for( const std::unique_ptr<ETEXT>& etext : aSheet->plain->texts )
996 screen->Append( loadPlainText( etext ) );
997
998 for( const std::unique_ptr<ECIRCLE>& ecircle : aSheet->plain->circles )
999 screen->Append( loadCircle( ecircle ) );
1000
1001 for( const std::unique_ptr<ERECT>& erectangle : aSheet->plain->rectangles )
1002 screen->Append( loadRectangle( erectangle ) );
1003
1004 for( const std::unique_ptr<EFRAME>& eframe : aSheet->plain->frames )
1005 {
1006 std::vector<SCH_ITEM*> frameItems;
1007
1008 loadFrame( eframe, frameItems );
1009
1010 for( SCH_ITEM* item : frameItems )
1011 screen->Append( item );
1012 }
1013
1014 // Holes and splines currently not handled. Not sure hole has any meaning in scheamtics.
1015 }
1016
1017 for( const std::unique_ptr<EINSTANCE>& einstance : aSheet->instances )
1018 {
1019 loadInstance( einstance, ( m_modules.size() ) ? m_modules.back()->parts
1020 : m_eagleDoc->drawing->schematic->parts );
1021 }
1022
1023 SHEET_WIRING wiring = collectSheetWiring( aSheet, screen );
1024
1025 // Loop through all buses
1026 // From the DTD: "Buses receive names which determine which signals they include.
1027 // A bus is a drawing object. It does not create any electrical connections.
1028 // These are always created by means of the nets and their names."
1029 for( const std::unique_ptr<EBUS>& ebus : aSheet->busses )
1030 {
1031 // Get the bus name
1032 wxString busName = translateEagleBusName( ebus->name );
1033
1034 // Load segments of this bus
1035 loadSegments( ebus->segments, busName, wxString(), wiring, /* aIsBus */ true );
1036 }
1037
1038 for( const std::unique_ptr<ENET>& enet : aSheet->nets )
1039 {
1040 // Get the net name and class
1041 wxString netName = enet->netname;
1042 wxString netClass = wxString::Format( wxS( "%i" ), enet->netcode );
1043
1044 // Load segments of this net
1045 loadSegments( enet->segments, netName, netClass, wiring );
1046 }
1047
1048 adjustNetLabels(); // needs to be called before addBusEntries()
1049 addBusEntries();
1050
1051 // Calculate the new sheet size.
1052 BOX2I sheetBoundingBox = getSheetBbox( sheet );
1053 VECTOR2I targetSheetSize = sheetBoundingBox.GetSize();
1054 targetSheetSize += VECTOR2I( schIUScale.MilsToIU( 1500 ), schIUScale.MilsToIU( 1500 ) );
1055
1056 // Get current Eeschema sheet size.
1057 VECTOR2I pageSizeIU = screen->GetPageSettings().GetSizeIU( schIUScale.IU_PER_MILS );
1058 PAGE_INFO pageInfo = screen->GetPageSettings();
1059
1060 // Increase if necessary
1061 if( pageSizeIU.x < targetSheetSize.x )
1062 pageInfo.SetWidthMils( schIUScale.IUToMils( targetSheetSize.x ) );
1063
1064 if( pageSizeIU.y < targetSheetSize.y )
1065 pageInfo.SetHeightMils( schIUScale.IUToMils( targetSheetSize.y ) );
1066
1067 // Set the new sheet size.
1068 screen->SetPageSettings( pageInfo );
1069
1070 pageSizeIU = screen->GetPageSettings().GetSizeIU( schIUScale.IU_PER_MILS );
1071 VECTOR2I sheetcentre( pageSizeIU.x / 2, pageSizeIU.y / 2 );
1072 VECTOR2I itemsCentre = sheetBoundingBox.Centre();
1073
1074 // round the translation to nearest 100mil to place it on the grid.
1075 VECTOR2I translation = sheetcentre - itemsCentre;
1076 translation.x = translation.x - translation.x % schIUScale.MilsToIU( 100 );
1077 translation.y = translation.y - translation.y % schIUScale.MilsToIU( 100 );
1078
1079 // Add global net labels for the named power input pins in this sheet
1080 for( SCH_ITEM* item : screen->Items().OfType( SCH_SYMBOL_T ) )
1081 {
1082 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
1083 addImplicitConnections( symbol, screen, true );
1084 }
1085
1086 m_connPoints.clear();
1087
1088 // Translate the items.
1089 std::vector<SCH_ITEM*> allItems;
1090
1091 std::copy( screen->Items().begin(), screen->Items().end(), std::back_inserter( allItems ) );
1092
1093 for( SCH_ITEM* item : allItems )
1094 {
1095 item->SetPosition( item->GetPosition() + translation );
1096
1097 // We don't read positions of Eagle label fields (primarily intersheet refs), so we
1098 // need to autoplace them after applying the translation.
1099 if( SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( item ) )
1100 label->AutoplaceFields( screen, AUTOPLACE_AUTO );
1101
1102 item->ClearFlags();
1103 screen->Update( item );
1104 }
1105}
1106
1107
1108void SCH_IO_EAGLE::loadModuleInstance( const std::unique_ptr<EMODULEINST>& aModuleInstance )
1109{
1110 SCH_SHEET* currentSheet = getCurrentSheet();
1111 SCH_SCREEN* currentScreen = getCurrentScreen();
1112
1113 wxCHECK( currentSheet &&currentScreen, /* void */ );
1114
1115 m_sheetIndex++;
1116
1117 // Eagle document has already be checked for drawing and schematic nodes so this
1118 // should not segfault.
1119 auto it = m_eagleDoc->drawing->schematic->modules.find( aModuleInstance->moduleinst );
1120
1121 // Find the module referenced by the module instance.
1122 if( it == m_eagleDoc->drawing->schematic->modules.end() )
1123 {
1124 THROW_IO_ERRORF( _( "No module instance '%s' found in schematic file:\n%s" ),
1125 aModuleInstance->name, m_filename.GetFullPath() );
1126 }
1127
1128 wxFileName fn = m_filename;
1129 fn.SetName( aModuleInstance->moduleinst );
1131
1132 VECTOR2I portExtWireEndpoint;
1133 VECTOR2I size( it->second->dx.ToSchUnits(), it->second->dy.ToSchUnits() );
1134
1135 int halfX = KiROUND( size.x / 2.0 );
1136 int halfY = KiROUND( size.y / 2.0 );
1137 int portExtWireLength = schIUScale.mmToIU( 5.08 );
1138 VECTOR2I pos( aModuleInstance->x.ToSchUnits() - halfX,
1139 -aModuleInstance->y.ToSchUnits() - halfY );
1140
1141 std::unique_ptr<SCH_SHEET> newSheet = std::make_unique<SCH_SHEET>( currentSheet, pos, size );
1142
1143 // The Eagle module for this instance (SCH_SCREEN in KiCad) may have already been loaded.
1144 SCH_SCREEN* newScreen = nullptr;
1145 SCH_SCREENS schFiles( m_rootSheet );
1146
1147 for( SCH_SCREEN* schFile = schFiles.GetFirst(); schFile; schFile = schFiles.GetNext() )
1148 {
1149 if( schFile->GetFileName() == fn.GetFullPath() )
1150 {
1151 newScreen = schFile;
1152 break;
1153 }
1154 }
1155
1156 bool isNewSchFile = ( newScreen == nullptr );
1157
1158 if( !newScreen )
1159 {
1160 newScreen = new SCH_SCREEN( m_schematic );
1161 newScreen->SetFileName( fn.GetFullPath() );
1162 }
1163
1164 wxCHECK( newSheet && newScreen, /* void */ );
1165
1166 newSheet->SetScreen( newScreen );
1167 newSheet->SetFileName( fn.GetFullName() );
1168 newSheet->SetName( aModuleInstance->name );
1169
1170 for( const auto& [portName, port] : it->second->ports )
1171 {
1172 VECTOR2I pinPos( 0, 0 );
1173 int pinOffset = port->coord.ToSchUnits();
1175
1176 if( port->side == "left" )
1177 {
1178 side = SHEET_SIDE::LEFT;
1179 pinPos.x = pos.x;
1180 pinPos.y = pos.y + halfY - pinOffset;
1181 portExtWireEndpoint = pinPos;
1182 portExtWireEndpoint.x -= portExtWireLength;
1183 }
1184 else if( port->side == "right" )
1185 {
1186 side = SHEET_SIDE::RIGHT;
1187 pinPos.x = pos.x + size.x;
1188 pinPos.y = pos.y + halfY - pinOffset;
1189 portExtWireEndpoint = pinPos;
1190 portExtWireEndpoint.x += portExtWireLength;
1191 }
1192 else if( port->side == "top" )
1193 {
1194 side = SHEET_SIDE::TOP;
1195 pinPos.x = pos.x + halfX + pinOffset;
1196 pinPos.y = pos.y;
1197 portExtWireEndpoint = pinPos;
1198 portExtWireEndpoint.y -= portExtWireLength;
1199 }
1200 else if( port->side == "bottom" )
1201 {
1202 side = SHEET_SIDE::BOTTOM;
1203 pinPos.x = pos.x + halfX + pinOffset;
1204 pinPos.y = pos.y + size.y;
1205 portExtWireEndpoint = pinPos;
1206 portExtWireEndpoint.y += portExtWireLength;
1207 }
1208
1209 SCH_LINE* portExtWire = new SCH_LINE( pinPos, LAYER_WIRE );
1210 portExtWire->SetEndPoint( portExtWireEndpoint );
1211 currentScreen->Append( portExtWire );
1212
1214
1215 if( port->direction.has_value() )
1216 {
1217 if( port->direction.value() == "in" )
1218 pinType = LABEL_FLAG_SHAPE::L_INPUT;
1219 else if( port->direction.value() == "out" )
1221 else if( port->direction.value() == "io" )
1222 pinType = LABEL_FLAG_SHAPE::L_BIDI;
1223 else if( port->direction.value() == "hiz" )
1225
1226 // KiCad does not support passive, power, open collector, or no-connect sheet pins that
1227 // Eagle ports support. They are left set to L_UNSPECIFIED to minimize ERC issues.
1228 }
1229
1230 SCH_SHEET_PIN* sheetPin = new SCH_SHEET_PIN( newSheet.get(), VECTOR2I( 0, 0 ), portName );
1231
1232 sheetPin->SetShape( pinType );
1233 sheetPin->SetPosition( pinPos );
1234 sheetPin->SetSide( side );
1235 newSheet->AddPin( sheetPin );
1236 }
1237
1238 wxString pageNo = wxString::Format( wxT( "%d" ), m_sheetIndex );
1239
1240 newSheet->SetParent( currentSheet );
1241 m_sheetPath.push_back( newSheet.get() );
1242 m_sheetPath.SetPageNumber( pageNo );
1243 currentScreen->Append( newSheet.release() );
1244
1245 m_modules.push_back( it->second.get() );
1246 m_moduleInstances.push_back( aModuleInstance.get() );
1247
1248 // Do not reload shared modules that are already loaded.
1249 if( isNewSchFile )
1250 {
1251 for( const std::unique_ptr<ESHEET>& esheet : it->second->sheets )
1252 loadSheet( esheet );
1253 }
1254 else
1255 {
1256 // Add instances for shared schematics.
1257 wxString refPrefix;
1258
1259 for( const EMODULEINST* emoduleInst : m_moduleInstances )
1260 {
1261 wxCHECK2( emoduleInst, continue );
1262
1263 refPrefix += emoduleInst->name + wxS( ":" );
1264 }
1265
1266 SCH_SCREEN* sharedScreen = m_sheetPath.LastScreen();
1267
1268 if( sharedScreen )
1269 {
1270 for( SCH_ITEM* schItem : sharedScreen->Items().OfType( SCH_SYMBOL_T ) )
1271 {
1272 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( schItem );
1273
1274 wxCHECK2( symbol && !symbol->GetInstances().empty(), continue );
1275
1276 SCH_SYMBOL_INSTANCE inst = symbol->GetInstances().at( 0 );
1277 wxString newReference = refPrefix + inst.m_Reference.AfterLast( ':' );
1278
1279 symbol->AddHierarchicalReference( m_sheetPath.Path(), newReference, inst.m_Unit );
1280 }
1281 }
1282 }
1283
1284 m_moduleInstances.pop_back();
1285 m_modules.pop_back();
1286 m_sheetPath.pop_back();
1287}
1288
1289
1290void SCH_IO_EAGLE::loadFrame( const std::unique_ptr<EFRAME>& aFrame, std::vector<SCH_ITEM*>& aItems,
1291 SCH_LAYER_ID aLayer )
1292{
1293 int xMin = aFrame->x1.ToSchUnits();
1294 int xMax = aFrame->x2.ToSchUnits();
1295 int yMin = -aFrame->y1.ToSchUnits();
1296 int yMax = -aFrame->y2.ToSchUnits();
1297
1298 if( xMin > xMax )
1299 std::swap( xMin, xMax );
1300
1301 if( yMin > yMax )
1302 std::swap( yMin, yMax );
1303
1304 SCH_SHAPE* lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1305 lines->AddPoint( VECTOR2I( xMin, yMin ) );
1306 lines->AddPoint( VECTOR2I( xMax, yMin ) );
1307 lines->AddPoint( VECTOR2I( xMax, yMax ) );
1308 lines->AddPoint( VECTOR2I( xMin, yMax ) );
1309 lines->AddPoint( VECTOR2I( xMin, yMin ) );
1310 aItems.push_back( lines );
1311
1312 if( !( aFrame->border_left == false ) )
1313 {
1314 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1315 lines->AddPoint( VECTOR2I( xMin + schIUScale.MilsToIU( 150 ), yMin + schIUScale.MilsToIU( 150 ) ) );
1316 lines->AddPoint( VECTOR2I( xMin + schIUScale.MilsToIU( 150 ), yMax - schIUScale.MilsToIU( 150 ) ) );
1317 aItems.push_back( lines );
1318
1319 int i;
1320 int height = yMax - yMin;
1321 int x1 = xMin;
1322 int x2 = x1 + schIUScale.MilsToIU( 150 );
1323 int legendPosX = xMin + schIUScale.MilsToIU( 75 );
1324 double rowSpacing = height / double( aFrame->rows );
1325 double legendPosY = yMin + ( rowSpacing / 2 );
1326
1327 for( i = 1; i < aFrame->rows; i++ )
1328 {
1329 int newY = KiROUND( yMin + ( rowSpacing * (double) i ) );
1330 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1331 lines->AddPoint( VECTOR2I( x1, newY ) );
1332 lines->AddPoint( VECTOR2I( x2, newY ) );
1333 aItems.push_back( lines );
1334 }
1335
1336 char legendChar = 'A';
1337
1338 for( i = 0; i < aFrame->rows; i++ )
1339 {
1340 SCH_TEXT* legendText = new SCH_TEXT();
1341 legendText->SetLayer( aLayer );
1342 legendText->SetPosition( VECTOR2I( legendPosX, KiROUND( legendPosY ) ) );
1345 legendText->SetText( wxString( legendChar ) );
1346 legendText->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 90 ), schIUScale.MilsToIU( 100 ) ) );
1347 aItems.push_back( legendText );
1348 legendChar++;
1349 legendPosY += rowSpacing;
1350 }
1351 }
1352
1353 if( !( aFrame->border_right == false ) )
1354 {
1355 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1356 lines->AddPoint( VECTOR2I( xMax - schIUScale.MilsToIU( 150 ), yMin + schIUScale.MilsToIU( 150 ) ) );
1357 lines->AddPoint( VECTOR2I( xMax - schIUScale.MilsToIU( 150 ), yMax - schIUScale.MilsToIU( 150 ) ) );
1358 aItems.push_back( lines );
1359
1360 int i;
1361 int height = yMax - yMin;
1362 int x1 = xMax - schIUScale.MilsToIU( 150 );
1363 int x2 = xMax;
1364 int legendPosX = xMax - schIUScale.MilsToIU( 75 );
1365 double rowSpacing = height / double( aFrame->rows );
1366 double legendPosY = yMin + ( rowSpacing / 2 );
1367
1368 for( i = 1; i < aFrame->rows; i++ )
1369 {
1370 int newY = KiROUND( yMin + ( rowSpacing * (double) i ) );
1371 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1372 lines->AddPoint( VECTOR2I( x1, newY ) );
1373 lines->AddPoint( VECTOR2I( x2, newY ) );
1374 aItems.push_back( lines );
1375 }
1376
1377 char legendChar = 'A';
1378
1379 for( i = 0; i < aFrame->rows; i++ )
1380 {
1381 SCH_TEXT* legendText = new SCH_TEXT();
1382 legendText->SetLayer( aLayer );
1383 legendText->SetPosition( VECTOR2I( legendPosX, KiROUND( legendPosY ) ) );
1386 legendText->SetText( wxString( legendChar ) );
1387 legendText->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 90 ), schIUScale.MilsToIU( 100 ) ) );
1388 aItems.push_back( legendText );
1389 legendChar++;
1390 legendPosY += rowSpacing;
1391 }
1392 }
1393
1394 if( !( aFrame->border_top == false ) )
1395 {
1396 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1397 lines->AddPoint( VECTOR2I( xMax - schIUScale.MilsToIU( 150 ), yMin + schIUScale.MilsToIU( 150 ) ) );
1398 lines->AddPoint( VECTOR2I( xMin + schIUScale.MilsToIU( 150 ), yMin + schIUScale.MilsToIU( 150 ) ) );
1399 aItems.push_back( lines );
1400
1401 int i;
1402 int width = xMax - xMin;
1403 int y1 = yMin;
1404 int y2 = yMin + schIUScale.MilsToIU( 150 );
1405 int legendPosY = yMin + schIUScale.MilsToIU( 75 );
1406 double columnSpacing = width / double( aFrame->columns );
1407 double legendPosX = xMin + ( columnSpacing / 2 );
1408
1409 for( i = 1; i < aFrame->columns; i++ )
1410 {
1411 int newX = KiROUND( xMin + ( columnSpacing * (double) i ) );
1412 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1413 lines->AddPoint( VECTOR2I( newX, y1 ) );
1414 lines->AddPoint( VECTOR2I( newX, y2 ) );
1415 aItems.push_back( lines );
1416 }
1417
1418 int legendNo = 1;
1419
1420 for( i = 0; i < aFrame->columns; i++ )
1421 {
1422 SCH_TEXT* legendText = new SCH_TEXT();
1423 legendText->SetLayer( aLayer );
1424 legendText->SetPosition( VECTOR2I( KiROUND( legendPosX ), legendPosY ) );
1427 legendText->SetText( fmt::format( "{}", legendNo++ ) );
1428 legendText->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 90 ), schIUScale.MilsToIU( 100 ) ) );
1429 aItems.push_back( legendText );
1430 legendPosX += columnSpacing;
1431 }
1432 }
1433
1434 if( !( aFrame->border_bottom == false ) )
1435 {
1436 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1437 lines->AddPoint( VECTOR2I( xMax - schIUScale.MilsToIU( 150 ), yMax - schIUScale.MilsToIU( 150 ) ) );
1438 lines->AddPoint( VECTOR2I( xMin + schIUScale.MilsToIU( 150 ), yMax - schIUScale.MilsToIU( 150 ) ) );
1439 aItems.push_back( lines );
1440
1441 int i;
1442 int width = xMax - xMin;
1443 int y1 = yMax - schIUScale.MilsToIU( 150 );
1444 int y2 = yMax;
1445 int legendPosY = yMax - schIUScale.MilsToIU( 75 );
1446 double columnSpacing = width / double( aFrame->columns );
1447 double legendPosX = xMin + ( columnSpacing / 2 );
1448
1449 for( i = 1; i < aFrame->columns; i++ )
1450 {
1451 int newX = KiROUND( xMin + ( columnSpacing * (double) i ) );
1452 lines = new SCH_SHAPE( SHAPE_T::POLY, aLayer );
1453 lines->AddPoint( VECTOR2I( newX, y1 ) );
1454 lines->AddPoint( VECTOR2I( newX, y2 ) );
1455 aItems.push_back( lines );
1456 }
1457
1458 int legendNo = 1;
1459
1460 for( i = 0; i < aFrame->columns; i++ )
1461 {
1462 SCH_TEXT* legendText = new SCH_TEXT();
1463 legendText->SetLayer( aLayer );
1464 legendText->SetPosition( VECTOR2I( KiROUND( legendPosX ), legendPosY ) );
1467 legendText->SetText( fmt::format( "{}", legendNo++ ) );
1468 legendText->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 90 ), schIUScale.MilsToIU( 100 ) ) );
1469 aItems.push_back( legendText );
1470 legendPosX += columnSpacing;
1471 }
1472 }
1473}
1474
1475
1477 SCH_SCREEN* aScreen )
1478{
1479 SHEET_WIRING wiring;
1480 std::map<VECTOR2I, int> netAt;
1481
1482 for( const std::unique_ptr<ENET>& enet : aSheet->nets )
1483 {
1484 auto netId = wiring.NetIds.try_emplace( enet->netname, static_cast<int>( wiring.NetIds.size() ) + 1 ).first;
1485 const int net = netId->second;
1486
1487 for( const std::unique_ptr<ESEGMENT>& esegment : enet->segments )
1488 {
1489 std::vector<SEG> segmentWires;
1490
1491 for( const std::unique_ptr<EWIRE>& ewire : esegment->wires )
1492 {
1493 if( kiCadLayer( ewire->layer ) != LAYER_WIRE )
1494 continue;
1495
1496 SEG seg( VECTOR2I( ewire->x1.ToSchUnits(), -ewire->y1.ToSchUnits() ),
1497 VECTOR2I( ewire->x2.ToSchUnits(), -ewire->y2.ToSchUnits() ) );
1498
1499 wiring.Detour.AddWire( seg, net );
1500 segmentWires.push_back( seg );
1501 netAt.try_emplace( seg.A, net );
1502 netAt.try_emplace( seg.B, net );
1503 }
1504
1505 for( const std::unique_ptr<EJUNCTION>& ejunction : esegment->junctions )
1506 {
1507 VECTOR2I pos( ejunction->x.ToSchUnits(), -ejunction->y.ToSchUnits() );
1508
1509 wiring.Detour.AddContact( pos, net );
1510 netAt.try_emplace( pos, net );
1511 }
1512
1513 // A detached label is moved onto its wire later, so only labels already on a wire are obstacles
1514 for( const std::unique_ptr<ELABEL>& elabel : esegment->labels )
1515 {
1516 const VECTOR2I pos( elabel->x.ToSchUnits(), -elabel->y.ToSchUnits() );
1517
1518 if( std::any_of( segmentWires.begin(), segmentWires.end(),
1519 [&]( const SEG& aSeg )
1520 {
1521 return aSeg.Contains( pos );
1522 } ) )
1523 {
1524 wiring.Detour.AddContact( pos, net );
1525 }
1526 }
1527 }
1528 }
1529
1530 // Eagle joins a pin only where a wire of its net ends
1531 for( SCH_ITEM* item : aScreen->Items().OfType( SCH_SYMBOL_T ) )
1532 {
1533 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
1534 int unit = symbol->GetUnit();
1535
1536 for( const SCH_PIN* pin : symbol->GetLibPins() )
1537 {
1538 if( unit && pin->GetUnit() && pin->GetUnit() != unit )
1539 continue;
1540
1541 const VECTOR2I pos = symbol->GetPinPhysicalPosition( pin );
1542 auto it = netAt.find( pos );
1543
1544 wiring.Detour.AddContact( pos, it != netAt.end() ? it->second : wiring.Detour.AnonymousNet() );
1545 }
1546 }
1547
1548 return wiring;
1549}
1550
1551
1552void SCH_IO_EAGLE::loadSegments( const std::vector<std::unique_ptr<ESEGMENT>>& aSegments,
1553 const wxString& netName, const wxString& aNetClass,
1554 SHEET_WIRING& aWiring, bool aIsBus )
1555{
1556 // Loop through all segments
1557 SCH_SCREEN* screen = getCurrentScreen();
1558
1559 wxCHECK( screen, /* void */ );
1560
1561 size_t segmentCount = aSegments.size();
1562
1563 for( const std::unique_ptr<ESEGMENT>& esegment : aSegments )
1564 {
1565 bool labelled = false; // has a label been added to this continuously connected segment
1566 bool firstWireFound = false;
1567 SEG firstWire;
1568
1569 m_segments.emplace_back();
1570 SEG_DESC& segDesc = m_segments.back();
1571
1572 for( const std::unique_ptr<EWIRE>& ewire : esegment->wires )
1573 {
1574 SEG eagleWire;
1575 SCH_ITEM* wire = loadWire( ewire, eagleWire );
1576
1577 std::vector<SEG> pieces = { eagleWire };
1578 std::vector<SCH_ITEM*> items = { wire };
1579
1580 if( !aIsBus && wire->GetLayer() == LAYER_WIRE )
1581 {
1583 aWiring.Detour.Route( eagleWire, aWiring.NetIds[netName] );
1584
1585 pieces = detour.Pieces;
1586
1587 if( detour.Failed )
1588 {
1589 Report( wxString::Format( _( "A wire of net %s passes over a pin or wire of another net and could "
1590 "not be rerouted. The nets may be joined and require manual fixing." ),
1591 netName ),
1593 }
1594 }
1595
1596 for( size_t i = 1; i < pieces.size(); i++ )
1597 {
1598 SCH_LINE* piece = new SCH_LINE;
1599
1600 piece->SetLayer( LAYER_WIRE );
1601 piece->SetStroke( static_cast<SCH_LINE*>( wire )->GetStroke() );
1602 items.push_back( piece );
1603 }
1604
1605 for( size_t i = 0; i < pieces.size(); i++ )
1606 {
1607 if( pieces.size() > 1 )
1608 {
1609 SCH_LINE* line = static_cast<SCH_LINE*>( items[i] );
1610
1611 line->SetStartPoint( pieces[i].A );
1612 line->SetEndPoint( pieces[i].B );
1613 }
1614
1615 // TODO: Check how intersections used in adjustNetLabels should be
1616 // calculated - for now we pretend that all wires are line segments.
1617 const SEG& thisWire = pieces[i];
1618 m_connPoints[thisWire.A].emplace( items[i] );
1619 m_connPoints[thisWire.B].emplace( items[i] );
1620
1621 if( !firstWireFound )
1622 {
1623 firstWire = thisWire;
1624 firstWireFound = true;
1625 }
1626
1627 // Test for intersections with other wires
1628 for( SEG_DESC& desc : m_segments )
1629 {
1630 if( !desc.labels.empty() && desc.labels.front()->GetText() == netName )
1631 continue; // no point in saving intersections of the same net
1632
1633 for( const SEG& seg : desc.segs )
1634 {
1635 OPT_VECTOR2I intersection = thisWire.Intersect( seg, true );
1636
1637 if( intersection )
1638 m_wireIntersections.push_back( *intersection );
1639 }
1640 }
1641
1642 segDesc.segs.push_back( thisWire );
1643 screen->Append( items[i] );
1644 }
1645 }
1646
1647 for( const std::unique_ptr<EJUNCTION>& ejunction : esegment->junctions )
1648 screen->Append( loadJunction( ejunction ) );
1649
1650 for( const std::unique_ptr<ELABEL>& elabel : esegment->labels )
1651 {
1652 SCH_LABEL_BASE* label = loadLabel( elabel, netName, aIsBus );
1653 screen->Append( label );
1654
1655 wxASSERT( segDesc.labels.empty() || segDesc.labels.front()->GetText() == label->GetText() );
1656
1657 segDesc.labels.push_back( label );
1658 labelled = true;
1659 }
1660
1661 for( const std::unique_ptr<EPINREF>& epinref : esegment->pinRefs )
1662 {
1663 wxString part = epinref->part;
1664 wxString pin = epinref->pin;
1665
1666 auto powerPort = m_powerPorts.find( wxT( "#" ) + part );
1667
1668 if( powerPort != m_powerPorts.end() && powerPort->second == EscapeString( pin, CTX_NETNAME ) )
1669 labelled = true;
1670 }
1671
1672 // Add a small label to the net segment if it hasn't been labeled already or is not
1673 // connect to a power symbol with a pin on the same net. This preserves the named net
1674 // feature of Eagle schematics.
1675 if( !labelled && firstWireFound )
1676 {
1677 std::unique_ptr<SCH_LABEL_BASE> label;
1678
1679 // Eagle uses a flat net namespace, so a named net should retain its name across
1680 // every segment and every sheet. The PCB importer carries Eagle signal names
1681 // through verbatim, so we must use a global label here too: a local SCH_LABEL
1682 // would prepend the sheet path (e.g. "/+24V_SWD") and split the net from the
1683 // matching PCB signal on net update.
1684 //
1685 // Two exceptions: (1) buses are conceptual groupings in Eagle, not electrical
1686 // signals, so a global bus label would join same-named buses project-wide where
1687 // Eagle only had visual grouping; (2) nets inside module instances are scoped
1688 // by the module's ports, so a global label would punch through the hierarchy.
1689 bool joinedByName = segmentCount > 1 || m_netCounts[netName] > 1;
1690
1691 if( aIsBus || !m_modules.empty() )
1692 {
1693 if( joinedByName )
1694 label.reset( new SCH_LABEL );
1695 }
1696 else if( joinedByName || !isEagleAutoNetName( netName ) )
1697 {
1698 // A lone segment is already wired, so only a user-chosen name is worth a label
1699 label.reset( new SCH_GLOBALLABEL );
1700 }
1701
1702 if( label )
1703 {
1704 label->SetPosition( firstWire.A );
1705 label->SetText( escapeName( netName ) );
1706 label->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 40 ), schIUScale.MilsToIU( 40 ) ) );
1707
1708 if( firstWire.A.y == firstWire.B.y ) // Horizontal wire.
1709 {
1710 if( firstWire.B.x > firstWire.A.x )
1711 label->SetSpinStyle( SPIN_STYLE::LEFT );
1712 else
1713 label->SetSpinStyle( SPIN_STYLE::RIGHT );
1714 }
1715 else if( firstWire.A.x == firstWire.B.x ) // Vertical wire.
1716 {
1717 if( firstWire.B.y > firstWire.A.y )
1718 label->SetSpinStyle( SPIN_STYLE::BOTTOM );
1719 else
1720 label->SetSpinStyle( SPIN_STYLE::UP );
1721 }
1722
1723 // adjustNetLabels() moves the label off a crossing wire so it does not join another net
1724 segDesc.labels.push_back( label.get() );
1725 screen->Append( label.release() );
1726 }
1727 }
1728 }
1729}
1730
1731
1732SCH_SHAPE* SCH_IO_EAGLE::loadPolyLine( const std::unique_ptr<EPOLYGON>& aPolygon )
1733{
1734 if( !aPolygon->IsValidOutline() )
1735 return nullptr;
1736
1737 std::unique_ptr<SCH_SHAPE> poly = std::make_unique<SCH_SHAPE>( SHAPE_T::POLY );
1738 VECTOR2I pt, prev_pt;
1739 std::optional<double> prev_curve;
1740
1741 for( const std::unique_ptr<EVERTEX>& evertex : aPolygon->vertices )
1742 {
1743 pt = VECTOR2I( evertex->x.ToSchUnits(), -evertex->y.ToSchUnits() );
1744
1745 if( prev_curve.has_value() )
1746 {
1747 SHAPE_ARC arc;
1748 arc.ConstructFromStartEndAngle( prev_pt, pt, -EDA_ANGLE( prev_curve.value(), DEGREES_T ) );
1749 poly->GetPolyShape().Append( arc, -1, -1, ARC_ACCURACY );
1750 }
1751 else
1752 {
1753 poly->AddPoint( pt );
1754 }
1755
1756 prev_pt = pt;
1757 prev_curve = evertex->curve;
1758 }
1759
1760 poly->SetLayer( kiCadLayer( aPolygon->layer ) );
1761 poly->SetStroke( STROKE_PARAMS( aPolygon->width.ToSchUnits(), LINE_STYLE::SOLID ) );
1762 poly->SetFillMode( FILL_T::FILLED_SHAPE );
1763
1764 return poly.release();
1765}
1766
1767
1768SCH_ITEM* SCH_IO_EAGLE::loadWire( const std::unique_ptr<EWIRE>& aWire, SEG& endpoints )
1769{
1770 VECTOR2I start, end;
1771
1772 start.x = aWire->x1.ToSchUnits();
1773 start.y = -aWire->y1.ToSchUnits();
1774 end.x = aWire->x2.ToSchUnits();
1775 end.y = -aWire->y2.ToSchUnits();
1776
1777 // For segment wires.
1778 endpoints = SEG( start, end );
1779
1780 int kicadLayer = kiCadLayer( aWire->layer );
1781
1782 // Don't process curved wires on an electrical layer into arcs, they aren't supported
1783 // in the rest of the code
1784 // TODO: When curved wires/buses are added, remove this restriction
1785 if( (kicadLayer == LAYER_NOTES) && aWire->curve )
1786 {
1787 std::unique_ptr<SCH_SHAPE> arc = std::make_unique<SCH_SHAPE>( SHAPE_T::ARC );
1788
1789 VECTOR2I center = ConvertArcCenter( start, end, *aWire->curve );
1790 arc->SetCenter( center );
1791 arc->SetStart( start );
1792
1793 // KiCad rotates the other way.
1794 arc->SetArcAngleAndEnd( -EDA_ANGLE( *aWire->curve, DEGREES_T ), true );
1795 arc->SetLayer( kiCadLayer( aWire->layer ) );
1796 arc->SetStroke( STROKE_PARAMS( aWire->width.ToSchUnits(), LINE_STYLE::SOLID ) );
1797
1798 return arc.release();
1799 }
1800 else
1801 {
1802 std::unique_ptr<SCH_LINE> line = std::make_unique<SCH_LINE>();
1803
1804 line->SetStartPoint( start );
1805 line->SetEndPoint( end );
1806 line->SetLayer( kiCadLayer( aWire->layer ) );
1807 line->SetStroke( STROKE_PARAMS( aWire->width.ToSchUnits(), LINE_STYLE::SOLID ) );
1808
1809 return line.release();
1810 }
1811}
1812
1813
1814SCH_SHAPE* SCH_IO_EAGLE::loadCircle( const std::unique_ptr<ECIRCLE>& aCircle )
1815{
1816 std::unique_ptr<SCH_SHAPE> circle = std::make_unique<SCH_SHAPE>( SHAPE_T::CIRCLE );
1817 VECTOR2I center( aCircle->x.ToSchUnits(), -aCircle->y.ToSchUnits() );
1818
1819 circle->SetLayer( kiCadLayer( aCircle->layer ) );
1820 circle->SetPosition( center );
1821 circle->SetEnd( VECTOR2I( center.x + aCircle->radius.ToSchUnits(), center.y ) );
1822 circle->SetStroke( STROKE_PARAMS( aCircle->width.ToSchUnits(), LINE_STYLE::SOLID ) );
1823
1824 return circle.release();
1825}
1826
1827
1828SCH_SHAPE* SCH_IO_EAGLE::loadRectangle( const std::unique_ptr<ERECT>& aRectangle )
1829{
1830 std::unique_ptr<SCH_SHAPE> rectangle = std::make_unique<SCH_SHAPE>( SHAPE_T::RECTANGLE );
1831
1832 rectangle->SetLayer( kiCadLayer( aRectangle->layer ) );
1833 rectangle->SetPosition( VECTOR2I( aRectangle->x1.ToSchUnits(), -aRectangle->y1.ToSchUnits() ) );
1834 rectangle->SetEnd( VECTOR2I( aRectangle->x2.ToSchUnits(), -aRectangle->y2.ToSchUnits() ) );
1835
1836 if( aRectangle->rot.has_value() )
1837 {
1838 VECTOR2I pos( rectangle->GetPosition() );
1839 VECTOR2I end( rectangle->GetEnd() );
1840 VECTOR2I center( rectangle->GetCenter() );
1841
1842 RotatePoint( pos, center, EDA_ANGLE( aRectangle->rot.value().degrees, DEGREES_T ) );
1843 RotatePoint( end, center, EDA_ANGLE( aRectangle->rot.value().degrees, DEGREES_T ) );
1844
1845 rectangle->SetPosition( pos );
1846 rectangle->SetEnd( end );
1847 }
1848
1849 // Eagle rectangles are filled by definition.
1850 rectangle->SetFillMode( FILL_T::FILLED_SHAPE );
1851
1852 return rectangle.release();
1853}
1854
1855
1856SCH_JUNCTION* SCH_IO_EAGLE::loadJunction( const std::unique_ptr<EJUNCTION>& aJunction )
1857{
1858 std::unique_ptr<SCH_JUNCTION> junction = std::make_unique<SCH_JUNCTION>();
1859
1860 VECTOR2I pos( aJunction->x.ToSchUnits(), -aJunction->y.ToSchUnits() );
1861
1862 junction->SetPosition( pos );
1863
1864 return junction.release();
1865}
1866
1867
1868SCH_LABEL_BASE* SCH_IO_EAGLE::loadLabel( const std::unique_ptr<ELABEL>& aLabel,
1869 const wxString& aNetName, bool aIsBus )
1870{
1871 VECTOR2I elabelpos( aLabel->x.ToSchUnits(), -aLabel->y.ToSchUnits() );
1872
1873 // Label-kind decision mirrors loadSegments(): SCH_HIERLABEL for module ports,
1874 // SCH_LABEL for buses and module-internal nets, SCH_GLOBALLABEL otherwise so the
1875 // Eagle flat net namespace round-trips through the matching PCB signal name.
1876 std::unique_ptr<SCH_LABEL_BASE> label;
1877
1878 VECTOR2I textSize = KiROUND( aLabel->size.ToSchUnits() * 0.7, aLabel->size.ToSchUnits() * 0.7 );
1879
1880 auto findModulePort =
1881 [&]() -> const EPORT*
1882 {
1883 if( m_modules.empty() )
1884 return nullptr;
1885
1886 const auto& ports = m_modules.back()->ports;
1887 const auto it = ports.find( aNetName );
1888 return it == ports.end() ? nullptr : it->second.get();
1889 };
1890
1891 const EPORT* port = findModulePort();
1892
1893 if( port )
1894 {
1895 std::unique_ptr<SCH_HIERLABEL> hierLabel = std::make_unique<SCH_HIERLABEL>();
1897
1898 if( port->direction.has_value() )
1899 {
1900 if( port->direction.value() == "in" )
1902 else if( port->direction.value() == "out" )
1904 else if( port->direction.value() == "io" )
1906 else if( port->direction.value() == "hiz" )
1908 }
1909
1910 hierLabel->SetLabelShape( type );
1911
1912 label = std::move( hierLabel );
1913 }
1914 else if( aIsBus || !m_modules.empty() )
1915 {
1916 label = std::make_unique<SCH_LABEL>();
1917 }
1918 else
1919 {
1920 label = std::make_unique<SCH_GLOBALLABEL>();
1921 }
1922
1923 label->SetText( escapeName( aNetName ) );
1924 label->SetPosition( elabelpos );
1925 label->SetTextSize( textSize );
1926 label->SetSpinStyle( SPIN_STYLE::RIGHT );
1927
1928 if( aLabel->rot.has_value() )
1929 {
1930 // According to the Eagle DTD, labels can only be rotated in 90 degree increments.
1931 int angle = KiROUND( aLabel->rot.value().degrees );
1932
1933 switch( angle )
1934 {
1935 case 90: label->SetSpinStyle( aLabel->rot.value().mirror ? SPIN_STYLE::BOTTOM : SPIN_STYLE::UP ); break;
1936 case 180: label->SetSpinStyle( aLabel->rot.value().mirror ? SPIN_STYLE::RIGHT : SPIN_STYLE::LEFT ); break;
1937 case 270: label->SetSpinStyle( aLabel->rot.value().mirror ? SPIN_STYLE::UP : SPIN_STYLE::BOTTOM ); break;
1938 default: label->SetSpinStyle( aLabel->rot.value().mirror ? SPIN_STYLE::LEFT : SPIN_STYLE::RIGHT ); break;
1939 }
1940 }
1941
1942 return label.release();
1943}
1944
1945
1946std::pair<VECTOR2I, const SEG*> SCH_IO_EAGLE::findNearestLinePoint( const VECTOR2I& aPoint,
1947 const std::vector<SEG>& aLines ) const
1948{
1949 VECTOR2I nearestPoint;
1950 const SEG* nearestLine = nullptr;
1951
1952 double d, mindistance = std::numeric_limits<double>::max();
1953
1954 // Project the label onto the closest wire. Snapping to the perpendicular foot keeps a
1955 // detached Eagle label at its position along the wire; snapping only to the wire's
1956 // endpoints or midpoint would slide it far along a long wire and pile parallel labels
1957 // onto the same point.
1958 for( const SEG& line : aLines )
1959 {
1960 VECTOR2I testpoint = line.NearestPoint( aPoint );
1961 d = aPoint.Distance( testpoint );
1962
1963 if( d < mindistance )
1964 {
1965 mindistance = d;
1966 nearestPoint = testpoint;
1967 nearestLine = &line;
1968 }
1969 }
1970
1971 return std::make_pair( nearestPoint, nearestLine );
1972}
1973
1974
1975void SCH_IO_EAGLE::loadInstance( const std::unique_ptr<EINSTANCE>& aInstance,
1976 const std::map<wxString, std::unique_ptr<EPART>>& aParts )
1977{
1978 wxCHECK( aInstance, /* void */ );
1979
1980 SCH_SCREEN* screen = getCurrentScreen();
1981
1982 wxCHECK( screen, /* void */ );
1983
1984 const auto partIt = aParts.find( aInstance->part );
1985
1986 if( partIt == aParts.end() )
1987 {
1988 Report( wxString::Format( _( "Error parsing Eagle file. Could not find '%s' "
1989 "instance but it is referenced in the schematic." ),
1990 aInstance->part ),
1992
1993 return;
1994 }
1995
1996 const std::unique_ptr<EPART>& epart = partIt->second;
1997
1998 wxString libName = epart->library;
1999
2000 // Correctly handle versioned libraries.
2001 if( epart->libraryUrn.has_value() )
2002 libName += wxS( "_" ) + epart->libraryUrn.value().assetId;
2003
2004 wxString gatename = epart->deviceset + wxS( "_" ) + epart->device + wxS( "_" ) + aInstance->gate;
2005 wxString symbolname = wxString( epart->deviceset + epart->device );
2006 wxString kiPackageName = epart->deviceset + epart->device;
2007
2008 if( epart->technology.has_value() )
2009 symbolname += epart->technology.value();
2010
2011 symbolname.Replace( wxT( "*" ), wxEmptyString );
2012 kiPackageName.Replace( wxT( "*" ), wxEmptyString );
2013
2014 wxString kisymbolname = EscapeString( symbolname, CTX_LIBID );
2015
2016 // Eagle schematics can have multiple libraries containing symbols with duplicate symbol
2017 // names. Because this parser stores all of the symbols in a single library, the
2018 // loadSymbol() function, prefixed the original Eagle library name to the symbol name
2019 // in case of a name clash. Check for the prefixed symbol first. This ensures that
2020 // the correct library symbol gets mapped on load.
2021 wxString altSymbolName = libName + wxT( "_" ) + symbolname;
2022 altSymbolName = EscapeString( altSymbolName, CTX_LIBID );
2023
2024 wxString libIdSymbolName = altSymbolName;
2025
2026 const auto libIt = m_eagleLibs.find( libName );
2027
2028 if( libIt == m_eagleLibs.end() )
2029 {
2030 Report( wxString::Format( wxS( "Eagle library '%s' not found while looking up symbol for "
2031 "deviceset '%s', device '%s', and gate '%s." ),
2032 libName, epart->deviceset, epart->device, aInstance->gate ), RPT_SEVERITY_WARNING );
2033 return;
2034 }
2035
2036 const auto gateIt = libIt->second.GateToUnitMap.find( gatename );
2037
2038 if( gateIt == libIt->second.GateToUnitMap.end() )
2039 {
2040 Report( wxString::Format( wxS( "Symbol not found for deviceset '%s', device '%s', and "
2041 "gate '%s in library '%s'." ),
2042 epart->deviceset, epart->device, aInstance->gate, libName ), RPT_SEVERITY_WARNING );
2043 return;
2044 }
2045
2046 int unit = gateIt->second;
2047
2048 wxString package;
2049 EAGLE_LIBRARY* elib = &m_eagleLibs[libName];
2050
2051 auto p = elib->package.find( kisymbolname );
2052
2053 if( p != elib->package.end() )
2054 {
2055 package = p->second;
2056 }
2057 else
2058 {
2059 p = elib->package.find( kiPackageName );
2060
2061 if( p != elib->package.end() )
2062 package = p->second;
2063 }
2064
2065 // set properties to prevent save file on every symbol save
2066 std::map<std::string, UTF8> properties;
2067 properties.emplace( SCH_IO_KICAD_SEXPR::PropBuffering, wxEmptyString );
2068
2069 LIB_SYMBOL* part = m_pi->LoadSymbol( getLibFileName().GetFullPath(), altSymbolName, &properties );
2070
2071 if( !part )
2072 {
2073 part = m_pi->LoadSymbol( getLibFileName().GetFullPath(), kisymbolname, &properties );
2074 libIdSymbolName = kisymbolname;
2075 }
2076
2077 if( !part )
2078 {
2079 Report( wxString::Format( _( "Could not find '%s' in the imported library." ),
2080 UnescapeString( kisymbolname ) ),
2082 return;
2083 }
2084
2085 LIB_ID libId( getLibName(), libIdSymbolName );
2086 std::unique_ptr<SCH_SYMBOL> symbol = std::make_unique<SCH_SYMBOL>();
2087 symbol->SetLibId( libId );
2088 symbol->SetUnit( unit );
2089 symbol->SetPosition( VECTOR2I( aInstance->x.ToSchUnits(), -aInstance->y.ToSchUnits() ) );
2090
2091 // assume that footprint library is identical to project name
2092 if( !package.IsEmpty() )
2093 {
2094 wxString footprint = m_schematic->Project().GetProjectName() + wxT( ":" ) + package;
2095 symbol->GetField( FIELD_T::FOOTPRINT )->SetText( footprint );
2096 }
2097
2098 if( aInstance->rot.has_value() )
2099 {
2100 symbol->SetOrientation( kiCadComponentRotation( aInstance->rot.value().degrees ) );
2101
2102 if( aInstance->rot.value().mirror )
2103 symbol->MirrorHorizontally( aInstance->x.ToSchUnits() );
2104 }
2105
2106 std::vector<SCH_FIELD*> partFields;
2107 part->GetFields( partFields );
2108
2109 VECTOR2I nextFieldPosition = getLastSymbolFieldPosition( part ) + symbol->GetPosition();
2110
2111 for( const SCH_FIELD* partField : partFields )
2112 {
2113 SCH_FIELD* symbolField = nullptr;
2114
2115 if( partField->IsMandatory() )
2116 symbolField = symbol->GetField( partField->GetId() );
2117 else
2118 symbolField = symbol->GetField( partField->GetName() );
2119
2120 if( !symbolField )
2121 {
2122 SCH_FIELD newField( symbol.get(), FIELD_T::USER, partField->GetName() );
2123
2124 newField.SetVisible( false );
2125 newField.SetText( partField->GetText() );
2126
2127 nextFieldPosition.y += newField.GetTextHeight() + schIUScale.MilsToIU( 10 );
2128 newField.SetPosition( nextFieldPosition );
2129 symbol->AddField( newField );
2130 }
2131 else
2132 {
2133 symbolField->ImportValues( *partField );
2134 symbolField->SetTextPos( symbol->GetPosition() + partField->GetTextPos() );
2135 }
2136 }
2137
2138 wxString reference = aInstance->part;
2139 bool referenceVisible = !reference.IsEmpty();
2140
2141 // If there is no footprint assigned, then prepend the reference value
2142 // with a hash character to mute netlist updater complaints
2143 if( package.IsEmpty() )
2144 reference.Prepend( '#' );
2145
2146 // reference must end with a number but EAGLE does not enforce this
2147 if( reference.find_last_not_of( wxT( "0123456789" ) ) == ( reference.Length()-1 ) )
2148 reference.Append( wxT( "0" ) );
2149
2150 // EAGLE allows references to be single digits. This breaks KiCad netlisting, which requires
2151 // parts to have non-digit + digit annotation. If the reference begins with a number,
2152 // we prepend 'UNK' (unknown) for the symbol designator
2153 if( reference.find_first_not_of( wxT( "0123456789" ) ) != 0 )
2154 reference.Prepend( wxT( "UNK" ) );
2155
2156 // EAGLE allows designator to start with # but that is used in KiCad
2157 // for symbols which do not have a footprint
2158 if( aInstance->part.find_first_not_of( wxT( "#" ) ) != 0 )
2159 reference.Prepend( wxT( "UNK" ) );
2160
2161 SCH_FIELD* referenceField = symbol->GetField( FIELD_T::REFERENCE );
2162 referenceField->SetVisible( referenceVisible );
2163 referenceField->SetText( reference );
2164
2165 SCH_FIELD* valueField = symbol->GetField( FIELD_T::VALUE );
2166 bool userValue = m_userValue.at( libIdSymbolName );
2167
2168 if( part->GetUnitCount() > 1 )
2169 {
2170 getEagleSymbolFieldAttributes( aInstance, wxS( ">NAME" ), referenceField );
2171 getEagleSymbolFieldAttributes( aInstance, wxS( ">VALUE" ), valueField );
2172 }
2173
2174 if( epart->value.has_value() && !epart->value.value().IsEmpty() )
2175 {
2176 valueField->SetText( epart->value.value() );
2177 }
2178 else
2179 {
2180 valueField->SetText( kisymbolname );
2181
2182 if( userValue )
2183 valueField->SetVisible( false );
2184 }
2185
2186 for( const auto& [ attrName, attr ] : epart->attributes )
2187 {
2188 SCH_FIELD newField( symbol.get(), FIELD_T::USER );
2189
2190 newField.SetName( attrName );
2191
2192 if( !symbol->GetFields().empty() )
2193 newField.SetTextPos( symbol->GetFields().back().GetPosition() );
2194
2195 if( attr->value.has_value() )
2196 newField.SetText( attr->value.value() );
2197
2198 if( attr->display.has_value() && attr->display.value() == EATTR::Off )
2199 newField.SetVisible( false );
2200
2201 symbol->AddField( newField );
2202 }
2203
2204 bool valueAttributeFound = false;
2205 bool nameAttributeFound = false;
2206
2207 // Parse attributes for the instance
2208 for( auto& [name, eattr] : aInstance->attributes )
2209 {
2210 SCH_FIELD* field = nullptr;
2211
2212 if( eattr->name.Lower() == wxT( "name" ) )
2213 {
2214 field = symbol->GetField( FIELD_T::REFERENCE );
2215 nameAttributeFound = true;
2216 }
2217 else if( eattr->name.Lower() == wxT( "value" ) )
2218 {
2219 field = symbol->GetField( FIELD_T::VALUE );
2220 valueAttributeFound = true;
2221 }
2222 else
2223 {
2224 field = symbol->GetField( eattr->name );
2225 }
2226
2227 if( field )
2228 {
2229 field->SetVisible( true );
2230 field->SetPosition( VECTOR2I( eattr->x->ToSchUnits(), -eattr->y->ToSchUnits() ) );
2231
2232 if( eattr->size.has_value() )
2233 field->SetTextSize( ConvertEagleTextSize( eattr->font, eattr->size.value() ) );
2234
2235 int align = eattr->align.value_or( ETEXT::BOTTOM_LEFT );
2236 int absdegrees = eattr->rot.has_value() ? KiROUND( eattr->rot.value().degrees ) : 0;
2237 bool mirror = eattr->rot.has_value() ? eattr->rot.value().mirror : false;
2238 bool spin = eattr->rot.has_value() ? eattr->rot.value().spin : false;
2239
2240 if( aInstance->rot.has_value() && aInstance->rot.value().mirror )
2241 mirror = !mirror;
2242
2243 if( eattr->display.has_value() && ( eattr->display.value() == EATTR::Off
2244 || eattr->display.value() == EATTR::NAME ) )
2245 {
2246 field->SetVisible( false );
2247 }
2248
2249 int rotation = aInstance->rot.has_value() ? KiROUND( aInstance->rot.value().degrees ) : 0;
2250 int reldegrees = KiROUND( absdegrees - rotation + 360.0 );
2251 reldegrees %= 360;
2252
2253 eagleToKicadAlignment( field, align, reldegrees, mirror, spin, absdegrees );
2254 }
2255 }
2256
2257 // Use the instance attribute to determine the reference and value field visibility.
2258 if( aInstance->smashed.has_value() && aInstance->smashed.value() )
2259 {
2260 symbol->GetField( FIELD_T::VALUE )->SetVisible( valueAttributeFound );
2261 symbol->GetField( FIELD_T::REFERENCE )->SetVisible( nameAttributeFound );
2262 }
2263
2264 // Eagle has a brain dead module reference scheme where the module names separated by colons
2265 // are prefixed to the symbol references. This will get blown away in KiCad the first time
2266 // any annotation is performed. It is required for the initial synchronization between the
2267 // schematic and the board.
2268 wxString refPrefix;
2269
2270 for( const EMODULEINST* emoduleInst : m_moduleInstances )
2271 {
2272 wxCHECK2( emoduleInst, continue );
2273
2274 refPrefix += emoduleInst->name + wxS( ":" );
2275 }
2276
2277 symbol->AddHierarchicalReference( m_sheetPath.Path(), refPrefix + reference, unit );
2278
2279 // Cache the lib symbol so pin positions are available for connection-point tracking.
2280 // Use the already-loaded `part` directly rather than re-fetching through the adapter,
2281 // because the .kicad_sym library is still buffered in m_pi and has not yet been saved to
2282 // disk at the time loadInstance runs.
2283 symbol->SetLibSymbol( part->Flatten().release() );
2284
2285 for( const auto& [name, variant] : epart->variants )
2286 {
2287 SCH_SYMBOL_VARIANT symbolVariant( name );
2288
2289 if( variant->populate.has_value() && variant->populate.value() == false )
2290 symbolVariant.m_DNP = true;
2291
2292 if( variant->value )
2293 symbolVariant.m_Fields[GetDefaultFieldName( FIELD_T::VALUE, UNTRANSLATED )] = *variant->value;
2294
2295 if( variant->technology.has_value() )
2296 {
2297 auto eLibIt = m_eagleDoc->drawing->schematic->libraries.find( epart->library );
2298
2299 if( eLibIt == m_eagleDoc->drawing->schematic->libraries.end() )
2300 {
2301 Report( wxString::Format( wxS( "Library '%s' not found in schematic." ), epart->library ),
2303 continue;
2304 }
2305
2306 auto eDeviceSetIt = eLibIt->second->devicesets.find( epart->deviceset );
2307
2308 if( eDeviceSetIt == eLibIt->second->devicesets.end() )
2309 {
2310 Report( wxString::Format( wxS( "Device set '%s' not found in library '%s'." ),
2311 epart->deviceset,
2312 epart->library ), RPT_SEVERITY_WARNING );
2313 continue;
2314 }
2315
2316 auto eDeviceIt = eDeviceSetIt->second->devices.find( epart->device );
2317
2318 if( eDeviceIt == eDeviceSetIt->second->devices.end() )
2319 {
2320 Report( wxString::Format( wxS( "Device '%s' not found in device set '%s' in library '%s'." ),
2321 epart->device,
2322 epart->deviceset,
2323 epart->library ), RPT_SEVERITY_WARNING );
2324 continue;
2325 }
2326
2327 auto eTechnologyIt = eDeviceIt->second->technologies.find( variant->technology.value() );
2328
2329 if( eTechnologyIt == eDeviceIt->second->technologies.end() )
2330 {
2331 Report( wxString::Format( wxS( "Technology '%s' not found in device '%s' in device set '%s' "
2332 "in library '%s'." ),
2333 variant->technology.value(),
2334 epart->device,
2335 epart->deviceset,
2336 epart->library ), RPT_SEVERITY_WARNING );
2337 continue;
2338 }
2339
2340 for( const std::unique_ptr<EATTR>& attr : eTechnologyIt->second->attributes )
2341 {
2342 wxString attrValue;
2343
2344 if( attr->value.has_value() )
2345 attrValue = attr->value.value();
2346
2347 symbolVariant.m_Fields[attr->name] = attrValue;
2348 }
2349 }
2350
2351 symbol->AddVariant( m_sheetPath, symbolVariant );
2352 }
2353
2354 for( const SCH_PIN* pin : symbol->GetLibPins() )
2355 m_connPoints[symbol->GetPinPhysicalPosition( pin )].emplace( pin );
2356
2357 if( part->IsGlobalPower() )
2358 m_powerPorts[ reference ] = symbol->GetField( FIELD_T::VALUE )->GetText();
2359
2360 symbol->ClearFlags();
2361
2362 screen->Append( symbol.release() );
2363}
2364
2365
2367{
2368 wxCHECK( aLibrary && aEagleLibrary, nullptr );
2370
2371 // Loop through the device sets and load each of them
2372 for( const auto& [name, edeviceset] : aLibrary->devicesets )
2373 {
2374 // Get Device set information
2375 wxString prefix = edeviceset->prefix.value_or( wxEmptyString );
2376 wxString deviceSetDescr;
2377
2378 if( edeviceset->description )
2379 deviceSetDescr = convertDescription( UnescapeHTML( edeviceset->description->text ) );
2380
2381 // For each device in the device set:
2382 for( const auto& [devname, edevice] : edeviceset->devices )
2383 {
2384 std::vector<std::unique_ptr<LIB_SYMBOL>> derivedSymbols;
2385
2386 // Create symbol name from deviceset and device names.
2387 wxString symbolName = edeviceset->name + edevice->name;
2388 symbolName.Replace( wxT( "*" ), wxEmptyString );
2389 wxASSERT( !symbolName.IsEmpty() );
2390 symbolName = EscapeString( symbolName, CTX_LIBID );
2391
2392 if( edevice->package.has_value() )
2393 aEagleLibrary->package[symbolName] = edevice->package.value();
2394
2395 // Create KiCad symbol.
2396 std::unique_ptr<LIB_SYMBOL> libSymbol = std::make_unique<LIB_SYMBOL>( symbolName );
2397
2398 // Process each gate in the deviceset for this device.
2399 int gate_count = static_cast<int>( edeviceset->gates.size() );
2400
2401 if( gate_count > 1 )
2402 libSymbol->SetUnitCount( gate_count, true );
2403
2404 libSymbol->LockUnits( true );
2405
2406 SCH_FIELD* reference = libSymbol->GetField( FIELD_T::REFERENCE );
2407
2408 if( prefix.length() == 0 )
2409 {
2410 reference->SetVisible( false );
2411 }
2412 else
2413 {
2414 // If there is no footprint assigned, then prepend the reference value
2415 // with a hash character to mute netlist updater complaints
2416 reference->SetText( edevice->package.has_value() ? prefix : '#' + prefix );
2417 }
2418
2419 libSymbol->GetValueField().SetVisible( true );
2420
2421 int gateindex = 1;
2422 bool ispower = false;
2423
2424 for( const auto& [gateName, egate] : edeviceset->gates )
2425 {
2426 const auto it = aLibrary->symbols.find( egate->symbol );
2427
2428 if( it == aLibrary->symbols.end() )
2429 {
2430 Report( wxString::Format( wxS( "Eagle symbol '%s' not found in library '%s'." ),
2431 egate->symbol,
2432 aLibrary->GetName() ), RPT_SEVERITY_WARNING );
2433 continue;
2434 }
2435
2436 wxString gateMapName = edeviceset->name + wxS( "_" ) + edevice->name + wxS( "_" ) + egate->name;
2437 aEagleLibrary->GateToUnitMap[gateMapName] = gateindex;
2438 ispower = loadSymbol( it->second, libSymbol, edevice, gateindex, egate->name );
2439
2440 gateindex++;
2441 }
2442
2443 std::vector<SCH_FIELD*> fields;
2444 libSymbol->GetFields( fields );
2445
2446 for( SCH_FIELD* field : fields )
2447 field->SetCanAutoplace( canAutoplace );
2448
2449 for( const auto& [techname, technology ] : edevice->technologies )
2450 {
2451 std::unique_ptr<LIB_SYMBOL> derivedSymbol;
2452 VECTOR2I nextFieldPosition = getLastSymbolFieldPosition( libSymbol.get() );
2453
2454 if( !technology->name.IsEmpty() )
2455 {
2456 derivedSymbol = std::make_unique<LIB_SYMBOL>( symbolName + technology->name, libSymbol.get() );
2457
2458 for( SCH_FIELD* parentField : fields )
2459 {
2460 SCH_FIELD* childField = derivedSymbol->GetField( parentField->GetName() );
2461
2462 if( childField )
2463 {
2464 childField->SetAttributes( *parentField );
2465 childField->SetCanAutoplace( canAutoplace );
2466 }
2467 }
2468 }
2469
2470 for( const std::unique_ptr<EATTR>& attr : technology->attributes )
2471 {
2472 if( !attr->value.has_value() )
2473 continue;
2474
2475 SCH_FIELD* field = nullptr;
2476
2477 if( !derivedSymbol )
2478 field = libSymbol->FindFieldCaseInsensitive( attr->name );
2479 else
2480 field = derivedSymbol->FindFieldCaseInsensitive( attr->name );
2481
2482 if( field )
2483 {
2484 field->SetText( attr->value.value() );
2485 }
2486 else
2487 {
2488 SCH_FIELD* newField = new SCH_FIELD( derivedSymbol ? derivedSymbol.get() : libSymbol.get(),
2489 FIELD_T::USER, attr->name );
2490
2491 if( derivedSymbol )
2492 {
2493 SCH_FIELD* parentField = libSymbol->FindFieldCaseInsensitive( attr->name );
2494
2495 if( parentField )
2496 newField->SetAttributes( *parentField );
2497 }
2498
2499 nextFieldPosition.y += newField->GetTextHeight() + schIUScale.MilsToIU( 10 );
2500 newField->SetText( attr->value.value() );
2501 newField->SetVisible( false );
2502 newField->SetPosition( nextFieldPosition );
2503 newField->SetCanAutoplace( canAutoplace );
2504
2505 if( !derivedSymbol )
2506 libSymbol->AddField( newField );
2507 else
2508 derivedSymbol->AddField( newField );
2509 }
2510 }
2511
2512 if( derivedSymbol )
2513 derivedSymbols.push_back( std::move( derivedSymbol ) );
2514 }
2515
2516 if( gate_count > 1 )
2517 libSymbol->SetUnitCount( gate_count, true );
2518
2519 if( gate_count == 1 && ispower )
2520 libSymbol->SetGlobalPower();
2521
2522 // Don't set the footprint field if no package is defined in the Eagle schematic.
2523 if( edevice->package.has_value() && !edevice->package.value().IsEmpty() )
2524 {
2525 wxString libName;
2526
2527 if( m_schematic )
2528 {
2529 // assume that footprint library is identical to project name
2530 libName = m_schematic->Project().GetProjectName();
2531 }
2532 else
2533 {
2534 libName = m_libName;
2535 }
2536
2537 wxString packageString = libName + wxT( ":" ) + aEagleLibrary->package[symbolName];
2538
2539 libSymbol->GetFootprintField().SetText( packageString );
2540 }
2541
2542 wxString libName = libSymbol->GetName();
2543 libSymbol->SetName( libName );
2544 libSymbol->SetDescription( deviceSetDescr );
2545
2546 if( m_pi )
2547 {
2548 // If duplicate symbol names exist in multiple Eagle symbol libraries, prefix the
2549 // Eagle symbol library name to the symbol which should ensure that it is unique.
2550 try
2551 {
2552 if( m_pi->LoadSymbol( getLibFileName().GetFullPath(), libName ) )
2553 {
2554 libName = aEagleLibrary->name + wxT( "_" ) + libName;
2555 libName = EscapeString( libName, CTX_LIBID );
2556 libSymbol->SetName( libName );
2557 }
2558
2559 // set properties to prevent save file on every symbol save
2560 std::map<std::string, UTF8> properties;
2561 properties.emplace( SCH_IO_KICAD_SEXPR::PropBuffering, wxEmptyString );
2562
2563
2564 std::unique_ptr<LIB_SYMBOL> parentSymbol = std::make_unique<LIB_SYMBOL>( *libSymbol );
2565
2566 m_pi->SaveSymbol( getLibFileName().GetFullPath(), std::move( parentSymbol ),
2567 &properties );
2568
2569 // The plugin cache owns the parent symbol after the save, we cannot use it
2570 // safely after handing it to the plugin.
2571 // Borrow the parent symbol from the plugin cache.
2572 LIB_SYMBOL* parent = m_pi->LoadSymbol( getLibFileName().GetFullPath(), libSymbol->GetName() );
2573
2574 if( !parent )
2575 {
2576 Report( wxString::Format( _( "Could not reload saved symbol '%s'" ),
2577 UnescapeString( libSymbol->GetName() ) ),
2579 }
2580 else
2581 {
2582 for( std::unique_ptr<LIB_SYMBOL>& symbol : derivedSymbols )
2583 {
2584 if( m_pi->LoadSymbol( getLibFileName().GetFullPath(), symbol->GetName() ) )
2585 {
2586 wxString tmp = aEagleLibrary->name + wxT( "_" ) + symbol->GetName();
2587 tmp = EscapeString( tmp, CTX_LIBID );
2588 symbol->SetName( tmp );
2589 }
2590
2591 std::unique_ptr<LIB_SYMBOL> derivedSymbol = std::make_unique<LIB_SYMBOL>( *symbol );
2592
2593 derivedSymbol->SetParent( parent );
2594 m_pi->SaveSymbol( getLibFileName().GetFullPath(), std::move( derivedSymbol ), &properties );
2595 }
2596 }
2597 }
2598 catch(...)
2599 {
2600 // A library symbol cannot be loaded for some reason.
2601 // Just skip this symbol creating an issue.
2602 // The issue will be reported later by the Reporter
2603 }
2604 }
2605
2606 aEagleLibrary->KiCadSymbols[ libName ] = std::move( libSymbol );
2607
2608 // Store information on whether the value of FIELD_T::VALUE for a part should be
2609 // part/@value or part/@deviceset + part/@device.
2610 m_userValue.emplace( std::make_pair( libName, edeviceset->uservalue.value_or( false ) ) );
2611
2612 for( std::unique_ptr<LIB_SYMBOL>& symbol : derivedSymbols )
2613 {
2614 m_userValue.emplace( std::make_pair( symbol->GetName(), edeviceset->uservalue.value_or( false ) ) );
2615 aEagleLibrary->KiCadSymbols[symbol->GetName()] = std::move( symbol );
2616 }
2617 }
2618 }
2619
2620 return aEagleLibrary;
2621}
2622
2623
2624bool SCH_IO_EAGLE::loadSymbol( const std::unique_ptr<ESYMBOL>& aEsymbol, std::unique_ptr<LIB_SYMBOL>& aSymbol,
2625 const std::unique_ptr<EDEVICE>& aDevice, int aGateNumber, const wxString& aGateName )
2626{
2627 wxCHECK( aEsymbol && aSymbol && aDevice, false );
2628
2629 std::vector<SCH_ITEM*> items;
2630
2631 bool showRefDes = false;
2632 bool showValue = false;
2633 bool ispower = false;
2634 int pincount = 0;
2635
2636 for( const std::unique_ptr<ECIRCLE>& ecircle : aEsymbol->circles )
2637 aSymbol->AddDrawItem( loadSymbolCircle( aSymbol, ecircle, aGateNumber ) );
2638
2639 for( const std::unique_ptr<EPIN>& epin : aEsymbol->pins )
2640 {
2641 std::unique_ptr<SCH_PIN> pin( loadPin( aSymbol, epin, aGateNumber ) );
2642 pincount++;
2643
2644 pin->SetType( ELECTRICAL_PINTYPE::PT_BIDI );
2645
2646 if( epin->direction.has_value() )
2647 {
2648 for( const auto& pinDir : pinDirectionsMap )
2649 {
2650 if( epin->direction.value().Lower() == pinDir.first )
2651 {
2652 pin->SetType( pinDir.second );
2653
2654 if( pinDir.first == wxT( "sup" ) ) // power supply symbol
2655 ispower = true;
2656
2657 break;
2658 }
2659 }
2660 }
2661
2662 if( aDevice->connects.size() != 0 )
2663 {
2664 for( const std::unique_ptr<ECONNECT>& connect : aDevice->connects )
2665 {
2666 // Eagle <connect> references the full pin name including any "@<tag>"
2667 // linking hint, so match against the raw Eagle name rather than the
2668 // stripped display name set on the pin.
2669 if( connect->gate == aGateName && epin->name == connect->pin )
2670 {
2671 wxArrayString pads = wxSplit( wxString( connect->pad ), ' ' );
2672
2673 pin->SetUnit( aGateNumber );
2674 pin->SetName( escapeName( pin->GetName() ) );
2675
2676 if( pads.GetCount() > 1 )
2677 {
2678 pin->SetNumberTextSize( 0 );
2679 }
2680
2681 for( unsigned i = 0; i < pads.GetCount(); i++ )
2682 {
2683 SCH_PIN* apin = new SCH_PIN( *pin );
2684
2685 wxString padname( pads[i] );
2686 apin->SetNumber( padname );
2687 aSymbol->AddDrawItem( apin );
2688 }
2689
2690 break;
2691 }
2692 }
2693 }
2694 else
2695 {
2696 pin->SetUnit( aGateNumber );
2697 pin->SetNumber( wxString::Format( wxT( "%i" ), pincount ) );
2698 aSymbol->AddDrawItem( pin.release() );
2699 }
2700 }
2701
2702 for( const std::unique_ptr<EPOLYGON>& epolygon : aEsymbol->polygons )
2703 {
2704 if( SCH_SHAPE* shape = loadSymbolPolyLine( aSymbol, epolygon, aGateNumber ) )
2705 aSymbol->AddDrawItem( shape );
2706 }
2707
2708 for( const std::unique_ptr<ERECT>& erectangle : aEsymbol->rectangles )
2709 aSymbol->AddDrawItem( loadSymbolRectangle( aSymbol, erectangle, aGateNumber ) );
2710
2711 for( const std::unique_ptr<ETEXT>& etext : aEsymbol->texts )
2712 {
2713 std::unique_ptr<SCH_TEXT> libtext( loadSymbolText( aSymbol, etext, aGateNumber ) );
2714
2715 if( libtext->GetText() == wxT( "${REFERENCE}" ) )
2716 {
2717 // Keep the deviceset prefix because the Eagle text is only a placeholder
2718 aSymbol->GetReferenceField().SetAttributes( *libtext );
2719
2720 // Show Reference field if Eagle reference was uppercase
2721 showRefDes = etext->text == wxT( ">NAME" );
2722 }
2723 else if( libtext->GetText() == wxT( "${VALUE}" ) )
2724 {
2725 // Keep the field value because the Eagle text is only a placeholder
2726 aSymbol->GetValueField().SetAttributes( *libtext );
2727
2728 // Show Value field if Eagle reference was uppercase
2729 showValue = etext->text == wxT( ">VALUE" );
2730 }
2731 else if( etext->text.StartsWith( ">" ) )
2732 {
2733 // Text values that start with '>' are place holders for fields defined later
2734 // in library deviceset objects.
2735 wxString fieldName = etext->text.Mid( 1 );
2736
2737 if( !fieldName.IsEmpty() )
2738 {
2739 SCH_FIELD* field = new SCH_FIELD( aSymbol.get(), FIELD_T::USER, fieldName );
2740
2741 field->SetAttributes( *libtext );
2742
2743 // Field visibility is determined by the symbol instance attributes.
2744 field->SetVisible( false );
2745 aSymbol->AddField( field );
2746 }
2747 }
2748 else
2749 {
2750 aSymbol->AddDrawItem( libtext.release() );
2751 }
2752 }
2753
2754 for( const std::unique_ptr<EWIRE>& ewire : aEsymbol->wires )
2755 aSymbol->AddDrawItem( loadSymbolWire( aSymbol, ewire, aGateNumber ) );
2756
2757 for( const std::unique_ptr<EFRAME>& eframe : aEsymbol->frames )
2758 {
2759 std::vector<SCH_ITEM*> frameItems;
2760
2761 loadFrame( eframe, frameItems );
2762
2763 for( SCH_ITEM* item : frameItems )
2764 {
2765 item->SetParent( aSymbol.get() );
2766 item->SetUnit( aGateNumber );
2767 aSymbol->AddDrawItem( item );
2768 }
2769 }
2770
2771 aSymbol->GetReferenceField().SetVisible( showRefDes );
2772 aSymbol->GetValueField().SetVisible( showValue );
2773
2774 return pincount == 1 ? ispower : false;
2775}
2776
2777
2778SCH_SHAPE* SCH_IO_EAGLE::loadSymbolCircle( std::unique_ptr<LIB_SYMBOL>& aSymbol,
2779 const std::unique_ptr<ECIRCLE>& aCircle, int aGateNumber )
2780{
2781 wxCHECK( aSymbol && aCircle, nullptr );
2782
2783 // Parse the circle properties
2785 VECTOR2I center( aCircle->x.ToSchUnits(), -aCircle->y.ToSchUnits() );
2786
2787 circle->SetParent( aSymbol.get() );
2788 circle->SetPosition( center );
2789 circle->SetEnd( VECTOR2I( center.x + aCircle->radius.ToSchUnits(), center.y ) );
2790
2791 if( aCircle->width.ToSchUnits() == 0 )
2792 {
2793 circle->SetStroke( STROKE_PARAMS( -1, LINE_STYLE::SOLID ) );
2794 circle->SetFillMode( FILL_T::FILLED_SHAPE );
2795 }
2796 else
2797 {
2798 circle->SetStroke( STROKE_PARAMS( aCircle->width.ToSchUnits(), LINE_STYLE::SOLID ) );
2799 }
2800
2801 if( aSymbol->IsMultiUnit() )
2802 circle->SetUnit( aGateNumber );
2803
2804 return circle;
2805}
2806
2807
2808SCH_SHAPE* SCH_IO_EAGLE::loadSymbolRectangle( std::unique_ptr<LIB_SYMBOL>& aSymbol,
2809 const std::unique_ptr<ERECT>& aRectangle, int aGateNumber )
2810{
2811 wxCHECK( aSymbol && aRectangle, nullptr );
2812
2814
2815 rectangle->SetParent( aSymbol.get() );
2816 rectangle->SetPosition( VECTOR2I( aRectangle->x1.ToSchUnits(), -aRectangle->y1.ToSchUnits() ) );
2817 rectangle->SetEnd( VECTOR2I( aRectangle->x2.ToSchUnits(), -aRectangle->y2.ToSchUnits() ) );
2818
2819 if( aRectangle->rot.has_value() )
2820 {
2821 VECTOR2I pos( rectangle->GetPosition() );
2822 VECTOR2I end( rectangle->GetEnd() );
2823 VECTOR2I center( rectangle->GetCenter() );
2824
2825 RotatePoint( pos, center, EDA_ANGLE( aRectangle->rot.value().degrees, DEGREES_T ) );
2826 RotatePoint( end, center, EDA_ANGLE( aRectangle->rot.value().degrees, DEGREES_T ) );
2827
2828 rectangle->SetPosition( pos );
2829 rectangle->SetEnd( end );
2830 }
2831
2832 if( aSymbol->IsMultiUnit() )
2833 rectangle->SetUnit( aGateNumber );
2834
2835 // Eagle rectangles are filled and have vanishing line width by definition.
2836 rectangle->SetFillMode( FILL_T::FILLED_SHAPE );
2837 rectangle->SetWidth( -1 );
2838
2839 return rectangle;
2840}
2841
2842
2843SCH_ITEM* SCH_IO_EAGLE::loadSymbolWire( std::unique_ptr<LIB_SYMBOL>& aSymbol,
2844 const std::unique_ptr<EWIRE>& aWire, int aGateNumber )
2845{
2846 wxCHECK( aSymbol && aWire, nullptr );
2847
2848 VECTOR2I begin, end;
2849
2850 begin.x = aWire->x1.ToSchUnits();
2851 begin.y = -aWire->y1.ToSchUnits();
2852 end.x = aWire->x2.ToSchUnits();
2853 end.y = -aWire->y2.ToSchUnits();
2854
2855 if( begin == end )
2856 return nullptr;
2857
2858 // if the wire is an arc
2859 if( aWire->curve )
2860 {
2862 VECTOR2I center = ConvertArcCenter( begin, end, *aWire->curve );
2863 double radius = sqrt( ( ( center.x - begin.x ) * ( center.x - begin.x ) ) +
2864 ( ( center.y - begin.y ) * ( center.y - begin.y ) ) );
2865
2866 arc->SetParent( aSymbol.get() );
2867
2868 // this emulates the filled semicircles created by a thick arc with flat ends caps.
2869 if( aWire->cap.has_value() && aWire->cap.value() == EWIRE::FLAT && aWire->width.ToSchUnits() >= 2 * radius )
2870 {
2871 VECTOR2I centerStartVector = ( begin - center ) * ( aWire->width.ToSchUnits() / radius );
2872 begin = center + centerStartVector;
2873
2876 }
2877 else
2878 {
2879 arc->SetStroke( STROKE_PARAMS( aWire->width.ToSchUnits(), LINE_STYLE::SOLID ) );
2880 }
2881
2882 arc->SetCenter( center );
2883 arc->SetStart( begin );
2884
2885 // KiCad rotates the other way.
2886 arc->SetArcAngleAndEnd( -EDA_ANGLE( *aWire->curve, DEGREES_T ), true );
2887
2888 if( aSymbol->IsMultiUnit() )
2889 arc->SetUnit( aGateNumber );
2890
2891 return arc;
2892 }
2893 else
2894 {
2896
2897 poly->AddPoint( begin );
2898 poly->AddPoint( end );
2899
2900 if( aSymbol->IsMultiUnit() )
2901 poly->SetUnit( aGateNumber );
2902
2903 poly->SetStroke( STROKE_PARAMS( aWire->width.ToSchUnits(), LINE_STYLE::SOLID ) );
2904
2905 return poly;
2906 }
2907}
2908
2909
2910SCH_SHAPE* SCH_IO_EAGLE::loadSymbolPolyLine( std::unique_ptr<LIB_SYMBOL>& aSymbol,
2911 const std::unique_ptr<EPOLYGON>& aPolygon, int aGateNumber )
2912{
2913 wxCHECK( aSymbol && aPolygon, nullptr );
2914
2915 if( !aPolygon->IsValidOutline() )
2916 return nullptr;
2917
2919 VECTOR2I pt;
2920 VECTOR2I prev_pt;
2921 std::optional<double> prev_curve;
2922 std::optional<VECTOR2I> first_pt;
2923
2924 poly->SetParent( aSymbol.get() );
2925
2926 for( const std::unique_ptr<EVERTEX>& evertex : aPolygon->vertices )
2927 {
2928 pt = VECTOR2I( evertex->x.ToSchUnits(), -evertex->y.ToSchUnits() );
2929
2930 if( !first_pt.has_value() )
2931 first_pt = pt;
2932
2933 if( prev_curve.has_value() )
2934 {
2935 SHAPE_ARC arc;
2936 arc.ConstructFromStartEndAngle( prev_pt, pt, -EDA_ANGLE( prev_curve.value(), DEGREES_T ) );
2937 poly->GetPolyShape().Append( arc, -1, -1, ARC_ACCURACY );
2938 }
2939 else
2940 {
2941 poly->AddPoint( pt );
2942 }
2943
2944 prev_pt = pt;
2945 prev_curve = evertex->curve;
2946 }
2947
2948 if( first_pt.has_value() )
2949 poly->AddPoint( first_pt.value() );
2950
2951 poly->SetStroke( STROKE_PARAMS( aPolygon->width.ToSchUnits(), LINE_STYLE::SOLID ) );
2953
2954 if( aSymbol->IsMultiUnit() )
2955 poly->SetUnit( aGateNumber );
2956
2957 return poly;
2958}
2959
2960
2961SCH_PIN* SCH_IO_EAGLE::loadPin( std::unique_ptr<LIB_SYMBOL>& aSymbol,
2962 const std::unique_ptr<EPIN>& aPin, int aGateNumber )
2963{
2964 wxCHECK( aSymbol && aPin, nullptr );
2965
2966 std::unique_ptr<SCH_PIN> pin = std::make_unique<SCH_PIN>( aSymbol.get() );
2967 pin->SetPosition( VECTOR2I( aPin->x.ToSchUnits(), -aPin->y.ToSchUnits() ) );
2968
2969 // Eagle pin names may carry a trailing "@<tag>" linking hint that disambiguates
2970 // duplicate names within a symbol. It is metadata, not visible text, so strip it
2971 // from the displayed name. The full Eagle name is still used to match <connect>.
2972 pin->SetName( extractNetName( aPin->name ) );
2973
2974 if( aSymbol->IsMultiUnit() )
2975 pin->SetUnit( aGateNumber );
2976
2977 int roti = aPin->rot.has_value() ? KiROUND( aPin->rot.value().degrees ) : 0;
2978
2979 switch( roti )
2980 {
2981 case 0: pin->SetOrientation( PIN_ORIENTATION::PIN_RIGHT ); break;
2982 case 90: pin->SetOrientation( PIN_ORIENTATION::PIN_UP ); break;
2983 case 180: pin->SetOrientation( PIN_ORIENTATION::PIN_LEFT ); break;
2984 case 270: pin->SetOrientation( PIN_ORIENTATION::PIN_DOWN ); break;
2985 default: wxFAIL_MSG( wxString::Format( wxT( "Unhandled orientation (%d degrees)." ), roti ) );
2986 }
2987
2988 pin->SetLength( schIUScale.MilsToIU( 300 ) ); // Default pin length when not defined.
2989
2990 if( aPin->length.has_value() )
2991 {
2992 if( aPin->length.value() == wxT( "short" ) )
2993 pin->SetLength( schIUScale.MilsToIU( 100 ) );
2994 else if( aPin->length.value() == wxT( "middle" ) )
2995 pin->SetLength( schIUScale.MilsToIU( 200 ) );
2996 else if( aPin->length.value() == wxT( "long" ) )
2997 pin->SetLength( schIUScale.MilsToIU( 300 ) );
2998 else if( aPin->length.value() == wxT( "point" ) )
2999 pin->SetLength( schIUScale.MilsToIU( 0 ) );
3000 }
3001
3002 // Pin names and numbers are fixed size in Eagle.
3003 pin->SetNumberTextSize( schIUScale.MilsToIU( 60 ) );
3004 pin->SetNameTextSize( schIUScale.MilsToIU( 60 ) );
3005
3006 // emulate the visibility of pin elements
3007 if( aPin->visible.has_value() )
3008 {
3009 if( aPin->visible.value() == wxT( "off" ) )
3010 {
3011 pin->SetNameTextSize( 0 );
3012 pin->SetNumberTextSize( 0 );
3013 }
3014 else if( aPin->visible.value() == wxT( "pad" ) )
3015 {
3016 pin->SetNameTextSize( 0 );
3017 }
3018 else if( aPin->visible.value() == wxT( "pin" ) )
3019 {
3020 pin->SetNumberTextSize( 0 );
3021 }
3022
3023 /*
3024 * else if( visible == wxT( "both" ) )
3025 * {
3026 * }
3027 */
3028 }
3029
3030 if( aPin->function.has_value() )
3031 {
3032 if( aPin->function.value() == wxT( "dot" ) )
3033 pin->SetShape( GRAPHIC_PINSHAPE::INVERTED );
3034 else if( aPin->function.value() == wxT( "clk" ) )
3035 pin->SetShape( GRAPHIC_PINSHAPE::CLOCK );
3036 else if( aPin->function.value() == wxT( "dotclk" ) )
3038 }
3039
3040 return pin.release();
3041}
3042
3043
3044SCH_TEXT* SCH_IO_EAGLE::loadSymbolText( std::unique_ptr<LIB_SYMBOL>& aSymbol,
3045 const std::unique_ptr<ETEXT>& aText, int aGateNumber )
3046{
3047 wxCHECK( aSymbol && aText, nullptr );
3048
3049 std::unique_ptr<SCH_TEXT> libtext = std::make_unique<SCH_TEXT>();
3050
3051 libtext->SetLayer( LAYER_DEVICE );
3052 libtext->SetParent( aSymbol.get() );
3053
3054 if( aSymbol->IsMultiUnit() )
3055 libtext->SetUnit( aGateNumber );
3056
3057 libtext->SetPosition( VECTOR2I( aText->x.ToSchUnits(), -aText->y.ToSchUnits() ) );
3058
3059 const wxString& eagleText = aText->text;
3060 wxString adjustedText;
3061 wxStringTokenizer tokenizer( eagleText, "\r\n" );
3062
3063 // Strip the whitespace from both ends of each line.
3064 while( tokenizer.HasMoreTokens() )
3065 {
3066 wxString tmp = interpretText( tokenizer.GetNextToken().Trim( true ).Trim( false ) );
3067
3068 if( tokenizer.HasMoreTokens() )
3069 tmp += wxT( "\n" );
3070
3071 adjustedText += tmp;
3072 }
3073
3074 libtext->SetText( adjustedText.IsEmpty() ? wxString( wxS( "~" ) ) : adjustedText );
3075
3076 loadTextAttributes( libtext.get(), aText );
3077
3078 return libtext.release();
3079}
3080
3081
3082SCH_TEXT* SCH_IO_EAGLE::loadPlainText( const std::unique_ptr<ETEXT>& aText )
3083{
3084 wxCHECK( aText, nullptr );
3085
3086 std::unique_ptr<SCH_TEXT> schtext = std::make_unique<SCH_TEXT>();
3087
3088 const wxString& eagleText = aText->text;
3089 wxString adjustedText;
3090 wxStringTokenizer tokenizer( eagleText, "\r\n" );
3091
3092 // Strip the whitespace from both ends of each line.
3093 while( tokenizer.HasMoreTokens() )
3094 {
3095 wxString tmp = interpretText( tokenizer.GetNextToken().Trim( true ).Trim( false ) );
3096
3097 if( tokenizer.HasMoreTokens() )
3098 tmp += wxT( "\n" );
3099
3100 adjustedText += tmp;
3101 }
3102
3103 schtext->SetText( adjustedText.IsEmpty() ? wxString( wxS( "\" \"" ) )
3104 : escapeName( adjustedText ) );
3105
3106 schtext->SetPosition( VECTOR2I( aText->x.ToSchUnits(), -aText->y.ToSchUnits() ) );
3107 loadTextAttributes( schtext.get(), aText );
3108 schtext->SetItalic( false );
3109
3110 return schtext.release();
3111}
3112
3113
3114void SCH_IO_EAGLE::loadTextAttributes( EDA_TEXT* aText, const std::unique_ptr<ETEXT>& aAttributes ) const
3115{
3116 wxCHECK( aText && aAttributes, /* void */ );
3117
3118 aText->SetTextSize( aAttributes->ConvertSize() );
3119
3120 // Must come after SetTextSize()
3121 if( aAttributes->ratio.value_or( 8 ) > 12 )
3122 aText->SetBold( true );
3123
3124 int align = aAttributes->align.value_or( ETEXT::BOTTOM_LEFT );
3125 int degrees = aAttributes->rot.has_value() ? KiROUND( aAttributes->rot.value().degrees ) : 0;
3126 bool mirror = aAttributes->rot.has_value() ? aAttributes->rot.value().mirror : false;
3127 bool spin = aAttributes->rot.has_value() ? aAttributes->rot.value().spin : false;
3128
3129 eagleToKicadAlignment( aText, align, degrees, mirror, spin, 0 );
3130}
3131
3132
3134{
3135 // Eagle supports detached labels, so a label does not need to be placed on a wire
3136 // to be associated with it. KiCad needs to move them, so the labels actually touch the
3137 // corresponding wires.
3138
3139 // Sort the intersection points to speed up the search process
3140 std::sort( m_wireIntersections.begin(), m_wireIntersections.end() );
3141
3142 auto onIntersection =
3143 [&]( const VECTOR2I& aPos )
3144 {
3145 return std::binary_search( m_wireIntersections.begin(), m_wireIntersections.end(), aPos );
3146 };
3147
3148 for( SEG_DESC& segDesc : m_segments )
3149 {
3150 for( SCH_LABEL_BASE* label : segDesc.labels )
3151 {
3152 VECTOR2I labelPos( label->GetPosition() );
3153 const SEG* segAttached = segDesc.LabelAttached( label );
3154
3155 if( segAttached && !onIntersection( labelPos ) )
3156 continue; // label is placed correctly
3157
3158 // Move the label to the nearest wire
3159 if( !segAttached )
3160 {
3161 std::tie( labelPos, segAttached ) = findNearestLinePoint( label->GetPosition(), segDesc.segs );
3162
3163 if( !segAttached ) // we cannot do anything
3164 continue;
3165 }
3166
3167 // Create a vector pointing in the direction of the wire, 50 mils long
3168 VECTOR2I wireDirection( segAttached->B - segAttached->A );
3169
3170 if( ( wireDirection.x == 0 ) && (wireDirection.y == 0 ) )
3171 continue;
3172
3173 wireDirection = wireDirection.Resize( schIUScale.MilsToIU( 50 ) );
3174 const VECTOR2I origPos( labelPos );
3175
3176 // Flags determining the search direction
3177 bool checkPositive = true;
3178 bool checkNegative = true;
3179 bool move = false;
3180 int trial = 0;
3181
3182 // Be sure the label is not placed on a wire intersection
3183 while( ( !move || onIntersection( labelPos ) ) && ( checkPositive || checkNegative ) )
3184 {
3185 move = false;
3186
3187 // Move along the attached wire to find the new label position
3188 if( trial % 2 == 1 )
3189 {
3190 labelPos = VECTOR2I( origPos + wireDirection * trial / 2 );
3191 move = checkPositive = segAttached->Contains( labelPos );
3192 }
3193 else
3194 {
3195 labelPos = VECTOR2I( origPos - wireDirection * trial / 2 );
3196 move = checkNegative = segAttached->Contains( labelPos );
3197 }
3198
3199 ++trial;
3200 }
3201
3202 if( move )
3203 {
3204 label->SetPosition( VECTOR2I( labelPos ) );
3205
3206 if( wireDirection.x == 0 ) // Moved vertically
3207 {
3208 if( wireDirection.y < 0 )
3209 label->SetSpinStyle( SPIN_STYLE::UP );
3210 else
3212 }
3213 else if( wireDirection.y == 0 ) // Moved horizontally
3214 {
3215 if( wireDirection.x < 0 )
3217 else
3219 }
3220 }
3221 }
3222 }
3223
3224 m_segments.clear();
3225 m_wireIntersections.clear();
3226}
3227
3228
3229bool SCH_IO_EAGLE::CanReadSchematicFile( const wxString& aFileName ) const
3230{
3231 if( !SCH_IO::CanReadSchematicFile( aFileName ) )
3232 return false;
3233
3234 return checkHeader( aFileName );
3235}
3236
3237
3238bool SCH_IO_EAGLE::CanReadLibrary( const wxString& aFileName ) const
3239{
3240 if( !SCH_IO::CanReadLibrary( aFileName ) )
3241 return false;
3242
3243 return checkHeader( aFileName );
3244}
3245
3246
3247bool SCH_IO_EAGLE::checkHeader( const wxString& aFileName ) const
3248{
3249 wxFileInputStream input( aFileName );
3250
3251 if( !input.IsOk() )
3252 return false;
3253
3254 // Pre-v6 schematics are a binary stream identified by a two-byte magic.
3255 if( EAGLE_BIN_PARSER::IsBinaryEagle( input ) )
3256 return true;
3257
3258 wxTextInputStream text( input );
3259
3260 for( int i = 0; i < 8; i++ )
3261 {
3262 if( input.Eof() )
3263 return false;
3264
3265 if( text.ReadLine().Contains( wxS( "<eagle" ) ) )
3266 return true;
3267 }
3268
3269 return false;
3270}
3271
3272
3273void SCH_IO_EAGLE::moveLabels( SCH_LINE* aWire, const VECTOR2I& aNewEndPoint )
3274{
3275 wxCHECK( aWire, /* void */ );
3276
3277 SCH_SCREEN* screen = getCurrentScreen();
3278
3279 wxCHECK( screen, /* void */ );
3280
3281 for( SCH_ITEM* item : screen->Items().Overlapping( aWire->GetBoundingBox() ) )
3282 {
3283 if( !item->IsType( { SCH_LABEL_LOCATE_ANY_T } ) )
3284 continue;
3285
3286 if( TestSegmentHit( item->GetPosition(), aWire->GetStartPoint(), aWire->GetEndPoint(), 0 ) )
3287 item->SetPosition( aNewEndPoint );
3288 }
3289}
3290
3291
3293{
3294 // Add bus entry symbols
3295 // TODO: Cleanup this function and break into pieces
3296
3297 // for each wire segment, compare each end with all busses.
3298 // If the wire end is found to end on a bus segment, place a bus entry symbol.
3299
3300 std::vector<SCH_LINE*> buses;
3301 std::vector<SCH_LINE*> wires;
3302
3303 SCH_SCREEN* screen = getCurrentScreen();
3304
3305 wxCHECK( screen, /* void */ );
3306
3307 for( SCH_ITEM* ii : screen->Items().OfType( SCH_LINE_T ) )
3308 {
3309 SCH_LINE* line = static_cast<SCH_LINE*>( ii );
3310
3311 if( line->IsBus() )
3312 buses.push_back( line );
3313 else if( line->IsWire() )
3314 wires.push_back( line );
3315 }
3316
3317 for( SCH_LINE* wire : wires )
3318 {
3319 VECTOR2I wireStart = wire->GetStartPoint();
3320 VECTOR2I wireEnd = wire->GetEndPoint();
3321
3322 for( SCH_LINE* bus : buses )
3323 {
3324 VECTOR2I busStart = bus->GetStartPoint();
3325 VECTOR2I busEnd = bus->GetEndPoint();
3326
3327 auto entrySize =
3328 []( int signX, int signY ) -> VECTOR2I
3329 {
3330 return VECTOR2I( schIUScale.MilsToIU( DEFAULT_SCH_ENTRY_SIZE ) * signX,
3331 schIUScale.MilsToIU( DEFAULT_SCH_ENTRY_SIZE ) * signY );
3332 };
3333
3334 auto testBusHit =
3335 [&]( const VECTOR2I& aPt ) -> bool
3336 {
3337 return TestSegmentHit( aPt, busStart, busEnd, 0 );
3338 };
3339
3340 if( wireStart.y == wireEnd.y && busStart.x == busEnd.x )
3341 {
3342 // Horizontal wire and vertical bus
3343
3344 if( testBusHit( wireStart ) )
3345 {
3346 // Wire start is on the vertical bus
3347
3348 if( wireEnd.x < busStart.x )
3349 {
3350 /* the end of the wire is to the left of the bus
3351 * ⎥⎢
3352 * ——————⎥⎢
3353 * ⎥⎢
3354 */
3355 VECTOR2I p = wireStart + entrySize( -1, 0 );
3356
3357 if( testBusHit( wireStart + entrySize( 0, -1 ) ) )
3358 {
3359 /* there is room above the wire for the bus entry
3360 * ⎥⎢
3361 * _____/⎥⎢
3362 * ⎥⎢
3363 */
3364 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3365 busEntry->SetFlags( IS_NEW );
3366 screen->Append( busEntry );
3367 moveLabels( wire, p );
3368 wire->SetStartPoint( p );
3369 }
3370 else if( testBusHit( wireStart + entrySize( 0, 1 ) ) )
3371 {
3372 /* there is room below the wire for the bus entry
3373 * _____ ⎥⎢
3374 * \⎥⎢
3375 * ⎥⎢
3376 */
3377 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3378 busEntry->SetFlags( IS_NEW );
3379 screen->Append( busEntry );
3380 moveLabels( wire, p );
3381 wire->SetStartPoint( p );
3382 }
3383 else
3384 {
3385 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3386 screen->Append( new SCH_MARKER( std::move( ercItem ), wireStart ) );
3387 }
3388 }
3389 else
3390 {
3391 /* the wire end is to the right of the bus
3392 * ⎥⎢
3393 * ⎥⎢——————
3394 * ⎥⎢
3395 */
3396 VECTOR2I p = wireStart + entrySize( 1, 0 );
3397
3398 if( testBusHit( wireStart + entrySize( 0, -1 ) ) )
3399 {
3400 /* There is room above the wire for the bus entry
3401 * ⎥⎢
3402 * ⎥⎢\_____
3403 * ⎥⎢
3404 */
3405 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p , 4 );
3406 busEntry->SetFlags( IS_NEW );
3407 screen->Append( busEntry );
3408 moveLabels( wire, p );
3409 wire->SetStartPoint( p );
3410 }
3411 else if( testBusHit( wireStart + entrySize( 0, 1 ) ) )
3412 {
3413 /* There is room below the wire for the bus entry
3414 * ⎥⎢ _____
3415 * ⎥⎢/
3416 * ⎥⎢
3417 */
3418 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3419 busEntry->SetFlags( IS_NEW );
3420 screen->Append( busEntry );
3421 moveLabels( wire, p );
3422 wire->SetStartPoint( p );
3423 }
3424 else
3425 {
3426 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3427 screen->Append( new SCH_MARKER( std::move( ercItem ), wireStart ) );
3428 }
3429 }
3430
3431 break;
3432 }
3433 else if( testBusHit( wireEnd ) )
3434 {
3435 // Wire end is on the vertical bus
3436
3437 if( wireStart.x < busStart.x )
3438 {
3439 /* start of the wire is to the left of the bus
3440 * ⎥⎢
3441 * ——————⎥⎢
3442 * ⎥⎢
3443 */
3444 VECTOR2I p = wireEnd + entrySize( -1, 0 );
3445
3446 if( testBusHit( wireEnd + entrySize( 0, -1 ) ) )
3447 {
3448 /* there is room above the wire for the bus entry
3449 * ⎥⎢
3450 * _____/⎥⎢
3451 * ⎥⎢
3452 */
3453 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3454 busEntry->SetFlags( IS_NEW );
3455 screen->Append( busEntry );
3456 moveLabels( wire, p );
3457 wire->SetEndPoint( p );
3458 }
3459 else if( testBusHit( wireEnd + entrySize( 0, -1 ) ) )
3460 {
3461 /* there is room below the wire for the bus entry
3462 * _____ ⎥⎢
3463 * \⎥⎢
3464 * ⎥⎢
3465 */
3466 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3467 busEntry->SetFlags( IS_NEW );
3468 screen->Append( busEntry );
3469 moveLabels( wire, wireEnd + entrySize( -1, 0 ) );
3470 wire->SetEndPoint( wireEnd + entrySize( -1, 0 ) );
3471 }
3472 else
3473 {
3474 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3475 screen->Append( new SCH_MARKER( std::move( ercItem ), wireEnd ) );
3476 }
3477 }
3478 else
3479 {
3480 /* the start of the wire is to the right of the bus
3481 * ⎥⎢
3482 * ⎥⎢——————
3483 * ⎥⎢
3484 */
3485 VECTOR2I p = wireEnd + entrySize( 1, 0 );
3486
3487 if( testBusHit( wireEnd + entrySize( 0, -1 ) ) )
3488 {
3489 /* There is room above the wire for the bus entry
3490 * ⎥⎢
3491 * ⎥⎢\_____
3492 * ⎥⎢
3493 */
3494 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 4 );
3495 busEntry->SetFlags( IS_NEW );
3496 screen->Append( busEntry );
3497 moveLabels( wire, p );
3498 wire->SetEndPoint( p );
3499 }
3500 else if( testBusHit( wireEnd + entrySize( 0, 1 ) ) )
3501 {
3502 /* There is room below the wire for the bus entry
3503 * ⎥⎢ _____
3504 * ⎥⎢/
3505 * ⎥⎢
3506 */
3507 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3508 busEntry->SetFlags( IS_NEW );
3509 screen->Append( busEntry );
3510 moveLabels( wire, p );
3511 wire->SetEndPoint( p );
3512 }
3513 else
3514 {
3515 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3516 screen->Append( new SCH_MARKER( std::move( ercItem ), wireEnd ) );
3517 }
3518 }
3519
3520 break;
3521 }
3522 }
3523 else if( wireStart.x == wireEnd.x && busStart.y == busEnd.y )
3524 {
3525 // Vertical wire and horizontal bus
3526
3527 if( testBusHit( wireStart ) )
3528 {
3529 // Wire start is on the bus
3530
3531 if( wireEnd.y < busStart.y )
3532 {
3533 /* the end of the wire is above the bus
3534 * |
3535 * |
3536 * |
3537 * =======
3538 */
3539 VECTOR2I p = wireStart + entrySize( 0, -1 );
3540
3541 if( testBusHit( wireStart + entrySize( -1, 0 ) ) )
3542 {
3543 /* there is room to the left of the wire for the bus entry
3544 * |
3545 * |
3546 * /
3547 * =======
3548 */
3549 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3550 busEntry->SetFlags( IS_NEW );
3551 screen->Append( busEntry );
3552 moveLabels( wire, p );
3553 wire->SetStartPoint( p );
3554 }
3555 else if( testBusHit( wireStart + entrySize( 1, 0 ) ) )
3556 {
3557 /* there is room to the right of the wire for the bus entry
3558 * |
3559 * |
3560 * \
3561 * =======
3562 */
3563 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3564 busEntry->SetFlags( IS_NEW );
3565 screen->Append( busEntry );
3566 moveLabels( wire, p );
3567 wire->SetStartPoint( p );
3568 }
3569 else
3570 {
3571 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3572 screen->Append( new SCH_MARKER( std::move( ercItem ), wireStart ) );
3573 }
3574 }
3575 else
3576 {
3577 /* wire end is below the bus
3578 * =======
3579 * |
3580 * |
3581 * |
3582 */
3583 VECTOR2I p = wireStart + entrySize( 0, 1 );
3584
3585 if( testBusHit( wireStart + entrySize( -1, 0 ) ) )
3586 {
3587 /* there is room to the left of the wire for the bus entry
3588 * =======
3589 * \
3590 * |
3591 * |
3592 */
3593 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 4 );
3594 busEntry->SetFlags( IS_NEW );
3595 screen->Append( busEntry );
3596 moveLabels( wire, p );
3597 wire->SetStartPoint( p );
3598 }
3599 else if( testBusHit( wireStart + entrySize( 1, 0 ) ) )
3600 {
3601 /* there is room to the right of the wire for the bus entry
3602 * =======
3603 * /
3604 * |
3605 * |
3606 */
3607 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3608 busEntry->SetFlags( IS_NEW );
3609 screen->Append( busEntry );
3610 moveLabels( wire, p );
3611 wire->SetStartPoint( p );
3612 }
3613 else
3614 {
3615 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3616 screen->Append( new SCH_MARKER( std::move( ercItem ), wireStart ) );
3617 }
3618 }
3619
3620 break;
3621 }
3622 else if( testBusHit( wireEnd ) )
3623 {
3624 // Wire end is on the bus
3625
3626 if( wireStart.y < busStart.y )
3627 {
3628 /* the start of the wire is above the bus
3629 * |
3630 * |
3631 * |
3632 * =======
3633 */
3634 VECTOR2I p = wireEnd + entrySize( 0, -1 );
3635
3636 if( testBusHit( wireEnd + entrySize( -1, 0 ) ) )
3637 {
3638 /* there is room to the left of the wire for the bus entry
3639 * |
3640 * |
3641 * /
3642 * =======
3643 */
3644 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3645 busEntry->SetFlags( IS_NEW );
3646 screen->Append( busEntry );
3647 moveLabels( wire, p );
3648 wire->SetEndPoint( p );
3649 }
3650 else if( testBusHit( wireEnd + entrySize( 1, 0 ) ) )
3651 {
3652 /* there is room to the right of the wire for the bus entry
3653 * |
3654 * |
3655 * \
3656 * =======
3657 */
3658 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3659 busEntry->SetFlags( IS_NEW );
3660 screen->Append( busEntry );
3661 moveLabels( wire, p );
3662 wire->SetEndPoint( p );
3663 }
3664 else
3665 {
3666 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3667 screen->Append( new SCH_MARKER( std::move( ercItem ), wireEnd ) );
3668 }
3669 }
3670 else
3671 {
3672 /* wire start is below the bus
3673 * =======
3674 * |
3675 * |
3676 * |
3677 */
3678 VECTOR2I p = wireEnd + entrySize( 0, 1 );
3679
3680 if( testBusHit( wireEnd + entrySize( -1, 0 ) ) )
3681 {
3682 /* there is room to the left of the wire for the bus entry
3683 * =======
3684 * \
3685 * |
3686 * |
3687 */
3688 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 4 );
3689 busEntry->SetFlags( IS_NEW );
3690 screen->Append( busEntry );
3691 moveLabels( wire, p );
3692 wire->SetEndPoint( p );
3693 }
3694 else if( testBusHit( wireEnd + entrySize( 1, 0 ) ) )
3695 {
3696 /* there is room to the right of the wire for the bus entry
3697 * =======
3698 * /
3699 * |
3700 * |
3701 */
3702 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3703 busEntry->SetFlags( IS_NEW );
3704 screen->Append( busEntry );
3705 moveLabels( wire, p );
3706 wire->SetEndPoint( p );
3707 }
3708 else
3709 {
3710 std::shared_ptr<ERC_ITEM> ercItem = ERC_ITEM::Create( ERCE_BUS_ENTRY_NEEDED );
3711 screen->Append( new SCH_MARKER( std::move( ercItem ), wireEnd ) );
3712 }
3713 }
3714
3715 break;
3716 }
3717 }
3718 else
3719 {
3720 // Wire isn't horizontal or vertical
3721
3722 if( testBusHit( wireStart ) )
3723 {
3724 VECTOR2I wirevector = wireStart - wireEnd;
3725
3726 if( wirevector.x > 0 )
3727 {
3728 if( wirevector.y > 0 )
3729 {
3730 VECTOR2I p = wireStart + entrySize( -1, -1 );
3731 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3732 busEntry->SetFlags( IS_NEW );
3733 screen->Append( busEntry );
3734
3735 moveLabels( wire, p );
3736 wire->SetStartPoint( p );
3737 }
3738 else
3739 {
3740 VECTOR2I p = wireStart + entrySize( -1, 1 );
3741 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3742 busEntry->SetFlags( IS_NEW );
3743 screen->Append( busEntry );
3744
3745 moveLabels( wire, p );
3746 wire->SetStartPoint( p );
3747 }
3748 }
3749 else
3750 {
3751 if( wirevector.y > 0 )
3752 {
3753 VECTOR2I p = wireStart + entrySize( 1, -1 );
3754 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3755 busEntry->SetFlags( IS_NEW );
3756 screen->Append( busEntry );
3757
3758 moveLabels( wire, p );
3759 wire->SetStartPoint( p );
3760 }
3761 else
3762 {
3763 VECTOR2I p = wireStart + entrySize( 1, 1 );
3764 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 4 );
3765 busEntry->SetFlags( IS_NEW );
3766 screen->Append( busEntry );
3767
3768 moveLabels( wire, p );
3769 wire->SetStartPoint( p );
3770 }
3771 }
3772
3773 break;
3774 }
3775 else if( testBusHit( wireEnd ) )
3776 {
3777 VECTOR2I wirevector = wireStart - wireEnd;
3778
3779 if( wirevector.x > 0 )
3780 {
3781 if( wirevector.y > 0 )
3782 {
3783 VECTOR2I p = wireEnd + entrySize( 1, 1 );
3784 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 4 );
3785 busEntry->SetFlags( IS_NEW );
3786 screen->Append( busEntry );
3787
3788 moveLabels( wire, p );
3789 wire->SetEndPoint( p );
3790 }
3791 else
3792 {
3793 VECTOR2I p = wireEnd + entrySize( 1, -1 );
3794 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 3 );
3795 busEntry->SetFlags( IS_NEW );
3796 screen->Append( busEntry );
3797
3798 moveLabels( wire, p );
3799 wire->SetEndPoint( p );
3800 }
3801 }
3802 else
3803 {
3804 if( wirevector.y > 0 )
3805 {
3806 VECTOR2I p = wireEnd + entrySize( -1, 1 );
3807 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 1 );
3808 busEntry->SetFlags( IS_NEW );
3809 screen->Append( busEntry );
3810
3811 moveLabels( wire, p );
3812 wire->SetEndPoint( p );
3813 }
3814 else
3815 {
3816 VECTOR2I p = wireEnd + entrySize( -1, -1 );
3817 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( p, 2 );
3818 busEntry->SetFlags( IS_NEW );
3819 screen->Append( busEntry );
3820
3821 moveLabels( wire, p );
3822 wire->SetEndPoint( p );
3823 }
3824 }
3825
3826 break;
3827 }
3828 }
3829 }
3830 }
3831}
3832
3833
3835{
3836 wxCHECK( aLabel, nullptr );
3837
3838 VECTOR2I labelPos( aLabel->GetPosition() );
3839
3840 for( const SEG& seg : segs )
3841 {
3842 if( seg.Contains( labelPos ) )
3843 return &seg;
3844 }
3845
3846 return nullptr;
3847}
3848
3849
3850// TODO could be used to place junctions, instead of IsJunctionNeeded()
3851// (see SCH_EDIT_FRAME::importFile())
3852bool SCH_IO_EAGLE::checkConnections( const SCH_SYMBOL* aSymbol, const SCH_PIN* aPin ) const
3853{
3854 wxCHECK( aSymbol && aPin, false );
3855
3856 VECTOR2I pinPosition = aSymbol->GetPinPhysicalPosition( aPin );
3857 auto pointIt = m_connPoints.find( pinPosition );
3858
3859 if( pointIt == m_connPoints.end() )
3860 return false;
3861
3862 const std::set<const EDA_ITEM*>& items = pointIt->second;
3863
3864 wxCHECK( items.find( aPin ) != items.end(), false );
3865
3866 return items.size() > 1;
3867}
3868
3869
3870void SCH_IO_EAGLE::addImplicitConnections( SCH_SYMBOL* aSymbol, SCH_SCREEN* aScreen, bool aUpdateSet )
3871{
3872 wxCHECK( aSymbol && aScreen && aSymbol->GetLibSymbolRef(), /*void*/ );
3873
3874 // Normally power parts also have power input pins,
3875 // but they already force net names on the attached wires
3876 if( aSymbol->GetLibSymbolRef()->IsGlobalPower() )
3877 return;
3878
3879 int unit = aSymbol->GetUnit();
3880 const wxString reference = aSymbol->GetField( FIELD_T::REFERENCE )->GetText();
3881 std::vector<SCH_PIN*> pins = aSymbol->GetLibSymbolRef()->GetGraphicalPins( 0, 0 );
3882 std::set<int> missingUnits;
3883
3884 // Search all units for pins creating implicit connections
3885 for( const SCH_PIN* pin : pins )
3886 {
3887 if( pin->GetType() == ELECTRICAL_PINTYPE::PT_POWER_IN )
3888 {
3889 bool pinInUnit = !unit || pin->GetUnit() == unit; // pin belongs to the tested unit
3890
3891 // Create a global net label only if there are no other wires/pins attached
3892 if( pinInUnit )
3893 {
3894 if( !checkConnections( aSymbol, pin ) )
3895 {
3896 // Create a net label to force the net name on the pin
3897 SCH_GLOBALLABEL* netLabel = new SCH_GLOBALLABEL;
3898 netLabel->SetPosition( aSymbol->GetPinPhysicalPosition( pin ) );
3899 netLabel->SetText( extractNetName( pin->GetName() ) );
3900 netLabel->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 40 ), schIUScale.MilsToIU( 40 ) ) );
3901
3902 switch( pin->GetOrientation() )
3903 {
3904 default:
3908 case PIN_ORIENTATION::PIN_DOWN: netLabel->SetSpinStyle( SPIN_STYLE::UP ); break;
3909 }
3910
3911 aScreen->Append( netLabel );
3912 }
3913 }
3914 else if( aUpdateSet )
3915 {
3916 // Found a pin creating implicit connection information in another unit.
3917 // Such units will be instantiated if they do not appear in another sheet and
3918 // processed later.
3919 wxASSERT( pin->GetUnit() );
3920 missingUnits.insert( pin->GetUnit() );
3921 }
3922 }
3923 }
3924
3925 if( aUpdateSet && aSymbol->GetLibSymbolRef()->GetUnitCount() > 1 )
3926 {
3927 auto cmpIt = m_missingCmps.find( reference );
3928
3929 // The first unit found has always already been processed.
3930 if( cmpIt == m_missingCmps.end() )
3931 {
3932 EAGLE_MISSING_CMP& entry = m_missingCmps[reference];
3933 entry.cmp = aSymbol;
3934 entry.screen = aScreen;
3935 entry.units.emplace( unit, false );
3936 }
3937 else
3938 {
3939 // Set the flag indicating this unit has been processed.
3940 cmpIt->second.units[unit] = false;
3941 }
3942
3943 if( !missingUnits.empty() ) // Save the units that need later processing
3944 {
3945 EAGLE_MISSING_CMP& entry = m_missingCmps[reference];
3946 entry.cmp = aSymbol;
3947 entry.screen = aScreen;
3948
3949 // Add units that haven't already been processed.
3950 for( int i : missingUnits )
3951 {
3952 if( entry.units.find( i ) != entry.units.end() )
3953 entry.units.emplace( i, true );
3954 }
3955 }
3956 }
3957}
3958
3959
3960wxString SCH_IO_EAGLE::translateEagleBusName( const wxString& aEagleName ) const
3961{
3962 if( NET_SETTINGS::ParseBusVector( aEagleName, nullptr, nullptr ) )
3963 return aEagleName;
3964
3965 wxString ret = wxT( "{" );
3966
3967 wxStringTokenizer tokenizer( aEagleName, "," );
3968
3969 while( tokenizer.HasMoreTokens() )
3970 {
3971 wxString member = tokenizer.GetNextToken();
3972
3973 // In Eagle, overbar text is automatically stopped at the end of the net name, even when
3974 // that net name is part of a bus definition. In KiCad, we don't (currently) do that, so
3975 // if there is an odd number of overbar markers in this net name, we need to append one
3976 // to close it out before appending the space.
3977
3978 if( member.Freq( '!' ) % 2 > 0 )
3979 member << wxT( "!" );
3980
3981 ret << member << wxS( " " );
3982 }
3983
3984 ret.Trim( true );
3985 ret << wxT( "}" );
3986
3987 return ret;
3988}
3989
3990
3991const ESYMBOL* SCH_IO_EAGLE::getEagleSymbol( const std::unique_ptr<EINSTANCE>& aInstance )
3992{
3993 wxCHECK( m_eagleDoc && m_eagleDoc->drawing && m_eagleDoc->drawing->schematic && aInstance, nullptr );
3994
3995 std::unique_ptr<EPART>& epart = m_eagleDoc->drawing->schematic->parts[aInstance->part];
3996
3997 if( !epart || epart->deviceset.IsEmpty() )
3998 return nullptr;
3999
4000 std::unique_ptr<ELIBRARY>& elibrary = m_eagleDoc->drawing->schematic->libraries[epart->library];
4001
4002 if( !elibrary )
4003 return nullptr;
4004
4005 std::unique_ptr<EDEVICE_SET>& edeviceset = elibrary->devicesets[epart->deviceset];
4006
4007 if( !edeviceset )
4008 return nullptr;
4009
4010 std::unique_ptr<EGATE>& egate = edeviceset->gates[aInstance->gate];
4011
4012 if( !egate )
4013 return nullptr;
4014
4015 std::unique_ptr<ESYMBOL>& esymbol = elibrary->symbols[egate->symbol];
4016
4017 if( esymbol )
4018 return esymbol.get();
4019
4020 return nullptr;
4021}
4022
4023
4024void SCH_IO_EAGLE::getEagleSymbolFieldAttributes( const std::unique_ptr<EINSTANCE>& aInstance,
4025 const wxString& aEagleFieldName,
4026 SCH_FIELD* aField )
4027{
4028 wxCHECK( aField && !aEagleFieldName.IsEmpty(), /* void */ );
4029
4030 const ESYMBOL* esymbol = getEagleSymbol( aInstance );
4031
4032 if( esymbol )
4033 {
4034 for( const std::unique_ptr<ETEXT>& text : esymbol->texts )
4035 {
4036 if( text->text == aEagleFieldName )
4037 {
4038 aField->SetVisible( true );
4039 VECTOR2I pos( text->x.ToSchUnits() + aInstance->x.ToSchUnits(),
4040 -text->y.ToSchUnits() - aInstance->y.ToSchUnits() );
4041
4042 bool mirror = text->rot ? text->rot->mirror : false;
4043
4044 if( aInstance->rot.has_value() && aInstance->rot.value().mirror )
4045 mirror = !mirror;
4046
4047 if( mirror )
4048 pos.y = -aInstance->y.ToSchUnits() + text->y.ToSchUnits();
4049
4050 aField->SetPosition( pos );
4051 }
4052 }
4053 }
4054}
4055
4056
4058{
4059 VECTOR2I retv;
4060
4061 std::vector<SCH_FIELD*> fields;
4062 aPart->GetFields( fields );
4063
4064 if( fields.size() )
4065 {
4066 retv = fields[0]->GetPosition();
4067
4068 for( size_t i = 1; i < fields.size(); i++ )
4069 {
4070 if( fields[i]->GetPosition().x > retv.x )
4071 retv.x = fields[i]->GetPosition().x;
4072
4073 if( fields[i]->GetPosition().y > retv.y )
4074 retv.y = fields[i]->GetPosition().y;
4075 }
4076 }
4077
4078 return retv;
4079}
const char * name
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
constexpr size_type GetWidth() const
Definition box2.h:217
constexpr Vec Centre() const
Definition box2.h:100
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 size_type GetHeight() const
Definition box2.h:218
constexpr const SizeVec & GetSize() const
Definition box2.h:209
Read-only parser for the pre-v6 binary Eagle .brd format.
std::unique_ptr< wxXmlDocument > Parse(const std::vector< uint8_t > &aBytes)
Parse a binary Eagle board into an XML DOM compatible with the XML walker.
static bool IsBinaryEagle(wxInputStream &aStream)
Probe the first two bytes for the binary magic without changing the stream position.
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
virtual void SetEnd(const VECTOR2I &aEnd)
Definition eda_shape.h:338
virtual void SetCenter(const VECTOR2I &aCenter)
SHAPE_POLY_SET & GetPolyShape()
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
void SetArcAngleAndEnd(const EDA_ANGLE &aAngle, bool aCheckNegativeAngle=false)
Set the end point from the angle center and start.
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
virtual int GetTextHeight() const
Definition eda_text.h:307
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
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
void SetBold(bool aBold)
Set the text to be bold - this will also update the font if needed.
Definition eda_text.cpp:311
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition eda_text.cpp:269
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_rtree::Iterator begin() const
Return a read/write iterator that points to the first.
Definition sch_rtree.h:288
ee_rtree::Iterator end() const
Return a read/write iterator that points to one past the last element in the EE_RTREE.
Definition sch_rtree.h:296
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
static std::shared_ptr< ERC_ITEM > Create(int aErrorCode)
Constructs an ERC_ITEM for the given error code.
Definition erc_item.cpp:321
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:385
virtual void Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) const
Definition io_base.cpp:124
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
Definition kiid.h:46
void ReloadLibraryEntry(const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH)
Synchronously recreates the plugin for and reloads the given library.
std::optional< LIBRARY_TABLE * > ProjectTable() const
Retrieves the project library table for this adapter type, or nullopt if one doesn't exist.
void SetNickname(const wxString &aNickname)
void SetType(const wxString &aType)
void SetURI(const wxString &aUri)
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
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 GetFields(std::vector< SCH_FIELD * > &aList, bool aVisibleOnly=false) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
bool IsGlobalPower() const override
int GetUnitCount() const override
std::unique_ptr< LIB_SYMBOL > Flatten() const
Return a flattened symbol inheritance to the caller.
std::vector< SCH_PIN * > GetGraphicalPins(int aUnit=0, int aBodyStyle=0) const override
Graphical pins: Return schematic pin objects as drawn (unexpanded), filtered by unit/body.
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:351
static bool ParseBusVector(const wxString &aBus, wxString *aName, std::vector< wxString > *aMemberList)
Parse a bus vector (e.g.
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
void SetHeightMils(double aHeightInMils)
const VECTOR2D GetSizeIU(double aIUScale) const
Gets the page size in internal units.
Definition page_info.h:172
void SetWidthMils(double aWidthInMils)
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Holds all the data relating to one schematic.
Definition schematic.h:155
PROJECT & Project() const
Return a reference to the project this schematic is part of.
Definition schematic.h:177
bool IsValid() const
A simple test if the schematic is loaded, not a complete one.
Definition schematic.h:384
SCH_SHEET & Root() const
Definition schematic.h:282
Class for a wire to bus entry.
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
void SetCanAutoplace(bool aCanPlace)
Definition sch_field.h:237
void ImportValues(const SCH_FIELD &aSource)
Copy parameters from a SCH_FIELD source.
bool IsEmpty()
Return true if both the name and value of the field are empty.
Definition sch_field.h:178
void SetPosition(const VECTOR2I &aPosition) override
void SetName(const wxString &aName)
void SetText(const wxString &aText) override
void SetSpinStyle(SPIN_STYLE aSpinStyle) override
std::unique_ptr< EAGLE_DOC > m_eagleDoc
The fully parsed Eagle schematic file.
SCH_ITEM * loadWire(const std::unique_ptr< EWIRE > &aWire, SEG &endpoints)
void loadTextAttributes(EDA_TEXT *aText, const std::unique_ptr< ETEXT > &aAttributes) const
void loadModuleInstance(const std::unique_ptr< EMODULEINST > &aModuleInstance)
void ensureLoadedLibrary(const wxString &aLibraryPath)
void loadSchematic(const ESCHEMATIC &aSchematic)
SCH_TEXT * loadPlainText(const std::unique_ptr< ETEXT > &aSchText)
void loadSheet(const std::unique_ptr< ESHEET > &aSheet)
void loadLayerDefs(const std::vector< std::unique_ptr< ELAYER > > &aLayers)
VECTOR2I getLastSymbolFieldPosition(const LIB_SYMBOL *aPart)
const ESYMBOL * getEagleSymbol(const std::unique_ptr< EINSTANCE > &aInstance)
EAGLE_LIBRARY * loadLibrary(const ELIBRARY *aLibrary, EAGLE_LIBRARY *aEagleLib)
wxXmlDocument loadXmlDocument(const wxString &aFileName)
wxString translateEagleBusName(const wxString &aEagleName) const
Translate an Eagle-style bus name into one that is KiCad-compatible.
std::map< wxString, wxString > m_powerPorts
map from symbol reference to global label equivalent
SCH_SHEET_PATH m_sheetPath
The current sheet path of the schematic being loaded.
wxString m_libName
Library name to save symbols.
SCH_TEXT * loadSymbolText(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< ETEXT > &aText, int aGateNumber)
std::pair< VECTOR2I, const SEG * > findNearestLinePoint(const VECTOR2I &aPoint, const std::vector< SEG > &aLines) const
std::map< wxString, long long > m_timestamps
void adjustNetLabels()
Move net labels that are detached from any wire to the nearest wire.
SCH_LABEL_BASE * loadLabel(const std::unique_ptr< ELABEL > &aLabel, const wxString &aNetName, bool aIsBus=false)
void loadInstance(const std::unique_ptr< EINSTANCE > &aInstance, const std::map< wxString, std::unique_ptr< EPART > > &aParts)
LIB_SYMBOL * LoadSymbol(const wxString &aLibraryPath, const wxString &aAliasName, const std::map< std::string, UTF8 > *aProperties) override
Load a LIB_SYMBOL object having aPartName from the aLibraryPath containing a library format that this...
std::unordered_map< wxString, bool > m_userValue
deviceset/@uservalue for device.
int GetModifyHash() const override
Return the modification hash from the library cache.
std::map< wxString, int > m_netCounts
wxFileName m_filename
std::map< wxString, EAGLE_LIBRARY > m_eagleLibs
bool loadSymbol(const std::unique_ptr< ESYMBOL > &aEsymbol, std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< EDEVICE > &aDevice, int aGateNumber, const wxString &aGateName)
SCH_SHEET * getCurrentSheet()
void loadDrawing(const std::unique_ptr< EDRAWING > &aDrawing)
void EnumerateSymbolLib(wxArrayString &aSymbolNameList, const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties) override
Populate a list of LIB_SYMBOL alias names contained within the library aLibraryPath.
SCH_SHAPE * loadSymbolPolyLine(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< EPOLYGON > &aPolygon, int aGateNumber)
std::vector< VECTOR2I > m_wireIntersections
Wire intersection points, used for quick checks whether placing a net label in a particular place wou...
std::map< VECTOR2I, std::set< const EDA_ITEM * > > m_connPoints
Positions of pins and wire endings mapped to its parent.
bool checkConnections(const SCH_SYMBOL *aSymbol, const SCH_PIN *aPin) const
Checks if there are other wires or pins at the position of the tested pin.
IO_RELEASER< SCH_IO > m_pi
PI to create KiCad symbol library.
SCH_SHAPE * loadRectangle(const std::unique_ptr< ERECT > &aRect)
void addBusEntries()
This function finds best way to place a bus entry symbol for when an Eagle wire segment ends on an Ea...
bool CanReadSchematicFile(const wxString &aFileName) const override
Checks if this SCH_IO can read the specified schematic file.
void addImplicitConnections(SCH_SYMBOL *aSymbol, SCH_SCREEN *aScreen, bool aUpdateSet)
Create net labels to emulate implicit connections in Eagle.
std::map< int, SCH_LAYER_ID > m_layerMap
SCH_LAYER_ID kiCadLayer(int aEagleLayer)
Return the matching layer or return LAYER_NOTES.
wxString getLibName()
SHEET_WIRING collectSheetWiring(const std::unique_ptr< ESHEET > &aSheet, SCH_SCREEN *aScreen)
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,...
SCH_PIN * loadPin(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< EPIN > &aPin, int aGateNumber)
SCH_SHAPE * loadCircle(const std::unique_ptr< ECIRCLE > &aCircle)
wxFileName getLibFileName()
SCH_SHAPE * loadSymbolRectangle(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< ERECT > &aRectangle, int aGateNumber)
SCH_JUNCTION * loadJunction(const std::unique_ptr< EJUNCTION > &aJunction)
wxString m_version
Eagle file version.
void getEagleSymbolFieldAttributes(const std::unique_ptr< EINSTANCE > &aInstance, const wxString &aEagleFieldName, SCH_FIELD *aField)
void loadSegments(const std::vector< std::unique_ptr< ESEGMENT > > &aSegments, const wxString &aNetName, const wxString &aNetClass, SHEET_WIRING &aWiring, bool aIsBus=false)
std::map< wxString, const EPART * > m_partlist
void moveLabels(SCH_LINE *aWire, const VECTOR2I &aNewEndPoint)
Move any labels on the wire to the new end point of the wire.
bool checkHeader(const wxString &aFileName) const
SCHEMATIC * m_schematic
Passed to Load(), the schematic object being loaded.
void countNets(const ESCHEMATIC &aSchematic)
SCH_SHEET * m_rootSheet
The root sheet of the schematic being loaded.
SCH_SHAPE * loadPolyLine(const std::unique_ptr< EPOLYGON > &aPolygon)
SCH_SHAPE * loadSymbolCircle(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< ECIRCLE > &aCircle, int aGateNumber)
SCH_SCREEN * getCurrentScreen()
bool CanReadLibrary(const wxString &aFileName) const override
Checks if this IO object can read the specified library file/directory.
std::map< wxString, EAGLE_MISSING_CMP > m_missingCmps
Map references to missing symbol units data.
void loadFrame(const std::unique_ptr< EFRAME > &aFrame, std::vector< SCH_ITEM * > &aItems, SCH_LAYER_ID aLayer=LAYER_NOTES)
const int ARC_ACCURACY
std::vector< SEG_DESC > m_segments
Segments representing wires for intersection checking.
std::vector< EMODULE * > m_modules
The current module stack being loaded.
std::vector< EMODULEINST * > m_moduleInstances
SCH_ITEM * loadSymbolWire(std::unique_ptr< LIB_SYMBOL > &aSymbol, const std::unique_ptr< EWIRE > &aWire, int aGateNumber)
long long getLibraryTimestamp(const wxString &aLibraryPath) const
static const char * PropBuffering
The property used internally by the plugin to enable cache buffering which prevents the library file ...
void AddContact(const VECTOR2I &aPos, int aNet)
Register a pin or junction.
RESULT Route(const SEG &aWire, int aNet)
Detour a wire around foreign items lying on it and register the result as the wire's geometry.
void AddWire(const SEG &aWire, int aNet)
Register a wire as an obstacle for the wires of other nets.
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
SCH_ITEM * Duplicate(bool addToParentGroup, SCH_COMMIT *aCommit=nullptr, bool aDoClone=false) const
Routine to create a new copy of given item.
Definition sch_item.cpp:191
int GetUnit() const
Definition sch_item.h:243
void SetLayer(SCH_LAYER_ID aLayer)
Definition sch_item.h:354
SCH_LAYER_ID GetLayer() const
Return the layer this item is on.
Definition sch_item.h:353
virtual void SetUnit(int aUnit)
Definition sch_item.h:242
void SetShape(LABEL_FLAG_SHAPE aShape)
Definition sch_label.h:179
void SetPosition(const VECTOR2I &aPosition) 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 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
VECTOR2I GetEndPoint() const
Definition sch_line.h:145
VECTOR2I GetStartPoint() const
Definition sch_line.h:136
bool IsBus() const
Return true if the line is a bus.
virtual void SetStroke(const STROKE_PARAMS &aStroke) override
Definition sch_line.h:199
void SetEndPoint(const VECTOR2I &aPosition)
Definition sch_line.h:146
void SetNumber(const wxString &aNumber)
Definition sch_pin.cpp:845
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()
const PAGE_INFO & GetPageSettings() const
Definition sch_screen.h:144
void Append(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
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
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
void Update(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Refresh a changed item in the tree and invalidate connectivity.
void SetPosition(const VECTOR2I &aPos) override
Definition sch_shape.h:89
void SetStroke(const STROKE_PARAMS &aStroke) override
VECTOR2I GetCenter() const
Definition sch_shape.h:96
void AddPoint(const VECTOR2I &aPosition)
VECTOR2I GetPosition() const override
Definition sch_shape.h:88
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
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 SetFileName(const wxString &aFilename)
Definition sch_sheet.h:434
bool LocatePathOfScreen(SCH_SCREEN *aScreen, SCH_SHEET_PATH *aList)
Search the existing hierarchy for an instance of screen loaded from aFileName.
void SetName(const wxString &aName)
Definition sch_sheet.h:185
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
void AutoplaceFields(SCH_SCREEN *aScreen, AUTOPLACE_ALGO aAlgo) override
Variant information for a schematic symbol.
Schematic symbol object.
Definition sch_symbol.h:76
const std::vector< SCH_SYMBOL_INSTANCE > & GetInstances() const
Definition sch_symbol.h:136
void AddHierarchicalReference(const KIID_PATH &aPath, const wxString &aRef, int aUnit)
Add a full hierarchical reference to this symbol.
std::vector< SCH_PIN * > GetLibPins() const
Populate a vector with all the pins from the library object that match the current unit and bodyStyle...
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
VECTOR2I GetPinPhysicalPosition(const SCH_PIN *Pin) const
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
VECTOR2I GetPosition() const override
Definition sch_text.h:143
void SetPosition(const VECTOR2I &aPosition) override
Definition sch_text.h:144
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I B
Definition seg.h:46
OPT_VECTOR2I Intersect(const SEG &aSeg, bool aIgnoreEndpoints=false, bool aLines=false) const
Compute intersection point of segment (this) with segment aSeg.
Definition seg.cpp:401
bool Contains(const SEG &aSeg) const
Definition seg.h:342
SHAPE_ARC & ConstructFromStartEndAngle(const VECTOR2I &aStart, const VECTOR2I &aEnd, const EDA_ANGLE &aAngle, double aWidth=0)
Construct this arc from the given start, end and angle.
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
Simple container to manage line stroke parameters.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
std::optional< LIB_STATUS > LoadOne(LIB_DATA *aLib) override
Loads or reloads the given library, if it exists.
wxString wx_str() const
Definition utf8.cpp:41
std::map< wxString, wxString > m_Fields
double Distance(const VECTOR2< extended_type > &aVector) const
Compute the distance between two vectors.
Definition vector2d.h:574
VECTOR2< T > Resize(T aNewLength) const
Return a vector of the same direction, but length specified in aNewLength.
Definition vector2d.h:406
#define DEFAULT_SCH_ENTRY_SIZE
The default bus and wire entry size in mils.
wxString escapeName(const wxString &aNetName)
Translates Eagle special characters to their counterparts in KiCad.
wxString interpretText(const wxString &aText)
Interprets special characters in Eagle text and converts them to KiCAD notation.
size_t GetNodeCount(const wxXmlNode *aNode)
Fetch the number of XML nodes within aNode.
VECTOR2I ConvertEagleTextSize(const std::optional< wxString > &font, const ECOORD &size)
Converts Eagle's text size to KiCad text size depending on the font used.
VECTOR2I ConvertArcCenter(const VECTOR2I &aStart, const VECTOR2I &aEnd, double aAngle)
Convert an Eagle curve end to a KiCad center for S_ARC.
wxString convertDescription(wxString aDescr)
Converts Eagle's HTML description into KiCad description format.
#define _(s)
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE ANGLE_VERTICAL
Definition eda_angle.h:469
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
#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
@ ERCE_BUS_ENTRY_NEEDED
Importer failed to auto-place a bus entry.
bool m_EagleImportFieldsCanAutoplace
Default CanAutoplace value for fields imported from EAGLE files.
#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)
SCH_LAYER_ID
Eeschema drawing layers.
Definition layer_ids.h:480
@ 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
STL namespace.
@ PT_INPUT
usual pin input: must be connected
Definition pin_type.h:33
@ PT_NC
not connected (must be left open)
Definition pin_type.h:46
@ 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_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_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
static wxString extractNetName(const wxString &aPinName)
Strip the Eagle "@<tag>" linking hint from a pin name (e.g. return 'GND' for 'GND@2')
static const std::map< wxString, ELECTRICAL_PINTYPE > pinDirectionsMap
Map of EAGLE pin type values to KiCad pin type values.
static bool isEagleAutoNetName(const wxString &aNetName)
True for the "N$<n>" names Eagle assigns to nets the user never named.
static SYMBOL_ORIENTATION_T kiCadComponentRotation(float eagleDegrees)
static void eagleToKicadAlignment(EDA_TEXT *aText, int aEagleAlignment, int aRelDegress, bool aMirror, bool aSpin, int aAbsDegress)
static BOX2I getSheetBbox(SCH_SHEET *aSheet)
Compute a bounding box for all items in a schematic sheet.
@ AUTOPLACE_AUTO
Definition sch_item.h:75
LABEL_FLAG_SHAPE
Label and flag shapes used with text objects.
Definition sch_label.h:97
@ L_BIDI
Definition sch_label.h:100
@ L_TRISTATE
Definition sch_label.h:101
@ L_UNSPECIFIED
Definition sch_label.h:102
@ L_OUTPUT
Definition sch_label.h:99
@ L_INPUT
Definition sch_label.h:98
LABEL_SHAPE
Specific enums for property manager (not used elsewhere)
Definition sch_label.h:115
@ LABEL_BIDI
Definition sch_label.h:118
@ LABEL_INPUT
Definition sch_label.h:116
@ LABEL_OUTPUT
Definition sch_label.h:117
@ LABEL_PASSIVE
Definition sch_label.h:120
@ LABEL_TRISTATE
Definition sch_label.h:119
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
SHEET_SIDE
Define the edge of the sheet that the sheet pin is positioned.
std::optional< VECTOR2I > OPT_VECTOR2I
Definition seg.h:35
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:...
wxString UnescapeHTML(const wxString &aString)
Return a new wxString unescaped from HTML format.
@ CTX_LIBID
@ CTX_NETNAME
std::map< wxString, std::unique_ptr< LIB_SYMBOL > > KiCadSymbols
std::unordered_map< wxString, wxString > package
wxString name
std::unordered_map< wxString, int > GateToUnitMap
Map Eagle gate unit number (which are strings) to KiCad library symbol unit number.
std::map< wxString, std::unique_ptr< EDEVICE_SET > > devicesets
wxString GetName() const
Fetch the fully unique library name.
std::map< wxString, std::unique_ptr< ESYMBOL > > symbols
std::optional< wxString > direction
std::map< wxString, std::unique_ptr< EMODULE > > modules
std::vector< std::unique_ptr< ESHEET > > sheets
std::map< wxString, std::unique_ptr< EPART > > parts
std::map< wxString, std::unique_ptr< ELIBRARY > > libraries
std::map< wxString, std::unique_ptr< EVARIANTDEF > > variantdefs
std::vector< std::unique_ptr< ETEXT > > texts
@ BOTTOM_CENTER
@ BOTTOM_RIGHT
@ CENTER_RIGHT
@ CENTER_LEFT
@ BOTTOM_LEFT
const SCH_SYMBOL * cmp
Link to the parent symbol.
SCH_SCREEN * screen
Screen where the parent symbol is located.
std::map< int, bool > units
Wires and labels of a single connection (segment in Eagle nomenclature)
std::vector< SEG > segs
std::vector< SCH_LABEL_BASE * > labels
const SEG * LabelAttached(const SCH_LABEL_BASE *aLabel) const
Test if a particular label is attached to any of the stored segments.
Wires and the pins and junctions around them on one sheet, for keeping wires off other nets' pins.
std::map< wxString, int > NetIds
SCH_IO_WIRE_DETOUR Detour
bool Failed
A foreign item lies on the wire and no safe detour was found, the wire is left as it was.
std::vector< SEG > Pieces
The wire itself when nothing lies on it, otherwise the pieces of the detoured wire in order.
A simple container for schematic symbol instance information.
Implement a simple wrapper around runtime_error to isolate the errors thrown by the Eagle XML parser.
SYMBOL_ORIENTATION_T
enum used in RotationMiroir()
Definition symbol.h:32
@ SYM_ORIENT_270
Definition symbol.h:39
@ SYM_ORIENT_180
Definition symbol.h:38
@ SYM_ORIENT_90
Definition symbol.h:37
@ SYM_ORIENT_0
Definition symbol.h:36
wxString GetDefaultFieldName(FIELD_T aFieldId, TRANSLATION aTranslation)
Return a default symbol field name for a mandatory field type.
@ USER
The field ID hasn't been set yet; field is invalid.
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
@ UNTRANSLATED
static std::vector< uint8_t > bytes(const std::string &aText)
const std::string table
KIBIS_PIN * pin
VECTOR2I center
int radius
VECTOR2I end
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
bool TestSegmentHit(const VECTOR2I &aRefPoint, const VECTOR2I &aStart, const VECTOR2I &aEnd, int aDist)
Test if aRefPoint is with aDistance on the line defined by aStart and aEnd.
Definition trigo.cpp:173
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:227
@ SCH_LINE_T
Definition typeinfo.h:159
@ SCH_SYMBOL_T
Definition typeinfo.h:168
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.