KiCad PCB EDA Suite
Loading...
Searching...
No Matches
eeschema.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) 2004 Jean-Pierre Charras, [email protected]
5 * Copyright (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <algorithm>
23
24#include <api/api_handler_sch.h>
27#include <api/api_server.h>
28#include <api/api_utils.h>
33#include <pgm_base.h>
34#include <kiface_base.h>
37#include <confirm.h>
38#include <gestfich.h>
40#include "eeschema_helpers.h"
42#include <reporter.h>
43#include "git/kigit_sch_merge.h"
46#include <eeschema_settings.h>
47#include <footprint_filter.h>
48#include <sch_edit_frame.h>
50#include <symbol_edit_frame.h>
51#include <symbol_viewer_frame.h>
58#include <kiway.h>
59#include <project_sch.h>
60#include <richio.h>
63#include <sexpr/sexpr.h>
64#include <sexpr/sexpr_parser.h>
65#include <string_utils.h>
66#include <trace_helpers.h>
67#include <thread_pool.h>
68#include <kiface_services.h>
70#include <widgets/kistatusbar.h>
72#include <wx/ffile.h>
73#include <wx/tokenzr.h>
75
76#include <schematic.h>
77#include <connection_graph.h>
88#include <sim/simulator_frame.h>
89
91#include <toolbars_sch_editor.h>
93
94#include <sch_io/sch_io.h>
95#include <sch_io/sch_io_mgr.h>
96
97#include <wx/crt.h>
98
99// The main sheet of the project
101
102
103namespace SCH {
104
105// Non-job kiface exports for diff/merge (returned by IfaceOrAddress). Defined
106// after the kiface instance so they can route into its jobs handler.
107static int eeschemaMergeExport( int aKind, const wxString& aAncestor, const wxString& aOurs,
108 const wxString& aTheirs, const wxString& aOutput, bool aInteractive,
109 bool aSingleFile, REPORTER* aReporter );
110static int eeschemaOpenDiffDialogExport( int aKind, const wxString& aFileA, const wxString& aFileB,
111 const wxString& aLabelA, const wxString& aLabelB,
112 wxWindow* aParent, REPORTER* aReporter );
114eeschemaAttachDiffCanvasesExport( int aKind, const wxString& aFileA, const wxString& aFileB,
115 WIDGET_DIFF_CANVAS* aBefore, WIDGET_DIFF_CANVAS* aAfter,
116 KICAD_DIFF::DOCUMENT_DIFF* aDiff, REPORTER* aReporter );
117
118
119// TODO: This should move out of this file
120static std::unique_ptr<SCHEMATIC> readSchematicFromFile( const std::string& aFilename )
121{
122 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
123 std::unique_ptr<SCHEMATIC> schematic = std::make_unique<SCHEMATIC>( nullptr );
124
126
127 wxFileName pro( aFilename );
128 pro.SetExt( FILEEXT::ProjectFileExtension );
129 pro.MakeAbsolute();
130 wxString projectPath = pro.GetFullPath();
131
132 PROJECT* project = manager.GetProject( projectPath );
133
134 if( !project )
135 {
136 manager.LoadProject( projectPath, true );
137 project = manager.GetProject( projectPath );
138 }
139
140 schematic->Reset();
141 schematic->SetProject( project );
142 SCH_SHEET* rootSheet = pi->LoadSchematicFile( aFilename, schematic.get() );
143
144 if( !rootSheet )
145 return nullptr;
146
147 std::vector<SCH_SHEET*> topLevelSheets = schematic->GetTopLevelSheets();
148 bool rootIsTopLevel = std::find( topLevelSheets.begin(), topLevelSheets.end(), rootSheet )
149 != topLevelSheets.end();
150 bool rootIsVirtualRoot = rootSheet == &schematic->Root() || rootSheet->IsVirtualRootSheet();
151
152 if( !rootIsTopLevel && !rootIsVirtualRoot )
153 schematic->SetTopLevelSheets( { rootSheet } );
154
155 SCH_SCREENS screens( schematic->Root() );
156
157 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
158 screen->UpdateLocalLibSymbolLinks();
159
160 SCH_SHEET_LIST sheets = schematic->Hierarchy();
161
162 // Restore all of the loaded symbol instances from the root sheet screen.
163 sheets.UpdateSymbolInstanceData( schematic->RootScreen()->GetSymbolInstances() );
164
165 if( schematic->RootScreen()->GetFileFormatVersionAtLoad() < 20230221 )
166 {
167 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
168 screen->FixLegacyPowerSymbolMismatches();
169 }
170
171 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
172 screen->MigrateSimModels();
173
174 // NOTE: This is required for multi-unit symbols to be correct
175 for( SCH_SHEET_PATH& sheet : sheets )
176 sheet.UpdateAllScreenReferences();
177
178 // TODO: this must handle SchematicCleanup somehow. The original version didn't because
179 // it knew that QA test cases were saved in a clean state.
180
181 // TODO: does this need to handle PruneOrphanedSymbolInstances() and
182 // PruneOrphanedSheetInstances()?
183
184 schematic->ConnectionGraph()->Recalculate( sheets, true );
185
186 return schematic;
187}
188
189
190// TODO: This should move out of this file
191bool generateSchematicNetlist( const wxString& aFilename, std::string& aNetlist, KIWAY* aKiway )
192{
193 std::unique_ptr<SCHEMATIC> schematic = readSchematicFromFile( aFilename.ToStdString() );
194
195 if( !schematic )
196 return false;
197
198 NETLIST_EXPORTER_KICAD exporter( schematic.get(), aKiway );
199 STRING_FORMATTER formatter;
200
201 exporter.Format( &formatter, GNL_ALL | GNL_OPT_KICAD );
202 aNetlist = formatter.GetString();
203
204 return true;
205}
206
207
212{
213 PROJECT* project = nullptr;
214
215 if( wxTheApp )
216 {
217 wxWindow* focus = wxWindow::FindFocus();
218 wxWindow* top = focus ? wxGetTopLevelParent( focus ) : wxTheApp->GetTopWindow();
219
220 if( top )
221 {
222 if( KIWAY_HOLDER* holder = dynamic_cast<KIWAY_HOLDER*>( top ) )
223 project = &holder->Prj();
224 }
225 }
226
227 if( !project )
229
230 return project;
231}
232
244static bool footprintReferenceMatches( const LIB_ID& aReference, const LIB_ID& aFootprint )
245{
246 if( !aReference.GetUniStringLibItemName().IsSameAs( aFootprint.GetUniStringLibItemName(), false ) )
247 return false;
248
249 if( !aReference.GetLibNickname().empty() && !aFootprint.GetLibNickname().empty()
250 && !aReference.GetUniStringLibNickname().IsSameAs( aFootprint.GetUniStringLibNickname(), false ) )
251 {
252 return false;
253 }
254
255 return true;
256}
257
258
260
264static bool symbolFilterMatchesFootprint( const LIB_SYMBOL& aSymbol, const LIB_ID& aFootprint,
265 FOOTPRINT_USER_MATCH& aMatch )
266{
267 for( const wxString& filter : aSymbol.GetFPFilters() )
268 {
269 if( filter.IsEmpty() )
270 continue;
271
273 matcher.SetPattern( filter.Lower() );
275 if( FootprintFilterMatchesName( matcher, aFootprint.GetUniStringLibNickname(),
276 aFootprint.GetUniStringLibItemName() ) )
277 {
279 return true;
280 }
281 }
283 return false;
284}
286
293static wxString effectiveFootprintText( const LIB_SYMBOL& aSymbol )
294{
295 if( const SCH_FIELD* field = aSymbol.GetField( FIELD_T::FOOTPRINT ) )
296 {
297 if( !field->GetText().IsEmpty() )
298 return field->GetText();
301 if( std::shared_ptr<LIB_SYMBOL> parent = aSymbol.GetParent().lock() )
302 return effectiveFootprintText( *parent );
304 return wxEmptyString;
305}
317static bool symbolPinMapsBindFootprint( const LIB_SYMBOL& aSymbol, const LIB_ID& aFootprint,
318 FOOTPRINT_USER_MATCH& aMatch )
319{
320 for( const ASSOCIATED_FOOTPRINT& associated : aSymbol.GetEffectiveAssociatedFootprints() )
321 {
322 // A symbol can bind several maps, to the same footprint or to different ones.
323 if( footprintReferenceMatches( associated.m_FootprintLibId, aFootprint ) )
324 aMatch.m_MatchedPinMaps.push_back( associated.m_MapName );
325 }
326
327 return !aMatch.m_MatchedPinMaps.empty();
328}
329
330
335static bool symbolFootprintFieldNamesFootprint( const LIB_SYMBOL& aSymbol, const LIB_ID& aFootprint,
336 FOOTPRINT_USER_MATCH& aMatch )
337{
338 LIB_ID fieldId;
339
340 if( fieldId.Parse( effectiveFootprintText( aSymbol ) ) == -1
341 && footprintReferenceMatches( fieldId, aFootprint ) )
342 {
343 aMatch.m_MatchesFootprintField = true;
344 return true;
345 }
346
347 return false;
348}
349
350
359static std::optional<FOOTPRINT_USER_MATCH> symbolUsesFootprint( const LIB_SYMBOL& aSymbol,
360 const LIB_ID& aFootprint )
361{
363 match.m_Symbol = aSymbol.GetLibId();
364
365 // Every predicate is evaluated: the match feeds the filter and the two flags alike.
366 const bool byFilter = symbolFilterMatchesFootprint( aSymbol, aFootprint, match );
367 const bool byField = symbolFootprintFieldNamesFootprint( aSymbol, aFootprint, match );
368 const bool byPinMap = symbolPinMapsBindFootprint( aSymbol, aFootprint, match );
369
370 if( !byFilter && !byField && !byPinMap )
371 return std::nullopt;
372
373 match.m_PinCount = aSymbol.GetPinCount();
374 match.m_IsDerived = aSymbol.IsDerived();
375
376 return match;
377}
378
379
394static wxString filterFootprintUsers( const wxString& aQueryJson )
395{
397 result.m_Success = false;
398
399 try
400 {
402
403 // A footprint with no item name cannot be referred to by a filter, field or
404 // association, so the query is a successful, empty one.
405 if( query.m_Footprint.GetLibItemName().empty() )
406 {
407 result.m_Success = true;
408 return result.ToJsonStr();
409 }
410
411 // No enabled way of using the footprint can match anything, so the query is a
412 // successful, empty one.
413 if( !query.m_MatchFilters && !query.m_MatchFootprintField && !query.m_MatchPinMaps )
414 {
415 result.m_Success = true;
416 return result.ToJsonStr();
417 }
418
420
421 if( !adapter )
422 return result.ToJsonStr();
423
424 adapter->AsyncLoad();
425 adapter->BlockUntilLoaded();
426
427 for( const wxString& nickname : adapter->GetLibraryNames() )
428 {
429 for( LIB_SYMBOL* symbol : adapter->GetSymbols( nickname ) )
430 {
431 if( !symbol )
432 continue;
433
434 std::optional<FOOTPRINT_USER_MATCH> match = symbolUsesFootprint( *symbol, query.m_Footprint );
435
436 if( !match )
437 continue;
438
439 const bool byFilter = query.m_MatchFilters && !match->m_MatchedFilter.IsEmpty();
440 const bool byField = query.m_MatchFootprintField && match->m_MatchesFootprintField;
441 const bool byPinMap = query.m_MatchPinMaps && !match->m_MatchedPinMaps.empty();
442
443 if( !byFilter && !byField && !byPinMap )
444 continue;
445
446 if( query.m_MaxResults > 0 && static_cast<int>( result.m_Matches.size() ) >= query.m_MaxResults )
447 {
448 result.m_IsLimited = true;
449 break;
450 }
451
452 result.m_Matches.push_back( std::move( *match ) );
453 }
454
455 if( result.m_IsLimited )
456 break;
457 }
458
459 result.m_Success = true;
460
461 return result.ToJsonStr();
462 }
463 catch( const std::exception& )
464 {
465 // A failure carries no matches, even if the scan had already collected some.
466 result.m_Matches.clear();
467 result.m_Success = false;
468 return result.ToJsonStr();
469 }
470}
471
472
477{
479
480 if( adapter )
481 {
482 adapter->AsyncLoad();
483 return true;
484 }
485
486 return false;
487}
488
489
497{
499
500 if( !adapter )
501 return 1.0f;
502
503 // Nothing to report means there is nothing to wait for.
504 if( std::optional<float> progress = adapter->AsyncLoadProgress() )
505 return *progress;
506
507 return 1.0f;
508}
509
510
511static struct IFACE : public KIFACE_BASE, public UNITS_PROVIDER
512{
513 // Of course all are virtual overloads, implementations of the KIFACE.
514
515 IFACE( const char* aName, KIWAY::FACE_T aType ) :
516 KIFACE_BASE( aName, aType ),
519 {}
520
521 bool OnKifaceStart( PGM_BASE* aProgram, int aCtlBits, KIWAY* aKiway ) override;
522
523 void Reset() override;
524
525 void OnKifaceEnd() override;
526
527 wxWindow* CreateKiWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) override
528 {
529 switch( aClassId )
530 {
531 case FRAME_SCH:
532 {
533 SCH_EDIT_FRAME* frame = new SCH_EDIT_FRAME( aKiway, aParent );
534
536
537 if( Kiface().IsSingle() )
538 {
539 // only run this under single_top, not under a project manager.
542 }
543
544 return frame;
545 }
546
548 return new SYMBOL_EDIT_FRAME( aKiway, aParent );
549
550 case FRAME_SIMULATOR:
551 {
552 try
553 {
554 SIMULATOR_FRAME* frame = new SIMULATOR_FRAME( aKiway, aParent );
555 return frame;
556 }
557 catch( const SIMULATOR_INIT_ERR& )
558 {
559 // catch the init err exception as we don't want it to bubble up
560 // its going to be some ngspice install issue but we don't want to log that
561 return nullptr;
562 }
563 }
564
565 case FRAME_SCH_VIEWER:
566 return new SYMBOL_VIEWER_FRAME( aKiway, aParent );
567
569 {
570 bool cancelled = false;
571 SYMBOL_CHOOSER_FRAME* chooser = new SYMBOL_CHOOSER_FRAME( aKiway, aParent, cancelled );
572
573 if( cancelled )
574 {
575 chooser->Destroy();
576 return nullptr;
577 }
578
579 return chooser;
580 }
581
583 InvokeSchEditSymbolLibTable( aKiway, aParent );
584 // Dialog has completed; nothing to return.
585 return nullptr;
586
588 InvokeEditDesignBlockLibTable( aKiway, aParent );
589 // Dialog has completed; nothing to return.
590 return nullptr;
591
593 return new PANEL_SYM_DISPLAY_OPTIONS( aParent, GetAppSettings<SYMBOL_EDITOR_SETTINGS>( "symbol_editor" ) );
594
596 {
598 EDA_BASE_FRAME* frame = aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
599
600 if( !frame )
601 frame = aKiway->Player( FRAME_SCH_VIEWER, false );
602
603 if( !frame )
604 frame = aKiway->Player( FRAME_SCH, false );
605
606 if( frame )
607 SetUserUnits( frame->GetUserUnits() );
608
609 return new PANEL_GRID_SETTINGS( aParent, this, frame, cfg, FRAME_SCH_SYMBOL_EDITOR );
610 }
611
613 return CreateSnappingPanel( aParent, GetAppSettings<SYMBOL_EDITOR_SETTINGS>( "symbol_editor" ),
615
617 {
618 EDA_BASE_FRAME* frame = aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
619
620 if( !frame )
621 frame = aKiway->Player( FRAME_SCH_VIEWER, false );
622
623 if( !frame )
624 frame = aKiway->Player( FRAME_SCH, false );
625
626 if( frame )
627 SetUserUnits( frame->GetUserUnits() );
628
629 return new PANEL_SYM_EDITING_OPTIONS( aParent, this, frame );
630 }
631
633 {
636
637 std::vector<TOOL_ACTION*> actions;
638 std::vector<ACTION_TOOLBAR_CONTROL*> controls;
639
641 actions.push_back( action );
642
644 controls.push_back( control );
645
646 return new PANEL_TOOLBAR_CUSTOMIZATION( aParent, cfg, tb, FRAME_SCH_SYMBOL_EDITOR, actions, controls );
647 }
648
649 case PANEL_SYM_COLORS:
650 return new PANEL_SYM_COLOR_SETTINGS( aParent );
651
653 return new PANEL_EESCHEMA_DISPLAY_OPTIONS( aParent, GetAppSettings<EESCHEMA_SETTINGS>( "eeschema" ) );
654
655 case PANEL_SCH_GRIDS:
656 {
658 EDA_BASE_FRAME* frame = aKiway->Player( FRAME_SCH, false );
659
660 if( !frame )
661 frame = aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
662
663 if( !frame )
664 frame = aKiway->Player( FRAME_SCH_VIEWER, false );
665
666 if( frame )
667 SetUserUnits( frame->GetUserUnits() );
668
669 return new PANEL_GRID_SETTINGS( aParent, this, frame, cfg, FRAME_SCH );
670 }
671
675
677 {
678 EDA_BASE_FRAME* frame = aKiway->Player( FRAME_SCH, false );
679
680 if( !frame )
681 frame = aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
682
683 if( !frame )
684 frame = aKiway->Player( FRAME_SCH_VIEWER, false );
685
686 if( frame )
687 SetUserUnits( frame->GetUserUnits() );
688
689 return new PANEL_EESCHEMA_EDITING_OPTIONS( aParent, this, frame );
690 }
691
693 {
696
697 std::vector<TOOL_ACTION*> actions;
698 std::vector<ACTION_TOOLBAR_CONTROL*> controls;
699
701 actions.push_back( action );
702
704 controls.push_back( control );
705
706 return new PANEL_TOOLBAR_CUSTOMIZATION( aParent, cfg, tb, FRAME_SCH, actions, controls );
707 }
708
709 case PANEL_SCH_COLORS:
710 return new PANEL_EESCHEMA_COLOR_SETTINGS( aParent );
711
713 return new PANEL_TEMPLATE_FIELDNAMES( aParent, nullptr );
714
716 {
717 EDA_BASE_FRAME* frame = aKiway->Player( FRAME_SCH, false );
718
719 if( !frame )
720 frame = aKiway->Player( FRAME_SCH_SYMBOL_EDITOR, false );
721
722 if( !frame )
723 frame = aKiway->Player( FRAME_SCH_VIEWER, false );
724
725 return new class PANEL_SCH_DATA_SOURCES( aParent, frame );
726 }
727
729 return new PANEL_SIMULATOR_PREFERENCES( aParent );
730
731 default:
732 return nullptr;
733 }
734 }
735
773
776
782 void SaveFileAs( const wxString& aProjectBasePath, const wxString& aProjectName,
783 const wxString& aNewProjectBasePath, const wxString& aNewProjectName,
784 const wxString& aSrcFilePath, wxString& aErrors ) override;
785
786
787 int HandleJob( JOB* aJob, REPORTER* aReporter, PROGRESS_REPORTER* aProgressReporter ) override;
788
789 bool HandleJobConfig( JOB* aJob, wxWindow* aParent ) override;
790
791 bool HandleApiOpenDocument( const DOCUMENT_SPEC& aSpec,
792 KICAD_API_SERVER* aServer,
793 wxString* aError ) override;
794
795 bool handleCreateSchematic( const wxString& aPath, KICAD_API_SERVER* aServer, wxString* aError );
796 bool handleOpenSymbol( const wxString& aProjectPath, const wxString& aLibIdStr, KICAD_API_SERVER* aServer,
797 wxString* aError );
798 bool HandleApiCloseDocument( const DOCUMENT_SPEC& aSpec,
799 KICAD_API_SERVER* aServer,
800 wxString* aError ) override;
801
802 void PreloadLibraries( KIWAY* aKiway ) override;
803 void CancelPreload( bool aBlock = true ) override;
804 void ProjectChanged() override;
805 void RegisterLibraryHandlers( KICAD_API_SERVER* aServer ) override;
806 bool LoadAllLibraries() override;
807
808
809private:
810 std::unique_ptr<EESCHEMA_JOBS_HANDLER> m_jobHandler;
811 std::shared_ptr<BACKGROUND_JOB> m_libraryPreloadBackgroundJob;
812 std::future<void> m_libraryPreloadReturn;
814 std::atomic_bool m_libraryPreloadAbort;
815
816 void closeSchematic( KICAD_API_SERVER* aServer );
817 void closeSymbol( KICAD_API_SERVER* aServer );
818
819 KIWAY* m_kiway = nullptr;
821 std::shared_ptr<HEADLESS_SCH_CONTEXT> m_openContext;
822 std::shared_ptr<HEADLESS_SYMBOL_EDITOR_CONTEXT> m_openSymbolContext;
823 std::unique_ptr<API_HANDLER_SYMBOL> m_openSymbolHandler;
824 std::unique_ptr<API_HANDLER_SCH> m_openHandler;
825 std::unique_ptr<API_HANDLER_SCH_LIBRARIES> m_apiHandlerSchLibs;
826
827} kiface( "eeschema", KIWAY::FACE_SCH );
828
829
830int eeschemaMergeExport( int aKind, const wxString& aAncestor, const wxString& aOurs,
831 const wxString& aTheirs, const wxString& aOutput, bool aInteractive,
832 bool aSingleFile, REPORTER* aReporter )
833{
834 return kiface.JobHandler()->RunMerge( static_cast<KICAD_DIFF::DOC_KIND>( aKind ), aAncestor,
835 aOurs, aTheirs, aOutput, aInteractive, aSingleFile,
836 aReporter );
837}
838
839
840int eeschemaOpenDiffDialogExport( int aKind, const wxString& aFileA, const wxString& aFileB,
841 const wxString& aLabelA, const wxString& aLabelB,
842 wxWindow* aParent, REPORTER* aReporter )
843{
844 return kiface.JobHandler()->OpenDiffDialog( static_cast<KICAD_DIFF::DOC_KIND>( aKind ), aFileA,
845 aFileB, aLabelA, aLabelB, aParent, aReporter );
846}
847
848
850 const wxString& aFileB, WIDGET_DIFF_CANVAS* aBefore,
851 WIDGET_DIFF_CANVAS* aAfter,
853 REPORTER* aReporter )
854{
855 return kiface.JobHandler()->AttachDiffCanvases( static_cast<KICAD_DIFF::DOC_KIND>( aKind ), aFileA, aFileB, aBefore,
856 aAfter, *aDiff, aReporter );
857}
858
859} // namespace
860
861using namespace SCH;
862
863
865
866
867// KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h.
868// KIFACE_GETTER will not have name mangling due to declaration in kiway.h.
869KIFACE_API KIFACE* KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram )
870{
871 return &kiface;
872}
873
874
875bool IFACE::OnKifaceStart( PGM_BASE* aProgram, int aCtlBits, KIWAY* aKiway )
876{
877 // This is process-level-initialization, not project-level-initialization of the DSO.
878 // Do nothing in here pertinent to a project!
880
881 // Register the symbol editor settings as well because they share a KiFACE and need to be
882 // loaded prior to use to avoid threading deadlocks
884 aProgram->GetSettingsManager().RegisterSettings( symSettings ); // manager takes ownership
885
886 // We intentionally register KifaceSettings after SYMBOL_EDITOR_SETTINGS
887 // In legacy configs, many settings were in a single editor config nd the migration routine
888 // for the main editor file will try and call into the now separate settings stores
889 // to move the settings into them
891
892 start_common( aCtlBits );
893
894 m_kiway = aKiway;
895
896 m_jobHandler = std::make_unique<EESCHEMA_JOBS_HANDLER>( aKiway );
897
899 {
900 m_jobHandler->SetReporter( &CLI_REPORTER::GetInstance() );
901 m_jobHandler->SetProgressReporter( &CLI_PROGRESS_REPORTER::GetInstance() );
902 }
903
904 if( Pgm().ApiServerOrNull() )
905 {
906 m_apiHandlerSchLibs = std::make_unique<API_HANDLER_SCH_LIBRARIES>();
908 }
909
910 // Register the schematic and symbol-library merge drivers with libgit2 so
911 // `.gitattributes` entries `merge=kicad-sch` and `merge=kicad-sym-lib`
912 // route through KiCad-aware merge logic.
915
916 return true;
917}
918
919
921{
922 if( m_jobHandler )
923 m_jobHandler->ClearCachedSchematic();
924
925 closeSchematic( nullptr );
926 closeSymbol( nullptr );
927}
928
929
931{
932 wxCHECK( aKiway, /* void */ );
933
934 // Use compare_exchange to atomically check and set the flag to prevent race conditions
935 // when PreloadLibraries is called multiple times concurrently (e.g., from project manager
936 // and schematic editor both scheduling via CallAfter)
937 bool expected = false;
938
939 if( !m_libraryPreloadInProgress.compare_exchange_strong( expected, true ) )
940 return;
941
943
945 Pgm().GetBackgroundJobMonitor().Create( _( "Loading Symbol Libraries" ) );
946
947 auto preload =
948 [this, aKiway]() -> void
949 {
950 std::shared_ptr<BACKGROUND_JOB_REPORTER> reporter =
952
954
955 reporter->Report( _( "Loading Symbol Libraries" ) );
956 bool aborted = !adapter->RunPreload( *reporter, m_libraryPreloadAbort );
957
958 // If aborted, skip operations that use the adapter since the project may have changed
959 // and the adapter's project reference could be stale. This prevents use-after-free
960 // crashes when switching projects during library preload.
961 if( !aborted )
962 {
963 // Collect library load errors for async reporting
965 }
966 else
967 {
968 wxLogTrace( traceLibraries, "eeschema PreloadLibraries: aborted, skipping symbol processing" );
969 }
970
973
974 // Only send reload notifications if we weren't aborted
975 if( !aborted )
976 {
977 std::string payload = "";
978 aKiway->ExpressMail( FRAME_SCH, MAIL_RELOAD_LIB, payload, nullptr, true );
979 aKiway->ExpressMail( FRAME_SCH_SYMBOL_EDITOR, MAIL_RELOAD_LIB, payload, nullptr, true );
980 aKiway->ExpressMail( FRAME_SCH_VIEWER, MAIL_RELOAD_LIB, payload, nullptr, true );
981 }
982
983 // A cancel that came after the loop left the flag set, and it would end the next preload at once
984 m_libraryPreloadAbort.store( false );
985 m_libraryPreloadInProgress.store( false );
986 };
987
988 std::future<void> preloadFuture = std::async( std::launch::async, preload );
989 m_libraryPreloadReturn = std::move( preloadFuture );
990}
991
992
993void IFACE::CancelPreload( bool aBlock )
994{
995 if( m_libraryPreloadInProgress.load() )
996 {
997 m_libraryPreloadAbort.store( true );
998
999 if( aBlock )
1000 {
1002
1003 // The preload has ended, so a flag it never read can only stop the next one
1004 m_libraryPreloadAbort.store( false );
1005 }
1006 }
1007}
1008
1009
1011{
1012 if( m_libraryPreloadInProgress.load() )
1013 m_libraryPreloadAbort.store( true );
1014}
1015
1016
1018{
1019 CancelPreload( true );
1020
1022 {
1023 if( Pgm().ApiServerOrNull() )
1025
1026 m_apiHandlerSchLibs.reset();
1027 }
1028
1029 // Release the CLI-cached schematic while the static ERC_ITEM tables it serializes against are
1030 // still alive; deferring to static teardown crashes reading dangling severity keys
1031 if( m_jobHandler )
1032 m_jobHandler->ClearCachedSchematic();
1033
1034 end_common();
1035}
1036
1037
1038void IFACE::SaveFileAs( const wxString& aProjectBasePath, const wxString& aProjectName,
1039 const wxString& aNewProjectBasePath, const wxString& aNewProjectName,
1040 const wxString& aSrcFilePath, wxString& aErrors )
1041{
1042 wxFileName destFile( aSrcFilePath );
1043 wxString destPath = destFile.GetPathWithSep();
1044 wxUniChar pathSep = wxFileName::GetPathSeparator();
1045 wxString ext = destFile.GetExt();
1046
1047 if( destPath.StartsWith( aProjectBasePath + pathSep ) )
1048 destPath.Replace( aProjectBasePath, aNewProjectBasePath, false );
1049
1050 destFile.SetPath( destPath );
1051
1056 {
1057 if( destFile.GetName() == aProjectName )
1058 {
1059 destFile.SetName( aNewProjectName );
1060 }
1061 else if( destFile.GetName() == aNewProjectName )
1062 {
1063 wxString msg;
1064
1065 if( !aErrors.empty() )
1066 aErrors += wxS( "\n" );
1067
1068 msg.Printf( _( "Cannot copy file '%s' as it will be overwritten by the new root "
1069 "sheet file." ), destFile.GetFullPath() );
1070 aErrors += msg;
1071 return;
1072 }
1073
1074 CopySexprFile( aSrcFilePath, destFile.GetFullPath(),
1075 [&]( const std::string& token, wxString& value ) -> bool
1076 {
1077 if( token == "project" && value == aProjectName )
1078 {
1079 value = aNewProjectName;
1080 return true;
1081 }
1082
1083 return false;
1084 },
1085 aErrors );
1086 }
1088 {
1089 // Symbols are not project-specific. Keep their source names.
1090 KiCopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
1091 }
1095 {
1096 if( destFile.GetName() == aProjectName + wxS( "-cache" ) )
1097 destFile.SetName( aNewProjectName + wxS( "-cache" ) );
1098
1099 if( destFile.GetName() == aProjectName + wxS( "-rescue" ) )
1100 destFile.SetName( aNewProjectName + wxS( "-rescue" ) );
1101
1102 KiCopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
1103 }
1104 else if( ext == FILEEXT::NetlistFileExtension )
1105 {
1106 if( destFile.GetName() == aProjectName )
1107 destFile.SetName( aNewProjectName );
1108
1109 CopySexprFile( aSrcFilePath, destFile.GetFullPath(),
1110 [&]( const std::string& token, wxString& value ) -> bool
1111 {
1112 if( token == "source" )
1113 {
1114 for( const wxString& extension : { wxString( wxT( ".sch" ) ), wxString( wxT( ".kicad_sch" ) ) } )
1115 {
1116 if( value == aProjectName + extension )
1117 {
1118 value = aNewProjectName + extension;
1119 return true;
1120 }
1121 else if( value == aProjectBasePath + "/" + aProjectName + extension )
1122 {
1123 value = aNewProjectBasePath + "/" + aNewProjectName + extension;
1124 return true;
1125 }
1126 else if( value.StartsWith( aProjectBasePath ) )
1127 {
1128 value.Replace( aProjectBasePath, aNewProjectBasePath, false );
1129 return true;
1130 }
1131 }
1132 }
1133
1134 return false;
1135 },
1136 aErrors );
1137 }
1138 else if( destFile.GetName() == FILEEXT::SymbolLibraryTableFileName )
1139 {
1140 wxFileName libTableFn( aSrcFilePath );
1141 LIBRARY_TABLE libTable( libTableFn, LIBRARY_TABLE_SCOPE::PROJECT );
1142 libTable.SetPath( destFile.GetFullPath() );
1143 libTable.SetType( LIBRARY_TABLE_TYPE::SYMBOL );
1144
1145 for( LIBRARY_TABLE_ROW& row : libTable.Rows() )
1146 {
1147 wxString uri = row.URI();
1148
1149 uri.Replace( wxS( "/" ) + aProjectName + wxS( "-cache.lib" ),
1150 wxS( "/" ) + aNewProjectName + wxS( "-cache.lib" ) );
1151 uri.Replace( wxS( "/" ) + aProjectName + wxS( "-rescue.lib" ),
1152 wxS( "/" ) + aNewProjectName + wxS( "-rescue.lib" ) );
1153 uri.Replace( wxS( "/" ) + aProjectName + wxS( ".lib" ),
1154 wxS( "/" ) + aNewProjectName + wxS( ".lib" ) );
1155
1156 row.SetURI( uri );
1157 }
1158
1159 libTable.Save().map_error(
1160 [&]( const LIBRARY_ERROR& aError )
1161 {
1162 wxString msg;
1163
1164 if( !aErrors.empty() )
1165 aErrors += wxT( "\n" );
1166
1167 msg.Printf( _( "Cannot copy file '%s'." ), destFile.GetFullPath() );
1168 aErrors += msg;
1169 } );
1170 }
1171 else
1172 {
1173 wxFAIL_MSG( wxS( "Unexpected filetype for Eeschema::SaveFileAs()" ) );
1174 }
1175}
1176
1177
1178int IFACE::HandleJob( JOB* aJob, REPORTER* aReporter, PROGRESS_REPORTER* aProgressReporter )
1179{
1180 return m_jobHandler->RunJob( aJob, aReporter, aProgressReporter );
1181}
1182
1183
1184bool IFACE::HandleJobConfig( JOB* aJob, wxWindow* aParent )
1185{
1186 return m_jobHandler->HandleJobConfig( aJob, aParent );
1187}
1188
1189
1190// TODO(JE) some of the below methods can probably be factored out and shared between sch/pcb
1192{
1193 if( m_openHandler )
1194 {
1195 if( aServer )
1196 aServer->DeregisterHandler( m_openHandler.get() );
1197
1198 m_openHandler.reset();
1199 }
1200
1201 m_openContext.reset();
1202
1203 delete m_openSchematic;
1204 m_openSchematic = nullptr;
1205
1206 // The jobs handler caches the last-loaded schematic. Clear it so the next job
1207 // uses the schematic from the newly opened document rather than a stale copy.
1208 if( m_jobHandler )
1209 m_jobHandler->ClearCachedSchematic();
1210}
1211
1212
1214{
1216 {
1217 if( aServer )
1218 aServer->DeregisterHandler( m_openSymbolHandler.get() );
1219
1220 m_openSymbolHandler.reset();
1221 }
1222
1223 m_openSymbolContext.reset();
1224}
1225
1226
1228 KICAD_API_SERVER* aServer, wxString* aError )
1229{
1230 wxCHECK( aServer, false );
1231
1232 if( aSpec.kind == DOCUMENT_SPEC::KIND::CREATE_KIND )
1233 return handleCreateSchematic( aSpec.path, aServer, aError );
1234
1235 if( aSpec.kind == DOCUMENT_SPEC::KIND::LIBID_KIND )
1236 return handleOpenSymbol( aSpec.path, aSpec.libId.GetUniStringLibId(), aServer, aError );
1237
1238 if( aSpec.path.IsEmpty() )
1239 {
1240 if( aError )
1241 *aError = wxS( "No path specified to open" );
1242
1243 return false;
1244 }
1245
1246 wxFileName projectPath( aSpec.path );
1247
1248 if( projectPath.GetExt() == FILEEXT::KiCadSchematicFileExtension )
1249 projectPath.SetExt( FILEEXT::ProjectFileExtension );
1250 else if( projectPath.GetExt() != FILEEXT::ProjectFileExtension )
1251 projectPath.SetExt( FILEEXT::ProjectFileExtension );
1252
1253 projectPath.MakeAbsolute();
1254
1255 // We currently only support one document per type (and each needs to come from
1256 // the same project). This will need evolution once we support MDI and multi-project.
1257 closeSchematic( aServer );
1258
1259 SETTINGS_MANAGER& settingsManager = Pgm().GetSettingsManager();
1260
1261 // Reuse an already-loaded project if one exists for this path.
1262 PROJECT* project = settingsManager.GetProject( projectPath.GetFullPath() );
1263
1264 if( !project )
1265 {
1266 if( !settingsManager.LoadProject( projectPath.GetFullPath(), true ) )
1267 wxLogTrace( traceApi, "Warning: no project file found for %s", aSpec.path );
1268
1269 project = settingsManager.GetProject( projectPath.GetFullPath() );
1270 }
1271
1272 if( !project )
1273 {
1274 if( aError )
1275 *aError = wxString::Format( wxS( "Error loading project for %s" ), aSpec.path );
1276
1277 return false;
1278 }
1279
1280 wxFileName schPath( projectPath );
1281 schPath.SetExt( FILEEXT::KiCadSchematicFileExtension );
1282
1283 if( !schPath.FileExists() )
1284 {
1285 if( aError )
1286 *aError = wxString::Format( wxS( "File not found: %s" ), schPath.GetFullPath() );
1287
1288 return false;
1289 }
1290
1291 SCHEMATIC* schematic = nullptr;
1292
1293 try
1294 {
1295 schematic = EESCHEMA_HELPERS::LoadSchematic( schPath.GetFullPath(), false, false, project );
1296
1297 if( !schematic )
1298 {
1299 if( aError )
1300 *aError = wxS( "Failed to load schematic" );
1301
1302 return false;
1303 }
1304 }
1305 catch( ... )
1306 {
1307 if( aError )
1308 *aError = wxS( "Failed to load schematic" );
1309
1310 return false;
1311 }
1312
1314
1315 m_openContext = std::make_shared<HEADLESS_SCH_CONTEXT>( &m_openSchematic, project, m_kiway );
1316
1317 if( !m_apiHandlerSchLibs )
1318 {
1319 m_apiHandlerSchLibs = std::make_unique<API_HANDLER_SCH_LIBRARIES>();
1320 aServer->RegisterHandler( m_apiHandlerSchLibs.get() );
1321 }
1322
1323 m_openHandler = std::make_unique<API_HANDLER_SCH>( m_openContext );
1324 aServer->RegisterHandler( m_openHandler.get() );
1325
1326 return true;
1327}
1328
1329
1330bool IFACE::handleCreateSchematic( const wxString& aPath, KICAD_API_SERVER* aServer, wxString* aError )
1331{
1332 wxFileName schPath( aPath );
1333 schPath.MakeAbsolute();
1334
1335 wxFileName projectPath( schPath );
1336 projectPath.SetExt( FILEEXT::ProjectFileExtension );
1337
1338 if( m_openSchematic && m_openSchematic->HasHierarchy() )
1339 {
1340 if( m_openSchematic->Hierarchy().IsModified() )
1341 {
1342 if( aError )
1343 *aError = wxS( "The current schematic has unsaved changes; save or revert it first" );
1344
1345 return false;
1346 }
1347 }
1348
1349 closeSchematic( aServer );
1350
1351 SETTINGS_MANAGER& settingsManager = Pgm().GetSettingsManager();
1352
1353 PROJECT* project = settingsManager.GetProject( projectPath.GetFullPath() );
1354
1355 if( !project )
1356 {
1357 // Create the project settings in memory (LoadProject falls back to defaults when the
1358 // file does not exist on disk) without writing any files.
1359 settingsManager.LoadProject( projectPath.GetFullPath(), true );
1360 project = settingsManager.GetProject( projectPath.GetFullPath() );
1361 }
1362
1363 if( !project )
1364 {
1365 if( aError )
1366 *aError = wxString::Format( wxS( "Error creating project for %s" ), aPath );
1367
1368 return false;
1369 }
1370
1371 std::unique_ptr<SCHEMATIC> schematic = std::make_unique<SCHEMATIC>( project );
1372 schematic->CreateDefaultScreens();
1373
1374 SCH_SCREENS screens( schematic->Root() );
1375 schematic->RootScreen()->SetFileName( schPath.GetFullPath() );
1376
1377 m_openSchematic = schematic.release();
1378
1379 m_openContext = std::make_shared<HEADLESS_SCH_CONTEXT>( &m_openSchematic, project, m_kiway );
1380
1381 if( !m_apiHandlerSchLibs )
1382 {
1383 m_apiHandlerSchLibs = std::make_unique<API_HANDLER_SCH_LIBRARIES>();
1384 aServer->RegisterHandler( m_apiHandlerSchLibs.get() );
1385 }
1386
1387 m_openHandler = std::make_unique<API_HANDLER_SCH>( m_openContext );
1388 aServer->RegisterHandler( m_openHandler.get() );
1389
1390 return true;
1391}
1392
1393
1394bool IFACE::handleOpenSymbol( const wxString& aProjectPath, const wxString& aLibIdStr, KICAD_API_SERVER* aServer,
1395 wxString* aError )
1396{
1397 LIB_ID libId;
1398
1399 if( libId.Parse( aLibIdStr ) >= 0 )
1400 {
1401 if( aError )
1402 *aError = wxString::Format( wxS( "Invalid symbol LIB_ID: %s" ), aLibIdStr );
1403
1404 return false;
1405 }
1406
1407 wxFileName projectPath( aProjectPath );
1408 projectPath.MakeAbsolute();
1409
1410 SETTINGS_MANAGER& settingsManager = Pgm().GetSettingsManager();
1411
1412 if( !settingsManager.LoadProject( projectPath.GetFullPath(), true ) )
1413 {
1414 wxLogTrace( traceApi, "Warning: no project file found for %s", aProjectPath );
1415 }
1416
1417 PROJECT* project = settingsManager.GetProject( projectPath.GetFullPath() );
1418
1419 if( !project )
1420 {
1421 if( aError )
1422 *aError = wxString::Format( wxS( "Error loading project for %s" ), aProjectPath );
1423
1424 return false;
1425 }
1426
1428 adapter->AsyncLoad();
1429 adapter->BlockUntilLoaded();
1430
1431 std::unique_ptr<LIB_SYMBOL> symbol;
1432
1433 try
1434 {
1435 LIB_SYMBOL* loaded = adapter->LoadSymbol( libId );
1436
1437 if( !loaded )
1438 {
1439 if( aError )
1440 *aError = wxString::Format( wxS( "Symbol not found: %s" ), aLibIdStr );
1441
1442 return false;
1443 }
1444
1445 symbol = std::make_unique<LIB_SYMBOL>( *loaded );
1446 }
1447 catch( const IO_ERROR& err )
1448 {
1449 if( aError )
1450 *aError = wxString::Format( wxS( "Failed to load symbol: %s" ), err.What() );
1451
1452 return false;
1453 }
1454 catch( ... )
1455 {
1456 if( aError )
1457 *aError = wxS( "Failed to load symbol" );
1458
1459 return false;
1460 }
1461
1462 closeSymbol( aServer );
1463
1464 if( !m_apiHandlerSchLibs )
1465 {
1466 m_apiHandlerSchLibs = std::make_unique<API_HANDLER_SCH_LIBRARIES>();
1467 aServer->RegisterHandler( m_apiHandlerSchLibs.get() );
1468 }
1469
1470 m_openSymbolContext = std::make_shared<HEADLESS_SYMBOL_EDITOR_CONTEXT>(
1471 std::move( symbol ), libId, project, GetAppSettings<SYMBOL_EDITOR_SETTINGS>( "symbol_editor" ), m_kiway );
1472
1473 m_openSymbolHandler = std::make_unique<API_HANDLER_SYMBOL>( m_openSymbolContext, nullptr );
1474 aServer->RegisterHandler( m_openSymbolHandler.get() );
1475
1476 return true;
1477}
1478
1479
1480bool IFACE::HandleApiCloseDocument( const DOCUMENT_SPEC& aSpec, KICAD_API_SERVER* aServer, wxString* aError )
1481{
1482 wxCHECK( aServer, false );
1483
1484 if( aSpec.kind == DOCUMENT_SPEC::KIND::LIBID_KIND )
1485 {
1486 if( !m_openSymbolContext )
1487 {
1488 if( aError )
1489 *aError = wxS( "No symbol is currently open" );
1490
1491 return false;
1492 }
1493
1494 if( aSpec.libId.IsValid() && m_openSymbolContext->GetLoadedLibId() != aSpec.libId )
1495 {
1496 if( aError )
1497 *aError = wxS( "Requested document does not match the open document" );
1498
1499 return false;
1500 }
1501
1502 closeSymbol( aServer );
1503 return true;
1504 }
1505
1506 if( !m_openContext )
1507 {
1508 if( aError )
1509 *aError = wxS( "No schematic is currently open" );
1510
1511 return false;
1512 }
1513
1514 if( !aSpec.path.IsEmpty() )
1515 {
1516 wxFileName currentSch( m_openContext->GetCurrentFileName() );
1517
1518 if( currentSch.GetFullName() != wxFileName( aSpec.path ).GetFullName() )
1519 {
1520 if( aError )
1521 *aError = wxS( "Requested document does not match the open document" );
1522
1523 return false;
1524 }
1525 }
1526
1527 closeSchematic( aServer );
1528 return true;
1529}
1530
1531
1533{
1534 wxCHECK_RET( aServer, "no API server provided" );
1535
1536 if( !m_apiHandlerSchLibs )
1537 {
1538 m_apiHandlerSchLibs = std::make_unique<API_HANDLER_SCH_LIBRARIES>();
1539 aServer->RegisterHandler( m_apiHandlerSchLibs.get() );
1540 }
1541}
1542
1543
1545{
1547
1548 if( !adapter )
1549 return false;
1550
1551 adapter->AsyncLoad();
1552 return true;
1553}
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
static std::list< TOOL_ACTION * > & GetActionList()
Return list of TOOL_ACTIONs.
Class to hold basic information about controls that can be added to the toolbars.
static std::list< ACTION_TOOLBAR_CONTROL * > GetCustomControlList(FRAME_T aContext)
Get the list of custom controls that could be used on a particular frame type.
APP_SETTINGS_BASE is a settings class that should be derived for each standalone KiCad application.
std::shared_ptr< BACKGROUND_JOB > Create(const wxString &aName)
Creates a background job with the given name.
void Remove(std::shared_ptr< BACKGROUND_JOB > job)
Removes the given background job from any lists and frees it.
static CLI_PROGRESS_REPORTER & GetInstance()
static CLI_REPORTER & GetInstance()
Definition reporter.cpp:261
static bool IsOnStandardSocketPath()
static void AnnounceToPrimary(FRAME_T aFrameType)
The base frame for deriving all KiCad main window classes.
virtual bool SetPattern(const wxString &aPattern) override
Set the pattern against which candidates will be matched.
static void SetSchEditFrame(SCH_EDIT_FRAME *aSchEditFrame)
static SCHEMATIC * LoadSchematic(const wxString &aFileName, bool aSetActive, bool aForceDefaultProject, PROJECT *aProject=nullptr, bool aCalculateConnectivity=true, REPORTER *aRootReporter=nullptr)
Handle Eeschema job dispatches.
SNAP_INFERENCE_SETTINGS m_SnapInference
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
An simple container class that lets us dispatch output jobs to kifaces.
Definition job.h:184
void RegisterHandler(API_HANDLER *aHandler)
Adds a new request handler to the server.
void DeregisterHandler(API_HANDLER *aHandler)
Keeps the documents drawn on a pair of diff canvases alive.
A KIFACE implementation.
Definition kiface_base.h:35
KIFACE_BASE(const char *aKifaceName, KIWAY::FACE_T aId)
Definition kiface_base.h:64
void InitSettings(APP_SETTINGS_BASE *aSettings)
Definition kiface_base.h:94
void end_common()
Common things to do for a top program module, during OnKifaceEnd();.
APP_SETTINGS_BASE * KifaceSettings() const
Definition kiface_base.h:92
bool start_common(int aCtlBits)
Common things to do for a top program module, during OnKifaceStart().
int m_start_flags
flags provided in OnKifaceStart()
bool IsSingle() const
Is this KIFACE running under single_top?
static int Apply(const git_merge_driver_source *aSrc, const char **aPathOut, unsigned int *aModeOut, git_buf *aMergedOut)
A mix in class which holds the location of a wxWindow's KIWAY.
bool Destroy() override
Our version of Destroy() which is virtual from wxWidgets.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:407
virtual void ExpressMail(FRAME_T aDestination, MAIL_T aCommand, std::string &aPayload, wxWindow *aSource=nullptr, bool aFromOtherThread=false)
Send aPayload to aDestination from aSource.
Definition kiway.cpp:511
FACE_T
Known KIFACE implementations.
Definition kiway.h:354
@ FACE_SCH
eeschema DSO
Definition kiway.h:355
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:210
std::optional< float > AsyncLoadProgress() const
Returns the fraction of the libraries queued by AsyncLoad() that have been processed,...
std::vector< KI_ERROR > GetLibraryLoadErrors() const
Returns all library load errors as newline-separated strings for display.
bool RunPreload(PROGRESS_REPORTER &aReporter, std::atomic_bool &aAbort)
Starts AsyncLoad() and waits for it on the calling thread, reporting progress to aReporter.
std::vector< wxString > GetLibraryNames() const
Returns a list of library nicknames that are available (skips any that failed to load)
void AsyncLoad()
Loads all available libraries for this adapter type in the background.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
wxString GetUniStringLibId() const
Definition lib_id.h:144
const wxString GetUniStringLibItemName() const
Get strings for display messages in dialogs.
Definition lib_id.h:108
const wxString GetUniStringLibNickname() const
Definition lib_id.h:84
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
Define a library symbol object.
Definition lib_symbol.h:114
const LIB_ID & GetLibId() const override
Definition lib_symbol.h:190
std::weak_ptr< LIB_SYMBOL > & GetParent()
Definition lib_symbol.h:152
int GetPinCount() const override
const std::vector< ASSOCIATED_FOOTPRINT > & GetEffectiveAssociatedFootprints() const
Definition lib_symbol.h:302
bool IsDerived() const
Definition lib_symbol.h:241
SCH_FIELD * GetField(const wxString &aFieldName)
Find a field within this symbol matching aFieldName; return nullptr if not found.
wxArrayString GetFPFilters() const
Definition lib_symbol.h:254
Generate the KiCad netlist format supported by Pcbnew.
void Format(OUTPUTFORMATTER *aOutputFormatter, int aCtl)
Output this s-expression netlist into aOutputFormatter.
Container for data for KiCad programs.
Definition pgm_base.h:102
virtual BACKGROUND_JOBS_MONITOR & GetBackgroundJobMonitor() const
Definition pgm_base.h:130
void AddLibraryLoadMessages(const std::vector< KI_ERROR > &aMessages)
Add library load messages to all registered status bars.
void ClearLibraryLoadMessages()
Clear library load messages from all registered status bars.
KICAD_API_SERVER & GetApiServer()
Definition pgm_base.h:142
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
A progress reporter interface for use in multi-threaded environments.
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Container for project specific data.
Definition project.h:63
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
Holds all the data relating to one schematic.
Definition schematic.h:155
Schematic editor (Eeschema) main window.
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
SCH_SCREEN * GetNext()
SCH_SCREEN * GetFirst()
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
void UpdateSymbolInstanceData(const std::vector< SCH_SYMBOL_INSTANCE > &aSymbolInstances)
Update all of the symbol instance information using aSymbolInstances.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
bool IsVirtualRootSheet() const
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Take ownership of the pointer passed in.
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
The SIMULATOR_FRAME holds the main user-interface for running simulations.
Simple error container for failure to init the simulation engine and ultimately abort the frame const...
Implement an OUTPUTFORMATTER to a memory buffer.
Definition richio.h:430
const std::string & GetString()
Definition richio.h:453
Symbol library viewer main window.
SNAP_INFERENCE_SETTINGS m_SnapInference
The symbol library editor main window.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
LIB_SYMBOL * LoadSymbol(const wxString &aNickname, const wxString &aName)
Load a LIB_SYMBOL having aName from the library given by aNickname.
std::vector< LIB_SYMBOL * > GetSymbols(const wxString &aNickname, SYMBOL_TYPE aType=SYMBOL_TYPE::ALL_SYMBOLS)
Symbol library viewer main window.
Represent a single user action.
UNITS_PROVIDER(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits)
EDA_UNITS GetUserUnits() const
void SetUserUnits(EDA_UNITS aUnits)
bool empty() const
Definition utf8.h:105
GAL-backed canvas for visualizing a KICAD_DIFF::DIFF_SCENE.
This file is part of the common library.
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
#define _(s)
EDA_UNITS
Definition eda_units.h:45
SCH_SHEET * g_RootSheet
Definition eeschema.cpp:100
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition eeschema.cpp:864
bool FootprintFilterMatchesName(const EDA_PATTERN_MATCH &aFilter, const wxString &aLibNickname, const wxString &aFootprintName)
Whether a given footprint matches a specified filter.
@ PANEL_SYM_EDIT_GRIDS
Definition frame_type.h:72
@ FRAME_SCH_SYMBOL_EDITOR
Definition frame_type.h:31
@ PANEL_SCH_FIELD_NAME_TEMPLATES
Definition frame_type.h:84
@ PANEL_SCH_TOOLBARS
Definition frame_type.h:83
@ PANEL_SYM_SNAPPING
Definition frame_type.h:73
@ FRAME_SCH_VIEWER
Definition frame_type.h:32
@ PANEL_SCH_DISP_OPTIONS
Definition frame_type.h:78
@ PANEL_SCH_SIMULATOR
Definition frame_type.h:85
@ FRAME_SCH
Definition frame_type.h:30
@ PANEL_SYM_TOOLBARS
Definition frame_type.h:76
@ FRAME_SIMULATOR
Definition frame_type.h:34
@ PANEL_SYM_EDIT_OPTIONS
Definition frame_type.h:74
@ PANEL_SCH_EDIT_OPTIONS
Definition frame_type.h:81
@ PANEL_SYM_DISP_OPTIONS
Definition frame_type.h:71
@ DIALOG_SCH_LIBRARY_TABLE
Definition frame_type.h:130
@ PANEL_SYM_COLORS
Definition frame_type.h:75
@ PANEL_SCH_SNAPPING
Definition frame_type.h:80
@ PANEL_SCH_GRIDS
Definition frame_type.h:79
@ PANEL_SCH_COLORS
Definition frame_type.h:82
@ DIALOG_DESIGN_BLOCK_LIBRARY_TABLE
Definition frame_type.h:129
@ FRAME_SYMBOL_CHOOSER
Definition frame_type.h:33
void CopySexprFile(const wxString &aSrcPath, const wxString &aDestPath, std::function< bool(const std::string &token, wxString &value)> aCallback, wxString &aErrors)
Definition gestfich.cpp:443
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Definition gestfich.cpp:416
static const std::string LegacySchematicFileExtension
static const std::string NetlistFileExtension
static const std::string SymbolLibraryTableFileName
static const std::string ProjectFileExtension
static const std::string SchematicSymbolFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string LegacySymbolLibFileExtension
static const std::string KiCadSymbolLibFileExtension
static const std::string BackupFileSuffix
static const std::string LegacySymbolDocumentFileExtension
const wxChar *const traceLibraries
Flag to enable library table and library manager tracing.
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
#define KIFACE_API
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
@ KIFACE_FILTER_FOOTPRINT_USERS
Function pointer type: wxString (*)(const wxString& aQueryJson) Input JSON: the object written by FOO...
Definition kiface_ids.h:50
@ KIFACE_MERGE_DOCUMENT
int (*)( int aKind, const wxString& aAncestor, const wxString& aOurs, const wxString& aTheirs,...
Definition kiface_ids.h:70
@ KIFACE_NETLIST_SCHEMATIC
Definition kiface_ids.h:63
@ KIFACE_TRIGGER_SYMBOLS_LOAD
Function pointer type: bool (*)() Starts loading the symbol libraries in the background.
Definition kiface_ids.h:55
@ KIFACE_ATTACH_DIFF_CANVASES
KICAD_DIFF::DIFF_CANVAS_CONTEXT* (*)( int aKind, const wxString& aFileA, const wxString& aFileB,...
Definition kiface_ids.h:85
@ KIFACE_OPEN_DIFF_DIALOG
int (*)( int aKind, const wxString& aFileA, const wxString& aFileB, const wxString& aLabelA,...
Definition kiface_ids.h:77
@ KIFACE_SYMBOLS_LOAD_PROGRESS
Function pointer type: float (*)() Returns how far the library loader has gotten as a fraction of the...
Definition kiface_ids.h:60
void * KifaceServiceAddress(T aAddress)
Return a service address for IfaceOrAddress().
#define KFCTL_CLI
Running as CLI app.
Definition kiway.h:176
#define KIFACE_GETTER
Definition kiway.h:110
@ MAIL_RELOAD_LIB
Definition mail_type.h:55
DOC_KIND
Document type a diff/merge entry point should route to, derived from a file path's extension.
bool RegisterMergeDriver(const char *aName, MERGE_APPLY_FN aApply)
Register a KiCad merge driver with libgit2.
static int eeschemaMergeExport(int aKind, const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive, bool aSingleFile, REPORTER *aReporter)
Definition eeschema.cpp:830
static float symbolLibraryLoadProgress()
Return how far a background load has got.
Definition eeschema.cpp:496
bool generateSchematicNetlist(const wxString &aFilename, std::string &aNetlist, KIWAY *aKiway)
Definition eeschema.cpp:191
static wxString filterFootprintUsers(const wxString &aQueryJson)
Find the symbols that select a given footprint somehow (but FP field, filters or pin maps)
Definition eeschema.cpp:394
static bool footprintReferenceMatches(const LIB_ID &aReference, const LIB_ID &aFootprint)
Whether a footprint reference names aFootprint.
Definition eeschema.cpp:244
static KICAD_DIFF::DIFF_CANVAS_CONTEXT * eeschemaAttachDiffCanvasesExport(int aKind, const wxString &aFileA, const wxString &aFileB, WIDGET_DIFF_CANVAS *aBefore, WIDGET_DIFF_CANVAS *aAfter, KICAD_DIFF::DOCUMENT_DIFF *aDiff, REPORTER *aReporter)
Definition eeschema.cpp:849
static bool symbolPinMapsBindFootprint(const LIB_SYMBOL &aSymbol, const LIB_ID &aFootprint, FOOTPRINT_USER_MATCH &aMatch)
Whether one of the pin maps of aSymbol is bound to aFootprint; collects the names of the bound maps i...
Definition eeschema.cpp:317
static bool symbolFootprintFieldNamesFootprint(const LIB_SYMBOL &aSymbol, const LIB_ID &aFootprint, FOOTPRINT_USER_MATCH &aMatch)
Whether the footprint field of aSymbol names aFootprint; sets the footprint field flag in aMatch.
Definition eeschema.cpp:335
static std::optional< FOOTPRINT_USER_MATCH > symbolUsesFootprint(const LIB_SYMBOL &aSymbol, const LIB_ID &aFootprint)
Return how aSymbol uses aFootprint, or nothing when it doesn't.
Definition eeschema.cpp:359
static std::unique_ptr< SCHEMATIC > readSchematicFromFile(const std::string &aFilename)
Definition eeschema.cpp:120
static PROJECT * symbolLibraryProject()
Return the project whose symbol libraries the kiface-level symbol services work with.
Definition eeschema.cpp:211
static wxString effectiveFootprintText(const LIB_SYMBOL &aSymbol)
Return the footprint field text in effect for a symbol.
Definition eeschema.cpp:293
static bool symbolFilterMatchesFootprint(const LIB_SYMBOL &aSymbol, const LIB_ID &aFootprint, FOOTPRINT_USER_MATCH &aMatch)
Whether any footprint filter of a symbol selects a given footprint.
Definition eeschema.cpp:264
static bool startSymbolLibraryLoad()
Start loading the symbol libraries in the background.
Definition eeschema.cpp:476
SCH::IFACE KIFACE_BASE, UNITS_PROVIDER kiface("eeschema", KIWAY::FACE_SCH)
static int eeschemaOpenDiffDialogExport(int aKind, const wxString &aFileA, const wxString &aFileB, const wxString &aLabelA, const wxString &aLabelB, wxWindow *aParent, REPORTER *aReporter)
Definition eeschema.cpp:840
#define GNL_ALL
@ GNL_OPT_KICAD
void InvokeEditDesignBlockLibTable(KIWAY *aKiway, wxWindow *aParent)
PANEL_SNAPPING * CreateSnappingPanel(wxWindow *aParent, SETTINGS_T *aCfg, FRAME_T aFrameType, SNAP_INFERENCE_SETTINGS SETTINGS_T::*aInference=nullptr, MAGNETIC_SETTINGS SETTINGS_T::*aMagnetics=nullptr)
Build the snapping page for an editor.
void InvokeSchEditSymbolLibTable(KIWAY *aKiway, wxWindow *aParent)
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
T * GetToolbarSettings(const wxString &aFilename)
T * GetAppSettings(const char *aFilename)
A first-class footprint choice on a LIB_SYMBOL, tied to a named pin map.
Definition pin_map.h:159
All the information needed to query the symbol libraries for the symbols using a footprint.
static FOOTPRINT_USERS_QUERY FromJsonStr(const wxString &aJson)
Parse the JSON object written by ToJsonStr().
bool m_MatchPinMaps
When true, symbols whose pin maps are bound to the footprint are returned.
int m_MaxResults
Limits the number of returned symbols; zero means no limit.
bool m_MatchFilters
When true, symbols whose footprint filters select the footprint are returned.
bool m_MatchFootprintField
When true, symbols whose footprint field names the footprint are returned.
LIB_ID m_Footprint
The footprint to find the users of.
The outcome of a footprint users query, and the JSON encoding used to move it across the Eeschema kif...
One symbol that uses a footprint, and the reason it matched.
wxString m_MatchedFilter
The footprint filter that selected the footprint, empty when the match did not come from a filter.
int m_PinCount
The number of pins of the matching symbol.
bool m_MatchesFootprintField
True when the symbol's footprint field names the footprint.
LIB_ID m_Symbol
The "library:symbol" name of the matching symbol.
bool m_IsDerived
True when the symbol is derived from another symbol rather than being a root symbol.
std::vector< wxString > m_MatchedPinMaps
The names of the symbol's pin maps that are bound to the footprint, in the order they were found; emp...
bool OnKifaceStart(PGM_BASE *aProgram, int aCtlBits, KIWAY *aKiway) override
Typically start_common() is called from here.
The full set of changes between two parsed documents of one type.
wxString path
File path (KIND::FILE_KIND) or project path (KIND::LIBID_KIND).
Definition kiway.h:164
LIB_ID libId
Library identifier; valid when kind == KIND::LIBID_KIND.
Definition kiway.h:165
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
std::future< void > m_libraryPreloadReturn
Definition eeschema.cpp:812
bool OnKifaceStart(PGM_BASE *aProgram, int aCtlBits, KIWAY *aKiway) override
Typically start_common() is called from here.
Definition eeschema.cpp:875
std::shared_ptr< BACKGROUND_JOB > m_libraryPreloadBackgroundJob
Definition eeschema.cpp:811
std::unique_ptr< API_HANDLER_SCH > m_openHandler
Definition eeschema.cpp:824
void PreloadLibraries(KIWAY *aKiway) override
Definition eeschema.cpp:930
void closeSymbol(KICAD_API_SERVER *aServer)
void SaveFileAs(const wxString &aProjectBasePath, const wxString &aProjectName, const wxString &aNewProjectBasePath, const wxString &aNewProjectName, const wxString &aSrcFilePath, wxString &aErrors) override
Saving a file under a different name is delegated to the various KIFACEs because the project doesn't ...
void ProjectChanged() override
std::unique_ptr< API_HANDLER_SYMBOL > m_openSymbolHandler
Definition eeschema.cpp:823
void CancelPreload(bool aBlock=true) override
Definition eeschema.cpp:993
wxWindow * CreateKiWindow(wxWindow *aParent, int aClassId, KIWAY *aKiway, int aCtlBits=0) override
Create a wxWindow for the current project.
Definition eeschema.cpp:527
EESCHEMA_JOBS_HANDLER * JobHandler() const
Accessor for the non-job diff/merge exports (eeschemaMergeExport etc.).
Definition eeschema.cpp:775
std::atomic_bool m_libraryPreloadAbort
Definition eeschema.cpp:814
KIWAY * m_kiway
Definition eeschema.cpp:819
IFACE(const char *aName, KIWAY::FACE_T aType)
Definition eeschema.cpp:515
void RegisterLibraryHandlers(KICAD_API_SERVER *aServer) override
Register this face's library API handlers on the given server.
void Reset() override
Reloads global state.
Definition eeschema.cpp:920
void * IfaceOrAddress(int aDataId) override
Return a pointer to the requested object.
Definition eeschema.cpp:746
int HandleJob(JOB *aJob, REPORTER *aReporter, PROGRESS_REPORTER *aProgressReporter) override
std::unique_ptr< EESCHEMA_JOBS_HANDLER > m_jobHandler
Definition eeschema.cpp:810
std::unique_ptr< API_HANDLER_SCH_LIBRARIES > m_apiHandlerSchLibs
Definition eeschema.cpp:825
bool LoadAllLibraries() override
Starts a background load of all libraries of the type owned by this face.
std::atomic_bool m_libraryPreloadInProgress
Definition eeschema.cpp:813
bool HandleApiCloseDocument(const DOCUMENT_SPEC &aSpec, KICAD_API_SERVER *aServer, wxString *aError) override
Close the document identified by aSpec.
bool HandleApiOpenDocument(const DOCUMENT_SPEC &aSpec, KICAD_API_SERVER *aServer, wxString *aError) override
void closeSchematic(KICAD_API_SERVER *aServer)
std::shared_ptr< HEADLESS_SYMBOL_EDITOR_CONTEXT > m_openSymbolContext
Definition eeschema.cpp:822
bool handleOpenSymbol(const wxString &aProjectPath, const wxString &aLibIdStr, KICAD_API_SERVER *aServer, wxString *aError)
bool HandleJobConfig(JOB *aJob, wxWindow *aParent) override
std::shared_ptr< HEADLESS_SCH_CONTEXT > m_openContext
Definition eeschema.cpp:821
bool handleCreateSchematic(const wxString &aPath, KICAD_API_SERVER *aServer, wxString *aError)
SCHEMATIC * m_openSchematic
Definition eeschema.cpp:820
void OnKifaceEnd() override
Called just once just before the DSO is to be unloaded.
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
IbisParser parser & reporter
KIBIS top(path, &reporter)
VECTOR3I expected(15, 30, 45)
static const long long MM
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.