forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectFileIO.cpp
2641 lines (2266 loc) · 74.1 KB
/
ProjectFileIO.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
ProjectFileIO.cpp
Paul Licameli split from SneedacityProject.cpp
**********************************************************************/
#include "ProjectFileIO.h"
#include <atomic>
#include <sqlite3.h>
#include <wx/crt.h>
#include <wx/frame.h>
#include <wx/progdlg.h>
#include <wx/sstream.h>
#include <wx/xml/xml.h>
#include "ActiveProjects.h"
#include "CodeConversions.h"
#include "DBConnection.h"
#include "Project.h"
#include "ProjectFileIORegistry.h"
#include "ProjectSerializer.h"
#include "ProjectSettings.h"
#include "SampleBlock.h"
#include "Tags.h"
#include "TempDirectory.h"
#include "ViewInfo.h"
#include "WaveTrack.h"
#include "widgets/SneedacityMessageBox.h"
#include "widgets/ErrorDialog.h"
#include "widgets/NumericTextCtrl.h"
#include "widgets/ProgressDialog.h"
#include "wxFileNameWrapper.h"
#include "xml/XMLFileReader.h"
// Don't change this unless the file format changes
// in an irrevocable way
#define SNEEDACITY_FILE_FORMAT_VERSION "1.3.0"
#undef NO_SHM
#if !defined(__WXMSW__)
#define NO_SHM
#endif
wxDEFINE_EVENT(EVT_PROJECT_TITLE_CHANGE, wxCommandEvent);
wxDEFINE_EVENT( EVT_CHECKPOINT_FAILURE, wxCommandEvent);
wxDEFINE_EVENT( EVT_RECONNECTION_FAILURE, wxCommandEvent);
// Used to convert 4 byte-sized values into an integer for use in SQLite
// PRAGMA statements. These values will be store in the database header.
//
// Note that endianness is not an issue here since SQLite integers are
// architecture independent.
#define PACK(b1, b2, b3, b4) ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4)
// The ProjectFileID is stored in the SQLite database header to identify the file
// as an Sneedacity project file. It can be used by applications that identify file
// types, such as the Linux "file" command.
static const int ProjectFileID = PACK('A', 'U', 'D', 'Y');
// The "ProjectFileVersion" represents the version of Sneedacity at which a specific
// database schema was used. It is assumed that any changes to the database schema
// will require a new Sneedacity version so if schema changes are required set this
// to the new release being produced.
//
// This version is checked before accessing any tables in the database since there's
// no guarantee what tables exist. If it's found that the database is newer than the
// currently running Sneedacity, an error dialog will be displayed informing the user
// that they need a newer version of Sneedacity.
//
// Note that this is NOT the "schema_version" that SQLite maintains. The value
// specified here is stored in the "user_version" field of the SQLite database
// header.
static const int ProjectFileVersion = PACK(3, 0, 0, 0);
// Navigation:
//
// Bindings are marked out in the code by, e.g.
// BIND SQL sampleblocks
// A search for "BIND SQL" will find all bindings.
// A search for "SQL sampleblocks" will find all SQL related
// to sampleblocks.
static const char *ProjectFileSchema =
// These are persistent and not connection based
//
// See the CMakeList.txt for the SQLite lib for more
// settings.
"PRAGMA <schema>.application_id = %d;"
"PRAGMA <schema>.user_version = %d;"
""
// project is a binary representation of an XML file.
// it's in binary for speed.
// One instance only. id is always 1.
// dict is a dictionary of fieldnames.
// doc is the binary representation of the XML
// in the doc, fieldnames are replaced by 2 byte dictionary
// index numbers.
// This is all opaque to SQLite. It just sees two
// big binary blobs.
// There is no limit to document blob size.
// dict will be smallish, with an entry for each
// kind of field.
"CREATE TABLE IF NOT EXISTS <schema>.project"
"("
" id INTEGER PRIMARY KEY,"
" dict BLOB,"
" doc BLOB"
");"
""
// CREATE SQL autosave
// autosave is a binary representation of an XML file.
// it's in binary for speed.
// One instance only. id is always 1.
// dict is a dictionary of fieldnames.
// doc is the binary representation of the XML
// in the doc, fieldnames are replaced by 2 byte dictionary
// index numbers.
// This is all opaque to SQLite. It just sees two
// big binary blobs.
// There is no limit to document blob size.
// dict will be smallish, with an entry for each
// kind of field.
"CREATE TABLE IF NOT EXISTS <schema>.autosave"
"("
" id INTEGER PRIMARY KEY,"
" dict BLOB,"
" doc BLOB"
");"
""
// CREATE SQL sampleblocks
// 'samples' are fixed size blocks of int16, int32 or float32 numbers.
// The blocks may be partially empty.
// The quantity of valid data in the blocks is
// provided in the project blob.
//
// sampleformat specifies the format of the samples stored.
//
// blockID is a 64 bit number.
//
// Rows are immutable -- never updated after addition, but may be
// deleted.
//
// summin to summary64K are summaries at 3 distance scales.
"CREATE TABLE IF NOT EXISTS <schema>.sampleblocks"
"("
" blockid INTEGER PRIMARY KEY AUTOINCREMENT,"
" sampleformat INTEGER,"
" summin REAL,"
" summax REAL,"
" sumrms REAL,"
" summary256 BLOB,"
" summary64k BLOB,"
" samples BLOB"
");";
// This singleton handles initialization/shutdown of the SQLite library.
// It is needed because our local SQLite is built with SQLITE_OMIT_AUTOINIT
// defined.
//
// It's safe to use even if a system version of SQLite is used that didn't
// have SQLITE_OMIT_AUTOINIT defined.
class SQLiteIniter
{
public:
SQLiteIniter()
{
// Enable URI filenames for all connections
mRc = sqlite3_config(SQLITE_CONFIG_URI, 1);
if (mRc == SQLITE_OK)
{
mRc = sqlite3_config(SQLITE_CONFIG_LOG, LogCallback, nullptr);
if (mRc == SQLITE_OK)
{
mRc = sqlite3_initialize();
}
}
#ifdef NO_SHM
if (mRc == SQLITE_OK)
{
// Use the "unix-excl" VFS to make access to the DB exclusive. This gets
// rid of the "<database name>-shm" shared memory file.
//
// Though it shouldn't, it doesn't matter if this fails.
auto vfs = sqlite3_vfs_find("unix-excl");
if (vfs)
{
sqlite3_vfs_register(vfs, 1);
}
}
#endif
}
~SQLiteIniter()
{
// This function must be called single-threaded only
// It returns a value, but there's nothing we can do with it
(void) sqlite3_shutdown();
}
static void LogCallback(void *WXUNUSED(arg), int code, const char *msg)
{
wxLogMessage("sqlite3 message: (%d) %s", code, msg);
}
int mRc;
};
bool ProjectFileIO::InitializeSQL()
{
static SQLiteIniter sqliteIniter;
return sqliteIniter.mRc == SQLITE_OK;
}
static void RefreshAllTitles(bool bShowProjectNumbers )
{
for ( auto pProject : AllProjects{} ) {
if ( !GetProjectFrame( *pProject ).IsIconized() ) {
ProjectFileIO::Get( *pProject ).SetProjectTitle(
bShowProjectNumbers ? pProject->GetProjectNumber() : -1 );
}
}
}
TitleRestorer::TitleRestorer(
wxTopLevelWindow &window, SneedacityProject &project )
{
if( window.IsIconized() )
window.Restore();
window.Raise(); // May help identifying the window on Mac
// Construct this project's name and number.
sProjName = project.GetProjectName();
if ( sProjName.empty() ) {
sProjName = _("<untitled>");
UnnamedCount = std::count_if(
AllProjects{}.begin(), AllProjects{}.end(),
[]( const AllProjects::value_type &ptr ){
return ptr->GetProjectName().empty();
}
);
if ( UnnamedCount > 1 ) {
sProjNumber.Printf(
_("[Project %02i] "), project.GetProjectNumber() + 1 );
RefreshAllTitles( true );
}
}
else
UnnamedCount = 0;
}
TitleRestorer::~TitleRestorer() {
if( UnnamedCount > 1 )
RefreshAllTitles( false );
}
static const SneedacityProject::AttachedObjects::RegisteredFactory sFileIOKey{
[]( SneedacityProject &parent ){
auto result = std::make_shared< ProjectFileIO >( parent );
return result;
}
};
ProjectFileIO &ProjectFileIO::Get( SneedacityProject &project )
{
auto &result = project.AttachedObjects::Get< ProjectFileIO >( sFileIOKey );
return result;
}
const ProjectFileIO &ProjectFileIO::Get( const SneedacityProject &project )
{
return Get( const_cast< SneedacityProject & >( project ) );
}
ProjectFileIO::ProjectFileIO(SneedacityProject &project)
: mProject{ project }
, mpErrors{ std::make_shared<DBConnectionErrors>() }
{
mPrevConn = nullptr;
mRecovered = false;
mModified = false;
mTemporary = true;
UpdatePrefs();
}
ProjectFileIO::~ProjectFileIO()
{
}
bool ProjectFileIO::HasConnection() const
{
auto &connectionPtr = ConnectionPtr::Get( mProject );
return connectionPtr.mpConnection != nullptr;
}
DBConnection &ProjectFileIO::GetConnection()
{
auto &curConn = CurrConn();
if (!curConn)
{
if (!OpenConnection())
{
throw SimpleMessageBoxException
{
ExceptionType::Internal,
XO("Failed to open the project's database"),
XO("Warning"),
"Error:_Disk_full_or_not_writable"
};
}
}
return *curConn;
}
wxString ProjectFileIO::GenerateDoc()
{
auto &trackList = TrackList::Get( mProject );
XMLStringWriter doc;
WriteXMLHeader(doc);
WriteXML(doc, false, trackList.empty() ? nullptr : &trackList);
return doc;
}
sqlite3 *ProjectFileIO::DB()
{
return GetConnection().DB();
}
/*!
@pre *CurConn() does not exist
@post *CurConn() exists or return value is false
*/
bool ProjectFileIO::OpenConnection(FilePath fileName /* = {} */)
{
auto &curConn = CurrConn();
wxASSERT(!curConn);
bool isTemp = false;
if (fileName.empty())
{
fileName = GetFileName();
if (fileName.empty())
{
fileName = TempDirectory::UnsavedProjectFileName();
isTemp = true;
}
}
else
{
// If this project resides in the temporary directory, then we'll mark it
// as temporary.
wxFileName temp(TempDirectory::TempDir(), wxT(""));
wxFileName file(fileName);
file.SetFullName(wxT(""));
if (file == temp)
{
isTemp = true;
}
}
// Pass weak_ptr to project into DBConnection constructor
curConn = std::make_unique<DBConnection>(
mProject.shared_from_this(), mpErrors, [this]{ OnCheckpointFailure(); } );
auto rc = curConn->Open(fileName);
if (rc != SQLITE_OK)
{
// Must use SetError() here since we do not have an active DB
SetError(
XO("Failed to open database file:\n\n%s").Format(fileName),
{},
rc
);
curConn.reset();
return false;
}
if (!CheckVersion())
{
CloseConnection();
curConn.reset();
return false;
}
mTemporary = isTemp;
SetFileName(fileName);
return true;
}
bool ProjectFileIO::CloseConnection()
{
auto &curConn = CurrConn();
if (!curConn)
return false;
if (!curConn->Close())
{
return false;
}
curConn.reset();
SetFileName({});
return true;
}
// Put the current database connection aside, keeping it open, so that
// another may be opened with OpenConnection()
void ProjectFileIO::SaveConnection()
{
// Should do nothing in proper usage, but be sure not to leak a connection:
DiscardConnection();
mPrevConn = std::move(CurrConn());
mPrevFileName = mFileName;
mPrevTemporary = mTemporary;
SetFileName({});
}
// Close any set-aside connection
void ProjectFileIO::DiscardConnection()
{
if (mPrevConn)
{
if (!mPrevConn->Close())
{
// Store an error message
SetDBError(
XO("Failed to discard connection")
);
}
// If this is a temporary project, we no longer want to keep the
// project file.
if (mPrevTemporary)
{
// This is just a safety check.
wxFileName temp(TempDirectory::TempDir(), wxT(""));
wxFileName file(mPrevFileName);
file.SetFullName(wxT(""));
if (file == temp)
{
if (!RemoveProject(mPrevFileName))
{
wxLogMessage("Failed to remove temporary project %s", mPrevFileName);
}
}
}
mPrevConn = nullptr;
mPrevFileName.clear();
}
}
// Close any current connection and switch back to using the saved
void ProjectFileIO::RestoreConnection()
{
auto &curConn = CurrConn();
if (curConn)
{
if (!curConn->Close())
{
// Store an error message
SetDBError(
XO("Failed to restore connection")
);
}
}
curConn = std::move(mPrevConn);
SetFileName(mPrevFileName);
mTemporary = mPrevTemporary;
mPrevFileName.clear();
}
void ProjectFileIO::UseConnection(Connection &&conn, const FilePath &filePath)
{
auto &curConn = CurrConn();
wxASSERT(!curConn);
curConn = std::move(conn);
SetFileName(filePath);
}
static int ExecCallback(void *data, int cols, char **vals, char **names)
{
auto &cb = *static_cast<const ProjectFileIO::ExecCB *>(data);
// Be careful not to throw anything across sqlite3's stack frames.
return GuardedCall<int>(
[&]{ return cb(cols, vals, names); },
MakeSimpleGuard( 1 )
);
}
int ProjectFileIO::Exec(const char *query, const ExecCB &callback)
{
char *errmsg = nullptr;
const void *ptr = &callback;
int rc = sqlite3_exec(DB(), query, ExecCallback,
const_cast<void*>(ptr), &errmsg);
if (rc != SQLITE_ABORT && errmsg)
{
SetDBError(
XO("Failed to execute a project file command:\n\n%s").Format(query),
Verbatim(errmsg),
rc
);
}
if (errmsg)
{
sqlite3_free(errmsg);
}
return rc;
}
bool ProjectFileIO::Query(const char *sql, const ExecCB &callback)
{
int rc = Exec(sql, callback);
// SQLITE_ABORT is a non-error return only meaning the callback
// stopped the iteration of rows early
if ( !(rc == SQLITE_OK || rc == SQLITE_ABORT) )
{
return false;
}
return true;
}
bool ProjectFileIO::GetValue(const char *sql, wxString &result)
{
// Retrieve the first column in the first row, if any
result.clear();
auto cb = [&result](int cols, char **vals, char **){
if (cols > 0)
result = vals[0];
// Stop after one row
return 1;
};
return Query(sql, cb);
}
bool ProjectFileIO::GetBlob(const char *sql, wxMemoryBuffer &buffer)
{
auto db = DB();
int rc;
buffer.Clear();
sqlite3_stmt *stmt = nullptr;
auto cleanup = finally([&]
{
if (stmt)
{
sqlite3_finalize(stmt);
}
});
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK)
{
SetDBError(
XO("Unable to prepare project file command:\n\n%s").Format(sql)
);
return false;
}
rc = sqlite3_step(stmt);
// A row wasn't found...not an error
if (rc == SQLITE_DONE)
{
return true;
}
if (rc != SQLITE_ROW)
{
SetDBError(
XO("Failed to retrieve data from the project file.\nThe following command failed:\n\n%s").Format(sql)
);
// AUD TODO handle error
return false;
}
const void *blob = sqlite3_column_blob(stmt, 0);
int size = sqlite3_column_bytes(stmt, 0);
buffer.AppendData(blob, size);
return true;
}
bool ProjectFileIO::CheckVersion()
{
auto db = DB();
int rc;
// Install our schema if this is an empty DB
wxString result;
if (!GetValue("SELECT Count(*) FROM sqlite_master WHERE type='table';", result))
{
// Bug 2718 workaround for a better error message:
// If at this point we get SQLITE_CANTOPEN, then the directory is read-only
if (GetLastErrorCode() == SQLITE_CANTOPEN)
{
SetError(
/* i18n-hint: An error message. */
XO("Project is in a read only directory\n(Unable to create the required temporary files)"),
GetLibraryError()
);
}
return false;
}
// If the return count is zero, then there are no tables defined, so this
// must be a new project file.
if (wxStrtol<char **>(result, nullptr, 10) == 0)
{
return InstallSchema(db);
}
// Check for our application ID
if (!GetValue("PRAGMA application_ID;", result))
{
return false;
}
// It's a database that SQLite recognizes, but it's not one of ours
if (wxStrtoul<char **>(result, nullptr, 10) != ProjectFileID)
{
SetError(XO("This is not an Sneedacity project file"));
return false;
}
// Get the project file version
if (!GetValue("PRAGMA user_version;", result))
{
return false;
}
long version = wxStrtol<char **>(result, nullptr, 10);
// Project file version is higher than ours. We will refuse to
// process it since we can't trust anything about it.
if (version > ProjectFileVersion)
{
SetError(
XO("This project was created with a newer version of Sneedacity.\n\nYou will need to upgrade to open it.")
);
return false;
}
// Project file is older than ours, ask the user if it's okay to
// upgrade.
if (version < ProjectFileVersion)
{
return UpgradeSchema();
}
return true;
}
bool ProjectFileIO::InstallSchema(sqlite3 *db, const char *schema /* = "main" */)
{
int rc;
wxString sql;
sql.Printf(ProjectFileSchema, ProjectFileID, ProjectFileVersion);
sql.Replace("<schema>", schema);
rc = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);
if (rc != SQLITE_OK)
{
SetDBError(
XO("Unable to initialize the project file")
);
return false;
}
return true;
}
bool ProjectFileIO::UpgradeSchema()
{
// To do
return true;
}
// The orphan block handling should be removed once autosave and related
// blocks become part of the same transaction.
// An SQLite function that takes a blockid and looks it up in a set of
// blockids captured during project load. If the blockid isn't found
// in the set, it will be deleted.
void ProjectFileIO::InSet(sqlite3_context *context, int argc, sqlite3_value **argv)
{
BlockIDs *blockids = (BlockIDs *) sqlite3_user_data(context);
SampleBlockID blockid = sqlite3_value_int64(argv[0]);
sqlite3_result_int(context, blockids->find(blockid) != blockids->end());
}
bool ProjectFileIO::DeleteBlocks(const BlockIDs &blockids, bool complement)
{
auto db = DB();
int rc;
auto cleanup = finally([&]
{
// Remove our function, whether it was successfully defined or not.
sqlite3_create_function(db, "inset", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr, nullptr, nullptr, nullptr);
});
// Add the function used to verify each row's blockid against the set of active blockids
const void *p = &blockids;
rc = sqlite3_create_function(db, "inset", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, const_cast<void*>(p), InSet, nullptr, nullptr);
if (rc != SQLITE_OK)
{
/* i18n-hint: An error message. Don't translate inset or blockids.*/
SetDBError(XO("Unable to add 'inset' function (can't verify blockids)"));
return false;
}
// Delete all rows in the set, or not in it
// This is the first command that writes to the database, and so we
// do more informative error reporting than usual, if it fails.
auto sql = wxString::Format(
"DELETE FROM sampleblocks WHERE %sinset(blockid);",
complement ? "NOT " : "" );
rc = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);
if (rc != SQLITE_OK)
{
if( rc==SQLITE_READONLY)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Project is read only\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_LOCKED)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Project is locked\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_BUSY)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Project is busy\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_CORRUPT)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Project is corrupt\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_PERM)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Some permissions issue\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_IOERR)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("A disk I/O error\n(Unable to work with the blockfiles)"));
else if( rc==SQLITE_AUTH)
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Not authorized\n(Unable to work with the blockfiles)"));
else
/* i18n-hint: An error message. Don't translate blockfiles.*/
SetDBError(XO("Unable to work with the blockfiles"));
return false;
}
// Mark the project recovered if we deleted any rows
int changes = sqlite3_changes(db);
if (changes > 0)
{
wxLogInfo(XO("Total orphan blocks deleted %d").Translation(), changes);
mRecovered = true;
}
return true;
}
bool ProjectFileIO::CopyTo(const FilePath &destpath,
const TranslatableString &msg,
bool isTemporary,
bool prune /* = false */,
const std::vector<const TrackList *> &tracks /* = {} */)
{
auto pConn = CurrConn().get();
if (!pConn)
return false;
// Get access to the active tracklist
auto pProject = &mProject;
SampleBlockIDSet blockids;
// Collect all active blockids
if (prune)
{
for (auto trackList : tracks)
if (trackList)
InspectBlocks( *trackList, {}, &blockids );
}
// Collect ALL blockids
else
{
auto cb = [&blockids](int cols, char **vals, char **){
SampleBlockID blockid;
wxString{ vals[0] }.ToLongLong(&blockid);
blockids.insert(blockid);
return 0;
};
if (!Query("SELECT blockid FROM sampleblocks;", cb))
{
// Error message already captured.
return false;
}
}
// Create the project doc
ProjectSerializer doc;
WriteXMLHeader(doc);
WriteXML(doc, false, tracks.empty() ? nullptr : tracks[0]);
auto db = DB();
Connection destConn = nullptr;
bool success = false;
int rc = SQLITE_OK;
ProgressResult res = ProgressResult::Success;
// Cleanup in case things go awry
auto cleanup = finally([&]
{
if (!success)
{
if (destConn)
{
destConn->Close();
destConn = nullptr;
}
// Rollback transaction in case one was active.
// If this fails (probably due to memory or disk space), the transaction will
// (presumably) stil be active, so further updates to the project file will
// fail as well. Not really much we can do about it except tell the user.
auto result = sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr);
// Only capture the error if there wasn't a previous error
if (result != SQLITE_OK && (rc == SQLITE_DONE || rc == SQLITE_OK))
{
SetDBError(
XO("Failed to rollback transaction during import")
);
}
// And detach the outbound DB in case (if it's attached). Don't check for
// errors since it may not be attached. But, if it is and the DETACH fails,
// subsequent CopyTo() actions will fail until Sneedacity is relaunched.
sqlite3_exec(db, "DETACH DATABASE outbound;", nullptr, nullptr, nullptr);
// RemoveProject not necessary to clean up attached database
wxRemoveFile(destpath);
}
});
// Attach the destination database
wxString sql;
wxString dbName = destpath;
// Bug 2793: Quotes in name need escaping for sqlite3.
dbName.Replace( "'", "''");
sql.Printf("ATTACH DATABASE '%s' AS outbound;", dbName.ToUTF8());
rc = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);
if (rc != SQLITE_OK)
{
SetDBError(
XO("Unable to attach destination database")
);
return false;
}
// Ensure attached DB connection gets configured
//
// NOTE: Between the above attach and setting the mode here, a normal DELETE
// mode journal will be used and will briefly appear in the filesystem.
if ( pConn->FastMode("outbound") != SQLITE_OK)
{
SetDBError(
XO("Unable to switch to fast journaling mode")
);
return false;
}
// Install our schema into the new database
if (!InstallSchema(db, "outbound"))
{
// Message already set
return false;
}
{
// Ensure statement gets cleaned up
sqlite3_stmt *stmt = nullptr;
auto cleanup = finally([&]
{
if (stmt)
{
// No need to check return code
sqlite3_finalize(stmt);
}
});
// Prepare the statement only once
rc = sqlite3_prepare_v2(db,
"INSERT INTO outbound.sampleblocks"
" SELECT * FROM main.sampleblocks"
" WHERE blockid = ?;",
-1,
&stmt,
nullptr);
if (rc != SQLITE_OK)
{
SetDBError(
XO("Unable to prepare project file command:\n\n%s").Format(sql)
);
return false;
}
/* i18n-hint: This title appears on a dialog that indicates the progress
in doing something.*/
ProgressDialog progress(XO("Progress"), msg, pdlgHideStopButton);
ProgressResult result = ProgressResult::Success;
wxLongLong_t count = 0;
wxLongLong_t total = blockids.size();
// Start a transaction. Since we're running without a journal,
// this really doesn't provide rollback. It just prevents SQLite
// from auto committing after each step through the loop.
//
// Also note that we will have an open transaction if we fail
// while copying the blocks. This is fine since we're just going
// to delete the database anyway.
sqlite3_exec(db, "BEGIN;", nullptr, nullptr, nullptr);
// Copy sample blocks from the main DB to the outbound DB
for (auto blockid : blockids)
{
// Bind statement parameters
rc = sqlite3_bind_int64(stmt, 1, blockid);
if (rc != SQLITE_OK)
{
SetDBError(
XO("Failed to bind SQL parameter")
);
return false;
}
// Process it
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
{
SetDBError(
XO("Failed to update the project file.\nThe following command failed:\n\n%s").Format(sql)
);
return false;
}
// Reset statement to beginning
if (sqlite3_reset(stmt) != SQLITE_OK)
{
THROW_INCONSISTENCY_EXCEPTION;
}
result = progress.Update(++count, total);
if (result != ProgressResult::Success)
{
// Note that we're not setting success, so the finally
// block above will take care of cleaning up
return false;
}
}
// Write the doc.
//
// If we're compacting a temporary project (user initiated from the File
// menu), then write the doc to the "autosave" table since temporary
// projects do not have a "project" doc.
if (!WriteDoc(isTemporary ? "autosave" : "project", doc, "outbound"))
{
return false;
}