forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectFileManager.cpp
1453 lines (1232 loc) · 46.1 KB
/
ProjectFileManager.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
/**********************************************************************
Sneedacity: A Digital Audio Editor
ProjectFileManager.cpp
Paul Licameli split from SneedacityProject.cpp
**********************************************************************/
#include "ProjectFileManager.h"
#include <wx/crt.h> // for wxPrintf
#if defined(__WXGTK__)
#include <wx/evtloop.h>
#endif
#include <wx/frame.h>
#include "CodeConversions.h"
#include "Legacy.h"
#include "PlatformCompatibility.h"
#include "Project.h"
#include "ProjectFileIO.h"
#include "ProjectFSCK.h"
#include "ProjectHistory.h"
#include "ProjectSelectionManager.h"
#include "ProjectSettings.h"
#include "ProjectStatus.h"
#include "ProjectWindow.h"
#include "SelectUtilities.h"
#include "SelectionState.h"
#include "Tags.h"
#include "TempDirectory.h"
#include "TrackPanelAx.h"
#include "TrackPanel.h"
#include "UndoManager.h"
#include "WaveTrack.h"
#include "wxFileNameWrapper.h"
#include "export/Export.h"
#include "import/Import.h"
#include "import/ImportMIDI.h"
#include "toolbars/SelectionBar.h"
#include "widgets/SneedacityMessageBox.h"
#include "widgets/ErrorDialog.h"
#include "widgets/FileHistory.h"
#include "widgets/Warning.h"
#include "xml/XMLFileReader.h"
static const SneedacityProject::AttachedObjects::RegisteredFactory sFileManagerKey{
[]( SneedacityProject &parent ){
auto result = std::make_shared< ProjectFileManager >( parent );
return result;
}
};
ProjectFileManager &ProjectFileManager::Get( SneedacityProject &project )
{
return project.AttachedObjects::Get< ProjectFileManager >( sFileManagerKey );
}
const ProjectFileManager &ProjectFileManager::Get( const SneedacityProject &project )
{
return Get( const_cast< SneedacityProject & >( project ) );
}
void ProjectFileManager::DiscardAutosave(const FilePath &filename)
{
InvisibleTemporaryProject tempProject;
auto &project = tempProject.Project();
auto &projectFileManager = Get(project);
// Read the project, discarding autosave
projectFileManager.ReadProjectFile(filename, true);
if (projectFileManager.mLastSavedTracks) {
for (auto wt : projectFileManager.mLastSavedTracks->Any<WaveTrack>())
wt->CloseLock();
projectFileManager.mLastSavedTracks.reset();
}
// Side-effect on database is done, and destructor of tempProject
// closes the temporary project properly
}
ProjectFileManager::ProjectFileManager( SneedacityProject &project )
: mProject{ project }
{
}
ProjectFileManager::~ProjectFileManager() = default;
namespace {
const char *const defaultHelpUrl =
"FAQ:Errors_on_opening_or_recovering_an_Sneedacity_project";
using Pair = std::pair< const char *, const char * >;
const Pair helpURLTable[] = {
{
"not well-formed (invalid token)",
"Error:_not_well-formed_(invalid_token)_at_line_x"
},
{
"reference to invalid character number",
"Error_Opening_Project:_Reference_to_invalid_character_number_at_line_x"
},
{
"mismatched tag",
"#mismatched"
},
// This error with FAQ entry is reported elsewhere, not here....
//#[[#corrupt|Error Opening File or Project: File may be invalid or corrupted]]
};
wxString FindHelpUrl( const TranslatableString &libraryError )
{
wxString helpUrl;
if ( !libraryError.empty() ) {
helpUrl = defaultHelpUrl;
auto msgid = libraryError.MSGID().GET();
auto found = std::find_if( begin(helpURLTable), end(helpURLTable),
[&]( const Pair &pair ) {
return msgid.Contains( pair.first ); }
);
if (found != end(helpURLTable)) {
auto url = found->second;
if (url[0] == '#')
helpUrl += url;
else
helpUrl = url;
}
}
return helpUrl;
}
}
auto ProjectFileManager::ReadProjectFile(
const FilePath &fileName, bool discardAutosave )
-> ReadProjectResults
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get( project );
auto &window = GetProjectFrame( project );
///
/// Parse project file
///
bool bParseSuccess = projectFileIO.LoadProject(fileName, discardAutosave);
bool err = false;
if (bParseSuccess)
{
if (discardAutosave)
// REVIEW: Failure OK?
projectFileIO.AutoSaveDelete();
else if (projectFileIO.IsRecovered()) {
bool resaved = false;
if (!projectFileIO.IsTemporary())
{
// Re-save non-temporary project to its own path. This
// might fail to update the document blob in the database.
resaved = projectFileIO.SaveProject(fileName, nullptr);
}
SneedacityMessageBox(
resaved
? XO("This project was not saved properly the last time Sneedacity ran.\n\n"
"It has been recovered to the last snapshot.")
: XO("This project was not saved properly the last time Sneedacity ran.\n\n"
"It has been recovered to the last snapshot, but you must save it\n"
"to preserve its contents."),
XO("Project Recovered"),
wxICON_WARNING,
&window);
}
// By making a duplicate set of pointers to the existing blocks
// on disk, we add one to their reference count, guaranteeing
// that their reference counts will never reach zero and thus
// the version saved on disk will be preserved until the
// user selects Save().
mLastSavedTracks = TrackList::Create( nullptr );
auto &tracks = TrackList::Get( project );
for (auto t : tracks.Any())
{
if (t->GetErrorOpening())
{
wxLogWarning(
wxT("Track %s had error reading clip values from project file."),
t->GetName());
err = true;
}
err = ( !t->LinkConsistencyCheck() ) || err;
mLastSavedTracks->Add(t->Duplicate());
}
}
return
{
bParseSuccess,
err,
projectFileIO.GetLastError(),
FindHelpUrl(projectFileIO.GetLibraryError())
};
}
bool ProjectFileManager::Save()
{
auto &projectFileIO = ProjectFileIO::Get(mProject);
// Prompt for file name?
if (projectFileIO.IsTemporary())
{
return SaveAs(true);
}
return DoSave(projectFileIO.GetFileName(), false);
}
#if 0
// I added this to "fix" bug #334. At that time, we were on wxWidgets 2.8.12 and
// there was a window between the closing of the "Save" progress dialog and the
// end of the actual save where the user was able to close the project window and
// recursively enter the Save code (where they could inadvertently cause the issue
// described in #334).
//
// When we converted to wx3, this "disabler" caused focus problems when returning
// to the project after the save (bug #1172) because the focus and activate events
// weren't being dispatched and the focus would get lost.
//
// After some testing, it looks like the window described above no longer exists,
// so I've disabled the disabler. However, I'm leaving it here in case we run
// into the problem in the future. (even though it can't be used as-is)
class ProjectDisabler
{
public:
ProjectDisabler(wxWindow *w)
: mWindow(w)
{
mWindow->GetEventHandler()->SetEvtHandlerEnabled(false);
}
~ProjectDisabler()
{
mWindow->GetEventHandler()->SetEvtHandlerEnabled(true);
}
private:
wxWindow *mWindow;
};
#endif
// Assumes ProjectFileIO::mFileName has been set to the desired path.
bool ProjectFileManager::DoSave(const FilePath & fileName, const bool fromSaveAs)
{
// See explanation above
// ProjectDisabler disabler(this);
auto &proj = mProject;
auto &window = GetProjectFrame( proj );
auto &projectFileIO = ProjectFileIO::Get( proj );
const auto &settings = ProjectSettings::Get( proj );
// Some confirmation dialogs
{
if (TempDirectory::FATFilesystemDenied(fileName, XO("Projects cannot be saved to FAT drives.")))
{
return false;
}
auto &tracks = TrackList::Get( proj );
if (!tracks.Any())
{
if (UndoManager::Get( proj ).UnsavedChanges() &&
settings.EmptyCanBeDirty())
{
int result = SneedacityMessageBox(
XO(
"Your project is now empty.\nIf saved, the project will have no tracks.\n\nTo save any previously open tracks:\nClick 'No', Edit > Undo until all tracks\nare open, then File > Save Project.\n\nSave anyway?"),
XO("Warning - Empty Project"),
wxYES_NO | wxICON_QUESTION,
&window);
if (result == wxNO)
{
return false;
}
}
}
wxULongLong fileSize = wxFileName::GetSize(projectFileIO.GetFileName());
wxDiskspaceSize_t freeSpace;
if (wxGetDiskSpace(FileNames::AbbreviatePath(fileName), NULL, &freeSpace))
{
if (freeSpace.GetValue() <= fileSize.GetValue())
{
ShowErrorDialog(
&window,
XO("Insufficient Disk Space"),
XO("The project size exceeds the available free space on the target disk.\n\n"
"Please select a different disk with more free space."),
"Error:_Disk_full_or_not_writable"
);
return false;
}
}
}
// End of confirmations
// Always save a backup of the original project file
Optional<ProjectFileIO::BackupProject> pBackupProject;
if (fromSaveAs && wxFileExists(fileName))
{
pBackupProject.emplace(projectFileIO, fileName);
if (!pBackupProject->IsOk())
return false;
}
if (FileNames::IsOnFATFileSystem(fileName))
{
if (wxFileName::GetSize(projectFileIO.GetFileName()) > UINT32_MAX)
{
ShowErrorDialog(
&window,
XO("Error Saving Project"),
XO("The project exceeds the maximum size of 4GB when writing to a FAT32 formatted filesystem."),
"Error:_Unsuitable_drive"
);
return false;
}
}
bool success = projectFileIO.SaveProject(fileName, mLastSavedTracks.get());
if (!success)
{
// Show this error only if we didn't fail reconnection in SaveProject
// REVIEW: Could HasConnection() be true but SaveProject() still have failed?
if (!projectFileIO.HasConnection())
ShowExceptionDialog(
&window,
XO("Error Saving Project"),
FileException::WriteFailureMessage(fileName),
"Error:_Disk_full_or_not_writable"
);
return false;
}
proj.SetProjectName(wxFileName(fileName).GetName());
projectFileIO.SetProjectTitle();
UndoManager::Get(proj).StateSaved();
ProjectStatus::Get(proj).Set(XO("Saved %s").Format(fileName));
if (mLastSavedTracks)
{
mLastSavedTracks->Clear();
}
mLastSavedTracks = TrackList::Create(nullptr);
auto &tracks = TrackList::Get(proj);
for (auto t : tracks.Any())
{
mLastSavedTracks->Add(t->Duplicate());
}
// If we get here, saving the project was successful, so we can DELETE
// any backup project.
if (pBackupProject)
pBackupProject->Discard();
return true;
}
// This version of SaveAs is invoked only from scripting and does not
// prompt for a file name
bool ProjectFileManager::SaveAs(const FilePath &newFileName, bool addToHistory /*= true*/)
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get( project );
auto oldFileName = projectFileIO.GetFileName();
bool bOwnsNewName = !projectFileIO.IsTemporary() && (oldFileName == newFileName);
//check to see if the NEW project file already exists.
//We should only overwrite it if this project already has the same name, where the user
//simply chose to use the save as command although the save command would have the effect.
if( !bOwnsNewName && wxFileExists(newFileName)) {
SneedacityMessageDialog m(
nullptr,
XO("The project was not saved because the file name provided would overwrite another project.\nPlease try again and select an original name."),
XO("Error Saving Project"),
wxOK|wxICON_ERROR );
m.ShowModal();
return false;
}
auto success = DoSave(newFileName, !bOwnsNewName);
if (success && addToHistory) {
FileHistory::Global().Append( projectFileIO.GetFileName() );
}
return(success);
}
bool ProjectFileManager::SaveAs(bool allowOverwrite /* = false */)
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get( project );
auto &window = GetProjectFrame( project );
TitleRestorer Restorer( window, project ); // RAII
wxFileName filename;
FilePath defaultSavePath = FileNames::FindDefaultPath(FileNames::Operation::Save);
if (projectFileIO.IsTemporary()) {
filename.SetPath(defaultSavePath);
filename.SetName(project.GetProjectName());
}
else {
filename = projectFileIO.GetFileName();
}
// Bug 1304: Set a default file path if none was given. For Save/SaveAs/SaveCopy
if( !FileNames::IsPathAvailable( filename.GetPath( wxPATH_GET_VOLUME| wxPATH_GET_SEPARATOR) ) ){
filename.SetPath(defaultSavePath);
}
TranslatableString title = XO("%sSave Project \"%s\" As...")
.Format( Restorer.sProjNumber, Restorer.sProjName );
TranslatableString message = XO("\
'Save Project' is for an Sneedacity project, not an audio file.\n\
For an audio file that will open in other apps, use 'Export'.\n");
if (ShowWarningDialog(&window, wxT("FirstProjectSave"), message, true) != wxID_OK) {
return false;
}
bool bPrompt = (project.mBatchMode == 0) || (projectFileIO.GetFileName().empty());
FilePath fName;
bool bOwnsNewName;
do {
if (bPrompt) {
// JKC: I removed 'wxFD_OVERWRITE_PROMPT' because we are checking
// for overwrite ourselves later, and we disallow it.
fName = FileNames::SelectFile(FileNames::Operation::Save,
title,
filename.GetPath(),
filename.GetFullName(),
wxT("aup3"),
{ FileNames::SneedacityProjects },
wxFD_SAVE | wxRESIZE_BORDER,
&window);
if (fName.empty())
return false;
filename = fName;
};
filename.SetExt(wxT("aup3"));
if ((!bPrompt || !allowOverwrite) && filename.FileExists()) {
// Saving a copy of the project should never overwrite an existing project.
SneedacityMessageDialog m(
nullptr,
XO("The project was not saved because the file name provided would overwrite another project.\nPlease try again and select an original name."),
XO("Error Saving Project"),
wxOK|wxICON_ERROR );
m.ShowModal();
return false;
}
fName = filename.GetFullPath();
bOwnsNewName = !projectFileIO.IsTemporary() && ( projectFileIO.GetFileName() == fName );
// Check to see if the project file already exists, and if it does
// check that the project file 'belongs' to this project.
// otherwise, prompt the user before overwriting.
if (!bOwnsNewName && filename.FileExists()) {
// Ensure that project of same name is not open in another window.
// fName is the destination file.
// mFileName is this project.
// It is possible for mFileName == fName even when this project is not
// saved to disk, and we then need to check the destination file is not
// open in another window.
int mayOverwrite = ( projectFileIO.GetFileName() == fName ) ? 2 : 1;
for ( auto p : AllProjects{} ) {
const wxFileName openProjectName{ ProjectFileIO::Get(*p).GetFileName() };
if (openProjectName.SameAs(fName)) {
mayOverwrite -= 1;
if (mayOverwrite == 0)
break;
}
}
if (mayOverwrite > 0) {
/* i18n-hint: In each case, %s is the name
of the file being overwritten.*/
auto Message = XO("\
Do you want to overwrite the project:\n\"%s\"?\n\n\
If you select \"Yes\" the project\n\"%s\"\n\
will be irreversibly overwritten.").Format( fName, fName );
// For safety, there should NOT be an option to hide this warning.
int result = SneedacityMessageBox(
Message,
/* i18n-hint: Heading: A warning that a project is about to be overwritten.*/
XO("Overwrite Project Warning"),
wxYES_NO | wxNO_DEFAULT | wxICON_WARNING,
&window);
if (result == wxNO) {
continue;
}
if (result == wxCANCEL) {
return false;
}
}
else {
// Overwrite disallowed. The destination project is open in another window.
SneedacityMessageDialog m(
nullptr,
XO("The project was not saved because the selected project is open in another window.\nPlease try again and select an original name."),
XO("Error Saving Project"),
wxOK|wxICON_ERROR );
m.ShowModal();
continue;
}
}
break;
} while (bPrompt);
auto success = DoSave(fName, !bOwnsNewName);
if (success) {
FileHistory::Global().Append( projectFileIO.GetFileName() );
}
return(success);
}
bool ProjectFileManager::SaveCopy(const FilePath &fileName /* = wxT("") */)
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get(project);
auto &window = GetProjectFrame(project);
TitleRestorer Restorer(window, project); // RAII
wxFileName filename = fileName;
FilePath defaultSavePath = FileNames::FindDefaultPath(FileNames::Operation::Save);
if (fileName.empty())
{
if (projectFileIO.IsTemporary())
{
filename.SetPath(defaultSavePath);
}
else
{
filename = projectFileIO.GetFileName();
}
}
// Bug 1304: Set a default file path if none was given. For Save/SaveAs/SaveCopy
if (!FileNames::IsPathAvailable(filename.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR)))
{
filename.SetPath(defaultSavePath);
}
TranslatableString title =
XO("%sSave Copy of Project \"%s\" As...")
.Format(Restorer.sProjNumber, Restorer.sProjName);
bool bPrompt = (project.mBatchMode == 0) || (projectFileIO.GetFileName().empty());
FilePath fName;
do
{
if (bPrompt)
{
// JKC: I removed 'wxFD_OVERWRITE_PROMPT' because we are checking
// for overwrite ourselves later, and we disallow it.
// Previously we disallowed overwrite because we would have had
// to DELETE the many smaller files too, or prompt to move them.
// Maybe we could allow it now that we have aup3 format?
fName = FileNames::SelectFile(FileNames::Operation::Export,
title,
filename.GetPath(),
filename.GetFullName(),
wxT("aup3"),
{ FileNames::SneedacityProjects },
wxFD_SAVE | wxRESIZE_BORDER,
&window);
if (fName.empty())
{
return false;
}
filename = fName;
};
filename.SetExt(wxT("aup3"));
if (TempDirectory::FATFilesystemDenied(filename.GetFullPath(), XO("Projects cannot be saved to FAT drives.")))
{
if (project.mBatchMode)
{
return false;
}
continue;
}
if (filename.FileExists())
{
// Saving a copy of the project should never overwrite an existing project.
SneedacityMessageDialog m(nullptr,
XO("Saving a copy must not overwrite an existing saved project.\nPlease try again and select an original name."),
XO("Error Saving Copy of Project"),
wxOK | wxICON_ERROR);
m.ShowModal();
if (project.mBatchMode)
{
return false;
}
continue;
}
wxULongLong fileSize = wxFileName::GetSize(projectFileIO.GetFileName());
wxDiskspaceSize_t freeSpace;
if (wxGetDiskSpace(FileNames::AbbreviatePath(filename.GetFullPath()), NULL, &freeSpace))
{
if (freeSpace.GetValue() <= fileSize.GetValue())
{
ShowErrorDialog(
&window,
XO("Insufficient Disk Space"),
XO("The project size exceeds the available free space on the target disk.\n\n"
"Please select a different disk with more free space."),
"Error:_Unsuitable_drive"
);
continue;
}
}
if (FileNames::IsOnFATFileSystem(filename.GetFullPath()))
{
if (fileSize > UINT32_MAX)
{
ShowErrorDialog(
&window,
XO("Error Saving Project"),
XO("The project exceeds the maximum size of 4GB when writing to a FAT32 formatted filesystem."),
"Error:_Unsuitable_drive"
);
if (project.mBatchMode)
{
return false;
}
continue;
}
}
fName = filename.GetFullPath();
break;
} while (bPrompt);
if (!projectFileIO.SaveCopy(fName))
{
auto msg = FileException::WriteFailureMessage(fName);
SneedacityMessageDialog m(
nullptr, msg, XO("Error Saving Project"), wxOK | wxICON_ERROR);
m.ShowModal();
return false;
}
return true;
}
bool ProjectFileManager::SaveFromTimerRecording(wxFileName fnFile)
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get( project );
// MY: Will save the project to a NEW location a-la Save As
// and then tidy up after itself.
wxString sNewFileName = fnFile.GetFullPath();
// MY: To allow SaveAs from Timer Recording we need to check what
// the value of mFileName is before we change it.
FilePath sOldFilename;
if (!projectFileIO.IsModified()) {
sOldFilename = projectFileIO.GetFileName();
}
// MY: If the project file already exists then bail out
// and send populate the message string (pointer) so
// we can tell the user what went wrong.
if (wxFileExists(sNewFileName)) {
return false;
}
auto success = DoSave(sNewFileName, true);
if (success) {
FileHistory::Global().Append( projectFileIO.GetFileName() );
}
return success;
}
void ProjectFileManager::CompactProjectOnClose()
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get(project);
// Lock all blocks in all tracks of the last saved version, so that
// the sample blocks aren't deleted from the database when we destroy the
// sample block objects in memory.
if (mLastSavedTracks)
{
for (auto wt : mLastSavedTracks->Any<WaveTrack>())
{
wt->CloseLock();
}
// Attempt to compact the project
projectFileIO.Compact( { mLastSavedTracks.get() } );
if ( !projectFileIO.WasCompacted() &&
UndoManager::Get( project ).UnsavedChanges() ) {
// If compaction failed, we must do some work in case of close
// without save. Don't leave the document blob from the last
// push of undo history, when that undo state may get purged
// with deletion of some new sample blocks.
// REVIEW: UpdateSaved() might fail too. Do we need to test
// for that and report it?
projectFileIO.UpdateSaved( mLastSavedTracks.get() );
}
}
}
bool ProjectFileManager::OpenProject()
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get(project);
return projectFileIO.OpenProject();
}
bool ProjectFileManager::OpenNewProject()
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get(project);
bool bOK = OpenProject();
if( !bOK )
{
ShowExceptionDialog(
nullptr,
XO("Can't open new empty project"),
XO("Error opening a new empty project"),
"FAQ:Errors_opening_a_new_empty_project",
true,
sneedacity::ToWString(projectFileIO.GetLastLog()));
}
return bOK;
}
void ProjectFileManager::CloseProject()
{
auto &project = mProject;
auto &projectFileIO = ProjectFileIO::Get(project);
projectFileIO.CloseProject();
// Blocks were locked in CompactProjectOnClose, so DELETE the data structure so that
// there's no memory leak.
if (mLastSavedTracks)
{
mLastSavedTracks->Clear();
mLastSavedTracks.reset();
}
}
// static method, can be called outside of a project
wxArrayString ProjectFileManager::ShowOpenDialog(FileNames::Operation op,
const FileNames::FileType &extraType )
{
// Construct the filter
const auto fileTypes = Importer::Get().GetFileTypes( extraType );
// Retrieve saved path
auto path = FileNames::FindDefaultPath(op);
// Construct and display the file dialog
wxArrayString selected;
FileDialogWrapper dlog(nullptr,
XO("Select one or more files"),
path,
wxT(""),
fileTypes,
wxFD_OPEN | wxFD_MULTIPLE | wxRESIZE_BORDER);
dlog.SetFilterIndex( Importer::SelectDefaultOpenType( fileTypes ) );
int dialogResult = dlog.ShowModal();
// Convert the filter index to type and save
auto index = dlog.GetFilterIndex();
const auto &saveType = fileTypes[ index ];
Importer::SetDefaultOpenType( saveType );
Importer::SetLastOpenType( saveType );
if (dialogResult == wxID_OK) {
// Return the selected files
dlog.GetPaths(selected);
// Remember the directory
FileNames::UpdateDefaultPath(op, ::wxPathOnly(dlog.GetPath()));
}
return selected;
}
// static method, can be called outside of a project
bool ProjectFileManager::IsAlreadyOpen(const FilePath &projPathName)
{
const wxFileName newProjPathName(projPathName);
auto start = AllProjects{}.begin(), finish = AllProjects{}.end(),
iter = std::find_if( start, finish,
[&]( const AllProjects::value_type &ptr ){
return newProjPathName.SameAs(wxFileNameWrapper{ ProjectFileIO::Get(*ptr).GetFileName() });
} );
if (iter != finish) {
auto errMsg =
XO("%s is already open in another window.")
.Format( newProjPathName.GetName() );
wxLogError(errMsg.Translation()); //Debug?
SneedacityMessageBox(
errMsg,
XO("Error Opening Project"),
wxOK | wxCENTRE);
return true;
}
return false;
}
SneedacityProject *ProjectFileManager::OpenFile( const ProjectChooserFn &chooser,
const FilePath &fileNameArg, bool addtohistory)
{
// On Win32, we may be given a short (DOS-compatible) file name on rare
// occasions (e.g. stuff like "C:\PROGRA~1\AUDACI~1\PROJEC~1.AUP"). We
// convert these to long file name first.
auto fileName = PlatformCompatibility::GetLongFileName(fileNameArg);
// Make sure it isn't already open.
// Vaughan, 2011-03-25: This was done previously in SneedacityProject::OpenFiles()
// and SneedacityApp::MRUOpen(), but if you open an aup file by double-clicking it
// from, e.g., Win Explorer, it would bypass those, get to here with no check,
// then open a NEW project from the same data with no warning.
// This was reported in http://bugzilla.sneedacityteam.org/show_bug.cgi?id=137#c17,
// but is not really part of that bug. Anyway, prevent it!
if (IsAlreadyOpen(fileName))
return nullptr;
// Data loss may occur if users mistakenly try to open ".aup3.bak" files
// left over from an unsuccessful save or by previous versions of Sneedacity.
// So we always refuse to open such files.
if (fileName.Lower().EndsWith(wxT(".aup3.bak")))
{
SneedacityMessageBox(
XO(
"You are trying to open an automatically created backup file.\nDoing this may result in severe data loss.\n\nPlease open the actual Sneedacity project file instead."),
XO("Warning - Backup File Detected"),
wxOK | wxCENTRE,
nullptr);
return nullptr;
}
if (!::wxFileExists(fileName)) {
SneedacityMessageBox(
XO("Could not open file: %s").Format( fileName ),
XO("Error Opening File"),
wxOK | wxCENTRE,
nullptr);
return nullptr;
}
// Following block covers cases other than a project file:
{
wxFFile ff(fileName, wxT("rb"));
auto cleanup = finally([&]
{
if (ff.IsOpened())
{
ff.Close();
}
});
if (!ff.IsOpened()) {
SneedacityMessageBox(
XO("Could not open file: %s").Format( fileName ),
XO("Error opening file"),
wxOK | wxCENTRE,
nullptr);
return nullptr;
}
char buf[7];
auto numRead = ff.Read(buf, 6);
if (numRead != 6) {
SneedacityMessageBox(
XO("File may be invalid or corrupted: \n%s").Format( fileName ),
XO("Error Opening File or Project"),
wxOK | wxCENTRE,
nullptr);
return nullptr;
}
if (wxStrncmp(buf, "SQLite", 6) != 0)
{
// Not a database
#ifdef EXPERIMENTAL_DRAG_DROP_PLUG_INS
// Is it a plug-in?
if (PluginManager::Get().DropFile(fileName)) {
MenuCreator::RebuildAllMenuBars();
// Plug-in installation happened, not really opening of a file,
// so return null
return nullptr;
}
#endif
#ifdef USE_MIDI
if (FileNames::IsMidi(fileName)) {
auto &project = chooser(false);
// If this succeeds, indo history is incremented, and it also does
// ZoomAfterImport:
if(DoImportMIDI(project, fileName))
return &project;
return nullptr;
}
#endif
auto &project = chooser(false);
// Undo history is incremented inside this:
if (Get(project).Import(fileName)) {
// Undo history is incremented inside this:
// Bug 2743: Don't zoom with lof.
if (!fileName.AfterLast('.').IsSameAs(wxT("lof"), false))
ProjectWindow::Get(project).ZoomAfterImport(nullptr);
return &project;
}
return nullptr;
}
}
// Disallow opening of .aup3 project files from FAT drives, but only such
// files, not importable types. (Bug 2800)
if (TempDirectory::FATFilesystemDenied(fileName,
XO("Project resides on FAT formatted drive.\n"
"Copy it to another drive to open it.")))
{
return nullptr;
}
auto &project = chooser(true);
return Get(project).OpenProjectFile(fileName, addtohistory);
}
SneedacityProject *ProjectFileManager::OpenProjectFile(
const FilePath &fileName, bool addtohistory)
{
auto &project = mProject;
auto &history = ProjectHistory::Get( project );
auto &tracks = TrackList::Get( project );
auto &trackPanel = TrackPanel::Get( project );
auto &projectFileIO = ProjectFileIO::Get( project );
auto &window = ProjectWindow::Get( project );
auto results = ReadProjectFile( fileName );
const bool bParseSuccess = results.parseSuccess;
const auto &errorStr = results.errorString;
const bool err = results.trackError;