-
-
Notifications
You must be signed in to change notification settings - Fork 491
/
files-io.cpp
1699 lines (1332 loc) · 58.7 KB
/
files-io.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2013 Jean-Pierre Charras, jp.charras at wanadoo.fr
* Copyright (C) 2013 Wayne Stambaugh <[email protected]>
* Copyright (C) 2013-2023 CERN (www.cern.ch)
* Copyright The KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <symbol_library.h>
#include <confirm.h>
#include <common.h>
#include <connection_graph.h>
#include <dialog_migrate_buses.h>
#include <dialog_symbol_remap.h>
#include <dialog_import_choose_project.h>
#include <eeschema_settings.h>
#include <id.h>
#include <kiface_base.h>
#include <kiplatform/app.h>
#include <lockfile.h>
#include <pgm_base.h>
#include <core/profile.h>
#include <project/project_file.h>
#include <project_rescue.h>
#include <project_sch.h>
#include <dialog_HTML_reporter_base.h>
#include <io/common/plugin_common_choose_project.h>
#include <reporter.h>
#include <richio.h>
#include <sch_bus_entry.h>
#include <sch_commit.h>
#include <sch_edit_frame.h>
#include <sch_io/kicad_legacy/sch_io_kicad_legacy.h>
#include <sch_file_versions.h>
#include <sch_line.h>
#include <sch_sheet.h>
#include <sch_sheet_path.h>
#include <schematic.h>
#include <settings/settings_manager.h>
#include <sim/simulator_frame.h>
#include <tool/actions.h>
#include <tool/tool_manager.h>
#include <tools/sch_editor_control.h>
#include <tools/sch_navigate_tool.h>
#include <trace_helpers.h>
#include <widgets/filedlg_import_non_kicad.h>
#include <widgets/wx_infobar.h>
#include <wildcards_and_files_ext.h>
#include <drawing_sheet/ds_data_model.h>
#include <wx/app.h>
#include <wx/ffile.h>
#include <wx/filedlg.h>
#include <wx/log.h>
#include <wx/richmsgdlg.h>
#include <wx/stdpaths.h>
#include <tools/ee_actions.h>
#include <tools/ee_inspection_tool.h>
#include <tools/ee_selection_tool.h>
#include <paths.h>
#include <wx_filename.h> // For ::ResolvePossibleSymlinks
#include <widgets/wx_progress_reporters.h>
#include <widgets/wx_html_report_box.h>
#include <kiplatform/io.h>
#include "widgets/filedlg_hook_save_project.h"
bool SCH_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
{
// ensure the splash screen does not obscure any dialog at startup
Pgm().HideSplash();
// implement the pseudo code from KIWAY_PLAYER.h:
wxString msg;
EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() );
// This is for python:
if( aFileSet.size() != 1 )
{
msg.Printf( "Eeschema:%s() takes only a single filename.", __WXFUNCTION__ );
DisplayError( this, msg );
return false;
}
wxString fullFileName( aFileSet[0] );
wxFileName wx_filename( fullFileName );
// We insist on caller sending us an absolute path, if it does not, we say it's a bug.
wxASSERT_MSG( wx_filename.IsAbsolute(), wxS( "Path is not absolute!" ) );
if( !LockFile( fullFileName ) )
{
msg.Printf( _( "Schematic '%s' is already open by '%s' at '%s'." ), fullFileName,
m_file_checker->GetUsername(), m_file_checker->GetHostname() );
if( !AskOverrideLock( this, msg ) )
return false;
m_file_checker->OverrideLock();
}
if( !AskToSaveChanges() )
return false;
#ifdef PROFILE
PROF_TIMER openFiles( "OpenProjectFile" );
#endif
wxFileName pro = fullFileName;
pro.SetExt( FILEEXT::ProjectFileExtension );
bool is_new = !wxFileName::IsFileReadable( fullFileName );
// If its a non-existent schematic and caller thinks it exists
if( is_new && !( aCtl & KICTL_CREATE ) )
{
// notify user that fullFileName does not exist, ask if user wants to create it.
msg.Printf( _( "Schematic '%s' does not exist. Do you wish to create it?" ),
fullFileName );
if( !IsOK( this, msg ) )
return false;
}
wxCommandEvent e( EDA_EVT_SCHEMATIC_CHANGING );
ProcessEventLocally( e );
// unload current project file before loading new
{
ClearUndoRedoList();
ClearRepeatItemsList();
SetScreen( nullptr );
m_toolManager->GetTool<EE_INSPECTION_TOOL>()->Reset( TOOL_BASE::SUPERMODEL_RELOAD );
CreateScreens();
}
SetStatusText( wxEmptyString );
m_infoBar->Dismiss();
WX_PROGRESS_REPORTER progressReporter( this, is_new ? _( "Creating Schematic" )
: _( "Loading Schematic" ), 1 );
bool differentProject = pro.GetFullPath() != Prj().GetProjectFullName();
if( differentProject )
{
if( !Prj().IsNullProject() )
{
SaveProjectLocalSettings();
GetSettingsManager()->SaveProject();
}
Schematic().SetProject( nullptr );
GetSettingsManager()->UnloadProject( &Prj(), false );
GetSettingsManager()->LoadProject( pro.GetFullPath() );
wxFileName legacyPro( pro );
legacyPro.SetExt( FILEEXT::LegacyProjectFileExtension );
// Do not allow saving a project if one doesn't exist. This normally happens if we are
// standalone and opening a schematic that has been moved from its project folder.
if( !pro.Exists() && !legacyPro.Exists() && !( aCtl & KICTL_CREATE ) )
Prj().SetReadOnly();
CreateScreens();
}
SCH_IO_MGR::SCH_FILE_T schFileType = SCH_IO_MGR::GuessPluginTypeFromSchPath( fullFileName,
KICTL_KICAD_ONLY );
if( schFileType == SCH_IO_MGR::SCH_LEGACY )
{
// Don't reload the symbol libraries if we are just launching Eeschema from KiCad again.
// They are already saved in the kiface project object.
if( differentProject || !Prj().GetElem( PROJECT::ELEM::SCH_SYMBOL_LIBS ) )
{
// load the libraries here, not in SCH_SCREEN::Draw() which is a context
// that will not tolerate DisplayError() dialog since we're already in an
// event handler in there.
// And when a schematic file is loaded, we need these libs to initialize
// some parameters (links to PART LIB, dangling ends ...)
Prj().SetElem( PROJECT::ELEM::SCH_SYMBOL_LIBS, nullptr );
PROJECT_SCH::SchLibs( &Prj() );
}
}
else
{
// No legacy symbol libraries including the cache are loaded with the new file format.
Prj().SetElem( PROJECT::ELEM::SCH_SYMBOL_LIBS, nullptr );
}
// Load the symbol library table, this will be used forever more.
Prj().SetElem( PROJECT::ELEM::SYMBOL_LIB_TABLE, nullptr );
PROJECT_SCH::SchSymbolLibTable( &Prj() );
// Load project settings after schematic has been set up with the project link, since this will
// update some of the needed schematic settings such as drawing defaults
LoadProjectSettings();
wxFileName rfn( GetCurrentFileName() );
rfn.MakeRelativeTo( Prj().GetProjectPath() );
LoadWindowState( rfn.GetFullPath() );
KIPLATFORM::APP::SetShutdownBlockReason( this, _( "Schematic file changes are unsaved" ) );
if( Kiface().IsSingle() )
{
KIPLATFORM::APP::RegisterApplicationRestart( fullFileName );
}
if( is_new || schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
{
// mark new, unsaved file as modified.
GetScreen()->SetContentModified();
GetScreen()->SetFileName( fullFileName );
if( schFileType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
{
msg.Printf( _( "'%s' is not a KiCad schematic file.\nUse File -> Import for "
"non-KiCad schematic files." ),
fullFileName );
progressReporter.Hide();
DisplayErrorMessage( this, msg );
}
}
else
{
wxFileName autoSaveFn = fullFileName;
autoSaveFn.SetName( getAutoSaveFileName() );
autoSaveFn.ClearExt();
if( ( aCtl & KICTL_REVERT ) )
{
DeleteAutoSaveFile( autoSaveFn );
}
else
{
// This will rename the file if there is an autosave and the user wants to recover
CheckForAutoSaveFile( autoSaveFn );
}
SetScreen( nullptr );
IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( schFileType ) );
pi->SetProgressReporter( &progressReporter );
bool failedLoad = false;
try
{
{
wxBusyCursor busy;
Schematic().SetRoot( pi->LoadSchematicFile( fullFileName, &Schematic() ) );
// Make ${SHEETNAME} work on the root sheet until we properly support
// naming the root sheet
Schematic().Root().SetName( _( "Root" ) );
wxLogTrace( tracePathsAndFiles, wxS( "Loaded schematic with root sheet UUID %s" ),
Schematic().Root().m_Uuid.AsString() );
}
if( !pi->GetError().IsEmpty() )
{
DisplayErrorMessage( this, _( "The entire schematic could not be loaded. Errors "
"occurred attempting to load hierarchical sheets." ),
pi->GetError() );
}
}
catch( const FUTURE_FORMAT_ERROR& ffe )
{
msg.Printf( _( "Error loading schematic '%s'." ), fullFileName);
progressReporter.Hide();
DisplayErrorMessage( this, msg, ffe.Problem() );
failedLoad = true;
}
catch( const IO_ERROR& ioe )
{
msg.Printf( _( "Error loading schematic '%s'." ), fullFileName);
progressReporter.Hide();
DisplayErrorMessage( this, msg, ioe.What() );
failedLoad = true;
}
catch( const std::bad_alloc& )
{
msg.Printf( _( "Memory exhausted loading schematic '%s'." ), fullFileName );
progressReporter.Hide();
DisplayErrorMessage( this, msg, wxEmptyString );
failedLoad = true;
}
// This fixes a focus issue after the progress reporter is done on GTK. It shouldn't
// cause any issues on macOS and Windows. If it does, it will have to be conditionally
// compiled.
Raise();
if( failedLoad )
{
// Do not leave g_RootSheet == NULL because it is expected to be
// a valid sheet. Therefore create a dummy empty root sheet and screen.
CreateScreens();
m_toolManager->RunAction( ACTIONS::zoomFitScreen );
msg.Printf( _( "Failed to load '%s'." ), fullFileName );
SetMsgPanel( wxEmptyString, msg );
return false;
}
// It's possible the schematic parser fixed errors due to bugs so warn the user
// that the schematic has been fixed (modified).
SCH_SHEET_LIST sheetList = Schematic().Hierarchy();
if( sheetList.IsModified() )
{
DisplayInfoMessage( this,
_( "An error was found when loading the schematic that has "
"been automatically fixed. Please save the schematic to "
"repair the broken file or it may not be usable with other "
"versions of KiCad." ) );
}
if( sheetList.AllSheetPageNumbersEmpty() )
sheetList.SetInitialPageNumbers();
UpdateFileHistory( fullFileName );
SCH_SCREENS schematic( Schematic().Root() );
// LIB_ID checks and symbol rescue only apply to the legacy file formats.
if( schFileType == SCH_IO_MGR::SCH_LEGACY )
{
// Convert any legacy bus-bus entries to just be bus wires
for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
{
std::vector<SCH_ITEM*> deleted;
for( SCH_ITEM* item : screen->Items() )
{
if( item->Type() == SCH_BUS_BUS_ENTRY_T )
{
SCH_BUS_BUS_ENTRY* entry = static_cast<SCH_BUS_BUS_ENTRY*>( item );
std::unique_ptr<SCH_LINE> wire = std::make_unique<SCH_LINE>();
wire->SetLayer( LAYER_BUS );
wire->SetStartPoint( entry->GetPosition() );
wire->SetEndPoint( entry->GetEnd() );
screen->Append( wire.release() );
deleted.push_back( item );
}
}
for( SCH_ITEM* item : deleted )
screen->Remove( item );
}
// Convert old projects over to use symbol library table.
if( schematic.HasNoFullyDefinedLibIds() )
{
DIALOG_SYMBOL_REMAP dlgRemap( this );
dlgRemap.ShowQuasiModal();
}
else
{
// Double check to ensure no legacy library list entries have been
// added to the project file symbol library list.
wxString paths;
wxArrayString libNames;
SYMBOL_LIBS::GetLibNamesAndPaths( &Prj(), &paths, &libNames );
if( !libNames.IsEmpty() )
{
if( eeconfig()->m_Appearance.show_illegal_symbol_lib_dialog )
{
wxRichMessageDialog invalidLibDlg(
this,
_( "Illegal entry found in project file symbol library list." ),
_( "Project Load Warning" ),
wxOK | wxCENTER | wxICON_EXCLAMATION );
invalidLibDlg.ShowDetailedText(
_( "Symbol libraries defined in the project file symbol library "
"list are no longer supported and will be removed.\n\n"
"This may cause broken symbol library links under certain "
"conditions." ) );
invalidLibDlg.ShowCheckBox( _( "Do not show this dialog again." ) );
invalidLibDlg.ShowModal();
eeconfig()->m_Appearance.show_illegal_symbol_lib_dialog =
!invalidLibDlg.IsCheckBoxChecked();
}
libNames.Clear();
paths.Clear();
SYMBOL_LIBS::SetLibNamesAndPaths( &Prj(), paths, libNames );
}
if( !cfg || !cfg->m_RescueNeverShow )
{
SCH_EDITOR_CONTROL* editor = m_toolManager->GetTool<SCH_EDITOR_CONTROL>();
editor->RescueSymbolLibTableProject( false );
}
}
// Ensure there is only one legacy library loaded and that it is the cache library.
SYMBOL_LIBS* legacyLibs = PROJECT_SCH::SchLibs( &Schematic().Prj() );
if( legacyLibs->GetLibraryCount() == 0 )
{
wxString extMsg;
wxFileName cacheFn = pro;
cacheFn.SetName( cacheFn.GetName() + "-cache" );
cacheFn.SetExt( FILEEXT::LegacySymbolLibFileExtension );
msg.Printf( _( "The project symbol library cache file '%s' was not found." ),
cacheFn.GetFullName() );
extMsg = _( "This can result in a broken schematic under certain conditions. "
"If the schematic does not have any missing symbols upon opening, "
"save it immediately before making any changes to prevent data "
"loss. If there are missing symbols, either manual recovery of "
"the schematic or recovery of the symbol cache library file and "
"reloading the schematic is required." );
wxMessageDialog dlgMissingCache( this, msg, _( "Warning" ),
wxOK | wxCANCEL | wxICON_EXCLAMATION | wxCENTER );
dlgMissingCache.SetExtendedMessage( extMsg );
dlgMissingCache.SetOKCancelLabels(
wxMessageDialog::ButtonLabel( _( "Load Without Cache File" ) ),
wxMessageDialog::ButtonLabel( _( "Abort" ) ) );
if( dlgMissingCache.ShowModal() == wxID_CANCEL )
{
Schematic().Reset();
CreateScreens();
return false;
}
}
// Update all symbol library links for all sheets.
schematic.UpdateSymbolLinks();
m_infoBar->RemoveAllButtons();
m_infoBar->AddCloseButton();
m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
"It will be converted to the new format when saved." ),
wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
// Legacy schematic can have duplicate time stamps so fix that before converting
// to the s-expression format.
schematic.ReplaceDuplicateTimeStamps();
for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
screen->FixLegacyPowerSymbolMismatches();
// Allow the schematic to be saved to new file format without making any edits.
OnModify();
}
else // S-expression schematic.
{
if( schematic.GetFirst()->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
{
m_infoBar->RemoveAllButtons();
m_infoBar->AddCloseButton();
m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
"It will be converted to the new format when saved." ),
wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
}
for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
screen->UpdateLocalLibSymbolLinks();
// Restore all of the loaded symbol and sheet instances from the root sheet.
if( Schematic().RootScreen()->GetFileFormatVersionAtLoad() < 20221002 )
sheetList.UpdateSymbolInstanceData( Schematic().RootScreen()->GetSymbolInstances() );
if( Schematic().RootScreen()->GetFileFormatVersionAtLoad() < 20221110 )
sheetList.UpdateSheetInstanceData( Schematic().RootScreen()->GetSheetInstances());
if( Schematic().RootScreen()->GetFileFormatVersionAtLoad() < 20230221 )
for( SCH_SCREEN* screen = schematic.GetFirst(); screen;
screen = schematic.GetNext() )
screen->FixLegacyPowerSymbolMismatches();
for( SCH_SCREEN* screen = schematic.GetFirst(); screen; screen = schematic.GetNext() )
screen->MigrateSimModels();
if( schematic.GetFirst()->GetFileFormatVersionAtLoad() < SEXPR_SCHEMATIC_FILE_VERSION )
{
// Allow the schematic to be saved to new file format without making any edits.
OnModify();
}
}
// After the schematic is successfully loaded, we load the drawing sheet.
// This allows us to use the drawing sheet embedded in the schematic (if any)
// instead of the default one.
LoadDrawingSheet();
schematic.PruneOrphanedSymbolInstances( Prj().GetProjectName(), sheetList );
schematic.PruneOrphanedSheetInstances( Prj().GetProjectName(), sheetList );
sheetList.CheckForMissingSymbolInstances( Prj().GetProjectName() );
Schematic().ConnectionGraph()->Reset();
SetScreen( GetCurrentSheet().LastScreen() );
// Migrate conflicting bus definitions
// TODO(JE) This should only run once based on schematic file version
if( Schematic().ConnectionGraph()->GetBusesNeedingMigration().size() > 0 )
{
DIALOG_MIGRATE_BUSES dlg( this );
dlg.ShowQuasiModal();
OnModify();
}
SCH_COMMIT dummy( this );
RecalculateConnections( &dummy, GLOBAL_CLEANUP );
if( schematic.HasSymbolFieldNamesWithWhiteSpace() )
{
m_infoBar->QueueShowMessage( _( "This schematic contains symbols that have leading "
"and/or trailing white space field names." ),
wxICON_WARNING );
}
}
// Load any exclusions from the project file
Schematic().ResolveERCExclusionsPostUpdate();
initScreenZoom();
SetSheetNumberAndCount();
RecomputeIntersheetRefs();
GetCurrentSheet().UpdateAllScreenReferences();
// Re-create junctions if needed. Eeschema optimizes wires by merging
// colinear segments. If a schematic is saved without a valid
// cache library or missing installed libraries, this can cause connectivity errors
// unless junctions are added.
//
// TODO: (RFB) This really needs to be put inside the Load() function of the SCH_IO_KICAD_LEGACY
// I can't put it right now because of the extra code that is above to convert legacy bus-bus
// entries to bus wires
if( schFileType == SCH_IO_MGR::SCH_LEGACY )
Schematic().FixupJunctions();
SyncView();
GetScreen()->ClearDrawingState();
TestDanglingEnds();
UpdateHierarchyNavigator( false );
wxCommandEvent changedEvt( EDA_EVT_SCHEMATIC_CHANGED );
ProcessEventLocally( changedEvt );
for( wxEvtHandler* listener : m_schematicChangeListeners )
{
wxCHECK2( listener, continue );
// Use the windows variant when handling event messages in case there is any special
// event handler pre and/or post processing specific to windows.
wxWindow* win = dynamic_cast<wxWindow*>( listener );
if( win )
win->HandleWindowEvent( e );
else
listener->SafelyProcessEvent( e );
}
updateTitle();
m_toolManager->GetTool<SCH_NAVIGATE_TOOL>()->ResetHistory();
wxFileName fn = Prj().AbsolutePath( GetScreen()->GetFileName() );
if( fn.FileExists() && !fn.IsFileWritable() )
{
m_infoBar->RemoveAllButtons();
m_infoBar->AddCloseButton();
m_infoBar->ShowMessage( _( "Schematic is read only." ),
wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
}
#ifdef PROFILE
openFiles.Show();
#endif
// Ensure all items are redrawn (especially the drawing-sheet items):
if( GetCanvas() )
GetCanvas()->DisplaySheet( GetCurrentSheet().LastScreen() );
return true;
}
void SCH_EDIT_FRAME::OnImportProject( wxCommandEvent& aEvent )
{
if( Schematic().RootScreen() && !Schematic().RootScreen()->Items().empty() )
{
wxString msg = _( "This operation replaces the contents of the current schematic, "
"which will be permanently lost.\n\n"
"Do you want to proceed?" );
if( !IsOK( this, msg ) )
return;
}
// Set the project location if none is set or if we are running in standalone mode
bool setProject = Prj().GetProjectFullName().IsEmpty() || Kiface().IsSingle();
wxString path = wxPathOnly( Prj().GetProjectFullName() );
wxString fileFiltersStr;
wxString allWildcardsStr;
for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
{
if( fileType == SCH_IO_MGR::SCH_KICAD || fileType == SCH_IO_MGR::SCH_LEGACY )
continue; // this is "Import non-KiCad schematic"
IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
if( !pi )
continue;
const IO_BASE::IO_FILE_DESC& desc = pi->GetSchematicFileDesc();
if( desc.m_FileExtensions.empty() || !desc.m_CanRead )
continue;
if( !fileFiltersStr.IsEmpty() )
fileFiltersStr += wxChar( '|' );
fileFiltersStr += desc.FileFilter();
for( const std::string& ext : desc.m_FileExtensions )
allWildcardsStr << wxS( "*." ) << formatWildcardExt( ext ) << wxS( ";" );
}
fileFiltersStr = _( "All supported formats" ) + wxS( "|" ) + allWildcardsStr + wxS( "|" )
+ fileFiltersStr;
wxFileDialog dlg( this, _( "Import Schematic" ), path, wxEmptyString, fileFiltersStr,
wxFD_OPEN | wxFD_FILE_MUST_EXIST ); // TODO
FILEDLG_IMPORT_NON_KICAD importOptions( eeconfig()->m_System.show_import_issues );
dlg.SetCustomizeHook( importOptions );
if( dlg.ShowModal() == wxID_CANCEL )
return;
eeconfig()->m_System.show_import_issues = importOptions.GetShowIssues();
// Don't leave dangling pointers to previously-opened document.
m_toolManager->GetTool<EE_SELECTION_TOOL>()->ClearSelection();
ClearUndoRedoList();
ClearRepeatItemsList();
if( setProject )
{
Schematic().SetProject( nullptr );
GetSettingsManager()->UnloadProject( &Prj(), false );
// Clear view before destroying schematic as repaints depend on schematic being valid
SetScreen( nullptr );
Schematic().Reset();
wxFileName projectFn( dlg.GetPath() );
projectFn.SetExt( FILEEXT::ProjectFileExtension );
GetSettingsManager()->LoadProject( projectFn.GetFullPath() );
Schematic().SetProject( &Prj() );
}
wxFileName fn = dlg.GetPath();
if( !fn.IsFileReadable() )
{
wxLogError( _( "Insufficient permissions to read file '%s'." ), fn.GetFullPath() );
return;
}
SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN;
for( const SCH_IO_MGR::SCH_FILE_T& fileType : SCH_IO_MGR::SCH_FILE_T_vector )
{
IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
if( !pi )
continue;
if( pi->CanReadSchematicFile( fn.GetFullPath() ) )
{
pluginType = fileType;
break;
}
}
if( pluginType == SCH_IO_MGR::SCH_FILE_T::SCH_FILE_UNKNOWN )
{
wxLogError( _( "No loader can read the specified file: '%s'." ), fn.GetFullPath() );
CreateScreens();
SetScreen( Schematic().RootScreen() );
return;
}
importFile( dlg.GetPath(), pluginType );
RefreshCanvas();
}
bool SCH_EDIT_FRAME::saveSchematicFile( SCH_SHEET* aSheet, const wxString& aSavePath )
{
wxString msg;
wxFileName schematicFileName;
wxFileName oldFileName;
bool success;
SCH_SCREEN* screen = aSheet->GetScreen();
wxCHECK( screen, false );
// Cannot save to nowhere
if( aSavePath.IsEmpty() )
return false;
// Construct the name of the file to be saved
schematicFileName = Prj().AbsolutePath( aSavePath );
oldFileName = schematicFileName;
// Write through symlinks, don't replace them
WX_FILENAME::ResolvePossibleSymlinks( schematicFileName );
if( !schematicFileName.DirExists() )
{
if( !wxMkdir( schematicFileName.GetPath() ) )
{
msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
schematicFileName.GetFullPath(),
"Could not create directory: %s" + schematicFileName.GetPath() );
DisplayError( this, msg );
return false;
}
}
if( !IsWritable( schematicFileName ) )
return false;
wxFileName projectFile( schematicFileName );
projectFile.SetExt( FILEEXT::ProjectFileExtension );
if( projectFile.FileExists() )
{
// Save various ERC settings, such as violation severities (which may have been edited
// via the ERC dialog as well as the Schematic Setup dialog), ERC exclusions, etc.
saveProjectSettings();
}
wxString tempFile = wxFileName::CreateTempFileName( wxS( "eeschema" ) );
// Save
wxLogTrace( traceAutoSave, wxS( "Saving file " ) + schematicFileName.GetFullPath() );
if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
m_infoBar->Dismiss();
SCH_IO_MGR::SCH_FILE_T pluginType = SCH_IO_MGR::GuessPluginTypeFromSchPath(
schematicFileName.GetFullPath() );
if( pluginType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
pluginType = SCH_IO_MGR::SCH_KICAD;
IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( pluginType ) );
try
{
pi->SaveSchematicFile( tempFile, aSheet, &Schematic() );
success = true;
}
catch( const IO_ERROR& ioe )
{
msg.Printf( _( "Error saving schematic file '%s'.\n%s" ),
schematicFileName.GetFullPath(),
ioe.What() );
DisplayError( this, msg );
msg.Printf( _( "Failed to create temporary file '%s'." ),
tempFile );
SetMsgPanel( wxEmptyString, msg );
// In case we started a file but didn't fully write it, clean up
wxRemoveFile( tempFile );
success = false;
}
if( success )
{
// Preserve the permissions of the current file
KIPLATFORM::IO::DuplicatePermissions( schematicFileName.GetFullPath(), tempFile );
// Replace the original with the temporary file we just wrote
success = wxRenameFile( tempFile, schematicFileName.GetFullPath() );
if( !success )
{
msg.Printf( _( "Error saving schematic file '%s'.\n"
"Failed to rename temporary file '%s'." ),
schematicFileName.GetFullPath(),
tempFile );
DisplayError( this, msg );
msg.Printf( _( "Failed to rename temporary file '%s'." ),
tempFile );
SetMsgPanel( wxEmptyString, msg );
}
}
if( success )
{
// Delete auto save file.
wxFileName autoSaveFileName = schematicFileName;
autoSaveFileName.SetName( FILEEXT::AutoSaveFilePrefix + schematicFileName.GetName() );
if( autoSaveFileName.FileExists() )
{
wxLogTrace( traceAutoSave,
wxS( "Removing auto save file <" ) + autoSaveFileName.GetFullPath() +
wxS( ">" ) );
wxRemoveFile( autoSaveFileName.GetFullPath() );
}
screen->SetContentModified( false );
msg.Printf( _( "File '%s' saved." ), screen->GetFileName() );
SetStatusText( msg, 0 );
}
else
{
DisplayError( this, _( "File write operation failed." ) );
}
return success;
}
bool SCH_EDIT_FRAME::SaveProject( bool aSaveAs )
{
wxString msg;
SCH_SCREEN* screen;
SCH_SCREENS screens( Schematic().Root() );
bool saveCopy = aSaveAs && !Kiface().IsSingle();
bool success = true;
bool updateFileHistory = false;
bool createNewProject = false;
// I want to see it in the debugger, show me the string! Can't do that with wxFileName.
wxString fileName = Prj().AbsolutePath( Schematic().Root().GetFileName() );
wxFileName fn = fileName;
// Path to save each screen to: will be the stored filename by default, but is overwritten by
// a Save As Copy operation.
std::unordered_map<SCH_SCREEN*, wxString> filenameMap;
// Handle "Save As" and saving a new project/schematic for the first time in standalone
if( Prj().IsNullProject() || aSaveAs )
{
// Null project should only be possible in standalone mode.
wxCHECK( Kiface().IsSingle() || aSaveAs, false );
wxFileName newFileName;
wxFileName savePath( Prj().GetProjectFullName() );
if( !savePath.IsOk() || !savePath.IsDirWritable() )
{
savePath = GetMruPath();
if( !savePath.IsOk() || !savePath.IsDirWritable() )
savePath = PATHS::GetDefaultUserProjectsPath();
}
if( savePath.HasExt() )
savePath.SetExt( FILEEXT::KiCadSchematicFileExtension );
else
savePath.SetName( wxEmptyString );
wxFileDialog dlg( this, _( "Schematic Files" ), savePath.GetPath(), savePath.GetFullName(),
FILEEXT::KiCadSchematicFileWildcard(),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
FILEDLG_HOOK_SAVE_PROJECT newProjectHook;
// Add a "Create a project" checkbox in standalone mode and one isn't loaded
if( Kiface().IsSingle() || aSaveAs )
{
dlg.SetCustomizeHook( newProjectHook );
}
if( dlg.ShowModal() == wxID_CANCEL )
return false;
newFileName = EnsureFileExtension( dlg.GetPath(), FILEEXT::KiCadSchematicFileExtension );
if( ( !newFileName.DirExists() && !newFileName.Mkdir() ) ||
!newFileName.IsDirWritable() )
{
msg.Printf( _( "Folder '%s' could not be created.\n\n"
"Make sure you have write permissions and try again." ),
newFileName.GetPath() );
wxMessageDialog dlgBadPath( this, msg, _( "Error" ),
wxOK | wxICON_EXCLAMATION | wxCENTER );
dlgBadPath.ShowModal();
return false;
}
if( newProjectHook.IsAttachedToDialog() )
createNewProject = newProjectHook.GetCreateNewProject();
if( !saveCopy )
{
Schematic().Root().SetFileName( newFileName.GetFullName() );
Schematic().RootScreen()->SetFileName( newFileName.GetFullPath() );
updateFileHistory = true;
}
else
{
filenameMap[Schematic().RootScreen()] = newFileName.GetFullPath();
}
// Set the base path to all new sheets.
for( size_t i = 0; i < screens.GetCount(); i++ )
{
screen = screens.GetScreen( i );
wxCHECK2( screen, continue );
// The root screen file name has already been set.
if( screen == Schematic().RootScreen() )
continue;
wxFileName tmp = screen->GetFileName();
// Assume existing sheet files are being reused and do not save them to the new
// path. Maybe in the future, add a user option to copy schematic files to the
// new project path.
if( tmp.FileExists() )
continue;
if( tmp.GetPath().IsEmpty() )
{
tmp.SetPath( newFileName.GetPath() );
}
else if( tmp.GetPath() == fn.GetPath() )
{
tmp.SetPath( newFileName.GetPath() );
}
else if( tmp.GetPath().StartsWith( fn.GetPath() ) )
{
// NOTE: this hasn't been tested because the sheet properties dialog no longer
// allows adding a path specifier in the file name field.
wxString newPath = newFileName.GetPath();
newPath += tmp.GetPath().Right( fn.GetPath().Length() );
tmp.SetPath( newPath );
}
wxLogTrace( tracePathsAndFiles,