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>
69#include <tools/sch_actions.h>
72#include <trace_helpers.h>
74#include <widgets/kistatusbar.h>
75#include <widgets/wx_infobar.h>
77#include <local_history.h>
79#include <wx/app.h>
80#include <wx/ffile.h>
81#include <wx/filedlg.h>
82#include <wx/log.h>
83#include <wx/richmsgdlg.h>
84#include <wx/stdpaths.h>
87#include <paths.h>
88#include <wx_filename.h> // For ::ResolvePossibleSymlinks
91
92#include <kiplatform/io.h>
93
96#include "save_project_utils.h"
97
98
100{
101 wxString file = Schematic().GetFileName();
102
103 if( file.IsEmpty() )
104 return false;
105
106 // Resolve the filename before changing sheets.
107 file = Prj().AbsolutePath( file );
108
109 // A pull can replace the first top-level sheet, and the load follows the project's list anyway
110 bool legacy = wxFileName( file ).GetExt() == FILEEXT::LegacySchematicFileExtension;
111
112 for( const TOP_LEVEL_SHEET_INFO& info : Prj().GetProjectFile().GetTopLevelSheets() )
113 {
114 wxFileName listed = SCHEMATIC::TopLevelSheetFile( info, Prj().GetProjectPath(), legacy );
115
116 if( listed.IsFileReadable() )
117 {
118 file = listed.GetFullPath();
119 break;
120 }
121 }
122
123 if( GetCurrentSheet().Last() != &Schematic().Root() )
124 {
125 // Use the hierarchy's root path so it includes the root sheet's KIID.
126 SCH_SHEET_PATH rootSheetPath = Schematic().Hierarchy().at( 0 );
128 }
129
130 // The caller already handled confirmation, so skip the save prompt.
131 SCH_SCREENS screens( Schematic().Root() );
132
133 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
134 screen->SetContentModified( false );
135
136 ReleaseFile();
137 return OpenProjectFiles( std::vector<wxString>( 1, file ), KICTL_REVERT );
138}
139
140
141bool SCH_EDIT_FRAME::ConfirmReloadFromDisk( const wxString& aMessage, const wxString& aTitle )
142{
143 if( !IsContentModified() )
144 return true;
145
146 wxMessageDialog dlg( this, aMessage, aTitle, wxYES_NO | wxNO_DEFAULT | wxICON_WARNING | wxCENTER );
147 dlg.SetYesNoLabels( _( "&Reload" ), _( "&Keep My Edits" ) );
148
149 return dlg.ShowModal() == wxID_YES;
150}
151
152
154{
155 PROJECT_FILE& projectFile = Prj().GetProjectFile();
156
157 if( !projectFile.TopLevelSheetsChangedOnLoad() )
158 return false;
159
160 // A list that only spells the open sheets differently is settled, so a later local edit is not taken for it
161 if( Schematic().TopLevelSheetsMatch( projectFile.GetTopLevelSheets() ) )
162 {
163 projectFile.AcknowledgeTopLevelSheetChange();
164 return false;
165 }
166
167 return true;
168}
169
170
171bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
172{
173 // ensure the splash screen does not obscure any dialog at startup
174 Pgm().HideSplash();
175
176 // implement the pseudo code from KIWAY_PLAYER.h:
177 wxString msg;
178
179 EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() );
180
181 // This is for python:
182 if( aFileSet.size() != 1 )
183 {
184 msg.Printf( "Eeschema:%s() takes only a single filename.", __WXFUNCTION__ );
185 DisplayError( this, msg );
186 return false;
187 }
188
189 wxString fullFileName( aFileSet[0] );
190 wxFileName wx_filename( fullFileName );
191
192 // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
193 wxASSERT_MSG( wx_filename.IsAbsolute(), wxS( "Path is not absolute!" ) );
194
195 if( !LockFile( fullFileName ) )
196 {
197 // If project-level lock override was already granted, silently override this file's lock
198 if( Prj().IsLockOverrideGranted() )
199 {
200 m_file_checker->OverrideLock();
201 }
202 else
203 {
204 msg.Printf( _( "Schematic '%s' is already open by '%s' at '%s'." ), fullFileName,
205 m_file_checker->GetUsername(), m_file_checker->GetHostname() );
206
207 if( !AskOverrideLock( this, msg ) )
208 return false;
209
210 m_file_checker->OverrideLock();
211 }
212 }
213
214 if( !AskToSaveChanges() )
215 return false;
216
217#ifdef PROFILE
218 PROF_TIMER openFiles( "OpenProjectFile" );
219#endif
220
221 wxFileName pro = fullFileName;
222 pro.SetExt( FILEEXT::ProjectFileExtension );
223
224 bool is_new = !wxFileName::IsFileReadable( fullFileName );
225
226 // If its a non-existent schematic and caller thinks it exists
227 if( is_new && !( aCtl & KICTL_CREATE ) )
228 {
229 // notify user that fullFileName does not exist, ask if user wants to create it.
230 msg.Printf( _( "Schematic '%s' does not exist. Do you wish to create it?" ), fullFileName );
231
232 if( !IsOK( this, msg ) )
233 return false;
234 }
235
236 wxCommandEvent e( EDA_EVT_SCHEMATIC_CHANGING );
237 ProcessEventLocally( e );
238
239 // unload current project file before loading new
240 {
243 SetScreen( nullptr );
245 }
246
247 SetStatusText( wxEmptyString );
248 m_infoBar->Dismiss();
249
250 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
251 statusBar->ClearWarningMessages( "load" );
252
253 WX_PROGRESS_REPORTER progressReporter( this, is_new ? _( "Create Schematic" ) : _( "Load Schematic" ), 1,
254 PR_CAN_ABORT );
255 WX_STRING_REPORTER loadReporter;
256 LOAD_INFO_REPORTER_SCOPE loadReporterScope( &loadReporter );
257
258 // A revert reloads the open project, whose first top-level sheet need not share its name
259 bool differentProject = !( aCtl & KICTL_REVERT ) && pro.GetFullPath() != Prj().GetProjectFullName();
260
261 // This is for handling standalone mode schematic changes
262 if( differentProject )
263 {
264 if( !Prj().IsNullProject() )
265 {
268 }
269
270 // disconnect existing project from schematic before we unload the project
271 Schematic().SetProject( nullptr );
272 GetSettingsManager()->UnloadProject( &Prj(), false );
273
274 GetSettingsManager()->LoadProject( pro.GetFullPath() );
275
276 wxFileName legacyPro( pro );
277 legacyPro.SetExt( FILEEXT::LegacyProjectFileExtension );
278
279 // Do not allow saving a project if one doesn't exist. This normally happens if we are
280 // standalone and opening a schematic that has been moved from its project folder.
281 if( !pro.Exists() && !legacyPro.Exists() && !( aCtl & KICTL_CREATE ) )
282 Prj().SetReadOnly();
283 }
284
285 // Crash-recovery: when zip-format autosave is active, look for autosave files newer
286 // than the saved schematic and offer to recover them before any sheet is loaded.
287 if( !is_new )
288 CheckForAutosaveFiles( wx_filename.GetPath(), { FILEEXT::KiCadSchematicFileExtension } );
289
290 // Start a new schematic object now that we sorted out our project
291 std::unique_ptr<SCHEMATIC> newSchematic = std::make_unique<SCHEMATIC>( &Prj() );
292
293 SCH_IO_MGR::SCH_FILE_T schFileType = SCH_IO_MGR::GuessPluginTypeFromSchPath( fullFileName, aCtl );
294
295 bool isNonKicadImport = schFileType != SCH_IO_MGR::SCH_KICAD
296 && schFileType != SCH_IO_MGR::SCH_LEGACY
297 && schFileType != SCH_IO_MGR::SCH_FILE_UNKNOWN;
298
299 // If this is a recognised non-KiCad format, delegate to the import path.
300 // Callers that pass KICTL_KICAD_ONLY (e.g. GUI open) won't reach
301 // this branch because GuessPluginTypeFromSchPath already returns SCH_FILE_UNKNOWN
302 // for these formats.
303 if( isNonKicadImport )
304 {
305 progressReporter.Hide();
306 return importFile( fullFileName, schFileType, nullptr );
307 }
308
309 if( schFileType == SCH_IO_MGR::SCH_LEGACY )
310 {
311 // Don't reload the symbol libraries if we are just launching Eeschema from KiCad again.
312 // They are already saved in the kiface project object.
313 if( differentProject || !Prj().GetElem( PROJECT::ELEM::LEGACY_SYMBOL_LIBS ) )
314 {
315 // load the libraries here, not in SCH_SCREEN::Draw() which is a context
316 // that will not tolerate DisplayError() dialog since we're already in an
317 // event handler in there.
318 // And when a schematic file is loaded, we need these libs to initialize
319 // some parameters (links to PART LIB, dangling ends ...)
322 }
323 }
324 else
325 {
326 // No legacy symbol libraries including the cache are loaded with the new file format.
328 }
329
330 wxFileName rfn( fullFileName );
331 rfn.MakeRelativeTo( Prj().GetProjectPath() );
332 LoadWindowState( rfn.GetFullPath() );
333
334 KIPLATFORM::APP::SetShutdownBlockReason( this, _( "Schematic file changes are unsaved" ) );
335
336 if( Kiface().IsSingle() )
337 {
339 }
340
341 if( is_new || schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
342 {
343 newSchematic->CreateDefaultScreens();
344 SetSchematic( newSchematic.release() );
345
346 // mark new, unsaved file as modified.
348 GetScreen()->SetFileName( fullFileName );
349
350 if( schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
351 {
352 if( aCtl & KICTL_KICAD_ONLY )
353 {
354 msg.Printf( _( "'%s' is not a KiCad schematic file.\n"
355 "Use File -> Import for non-KiCad schematic files." ), fullFileName );
356 }
357 else
358 {
359 // Even the non-KiCad plugin type didn't know
360 msg.Printf( _( "'%s' is not a recognised schematic format." ), fullFileName );
361 }
362
363 progressReporter.Hide();
364 DisplayErrorMessage( this, msg );
365 }
366 }
367 else
368 {
369 SetScreen( nullptr );
370
371 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( schFileType ) );
372
373 pi->SetProgressReporter( &progressReporter );
374
375 bool failedLoad = false;
376
377 try
378 {
379 {
380 wxBusyCursor busy;
381 WINDOW_DISABLER raii( this );
382
383 // Check if project file has top-level sheets defined
384 PROJECT_FILE& projectFile = Prj().GetProjectFile();
385 const std::vector<TOP_LEVEL_SHEET_INFO>& topLevelSheets = projectFile.GetTopLevelSheets();
386
387 if( !topLevelSheets.empty() )
388 {
389 std::vector<SCH_SHEET*> loadedSheets;
390
391 // Load each top-level sheet
392 for( const TOP_LEVEL_SHEET_INFO& sheetInfo : topLevelSheets )
393 {
394 wxString sheetPath = SCHEMATIC::TopLevelSheetFile( sheetInfo, Prj().GetProjectPath(),
395 schFileType == SCH_IO_MGR::SCH_LEGACY )
396 .GetFullPath();
397
398 if( !wxFileName::FileExists( sheetPath ) )
399 {
400 wxLogWarning( wxT( "Top-level sheet file not found: %s" ), sheetPath );
401 continue;
402 }
403
404 SCH_SHEET* sheet = pi->LoadSchematicFile( sheetPath, newSchematic.get() );
405
406 if( sheet )
407 {
408 // Preserve the UUID from the project file, unless it's niluuid which is
409 // just a placeholder meaning "use the UUID from the file"
410 if( sheetInfo.uuid != niluuid )
411 {
412 const_cast<KIID&>( sheet->m_Uuid ) = sheetInfo.uuid;
413 }
414
415 sheet->SetName( sheetInfo.name );
416 loadedSheets.push_back( sheet );
417
418 wxLogTrace( tracePathsAndFiles, wxS( "Loaded top-level sheet '%s' (UUID %s) from %s" ),
419 sheet->GetName(), sheet->m_Uuid.AsString(), sheetPath );
420 }
421 }
422
423 if( !loadedSheets.empty() )
424 {
425 newSchematic->SetTopLevelSheets( loadedSheets );
426 }
427 else
428 {
429 wxLogTrace( tracePathsAndFiles,
430 wxS( "Loaded multi-root schematic with no top-level sheets!" ) );
431 newSchematic->CreateDefaultScreens();
432 }
433 }
434 else
435 {
436 // Legacy single-root format: Load the single root sheet
437 SCH_SHEET* rootSheet = pi->LoadSchematicFile( fullFileName, newSchematic.get() );
438
439 if( rootSheet )
440 {
441 newSchematic->SetTopLevelSheets( { rootSheet } );
442
443 // Make ${SHEETNAME} work on the root sheet until we properly support
444 // naming the root sheet
445 if( SCH_SHEET* topSheet = newSchematic->GetTopLevelSheet() )
446 topSheet->SetName( _( "Root" ) );
447
448 wxLogTrace( tracePathsAndFiles, wxS( "Loaded schematic with root sheet UUID %s" ),
449 rootSheet->m_Uuid.AsString() );
450 wxLogTrace( traceSchCurrentSheet,
451 wxS( "After loading: Current sheet path='%s', size=%zu, empty=%d" ),
452 newSchematic->CurrentSheet().Path().AsString(),
453 newSchematic->CurrentSheet().size(),
454 newSchematic->CurrentSheet().empty() ? 1 : 0 );
455 }
456 else
457 {
458 newSchematic->CreateDefaultScreens();
459 }
460
461 }
462 }
463
464 if( !pi->GetError().IsEmpty() )
465 {
466 DisplayErrorMessage( this, _( "The entire schematic could not be loaded. Errors "
467 "occurred attempting to load hierarchical sheets." ),
468 pi->GetError() );
469 }
470 }
471 catch( const FUTURE_FORMAT_ERROR& ffe )
472 {
473 newSchematic->CreateDefaultScreens();
474 msg.Printf( _( "Error loading schematic '%s'." ), fullFileName );
475 progressReporter.Hide();
476 DisplayErrorMessage( this, msg, ffe.Problem() );
477
478 failedLoad = true;
479 }
480 catch( const IO_ERROR& ioe )
481 {
482 newSchematic->CreateDefaultScreens();
483 msg.Printf( _( "Error loading schematic '%s'." ), fullFileName );
484 progressReporter.Hide();
485 DisplayErrorMessage( this, msg, ioe.What() );
486
487 failedLoad = true;
488 }
489 catch( const std::bad_alloc& )
490 {
491 newSchematic->CreateDefaultScreens();
492 msg.Printf( _( "Memory exhausted loading schematic '%s'." ), fullFileName );
493 progressReporter.Hide();
494 DisplayErrorMessage( this, msg, wxEmptyString );
495
496 failedLoad = true;
497 }
498
499 SetSchematic( newSchematic.release() );
500
501 // This fixes a focus issue after the progress reporter is done on GTK. It shouldn't
502 // cause any issues on macOS and Windows. If it does, it will have to be conditionally
503 // compiled.
504 Raise();
505
506 if( failedLoad )
507 {
508 // Do not leave g_RootSheet == NULL because it is expected to be
509 // a valid sheet. Therefore create a dummy empty root sheet and screen.
512
513 // Show any messages collected before the failure
514 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
515 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
516
517 msg.Printf( _( "Failed to load '%s'." ), fullFileName );
518 SetMsgPanel( wxEmptyString, msg );
519
520 return false;
521 }
522
523 // Load project settings after schematic has been set up with the project link, since this will
524 // update some of the needed schematic settings such as drawing defaults
526
527 SCH_SHEET_LIST sheetList = Schematic().Hierarchy();
528
529 bool repairedPageNumbers = false;
530
531 if( sheetList.AllSheetPageNumbersEmpty() )
532 sheetList.SetInitialPageNumbers();
533 else
534 repairedPageNumbers = sheetList.RepairPageNumbers();
535
536 // It's possible the schematic parser fixed errors due to bugs, or that we reassigned
537 // duplicate or blank sheet page numbers, so warn the user that the schematic has been
538 // fixed (modified).
539 if( sheetList.IsModified() || repairedPageNumbers )
540 {
541 DisplayInfoMessage( this, _( "An error was found when loading the schematic that has been "
542 "automatically fixed. Please save the schematic to repair the "
543 "broken file or it may not be usable with other versions of "
544 "KiCad." ) );
545 }
546
547 UpdateFileHistory( fullFileName );
548
549 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
550 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
551
552 SCH_SCREENS schematic( Schematic().Root() );
553
554 // LIB_ID checks and symbol rescue only apply to the legacy file formats.
555 if( schFileType == SCH_IO_MGR::SCH_LEGACY )
556 {
557 // Convert any legacy bus-bus entries to just be bus wires
558 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
559 {
560 std::vector<SCH_ITEM*> deleted;
561
562 for( SCH_ITEM* item : screen->Items() )
563 {
564 if( item->Type() == SCH_BUS_BUS_ENTRY_T )
565 {
566 SCH_BUS_BUS_ENTRY* entry = static_cast<SCH_BUS_BUS_ENTRY*>( item );
567 std::unique_ptr<SCH_LINE> wire = std::make_unique<SCH_LINE>();
568
569 wire->SetLayer( LAYER_BUS );
570 wire->SetStartPoint( entry->GetPosition() );
571 wire->SetEndPoint( entry->GetEnd() );
572
573 screen->Append( wire.release() );
574 deleted.push_back( item );
575 }
576 }
577
578 for( SCH_ITEM* item : deleted )
579 screen->Remove( item );
580 }
581
582
583 // Convert old projects over to use symbol library table.
584 if( schematic.HasNoFullyDefinedLibIds() )
585 {
586 DIALOG_SYMBOL_REMAP dlgRemap( this );
587
588 dlgRemap.ShowQuasiModal();
589 }
590 else
591 {
592 // Double check to ensure no legacy library list entries have been
593 // added to the project file symbol library list.
594 wxString paths;
595 wxArrayString libNames;
596
597 LEGACY_SYMBOL_LIBS::GetLibNamesAndPaths( &Prj(), &paths, &libNames );
598
599 if( !libNames.IsEmpty() )
600 {
601 if( eeconfig()->m_Appearance.show_illegal_symbol_lib_dialog )
602 {
603 wxRichMessageDialog dlg( this,
604 _( "Illegal entry found in project file symbol library list." ),
605 _( "Project Load Warning" ),
606 wxOK | wxCENTER | wxICON_EXCLAMATION );
607 dlg.ShowDetailedText( _( "Symbol libraries defined in the project file symbol library "
608 "list are no longer supported and will be removed.\n\n"
609 "This may cause broken symbol library links under certain "
610 "conditions." ) );
611 dlg.ShowCheckBox( _( "Do not show this dialog again." ) );
612 dlg.ShowModal();
613 eeconfig()->m_Appearance.show_illegal_symbol_lib_dialog = !dlg.IsCheckBoxChecked();
614 }
615
616 libNames.Clear();
617 paths.Clear();
618 LEGACY_SYMBOL_LIBS::SetLibNamesAndPaths( &Prj(), paths, libNames );
619 }
620
621 // Check for cache file
622 wxFileName cacheFn( fullFileName );
623 cacheFn.SetName( cacheFn.GetName() + "-cache" );
625 bool cacheExists = cacheFn.FileExists();
626
627 if( cacheExists )
628 {
630 std::optional<LIBRARY_TABLE*> table = adapter->ProjectTable();
631
632 if( table && *table )
633 {
634 wxString nickname = Prj().GetProjectName() + "-cache";
635
636 if( !(*table)->HasRow( nickname ) )
637 {
638 LIBRARY_TABLE_ROW& row = (*table)->InsertRow();
639 row.SetNickname( nickname );
640 row.SetURI( cacheFn.GetFullPath() );
641 row.SetType( SCH_IO_MGR::ShowType( SCH_IO_MGR::SCH_LEGACY ) );
642 row.SetDescription( _( "Legacy project cache library" ) );
643 (*table)->Save();
644 }
645
646 std::vector<KI_ERROR> libErrors;
647
648 ReconcileLegacyCacheSymbols( *adapter, nickname, schematic, libErrors );
649
650 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
651 statusBar->AddWarningMessages( "load", libErrors );
652 }
653 }
654
655 if( ( !cfg || !cfg->m_RescueNeverShow ) && !cacheExists )
656 {
658 editor->RescueSymbolLibTableProject( false );
659 }
660 }
661
662 // Ensure there is only one legacy library loaded and that it is the cache library.
663 LEGACY_SYMBOL_LIBS* legacyLibs = PROJECT_SCH::LegacySchLibs( &Schematic().Project() );
664
665 if( legacyLibs->GetLibraryCount() == 0 )
666 {
667 wxFileName cacheFn = pro;
668
669 wxLogTrace( traceAutoSave, "[SetName dbg] cacheFn BEFORE path='%s' name='%s' full='%s' arg='%s'",
670 cacheFn.GetPath(), cacheFn.GetName(), cacheFn.GetFullPath(), cacheFn.GetName() + "-cache" );
671 cacheFn.SetName( cacheFn.GetName() + "-cache" );
672 wxLogTrace( traceAutoSave, "[SetName dbg] cacheFn AFTER path='%s' name='%s' full='%s'",
673 cacheFn.GetPath(), cacheFn.GetName(), cacheFn.GetFullPath() );
675
676 msg.Printf( _( "The project symbol library cache file '%s' was not found." ), cacheFn.GetFullName() );
677
678 KICAD_MESSAGE_DIALOG dlg( this, msg, _( "Warning" ), wxOK | wxCANCEL | wxICON_EXCLAMATION | wxCENTER );
679 dlg.SetExtendedMessage( _( "This can result in a broken schematic under certain conditions. If the "
680 "schematic does not have any missing symbols upon opening, save it "
681 "immediately before making any changes to prevent data loss. If there "
682 "are missing symbols, either manual recovery of the schematic or "
683 "recovery of the symbol cache library file and reloading the schematic is "
684 "required." ) );
685 dlg.SetOKCancelLabels( KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Load Without Cache File" ) ),
686 KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Abort" ) ) );
687
688 if( dlg.ShowModal() == wxID_CANCEL )
689 {
690 Schematic().Reset();
692 return false;
693 }
694 }
695
696 // Update all symbol library links for all sheets.
697 schematic.UpdateSymbolLinks( &loadReporter );
698
699 m_infoBar->RemoveAllButtons();
700 m_infoBar->AddCloseButton();
701 m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
702 "It will be converted to the new format when saved." ),
703 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
704
705 // Legacy schematic can have duplicate time stamps so fix that before converting
706 // to the s-expression format.
707 schematic.ReplaceDuplicateTimeStamps();
708
709 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
710 screen->FixLegacyPowerSymbolMismatches();
711
712 // Allow the schematic to be saved to new file format without making any edits.
713 OnModify();
714 }
715 else // S-expression schematic.
716 {
717 SCH_SCREEN* first_screen = schematic.GetFirst();
718
719 // Skip the first screen as it is a virtual root with no version info.
720 if( first_screen && first_screen->GetFileFormatVersionAtLoad() == 0 )
721 first_screen = schematic.GetNext();
722
723 if( first_screen && first_screen->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
724 {
725 m_infoBar->RemoveAllButtons();
726 m_infoBar->AddCloseButton();
727 m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
728 "It will be converted to the new format when saved." ),
729 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
730 }
731
732 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
734
735 SCH_SCREEN* rootScreen = Schematic().RootScreen();
736
737 // Restore all of the loaded symbol and sheet instances from the root sheet.
738 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20221002 )
739 sheetList.UpdateSymbolInstanceData( rootScreen->GetSymbolInstances() );
740
741 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20221110 )
742 sheetList.UpdateSheetInstanceData( rootScreen->GetSheetInstances());
743
744 if( rootScreen && rootScreen->GetFileFormatVersionAtLoad() < 20230221 )
745 for( SCH_SCREEN* screen = schematic.GetFirst(); screen;
746 screen = schematic.GetNext() )
747 screen->FixLegacyPowerSymbolMismatches();
748
749 for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
750 screen->MigrateSimModels();
751
754 }
755
756 // After the schematic is successfully loaded, we load the drawing sheet.
757 // This allows us to use the drawing sheet embedded in the schematic (if any)
758 // instead of the default one.
760
761 wxLogTrace( traceSchCurrentSheet, "Before CheckForMissingSymbolInstances: Current sheet path='%s', size=%zu",
762 GetCurrentSheet().Path().AsString(), GetCurrentSheet().size() );
763
764 // Check must run before pruning so variant data on a stale instance path is migrated
765 // onto the new instance before the orphan is removed.
766 sheetList.CheckForMissingSymbolInstances( Prj().GetProjectName() );
767
768 schematic.PruneOrphanedSymbolInstances( Prj().GetProjectName(), sheetList );
769 schematic.PruneOrphanedSheetInstances( Prj().GetProjectName(), sheetList );
770
772
773 SetScreen( GetCurrentSheet().LastScreen() );
774
775 // Repaired page numbers changed in-memory sheet instances; flag the schematic so the
776 // fixed numbering can be saved instead of silently reverting on the next load.
777 if( repairedPageNumbers )
778 OnModify();
779
780 wxLogTrace( traceSchCurrentSheet, "After SetScreen: Current sheet path='%s', size=%zu",
781 GetCurrentSheet().Path().AsString(), GetCurrentSheet().size() );
782
783 // Older files can omit implied junctions. Repair them before publishing connectivity;
784 // repairing current files could instead connect an intentional wire crossing.
785 const bool nativeNeedsFixup = schFileType == SCH_IO_MGR::SCH_KICAD
787
788 // Don't include in commit or call OnModify(); this fixup is necessary to move forward
789 // but isn't required in the older files. If they discard this file and open it again,
790 // we'll just re-apply the fixup.
791 if( schFileType == SCH_IO_MGR::SCH_LEGACY || nativeNeedsFixup )
793
794 SCH_COMMIT dummy( this );
795
796 progressReporter.Report( _( "Updating connections..." ) );
797 progressReporter.KeepRefreshing();
798
799 RecalculateConnections( &dummy, GLOBAL_CLEANUP, &progressReporter );
800 dummy.Push( _( "Schematic Cleanup" ), SKIP_UNDO | SKIP_SET_DIRTY | SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
801
802 // Migrate conflicting bus definitions, but only for files old enough to store them.
803 // The connection graph must be rebuilt first so GetBusesNeedingMigration() can see the
804 // conflicting subgraphs; the earlier Reset() clears them.
805 SCH_SCREEN* schRootScreen = Schematic().RootScreen();
806 int schFileVersion = schRootScreen ? schRootScreen->GetFileFormatVersionAtLoad() : 0;
807
809 schFileVersion, Schematic().ConnectionGraph()->GetBusesNeedingMigration().size() ) )
810 {
811 progressReporter.Hide();
812
813 // The rebuild below frees the subgraphs the dialog caches, and a progress update can
814 // dispatch queued UI events into its still-bound handlers, so destroy the dialog first.
815 {
816 DIALOG_MIGRATE_BUSES dlg( this );
817 dlg.ShowQuasiModal();
818 }
819
820 OnModify();
821 progressReporter.Show();
822
823 // Relabeling the conflicting buses changes connectivity, so rebuild it.
824 RecalculateConnections( &dummy, GLOBAL_CLEANUP, &progressReporter );
825 dummy.Push( _( "Schematic Cleanup" ),
827 }
828
829 if( schematic.HasSymbolFieldNamesWithWhiteSpace() )
830 {
831 m_infoBar->QueueShowMessage( _( "This schematic contains symbols that have leading "
832 "and/or trailing white space field names." ),
833 wxICON_WARNING );
834 }
835 }
836
837 // Load any exclusions from the project file
839
842
845
846 SyncView();
848
850
851 UpdateHierarchyNavigator( false, true );
852 CallAfter(
853 [this]()
854 {
857 } );
858
859 wxCommandEvent changedEvt( EDA_EVT_SCHEMATIC_CHANGED );
860 ProcessEventLocally( changedEvt );
861
862 if( !differentProject )
863 {
864 // If we didn't reload the project, we still need to call ProjectChanged() to ensure
865 // frame-specific initialization happens (like registering the autosave saver).
866 // When running under the project manager, KIWAY::ProjectChanged() was called before
867 // this frame existed, so we need to call our own ProjectChanged() now.
869 }
870
871 for( wxEvtHandler* listener : m_schematicChangeListeners )
872 {
873 wxCHECK2( listener, continue );
874
875 // Use the windows variant when handling event messages in case there is any special
876 // event handler pre and/or post processing specific to windows.
877 wxWindow* win = dynamic_cast<wxWindow*>( listener );
878
879 if( win )
880 win->HandleWindowEvent( e );
881 else
882 listener->SafelyProcessEvent( e );
883 }
884
885 updateTitle();
886 m_toolManager->GetTool<SCH_NAVIGATE_TOOL>()->ResetHistory();
888
889 wxFileName fn = Prj().AbsolutePath( GetScreen()->GetFileName() );
890
891 if( fn.FileExists() && !fn.IsFileWritable() )
892 {
893 m_infoBar->RemoveAllButtons();
894 m_infoBar->AddCloseButton();
895 m_infoBar->ShowMessage( _( "Schematic is read only." ), wxICON_WARNING,
896 WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
897 }
898
899#ifdef PROFILE
900 openFiles.Show();
901#endif
902 // Ensure all items are redrawn (especially the drawing-sheet items):
903 if( GetCanvas() )
904 GetCanvas()->DisplaySheet( GetCurrentSheet().LastScreen() );
905
906 // Trigger a library load to handle any project-specific libraries
907 CallAfter(
908 [&]()
909 {
910 KIFACE *schface = Kiway().KiFACE( KIWAY::FACE_SCH );
911 schface->PreloadLibraries( &Kiway() );
912
914 } );
915
916 m_remoteSymbolPane->BindWebViewLoaded();
917
918 // A standalone editor has no project manager to attach the git session for it.
920
921 return true;
922}
923
924
926{
927 if( Schematic().RootScreen() && !Schematic().RootScreen()->Items().empty() )
928 {
929 wxString msg = _( "This operation replaces the contents of the current schematic, "
930 "which will be permanently lost.\n\n"
931 "Do you want to proceed?" );
932
933 if( !IsOK( this, msg ) )
934 return;
935 }
936
937 // Set the project location if none is set or if we are running in standalone mode
938 bool setProject = Prj().GetProjectFullName().IsEmpty() || Kiface().IsSingle();
939 wxString path = wxPathOnly( Prj().GetProjectFullName() );
940
941 wxString fileFiltersStr;
942 wxString allWildcardsStr;
943
944 for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
945 {
946 if( fileType == SCH_IO_MGR::SCH_KICAD || fileType == SCH_IO_MGR::SCH_LEGACY )
947 continue; // this is "Import non-KiCad schematic"
948
949 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
950
951 if( !pi )
952 continue;
953
954 const IO_BASE::IO_FILE_DESC& desc = pi->GetSchematicFileDesc();
955
956 if( desc.m_FileExtensions.empty() || !desc.m_CanRead )
957 continue;
958
959 if( !fileFiltersStr.IsEmpty() )
960 fileFiltersStr += wxChar( '|' );
961
962 fileFiltersStr += desc.FileFilter();
963
964 for( const std::string& ext : desc.m_FileExtensions )
965 allWildcardsStr << wxS( "*." ) << formatWildcardExt( ext ) << wxS( ";" );
966 }
967
968 fileFiltersStr = _( "All supported formats" ) + wxS( "|" ) + allWildcardsStr + wxS( "|" ) + fileFiltersStr;
969
970 wxFileDialog dlg( this, _( "Import Schematic" ), path, wxEmptyString, fileFiltersStr,
971 wxFD_OPEN | wxFD_FILE_MUST_EXIST );
972
973 FILEDLG_IMPORT_NON_KICAD importOptions( eeconfig()->m_System.show_import_issues );
974 dlg.SetCustomizeHook( importOptions );
975
977
978 if( dlg.ShowModal() == wxID_CANCEL )
979 return;
980
982
983 // Don't leave dangling pointers to previously-opened document.
984 m_toolManager->GetTool<SCH_SELECTION_TOOL>()->ClearSelection();
987
988 if( setProject )
989 {
990 Schematic().SetProject( nullptr );
991 GetSettingsManager()->UnloadProject( &Prj(), false );
992
993 // Clear view before destroying schematic as repaints depend on schematic being valid
994 SetScreen( nullptr );
995
996 Schematic().Reset();
997
998 wxFileName projectFn( dlg.GetPath() );
999 projectFn.SetExt( FILEEXT::ProjectFileExtension );
1000 GetSettingsManager()->LoadProject( projectFn.GetFullPath() );
1001 }
1002
1003 wxFileName fn = dlg.GetPath();
1004
1005 if( !fn.IsFileReadable() )
1006 {
1007 wxLogError( _( "Insufficient permissions to read file '%s'." ), fn.GetFullPath() );
1008 return;
1009 }
1010
1011 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN;
1012
1013 for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
1014 {
1015 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
1016
1017 if( !pi )
1018 continue;
1019
1020 if( pi->CanReadSchematicFile( fn.GetFullPath() ) )
1021 {
1022 pluginType = fileType;
1023 break;
1024 }
1025 }
1026
1027 if( pluginType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
1028 {
1029 wxLogError( _( "No loader can read the specified file: '%s'." ), fn.GetFullPath() );
1031 SetScreen( Schematic().RootScreen() );
1032 return;
1033 }
1034
1035 importFile( dlg.GetPath(), pluginType );
1036
1037 RefreshCanvas();
1038}
1039
1040
1041bool SCH_EDIT_FRAME::saveSchematicFile( SCH_SHEET* aSheet, const wxString& aSavePath, bool isSaveAs )
1042{
1043 wxString msg;
1044 wxFileName schematicFileName;
1045 wxFileName oldFileName;
1046 bool success;
1047
1048 SCH_SCREEN* screen = aSheet->GetScreen();
1049
1050 wxCHECK( screen, false );
1051
1052 // Cannot save to nowhere
1053 if( aSavePath.IsEmpty() )
1054 return false;
1055
1056 // Construct the name of the file to be saved
1057 schematicFileName = Prj().AbsolutePath( aSavePath );
1058 oldFileName = schematicFileName;
1059
1060 // Write through symlinks, don't replace them
1061 WX_FILENAME::ResolvePossibleSymlinks( schematicFileName );
1062
1063 if( !schematicFileName.DirExists() )
1064 {
1065 if( !wxMkdir( schematicFileName.GetPath() ) )
1066 {
1067 msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
1068 schematicFileName.GetFullPath(),
1069 "Could not create directory: %s" + schematicFileName.GetPath() );
1070 DisplayError( this, msg );
1071
1072 return false;
1073 }
1074 }
1075
1076 if( !IsWritable( schematicFileName ) )
1077 return false;
1078
1079 wxFileName projectFile( schematicFileName );
1080
1081 projectFile.SetExt( FILEEXT::ProjectFileExtension );
1082
1083 if( projectFile.FileExists() )
1084 {
1085 // Save various ERC settings, such as violation severities (which may have been edited
1086 // via the ERC dialog as well as the Schematic Setup dialog), ERC exclusions, etc.
1088 }
1089
1090 // Save
1091 wxLogTrace( traceAutoSave, wxS( "Saving file " ) + schematicFileName.GetFullPath() );
1092
1093 if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
1094 m_infoBar->Dismiss();
1095
1096 SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::GuessPluginTypeFromSchPath( schematicFileName.GetFullPath() );
1097
1098 if( pluginType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
1099 pluginType = SCH_IO_MGR::SCH_KICAD;
1100
1101 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pluginType ) );
1102
1103 // On Windows, ensure the target file is writeable by clearing problematic attributes like
1104 // hidden or read-only. This can happen when files are synced via cloud services.
1105 if( schematicFileName.FileExists() )
1106 KIPLATFORM::IO::MakeWriteable( schematicFileName.GetFullPath() );
1107
1108 try
1109 {
1110 pi->SaveSchematicFile( schematicFileName.GetFullPath(), aSheet, &Schematic() );
1111 success = true;
1112 }
1113 catch( const IO_ERROR& ioe )
1114 {
1115 msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
1116 schematicFileName.GetFullPath(),
1117 ioe.What() );
1118 DisplayError( this, msg );
1119
1120 success = false;
1121 }
1122
1123 if( success )
1124 {
1125 if( !isSaveAs )
1126 screen->SetContentModified( false );
1127
1128 msg.Printf( _( "File '%s' saved." ), screen->GetFileName() );
1129 SetStatusText( msg, 0 );
1130 }
1131
1132 return success;
1133}
1134
1135
1136bool PrepareSaveAsFiles( SCHEMATIC& aSchematic, SCH_SCREENS& aScreens, const wxFileName& aOldRoot,
1137 const wxFileName& aNewRoot, bool aSaveCopy, bool aCopySubsheets, bool aIncludeExternSheets,
1138 std::unordered_map<SCH_SCREEN*, wxString>& aFilenameMap, wxString& aErrorMsg )
1139{
1140 SCH_SCREEN* screen;
1141
1142 for( size_t i = 0; i < aScreens.GetCount(); i++ )
1143 {
1144 screen = aScreens.GetScreen( i );
1145
1146 wxCHECK2( screen, continue );
1147
1148 if( screen == aSchematic.RootScreen() )
1149 continue;
1150
1151 // The virtual root's screen only holds the top-level sheets and has no file of its own
1152 // A destination here would be a nameless path that callers turn into a stray ".kicad_sch"
1153 if( screen == aSchematic.Root().GetScreen() )
1154 continue;
1155
1156 wxFileName src = screen->GetFileName();
1157
1158 if( !src.IsAbsolute() )
1159 src.MakeAbsolute( aOldRoot.GetPath() );
1160
1161 bool internalSheet = src.GetPath().StartsWith( aOldRoot.GetPath() );
1162
1163 if( aCopySubsheets && ( internalSheet || aIncludeExternSheets ) )
1164 {
1165 wxFileName dest = src;
1166
1167 if( internalSheet && dest.MakeRelativeTo( aOldRoot.GetPath() ) )
1168 dest.MakeAbsolute( aNewRoot.GetPath() );
1169 else
1170 dest.Assign( aNewRoot.GetPath(), dest.GetFullName() );
1171
1172 wxLogTrace( tracePathsAndFiles, wxS( "Moving schematic from '%s' to '%s'." ),
1173 screen->GetFileName(), dest.GetFullPath() );
1174
1175 if( !dest.DirExists() && !dest.Mkdir() )
1176 {
1177 aErrorMsg.Printf( _( "Folder '%s' could not be created.\n\n"
1178 "Make sure you have write permissions and try again." ),
1179 dest.GetPath() );
1180 return false;
1181 }
1182
1183 if( aSaveCopy )
1184 aFilenameMap[screen] = dest.GetFullPath();
1185 else
1186 screen->SetFileName( dest.GetFullPath() );
1187 }
1188 else
1189 {
1190 if( aSaveCopy )
1191 aFilenameMap[screen] = wxString();
1192
1193 screen->SetFileName( src.GetFullPath() );
1194 }
1195 }
1196
1197 for( SCH_SHEET_PATH& sheet : aSchematic.Hierarchy() )
1198 {
1199 if( !sheet.Last()->IsTopLevelSheet() )
1200 sheet.MakeFilePathRelativeToParentSheet();
1201 }
1202
1203 return true;
1204}
1205
1207{
1208 wxString msg;
1209 SCH_SCREEN* screen;
1210 SCH_SCREENS screens( Schematic().Root() );
1211 bool saveCopy = aSaveAs && !Kiface().IsSingle();
1212 bool success = true;
1213 bool updateFileHistory = false;
1214 bool createNewProject = false;
1215 bool copySubsheets = false;
1216 bool includeExternSheets = false;
1217
1218 // I want to see it in the debugger, show me the string! Can't do that with wxFileName.
1219 wxString fileName = Prj().AbsolutePath( Schematic().Root().GetFileName() );
1220 wxFileName fn = fileName;
1221
1222 // Path to save each screen to: will be the stored filename by default, but is overwritten by
1223 // a Save As Copy operation.
1224 std::unordered_map<SCH_SCREEN*, wxString> filenameMap;
1225
1226 // Handle "Save As" and saving a new project/schematic for the first time in standalone
1227 if( Prj().IsNullProject() || aSaveAs )
1228 {
1229 // Null project should only be possible in standalone mode.
1230 wxCHECK( Kiface().IsSingle() || aSaveAs, false );
1231
1232 wxFileName newFileName;
1233 wxFileName savePath( Prj().GetProjectFullName() );
1234
1235 if( !savePath.IsOk() || !savePath.IsDirWritable() )
1236 {
1237 savePath = GetMruPath();
1238
1239 if( !savePath.IsOk() || !savePath.IsDirWritable() )
1241 }
1242
1243 if( savePath.HasExt() )
1244 savePath.SetExt( FILEEXT::KiCadSchematicFileExtension );
1245 else
1246 savePath.SetName( wxEmptyString );
1247
1248 wxFileDialog dlg( this, _( "Schematic Files" ), savePath.GetPath(), savePath.GetFullName(),
1249 FILEEXT::KiCadSchematicFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
1250
1251 FILEDLG_HOOK_SAVE_PROJECT newProjectHook;
1252
1253 // Add a "Create a project" checkbox in standalone mode and one isn't loaded
1254 if( Kiface().IsSingle() || aSaveAs )
1255 {
1256 dlg.SetCustomizeHook( newProjectHook );
1257 }
1258
1260
1261 if( dlg.ShowModal() == wxID_CANCEL )
1262 return false;
1263
1264 newFileName = EnsureFileExtension( dlg.GetPath(), FILEEXT::KiCadSchematicFileExtension );
1265
1266 if( ( !newFileName.DirExists() && !newFileName.Mkdir() )
1267 || !newFileName.IsDirWritable() )
1268 {
1269 msg.Printf( _( "Folder '%s' could not be created.\n\n"
1270 "Make sure you have write permissions and try again." ),
1271 newFileName.GetPath() );
1272
1273 KICAD_MESSAGE_DIALOG dlgBadPath( this, msg, _( "Error" ), wxOK | wxICON_EXCLAMATION | wxCENTER );
1274
1275 dlgBadPath.ShowModal();
1276 return false;
1277 }
1278
1279 if( newProjectHook.IsAttachedToDialog() )
1280 {
1281 createNewProject = newProjectHook.GetCreateNewProject();
1282 copySubsheets = newProjectHook.GetCopySubsheets();
1283 includeExternSheets = newProjectHook.GetIncludeExternSheets();
1284 }
1285
1286 if( !saveCopy )
1287 {
1288 Schematic().Root().SetFileName( newFileName.GetFullName() );
1289 Schematic().RootScreen()->SetFileName( newFileName.GetFullPath() );
1290 updateFileHistory = true;
1291 }
1292 else
1293 {
1294 filenameMap[Schematic().RootScreen()] = newFileName.GetFullPath();
1295 }
1296
1297 if( !PrepareSaveAsFiles( Schematic(), screens, fn, newFileName, saveCopy, copySubsheets, includeExternSheets,
1298 filenameMap, msg ) )
1299 {
1300 KICAD_MESSAGE_DIALOG dlgBadFilePath( this, msg, _( "Error" ), wxOK | wxICON_EXCLAMATION | wxCENTER );
1301
1302 dlgBadFilePath.ShowModal();
1303 return false;
1304 }
1305 }
1306 else if( !fn.FileExists() )
1307 {
1308 // File doesn't exist yet; true if we just imported something
1309 updateFileHistory = true;
1310 }
1311 else if( screens.GetFirst() && screens.GetFirst()->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
1312 {
1313 // Allow the user to save un-edited files in new format
1314 }
1315 else if( !IsContentModified() )
1316 {
1317 return true;
1318 }
1319
1320 if( filenameMap.empty() || !saveCopy )
1321 {
1322 for( size_t i = 0; i < screens.GetCount(); i++ )
1323 filenameMap[screens.GetScreen( i )] = screens.GetScreen( i )->GetFileName();
1324 }
1325
1326 // Warn user on potential file overwrite. This can happen on shared sheets.
1327 wxArrayString overwrittenFiles;
1328 wxArrayString lockedFiles;
1329
1330 for( size_t i = 0; i < screens.GetCount(); i++ )
1331 {
1332 screen = screens.GetScreen( i );
1333
1334 wxCHECK2( screen, continue );
1335
1336 // Convert legacy schematics file name extensions for the new format.
1337 wxFileName tmpFn = filenameMap[screen];
1338
1339 if( !tmpFn.IsOk() )
1340 continue;
1341
1342 if( tmpFn.FileExists() && !tmpFn.IsFileWritable() )
1343 lockedFiles.Add( tmpFn.GetFullPath() );
1344
1345 if( tmpFn.GetExt() == FILEEXT::KiCadSchematicFileExtension )
1346 continue;
1347
1349
1350 if( tmpFn.FileExists() )
1351 overwrittenFiles.Add( tmpFn.GetFullPath() );
1352 }
1353
1354 if( !lockedFiles.IsEmpty() )
1355 {
1356 for( const wxString& lockedFile : lockedFiles )
1357 {
1358 if( msg.IsEmpty() )
1359 msg = lockedFile;
1360 else
1361 msg += "\n" + lockedFile;
1362 }
1363
1364 wxRichMessageDialog dlg( this, wxString::Format( _( "Failed to save %s." ), Schematic().Root().GetFileName() ),
1365 _( "Locked File Warning" ), wxOK | wxICON_WARNING | wxCENTER );
1366 dlg.SetExtendedMessage( _( "You do not have write permissions to:\n\n" ) + msg );
1367
1368 dlg.ShowModal();
1369 return false;
1370 }
1371
1372 if( !overwrittenFiles.IsEmpty() )
1373 {
1374 for( const wxString& overwrittenFile : overwrittenFiles )
1375 {
1376 if( msg.IsEmpty() )
1377 msg = overwrittenFile;
1378 else
1379 msg += "\n" + overwrittenFile;
1380 }
1381
1382 wxRichMessageDialog dlg( this, _( "Saving will overwrite existing files." ), _( "Save Warning" ),
1383 wxOK | wxCANCEL | wxCANCEL_DEFAULT | wxCENTER | wxICON_EXCLAMATION );
1384 dlg.ShowDetailedText( _( "The following files will be overwritten:\n\n" ) + msg );
1385 dlg.SetOKCancelLabels( KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Overwrite Files" ) ),
1386 KICAD_MESSAGE_DIALOG::ButtonLabel( _( "Abort Project Save" ) ) );
1387
1388 if( dlg.ShowModal() == wxID_CANCEL )
1389 return false;
1390 }
1391
1392 screens.BuildClientSheetPathList();
1393
1394 std::vector<wxString> savedSheetPaths;
1395
1396 for( size_t i = 0; i < screens.GetCount(); i++ )
1397 {
1398 screen = screens.GetScreen( i );
1399
1400 wxCHECK2( screen, continue );
1401
1402 // Convert legacy schematics file name extensions for the new format.
1403 wxFileName tmpFn = filenameMap[screen];
1404
1405 if( tmpFn.IsOk() && tmpFn.GetExt() != FILEEXT::KiCadSchematicFileExtension )
1406 {
1407 updateFileHistory = true;
1409
1410 for( EDA_ITEM* item : screen->Items().OfType( SCH_SHEET_T ) )
1411 {
1412 SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
1413 wxFileName sheetFileName = sheet->GetFileName();
1414
1415 if( !sheetFileName.IsOk() || sheetFileName.GetExt() == FILEEXT::KiCadSchematicFileExtension )
1416 continue;
1417
1418 sheetFileName.SetExt( FILEEXT::KiCadSchematicFileExtension );
1419 sheet->SetFileName( sheetFileName.GetFullPath() );
1420 UpdateItem( sheet );
1421 }
1422
1423 filenameMap[screen] = tmpFn.GetFullPath();
1424
1425 if( !saveCopy )
1426 screen->SetFileName( tmpFn.GetFullPath() );
1427 }
1428
1429 // Do not save sheet symbols with no valid filename set
1430 if( !tmpFn.IsOk() )
1431 continue;
1432
1433 std::vector<SCH_SHEET_PATH>& sheets = screen->GetClientSheetPaths();
1434
1435 if( sheets.size() == 1 )
1436 screen->SetVirtualPageNumber( 1 );
1437 else
1438 screen->SetVirtualPageNumber( 0 ); // multiple uses; no way to store the real sheet #
1439
1440 // This is a new schematic file so make sure it has a unique ID.
1441 if( !saveCopy && tmpFn.GetFullPath() != screen->GetFileName() )
1442 screen->AssignNewUuid();
1443
1444 bool savedThisSheet = saveSchematicFile( screens.GetSheet( i ), tmpFn.GetFullPath(), saveCopy );
1445
1446 if( savedThisSheet )
1447 savedSheetPaths.push_back( tmpFn.GetFullPath() );
1448
1449 success &= savedThisSheet;
1450 }
1451
1452 if( success && !saveCopy )
1453 {
1454 if( m_autoSaveTimer )
1455 m_autoSaveTimer->Stop();
1456
1457 m_autoSavePending = false;
1458 m_autoSaveRequired = false;
1459
1460 LockFile( Schematic().RootScreen()->GetFileName() );
1461 }
1462
1463 if( updateFileHistory )
1464 UpdateFileHistory( Schematic().RootScreen()->GetFileName() );
1465
1466 // Save the sheet name map to the project file
1467 std::vector<FILE_INFO_PAIR>& sheets = Prj().GetProjectFile().GetSheets();
1468 sheets.clear();
1469
1470 for( SCH_SHEET_PATH& sheetPath : Schematic().Hierarchy() )
1471 {
1472 SCH_SHEET* sheet = sheetPath.Last();
1473
1474 wxCHECK2( sheet, continue );
1475
1476 // Do not save the virtual root sheet
1477 if( !sheet->IsVirtualRootSheet() )
1478 sheets.emplace_back( std::make_pair( sheet->m_Uuid, sheet->GetName() ) );
1479 }
1480
1481 wxASSERT( filenameMap.count( Schematic().RootScreen() ) );
1482 wxFileName projectPath( filenameMap.at( Schematic().RootScreen() ) );
1483 projectPath.SetExt( FILEEXT::ProjectFileExtension );
1484
1485 if( Prj().IsNullProject() || ( aSaveAs && !saveCopy ) )
1486 {
1487 Prj().SetReadOnly( !createNewProject );
1488 GetSettingsManager()->SaveProjectAs( projectPath.GetFullPath() );
1489 }
1490 else if( saveCopy && createNewProject )
1491 {
1492 GetSettingsManager()->SaveProjectCopy( projectPath.GetFullPath() );
1493 }
1494 else
1495 {
1498 }
1499
1500 // Record a full project snapshot so related files (symbols, libs, sheets) are captured.
1501 // Skip when running standalone without a project loaded - the save path can land
1502 // anywhere on the filesystem and there is no project context for a snapshot.
1503 if( success && !saveCopy && !Prj().IsNullProject() )
1504 {
1505 Kiway().LocalHistory().RunRegisteredSaversAndCommit( Prj().GetProjectPath(), wxS( "SCH Save" ), wxS( "sch" ) );
1506
1507 // Drop the autosave files for the sheets we just persisted. Scope to those
1508 // sources so other dirty sheets (and any open PCB) keep their autosaves until
1509 // they are saved themselves; otherwise a Save All across editors would lose
1510 // recovery data for files this save did not write.
1511 // RunRegisteredSaversAndCommit above is a no-op when format is ZIP, and
1512 // RemoveAutosaveFiles is conversely a no-op in INCREMENTAL mode.
1513 Kiway().LocalHistory().RemoveAutosaveFiles( Prj().GetProjectPath(), savedSheetPaths );
1514 }
1515
1516 WX_STRING_REPORTER backupReporter;
1517
1518 if( !Kiface().IsSingle() )
1519 GetSettingsManager()->TriggerBackupIfNeeded( backupReporter );
1520
1521 // Restore the virtual page numbers that were modified during save. When saving, screens are
1522 // assigned page number 1 (single use) or 0 (multiple uses) for serialization purposes.
1523 // We restore all screens here, not just the current one, because other code paths (e.g.
1524 // ERC tree model, temporary sheet switches) may read any screen's virtual page number.
1525 for( const SCH_SHEET_PATH& sheet : Schematic().Hierarchy() )
1526 sheet.LastScreen()->SetVirtualPageNumber( sheet.GetVirtualPageNumber() );
1527
1529
1530 if( GetCanvas() && GetCanvas()->GetView() )
1531 {
1533 GetCanvas()->Refresh();
1534 }
1535
1536 updateTitle();
1537
1538 if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
1539 m_infoBar->Dismiss();
1540
1541 if( backupReporter.HasMessage() )
1542 {
1543 wxString backupMsg = backupReporter.GetMessages();
1544 m_infoBar->ShowMessageFor( backupMsg.Trim(), 10000, wxICON_WARNING );
1545 }
1546
1547 if( success )
1549
1550 return success;
1551}
1552
1553
1554bool SCH_EDIT_FRAME::importFile( const wxString& aFileName, int aFileType,
1555 const std::map<std::string, UTF8>* aProperties )
1556{
1557 bool success = true;
1558 wxFileName filename( aFileName );
1559 wxFileName newfilename;
1560 SCH_IO_MGR::SCH_FILE_T fileType = (SCH_IO_MGR::SCH_FILE_T) aFileType;
1561
1562 wxCommandEvent changingEvt( EDA_EVT_SCHEMATIC_CHANGING );
1563 ProcessEventLocally( changingEvt );
1564
1565 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
1566 statusBar->ClearWarningMessages( "load" );
1567
1568 WX_STRING_REPORTER loadReporter;
1569 LOAD_INFO_REPORTER_SCOPE loadReporterScope( &loadReporter );
1570
1571 std::unique_ptr<SCHEMATIC> newSchematic = std::make_unique<SCHEMATIC>( &Prj() );
1572
1573 switch( fileType )
1574 {
1575 case SCH_IO_MGR::SCH_ALTIUM:
1576 case SCH_IO_MGR::SCH_CADSTAR_ARCHIVE:
1577 case SCH_IO_MGR::SCH_EAGLE:
1578 case SCH_IO_MGR::SCH_LTSPICE:
1579 case SCH_IO_MGR::SCH_EASYEDA:
1580 case SCH_IO_MGR::SCH_EASYEDAPRO:
1581 case SCH_IO_MGR::SCH_EASYEDAPRO_V3:
1582 case SCH_IO_MGR::SCH_PADS:
1583 case SCH_IO_MGR::SCH_GEDA:
1584 case SCH_IO_MGR::SCH_DIPTRACE:
1585 case SCH_IO_MGR::SCH_PCAD:
1586 case SCH_IO_MGR::SCH_ORCAD:
1587 case SCH_IO_MGR::SCH_EASYPC:
1588 case SCH_IO_MGR::SCH_TARGET3001:
1589 {
1590 // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
1591 // Unless we are passing the files in aproperties, in which case aFileName can be empty.
1592 wxCHECK_MSG( aFileName.IsEmpty() || filename.IsAbsolute(), false,
1593 wxS( "Import schematic: path is not absolute!" ) );
1594
1595 try
1596 {
1597 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
1598 DIALOG_HTML_REPORTER errorReporter( this );
1599 WX_PROGRESS_REPORTER progressReporter( this, _( "Import Schematic" ), 1, PR_CAN_ABORT );
1600
1601 if( PROJECT_CHOOSER_PLUGIN* c_pi = dynamic_cast<PROJECT_CHOOSER_PLUGIN*>( pi.get() ) )
1602 {
1603 c_pi->RegisterCallback( std::bind( DIALOG_IMPORT_CHOOSE_PROJECT::RunModal,
1604 this, std::placeholders::_1 ) );
1605 }
1606
1607 if( eeconfig()->m_System.show_import_issues )
1608 pi->SetReporter( errorReporter.m_Reporter );
1609 else
1610 pi->SetReporter( &NULL_REPORTER::GetInstance() );
1611
1612 pi->SetProgressReporter( &progressReporter );
1613
1614 SCH_SHEET* loadedSheet = pi->LoadSchematicFile( aFileName, newSchematic.get(), nullptr, aProperties );
1615
1616 SetSchematic( newSchematic.release() );
1617
1619
1621
1622 if( loadedSheet )
1623 {
1624 std::vector<SCH_SHEET*> topLevelSheets = Schematic().GetTopLevelSheets();
1625 bool loadedIsTopLevel = std::find( topLevelSheets.begin(), topLevelSheets.end(), loadedSheet )
1626 != topLevelSheets.end();
1627 bool loadedIsVirtualRoot = loadedSheet == &Schematic().Root()
1628 || loadedSheet->IsVirtualRootSheet();
1629
1630 // Some importers create the full top-level sheet set themselves. Do not collapse
1631 // that back to the returned sheet.
1632 if( !loadedIsTopLevel && !loadedIsVirtualRoot )
1633 Schematic().SetTopLevelSheets( { loadedSheet } );
1634
1635 // extract a project symbol library and re-link LIB_IDs so every symbol resolves
1636 ReconcileImportedSymbols( *pi, Schematic(), Prj(), aFileName, aProperties, loadReporter );
1637
1638 // re-link footprint fields to the project lib so update-from-schematic works
1639 {
1640 wxString cacheNick;
1641 std::vector<wxString> sourceFpLibs;
1642 IMPORT_PROJ_PROPS::ReadFootprintProps( aProperties, cacheNick, sourceFpLibs );
1643
1644 SCH_FOOTPRINT_FIELD_RECONCILER fpReconciler( cacheNick, sourceFpLibs, &loadReporter );
1645 fpReconciler.Reconcile( Schematic() );
1646 }
1647
1648 if( errorReporter.m_Reporter->HasMessage() )
1649 {
1650 errorReporter.m_Reporter->Flush(); // Build HTML messages
1651 errorReporter.ShowModal();
1652
1653 // These are not catastrophic errors: leave success set to true so the caller
1654 // doesn't destroy the frame.
1655 }
1656
1657 const wxString drawingSheetName = Schematic().Settings().m_SchDrawingSheetFileName;
1658 const wxString embeddedPrefix = wxS( "kicad-embed://" );
1659 const EMBEDDED_FILES::EMBEDDED_FILE* embeddedWorksheet = nullptr;
1660
1661 if( drawingSheetName.StartsWith( embeddedPrefix ) )
1662 {
1663 wxString sheetFile = drawingSheetName.Mid( embeddedPrefix.length() );
1664 embeddedWorksheet = Schematic().GetEmbeddedFiles()->GetEmbeddedFile( sheetFile );
1665 }
1666
1667 if( !embeddedWorksheet
1669 {
1672 }
1673 else
1674 {
1677 }
1678
1679 newfilename.SetPath( Prj().GetProjectPath() );
1680 newfilename.SetName( Prj().GetProjectName() );
1681 newfilename.SetExt( FILEEXT::KiCadSchematicFileExtension );
1682
1683 SetScreen( Schematic().RootScreen() );
1684
1685 if( SCH_SHEET* topSheet = Schematic().GetTopLevelSheet() )
1686 topSheet->SetFileName( newfilename.GetFullName() );
1687
1688 GetScreen()->SetFileName( newfilename.GetFullPath() );
1690
1691 progressReporter.Report( _( "Updating connections..." ) );
1692
1693 if( !progressReporter.KeepRefreshing() )
1695
1696 RecalculateConnections( nullptr, GLOBAL_CLEANUP, &progressReporter );
1697
1698 // Only perform the dangling end test on root sheet.
1700 }
1701 else
1702 {
1704 }
1705 }
1706 catch( const IO_ERROR& ioe )
1707 {
1708 // Do not leave g_RootSheet == NULL because it is expected to be
1709 // a valid sheet. Therefore create a dummy empty root sheet and screen.
1712
1713 wxString msg = wxString::Format( _( "Error loading schematic '%s'." ), aFileName );
1714 DisplayErrorMessage( this, msg, ioe.What() );
1715
1716 msg.Printf( _( "Failed to load '%s'." ), aFileName );
1717 SetMsgPanel( wxEmptyString, msg );
1718
1719 success = false;
1720 }
1721 catch( const std::exception& exc )
1722 {
1725
1726 wxString msg = wxString::Format( _( "Unhandled exception occurred loading schematic '%s'." ), aFileName );
1727 DisplayErrorMessage( this, msg, exc.what() );
1728
1729 msg.Printf( _( "Failed to load '%s'." ), aFileName );
1730 SetMsgPanel( wxEmptyString, msg );
1731
1732 success = false;
1733 }
1734
1737
1740 SyncView();
1741
1742 UpdateHierarchyNavigator( false, true );
1743 SyncVariantUI();
1744 SetCurrentVariant( m_schematic->GetCurrentVariant() );
1745
1746 CallAfter(
1747 [this]()
1748 {
1751 } );
1752
1753 wxCommandEvent e( EDA_EVT_SCHEMATIC_CHANGED );
1754 ProcessEventLocally( e );
1755
1756 for( wxEvtHandler* listener : m_schematicChangeListeners )
1757 {
1758 wxCHECK2( listener, continue );
1759
1760 // Use the windows variant when handling event messages in case there is any
1761 // special event handler pre and/or post processing specific to windows.
1762 wxWindow* win = dynamic_cast<wxWindow*>( listener );
1763
1764 if( win )
1765 win->HandleWindowEvent( e );
1766 else
1767 listener->SafelyProcessEvent( e );
1768 }
1769
1770 updateTitle();
1771
1772 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
1773 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
1774
1775 break;
1776 }
1777
1778 default:
1779 break;
1780 }
1781
1782 if( success )
1784
1785 return success;
1786}
1787
1788
1790{
1791 SCH_SCREENS screenList( Schematic().Root() );
1792
1793 // Save any currently open and modified project files.
1794 for( SCH_SCREEN* screen = screenList.GetFirst(); screen; screen = screenList.GetNext() )
1795 {
1796 SIMULATOR_FRAME* simFrame = (SIMULATOR_FRAME*) Kiway().Player( FRAME_SIMULATOR, false );
1797
1798 // Simulator must be closed before loading another schematic, otherwise it may crash.
1799 // If there are any changes in the simulator the user will be prompted to save them.
1800 if( simFrame && !simFrame->Close() )
1801 return false;
1802
1803 if( screen->IsContentModified() )
1804 {
1805 if( !HandleUnsavedChanges( this, _( "The current schematic has been modified. Save changes?" ),
1806 [&]() -> bool
1807 {
1808 return SaveProject();
1809 } ) )
1810 {
1811 return false;
1812 }
1813 }
1814 }
1815
1816 return true;
1817}
static TOOL_ACTION zoomFitScreen
Definition actions.h:139
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.
void ReleaseFile()
Release the current file marked in use.
std::unique_ptr< LOCKFILE > m_file_checker
Prevents opening same file multiple times.
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.
void RefreshGitCommitPane()
Attach the git session if needed and refresh the version-control pane, when it is shown.
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:599
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 create new project option.
bool GetCopySubsheets() const
Gets the selected state of the copy subsheets option.
bool IsAttachedToDialog() const
Gets if this hook has attached controls to a dialog box.
bool GetIncludeExternSheets() const
Gets the selected state of the include external sheets option.
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:92
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:246
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:401
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:214
@ FACE_SCH
eeschema DSO
Definition kiway.h:355
LOCAL_HISTORY & LocalHistory()
Return the LOCAL_HISTORY associated with this KIWAY.
Definition kiway.h:457
A collection of LIB_SYMBOL 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:922
void HideSplash()
Definition pgm_base.cpp:338
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:104
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()
bool TopLevelSheetsChangedOnLoad() const
True when the last read of the file replaced a top-level sheet list held from before it.
void AcknowledgeTopLevelSheetChange()
Settle a changed list once the schematic has been loaded from it.
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:271
virtual void SetElem(PROJECT::ELEM aIndex, _ELEM *aElem)
Definition project.cpp:490
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:289
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:501
@ 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:155
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.
wxString GetFileName() const
Helper to retrieve the filename from the root sheet screen.
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:414
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:282
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.
static wxFileName TopLevelSheetFile(const TOP_LEVEL_SHEET_INFO &aSheet, const wxString &aProjectPath, bool aLegacy)
The file loaded for a listed top-level sheet. A legacy project reads it under the legacy extension.
static TOOL_ACTION changeSheet
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
Commit for the schematic and symbol editors.
Definition sch_commit.h:54
KIGFX::SCH_VIEW * GetView() const override
Return a pointer to the KIGFX::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 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.
NET_NAVIGATOR_TREE * m_netNavigator
bool TopLevelSheetsChangedOnDisk()
Check whether the last read of the project file brought a top-level sheet list that the open schemati...
SCH_SCREEN * GetScreen() const override
Return a pointer to a BASE_SCREEN or one of its derivatives.
void SyncVariantUI()
Refill the toolbar variant control and any open symbol fields table from the schematic.
void RefreshNetNavigator(const NET_NAVIGATOR_ITEM_DATA *aSelection=nullptr, const std::vector< wxString > *aChangedNets=nullptr)
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)
bool RecalculateConnections(SCH_COMMIT *aCommit, SCH_CLEANUP_FLAGS aCleanupFlags, PROGRESS_REPORTER *aProgressReporter=nullptr, bool aCleanupDone=false)
Generate the connection data for the entire schematic hierarchy.
std::vector< wxEvtHandler * > m_schematicChangeListeners
bool ReloadFromDisk()
Reload the schematic and all its sheets from disk.
PANEL_REMOTE_SYMBOL * m_remoteSymbolPane
bool saveSchematicFile(SCH_SHEET *aSheet, const wxString &aSavePath, bool isSaveAs)
Save aSheet to a schematic file.
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 LoadProjectSettings()
Load the KiCad project file (*.pro) settings specific to Eeschema.
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.
bool ConfirmReloadFromDisk(const wxString &aMessage, const wxString &aTitle)
Ask whether to reload when that would discard unsaved edits.
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.
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.
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:170
Handle actions specific to the schematic editor.
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
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:831
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:226
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:122
const wxString & GetFileName() const
Definition sch_screen.h:157
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:592
int GetFileFormatVersionAtLoad() const
Definition sch_screen.h:142
void AssignNewUuid()
Definition sch_screen.h:604
const std::vector< SCH_SHEET_INSTANCE > & GetSheetInstances() const
Definition sch_screen.h:597
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:50
void SetFileName(const wxString &aFilename)
Definition sch_sheet.h:434
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
wxString GetName() const
Definition sch_sheet.h:150
void SetName(const wxString &aName)
Definition sch_sheet.h:185
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
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 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.
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.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
TOOL_MANAGER * m_toolManager
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
@ SUPERMODEL_RELOAD
For schematics, the entire schematic changed, not just the sheet.
Definition tool_base.h:77
bool RunAction(const std::string &aActionName, T aParam)
Run the specified action immediately, pausing the current action to run the new one.
Temporarily disable a window, and then re-enable on destruction.
Definition raii.h:89
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:880
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
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
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
#define THROW_IO_CANCELLED()
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
PROJECT & Prj()
Definition kicad.cpp:724
KIID niluuid(0)
#define KICTL_CREATE
caller thinks requested project files may not exist.
#define KICTL_REVERT
reverting to a previously-saved (KiCad) file.
#define KICTL_KICAD_ONLY
chosen file is from KiCad according to user
@ LAYER_BUS
Definition layer_ids.h:484
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.
Definition for symbol library class.
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:108
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:83
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:747
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:101
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:298
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.
const std::string table
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