KiCad PCB EDA Suite
Loading...
Searching...
No Matches
eeschema/files-io.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) 2013 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2013 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 2013-2023 CERN (www.cern.ch)
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23
24#include <algorithm>
25
26#include <confirm.h>
27#include <common.h>
28#include <connection_graph.h>
30#include <dialog_symbol_remap.h>
32#include <embedded_files.h>
33#include <eeschema_settings.h>
34#include <id.h>
35#include <kiface_base.h>
36#include <kiplatform/app.h>
37#include <kiplatform/ui.h>
41#include <local_history.h>
42#include <lockfile.h>
43#include <pgm_base.h>
44#include <core/profile.h>
46#include <project_rescue.h>
47#include <project_sch.h>
51#include <reporter.h>
52#include <richio.h>
54#include <sch_bus_entry.h>
55#include <sch_commit.h>
56#include <sch_edit_frame.h>
57#include <sch_draw_panel.h>
59#include <sch_file_versions.h>
60#include <sch_line.h>
61#include <sch_sheet.h>
62#include <sch_sheet_path.h>
63#include <schematic.h>
65#include <sim/simulator_frame.h>
67#include <tool/actions.h>
68#include <tool/tool_manager.h>
71#include <trace_helpers.h>
73#include <widgets/kistatusbar.h>
74#include <widgets/wx_infobar.h>
76#include <local_history.h>
78#include <wx/app.h>
79#include <wx/ffile.h>
80#include <wx/filedlg.h>
81#include <wx/log.h>
82#include <wx/richmsgdlg.h>
83#include <wx/stdpaths.h>
86#include <paths.h>
87#include <wx_filename.h> // For ::ResolvePossibleSymlinks
90
91#include <kiplatform/io.h>
92
95#include "save_project_utils.h"
96
97bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
98{
99 // ensure the splash screen does not obscure any dialog at startup
100 Pgm().HideSplash();
101
102 // implement the pseudo code from KIWAY_PLAYER.h:
103 wxString msg;
104
105 EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() );
106
107 // This is for python:
108 if( aFileSet.size() != 1 )
109 {
110 msg.Printf( "Eeschema:%s() takes only a single filename.", __WXFUNCTION__ );
111 DisplayError( this, msg );
112 return false;
113 }
114
115 wxString fullFileName( aFileSet[0] );
116 wxFileName wx_filename( fullFileName );
117
118 // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
119 wxASSERT_MSG( wx_filename.IsAbsolute(), wxS( "Path is not absolute!" ) );
120
121 if( !LockFile( fullFileName ) )
122 {
123 // If project-level lock override was already granted, silently override this file's lock
124 if( Prj().IsLockOverrideGranted() )
125 {
126 m_file_checker->OverrideLock();
127 }
128 else
129 {
130 msg.Printf( _( "Schematic '%s' is already open by '%s' at '%s'." ), fullFileName,
131 m_file_checker->GetUsername(), m_file_checker->GetHostname() );
132
133 if( !AskOverrideLock( this, msg ) )
134 return false;
135
136 m_file_checker->OverrideLock();
137 }
138 }
139
140 if( !AskToSaveChanges() )
141 return false;
142
143#ifdef PROFILE
144 PROF_TIMER openFiles( "OpenProjectFile" );
145#endif
146
147 wxFileName pro = fullFileName;
148 pro.SetExt( FILEEXT::ProjectFileExtension );
149
150 bool is_new = !wxFileName::IsFileReadable( fullFileName );
151
152 // If its a non-existent schematic and caller thinks it exists
153 if( is_new && !( aCtl & KICTL_CREATE ) )
154 {
155 // notify user that fullFileName does not exist, ask if user wants to create it.
156 msg.Printf( _( "Schematic '%s' does not exist. Do you wish to create it?" ),
157 fullFileName );
158
159 if( !IsOK( this, msg ) )
160 return false;
161 }
162
163 wxCommandEvent e( EDA_EVT_SCHEMATIC_CHANGING );
164 ProcessEventLocally( e );
165
166 // unload current project file before loading new
167 {
170 SetScreen( nullptr );
172 }
173
174 SetStatusText( wxEmptyString );
175 m_infoBar->Dismiss();
176
177 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
178 statusBar->ClearWarningMessages( "load" );
179
180 WX_PROGRESS_REPORTER progressReporter( this, is_new ? _( "Create Schematic" )
181 : _( "Load Schematic" ), 1,
182 PR_CAN_ABORT );
183 WX_STRING_REPORTER loadReporter;
184 LOAD_INFO_REPORTER_SCOPE loadReporterScope( &loadReporter );
185
186 bool differentProject = pro.GetFullPath() != Prj().GetProjectFullName();
187
188 // This is for handling standalone mode schematic changes
189 if( differentProject )
190 {
191 if( !Prj().IsNullProject() )
192 {
195 }
196
197 // disconnect existing project from schematic before we unload the project
198 Schematic().SetProject( nullptr );
199 GetSettingsManager()->UnloadProject( &Prj(), false );
200
201 GetSettingsManager()->LoadProject( pro.GetFullPath() );
202
203 wxFileName legacyPro( pro );
204 legacyPro.SetExt( FILEEXT::LegacyProjectFileExtension );
205
206 // Do not allow saving a project if one doesn't exist. This normally happens if we are
207 // standalone and opening a schematic that has been moved from its project folder.
208 if( !pro.Exists() && !legacyPro.Exists() && !( aCtl & KICTL_CREATE ) )
209 Prj().SetReadOnly();
210 }
211
212 // Crash-recovery: when zip-format autosave is active, look for autosave files newer
213 // than the saved schematic and offer to recover them before any sheet is loaded.
214 if( !is_new )
215 CheckForAutosaveFiles( wx_filename.GetPath(), { FILEEXT::KiCadSchematicFileExtension } );
216
217 // Start a new schematic object now that we sorted out our project
218 std::unique_ptr<SCHEMATIC> newSchematic = std::make_unique<SCHEMATIC>( &Prj() );
219
220 SCH_IO_MGR::SCH_FILE_T schFileType = SCH_IO_MGR::GuessPluginTypeFromSchPath( fullFileName, aCtl );
221
222 bool isNonKicadImport = schFileType != SCH_IO_MGR::SCH_KICAD
223 && schFileType != SCH_IO_MGR::SCH_LEGACY
224 && schFileType != SCH_IO_MGR::SCH_FILE_UNKNOWN;
225
226 // If this is a recognised non-KiCad format, delegate to the import path.
227 // Callers that pass KICTL_KICAD_ONLY (e.g. GUI open) won't reach
228 // this branch because GuessPluginTypeFromSchPath already returns SCH_FILE_UNKNOWN
229 // for these formats.
230 if( isNonKicadImport )
231 {
232 progressReporter.Hide();
233 importFile( fullFileName, schFileType, nullptr );
234 return true;
235 }
236
237 if( schFileType == SCH_IO_MGR::SCH_LEGACY )
238 {
239 // Don't reload the symbol libraries if we are just launching Eeschema from KiCad again.
240 // They are already saved in the kiface project object.
241 if( differentProject || !Prj().GetElem( PROJECT::ELEM::LEGACY_SYMBOL_LIBS ) )
242 {
243 // load the libraries here, not in SCH_SCREEN::Draw() which is a context
244 // that will not tolerate DisplayError() dialog since we're already in an
245 // event handler in there.
246 // And when a schematic file is loaded, we need these libs to initialize
247 // some parameters (links to PART LIB, dangling ends ...)
250 }
251 }
252 else
253 {
254 // No legacy symbol libraries including the cache are loaded with the new file format.
256 }
257
258 wxFileName rfn( GetCurrentFileName() );
259 rfn.MakeRelativeTo( Prj().GetProjectPath() );
260 LoadWindowState( rfn.GetFullPath() );
261
262 KIPLATFORM::APP::SetShutdownBlockReason( this, _( "Schematic file changes are unsaved" ) );
263
264 if( Kiface().IsSingle() )
265 {
267 }
268
269 if( is_new || schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
270 {
271 newSchematic->CreateDefaultScreens();
272 SetSchematic( newSchematic.release() );
273
274 // mark new, unsaved file as modified.
276 GetScreen()->SetFileName( fullFileName );
277
278 if( schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
279 {
280 if( aCtl & KICTL_KICAD_ONLY )
281 {
282 msg.Printf( _( "'%s' is not a KiCad schematic file.\nUse File -> Import for "
283 "non-KiCad schematic files." ),
284 fullFileName );
285 }
286 else
287 {
288 // Even the non-KiCad plugin type didn't know
289 msg.Printf( _( "'%s' is not a recognised schematic format." ), fullFileName );
290 }
291
292 progressReporter.Hide();
293 DisplayErrorMessage( this, msg );
294 }
295 }
296 else
297 {
298 SetScreen( nullptr );
299
300 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( schFileType ) );
301
302 pi->SetProgressReporter( &progressReporter );
303
304 bool failedLoad = false;
305
306 try
307 {
308 {
309 wxBusyCursor busy;
310 WINDOW_DISABLER raii( this );
311
312 // Check if project file has top-level sheets defined
313 PROJECT_FILE& projectFile = Prj().GetProjectFile();
314 const std::vector<TOP_LEVEL_SHEET_INFO>& topLevelSheets = projectFile.GetTopLevelSheets();
315
316 if( !topLevelSheets.empty() )
317 {
318 std::vector<SCH_SHEET*> loadedSheets;
319
320 // Load each top-level sheet
321 for( const TOP_LEVEL_SHEET_INFO& sheetInfo : topLevelSheets )
322 {
323 wxFileName sheetFileName( Prj().GetProjectPath(), sheetInfo.filename );
324
325 // When loading legacy schematic files, ensure we are referencing the correct extension
326 if( schFileType == SCH_IO_MGR::SCH_LEGACY )
327 sheetFileName.SetExt( FILEEXT::LegacySchematicFileExtension );
328
329 wxString sheetPath = sheetFileName.GetFullPath();
330
331 if( !wxFileName::FileExists( sheetPath ) )
332 {
333 wxLogWarning( wxT( "Top-level sheet file not found: %s" ), sheetPath );
334 continue;
335 }
336
337 SCH_SHEET* sheet = pi->LoadSchematicFile( sheetPath, newSchematic.get() );
338
339 if( sheet )
340 {
341 // Preserve the UUID from the project file, unless it's niluuid which is
342 // just a placeholder meaning "use the UUID from the file"
343 if( sheetInfo.uuid != niluuid )
344 {
345 const_cast<KIID&>( sheet->m_Uuid ) = sheetInfo.uuid;
346 }
347
348 sheet->SetName( sheetInfo.name );
349 loadedSheets.push_back( sheet );
350
351 wxLogTrace( tracePathsAndFiles,
352 wxS( "Loaded top-level sheet '%s' (UUID %s) from %s" ),
353 sheet->GetName(),
354 sheet->m_Uuid.AsString(),
355 sheetPath );
356 }
357 }
358
359 if( !loadedSheets.empty() )
360 {
361 newSchematic->SetTopLevelSheets( loadedSheets );
362 }
363 else
364 {
365 wxLogTrace( tracePathsAndFiles,
366 wxS( "Loaded multi-root schematic with no top-level sheets!" ) );
367 newSchematic->CreateDefaultScreens();
368 }
369 }
370 else
371 {
372 // Legacy single-root format: Load the single root sheet
373 SCH_SHEET* rootSheet = pi->LoadSchematicFile( fullFileName, newSchematic.get() );
374
375 if( rootSheet )
376 {
377 newSchematic->SetTopLevelSheets( { rootSheet } );
378
379 // Make ${SHEETNAME} work on the root sheet until we properly support
380 // naming the root sheet
381 if( SCH_SHEET* topSheet = newSchematic->GetTopLevelSheet() )
382 topSheet->SetName( _( "Root" ) );
383
384 wxLogTrace( tracePathsAndFiles,
385 wxS( "Loaded schematic with root sheet UUID %s" ),
386 rootSheet->m_Uuid.AsString() );
387 wxLogTrace( traceSchCurrentSheet,
388 "After loading: Current sheet path='%s', size=%zu, empty=%d",
389 newSchematic->CurrentSheet().Path().AsString(),
390 newSchematic->CurrentSheet().size(),
391 newSchematic->CurrentSheet().empty() ? 1 : 0 );
392 }
393 else
394 {
395 newSchematic->CreateDefaultScreens();
396 }
397
398 }
399 }
400
401 if( !pi->GetError().IsEmpty() )
402 {
403 DisplayErrorMessage( this, _( "The entire schematic could not be loaded. Errors "
404 "occurred attempting to load hierarchical sheets." ),
405 pi->GetError() );
406 }
407 }
408 catch( const FUTURE_FORMAT_ERROR& ffe )
409 {
410 newSchematic->CreateDefaultScreens();
411 msg.Printf( _( "Error loading schematic '%s'." ), fullFileName );
412 progressReporter.Hide();
413 DisplayErrorMessage( this, msg, ffe.Problem() );
414
415 failedLoad = true;
416 }
417 catch( const IO_ERROR& ioe )
418 {
419 newSchematic->CreateDefaultScreens();
420 msg.Printf( _( "Error loading schematic '%s'." ), fullFileName );
421 progressReporter.Hide();
422 DisplayErrorMessage( this, msg, ioe.What() );
423
424 failedLoad = true;
425 }
426 catch( const std::bad_alloc& )
427 {
428 newSchematic->CreateDefaultScreens();
429 msg.Printf( _( "Memory exhausted loading schematic '%s'." ), fullFileName );
430 progressReporter.Hide();
431 DisplayErrorMessage( this, msg, wxEmptyString );
432
433 failedLoad = true;
434 }
435
436 SetSchematic( newSchematic.release() );
437
438 // This fixes a focus issue after the progress reporter is done on GTK. It shouldn't
439 // cause any issues on macOS and Windows. If it does, it will have to be conditionally
440 // compiled.
441 Raise();
442
443 if( failedLoad )
444 {
445 // Do not leave g_RootSheet == NULL because it is expected to be
446 // a valid sheet. Therefore create a dummy empty root sheet and screen.
449
450 // Show any messages collected before the failure
451 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
452 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
453
454 msg.Printf( _( "Failed to load '%s'." ), fullFileName );
455 SetMsgPanel( wxEmptyString, msg );
456
457 return false;
458 }
459
460 // Load project settings after schematic has been set up with the project link, since this will
461 // update some of the needed schematic settings such as drawing defaults
463
464 SCH_SHEET_LIST sheetList = Schematic().Hierarchy();
465
466 bool repairedPageNumbers = false;
467
468 if( sheetList.AllSheetPageNumbersEmpty() )
469 sheetList.SetInitialPageNumbers();
470 else
471 repairedPageNumbers = sheetList.RepairPageNumbers();
472
473 // It's possible the schematic parser fixed errors due to bugs, or that we reassigned
474 // duplicate or blank sheet page numbers, so warn the user that the schematic has been
475 // fixed (modified).
476 if( sheetList.IsModified() || repairedPageNumbers )
477 {
478 DisplayInfoMessage( this,
479 _( "An error was found when loading the schematic that has "
480 "been automatically fixed. Please save the schematic to "
481 "repair the broken file or it may not be usable with other "
482 "versions of KiCad." ) );
483 }
484
485 UpdateFileHistory( fullFileName );
486
487 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
488 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
489
490 SCH_SCREENS schematic( Schematic().Root() );
491
492 // LIB_ID checks and symbol rescue only apply to the legacy file formats.
493 if( schFileType == SCH_IO_MGR::SCH_LEGACY )
494 {
495 // Convert any legacy bus-bus entries to just be bus wires
496 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
497 {
498 std::vector<SCH_ITEM*> deleted;
499
500 for( SCH_ITEM* item : screen->Items() )
501 {
502 if( item->Type() == SCH_BUS_BUS_ENTRY_T )
503 {
504 SCH_BUS_BUS_ENTRY* entry = static_cast<SCH_BUS_BUS_ENTRY*>( item );
505 std::unique_ptr<SCH_LINE> wire = std::make_unique<SCH_LINE>();
506
507 wire->SetLayer( LAYER_BUS );
508 wire->SetStartPoint( entry->GetPosition() );
509 wire->SetEndPoint( entry->GetEnd() );
510
511 screen->Append( wire.release() );
512 deleted.push_back( item );
513 }
514 }
515
516 for( SCH_ITEM* item : deleted )
517 screen->Remove( item );
518 }
519
520
521 // Convert old projects over to use symbol library table.
522 if( schematic.HasNoFullyDefinedLibIds() )
523 {
524 DIALOG_SYMBOL_REMAP dlgRemap( this );
525
526 dlgRemap.ShowQuasiModal();
527 }
528 else
529 {
530 // Double check to ensure no legacy library list entries have been
531 // added to the project file symbol library list.
532 wxString paths;
533 wxArrayString libNames;
534
535 LEGACY_SYMBOL_LIBS::GetLibNamesAndPaths( &Prj(), &paths, &libNames );
536
537 if( !libNames.IsEmpty() )
538 {
539 if( eeconfig()->m_Appearance.show_illegal_symbol_lib_dialog )
540 {
541 wxRichMessageDialog invalidLibDlg(
542 this,
543 _( "Illegal entry found in project file symbol library list." ),
544 _( "Project Load Warning" ),
545 wxOK | wxCENTER | wxICON_EXCLAMATION );
546 invalidLibDlg.ShowDetailedText(
547 _( "Symbol libraries defined in the project file symbol library "
548 "list are no longer supported and will be removed.\n\n"
549 "This may cause broken symbol library links under certain "
550 "conditions." ) );
551 invalidLibDlg.ShowCheckBox( _( "Do not show this dialog again." ) );
552 invalidLibDlg.ShowModal();
554 !invalidLibDlg.IsCheckBoxChecked();
555 }
556
557 libNames.Clear();
558 paths.Clear();
559 LEGACY_SYMBOL_LIBS::SetLibNamesAndPaths( &Prj(), paths, libNames );
560 }
561
562 // Check for cache file
563 wxFileName cacheFn( fullFileName );
564 cacheFn.SetName( cacheFn.GetName() + "-cache" );
566 bool cacheExists = cacheFn.FileExists();
567
568 if( cacheExists )
569 {
571 std::optional<LIBRARY_TABLE*> table = adapter->ProjectTable();
572
573 if( table && *table )
574 {
575 wxString nickname = Prj().GetProjectName() + "-cache";
576
577 if( !(*table)->HasRow( nickname ) )
578 {
579 LIBRARY_TABLE_ROW& row = (*table)->InsertRow();
580 row.SetNickname( nickname );
581 row.SetURI( cacheFn.GetFullPath() );
582 row.SetType( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY ) );
583 row.SetDescription( _( "Legacy project cache library" ) );
584 (*table)->Save();
585 }
586
587 std::vector<KI_ERROR> libErrors;
588
589 ReconcileLegacyCacheSymbols( *adapter, nickname, schematic, libErrors );
590
591 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
592 statusBar->AddWarningMessages( "load", libErrors );
593 }
594 }
595
596 if( ( !cfg || !cfg->m_RescueNeverShow ) && !cacheExists )
597 {
599 editor->RescueSymbolLibTableProject( false );
600 }
601 }
602
603 // Ensure there is only one legacy library loaded and that it is the cache library.
604 LEGACY_SYMBOL_LIBS* legacyLibs = PROJECT_SCH::LegacySchLibs( &Schematic().Project() );
605
606 if( legacyLibs->GetLibraryCount() == 0 )
607 {
608 wxString extMsg;
609 wxFileName cacheFn = pro;
610
611 wxLogTrace( traceAutoSave, "[SetName dbg] cacheFn BEFORE path='%s' name='%s' full='%s' arg='%s'",
612 cacheFn.GetPath(), cacheFn.GetName(), cacheFn.GetFullPath(), cacheFn.GetName() + "-cache" );
613 cacheFn.SetName( cacheFn.GetName() + "-cache" );
614 wxLogTrace( traceAutoSave, "[SetName dbg] cacheFn AFTER path='%s' name='%s' full='%s'",
615 cacheFn.GetPath(), cacheFn.GetName(), cacheFn.GetFullPath() );
617
618 msg.Printf( _( "The project symbol library cache file '%s' was not found." ),
619 cacheFn.GetFullName() );
620 extMsg = _( "This can result in a broken schematic under certain conditions. "
621 "If the schematic does not have any missing symbols upon opening, "
622 "save it immediately before making any changes to prevent data "
623 "loss. If there are missing symbols, either manual recovery of "
624 "the schematic or recovery of the symbol cache library file and "
625 "reloading the schematic is required." );
626
627 KICAD_MESSAGE_DIALOG dlgMissingCache( this, msg, _( "Warning" ),
628 wxOK | wxCANCEL | wxICON_EXCLAMATION | wxCENTER );
629 dlgMissingCache.SetExtendedMessage( extMsg );
630 dlgMissingCache.SetOKCancelLabels( KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Load Without Cache File" ) ),
631 KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Abort" ) ) );
632
633 if( dlgMissingCache.ShowModal() == wxID_CANCEL )
634 {
635 Schematic().Reset();
637 return false;
638 }
639 }
640
641 // Update all symbol library links for all sheets.
642 schematic.UpdateSymbolLinks( &loadReporter );
643
644 m_infoBar->RemoveAllButtons();
645 m_infoBar->AddCloseButton();
646 m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
647 "It will be converted to the new format when saved." ),
648 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
649
650 // Legacy schematic can have duplicate time stamps so fix that before converting
651 // to the s-expression format.
652 schematic.ReplaceDuplicateTimeStamps();
653
654 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
655 screen->FixLegacyPowerSymbolMismatches();
656
657 // Allow the schematic to be saved to new file format without making any edits.
658 OnModify();
659 }
660 else // S-expression schematic.
661 {
662 SCH_SCREEN* first_screen = schematic.GetFirst();
663
664 // Skip the first screen as it is a virtual root with no version info.
665 if( first_screen && first_screen->GetFileFormatVersionAtLoad() == 0 )
666 first_screen = schematic.GetNext();
667
668 if( first_screen && first_screen->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
669 {
670 m_infoBar->RemoveAllButtons();
671 m_infoBar->AddCloseButton();
672 m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
673 "It will be converted to the new format when saved." ),
674 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
675 }
676
677 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
679
680 SCH_SCREEN* rootScreen = Schematic().RootScreen();
681
682 // Restore all of the loaded symbol and sheet instances from the root sheet.
683 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20221002 )
684 sheetList.UpdateSymbolInstanceData( rootScreen->GetSymbolInstances() );
685
686 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20221110 )
687 sheetList.UpdateSheetInstanceData( rootScreen->GetSheetInstances());
688
689 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20230221 )
690 for( SCH_SCREEN* screen = schematic.GetFirst(); screen;
691 screen = schematic.GetNext() )
692 screen->FixLegacyPowerSymbolMismatches();
693
694 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
695 screen->MigrateSimModels();
696
698 UpdateVariantSelectionCtrl( Schematic().GetVariantNamesForUI() );
699 }
700
701 // After the schematic is successfully loaded, we load the drawing sheet.
702 // This allows us to use the drawing sheet embedded in the schematic (if any)
703 // instead of the default one.
705
706 wxLogTrace( traceSchCurrentSheet,
707 "Before CheckForMissingSymbolInstances: Current sheet path='%s', size=%zu",
708 GetCurrentSheet().Path().AsString(),
709 GetCurrentSheet().size() );
710
711 // Check must run before pruning so variant data on a stale instance path is migrated
712 // onto the new instance before the orphan is removed.
713 sheetList.CheckForMissingSymbolInstances( Prj().GetProjectName() );
714
715 schematic.PruneOrphanedSymbolInstances( Prj().GetProjectName(), sheetList );
716 schematic.PruneOrphanedSheetInstances( Prj().GetProjectName(), sheetList );
717
719
720 SetScreen( GetCurrentSheet().LastScreen() );
721
722 // Repaired page numbers changed in-memory sheet instances; flag the schematic so the
723 // fixed numbering can be saved instead of silently reverting on the next load.
724 if( repairedPageNumbers )
725 OnModify();
726
727 wxLogTrace( traceSchCurrentSheet,
728 "After SetScreen: Current sheet path='%s', size=%zu",
729 GetCurrentSheet().Path().AsString(),
730 GetCurrentSheet().size() );
731
732 // Older files can omit implied junctions. Repair them before publishing connectivity;
733 // repairing current files could instead connect an intentional wire crossing.
734 const bool nativeNeedsFixup = schFileType == SCH_IO_MGR::SCH_KICAD
737
738 if( schFileType == SCH_IO_MGR::SCH_LEGACY || nativeNeedsFixup )
740
741 SCH_COMMIT dummy( this );
742
743 progressReporter.Report( _( "Updating connections..." ) );
744 progressReporter.KeepRefreshing();
745
746 RecalculateConnections( &dummy, GLOBAL_CLEANUP, &progressReporter );
747 dummy.Push( _( "Schematic Cleanup" ),
749
750 // Migrate conflicting bus definitions, but only for files old enough to store them.
751 // The connection graph must be rebuilt first so GetBusesNeedingMigration() can see the
752 // conflicting subgraphs; the earlier Reset() clears them.
753 SCH_SCREEN* schRootScreen = Schematic().RootScreen();
754 int schFileVersion = schRootScreen ? schRootScreen->GetFileFormatVersionAtLoad() : 0;
755
757 schFileVersion, Schematic().ConnectionGraph()->GetBusesNeedingMigration().size() ) )
758 {
759 progressReporter.Hide();
760
761 // The rebuild below frees the subgraphs the dialog caches, and a progress update can
762 // dispatch queued UI events into its still-bound handlers, so destroy the dialog first.
763 {
764 DIALOG_MIGRATE_BUSES dlg( this );
765 dlg.ShowQuasiModal();
766 }
767
768 OnModify();
769 progressReporter.Show();
770
771 // Relabeling the conflicting buses changes connectivity, so rebuild it.
772 RecalculateConnections( &dummy, GLOBAL_CLEANUP, &progressReporter );
773 dummy.Push( _( "Schematic Cleanup" ),
775 }
776
777 if( schematic.HasSymbolFieldNamesWithWhiteSpace() )
778 {
779 m_infoBar->QueueShowMessage( _( "This schematic contains symbols that have leading "
780 "and/or trailing white space field names." ),
781 wxICON_WARNING );
782 }
783 }
784
785 // Load any exclusions from the project file
787
790
793
794 SyncView();
796
798
799 UpdateHierarchyNavigator( false, true );
800 CallAfter(
801 [this]()
802 {
803 if( m_netNavigator && m_netNavigator->IsEmpty() )
804 {
806 }
807 } );
808
809 wxCommandEvent changedEvt( EDA_EVT_SCHEMATIC_CHANGED );
810 ProcessEventLocally( changedEvt );
811
812 if( !differentProject )
813 {
814 // If we didn't reload the project, we still need to call ProjectChanged() to ensure
815 // frame-specific initialization happens (like registering the autosave saver).
816 // When running under the project manager, KIWAY::ProjectChanged() was called before
817 // this frame existed, so we need to call our own ProjectChanged() now.
819 }
820
821 for( wxEvtHandler* listener : m_schematicChangeListeners )
822 {
823 wxCHECK2( listener, continue );
824
825 // Use the windows variant when handling event messages in case there is any special
826 // event handler pre and/or post processing specific to windows.
827 wxWindow* win = dynamic_cast<wxWindow*>( listener );
828
829 if( win )
830 win->HandleWindowEvent( e );
831 else
832 listener->SafelyProcessEvent( e );
833 }
834
835 updateTitle();
836 m_toolManager->GetTool<SCH_NAVIGATE_TOOL>()->ResetHistory();
837
838 wxFileName fn = Prj().AbsolutePath( GetScreen()->GetFileName() );
839
840 if( fn.FileExists() && !fn.IsFileWritable() )
841 {
842 m_infoBar->RemoveAllButtons();
843 m_infoBar->AddCloseButton();
844 m_infoBar->ShowMessage( _( "Schematic is read only." ),
845 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
846 }
847
848#ifdef PROFILE
849 openFiles.Show();
850#endif
851 // Ensure all items are redrawn (especially the drawing-sheet items):
852 if( GetCanvas() )
853 GetCanvas()->DisplaySheet( GetCurrentSheet().LastScreen() );
854
855 // Trigger a library load to handle any project-specific libraries
856 CallAfter( [&]()
857 {
858 KIFACE *schface = Kiway().KiFACE( KIWAY::FACE_SCH );
859 schface->PreloadLibraries( &Kiway() );
860
862 } );
863
864 m_remoteSymbolPane->BindWebViewLoaded();
865
866 return true;
867}
868
869
871{
872 if( Schematic().RootScreen() && !Schematic().RootScreen()->Items().empty() )
873 {
874 wxString msg = _( "This operation replaces the contents of the current schematic, "
875 "which will be permanently lost.\n\n"
876 "Do you want to proceed?" );
877
878 if( !IsOK( this, msg ) )
879 return;
880 }
881
882 // Set the project location if none is set or if we are running in standalone mode
883 bool setProject = Prj().GetProjectFullName().IsEmpty() || Kiface().IsSingle();
884 wxString path = wxPathOnly( Prj().GetProjectFullName() );
885
886 wxString fileFiltersStr;
887 wxString allWildcardsStr;
888
889 for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
890 {
891 if( fileType == SCH_IO_MGR::SCH_KICAD || fileType == SCH_IO_MGR::SCH_LEGACY )
892 continue; // this is "Import non-KiCad schematic"
893
894 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
895
896 if( !pi )
897 continue;
898
899 const IO_BASE::IO_FILE_DESC& desc = pi->GetSchematicFileDesc();
900
901 if( desc.m_FileExtensions.empty() || !desc.m_CanRead )
902 continue;
903
904 if( !fileFiltersStr.IsEmpty() )
905 fileFiltersStr += wxChar( '|' );
906
907 fileFiltersStr += desc.FileFilter();
908
909 for( const std::string& ext : desc.m_FileExtensions )
910 allWildcardsStr << wxS( "*." ) << formatWildcardExt( ext ) << wxS( ";" );
911 }
912
913 fileFiltersStr = _( "All supported formats" ) + wxS( "|" ) + allWildcardsStr + wxS( "|" )
914 + fileFiltersStr;
915
916 wxFileDialog dlg( this, _( "Import Schematic" ), path, wxEmptyString, fileFiltersStr,
917 wxFD_OPEN | wxFD_FILE_MUST_EXIST );
918
919 FILEDLG_IMPORT_NON_KICAD importOptions( eeconfig()->m_System.show_import_issues );
920 dlg.SetCustomizeHook( importOptions );
921
923
924 if( dlg.ShowModal() == wxID_CANCEL )
925 return;
926
928
929 // Don't leave dangling pointers to previously-opened document.
930 m_toolManager->GetTool<SCH_SELECTION_TOOL>()->ClearSelection();
933
934 if( setProject )
935 {
936 Schematic().SetProject( nullptr );
937 GetSettingsManager()->UnloadProject( &Prj(), false );
938
939 // Clear view before destroying schematic as repaints depend on schematic being valid
940 SetScreen( nullptr );
941
942 Schematic().Reset();
943
944 wxFileName projectFn( dlg.GetPath() );
945 projectFn.SetExt( FILEEXT::ProjectFileExtension );
946 GetSettingsManager()->LoadProject( projectFn.GetFullPath() );
947 }
948
949 wxFileName fn = dlg.GetPath();
950
951 if( !fn.IsFileReadable() )
952 {
953 wxLogError( _( "Insufficient permissions to read file '%s'." ), fn.GetFullPath() );
954 return;
955 }
956
957 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN;
958
959 for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
960 {
961 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
962
963 if( !pi )
964 continue;
965
966 if( pi->CanReadSchematicFile( fn.GetFullPath() ) )
967 {
968 pluginType = fileType;
969 break;
970 }
971 }
972
973 if( pluginType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
974 {
975 wxLogError( _( "No loader can read the specified file: '%s'." ), fn.GetFullPath() );
977 SetScreen( Schematic().RootScreen() );
978 return;
979 }
980
981 importFile( dlg.GetPath(), pluginType );
982
984}
985
986
987bool SCH_EDIT_FRAME::saveSchematicFile( SCH_SHEET* aSheet, const wxString& aSavePath )
988{
989 wxString msg;
990 wxFileName schematicFileName;
991 wxFileName oldFileName;
992 bool success;
993
994 SCH_SCREEN* screen = aSheet->GetScreen();
995
996 wxCHECK( screen, false );
997
998 // Cannot save to nowhere
999 if( aSavePath.IsEmpty() )
1000 return false;
1001
1002 // Construct the name of the file to be saved
1003 schematicFileName = Prj().AbsolutePath( aSavePath );
1004 oldFileName = schematicFileName;
1005
1006 // Write through symlinks, don't replace them
1007 WX_FILENAME::ResolvePossibleSymlinks( schematicFileName );
1008
1009 if( !schematicFileName.DirExists() )
1010 {
1011 if( !wxMkdir( schematicFileName.GetPath() ) )
1012 {
1013 msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
1014 schematicFileName.GetFullPath(),
1015 "Could not create directory: %s" + schematicFileName.GetPath() );
1016 DisplayError( this, msg );
1017
1018 return false;
1019 }
1020 }
1021
1022 if( !IsWritable( schematicFileName ) )
1023 return false;
1024
1025 wxFileName projectFile( schematicFileName );
1026
1027 projectFile.SetExt( FILEEXT::ProjectFileExtension );
1028
1029 if( projectFile.FileExists() )
1030 {
1031 // Save various ERC settings, such as violation severities (which may have been edited
1032 // via the ERC dialog as well as the Schematic Setup dialog), ERC exclusions, etc.
1034 }
1035
1036 // Save
1037 wxLogTrace( traceAutoSave, wxS( "Saving file " ) + schematicFileName.GetFullPath() );
1038
1039 if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
1040 m_infoBar->Dismiss();
1041
1042 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::GuessPluginTypeFromSchPath(
1043 schematicFileName.GetFullPath() );
1044
1045 if( pluginType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
1046 pluginType = SCH_IO_MGR::SCH_KICAD;
1047
1048 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pluginType ) );
1049
1050 // On Windows, ensure the target file is writeable by clearing problematic attributes like
1051 // hidden or read-only. This can happen when files are synced via cloud services.
1052 if( schematicFileName.FileExists() )
1053 KIPLATFORM::IO::MakeWriteable( schematicFileName.GetFullPath() );
1054
1055 try
1056 {
1057 pi->SaveSchematicFile( schematicFileName.GetFullPath(), aSheet, &Schematic() );
1058 success = true;
1059 }
1060 catch( const IO_ERROR& ioe )
1061 {
1062 msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
1063 schematicFileName.GetFullPath(),
1064 ioe.What() );
1065 DisplayError( this, msg );
1066
1067 success = false;
1068 }
1069
1070 if( success )
1071 {
1072 screen->SetContentModified( false );
1073
1074 msg.Printf( _( "File '%s' saved." ), screen->GetFileName() );
1075 SetStatusText( msg, 0 );
1076 }
1077
1078 return success;
1079}
1080
1081
1082bool PrepareSaveAsFiles( SCHEMATIC& aSchematic, SCH_SCREENS& aScreens,
1083 const wxFileName& aOldRoot, const wxFileName& aNewRoot,
1084 bool aSaveCopy, bool aCopySubsheets, bool aIncludeExternSheets,
1085 std::unordered_map<SCH_SCREEN*, wxString>& aFilenameMap,
1086 wxString& aErrorMsg )
1087{
1088 SCH_SCREEN* screen;
1089
1090 for( size_t i = 0; i < aScreens.GetCount(); i++ )
1091 {
1092 screen = aScreens.GetScreen( i );
1093
1094 wxCHECK2( screen, continue );
1095
1096 if( screen == aSchematic.RootScreen() )
1097 continue;
1098
1099 // The virtual root's screen only holds the top-level sheets and has no file of its own
1100 // A destination here would be a nameless path that callers turn into a stray ".kicad_sch"
1101 if( screen == aSchematic.Root().GetScreen() )
1102 continue;
1103
1104 wxFileName src = screen->GetFileName();
1105
1106 if( !src.IsAbsolute() )
1107 src.MakeAbsolute( aOldRoot.GetPath() );
1108
1109 bool internalSheet = src.GetPath().StartsWith( aOldRoot.GetPath() );
1110
1111 if( aCopySubsheets && ( internalSheet || aIncludeExternSheets ) )
1112 {
1113 wxFileName dest = src;
1114
1115 if( internalSheet && dest.MakeRelativeTo( aOldRoot.GetPath() ) )
1116 dest.MakeAbsolute( aNewRoot.GetPath() );
1117 else
1118 dest.Assign( aNewRoot.GetPath(), dest.GetFullName() );
1119
1120 wxLogTrace( tracePathsAndFiles,
1121 wxS( "Moving schematic from '%s' to '%s'." ),
1122 screen->GetFileName(),
1123 dest.GetFullPath() );
1124
1125 if( !dest.DirExists() && !dest.Mkdir() )
1126 {
1127 aErrorMsg.Printf( _( "Folder '%s' could not be created.\n\n"
1128 "Make sure you have write permissions and try again." ),
1129 dest.GetPath() );
1130 return false;
1131 }
1132
1133 if( aSaveCopy )
1134 aFilenameMap[screen] = dest.GetFullPath();
1135 else
1136 screen->SetFileName( dest.GetFullPath() );
1137 }
1138 else
1139 {
1140 if( aSaveCopy )
1141 aFilenameMap[screen] = wxString();
1142
1143 screen->SetFileName( src.GetFullPath() );
1144 }
1145 }
1146
1147 for( SCH_SHEET_PATH& sheet : aSchematic.Hierarchy() )
1148 {
1149 if( !sheet.Last()->IsTopLevelSheet() )
1150 sheet.MakeFilePathRelativeToParentSheet();
1151 }
1152
1153 return true;
1154}
1155
1157{
1158 wxString msg;
1159 SCH_SCREEN* screen;
1160 SCH_SCREENS screens( Schematic().Root() );
1161 bool saveCopy = aSaveAs && !Kiface().IsSingle();
1162 bool success = true;
1163 bool updateFileHistory = false;
1164 bool createNewProject = false;
1165 bool copySubsheets = false;
1166 bool includeExternSheets = false;
1167
1168 // I want to see it in the debugger, show me the string! Can't do that with wxFileName.
1169 wxString fileName = Prj().AbsolutePath( Schematic().Root().GetFileName() );
1170 wxFileName fn = fileName;
1171
1172 // Path to save each screen to: will be the stored filename by default, but is overwritten by
1173 // a Save As Copy operation.
1174 std::unordered_map<SCH_SCREEN*, wxString> filenameMap;
1175
1176 // Handle "Save As" and saving a new project/schematic for the first time in standalone
1177 if( Prj().IsNullProject() || aSaveAs )
1178 {
1179 // Null project should only be possible in standalone mode.
1180 wxCHECK( Kiface().IsSingle() || aSaveAs, false );
1181
1182 wxFileName newFileName;
1183 wxFileName savePath( Prj().GetProjectFullName() );
1184
1185 if( !savePath.IsOk() || !savePath.IsDirWritable() )
1186 {
1187 savePath = GetMruPath();
1188
1189 if( !savePath.IsOk() || !savePath.IsDirWritable() )
1191 }
1192
1193 if( savePath.HasExt() )
1194 savePath.SetExt( FILEEXT::KiCadSchematicFileExtension );
1195 else
1196 savePath.SetName( wxEmptyString );
1197
1198 wxFileDialog dlg( this, _( "Schematic Files" ), savePath.GetPath(), savePath.GetFullName(),
1200 wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
1201
1202 FILEDLG_HOOK_SAVE_PROJECT newProjectHook;
1203
1204 // Add a "Create a project" checkbox in standalone mode and one isn't loaded
1205 if( Kiface().IsSingle() || aSaveAs )
1206 {
1207 dlg.SetCustomizeHook( newProjectHook );
1208 }
1209
1211
1212 if( dlg.ShowModal() == wxID_CANCEL )
1213 return false;
1214
1215 newFileName = EnsureFileExtension( dlg.GetPath(), FILEEXT::KiCadSchematicFileExtension );
1216
1217 if( ( !newFileName.DirExists() && !newFileName.Mkdir() ) ||
1218 !newFileName.IsDirWritable() )
1219 {
1220 msg.Printf( _( "Folder '%s' could not be created.\n\n"
1221 "Make sure you have write permissions and try again." ),
1222 newFileName.GetPath() );
1223
1224 KICAD_MESSAGE_DIALOG dlgBadPath( this, msg, _( "Error" ),
1225 wxOK | wxICON_EXCLAMATION | wxCENTER );
1226
1227 dlgBadPath.ShowModal();
1228 return false;
1229 }
1230
1231 if( newProjectHook.IsAttachedToDialog() )
1232 {
1233 createNewProject = newProjectHook.GetCreateNewProject();
1234 copySubsheets = newProjectHook.GetCopySubsheets();
1235 includeExternSheets = newProjectHook.GetIncludeExternSheets();
1236 }
1237
1238 if( !saveCopy )
1239 {
1240 Schematic().Root().SetFileName( newFileName.GetFullName() );
1241 Schematic().RootScreen()->SetFileName( newFileName.GetFullPath() );
1242 updateFileHistory = true;
1243 }
1244 else
1245 {
1246 filenameMap[Schematic().RootScreen()] = newFileName.GetFullPath();
1247 }
1248
1249 if( !PrepareSaveAsFiles( Schematic(), screens, fn, newFileName, saveCopy,
1250 copySubsheets, includeExternSheets, filenameMap, msg ) )
1251 {
1252 KICAD_MESSAGE_DIALOG dlgBadFilePath( this, msg, _( "Error" ),
1253 wxOK | wxICON_EXCLAMATION | wxCENTER );
1254
1255 dlgBadFilePath.ShowModal();
1256 return false;
1257 }
1258 }
1259 else if( !fn.FileExists() )
1260 {
1261 // File doesn't exist yet; true if we just imported something
1262 updateFileHistory = true;
1263 }
1264 else if( screens.GetFirst() && screens.GetFirst()->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
1265 {
1266 // Allow the user to save un-edited files in new format
1267 }
1268 else if( !IsContentModified() )
1269 {
1270 return true;
1271 }
1272
1273 if( filenameMap.empty() || !saveCopy )
1274 {
1275 for( size_t i = 0; i < screens.GetCount(); i++ )
1276 filenameMap[screens.GetScreen( i )] = screens.GetScreen( i )->GetFileName();
1277 }
1278
1279 // Warn user on potential file overwrite. This can happen on shared sheets.
1280 wxArrayString overwrittenFiles;
1281 wxArrayString lockedFiles;
1282
1283 for( size_t i = 0; i < screens.GetCount(); i++ )
1284 {
1285 screen = screens.GetScreen( i );
1286
1287 wxCHECK2( screen, continue );
1288
1289 // Convert legacy schematics file name extensions for the new format.
1290 wxFileName tmpFn = filenameMap[screen];
1291
1292 if( !tmpFn.IsOk() )
1293 continue;
1294
1295 if( tmpFn.FileExists() && !tmpFn.IsFileWritable() )
1296 lockedFiles.Add( tmpFn.GetFullPath() );
1297
1298 if( tmpFn.GetExt() == FILEEXT::KiCadSchematicFileExtension )
1299 continue;
1300
1302
1303 if( tmpFn.FileExists() )
1304 overwrittenFiles.Add( tmpFn.GetFullPath() );
1305 }
1306
1307 if( !lockedFiles.IsEmpty() )
1308 {
1309 for( const wxString& lockedFile : lockedFiles )
1310 {
1311 if( msg.IsEmpty() )
1312 msg = lockedFile;
1313 else
1314 msg += "\n" + lockedFile;
1315 }
1316
1317 wxRichMessageDialog dlg( this, wxString::Format( _( "Failed to save %s." ),
1318 Schematic().Root().GetFileName() ),
1319 _( "Locked File Warning" ),
1320 wxOK | wxICON_WARNING | wxCENTER );
1321 dlg.SetExtendedMessage( _( "You do not have write permissions to:\n\n" ) + msg );
1322
1323 dlg.ShowModal();
1324 return false;
1325 }
1326
1327 if( !overwrittenFiles.IsEmpty() )
1328 {
1329 for( const wxString& overwrittenFile : overwrittenFiles )
1330 {
1331 if( msg.IsEmpty() )
1332 msg = overwrittenFile;
1333 else
1334 msg += "\n" + overwrittenFile;
1335 }
1336
1337 wxRichMessageDialog dlg( this, _( "Saving will overwrite existing files." ),
1338 _( "Save Warning" ),
1339 wxOK | wxCANCEL | wxCANCEL_DEFAULT | wxCENTER |
1340 wxICON_EXCLAMATION );
1341 dlg.ShowDetailedText( _( "The following files will be overwritten:\n\n" ) + msg );
1342 dlg.SetOKCancelLabels( KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Overwrite Files" ) ),
1343 KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Abort Project Save" ) ) );
1344
1345 if( dlg.ShowModal() == wxID_CANCEL )
1346 return false;
1347 }
1348
1349 screens.BuildClientSheetPathList();
1350
1351 std::vector<wxString> savedSheetPaths;
1352
1353 for( size_t i = 0; i < screens.GetCount(); i++ )
1354 {
1355 screen = screens.GetScreen( i );
1356
1357 wxCHECK2( screen, continue );
1358
1359 // Convert legacy schematics file name extensions for the new format.
1360 wxFileName tmpFn = filenameMap[screen];
1361
1362 if( tmpFn.IsOk() && tmpFn.GetExt() != FILEEXT::KiCadSchematicFileExtension )
1363 {
1364 updateFileHistory = true;
1366
1367 for( EDA_ITEM* item : screen->Items().OfType( SCH_SHEET_T ) )
1368 {
1369 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
1370 wxFileName sheetFileName = sheet->GetFileName();
1371
1372 if( !sheetFileName.IsOk()
1373 || sheetFileName.GetExt() == FILEEXT::KiCadSchematicFileExtension )
1374 continue;
1375
1376 sheetFileName.SetExt( FILEEXT::KiCadSchematicFileExtension );
1377 sheet->SetFileName( sheetFileName.GetFullPath() );
1378 UpdateItem( sheet );
1379 }
1380
1381 filenameMap[screen] = tmpFn.GetFullPath();
1382
1383 if( !saveCopy )
1384 screen->SetFileName( tmpFn.GetFullPath() );
1385 }
1386
1387 // Do not save sheet symbols with no valid filename set
1388 if( !tmpFn.IsOk() )
1389 continue;
1390
1391 std::vector<SCH_SHEET_PATH>& sheets = screen->GetClientSheetPaths();
1392
1393 if( sheets.size() == 1 )
1394 screen->SetVirtualPageNumber( 1 );
1395 else
1396 screen->SetVirtualPageNumber( 0 ); // multiple uses; no way to store the real sheet #
1397
1398 // This is a new schematic file so make sure it has a unique ID.
1399 if( !saveCopy && tmpFn.GetFullPath() != screen->GetFileName() )
1400 screen->AssignNewUuid();
1401
1402 bool savedThisSheet = saveSchematicFile( screens.GetSheet( i ), tmpFn.GetFullPath() );
1403
1404 if( savedThisSheet )
1405 savedSheetPaths.push_back( tmpFn.GetFullPath() );
1406
1407 success &= savedThisSheet;
1408 }
1409
1410 if( success )
1411 {
1412 if( m_autoSaveTimer )
1413 m_autoSaveTimer->Stop();
1414
1415 m_autoSavePending = false;
1416 m_autoSaveRequired = false;
1417
1418 LockFile( Schematic().RootScreen()->GetFileName() );
1419 }
1420
1421 if( updateFileHistory )
1422 UpdateFileHistory( Schematic().RootScreen()->GetFileName() );
1423
1424 // Save the sheet name map to the project file
1425 std::vector<FILE_INFO_PAIR>& sheets = Prj().GetProjectFile().GetSheets();
1426 sheets.clear();
1427
1428 for( SCH_SHEET_PATH& sheetPath : Schematic().Hierarchy() )
1429 {
1430 SCH_SHEET* sheet = sheetPath.Last();
1431
1432 wxCHECK2( sheet, continue );
1433
1434 // Do not save the virtual root sheet
1435 if( !sheet->IsVirtualRootSheet() )
1436 {
1437 sheets.emplace_back( std::make_pair( sheet->m_Uuid, sheet->GetName() ) );
1438 }
1439 }
1440
1441 wxASSERT( filenameMap.count( Schematic().RootScreen() ) );
1442 wxFileName projectPath( filenameMap.at( Schematic().RootScreen() ) );
1443 projectPath.SetExt( FILEEXT::ProjectFileExtension );
1444
1445 if( Prj().IsNullProject() || ( aSaveAs && !saveCopy ) )
1446 {
1447 Prj().SetReadOnly( !createNewProject );
1448 GetSettingsManager()->SaveProjectAs( projectPath.GetFullPath() );
1449 }
1450 else if( saveCopy && createNewProject )
1451 {
1452 GetSettingsManager()->SaveProjectCopy( projectPath.GetFullPath() );
1453 }
1454 else
1455 {
1458 }
1459
1460 // Record a full project snapshot so related files (symbols, libs, sheets) are captured.
1461 // Skip when running standalone without a project loaded - the save path can land
1462 // anywhere on the filesystem and there is no project context for a snapshot.
1463 if( success && !Prj().IsNullProject() )
1464 {
1465 Kiway().LocalHistory().RunRegisteredSaversAndCommit( Prj().GetProjectPath(), wxS( "SCH Save" ), wxS( "sch" ) );
1466
1467 // Drop the autosave files for the sheets we just persisted. Scope to those
1468 // sources so other dirty sheets (and any open PCB) keep their autosaves until
1469 // they are saved themselves; otherwise a Save All across editors would lose
1470 // recovery data for files this save did not write.
1471 // RunRegisteredSaversAndCommit above is a no-op when format is ZIP, and
1472 // RemoveAutosaveFiles is conversely a no-op in INCREMENTAL mode.
1473 Kiway().LocalHistory().RemoveAutosaveFiles( Prj().GetProjectPath(), savedSheetPaths );
1474 }
1475
1476 WX_STRING_REPORTER backupReporter;
1477
1478 if( !Kiface().IsSingle() )
1479 GetSettingsManager()->TriggerBackupIfNeeded( backupReporter );
1480
1481 // Restore the virtual page numbers that were modified during save. When saving, screens are
1482 // assigned page number 1 (single use) or 0 (multiple uses) for serialization purposes.
1483 // We restore all screens here, not just the current one, because other code paths (e.g.
1484 // ERC tree model, temporary sheet switches) may read any screen's virtual page number.
1485 for( const SCH_SHEET_PATH& sheet : Schematic().Hierarchy() )
1486 sheet.LastScreen()->SetVirtualPageNumber( sheet.GetVirtualPageNumber() );
1487
1489
1490 if( GetCanvas() && GetCanvas()->GetView() )
1491 {
1493 GetCanvas()->Refresh();
1494 }
1495
1496 updateTitle();
1497
1498 if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
1499 m_infoBar->Dismiss();
1500
1501 if( backupReporter.HasMessage() )
1502 {
1503 wxString backupMsg = backupReporter.GetMessages();
1504 m_infoBar->ShowMessageFor( backupMsg.Trim(), 10000, wxICON_WARNING );
1505 }
1506
1507 return success;
1508}
1509
1510
1511bool SCH_EDIT_FRAME::importFile( const wxString& aFileName, int aFileType,
1512 const std::map<std::string, UTF8>* aProperties )
1513{
1514 wxFileName filename( aFileName );
1515 wxFileName newfilename;
1516 SCH_IO_MGR::SCH_FILE_T fileType = (SCH_IO_MGR::SCH_FILE_T) aFileType;
1517
1518 wxCommandEvent changingEvt( EDA_EVT_SCHEMATIC_CHANGING );
1519 ProcessEventLocally( changingEvt );
1520
1521 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
1522 statusBar->ClearWarningMessages( "load" );
1523
1524 WX_STRING_REPORTER loadReporter;
1525 LOAD_INFO_REPORTER_SCOPE loadReporterScope( &loadReporter );
1526
1527 std::unique_ptr<SCHEMATIC> newSchematic = std::make_unique<SCHEMATIC>( &Prj() );
1528
1529 switch( fileType )
1530 {
1531 case SCH_IO_MGR::SCH_ALTIUM:
1532 case SCH_IO_MGR::SCH_CADSTAR_ARCHIVE:
1533 case SCH_IO_MGR::SCH_EAGLE:
1534 case SCH_IO_MGR::SCH_LTSPICE:
1535 case SCH_IO_MGR::SCH_EASYEDA:
1536 case SCH_IO_MGR::SCH_EASYEDAPRO:
1537 case SCH_IO_MGR::SCH_EASYEDAPRO_V3:
1538 case SCH_IO_MGR::SCH_PADS:
1539 case SCH_IO_MGR::SCH_GEDA:
1540 case SCH_IO_MGR::SCH_DIPTRACE:
1541 case SCH_IO_MGR::SCH_PCAD:
1542 case SCH_IO_MGR::SCH_ORCAD:
1543 {
1544 // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
1545 // Unless we are passing the files in aproperties, in which case aFileName can be empty.
1546 wxCHECK_MSG( aFileName.IsEmpty() || filename.IsAbsolute(), false,
1547 wxS( "Import schematic: path is not absolute!" ) );
1548
1549 try
1550 {
1551 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
1552 DIALOG_HTML_REPORTER errorReporter( this );
1553 WX_PROGRESS_REPORTER progressReporter( this, _( "Import Schematic" ), 1, PR_CAN_ABORT );
1554
1555 if( PROJECT_CHOOSER_PLUGIN* c_pi = dynamic_cast<PROJECT_CHOOSER_PLUGIN*>( pi.get() ) )
1556 {
1557 c_pi->RegisterCallback( std::bind( DIALOG_IMPORT_CHOOSE_PROJECT::RunModal,
1558 this, std::placeholders::_1 ) );
1559 }
1560
1561 if( eeconfig()->m_System.show_import_issues )
1562 pi->SetReporter( errorReporter.m_Reporter );
1563 else
1564 pi->SetReporter( &NULL_REPORTER::GetInstance() );
1565
1566 pi->SetProgressReporter( &progressReporter );
1567
1568 SCH_SHEET* loadedSheet = pi->LoadSchematicFile( aFileName, newSchematic.get(), nullptr,
1569 aProperties );
1570
1571 SetSchematic( newSchematic.release() );
1572
1574
1575 // SetSchematic() killed the previous schematic's history saver
1576 // So we need a new one for the new schematic
1578
1579 if( loadedSheet )
1580 {
1581 std::vector<SCH_SHEET*> topLevelSheets = Schematic().GetTopLevelSheets();
1582 bool loadedIsTopLevel = std::find( topLevelSheets.begin(), topLevelSheets.end(), loadedSheet )
1583 != topLevelSheets.end();
1584 bool loadedIsVirtualRoot = loadedSheet == &Schematic().Root()
1585 || loadedSheet->IsVirtualRootSheet();
1586
1587 // Some importers create the full top-level sheet set themselves. Do not collapse
1588 // that back to the returned sheet.
1589 if( !loadedIsTopLevel && !loadedIsVirtualRoot )
1590 Schematic().SetTopLevelSheets( { loadedSheet } );
1591
1592 // extract a project symbol library and re-link LIB_IDs so every symbol resolves
1593 ReconcileImportedSymbols( *pi, Schematic(), Prj(), aFileName, aProperties,
1594 loadReporter );
1595
1596 // re-link footprint fields to the project lib so update-from-schematic works
1597 {
1598 wxString cacheNick;
1599 std::vector<wxString> sourceFpLibs;
1600 IMPORT_PROJ_PROPS::ReadFootprintProps( aProperties, cacheNick, sourceFpLibs );
1601
1602 SCH_FOOTPRINT_FIELD_RECONCILER fpReconciler( cacheNick, sourceFpLibs,
1603 &loadReporter );
1604 fpReconciler.Reconcile( Schematic() );
1605 }
1606
1607 if( errorReporter.m_Reporter->HasMessage() )
1608 {
1609 errorReporter.m_Reporter->Flush(); // Build HTML messages
1610 errorReporter.ShowModal();
1611 }
1612
1613 const wxString drawingSheetName = Schematic().Settings().m_SchDrawingSheetFileName;
1614 const wxString embeddedPrefix = wxS( "kicad-embed://" );
1615 const EMBEDDED_FILES::EMBEDDED_FILE* embeddedWorksheet = nullptr;
1616
1617 if( drawingSheetName.StartsWith( embeddedPrefix ) )
1618 {
1619 embeddedWorksheet = Schematic().GetEmbeddedFiles()->GetEmbeddedFile(
1620 drawingSheetName.Mid( embeddedPrefix.length() ) );
1621 }
1622
1623 if( !embeddedWorksheet
1625 {
1628 }
1629 else
1630 {
1633 }
1634
1635 newfilename.SetPath( Prj().GetProjectPath() );
1636 newfilename.SetName( Prj().GetProjectName() );
1637 newfilename.SetExt( FILEEXT::KiCadSchematicFileExtension );
1638
1639 SetScreen( Schematic().RootScreen() );
1640
1641 if( SCH_SHEET* topSheet = Schematic().GetTopLevelSheet() )
1642 topSheet->SetFileName( newfilename.GetFullName() );
1643
1644 GetScreen()->SetFileName( newfilename.GetFullPath() );
1646
1647 progressReporter.Report( _( "Updating connections..." ) );
1648
1649 if( !progressReporter.KeepRefreshing() )
1651
1652 RecalculateConnections( nullptr, GLOBAL_CLEANUP, &progressReporter );
1653
1654 // Only perform the dangling end test on root sheet.
1656 }
1657 else
1658 {
1660 }
1661 }
1662 catch( const IO_ERROR& ioe )
1663 {
1664 // Do not leave g_RootSheet == NULL because it is expected to be
1665 // a valid sheet. Therefore create a dummy empty root sheet and screen.
1668
1669 wxString msg = wxString::Format( _( "Error loading schematic '%s'." ), aFileName );
1670 DisplayErrorMessage( this, msg, ioe.What() );
1671
1672 msg.Printf( _( "Failed to load '%s'." ), aFileName );
1673 SetMsgPanel( wxEmptyString, msg );
1674 }
1675 catch( const std::exception& exc )
1676 {
1679
1680 wxString msg = wxString::Format( _( "Unhandled exception occurred loading schematic "
1681 "'%s'." ), aFileName );
1682 DisplayErrorMessage( this, msg, exc.what() );
1683
1684 msg.Printf( _( "Failed to load '%s'." ), aFileName );
1685 SetMsgPanel( wxEmptyString, msg );
1686 }
1687
1690
1693 SyncView();
1694
1695 UpdateHierarchyNavigator( false, true );
1696 UpdateVariantSelectionCtrl( m_schematic->GetVariantNamesForUI() );
1697 SetCurrentVariant( m_schematic->GetCurrentVariant() );
1698
1699 CallAfter(
1700 [this]()
1701 {
1702 if( m_netNavigator && m_netNavigator->IsEmpty() )
1703 {
1705 }
1706 } );
1707
1708 wxCommandEvent e( EDA_EVT_SCHEMATIC_CHANGED );
1709 ProcessEventLocally( e );
1710
1711 for( wxEvtHandler* listener : m_schematicChangeListeners )
1712 {
1713 wxCHECK2( listener, continue );
1714
1715 // Use the windows variant when handling event messages in case there is any
1716 // special event handler pre and/or post processing specific to windows.
1717 wxWindow* win = dynamic_cast<wxWindow*>( listener );
1718
1719 if( win )
1720 win->HandleWindowEvent( e );
1721 else
1722 listener->SafelyProcessEvent( e );
1723 }
1724
1725 updateTitle();
1726
1727 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
1728 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
1729
1730 break;
1731 }
1732
1733 default:
1734 break;
1735 }
1736
1737 return true;
1738}
1739
1740
1742{
1743 SCH_SCREENS screenList( Schematic().Root() );
1744
1745 // Save any currently open and modified project files.
1746 for( SCH_SCREEN* screen = screenList.GetFirst(); screen; screen = screenList.GetNext() )
1747 {
1748 SIMULATOR_FRAME* simFrame = (SIMULATOR_FRAME*) Kiway().Player( FRAME_SIMULATOR, false );
1749
1750 // Simulator must be closed before loading another schematic, otherwise it may crash.
1751 // If there are any changes in the simulator the user will be prompted to save them.
1752 if( simFrame && !simFrame->Close() )
1753 return false;
1754
1755 if( screen->IsContentModified() )
1756 {
1757 if( !HandleUnsavedChanges( this, _( "The current schematic has been modified. "
1758 "Save changes?" ),
1759 [&]() -> bool
1760 {
1761 return SaveProject();
1762 } ) )
1763 {
1764 return false;
1765 }
1766 }
1767 }
1768
1769 return true;
1770}
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
static TOOL_ACTION zoomFitScreen
Definition actions.h:138
void SetVirtualPageNumber(int aPageNumber)
Definition base_screen.h:72
static wxString m_DrawingSheetFileName
the name of the drawing sheet file, or empty to use the default drawing sheet
Definition base_screen.h:81
void SetContentModified(bool aModified=true)
Definition base_screen.h:55
Class DIALOG_HTML_REPORTER.
WX_HTML_REPORT_BOX * m_Reporter
static std::vector< IMPORT_PROJECT_DESC > RunModal(wxWindow *aParent, const std::vector< IMPORT_PROJECT_DESC > &aProjectDesc)
Create and show a dialog (modal) and returns the data from it after completion.
static bool ShouldPrompt(int aFileFormatVersionAtLoad, size_t aBusesNeedingMigration)
Multiple differently-named labels on a single bus subgraph were only permitted before KiCad 6....
int ShowModal() override
static DS_DATA_MODEL & GetTheInstance()
Return the instance of DS_DATA_MODEL used in the application.
static const wxString & EmptyLayoutName()
Return the reserved drawing-sheet name that marks a design as deliberately having no sheet,...
void LoadWindowState(const wxString &aFileName)
void CheckForAutosaveFiles(const wxString &aProjectPath, const std::vector< wxString > &aExtensions)
Check for autosave files newer than their source files for the given project.
virtual void ClearUndoRedoList()
Clear the undo and redo list using ClearUndoORRedoList()
SETTINGS_MANAGER * GetSettingsManager() const
WX_INFOBAR * m_infoBar
wxTimer * m_autoSaveTimer
void UpdateFileHistory(const wxString &FullFileName, FILE_HISTORY *aFileHistory=nullptr)
Update the list of recently opened files.
wxString GetMruPath() const
bool IsWritable(const wxFileName &aFileName, bool aVerbose=true)
Check if aFileName can be written.
std::unique_ptr< LOCKFILE > m_file_checker
void SetMsgPanel(const std::vector< MSG_PANEL_ITEM > &aList)
Clear the message panel and populates it with the contents of aList.
void RefreshCanvas() override
bool LockFile(const wxString &aFileName)
Mark a schematic file as being in use.
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
const KIID m_Uuid
Definition eda_item.h:597
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
EMBEDDED_FILE * GetEmbeddedFile(const wxString &aName) const
Returns the embedded file with the given name or nullptr if it does not exist.
bool GetCreateNewProject() const
Gets the selected state of the copy subsheets option.
bool GetCopySubsheets() const
Gets the selected state of the include external sheets option.
bool GetIncludeExternSheets() const
Gets if this hook has attached controls to a dialog box.
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()
virtual const wxString Problem() const
what was the problem?
APP_SETTINGS_BASE * KifaceSettings() const
Definition kiface_base.h:91
bool IsSingle() const
Is this KIFACE running under single_top?
void RefreshDrawingSheetPageInfo()
Update the drawing sheet proxy's page number and first-page flag from the current edit frame state.
Definition sch_view.cpp:235
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
KISTATUSBAR is a wxStatusBar suitable for Kicad manager.
Definition kistatusbar.h:50
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:388
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:207
@ FACE_SCH
eeschema DSO
Definition kiway.h:347
LOCAL_HISTORY & LocalHistory()
Return the LOCAL_HISTORY associated with this KIWAY.
Definition kiway.h:451
A collection of #SYMBOL_LIB objects.
static void GetLibNamesAndPaths(PROJECT *aProject, wxString *aPaths, wxArrayString *aNames=nullptr)
static void SetLibNamesAndPaths(PROJECT *aProject, const wxString &aPaths, const wxArrayString &aNames)
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 SetDescription(const wxString &aDescription)
void SetURI(const wxString &aUri)
bool RunRegisteredSaversAndCommit(const wxString &aProjectPath, const wxString &aTitle, const wxString &aTagFileType=wxEmptyString)
Run all registered savers and, if any staged changes differ from HEAD, create a commit.
void RemoveAutosaveFiles(const wxString &aProjectPath) const
Remove every autosave file under the project at aProjectPath regardless of which source it shadowed.
static REPORTER & GetInstance()
Definition reporter.cpp:207
static wxString GetDefaultUserProjectsPath()
Gets the default path we point users to create projects.
Definition paths.cpp:137
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
Definition pgm_base.cpp:892
void HideSplash()
Definition pgm_base.cpp:307
A small class to help profiling.
Definition profile.h:46
void Show(std::ostream &aStream=std::cerr)
Print the elapsed time (in a suitable unit) to a stream.
Definition profile.h:103
virtual void Report(const wxString &aMessage) override
Display aMessage in the progress bar dialog.
bool KeepRefreshing(bool aWait=false) override
Update the UI dialog.
Plugin class for import plugins that support choosing a project.
The backing store for a PROJECT, in JSON format.
std::vector< FILE_INFO_PAIR > & GetSheets()
std::vector< TOP_LEVEL_SHEET_INFO > & GetTopLevelSheets()
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
static LEGACY_SYMBOL_LIBS * LegacySchLibs(PROJECT *aProject)
Returns the list of symbol libraries from a legacy (pre-5.x) design This is only used from the remapp...
virtual void SetReadOnly(bool aReadOnly=true)
Definition project.h:161
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:177
virtual void SetElem(PROJECT::ELEM aIndex, _ELEM *aElem)
Definition project.cpp:396
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:195
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
virtual const wxString AbsolutePath(const wxString &aFileName) const
Fix up aFileName if it is relative to the project's directory to be an absolute path and filename.
Definition project.cpp:407
@ LEGACY_SYMBOL_LIBS
Definition project.h:70
virtual bool HasMessage() const
Returns true if any messages were reported.
Definition reporter.h:143
Holds all the data relating to one schematic.
Definition schematic.h:148
void Reset()
Initialize this schematic to a blank one, unloading anything existing.
void ResolveERCExclusionsPostUpdate()
Update markers to match recorded exclusions.
void LoadVariants()
This is a throw away method for variant testing.
SCHEMATIC_SETTINGS & Settings() const
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
void SetProject(PROJECT *aPrj)
EMBEDDED_FILES * GetEmbeddedFiles() override
CONNECTION_GRAPH * ConnectionGraph() const
Definition schematic.h:317
SCH_SCREEN * RootScreen() const
Helper to retrieve the screen of the root sheet.
void SetTopLevelSheets(const std::vector< SCH_SHEET * > &aSheets)
Replace the top level sheets, rebuilding the hierarchy and connectivity around them.
SCH_SHEET & Root() const
Definition schematic.h:199
std::vector< SCH_SHEET * > GetTopLevelSheets() const
Get the list of top-level sheets.
int FixupJunctionsAfterImport(const std::function< void(SCH_LINE *, SCH_LINE *)> &aOnSplit={})
Add junctions to this schematic where required.
SCH_DRAW_PANEL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
void SyncView()
Mark all items for refresh.
EESCHEMA_SETTINGS * eeconfig() const
Class for a bus to bus entry.
VECTOR2I GetPosition() const override
VECTOR2I GetEnd() const
KIGFX::SCH_VIEW * GetView() const override
Return a pointer to the #VIEW instance used in the panel.
void DisplaySheet(SCH_SCREEN *aScreen)
bool IsContentModified() const override
Get if the current schematic has been modified but not saved.
void RecalculateConnections(SCH_COMMIT *aCommit, SCH_CLEANUP_FLAGS aCleanupFlags, PROGRESS_REPORTER *aProgressReporter=nullptr, bool aCleanupDone=false)
Generate the connection data for the entire schematic hierarchy.
void OnModify() override
Must be called after a schematic change in order to set the "modify" flag and update other data struc...
void SaveProjectLocalSettings() override
Save changes to the project settings to the project (.pro) file.
bool OpenProjectFiles(const std::vector< wxString > &aFileSet, int aCtl=0) override
Open a project or set of files given by aFileList.
SCH_SCREEN * GetScreen() const override
Return a pointer to a BASE_SCREEN or one of its derivatives.
void SetScreen(BASE_SCREEN *aScreen) override
bool AskToSaveChanges()
Check if any of the screens has unsaved changes and asks the user whether to save or drop them.
friend class SCH_EDITOR_CONTROL
void SetCurrentVariant(const wxString &aVariantName)
void UpdateVariantSelectionCtrl(const wxArrayString &aVariantNames)
Update the variant name control on the main toolbar.
std::vector< wxEvtHandler * > m_schematicChangeListeners
PANEL_REMOTE_SYMBOL * m_remoteSymbolPane
SCHEMATIC * m_schematic
The currently loaded schematic.
SCH_SHEET_PATH & GetCurrentSheet() const
void ProjectChanged() override
Notification event that the project has changed.
SCHEMATIC & Schematic() const
void updateTitle()
Set the main window title bar text.
void SetSchematic(SCHEMATIC *aSchematic)
bool saveSchematicFile(SCH_SHEET *aSheet, const wxString &aSavePath)
Save aSheet to a schematic file.
bool LoadProjectSettings()
Load the KiCad project file (*.pro) settings specific to Eeschema.
void RefreshNetNavigator(const NET_NAVIGATOR_ITEM_DATA *aSelection=nullptr)
void RecomputeIntersheetRefs()
Update the schematic's page reference map for all global labels, and refresh the labels so that they ...
void UpdateHierarchyNavigator(bool aRefreshNetNavigator=true, bool aClear=false)
Update the hierarchy navigation tree and history.
bool importFile(const wxString &aFileName, int aFileType, const std::map< std::string, UTF8 > *aProperties=nullptr)
Load the given filename but sets the path to the current project path.
void LoadDrawingSheet()
Load the drawing sheet file.
void SetSheetNumberAndCount()
Set the m_ScreenNumber and m_NumberOfScreens members for screens.
void ClearRepeatItemsList()
Clear the list of items which are to be repeated with the insert key.
wxGenericTreeCtrl * m_netNavigator
void initScreenZoom()
Initialize the zoom value of the current screen and mark the screen as zoom-initialized.
void UpdateItem(EDA_ITEM *aItem, bool isAddOrDelete=false, bool aUpdateRtree=false) override
Mark an item for refresh.
wxString GetCurrentFileName() const override
Get the full filename + path of the currently opened file in the frame.
void TestDanglingEnds()
Test all of the connectable objects in the schematic for unused connection points.
bool SaveProject(bool aSaveAs=false)
Save the currently-open schematic (including its hierarchy) and associated project.
void saveProjectSettings() override
Save any design-related project settings associated with this frame.
Frame-independent, non-interactive service that rewrites the library nickname of every schematic symb...
SCH_FP_FIELD_RECONCILE_RESULT Reconcile(SCHEMATIC &aSchematic)
static const wxString ShowType(SCH_FILE_T aFileType)
Return a brief name for a plugin, given aFileType enum.
static SCH_FILE_T GuessPluginTypeFromSchPath(const wxString &aSchematicPath, int aCtl=0)
Return a plugin type given a schematic using the file extension of aSchematicPath.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:165
Handle actions specific to the schematic editor.
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:758
SCH_SCREEN * GetNext()
SCH_SCREEN * GetScreen(unsigned int aIndex) const
void UpdateSymbolLinks(REPORTER *aReporter=nullptr)
Initialize the LIB_SYMBOL reference for each SCH_SYMBOL found in the full schematic.
SCH_SCREEN * GetFirst()
void PruneOrphanedSheetInstances(const wxString &aProjectName, const SCH_SHEET_LIST &aValidSheetPaths)
void BuildClientSheetPathList()
Build the list of sheet paths sharing a screen for each screen in use.
bool HasSymbolFieldNamesWithWhiteSpace() const
size_t GetCount() const
Definition sch_screen.h:763
void PruneOrphanedSymbolInstances(const wxString &aProjectName, const SCH_SHEET_LIST &aValidSheetPaths)
bool HasNoFullyDefinedLibIds()
Test all of the schematic symbols to see if all LIB_ID objects library nickname is not set.
SCH_SHEET * GetSheet(unsigned int aIndex) const
int ReplaceDuplicateTimeStamps()
Test all sheet and symbol objects in the schematic for duplicate time stamps and replaces them as nec...
void ClearDrawingState()
Clear the state flags of all the items in the screen.
std::vector< SCH_SHEET_PATH > & GetClientSheetPaths()
Return the number of times this screen is used.
Definition sch_screen.h:191
void TestDanglingEnds(const SCH_SHEET_PATH *aPath=nullptr, std::function< void(SCH_ITEM *)> *aChangedHandler=nullptr) const
Test all of the connectable objects in the schematic for unused connection points.
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:118
const wxString & GetFileName() const
Definition sch_screen.h:153
void UpdateLocalLibSymbolLinks()
Initialize the LIB_SYMBOL reference for each SCH_SYMBOL found in this schematic with the local projec...
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
const std::vector< SCH_SYMBOL_INSTANCE > & GetSymbolInstances() const
Definition sch_screen.h:530
int GetFileFormatVersionAtLoad() const
Definition sch_screen.h:138
void AssignNewUuid()
Definition sch_screen.h:542
const std::vector< SCH_SHEET_INSTANCE > & GetSheetInstances() const
Definition sch_screen.h:535
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
void UpdateSheetInstanceData(const std::vector< SCH_SHEET_INSTANCE > &aSheetInstances)
Update all of the sheet instance information using aSheetInstances.
void SetInitialPageNumbers()
Set initial sheet page numbers.
bool AllSheetPageNumbersEmpty() const
Check all of the sheet instance for empty page numbers.
bool IsModified() const
Check the entire hierarchy for any modifications.
void UpdateSymbolInstanceData(const std::vector< SCH_SYMBOL_INSTANCE > &aSymbolInstances)
Update all of the symbol instance information using aSymbolInstances.
bool RepairPageNumbers()
Assign valid page numbers to sheet paths whose stored page number is missing or collides with an earl...
void CheckForMissingSymbolInstances(const wxString &aProjectName)
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
void UpdateAllScreenReferences() const
Update all the symbol references for this sheet path.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:48
void SetFileName(const wxString &aFilename)
Definition sch_sheet.h:390
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:384
wxString GetName() const
Definition sch_sheet.h:142
void SetName(const wxString &aName)
Definition sch_sheet.h:143
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:145
bool IsVirtualRootSheet() const
void SaveProjectAs(const wxString &aFullPath, PROJECT *aProject=nullptr)
Set the currently loaded project path and saves it (pointers remain valid).
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
bool SaveProjectCopy(const wxString &aFullPath, PROJECT *aProject=nullptr)
Save a copy of the current project under the given path.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Load a project or sets up a new project with a specified path.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
bool TriggerBackupIfNeeded(REPORTER &aReporter) const
Call BackupProject() if a new backup is needed according to the current backup policy.
The SIMULATOR_FRAME holds the main user-interface for running simulations.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
TOOL_MANAGER * m_toolManager
@ SUPERMODEL_RELOAD
For schematics, the entire schematic changed, not just the sheet.
Definition tool_base.h:77
Temporarily disable a window, and then re-enable on destruction.
Definition raii.h:83
static void ResolvePossibleSymlinks(wxFileName &aFilename)
void Flush()
Build the HTML messages page.
bool HasMessage() const override
Returns true if any messages were reported.
Multi-thread safe progress reporter dialog, intended for use of tasks that parallel reporting back of...
A wrapper for reporting to a wxString object.
Definition reporter.h:242
const wxString & GetMessages() const
Definition reporter.cpp:188
wxString EnsureFileExtension(const wxString &aFilename, const wxString &aExtension)
It's annoying to throw up nag dialogs when the extension isn't right.
Definition common.cpp:848
bool AskOverrideLock(wxWindow *aParent, const wxString &aMessage)
Display a dialog indicating the file is already open, with an option to reset the lock.
Definition confirm.cpp:38
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
bool HandleUnsavedChanges(wxWindow *aParent, const wxString &aMessage, const std::function< bool()> &aSaveFunction)
Display a dialog with Save, Cancel and Discard Changes buttons.
Definition confirm.cpp:146
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:192
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
Definition confirm.h:48
static bool empty(const wxTextEntryBase *aCtrl)
#define _(s)
bool PrepareSaveAsFiles(SCHEMATIC &aSchematic, SCH_SCREENS &aScreens, const wxFileName &aOldRoot, const wxFileName &aNewRoot, bool aSaveCopy, bool aCopySubsheets, bool aIncludeExternSheets, std::unordered_map< SCH_SCREEN *, wxString > &aFilenameMap, wxString &aErrorMsg)
void Reset() override
@ FRAME_SIMULATOR
Definition frame_type.h:34
static const std::string LegacySchematicFileExtension
static const std::string ProjectFileExtension
static const std::string LegacyProjectFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string LegacySymbolLibFileExtension
static wxString KiCadSchematicFileWildcard()
const wxChar *const traceSchCurrentSheet
Flag to enable debug output of current sheet tracking in the schematic editor.
const wxChar *const traceAutoSave
Flag to enable auto save feature debug tracing.
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
#define THROW_IO_CANCELLED()
PROJECT & Prj()
Definition kicad.cpp:727
KIID niluuid(0)
#define KICTL_CREATE
caller thinks requested project files may not exist.
#define KICTL_KICAD_ONLY
chosen file is from KiCad according to user
@ LAYER_BUS
Definition layer_ids.h:475
int ReconcileLegacyCacheSymbols(SYMBOL_LIBRARY_ADAPTER &aAdapter, const wxString &aCacheNickname, SCH_SCREENS &aScreens, std::vector< KI_ERROR > &aErrors)
Point symbols that are only available in a legacy project cache library at that cache.
File locking utilities.
void ReadFootprintProps(const std::map< std::string, UTF8 > *aProps, wxString &aCacheNickname, std::vector< wxString > &aSourceFpLibs)
Read the footprint-import coordination properties out of a properties map.
void SetShutdownBlockReason(wxWindow *aWindow, const wxString &aReason)
Sets the block reason why the window/application is preventing OS shutdown.
Definition unix/app.cpp:102
bool RegisterApplicationRestart(const wxString &aCommandLine)
Registers the application for restart with the OS with the given command line string to pass as args.
Definition unix/app.cpp:77
bool MakeWriteable(const wxString &aFilePath)
Ensures that a file has write permissions.
Definition unix/io.cpp:78
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:521
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
#define SKIP_CONNECTIVITY
Definition sch_commit.h:41
#define SKIP_SET_DIRTY
Definition sch_commit.h:40
#define DELETE_REMOVED_ITEMS
Definition sch_commit.h:43
#define SKIP_UNDO
Definition sch_commit.h:38
#define SEXPR_SCHEMATIC_FILE_VERSION
Schematic file version.
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
@ GLOBAL_CLEANUP
Definition schematic.h:94
KIWAY Kiway(KFCTL_STANDALONE)
std::vector< FAB_LAYER_COLOR > dummy
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
bool show_import_issues
Stored value for "show import issues" when importing non-KiCad designs to this application.
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
Container that describes file type info.
Definition io_base.h:43
std::vector< std::string > m_FileExtensions
Filter used for file pickers if m_IsFile is true.
Definition io_base.h:47
bool m_CanRead
Whether the IO can read this file type.
Definition io_base.h:52
wxString FileFilter() const
Definition io_base.cpp:40
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
virtual void PreloadLibraries(KIWAY *aKiway)
Definition kiway.h:290
Information about a top-level schematic sheet.
SYMBOL_IMPORT_RECONCILE_RESULT ReconcileImportedSymbols(SCH_IO &aPlugin, SCHEMATIC &aSchematic, PROJECT &aProject, const wxString &aSchematicPath, const std::map< std::string, UTF8 > *aProperties, REPORTER &aReporter)
Reconcile aSchematic against the definitions aPlugin retained while loading it.
std::string path
wxLogTrace helper definitions.
@ SCH_SHEET_T
Definition typeinfo.h:171
@ SCH_BUS_BUS_ENTRY_T
Definition typeinfo.h:158
wxString formatWildcardExt(const wxString &aWildcard)
Format wildcard extension to support case sensitive file dialogs.
Definition of file extensions used in Kicad.
#define PR_CAN_ABORT