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
|
#include "algorithm.h"
#include <wx/intl.h>
#include <stdexcept>
#include <wx/log.h>
#include "library/resources.h"
#include "shared/fileHandling.h"
#include <wx/msgdlg.h>
#include "library/filter.h"
#include <boost/bind.hpp>
#include "shared/stringConv.h"
#include "shared/globalFunctions.h"
#include "shared/loki/TypeManip.h"
#include "shared/loki/NullType.h"
using namespace FreeFileSync;
void FreeFileSync::swapGrids(const MainConfiguration& config, FolderComparison& folderCmp)
{
std::for_each(folderCmp.begin(), folderCmp.end(), boost::bind(&BaseDirMapping::swap, _1));
redetermineSyncDirection(config, folderCmp, NULL);
}
//----------------------------------------------------------------------------------------------
class Redetermine
{
public:
Redetermine(const SyncConfiguration& configIn) : config(configIn) {}
void execute(HierarchyObject& hierObj) const
{
//process files
std::for_each(hierObj.subFiles.begin(), hierObj.subFiles.end(), *this);
//process directories
std::for_each(hierObj.subDirs.begin(), hierObj.subDirs.end(), *this);
}
private:
template<typename Iterator, typename Function>
friend Function std::for_each(Iterator, Iterator, Function);
void operator()(FileMapping& fileObj) const
{
switch (fileObj.getCategory())
{
case FILE_LEFT_SIDE_ONLY:
fileObj.setSyncDir(config.exLeftSideOnly);
break;
case FILE_RIGHT_SIDE_ONLY:
fileObj.setSyncDir(config.exRightSideOnly);
break;
case FILE_RIGHT_NEWER:
fileObj.setSyncDir(config.rightNewer);
break;
case FILE_LEFT_NEWER:
fileObj.setSyncDir(config.leftNewer);
break;
case FILE_DIFFERENT:
fileObj.setSyncDir(config.different);
break;
case FILE_CONFLICT:
fileObj.setSyncDir(config.conflict);
break;
case FILE_EQUAL:
fileObj.setSyncDir(SYNC_DIR_NONE);
break;
}
}
void operator()(DirMapping& dirObj) const
{
switch (dirObj.getDirCategory())
{
case DIR_LEFT_SIDE_ONLY:
dirObj.setSyncDir(config.exLeftSideOnly);
break;
case DIR_RIGHT_SIDE_ONLY:
dirObj.setSyncDir(config.exRightSideOnly);
break;
case DIR_EQUAL:
dirObj.setSyncDir(SYNC_DIR_NONE);
break;
}
//recursion
execute(dirObj);
}
const SyncConfiguration& config;
};
//---------------------------------------------------------------------------------------------------------------
enum Answer
{
CHANGE_DETECTED,
NO_CHANGE,
CANT_SAY_FILTERING_CHANGED
};
template <bool respectFiltering>
class DetectChanges
{
public:
DetectChanges(const DirContainer* dirCont, //DirContainer in sense of a HierarchyObject
const FilterProcess& dbFilter);
DetectChanges(const DirContainer* dirCont); //DirContainer in sense of a HierarchyObject
template <SelectedSide side>
Answer detectFileChange(const FileMapping& fileObj) const;
struct DirAnswer
{
DirAnswer(Answer status, const DetectChanges instance) : dirStatus(status), subDirInstance(instance) {}
Answer dirStatus;
DetectChanges subDirInstance; //not valid if dirStatus == CANT_SAY_FILTERING_CHANGED
};
template <SelectedSide side>
DirAnswer detectDirChange(const DirMapping& dirObj) const;
private:
const DirContainer* const dirCont_; //if NULL: did not exist during db creation
typename Loki::Select<respectFiltering, const FilterProcess&, Loki::NullType>::Result dbFilter_; //filter setting that was used when db was created
};
template <>
inline
DetectChanges<true>::DetectChanges(const DirContainer* dirCont, //DirContainer in sense of a HierarchyObject
const FilterProcess& dbFilter) :
dirCont_(dirCont),
dbFilter_(dbFilter) {}
template <>
inline
DetectChanges<false>::DetectChanges(const DirContainer* dirCont) : //DirContainer in sense of a HierarchyObject
dirCont_(dirCont) {}
template <SelectedSide side>
Answer detectFileChangeSub(const FileMapping& fileObj, const DirContainer* dbDirectory)
{
if (dbDirectory)
{
DirContainer::SubFileList::const_iterator j = dbDirectory->getSubFiles().find(fileObj.getObjShortName());
if (j == dbDirectory->getSubFiles().end())
{
if (fileObj.isEmpty<side>())
return NO_CHANGE;
else
return CHANGE_DETECTED; //->create
}
else
{
if (fileObj.isEmpty<side>())
return CHANGE_DETECTED; //->delete
else
{
const FileDescriptor& dbData = j->second.getData();
if ( fileObj.getLastWriteTime<side>() == dbData.lastWriteTimeRaw &&
fileObj.getFileSize<side>() == dbData.fileSize)
return NO_CHANGE;
else
return CHANGE_DETECTED; //->update
}
}
}
else
{
if (fileObj.isEmpty<side>())
return NO_CHANGE;
else
return CHANGE_DETECTED; //->create
}
}
template <>
template <SelectedSide side>
inline
Answer DetectChanges<false>::detectFileChange(const FileMapping& fileObj) const
{
return detectFileChangeSub<side>(fileObj, dirCont_);
}
template <>
template <SelectedSide side>
inline
Answer DetectChanges<true>::detectFileChange(const FileMapping& fileObj) const
{
//if filtering would have excluded file during database creation, then we can't say anything about its former state
if (!dbFilter_.passFileFilter(fileObj.getObjShortName()))
return CANT_SAY_FILTERING_CHANGED;
return detectFileChangeSub<side>(fileObj, dirCont_);
}
template <SelectedSide side>
Answer detectDirChangeSub(const DirMapping& dirObj, const DirContainer* dbDirectory, const DirContainer*& dbSubDirectory)
{
if (dbDirectory)
{
DirContainer::SubDirList::const_iterator j = dbDirectory->getSubDirs().find(dirObj.getObjShortName());
if (j == dbDirectory->getSubDirs().end())
{
if (dirObj.isEmpty<side>())
return NO_CHANGE;
else
return CHANGE_DETECTED; //->create
}
else
{
dbSubDirectory = &j->second;
if (dirObj.isEmpty<side>())
return CHANGE_DETECTED; //->delete
else
return NO_CHANGE;
}
}
else
{
if (dirObj.isEmpty<side>())
return NO_CHANGE;
else
return CHANGE_DETECTED; //->create
}
}
template <>
template <SelectedSide side>
DetectChanges<false>::DirAnswer DetectChanges<false>::detectDirChange(const DirMapping& dirObj) const
{
const DirContainer* dbSubDir = NULL;
const Answer answer = detectDirChangeSub<side>(dirObj, dirCont_, dbSubDir);
return DirAnswer(answer, DetectChanges<false>(dbSubDir));
}
template <>
template <SelectedSide side>
DetectChanges<true>::DirAnswer DetectChanges<true>::detectDirChange(const DirMapping& dirObj) const
{
//if filtering would have excluded file during database creation, then we can't say anything about its former state
if (!dbFilter_.passDirFilter(dirObj.getObjShortName(), NULL))
return DirAnswer(CANT_SAY_FILTERING_CHANGED, DetectChanges<true>(NULL, dbFilter_));
const DirContainer* dbSubDir = NULL;
const Answer answer = detectDirChangeSub<side>(dirObj, dirCont_, dbSubDir);
return DirAnswer(answer, DetectChanges<true>(dbSubDir, dbFilter_));
}
//----------------------------------------------------------------------------------------------
class SetDirChangedFilter
{
public:
SetDirChangedFilter() :
txtFilterChanged(_("Cannot determine sync-direction: Changed filter settings!")) {}
void execute(HierarchyObject& hierObj) const
{
//files
std::for_each(hierObj.subFiles.begin(), hierObj.subFiles.end(), *this);
//directories
std::for_each(hierObj.subDirs.begin(), hierObj.subDirs.end(), *this);
}
private:
template<typename Iterator, typename Function>
friend Function std::for_each(Iterator, Iterator, Function);
void operator()(FileMapping& fileObj) const
{
const CompareFilesResult cat = fileObj.getCategory();
if (cat == FILE_LEFT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_RIGHT);
else if (cat == FILE_RIGHT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_LEFT);
else
fileObj.setSyncDirConflict(txtFilterChanged); //set syncDir = SYNC_DIR_INT_CONFLICT
}
void operator()(DirMapping& dirObj) const
{
switch (dirObj.getDirCategory())
{
case DIR_LEFT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_RIGHT);
break;
case DIR_RIGHT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_LEFT);
break;
case DIR_EQUAL:
break;
}
execute(dirObj); //recursion
}
const wxString txtFilterChanged;
};
//----------------------------------------------------------------------------------------------
class RedetermineAuto
{
public:
RedetermineAuto(BaseDirMapping& baseDirectory,
DeterminationProblem* handler) :
txtBothSidesChanged(_("Both sides have changed since last synchronization!")),
txtNoSideChanged(_("Cannot determine sync-direction: No change since last synchronization!")),
txtFilterChanged(_("Cannot determine sync-direction: Changed filter settings!")),
handler_(handler)
{
if (baseDirectory.subFiles.empty() && baseDirectory.subDirs.empty()) //don't show nag-screens in this case
return;
//try to load sync-database files
std::pair<DirInfoPtr, DirInfoPtr> dirInfo = loadDBFile(baseDirectory);
if ( dirInfo.first.get() == NULL ||
dirInfo.second.get() == NULL)
{
//use standard settings:
SyncConfiguration defaultSync;
defaultSync.setVariant(SyncConfiguration::TWOWAY);
Redetermine(defaultSync).execute(baseDirectory);
return;
}
const DirInformation& dirInfoLeft = *dirInfo.first;
const DirInformation& dirInfoRight = *dirInfo.second;
if ( respectFiltering(baseDirectory, dirInfoLeft) &&
respectFiltering(baseDirectory, dirInfoRight))
{
execute(baseDirectory,
DetectChanges<true>(&dirInfoLeft.baseDirContainer,
FilterProcess(dirInfoLeft.includeFilter,
dirInfoLeft.excludeFilter)),
DetectChanges<true>(&dirInfoRight.baseDirContainer,
FilterProcess(dirInfoRight.includeFilter,
dirInfoRight.excludeFilter)));
}
else if ( !respectFiltering(baseDirectory, dirInfoLeft) &&
respectFiltering( baseDirectory, dirInfoRight))
{
execute(baseDirectory,
DetectChanges<false>(&dirInfoLeft.baseDirContainer),
DetectChanges<true>(&dirInfoRight.baseDirContainer,
FilterProcess(dirInfoRight.includeFilter,
dirInfoRight.excludeFilter)));
}
else if ( respectFiltering( baseDirectory, dirInfoLeft) &&
!respectFiltering(baseDirectory, dirInfoRight))
{
execute(baseDirectory,
DetectChanges<true>(&dirInfoLeft.baseDirContainer,
FilterProcess(dirInfoLeft.includeFilter,
dirInfoLeft.excludeFilter)),
DetectChanges<false>(&dirInfoRight.baseDirContainer));
}
else
{
execute(baseDirectory,
DetectChanges<false>(&dirInfoLeft.baseDirContainer),
DetectChanges<false>(&dirInfoRight.baseDirContainer));
}
}
private:
static bool respectFiltering(const BaseDirMapping& baseDirectory, const DirInformation& dirInfo)
{
return dirInfo.filterActive && //respect filtering if sync-DB filter is active && different from baseDir's filter
(!baseDirectory.getFilter().filterActive ||
FilterProcess(baseDirectory.getFilter().includeFilter,
baseDirectory.getFilter().excludeFilter) !=
FilterProcess(dirInfo.includeFilter,
dirInfo.excludeFilter));
}
std::pair<DirInfoPtr, DirInfoPtr> loadDBFile(const BaseDirMapping& baseDirectory) //return NULL on failure
{
try
{
return loadFromDisk(baseDirectory);
}
catch (FileError& error) //e.g. incompatible database version
{
if (handler_) handler_->reportWarning(error.show() + wxT(" \n\n") +
_("Using default synchronization directions. Please recheck."));
}
return std::pair<DirInfoPtr, DirInfoPtr>(); //NULL
}
template<typename Iterator, typename Function>
friend Function std::for_each(Iterator, Iterator, Function);
template <bool dbLeftFilterActive, bool dbRightFilterActive>
void execute(HierarchyObject& hierObj,
const DetectChanges<dbLeftFilterActive>& dbLeft,
const DetectChanges<dbRightFilterActive>& dbRight)
{
//process files
std::for_each(hierObj.subFiles.begin(), hierObj.subFiles.end(),
boost::bind(&RedetermineAuto::processFile<dbLeftFilterActive, dbRightFilterActive>, this, _1, boost::ref(dbLeft), boost::ref(dbRight)));
//process directories
std::for_each(hierObj.subDirs.begin(), hierObj.subDirs.end(),
boost::bind(&RedetermineAuto::processDir<dbLeftFilterActive, dbRightFilterActive>, this, _1, boost::ref(dbLeft), boost::ref(dbRight)));
}
template <bool dbLeftFilterActive, bool dbRightFilterActive>
void processFile(FileMapping& fileObj,
const DetectChanges<dbLeftFilterActive>& dbLeft,
const DetectChanges<dbRightFilterActive>& dbRight)
{
const CompareFilesResult cat = fileObj.getCategory();
if (cat == FILE_EQUAL)
return;
const Answer statusLeft = dbLeft. template detectFileChange<LEFT_SIDE>(fileObj);
const Answer statusRight = dbRight.template detectFileChange<RIGHT_SIDE>(fileObj);
if ( statusLeft == CANT_SAY_FILTERING_CHANGED ||
statusRight == CANT_SAY_FILTERING_CHANGED)
{
if (cat == FILE_LEFT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_RIGHT);
else if (cat == FILE_RIGHT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_LEFT);
else
fileObj.setSyncDirConflict(txtFilterChanged); //set syncDir = SYNC_DIR_INT_CONFLICT
return;
}
if ( statusLeft == CHANGE_DETECTED &&
statusRight == NO_CHANGE)
fileObj.setSyncDir(SYNC_DIR_RIGHT);
else if ( statusLeft == NO_CHANGE &&
statusRight == CHANGE_DETECTED)
fileObj.setSyncDir(SYNC_DIR_LEFT);
else if ( statusLeft == CHANGE_DETECTED &&
statusRight == CHANGE_DETECTED)
fileObj.setSyncDirConflict(txtBothSidesChanged); //set syncDir = SYNC_DIR_INT_CONFLICT
else if ( statusLeft == NO_CHANGE &&
statusRight == NO_CHANGE)
{
if (cat == FILE_LEFT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_RIGHT);
else if (cat == FILE_RIGHT_SIDE_ONLY)
fileObj.setSyncDir(SYNC_DIR_LEFT);
else
fileObj.setSyncDirConflict(txtNoSideChanged); //set syncDir = SYNC_DIR_INT_CONFLICT
}
}
template <bool dbLeftFilterActive, bool dbRightFilterActive>
void processDir(DirMapping& dirObj,
const DetectChanges<dbLeftFilterActive>& dbLeft,
const DetectChanges<dbRightFilterActive>& dbRight)
{
const typename DetectChanges<dbLeftFilterActive> ::DirAnswer statusLeft = dbLeft. template detectDirChange<LEFT_SIDE>(dirObj);
const typename DetectChanges<dbRightFilterActive>::DirAnswer statusRight = dbRight.template detectDirChange<RIGHT_SIDE>(dirObj);
const CompareDirResult cat = dirObj.getDirCategory();
if (cat != DIR_EQUAL)
{
if ( (statusLeft.dirStatus == CANT_SAY_FILTERING_CHANGED ||
statusRight.dirStatus == CANT_SAY_FILTERING_CHANGED))
{
switch (cat)
{
case DIR_LEFT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_RIGHT);
break;
case DIR_RIGHT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_LEFT);
break;
case DIR_EQUAL:
assert(false);
}
SetDirChangedFilter().execute(dirObj); //filter issue for this directory => treat subfiles/-dirs the same
return;
}
else if ( statusLeft.dirStatus == CHANGE_DETECTED &&
statusRight.dirStatus == NO_CHANGE)
dirObj.setSyncDir(SYNC_DIR_RIGHT);
else if ( statusLeft.dirStatus == NO_CHANGE &&
statusRight.dirStatus == CHANGE_DETECTED)
dirObj.setSyncDir(SYNC_DIR_LEFT);
else if ( statusLeft.dirStatus == CHANGE_DETECTED &&
statusRight.dirStatus == CHANGE_DETECTED)
dirObj.setSyncDirConflict(txtBothSidesChanged); //set syncDir = SYNC_DIR_INT_CONFLICT
else if ( statusLeft.dirStatus == NO_CHANGE &&
statusRight.dirStatus == NO_CHANGE)
{
switch (cat)
{
case DIR_LEFT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_RIGHT);
break;
case DIR_RIGHT_SIDE_ONLY:
dirObj.setSyncDir(SYNC_DIR_LEFT);
break;
case DIR_EQUAL:
assert(false);
}
}
}
execute(dirObj, statusLeft.subDirInstance, statusRight.subDirInstance); //recursion
}
const wxString txtBothSidesChanged;
const wxString txtNoSideChanged;
const wxString txtFilterChanged;
DeterminationProblem* const handler_;
};
//---------------------------------------------------------------------------------------------------------------
void FreeFileSync::redetermineSyncDirection(const SyncConfiguration& config, BaseDirMapping& baseDirectory, DeterminationProblem* handler)
{
if (config.automatic)
RedetermineAuto(baseDirectory, handler);
else
Redetermine(config).execute(baseDirectory);
}
void FreeFileSync::redetermineSyncDirection(const MainConfiguration& currentMainCfg, FolderComparison& folderCmp, DeterminationProblem* handler)
{
if (folderCmp.size() == 0)
return;
else if (folderCmp.size() != currentMainCfg.additionalPairs.size() + 1)
throw std::logic_error("Programming Error: Contract violation!");
//main pair
redetermineSyncDirection(currentMainCfg.syncConfiguration, folderCmp[0], handler);
//add. folder pairs
for (std::vector<FolderPairEnh>::const_iterator i = currentMainCfg.additionalPairs.begin(); i != currentMainCfg.additionalPairs.end(); ++i)
{
redetermineSyncDirection(i->altSyncConfig.get() ? i->altSyncConfig->syncConfiguration : currentMainCfg.syncConfiguration,
folderCmp[i - currentMainCfg.additionalPairs.begin() + 1], handler);
}
}
//---------------------------------------------------------------------------------------------------------------
class SetNewDirection
{
public:
SetNewDirection(SyncDirection newDirection) :
newDirection_(newDirection) {}
void execute(HierarchyObject& hierObj) const
{
//directories
std::for_each(hierObj.subDirs.begin(), hierObj.subDirs.end(), *this);
//files
std::for_each(hierObj.subFiles.begin(), hierObj.subFiles.end(), *this);
}
private:
template<typename Iterator, typename Function>
friend Function std::for_each(Iterator, Iterator, Function);
void operator()(FileMapping& fileObj) const
{
fileObj.setSyncDir(newDirection_);
}
void operator()(DirMapping& dirObj) const
{
dirObj.setSyncDir(newDirection_);
execute(dirObj); //recursion
}
const SyncDirection newDirection_;
};
void FreeFileSync::setSyncDirectionRec(SyncDirection newDirection, FileSystemObject& fsObj)
{
fsObj.setSyncDir(newDirection);
DirMapping* dirObj = dynamic_cast<DirMapping*>(&fsObj);
if (dirObj) //process subdirectories also!
SetNewDirection(newDirection).execute(*dirObj);
}
void FreeFileSync::applyFiltering(const MainConfiguration& currentMainCfg, FolderComparison& folderCmp)
{
if (folderCmp.size() == 0)
return;
else if (folderCmp.size() != currentMainCfg.additionalPairs.size() + 1)
throw std::logic_error("Programming Error: Contract violation!");
//main pair
FreeFileSync::FilterProcess(currentMainCfg.includeFilter, currentMainCfg.excludeFilter).filterAll(folderCmp[0]);
//add. folder pairs
for (std::vector<FolderPairEnh>::const_iterator i = currentMainCfg.additionalPairs.begin(); i != currentMainCfg.additionalPairs.end(); ++i)
{
HierarchyObject& baseDirectory = folderCmp[i - currentMainCfg.additionalPairs.begin() + 1];
if (i->altFilter.get())
FreeFileSync::FilterProcess(i->altFilter->includeFilter, i->altFilter->excludeFilter).filterAll(baseDirectory);
else
FreeFileSync::FilterProcess(currentMainCfg.includeFilter, currentMainCfg.excludeFilter).filterAll(baseDirectory);
}
}
//############################################################################################################
std::pair<wxString, int> FreeFileSync::deleteFromGridAndHDPreview( //assemble message containing all files to be deleted
const std::vector<FileSystemObject*>& rowsToDeleteOnLeft,
const std::vector<FileSystemObject*>& rowsToDeleteOnRight,
const bool deleteOnBothSides)
{
wxString filesToDelete;
int totalDelCount = 0;
if (deleteOnBothSides)
{
//mix selected rows from left and right
std::set<FileSystemObject*> rowsToDelete(rowsToDeleteOnLeft.begin(), rowsToDeleteOnLeft.end());
rowsToDelete.insert(rowsToDeleteOnRight.begin(), rowsToDeleteOnRight.end());
for (std::set<FileSystemObject*>::const_iterator i = rowsToDelete.begin(); i != rowsToDelete.end(); ++i)
{
const FileSystemObject& currObj = *(*i);
if (!currObj.isEmpty<LEFT_SIDE>())
{
filesToDelete += zToWx(currObj.getFullName<LEFT_SIDE>()) + wxT("\n");
++totalDelCount;
}
if (!currObj.isEmpty<RIGHT_SIDE>())
{
filesToDelete += zToWx(currObj.getFullName<RIGHT_SIDE>()) + wxT("\n");
++totalDelCount;
}
filesToDelete += wxT("\n");
}
}
else //delete selected files only
{
for (std::vector<FileSystemObject*>::const_iterator i = rowsToDeleteOnLeft.begin(); i != rowsToDeleteOnLeft.end(); ++i)
{
const FileSystemObject& currObj = *(*i);
if (!currObj.isEmpty<LEFT_SIDE>())
{
filesToDelete += zToWx(currObj.getFullName<LEFT_SIDE>()) + wxT("\n");
++totalDelCount;
}
}
for (std::vector<FileSystemObject*>::const_iterator i = rowsToDeleteOnRight.begin(); i != rowsToDeleteOnRight.end(); ++i)
{
const FileSystemObject& currObj = *(*i);
if (!currObj.isEmpty<RIGHT_SIDE>())
{
filesToDelete += zToWx(currObj.getFullName<RIGHT_SIDE>()) + wxT("\n");
++totalDelCount;
}
}
}
return std::make_pair(filesToDelete, totalDelCount);
}
template <SelectedSide side>
void deleteFromGridAndHDOneSide(std::vector<FileSystemObject*>& rowsToDeleteOneSide,
const bool useRecycleBin,
DeleteFilesHandler* statusHandler)
{
for (std::vector<FileSystemObject*>::const_iterator i = rowsToDeleteOneSide.begin(); i != rowsToDeleteOneSide.end(); ++i)
{
if (!(*i)->isEmpty<side>())
{
while (true)
{
try
{
FileMapping* fileObj = dynamic_cast<FileMapping*>(*i);
if (fileObj != NULL)
{
FreeFileSync::removeFile(fileObj->getFullName<side>(), useRecycleBin);
fileObj->removeObject<side>();
statusHandler->deletionSuccessful(); //notify successful file/folder deletion
}
else
{
DirMapping* dirObj = dynamic_cast<DirMapping*>(*i);
if (dirObj != NULL)
{
FreeFileSync::removeDirectory(dirObj->getFullName<side>(), useRecycleBin);
dirObj->removeObject<side>(); //directory: removes recursively!
statusHandler->deletionSuccessful(); //notify successful file/folder deletion
}
else
assert(!"It's no file, no dir, what is it then?");
}
break;
}
catch (const FileError& error)
{
DeleteFilesHandler::Response rv = statusHandler->reportError(error.show());
if (rv == DeleteFilesHandler::IGNORE_ERROR)
break;
else if (rv == DeleteFilesHandler::RETRY)
; //continue in loop
else
assert (false);
}
}
}
}
}
class FinalizeDeletion
{
public:
FinalizeDeletion(FolderComparison& folderCmp, const MainConfiguration& mainConfig) :
folderCmp_(folderCmp),
mainConfig_(mainConfig) {}
~FinalizeDeletion()
{
std::for_each(folderCmp_.begin(), folderCmp_.end(), FileSystemObject::removeEmpty);
redetermineSyncDirection(mainConfig_, folderCmp_, NULL);
}
private:
FolderComparison& folderCmp_;
const MainConfiguration& mainConfig_;
};
void FreeFileSync::deleteFromGridAndHD(FolderComparison& folderCmp, //attention: rows will be physically deleted!
std::vector<FileSystemObject*>& rowsToDeleteOnLeft, //refresh GUI grid after deletion to remove invalid rows
std::vector<FileSystemObject*>& rowsToDeleteOnRight, //all pointers need to be bound!
const bool deleteOnBothSides,
const bool useRecycleBin,
const MainConfiguration& mainConfig,
DeleteFilesHandler* statusHandler)
{
if (folderCmp.size() == 0)
return;
else if (folderCmp.size() != mainConfig.additionalPairs.size() + 1)
throw std::logic_error("Programming Error: Contract violation!");
FinalizeDeletion dummy(folderCmp, mainConfig); //ensure cleanup: redetermination of sync-directions and removal of invalid rows
if (deleteOnBothSides)
{
//mix selected rows from left and right (and remove duplicates)
std::set<FileSystemObject*> temp(rowsToDeleteOnLeft.begin(), rowsToDeleteOnLeft.end());
temp.insert(rowsToDeleteOnRight.begin(), rowsToDeleteOnRight.end());
std::vector<FileSystemObject*> rowsToDeleteBothSides(temp.begin(), temp.end());
deleteFromGridAndHDOneSide<LEFT_SIDE>(rowsToDeleteBothSides,
useRecycleBin,
statusHandler);
deleteFromGridAndHDOneSide<RIGHT_SIDE>(rowsToDeleteBothSides,
useRecycleBin,
statusHandler);
}
else
{
deleteFromGridAndHDOneSide<LEFT_SIDE>(rowsToDeleteOnLeft,
useRecycleBin,
statusHandler);
deleteFromGridAndHDOneSide<RIGHT_SIDE>(rowsToDeleteOnRight,
useRecycleBin,
statusHandler);
}
}
//############################################################################################################
/*Statistical theory: detect daylight saving time (DST) switch by comparing files that exist on both sides (and have same filesizes). If there are "enough"
that have a shift by +-1h then assert that DST switch occured.
What is "enough" =: N? N should be large enough AND small enough that the following two errors remain small:
Error 1: A DST switch is detected although there was none
Error 2: A DST switch is not detected although it took place
Error 1 results in lower bound, error 2 in upper bound for N.
Target: Choose N such that probability of error 1 and error 2 is lower than 0.001 (0.1%)
Definitions:
p1: probability that a file with same filesize on both sides was changed nevertheless
p2: probability that a changed file has +1h shift in filetime due to a change
M: number of files with same filesize on both sides in total
N: number of files with same filesize and time-diff +1h when DST check shall detect "true"
X: number of files with same filesize that have a +1h difference after change
Error 1 ("many files have +1h shift by chance") imposes:
Probability of error 1: (binomial distribution)
P(X >= N) = 1 - P(X <= N - 1) =
1 - sum_i=0^N-1 p3^i * (1 - p3)^(M - i) (M above i) shall be <= 0.0005
with p3 := p1 * p2
Probability of error 2 also will be <= 0.0005 if we choose N as lowest number that satisfies the preceding formula. Proof is left to the reader.
The function M |-> N behaves almost linearly and can be empirically approximated by:
N(M) =
2 for 0 <= M <= 500
125/1000000 * M + 5 for 500 < M <= 50000
77/1000000 * M + 10 for 50000 < M <= 400000
60/1000000 * M + 35 for 400000 < M
inline
bool sameFileTime(const time_t a, const time_t b)
{
if (a < b)
return b - a <= FILE_TIME_PRECISION;
else
return a - b <= FILE_TIME_PRECISION;
}
#ifdef FFS_WIN
unsigned int getThreshold(const unsigned filesWithSameSizeTotal)
{
if (filesWithSameSizeTotal <= 500)
return 2;
else if (filesWithSameSizeTotal <= 50000)
return unsigned(125.0/1000000 * filesWithSameSizeTotal + 5.0);
else if (filesWithSameSizeTotal <= 400000)
return unsigned(77.0/1000000 * filesWithSameSizeTotal + 10.0);
else
return unsigned(60.0/1000000 * filesWithSameSizeTotal + 35.0);
}
void FreeFileSync::checkForDSTChange(const FileCompareResult& gridData,
const std::vector<FolderPair>& directoryPairsFormatted,
int& timeShift, wxString& driveName)
{
driveName.Clear();
timeShift = 0;
TIME_ZONE_INFORMATION dummy;
DWORD rv = GetTimeZoneInformation(&dummy);
if (rv == TIME_ZONE_ID_UNKNOWN) return;
bool dstActive = rv == TIME_ZONE_ID_DAYLIGHT;
for (std::vector<FolderPair>::const_iterator i = directoryPairsFormatted.begin(); i != directoryPairsFormatted.end(); ++i)
{
bool leftDirIsFat = isFatDrive(i->leftDirectory);
bool rightDirIsFat = isFatDrive(i->rightDirectory);
if (leftDirIsFat || rightDirIsFat)
{
unsigned int filesTotal = 0; //total number of files (with same size on both sides)
unsigned int plusOneHourCount = 0; //number of files with +1h time shift
unsigned int minusOneHourCount = 0; // "
for (FileCompareResult::const_iterator j = gridData.begin(); j != gridData.end(); ++j)
{
const FileDescrLine& leftFile = j->fileDescrLeft;
const FileDescrLine& rightFile = j->fileDescrRight;
if ( leftFile.objType == FileDescrLine::TYPE_FILE && rightFile.objType == FileDescrLine::TYPE_FILE &&
leftFile.fileSize == rightFile.fileSize &&
leftFile.directory.CmpNoCase(i->leftDirectory.c_str()) == 0 && //Windows does NOT distinguish between upper/lower-case
rightFile.directory.CmpNoCase(i->rightDirectory.c_str()) == 0) //
{
++filesTotal;
if (sameFileTime(leftFile.lastWriteTimeRaw - 3600, rightFile.lastWriteTimeRaw))
++plusOneHourCount;
else if (sameFileTime(leftFile.lastWriteTimeRaw + 3600, rightFile.lastWriteTimeRaw))
++minusOneHourCount;
}
}
unsigned int threshold = getThreshold(filesTotal);
if (plusOneHourCount >= threshold)
{
if (dstActive)
{
if (rightDirIsFat) //it should be FAT; else this were some kind of error
{
timeShift = 3600;
driveName = getDriveName(i->rightDirectory);
}
}
else
{
if (leftDirIsFat) //it should be FAT; else this were some kind of error
{
timeShift = -3600;
driveName = getDriveName(i->leftDirectory);
}
}
return;
}
else if (minusOneHourCount >= threshold)
{
if (dstActive)
{
if (leftDirIsFat) //it should be FAT; else this were some kind of error
{
timeShift = 3600;
driveName = getDriveName(i->leftDirectory);
}
}
else
{
if (rightDirIsFat) //it should be FAT; else this were some kind of error
{
timeShift = -3600;
driveName = getDriveName(i->rightDirectory);
}
}
return;
}
}
}
}
#endif //FFS_WIN
*/
|