forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDirManager.cpp
More file actions
2085 lines (1793 loc) · 70.3 KB
/
DirManager.cpp
File metadata and controls
2085 lines (1793 loc) · 70.3 KB
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
/**********************************************************************
Audacity: A Digital Audio Editor
Audacity(R) is copyright (c) 1999-2008 Audacity Team.
License: GPL v2. See License.txt.
DirManager.cpp
Dominic Mazzoni
Matt Brubeck
Michael Chinen
James Crook
Al Dimond
Brian Gunlogson
Josh Haberman
Vaughan Johnson
Leland Lucius
Monty
Markus Meyer
*******************************************************************//*!
\class DirManager
\brief Creates and manages BlockFile objects.
This class manages the files that a project uses to store most
of its data. It creates NEW BlockFile objects, which can
be used to store any type of data. BlockFiles support all of
the common file operations, but they also support reference
counting, so two different parts of a project can point to
the same block of data.
For example, a track might contain 10 blocks of data representing
its audio. If you copy the last 5 blocks and paste at the
end of the file, no NEW blocks need to be created - we just store
pointers to NEW ones. When part of a track is deleted, the
affected blocks decrement their reference counts, and when they
reach zero they are deleted. This same mechanism is also used
to implement Undo.
The DirManager, besides mapping filenames to absolute paths,
also hashes all of the block names used in a project, so that
when reading a project from disk, multiple copies of the
same block still get mapped to the same BlockFile object.
The blockfile/directory scheme is rather complicated with two different schemes.
The current scheme uses two levels of subdirectories - up to 256 'eXX' and up to
256 'dYY' directories within each of the 'eXX' dirs, where XX and YY are hex chars.
In each of the dXX directories there are up to 256 audio files (e.g. .au or .auf).
They have a filename scheme of 'eXXYYZZZZ', where XX and YY refers to the
subdirectories as above. The 'ZZZZ' component is generated randomly for some reason.
The XX and YY components are sequential.
DirManager fills up the current dYY subdir until 256 are created, and moves on to the next one.
So for example, the first blockfile created may be 'e00/d00/e0000a23b.au' and the next
'e00/d00/e000015e8.au', and the 257th may be 'e00/d01/e0001f02a.au'.
On close the blockfiles that are no longer referenced by the project (edited or deleted) are removed,
along with the consequent empty directories.
*//*******************************************************************/
#include "Audacity.h"
#include "DirManager.h"
#include "MemoryX.h"
#include <time.h> // to use time() for srand()
#include <wx/defs.h>
#include <wx/app.h>
#include <wx/dir.h>
#include <wx/log.h>
#include <wx/filefn.h>
#include <wx/hash.h>
#include <wx/msgdlg.h>
#include <wx/progdlg.h>
#include <wx/timer.h>
#include <wx/intl.h>
#include <wx/file.h>
#include <wx/filename.h>
#include <wx/object.h>
// chmod
#ifdef __UNIX__
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include "AudacityApp.h"
#include "BlockFile.h"
#include "blockfile/LegacyBlockFile.h"
#include "blockfile/LegacyAliasBlockFile.h"
#include "blockfile/SimpleBlockFile.h"
#include "blockfile/SilentBlockFile.h"
#include "blockfile/PCMAliasBlockFile.h"
#include "blockfile/ODPCMAliasBlockFile.h"
#include "blockfile/ODDecodeBlockFile.h"
#include "Internat.h"
#include "Project.h"
#include "Prefs.h"
#include "Sequence.h"
#include "widgets/Warning.h"
#include "widgets/MultiDialog.h"
#include "ondemand/ODManager.h"
#include "Track.h"
#if defined(__WXMAC__)
#include <mach/mach.h>
#include <mach/vm_statistics.h>
#endif
wxMemorySize GetFreeMemory()
{
wxMemorySize avail;
#if defined(__WXMAC__)
mach_port_t port = mach_host_self();
mach_msg_type_number_t cnt = HOST_VM_INFO_COUNT;
vm_statistics_data_t stats;
vm_size_t pagesize = 0;
memset(&stats, 0, sizeof(stats));
host_page_size(port, &pagesize);
host_statistics(port, HOST_VM_INFO, (host_info_t) &stats, &cnt);
avail = stats.free_count * pagesize;
#else
avail = wxGetFreeMemory();
#endif
return avail;
}
//
// local helper functions for subdirectory traversal
//
// Behavior of RecursivelyEnumerate is tailored to our uses and not
// entirely straightforward. We use it only for recursing into
// Audacity projects, but beware that it may be applied to a directory
// that contains other things too, for example a temp directory.
// It recurses depth-first from the passed-
// in directory into its subdirs according to optional dirspec
// pattern, building a list of directories and (optionally) files
// in the listed order.
// The dirspec is not applied to subdirs of subdirs.
// The filespec is applied to all files in subdirectories.
// Files in the passed-in directory will not be
// enumerated. Also, the passed-in directory is the last entry added
// to the list.
// JKC: Using flag wxDIR_NO_FOLLOW to NOT follow symbolic links.
// Directories and files inside a project should never be symbolic
// links, so if we find one, do not follow it.
static int RecursivelyEnumerate(wxString dirPath,
wxArrayString& filePathArray, // output: all files in dirPath tree
wxString dirspec,
wxString filespec,
bool bFiles, bool bDirs,
int progress_count = 0,
int progress_bias = 0,
ProgressDialog* progress = NULL)
{
int count=0;
bool cont;
wxDir dir(dirPath);
if(dir.IsOpened()){
wxString name;
// Don't delete files from a selective top level, e.g. if handed "projects*" as the
// directory specifier.
if (bFiles && dirspec.IsEmpty() ){
cont= dir.GetFirst(&name, filespec, wxDIR_FILES | wxDIR_HIDDEN | wxDIR_NO_FOLLOW);
while ( cont ){
wxString filepath = dirPath + wxFILE_SEP_PATH + name;
count++;
filePathArray.Add(filepath);
cont = dir.GetNext(&name);
if (progress)
progress->Update(count + progress_bias,
progress_count);
}
}
cont= dir.GetFirst(&name, dirspec, wxDIR_DIRS | wxDIR_NO_FOLLOW);
while ( cont ){
wxString subdirPath = dirPath + wxFILE_SEP_PATH + name;
count += RecursivelyEnumerate(
subdirPath, filePathArray, wxEmptyString,filespec,
bFiles, bDirs,
progress_count, count + progress_bias,
progress);
cont = dir.GetNext(&name);
}
}
if (bDirs) {
filePathArray.Add(dirPath);
count++;
}
return count;
}
static int RecursivelyEnumerateWithProgress(wxString dirPath,
wxArrayString& filePathArray, // output: all files in dirPath tree
wxString dirspec,
wxString filespec,
bool bFiles, bool bDirs,
int progress_count,
const wxChar* message)
{
Maybe<ProgressDialog> progress{};
if (message)
progress.create( _("Progress"), message );
int count = RecursivelyEnumerate(
dirPath, filePathArray, dirspec,filespec,
bFiles, bDirs,
progress_count, 0,
progress.get());
return count;
}
static int RecursivelyCountSubdirs(wxString dirPath)
{
bool bContinue;
int nCount = 0;
wxDir dir(dirPath);
if (dir.IsOpened() && dir.HasSubDirs())
{
wxString name;
bContinue = dir.GetFirst(&name, wxEmptyString, wxDIR_DIRS);
while (bContinue)
{
nCount++;
wxString subdirPath = dirPath + wxFILE_SEP_PATH + name;
nCount += RecursivelyCountSubdirs(subdirPath);
bContinue = dir.GetNext(&name);
}
}
return nCount;
}
static int RecursivelyRemoveEmptyDirs(wxString dirPath,
int nDirCount = 0,
ProgressDialog* pProgress = NULL)
{
bool bContinue;
wxDir dir(dirPath);
int nCount = 0;
if (dir.IsOpened())
{
if (dir.HasSubDirs())
{
wxString name;
bContinue = dir.GetFirst(&name, wxEmptyString, wxDIR_DIRS);
while (bContinue)
{
wxString subdirPath = dirPath + wxFILE_SEP_PATH + name;
nCount += RecursivelyRemoveEmptyDirs(subdirPath, nDirCount, pProgress);
bContinue = dir.GetNext(&name);
}
}
// Have to recheck dir.HasSubDirs() again, in case they all were deleted in recursive calls.
if (!dir.HasSubDirs() && !dir.HasFiles() && (dirPath.Right(5) != wxT("_data")))
{
// No subdirs or files. It's empty so DELETE it.
// Vaughan, 2010-07-07:
// Note that, per http://src.chromium.org/svn/trunk/src/base/file_util_win.cc, among others,
// "Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
// an empty directory..." Supposedly fixed in Vista and up.
// I discovered this on WinXP. I tried several other Windows SDK functions (e.g., _rmdir
// and RemoveDirectory), and they all give same results.
// I noticed dirs get deleted in RecursivelyRemove, maybe because it doesn't
// consider whether the path is a directory or a file and wxRemoveFile()'s it first.
// Tried it here on WinXP, but no joy. Leave the code in case it works on other Win systems.
#ifdef __WXMSW__
::wxRemoveFile(dirPath);
#endif
::wxRmdir(dirPath);
}
nCount++; // Count dirPath in progress.
if (pProgress)
pProgress->Update(nCount, nDirCount);
}
return nCount;
}
static void RecursivelyRemove(wxArrayString& filePathArray, int count, int bias,
int flags, const wxChar* message = NULL)
{
bool bFiles= (flags & kCleanFiles) != 0;
bool bDirs = (flags & kCleanDirs) != 0;
bool bDirsMustBeEmpty = (flags & kCleanDirsOnlyIfEmpty) != 0;
Maybe<ProgressDialog> progress{};
if (message)
progress.create( _("Progress"), message );
auto nn = filePathArray.size();
for (int i = 0; i < nn; i++) {
const wxChar *file = filePathArray[i].c_str();
if (bFiles)
::wxRemoveFile(file);
if (bDirs) {
// continue will go to the next item, and skip
// attempting to delete the directory.
if( bDirsMustBeEmpty ){
wxDir dir( file );
if( !dir.IsOpened() )
continue;
if( dir.HasFiles() )
continue;
if( dir.HasSubDirs() )
continue;
}
#ifdef __WXMSW__
if (!bFiles)
::wxRemoveFile(file); // See note above about wxRmdir sometimes incorrectly failing on Windows.
#endif
if (! ::wxRmdir(file) ) {
wxDir dir(file);
if(dir.IsOpened()) {
wxLogMessage(file + wxString(" still contains:"));
wxString name;
auto cont = dir.GetFirst(&name);
while ( cont ) {
wxLogMessage(file + wxString(wxFILE_SEP_PATH) + name );
cont = dir.GetNext(&name);
}
}
else
wxLogMessage(wxString("Can't enumerate directory ") + file);
}
}
if (progress)
progress->Update(i + bias, count);
}
}
//
// DirManager
//
// Static class variables
wxString DirManager::globaltemp;
int DirManager::numDirManagers = 0;
bool DirManager::dontDeleteTempFiles = false;
DirManager::DirManager()
{
wxLogDebug(wxT("DirManager: Created new instance."));
mLastBlockFileDestructionCount = BlockFile::gBlockFileDestructionCount;
// Seed the random number generator.
// this need not be strictly uniform or random, but it should give
// unclustered numbers
srand(time(NULL));
// Set up local temp subdir
// Previously, Audacity just named project temp directories "project0",
// "project1" and so on. But with the advent of recovery code, we need a
// unique name even after a crash. So we create a random project index
// and make sure it is not used already. This will not pose any performance
// penalties as long as the number of open Audacity projects is much
// lower than RAND_MAX.
do {
mytemp = globaltemp + wxFILE_SEP_PATH +
wxString::Format(wxT("project%d"), rand());
} while (wxDirExists(mytemp));
numDirManagers++;
projPath = wxT("");
projName = wxT("");
mLoadingTarget = NULL;
mLoadingTargetIdx = 0;
mMaxSamples = ~size_t(0);
// toplevel pool hash is fully populated to begin
{
// We can bypass the accessor function while initializing
auto &balanceInfo = mBalanceInfo;
auto &dirTopPool = balanceInfo.dirTopPool;
for(int i = 0; i < 256; ++i)
dirTopPool[i] = 0;
}
// Make sure there is plenty of space for temp files
wxLongLong freeSpace = 0;
if (wxGetDiskSpace(globaltemp, NULL, &freeSpace)) {
if (freeSpace < wxLongLong(wxLL(100 * 1048576))) {
ShowWarningDialog(NULL, wxT("DiskSpaceWarning"),
_("There is very little free disk space left on this volume.\nPlease select another temporary directory in Preferences."));
}
}
}
DirManager::~DirManager()
{
numDirManagers--;
if (numDirManagers == 0) {
CleanTempDir();
//::wxRmdir(temp);
} else if( projFull.IsEmpty() && !mytemp.IsEmpty()) {
CleanDir(mytemp, wxEmptyString, ".DS_Store", _("Cleaning project temporary files"), kCleanTopDirToo | kCleanDirsOnlyIfEmpty );
}
}
// static
// This is quite a dangerous function. In the temp dir it will delete every directory
// recursively, that has 'project*' as the name - EVEN if it happens not to be an Audacity
// project but just something else called project.
void DirManager::CleanTempDir()
{
// with default flags (none) this does not clean the top directory, and may remove non-empty
// directories.
CleanDir(globaltemp, wxT("project*"), wxEmptyString, _("Cleaning up temporary files"));
}
// static
void DirManager::CleanDir(
const wxString &path,
const wxString &dirSpec,
const wxString &fileSpec,
const wxString &msg,
int flags)
{
if (dontDeleteTempFiles)
return; // do nothing
wxArrayString filePathArray, dirPathArray;
int countFiles =
RecursivelyEnumerate(path, filePathArray, dirSpec, fileSpec, true, false);
int countDirs =
RecursivelyEnumerate(path, dirPathArray, dirSpec, fileSpec, false, true);
// Subtract 1 because we don't want to DELETE the global temp directory,
// which this will find and list last.
if ((flags & kCleanTopDirToo)==0) {
// Remove the globaltemp itself from the array so that it is not deleted.
--countDirs;
dirPathArray.resize(countDirs);
}
auto count = countFiles + countDirs;
if (count == 0)
return;
RecursivelyRemove(filePathArray, count, 0, flags | kCleanFiles, msg);
RecursivelyRemove(dirPathArray, count, countFiles, flags | kCleanDirs, msg);
}
bool DirManager::SetProject(wxString& newProjPath, wxString& newProjName, const bool bCreate)
{
bool copying = false;
wxString oldPath = this->projPath;
wxString oldName = this->projName;
wxString oldFull = projFull;
wxString oldLoc = projFull;
if (oldLoc == wxT(""))
oldLoc = mytemp;
if (newProjPath == wxT(""))
newProjPath = ::wxGetCwd();
this->projPath = newProjPath;
this->projName = newProjName;
if (newProjPath.Last() == wxFILE_SEP_PATH)
this->projFull = newProjPath + newProjName;
else
this->projFull = newProjPath + wxFILE_SEP_PATH + newProjName;
wxString cleanupLoc1=oldLoc;
wxString cleanupLoc2=projFull;
if (bCreate) {
if (!wxDirExists(projFull))
if (!wxMkdir(projFull))
return false;
#ifdef __UNIX__
chmod(OSFILENAME(projFull), 0775);
#endif
#ifdef __WXMAC__
chmod(OSFILENAME(projFull), 0775);
#endif
} else {
if (!wxDirExists(projFull))
return false;
}
/* Move all files into this NEW directory. Files which are
"locked" get copied instead of moved. (This happens when
we perform a Save As - the files which belonged to the last
saved version of the old project must not be moved,
otherwise the old project would not be safe.) */
int trueTotal = 0;
{
/*i18n-hint: This title appears on a dialog that indicates the progress in doing something.*/
ProgressDialog progress(_("Progress"),
_("Saving project data files"));
int total = mBlockFileHash.size();
BlockHash::iterator iter = mBlockFileHash.begin();
bool success = true;
int count = 0;
while ((iter != mBlockFileHash.end()) && success)
{
BlockFilePtr b = iter->second.lock();
if (b) {
// FIXME: TRAP_ERR
// JKC: The 'success' variable and recovery strategy looks
// broken/bogus to me. Would need to be using &= to catch
// failure in one of the copies/moves. Besides which,
// our temporary files are going to be deleted when we exit
// anyway, if saving from temporary to named project.
if (b->IsLocked())
success = CopyToNewProjectDirectory( &*b ), copying = true;
else{
success = MoveToNewProjectDirectory( &*b );
}
progress.Update(count, total);
count++;
}
++iter;
}
// in case there are any nulls
trueTotal = count;
if (!success) {
// If the move failed, we try to move/copy as many files
// back as possible so that no damage was done. (No sense
// in checking for errors this time around - there's nothing
// that could be done about it.)
// Likely causes: directory was not writeable, disk was full
projFull = oldLoc;
BlockHash::iterator iter = mBlockFileHash.begin();
while (iter != mBlockFileHash.end())
{
BlockFilePtr b = iter->second.lock();
if (b) {
MoveToNewProjectDirectory(&*b);
if (count >= 0)
progress.Update(count, total);
count--;
}
++iter;
}
this->projFull = oldFull;
this->projPath = oldPath;
this->projName = oldName;
return false;
}
}
// Some subtlety; SetProject is used both to move a temp project
// into a permanent home as well as just set up path variables when
// loading a project; in this latter case, the movement code does
// nothing because SetProject is called before there are any
// blockfiles. Cleanup code trigger is the same
// Do the cleanup of the temporary directory only if not saving-as, which we
// detect by having done copies rather than moves.
if (!copying && trueTotal > 0) {
// Clean up after ourselves; boldly remove all files and directories
// in the tree. (Unlike what the earlier version of this comment said.)
// Because this is a relocation of the project, not the case of closing
// a persistent project.
// You may think the loops above guarantee that all files we put in the
// folders have been moved away already, but:
// to fix bug1567 on Mac, we need to find the extraneous .DS_Store files
// that we didn't put there, but that Finder may insert into the folders,
// and mercilessly remove them, in addition to removing the directories.
CleanDir(
cleanupLoc1,
wxEmptyString, // EmptyString => ALL directories.
// If the next line were wxEmptyString, ALL files would be removed.
".DS_Store", // Other project files should already have been removed.
_("Cleaning up cache directories"),
kCleanTopDirToo);
//This destroys the empty dirs of the OD block files, which are yet to come.
//Dont know if this will make the project dirty, but I doubt it. (mchinen)
// count += RecursivelyEnumerate(cleanupLoc2, dirlist, wxEmptyString, false, true);
}
return true;
}
wxString DirManager::GetProjectDataDir()
{
return projFull;
}
wxString DirManager::GetProjectName()
{
return projName;
}
wxLongLong DirManager::GetFreeDiskSpace()
{
wxLongLong freeSpace = -1;
wxFileName path;
path.SetPath(projPath.IsEmpty() ? mytemp : projPath);
// Use the parent directory if the project directory hasn't yet been created
if (!path.DirExists())
{
path.RemoveLastDir();
}
if (!wxGetDiskSpace(path.GetFullPath(), NULL, &freeSpace))
{
freeSpace = -1;
}
return freeSpace;
}
wxString DirManager::GetDataFilesDir() const
{
return projFull != wxT("")? projFull: mytemp;
}
void DirManager::SetLocalTempDir(const wxString &path)
{
mytemp = path;
}
wxFileNameWrapper DirManager::MakeBlockFilePath(const wxString &value) {
wxFileNameWrapper dir;
dir.AssignDir(GetDataFilesDir());
if(value.GetChar(0)==wxT('d')){
// this file is located in a subdirectory tree
int location=value.Find(wxT('b'));
wxString subdir=value.Mid(0,location);
dir.AppendDir(subdir);
if(!dir.DirExists())
dir.Mkdir();
}
if(value.GetChar(0)==wxT('e')){
// this file is located in a NEW style two-deep subdirectory tree
wxString topdir=value.Mid(0,3);
wxString middir=wxT("d");
middir.Append(value.Mid(3,2));
dir.AppendDir(topdir);
dir.AppendDir(middir);
if(!dir.DirExists() && !dir.Mkdir(0777,wxPATH_MKDIR_FULL))
{ // need braces to avoid compiler warning about ambiguous else, see the macro
wxLogSysError(_("mkdir in DirManager::MakeBlockFilePath failed."));
}
}
return dir;
}
bool DirManager::AssignFile(wxFileNameWrapper &fileName,
const wxString &value,
bool diskcheck)
{
wxFileNameWrapper dir{ MakeBlockFilePath(value) };
if(diskcheck){
// verify that there's no possible collision on disk. If there
// is, log the problem and return FALSE so that MakeBlockFileName
// can try again
wxDir checkit(dir.GetFullPath());
if(!checkit.IsOpened()) return FALSE;
// this code is only valid if 'value' has no extention; that
// means, effectively, AssignFile may be called with 'diskcheck'
// set to true only if called from MakeFileBlockName().
wxString filespec;
filespec.Printf(wxT("%s.*"),value.c_str());
if(checkit.HasFiles(filespec)){
// collision with on-disk state!
wxString collision;
checkit.GetFirst(&collision,filespec);
wxLogWarning(_("Audacity found an orphan block file: %s. \nPlease consider saving and reloading the project to perform a complete project check."),
collision.c_str());
return FALSE;
}
}
fileName.Assign(dir.GetFullPath(),value);
return fileName.IsOk();
}
static inline unsigned int hexchar_to_int(unsigned int x)
{
if(x<48U)return 0;
if(x<58U)return x-48U;
if(x<65U)return 10U;
if(x<71U)return x-55U;
if(x<97U)return 10U;
if(x<103U)return x-87U;
return 15U;
}
int DirManager::BalanceMidAdd(int topnum, int midkey)
{
// enter the midlevel directory if it doesn't exist
auto &balanceInfo = GetBalanceInfo();
auto &dirMidPool = balanceInfo.dirMidPool;
auto &dirMidFull = balanceInfo.dirMidFull;
auto &dirTopPool = balanceInfo.dirTopPool;
auto &dirTopFull = balanceInfo.dirTopFull;
if(dirMidPool.find(midkey) == dirMidPool.end() &&
dirMidFull.find(midkey) == dirMidFull.end()){
dirMidPool[midkey]=0;
// increment toplevel directory fill
dirTopPool[topnum]++;
if(dirTopPool[topnum]>=256){
// this toplevel is now full; move it to the full hash
dirTopPool.erase(topnum);
dirTopFull[topnum]=256;
}
return 1;
}
return 0;
}
void DirManager::BalanceFileAdd(int midkey)
{
auto &balanceInfo = GetBalanceInfo();
auto &dirMidPool = balanceInfo.dirMidPool;
auto &dirMidFull = balanceInfo.dirMidFull;
// increment the midlevel directory usage information
if(dirMidPool.find(midkey) != dirMidPool.end()){
dirMidPool[midkey]++;
if(dirMidPool[midkey]>=256){
// this middir is now full; move it to the full hash
dirMidPool.erase(midkey);
dirMidFull[midkey]=256;
}
}else{
// this case only triggers in absurdly large projects; we still
// need to track directory fill even if we're over 256/256/256
dirMidPool[midkey]++;
}
}
void DirManager::BalanceInfoAdd(const wxString &file)
{
const wxChar *s=file.c_str();
if(s[0]==wxT('e')){
// this is one of the modern two-deep managed files
// convert filename to keys
unsigned int topnum = (hexchar_to_int(s[1]) << 4) |
hexchar_to_int(s[2]);
unsigned int midnum = (hexchar_to_int(s[3]) << 4) |
hexchar_to_int(s[4]);
unsigned int midkey=topnum<<8|midnum;
BalanceMidAdd(topnum,midkey);
BalanceFileAdd(midkey);
}
}
auto DirManager::GetBalanceInfo() -> BalanceInfo &
{
// Before returning the map,
// see whether any block files have disappeared,
// and if so update
auto count = BlockFile::gBlockFileDestructionCount;
if ( mLastBlockFileDestructionCount != count ) {
auto it = mBlockFileHash.begin(), end = mBlockFileHash.end();
while (it != end)
{
BlockFilePtr ptr { it->second.lock() };
if (!ptr) {
auto name = it->first;
mBlockFileHash.erase( it++ );
BalanceInfoDel( name );
}
else
++it;
}
}
mLastBlockFileDestructionCount = count;
return mBalanceInfo;
}
// Note that this will try to clean up directories out from under even
// locked blockfiles; this is actually harmless as the rmdir will fail
// on non-empty directories.
void DirManager::BalanceInfoDel(const wxString &file)
{
// do not use GetBalanceInfo(),
// rather this function will be called from there.
auto &balanceInfo = mBalanceInfo;
auto &dirMidPool = balanceInfo.dirMidPool;
auto &dirMidFull = balanceInfo.dirMidFull;
auto &dirTopPool = balanceInfo.dirTopPool;
auto &dirTopFull = balanceInfo.dirTopFull;
const wxChar *s=file.c_str();
if(s[0]==wxT('e')){
// this is one of the modern two-deep managed files
unsigned int topnum = (hexchar_to_int(s[1]) << 4) |
hexchar_to_int(s[2]);
unsigned int midnum = (hexchar_to_int(s[3]) << 4) |
hexchar_to_int(s[4]);
unsigned int midkey=topnum<<8|midnum;
// look for midkey in the mid pool
if(dirMidFull.find(midkey) != dirMidFull.end()){
// in the full pool
if(--dirMidFull[midkey]<256){
// move out of full into available
dirMidPool[midkey]=dirMidFull[midkey];
dirMidFull.erase(midkey);
}
}else{
if(--dirMidPool[midkey]<1){
// erasing the key here is OK; we have provision to add it
// back if its needed (unlike the dirTopPool hash)
dirMidPool.erase(midkey);
// DELETE the actual directory
wxString dir=(projFull != wxT("")? projFull: mytemp);
dir += wxFILE_SEP_PATH;
dir += file.Mid(0,3);
dir += wxFILE_SEP_PATH;
dir += wxT("d");
dir += file.Mid(3,2);
wxFileName::Rmdir(dir);
// also need to remove from toplevel
if(dirTopFull.find(topnum) != dirTopFull.end()){
// in the full pool
if(--dirTopFull[topnum]<256){
// move out of full into available
dirTopPool[topnum]=dirTopFull[topnum];
dirTopFull.erase(topnum);
}
}else{
if(--dirTopPool[topnum]<1){
// do *not* erase the hash entry from dirTopPool
// *do* DELETE the actual directory
wxString dir=(projFull != wxT("")? projFull: mytemp);
dir += wxFILE_SEP_PATH;
dir += file.Mid(0,3);
wxFileName::Rmdir(dir);
}
}
}
}
}
}
// only determines appropriate filename and subdir balance; does not
// perform maintainence
wxFileNameWrapper DirManager::MakeBlockFileName()
{
auto &balanceInfo = GetBalanceInfo();
auto &dirMidPool = balanceInfo.dirMidPool;
auto &dirTopPool = balanceInfo.dirTopPool;
auto &dirTopFull = balanceInfo.dirTopFull;
wxFileNameWrapper ret;
wxString baseFileName;
unsigned int filenum,midnum,topnum,midkey;
while(1){
/* blockfiles are divided up into heirarchical directories.
Each toplevel directory is represented by "e" + two unique
hexadecimal digits, for a total possible number of 256
toplevels. Each toplevel contains up to 256 subdirs named
"d" + two hex digits. Each subdir contains 'a number' of
files. */
filenum=0;
midnum=0;
topnum=0;
// first action: if there is no available two-level directory in
// the available pool, try to make one
if(dirMidPool.empty()){
// is there a toplevel directory with space for a NEW subdir?
if(!dirTopPool.empty()){
// there's still a toplevel with room for a subdir
DirHash::iterator iter = dirTopPool.begin();
int newcount = 0;
topnum = iter->first;
// search for unused midlevels; linear search adequate
// add 32 NEW topnum/midnum dirs full of prospective filenames to midpool
for(midnum=0;midnum<256;midnum++){
midkey=(topnum<<8)+midnum;
if(BalanceMidAdd(topnum,midkey)){
newcount++;
if(newcount>=32)break;
}
}
if(dirMidPool.empty()){
// all the midlevels in this toplevel are in use yet the
// toplevel claims some are free; this implies multiple
// internal logic faults, but simply giving up and going
// into an infinite loop isn't acceptible. Just in case,
// for some reason, we get here, dynamite this toplevel so
// we don't just fail.
// this is 'wrong', but the best we can do given that
// something else is also wrong. It will contain the
// problem so we can keep going without worry.
dirTopPool.erase(topnum);
dirTopFull[topnum]=256;
}
continue;
}
}
if(dirMidPool.empty()){
// still empty, thus an absurdly large project; all dirs are
// full to 256/256/256; keep working, but fall back to 'big
// filenames' and randomized placement
filenum = rand();
midnum = (int)(256.*rand()/(RAND_MAX+1.));
topnum = (int)(256.*rand()/(RAND_MAX+1.));
midkey=(topnum<<8)+midnum;
}else{
DirHash::iterator iter = dirMidPool.begin();
midkey = iter->first;
// split the retrieved 16 bit directory key into two 8 bit numbers
topnum = midkey >> 8;
midnum = midkey & 0xff;
filenum = (int)(4096.*rand()/(RAND_MAX+1.));
}
baseFileName.Printf(wxT("e%02x%02x%03x"),topnum,midnum,filenum);
if (!ContainsBlockFile(baseFileName)) {
// not in the hash, good.