-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
FlycutOperator.m
1152 lines (1014 loc) · 38.5 KB
/
FlycutOperator.m
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
//
// FlycutOperator.m
// Flycut
//
// Flycut by Gennadiy Potapov and contributors. Based on Jumpcut by Steve Cook.
// Copyright 2011 General Arcade. All rights reserved.
//
// This code is open-source software subject to the MIT License; see the homepage
// at <https://github.com/TermiT/Flycut> for details.
//
// FlycutOperator owns and interacts with the FlycutStores, providing
// manipulation of the stores.
#import <Foundation/Foundation.h>
#import "FlycutOperator.h"
#import "MJCloudKitUserDefaultsSync/MJCloudKitUserDefaultsSync/MJCloudKitUserDefaultsSync.h"
#ifdef FLYCUT_MAC
#import "AppController.h"
#endif
@implementation FlycutOperator {
NSDateFormatter *dateFormatterForFilename;
NSDateFormatter *dateFormatterForDirectory;
}
- (id)init
{
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:40],
@"rememberNum",
[NSNumber numberWithInt:40],
@"favoritesRememberNum",
[NSNumber numberWithInt:1],
@"savePreference",
[NSDictionary dictionary],
@"store",
[NSNumber numberWithBool:YES],
@"skipPasswordFields",
[NSNumber numberWithBool:YES],
@"skipPboardTypes",
@"PasswordPboardType,org.nspasteboard.TransientType,org.nspasteboard.ConcealedType,org.nspasteboard.AutoGeneratedType,com.agilebits.onepassword",
@"skipPboardTypesList",
[NSNumber numberWithBool:NO],
@"skipPasswordLengths",
@"12, 20, 32",
@"skipPasswordLengthsList",
[NSNumber numberWithBool:NO],
@"revealPasteboardTypes",
[NSNumber numberWithBool:NO],
@"removeDuplicates",
[NSNumber numberWithBool:NO],
@"pasteMovesToTop",
[NSNumber numberWithBool:NO],
@"syncSettingsViaICloud",
[NSNumber numberWithBool:NO],
@"syncClippingsViaICloud",
nil]];
settingsSyncList = @[@"rememberNum",
@"favoritesRememberNum",
@"savePreference",
@"skipPasswordFields",
@"skipPboardTypes",
@"skipPboardTypesList",
@"skipPasswordLengths",
@"skipPasswordLengthsList",
@"removeDuplicates",
@"pasteMovesToTop"];
[settingsSyncList retain];
return self;
}
- (void)awakeFromNibDisplaying:(int) dispNum withDisplayLength:(int) dispLength withSaveSelector:(SEL) selector forTarget:(NSObject*) target
{
displayNum = dispNum;
displayLength = dispLength;
saveSelector = selector;
saveTarget = target;
// Initialize the FlycutStore
[self initializeStoresAndLoadContents];
// Stack position starts @ 0 by default
stackPosition = favoritesStackPosition = stashedStackPosition = 0;
[self registerOrDeregisterICloudSync];
}
-(FlycutStore*) allocInitFlycutStoreRemembering:(int) remembering
{
return [[FlycutStore alloc] initRemembering:remembering
displaying:displayNum
withDisplayLength:displayLength];
}
-(void) initializeStores
{
// Fixme - These stores are not released anywhere.
if ( !clippingStore )
{
clippingStore = [self allocInitFlycutStoreRemembering:[[NSUserDefaults standardUserDefaults] integerForKey:@"rememberNum"]];
clippingStore.deleteDelegate = self;
}
else
{
[clippingStore setDisplayNum:displayNum];
[clippingStore setDisplayLen:displayLength];
}
if ( ! favoritesStore )
{
favoritesStore = [self allocInitFlycutStoreRemembering:[[NSUserDefaults standardUserDefaults] integerForKey:@"favoritesRememberNum"]];
favoritesStore.deleteDelegate = self;
}
else
{
[favoritesStore setDisplayNum:displayNum];
[favoritesStore setDisplayLen:displayLength];
}
stashedStore = NULL;
}
-(void) initializeStoresAndLoadContents
{
[self initializeStores];
// If our preferences indicate that we are saving, load the dictionary from the saved plist
// and use it to get everything set up.
if ( [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 1 ) {
[self loadEngineFromPList];
}
}
-(void) willShowPreferences
{
issuedRememberResizeWarning = NO;
}
-(int) setRememberNum:(int)newRemember forPrimaryStore:(BOOL) isPrimaryStore
{
int oldRemeber = [self rememberNum];
// Ensure that we don't remember zero or fewer clippings.
if ( newRemember <= 0 )
{
newRemember = oldRemeber;
if ( newRemember <= 0 )
newRemember = 40;
}
if ( newRemember < [self jcListCount] &&
! issuedRememberResizeWarning &&
! [[NSUserDefaults standardUserDefaults] boolForKey:@"stifleRememberResizeWarning"]
) {
NSString *choice = [self delegateAlertWithMessageText:@"Resize Stack"
informationText:@"Resizing the stack to a value below its present size will cause clippings to be lost."
buttonsTexts:@[@"Resize", @"Cancel", @"Don't Warn Me Again"]];
if ( [choice isEqualToString:@"Cancel"] ) {
// Cancel - Change to prior setting.
newRemember = oldRemeber;
if ( isPrimaryStore ) {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:newRemember]
forKey:@"rememberNum"];
} else {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:newRemember]
forKey:@"favoritesRememberNum"];
}
} else if ( [choice isEqualToString:@"Don't Warn Me Again"] ) {
// Don't Warn Me Again
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES]
forKey:@"stifleRememberResizeWarning"];
} else {
// Resize
issuedRememberResizeWarning = YES;
}
}
// Set the value.
[clippingStore setRememberNum:newRemember];
return newRemember;
}
-(void)toggleToFromFavoritesStore
{
if (NULL != stashedStore)
[self restoreStashedStore];
else
[self switchToFavoritesStore];
}
-(bool)favoritesStoreIsSelected
{
return clippingStore == favoritesStore;
}
-(void)switchToFavoritesStore
{
stashedStore = clippingStore;
clippingStore = favoritesStore;
stashedStackPosition = stackPosition;
stackPosition = favoritesStackPosition;
}
- (bool)restoreStashedStore
{
if (NULL != stashedStore)
{
clippingStore = stashedStore;
stashedStore = NULL;
favoritesStackPosition = stackPosition;
stackPosition = stashedStackPosition;
return YES;
}
return NO;
}
- (NSString*)getPasteFromStackPosition
{
if ( [clippingStore jcListCount] > stackPosition ) {
return [self getPasteFromIndex: stackPosition];
}
return nil;
}
- (bool)saveFromStack
{
return [self saveFromStackWithPrefix:@""];
}
- (bool)saveFromStackWithPrefix:(NSString*) prefix
{
return [self saveFromStore:clippingStore atIndex:stackPosition withPrefix:prefix];
}
- (bool)saveFromStore:(FlycutStore*)store atIndex:(int)index withPrefix:(NSString*) prefix
{
#ifdef SANDBOXING
// This works fine when sandboxed. It just saves to ~/Library/Containers/.....
return NO;
# else
if ( [store jcListCount] > index ) {
// Get text from clipping store.
NSString *pbFullText = [self clippingStringWithCount:index inStore:store];
pbFullText = [pbFullText stringByReplacingOccurrencesOfString:@"\r" withString:@"\r\n"];
if (!dateFormatterForFilename) {
// Date formatters are time-expensive to create, so create once and reuse.
dateFormatterForFilename = [[NSDateFormatter alloc] init];
[dateFormatterForFilename setDateFormat:@"yyyy-MM-dd 'at' HH.mm.ss"];
}
// Get the timestamp string:
NSDate *currentDate = [NSDate date];
NSString *dateString = [dateFormatterForFilename stringFromDate:currentDate];
// Make a file name
NSString *fileName = [NSString stringWithFormat:@"%@%@Clipping %@.txt",
prefix, store == favoritesStore ? @"Favorite " : @"", dateString];
// Make a subdirectory, if doing autosave, to avoid a directory with too many files in it as that can make Finder effectively hang on launch if that directory were the desktop.
NSString *subdirectoryString = nil;
if ([prefix isEqualToString:@"Autosave "]) {
if (!dateFormatterForDirectory) {
// Date formatters are time-expensive to create, so create once and reuse.
dateFormatterForDirectory = [[NSDateFormatter alloc] init];
[dateFormatterForDirectory setDateFormat:@"'Autosave Clippings' yyyy/MM"];
}
subdirectoryString = [dateFormatterForDirectory stringFromDate:currentDate];
}
NSString *baseDirectoryString = nil;
NSString *fileNameWithPath = nil;
#ifdef FLYCUT_MAC
if ([AppController isAppSandboxed] && ![prefix isEqualToString:@"Autosave "]) {
// Since the app is sandboxed and this is not an auto-save, the user might want to say where to save it rather than just put it in ~/Library/Containers/..., so show a save dialog.
// Set the default name for the file and show the panel.
NSSavePanel* panel = [NSSavePanel savePanel];
[panel setNameFieldStringValue:fileName];
[panel setLevel:NSModalPanelWindowLevel];
[panel setAllowedFileTypes:@[@"txt"]];
if ([panel runModal] == NSFileHandlingPanelOKButton)
{
fileNameWithPath = [panel URL].path;
}
} else {
if ([prefix isEqualToString:@"Autosave "]) {
NSURL* autoSaveToLocation = [[NSUserDefaults standardUserDefaults] URLForKey:@"autoSaveToLocation"];
if (autoSaveToLocation) {
baseDirectoryString = autoSaveToLocation.path;
}
} else {
NSURL* saveToLocation = [[NSUserDefaults standardUserDefaults] URLForKey:@"saveToLocation"];
if (saveToLocation) {
baseDirectoryString = saveToLocation.path;
}
}
}
#endif
if (!fileNameWithPath) {
// An exact place to save wasn't set (like from a Save panel), so build one.
if (!baseDirectoryString) {
// Get the Desktop directory since nothing else was specified.
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory = [paths objectAtIndex:0];
baseDirectoryString = desktopDirectory;
}
if (subdirectoryString) {
// Apply a subdirectory / subdirectories.
NSString *directoryPath = [NSString stringWithFormat:@"%@/%@",
baseDirectoryString, subdirectoryString];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
withIntermediateDirectories:YES
attributes:nil
error:nil];
baseDirectoryString = directoryPath;
}
// Make a file name to write the data to using the base directory:
fileNameWithPath = [NSString stringWithFormat:@"%@/%@",
baseDirectoryString, fileName];
}
// Save content to the file
[pbFullText writeToFile:fileNameWithPath
atomically:NO
encoding:NSNonLossyASCIIStringEncoding
error:nil];
return YES;
}
return NO;
#endif
}
- (bool)saveFromStackToFavorites
{
if ( clippingStore != favoritesStore && [clippingStore jcListCount] > stackPosition ) {
// Get text from clipping store.
[favoritesStore addClipping:[clippingStore clippingAtPosition:stackPosition] ];
[self clearItemAtStackPosition];
return YES;
}
return NO;
}
- (NSString*)getPasteFromIndex:(int) position {
NSString *clipping = [self getClipFromCount:position];
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"pasteMovesToTop"] ) {
[clippingStore clippingMoveToTop:position];
stackPosition = 0;
[self actionAfterListModification];
}
return clipping;
}
-(NSString*)getClipFromCount:(int)indexInt
{
NSString *pbFullText;
NSArray *pbTypes;
if ( (indexInt + 1) > [clippingStore jcListCount] ) {
// We're asking for a clipping that isn't there yet
// This only tends to happen immediately on startup when not saving, as the entire list is empty.
DLog(@"Out of bounds request to jcList ignored.");
return nil;
}
return [self clippingStringWithCount:indexInt];
}
-(BOOL)shouldSkip:(NSString *)contents ofType:(NSString *)type fromAvailableTypes:(NSArray<NSString *> *)availableTypes
{
// Check to see if we are skipping passwords based on length and characters.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"skipPasswordFields"] )
{
// Check to see if they want a little help figuring out what types to enter.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"revealPasteboardTypes"] )
[clippingStore addClipping:type ofType:type fromAppLocalizedName:@"Flycut" fromAppBundleURL:nil atTimestamp:0];
[self actionAfterListModification];
__block bool skipClipping = NO;
// Check the array of types to skip.
if ( availableTypes && [[NSUserDefaults standardUserDefaults] boolForKey:@"skipPboardTypes"] )
{
NSSet *typesToSkip = [NSSet setWithArray: [[[[NSUserDefaults standardUserDefaults] stringForKey:@"skipPboardTypesList"] stringByReplacingOccurrencesOfString:@" " withString:@""] componentsSeparatedByString: @","]];
NSSet *pasteBoardTypes = [NSSet setWithArray: availableTypes];
if ( [pasteBoardTypes intersectsSet: typesToSkip] )
{
skipClipping = YES;
};
}
if (skipClipping)
return YES;
// Check the array of lengths to skip for suspicious strings.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"skipPasswordLengths"] )
{
int contentsLength = [contents length];
NSArray *lengthsArray = [[[[NSUserDefaults standardUserDefaults] stringForKey:@"skipPasswordLengthsList"] stringByReplacingOccurrencesOfString:@" " withString:@""] componentsSeparatedByString: @","];
[lengthsArray enumerateObjectsUsingBlock:^(id lengthString, NSUInteger idx, BOOL *stop)
{
if ( [lengthString integerValue] == contentsLength )
{
NSRange uppercaseLetter = [contents rangeOfCharacterFromSet: [NSCharacterSet uppercaseLetterCharacterSet]];
NSRange lowercaseLetter = [contents rangeOfCharacterFromSet: [NSCharacterSet lowercaseLetterCharacterSet]];
NSRange decimalDigit = [contents rangeOfCharacterFromSet: [NSCharacterSet decimalDigitCharacterSet]];
NSRange punctuation = [contents rangeOfCharacterFromSet: [NSCharacterSet punctuationCharacterSet]];
NSRange symbol = [contents rangeOfCharacterFromSet: [NSCharacterSet symbolCharacterSet]];
NSRange control = [contents rangeOfCharacterFromSet: [NSCharacterSet controlCharacterSet]];
NSRange illegal = [contents rangeOfCharacterFromSet: [NSCharacterSet illegalCharacterSet]];
NSRange whitespaceAndNewline = [contents rangeOfCharacterFromSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ( NSNotFound == control.location
&& NSNotFound == illegal.location
&& NSNotFound == whitespaceAndNewline.location
&& NSNotFound != uppercaseLetter.location
&& NSNotFound != lowercaseLetter.location
&& NSNotFound != decimalDigit.location
&& ( NSNotFound != punctuation.location
|| NSNotFound != symbol.location ) )
{
skipClipping = YES;
*stop = YES;
}
}
}];
if (skipClipping)
return YES;
}
}
return NO;
}
-(void)setDisableStoreTo:(bool) value
{
disableStore = value;
}
-(bool)storeDisabled
{
return disableStore;
}
-(void)setClippingsStoreDelegate:(id<FlycutStoreDelegate>) delegate
{
if ( !clippingStore )
[self initializeStores];
clippingStore.delegate = delegate;
}
-(void)setFavoritesStoreDelegate:(id<FlycutStoreDelegate>) delegate
{
if ( !favoritesStore )
[self initializeStores];
favoritesStore.delegate = delegate;
}
-(int)indexOfClipping:(NSString*)contents ofType:(NSString*)type fromApp:(NSString *)appName withAppBundleURL:(NSString *)bundleURL
{
return [clippingStore indexOfClipping:contents
ofType:type
fromAppLocalizedName:appName
fromAppBundleURL:bundleURL
atTimestamp:[[NSDate date] timeIntervalSince1970]];
}
-(bool)addClipping:(NSString*)contents ofType:(NSString*)type fromApp:(NSString *)appName withAppBundleURL:(NSString *)bundleURL target:(id)selectorTarget clippingAddedSelector:(SEL)clippingAddedSelector
{
if ( [clippingStore jcListCount] == 0 || ! [contents isEqualToString:[clippingStore clippingContentsAtPosition:0]]) {
bool success = [clippingStore addClipping:contents
ofType:type
fromAppLocalizedName:appName
fromAppBundleURL:bundleURL
atTimestamp:[[NSDate date] timeIntervalSince1970]];
// The below tracks our position down down down... Maybe as an option?
// if ( [clippingStore jcListCount] > 1 ) stackPosition++;
stackPosition = 0;
[selectorTarget performSelector:clippingAddedSelector];
[self actionAfterListModification];
return success;
}
return NO;
}
- (void)willDeleteClippingFromStore:(id)store AtIndex:(int)index {
if ( (!inhibitAutosaveClippings) // Avoid saving things that the user explicitly deletes.
&& ( store == favoritesStore
? [[[NSUserDefaults standardUserDefaults] valueForKey:@"saveForgottenFavorites"] boolValue]
: [[[NSUserDefaults standardUserDefaults] valueForKey:@"saveForgottenClippings"] boolValue] ) )
{
// clipping is being removed, so save it before it gets lost.
// Set to last item, save, and restore position.
[self saveFromStore:store atIndex:index withPrefix:@"Autosave "];
}
}
-(void)actionAfterListModification
{
if ( !inhibitSaveEngineAfterListModification
&& [[NSUserDefaults standardUserDefaults] integerForKey:@"savePreference"] >= 2 )
[self saveEngine];
}
-(int)jcListCount
{
return [clippingStore jcListCount];
}
-(int)rememberNum
{
return [clippingStore rememberNum];
}
-(int)stackPosition
{
return stackPosition;
}
-(bool)setStackPositionToFirstItem
{
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = 0;
return YES;
}
return NO;
}
-(bool)setStackPositionToLastItem
{
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = [clippingStore jcListCount] - 1;
return YES;
}
return NO;
}
-(bool)setStackPositionToTenMoreRecent
{
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = stackPosition - 10; if ( stackPosition < 0 ) stackPosition = 0;
return YES;
}
return NO;
}
-(bool)setStackPositionToTenLessRecent
{
if ( [clippingStore jcListCount] > 0 ) {
stackPosition = stackPosition + 10; if ( stackPosition >= [clippingStore jcListCount] ) stackPosition = [clippingStore jcListCount] - 1;
return YES;
}
return NO;
}
-(bool)clearItemAtStackPosition
{
if ([clippingStore jcListCount] == 0)
return NO;
inhibitAutosaveClippings = YES; // Avoid saving things that the user explicitly deletes.
[clippingStore clearItem:stackPosition];
inhibitAutosaveClippings = NO;
[self actionAfterListModification];
return YES;
}
-(bool)setStackPositionTo:(int) newStackPosition
{
if ( [clippingStore jcListCount] >= newStackPosition ) {
stackPosition = newStackPosition;
return YES;
}
return NO;
}
// Would probably be good to just prevent this scenario where it originates and
// delete this check.
-(void)adjustStackPositionIfOutOfBounds
{
if (stackPosition >= [clippingStore jcListCount] && stackPosition != 0) { // deleted last item
stackPosition = [clippingStore jcListCount] - 1;
}
}
-(bool)stackPositionIsInBounds
{
return ( [clippingStore jcListCount] > 0 && [clippingStore jcListCount] > stackPosition );
}
-(void)clearList
{
[clippingStore clearList];
[self actionAfterListModification];
}
-(void)mergeList
{
[clippingStore mergeList];
}
-(BOOL) isValidClippingNumber:(NSNumber *)number {
return [self isValidClippingNumber:number inStore:clippingStore];
}
-(BOOL) isValidClippingNumber:(NSNumber *)number inStore:(FlycutStore*)store {
return ( ([number intValue] + 1) <= [store jcListCount] );
}
-(NSString *) clippingStringWithCount:(int)count {
return [self clippingStringWithCount:count inStore:clippingStore];
}
-(NSString *) clippingStringWithCount:(int)count inStore:(FlycutStore*)store {
if ( [self isValidClippingNumber:[NSNumber numberWithInt:count] inStore:store] ) {
return [store clippingContentsAtPosition:count];
} else { // It fails -- we shouldn't be passed this, but...
return @"";
}
}
-(void) registerOrDeregisterICloudSync
{
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"syncSettingsViaICloud"] ) {
[[MJCloudKitUserDefaultsSync sharedSync] startWithKeyMatchList:settingsSyncList
withContainerIdentifier:kiCloudId];
}
else {
[[MJCloudKitUserDefaultsSync sharedSync] stopForKeyMatchList:settingsSyncList];
}
BOOL syncClippings = [[NSUserDefaults standardUserDefaults] boolForKey:@"syncClippingsViaICloud"];
BOOL changedSyncClippings = ( ![[NSUserDefaults standardUserDefaults] objectForKey:@"previousSyncClippingsViaICloud"]
|| syncClippings != [[NSUserDefaults standardUserDefaults] boolForKey:@"previousSyncClippingsViaICloud"] );
if ( changedSyncClippings )
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:syncClippings]
forKey:@"previousSyncClippingsViaICloud"];
// We will enable / disable regardless of changedSyncClippings because this gets called at app launch, where the feature was previously enabled but needs to be registered.
if ( syncClippings ) {
if ( changedSyncClippings )
firstClippingsSyncAfterEnabling = YES;
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationChanges forTarget:self];
[[MJCloudKitUserDefaultsSync sharedSync] addNotificationFor:MJSyncNotificationChanges withSelector:@selector(checkPreferencesChanges:) withTarget: self];
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationConflicts forTarget:self];
[[MJCloudKitUserDefaultsSync sharedSync] addNotificationFor:MJSyncNotificationConflicts withSelector:@selector(checkPreferencesConflicts:) withTarget: self];
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationSaveSuccess forTarget:self];
[[MJCloudKitUserDefaultsSync sharedSync] addNotificationFor:MJSyncNotificationSaveSuccess withSelector:@selector(checkPreferencesSaveSuccess:) withTarget: self];
[[MJCloudKitUserDefaultsSync sharedSync] startWithKeyMatchList:@[@"store"]
withContainerIdentifier:kiCloudId];
}
else {
[[MJCloudKitUserDefaultsSync sharedSync] removeNotificationsFor:MJSyncNotificationChanges forTarget:self];
[[MJCloudKitUserDefaultsSync sharedSync] stopForKeyMatchList:@[@"store"]];
}
}
-(NSDictionary*) checkPreferencesChanges:(NSDictionary*)changes
{
if ( [changes valueForKey:@"store"] )
{
[self integrateAllStores];
}
return nil;
}
-(void) integrateAllStores
{
DLog(@"integrating stores");
inhibitSaveEngineAfterListModification = YES;
[self integrateStoreAtKey:@"jcList" into:clippingStore descriptiveName:@""];
// It is possible that the user would disable sync rather than merge the main clippings store. They would have a poor user experience if they were then asked the same question about the favorites store after believing that they had disabled sync, so check setting before integrating.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"syncClippingsViaICloud"] )
[self integrateStoreAtKey:@"favoritesList" into:favoritesStore descriptiveName:@"favorites "];
DLog(@"integrating stores complete");
inhibitSaveEngineAfterListModification = NO;
firstClippingsSyncAfterEnabling = NO;
[self actionAfterListModification];
}
-(void) integrateStoreAtKey:(NSString*)listKey into:(FlycutStore*)store descriptiveName:(NSString*)name
{
FlycutStore *newContent = [self allocInitFlycutStoreRemembering:[clippingStore rememberNum]];
NSDictionary *loadDict = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"store"] copy];
if ( loadDict && [self loadEngineFrom:loadDict key:listKey into:newContent] )
{
BOOL mergeLists = NO;
if ( firstClippingsSyncAfterEnabling )
{
if ( 0 == [store jcListCount] )
{
// Just accept whatever iCloud has.
[store clearInsertionJournalCount:[[store insertionJournal] count]];
[store clearDeletionJournalCount:[[store deletionJournal] count]];
}
else if ( 0 == [newContent jcListCount] )
{
// We have something. iCloud has nothing. Ignore iCloud this time.
[newContent release];
[self actionAfterListModification]; // To overwrite what sync put in the defaults.
return;
}
else
{
int newCount = [newContent jcListCount];
int ourCount = [store jcListCount];
int newDistinct = 0;
int ourDistinct = 0;
for ( int i = 0 ; i < newCount ; i++ )
{
if ( 0 > [store indexOfClipping:[newContent clippingAtPosition:i]] )
{
newDistinct++;
}
}
for ( int i = 0 ; i < ourCount ; i++ )
{
if ( 0 > [newContent indexOfClipping:[store clippingAtPosition:i]] )
{
ourDistinct++;
}
}
BOOL promptUser = NO;
if ( 0 == ourDistinct )
{
// Just accept whatever iCloud has.
[store clearInsertionJournalCount:[[store insertionJournal] count]];
[store clearDeletionJournalCount:[[store deletionJournal] count]];
}
else if ( 0 == newDistinct )
{
// We have something. iCloud has nothing. Ignore iCloud this time.
[newContent release];
[self actionAfterListModification]; // To overwrite what sync put in the defaults.
return;
}
else
{
// Policy: For sake of user experience, the user will not be asked to merge or overwrite if one is a superset of the other and they have just said that they want sync. Assume they meant, "I want sync and I want it to include all content."
promptUser = YES;
}
while ( promptUser )
{
promptUser = NO;
NSString *choice = [self delegateAlertWithMessageText:@"First Sync"
informationText:[NSString stringWithFormat:@"Flycut found %i %@clipping%@ shared by both iCloud and this device, %i only in iCloud, and \%i only on this device. How can I handle these for you?",
(ourCount-ourDistinct),
name,
((ourCount-ourDistinct)!=1?@"s":@""),
newDistinct,ourDistinct]
buttonsTexts:@[@"Merge Lists",
@"Overwrite Device List",
@"Overwrite iCloud List",
@"Disable Sync"]];
if (!choice )
{
// This most likely means the UI wasn't implemented, so cover it with merge.
choice = @"Merge Lists";
}
if ( [choice isEqualToString:@"Merge Lists"] )
{
mergeLists = YES;
}
else if ( [choice isEqualToString:@"Disable Sync"] )
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO]
forKey:@"syncClippingsViaICloud"];
[newContent release];
[self registerOrDeregisterICloudSync];
[self actionAfterListModification]; // To overwrite what sync put in the defaults.
return;
}
else
{
NSString *okCancel = [self delegateAlertWithMessageText:@"Warning"
informationText:[NSString stringWithFormat:@"%@ will cause clippings to be lost!", choice]
buttonsTexts:@[@"Ok", @"Cancel"]];
if ( [okCancel isEqualToString:@"Ok"] )
{
if ( [choice isEqualToString:@"Overwrite Device List"] )
{
// Just accept whatever iCloud has.
[store clearInsertionJournalCount:[[store insertionJournal] count]];
[store clearDeletionJournalCount:[[store deletionJournal] count]];
}
else if ( [choice isEqualToString:@"Overwrite iCloud List"] )
{
// Ignore iCloud this time.
[newContent release];
[self actionAfterListModification]; // To overwrite what sync put in the defaults.
return;
}
else
{
// This should be impossible, so cover it with disabling sync.
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO] forKey:@"syncClippingsViaICloud"];
[newContent release];
[self registerOrDeregisterICloudSync];
[self actionAfterListModification]; // To overwrite what sync put in the defaults.
return;
}
}
else
{
promptUser = YES;
}
}
}
}
}
int newCount = [newContent jcListCount];
int offsetForMerge = 0;
for ( int i = 0 ; i < newCount ; i++ )
{
FlycutClipping *newClipping = [newContent clippingAtPosition:i];
if ( i >= [store jcListCount] )
{
// Clipping was beyond the end of the store, so just add it.
[self integrateInsertClipping:newClipping toStore:store atIndex:(i+offsetForMerge) withMerge:mergeLists];
}
else if ( ![newClipping isEqual:[store clippingAtPosition:(i+offsetForMerge)]] )
{
BOOL contentAtThisStorePositionNotInNewContent = (i+offsetForMerge) < [store jcListCount] && [newContent indexOfClipping:[store clippingAtPosition:(i+offsetForMerge)]] < 0;
int firstIndex = [store indexOfClipping:newClipping];
if ( firstIndex < 0 && [[store deletionJournal] containsObject:newClipping] )
{
// Clipping was deleted locally, so delete from the new content and move on.
[newContent clearItem:i];
i--;
newCount--;
}
else if ( firstIndex < 0 )
{
// Clipping wasn't previously in the store, so just add it.
if ( mergeLists && contentAtThisStorePositionNotInNewContent )
{
// Give priority to local items so they end up at the top of the list.
// Look to the next store item.
offsetForMerge++;
// While checking this newContent item again.
i--;
}
else
{
[self integrateInsertClipping:newClipping toStore:store atIndex:(i+offsetForMerge) withMerge:mergeLists];
}
}
else if ( contentAtThisStorePositionNotInNewContent )
{
// Contents in the store at this position didn't exist in the newContent. Handle deletion.
if ( mergeLists
|| [[store insertionJournal] containsObject:[store clippingAtPosition:(i+offsetForMerge)]] )
{
// Look to the next store item.
offsetForMerge++;
// While checking this newContent item again.
i--;
}
else
{
[store clearItem:(i+offsetForMerge)];
i--;
}
}
else if ( [store removeDuplicates] )
{
if ( i < firstIndex )
[store clippingMoveFrom:firstIndex To:(i+offsetForMerge)];
else
{
// This can only happen if the remote store allowed duplicates and we do not. Just delete from the new content and move on.
[newContent clearItem:i];
i--;
newCount--;
}
}
else
{
[self integrateInsertClipping:newClipping toStore:store atIndex:(i+offsetForMerge) withMerge:mergeLists];
}
}
}
while ( [store jcListCount] > newCount + offsetForMerge )
[store clearItem:(newCount + offsetForMerge)];
#ifdef DEBUG
if ( !mergeLists )
{
[newContent release];
newContent = [self allocInitFlycutStoreRemembering:[clippingStore rememberNum]];
[self loadEngineFrom:loadDict key:listKey into:newContent];
newCount = [newContent jcListCount];
if ( newCount != [store jcListCount] )
NSLog(@"Error in integrateStoreAtKey with mismatching after counts!");
else
{
for ( int i = 0 ; i < newCount ; i++ )
{
if ( ![[store clippingAtPosition:i] isEqual:[newContent clippingAtPosition:i]] )
NSLog(@"Error in integrateStoreAtKey with mismatching clippings at index %i!", i);
}
}
}
#endif
}
[newContent release];
}
-(void) integrateInsertClipping:(FlycutClipping*)clipping toStore:(FlycutStore*)store atIndex:(int)index withMerge:(BOOL)mergeLists
{
[clipping setDisplayLength:displayLength];
if ( mergeLists && [store jcListCount] == [store rememberNum] )
{
// Grow the rememberNum if needed in merge.
int newRememberNum = [store rememberNum] + 1;
[store setRememberNum:newRememberNum];
if ( store == favoritesStore )
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:newRememberNum]
forKey:@"favoritesRememberNum"];
}
else
{
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:newRememberNum]
forKey:@"rememberNum"];
}
}
[store insertClipping:clipping atIndex:index];
}
-(NSDictionary*) checkPreferencesConflicts:(NSDictionary*)changes
{
NSMutableDictionary *corrections = nil;
if ( [changes valueForKey:@"store"] )
{
// Load the version that the other party pushed.
[[NSUserDefaults standardUserDefaults] setObject:[changes valueForKey:@"store"][2] forKey:@"store"];
// Integrate stores to apply journaled changes to conflict resolution.
[self integrateAllStores];
// Load the resolution into corrections.
if ( !corrections )
corrections = [[NSMutableDictionary alloc] init];
corrections[@"store"] = [[NSUserDefaults standardUserDefaults] objectForKey: @"store"];
}
return corrections;
}
-(NSDictionary*) checkPreferencesSaveSuccess:(NSDictionary*)changes
{
if ( [changes valueForKey:@"store"] )
{
[clippingStore pruneJournals];
[favoritesStore pruneJournals];
}
return nil;
}
-(void) checkCloudKitUpdates
{
[[MJCloudKitUserDefaultsSync sharedSync] checkCloudKitUpdates];
}
-(bool) loadEngineFrom:(NSDictionary*)loadDict key:(NSString*)listKey into:(FlycutStore*)store