-
Notifications
You must be signed in to change notification settings - Fork 0
/
Notr_AppDelegate.m
executable file
·1462 lines (1080 loc) · 47.9 KB
/
Notr_AppDelegate.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
#import "Notr_AppDelegate.h"
#import <BWToolkitFramework/BWToolkitFramework.h>
enum WindowSize {
WSNormal,
WSBig,
WSLong
};
enum NotePosition {
NPTop,
NPBottom
};
@implementation Notr_AppDelegate
@synthesize statusItem, statusView, statusMenu, mainWindow, preferencesWindow, mainView, editView, currentView, notesTableView,
searchField, titleTextField, contentTextView, notesArrayController, pProgressSpinner, bIsSyncInProcess, bIsRemovingNotesDictionaryItems;
@synthesize query, bIsEditMode;
typedef void * CGSConnection;
extern OSStatus CGSNewConnection(const void **attributes, CGSConnection * id);
// Values for different types of item positions
int temporaryViewPosition = -1;
int startViewPosition = -2;
int endViewPosition = -3;
#define temporaryViewPositionNum [NSNumber numberWithInt:temporaryViewPosition]
#define startViewPositionNum [NSNumber numberWithInt:startViewPosition]
#define endViewPositionNum [NSNumber numberWithInt:endViewPosition]
// Scrawl drop type
NSString *NotrDropType = @"NotrDropType";
#pragma mark -
#pragma mark Initialization and deallocation methods
- (id)init {
if (self = [super init]) {
NSMutableDictionary *initialValues = [[NSMutableDictionary alloc] init];
pDeleteNotesDictionary = [[NSMutableDictionary alloc] init];
[initialValues setObject:[NSNumber numberWithBool:NO]
forKey:@"startOnLogin"];
[initialValues setObject:[NSNumber numberWithBool:YES]
forKey:@"editOnCreate"];
[initialValues setObject:[NSNumber numberWithBool:YES]
forKey:@"showBlur"];
[initialValues setObject:[NSNumber numberWithInteger:WSNormal]
forKey:@"windowSize"];
[initialValues setObject:[NSNumber numberWithInteger:NPTop]
forKey:@"newNotePosition"];
[[NSUserDefaultsController sharedUserDefaultsController]
setInitialValues:initialValues];
[initialValues release];
bIsSyncInProcess = FALSE;
bIsEditMode = FALSE;
}
return self;
}
- (void)applicationWillFinishLaunching:(NSNotification *)notification {
PFMoveToApplicationsFolderIfNecessary();
//[self ClearICloud];
if (![self IsICloudAvailable])
{
NSLog(@"No iCloud access");
}
// Sync data on every minute = 5 seconds
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(startBackgroundJobOfSyncData) userInfo:nil repeats:YES];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
// Hide the application upon startup
[[NSApplication sharedApplication] hide:self];
}
- (void)awakeFromNib {
float width = 30.0;
float height = [[NSStatusBar systemStatusBar] thickness];
NSRect viewFrame = NSMakeRect(0, 0, width, height);
bIsRemovingNotesDictionaryItems = FALSE;
[mainWindow setDelegate:self];
// Setup the Notr login item
[self setupLoginItem:self];
// Create a status item
statusView = [[StatusView alloc] initWithFrame:viewFrame controller:self];
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:width] retain];
[statusItem setView:statusView];
// Set the status menu's delegate
statusMenuDelegate = [[StatusMenuDelegate alloc] initWithController:self];
[statusMenu setDelegate:statusMenuDelegate];
// Setup a global hotkey
notrKeyCombo = [[PTKeyCombo alloc] initWithKeyCode:45 modifiers:controlKey+
optionKey+cmdKey];
notrHotKey = [[PTHotKey alloc] initWithIdentifier:@"NotrHotKey" keyCombo:notrKeyCombo];
[notrHotKey setTarget:self];
[notrHotKey setAction:@selector(toggleMainWindow:)];
[[PTHotKeyCenter sharedCenter] registerHotKey:notrHotKey];
// Set up the notes table view (delegate, dragging and dropping, etc.)
NSArray *dragTypes = [[NSArray alloc] initWithObjects:NotrDropType, nil];
[notesTableView setTarget:self];
[notesTableView setDataSource:self];
[notesTableView setDelegate:self];
[notesTableView setDoubleAction:@selector(showEditor:)];
[notesTableView registerForDraggedTypes:dragTypes];
[notesTableView setDraggingSourceOperationMask:(NSDragOperationMove | NSDragOperationCopy) forLocal:YES];
[dragTypes release];
// Add observers for when the notes are modified
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noteWasModified:) name:NSTextDidChangeNotification
object:contentTextView];
}
- (void)dealloc {
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem];
[statusView release];
[mainWindow release];
[currentView release];
[managedObjectContext release];
[persistentStoreCoordinator release];
[managedObjectModel release];
[pProgressSpinner release];
[super dealloc];
}
/**
Implementation of the applicationShouldTerminate: method, used here to
handle the saving of changes in the application managed object context
before the application terminates.
*/
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
if (!managedObjectContext) return NSTerminateNow;
if (![managedObjectContext commitEditing]) {
NSLog(@"%@:%s unable to commit editing to terminate", [self class], _cmd);
return NSTerminateCancel;
}
if (![managedObjectContext hasChanges]) return NSTerminateNow;
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// This error handling simply presents error information in a panel with an
// "Ok" button, which does not include any attempt at error recovery (meaning,
// attempting to fix the error.) As a result, this implementation will
// present the information to the user and then follow up with a panel asking
// if the user wishes to "Quit Anyway", without saving the changes.
// Typically, this process should be altered to include application-specific
// recovery steps.
BOOL result = [sender presentError:error];
if (result) return NSTerminateCancel;
NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?",
@"Quit without saves error question message");
NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save",
@"Quit without saves error question info");
NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:question];
[alert setInformativeText:info];
[alert addButtonWithTitle:quitButton];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
[alert release];
alert = nil;
if (answer == NSAlertAlternateReturn) return NSTerminateCancel;
}
return NSTerminateNow;
}
- (void)applicationDidResignActive:(NSNotification *)aNotification {
[statusView setClicked:NO];
[statusView setNeedsDisplay:YES];
[self closeMainWindow:self];
}
#pragma mark -
#pragma mark Methods for Sync iCloud Data
- (BOOL) IsICloudAvailable
{
BOOL bRes = FALSE;
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"8W27B5T8XC.com.allendunahoo.Scrawl"];
if (ubiq)
bRes = TRUE;
return bRes;
}
- (void) ClearICloud
{
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"8W27B5T8XC.com.allendunahoo.Scrawl"];
if (ubiq)
{
NSUbiquitousKeyValueStore *cloudStore = [NSUbiquitousKeyValueStore defaultStore];
NSMutableArray *pCloudArrary = [[NSMutableArray alloc] init];
[cloudStore setArray:pCloudArrary forKey:@"notesarray"];
[cloudStore synchronize];
[pCloudArrary release];
}
}
- (void)alertDidEnd:(NSAlert *)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
NSLog(@"clicked %d button\n", returnCode);
[alert release];
}
- (void)startBackgroundJobOfSyncData
{
if (!bIsSyncInProcess && !bIsEditMode)
{
//NSLog(@"Load document");
NSMetadataQuery *metaquery = [[NSMetadataQuery alloc] init];
query = metaquery;
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat: @"%K.pathExtension = 'txt'", NSMetadataItemFSNameKey];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
}
- (void)queryDidFinishGathering:(NSNotification *)notification
{
//NSLog(@"Finish query");
NSMetadataQuery *metaquery = [notification object];
[metaquery disableUpdates];
[metaquery stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:metaquery];
query = nil;
[self UpLoadNotesDataOnICloud:metaquery];
}
-(BOOL) IsItemNeedToRemoveFromDictonary : (NSDate*)pModifiedDate
{
BOOL bRes = FALSE;
NSDate *currentDate = [NSDate date];
NSTimeInterval seconds = [currentDate timeIntervalSinceDate:pModifiedDate];
NSInteger nDaysPassed = seconds / (24*60*60);
if (nDaysPassed > 10)
bRes = TRUE;
return bRes;
}
- (void) UpLoadNotesDataOnICloud:(NSMetadataQuery *)pSearchQuery
{
//NSLog(@"IN THE FUNCTION");
BOOL bShouldSyncWithCloud = false;
bIsSyncInProcess = TRUE;
// First get the values from icloud and update notes
[self saveAction:self];
BOOL bIsICloudDictionaryFound = FALSE;
NSMutableDictionary *pDataDictionary = nil;
if (pSearchQuery && [pSearchQuery resultCount]>0)
{
//NSLog(@"Dictionary Found");
NSMetadataItem *item = [pSearchQuery resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
NotesDocument *notedoc = [[NotesDocument alloc] initWithContentsOfURL:url ofType:@"txt" error:nil];
if (notedoc)
{
//NSLog(@"Note document initialize");
NSData* data=[[notedoc noteContent] dataUsingEncoding:NSUTF8StringEncoding];
CFPropertyListRef plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, kCFPropertyListImmutable, NULL);
// we check if it is the correct type and only return it if it is
if ([(id)plist isKindOfClass:[NSDictionary class]])
{
//NSLog(@"Plist created and udpdated dictionary");
NSDictionary *pDataDic = [(NSDictionary *)plist autorelease];
pDataDictionary = [[NSMutableDictionary alloc] initWithDictionary:pDataDic];
}
else
{
//NSLog(@"Dictionary is nil");
pDataDictionary = nil;
}
bIsICloudDictionaryFound = TRUE;
}
}
else
{
//NSLog(@"Dictionary Not Found, Init new");
pDataDictionary = [[NSMutableDictionary alloc] init];
}
// Delete items from dictionary if there are some to delete
if (pDeleteNotesDictionary && [pDeleteNotesDictionary count]>0)
{
bIsRemovingNotesDictionaryItems = TRUE;
NSArray *pAllKeys = [pDeleteNotesDictionary allKeys];
for (int n=0; n < [pAllKeys count]; n++)
{
NSString *csKey = [pAllKeys objectAtIndex:n];
if (csKey)
{
NSDictionary *pItemDic = [pDataDictionary objectForKey:csKey];
if (pItemDic)
{
// Find the key in cloud dictionary, if available delete it from there
[pItemDic setValue:@"TRUE" forKey:@"deletenote"];
bShouldSyncWithCloud = true;
}
}
}
[pDeleteNotesDictionary removeAllObjects];
bIsRemovingNotesDictionaryItems = FALSE;
}
// Upload notes data on icloud (start)
if (pDataDictionary)
{
//NSLog(@"Upload start");
// Loop on all notes ans then sync with icloud
NSArray *pLocalArary = [notesArrayController arrangedObjects];
for (int n=0; n < [pLocalArary count]; n++)
{
Notes *noteItem = [pLocalArary objectAtIndex:n];
NSDate *nsNoteCreateDate = [noteItem createDate];
NSString *csLocalCreatedDate = [nsNoteCreateDate description];
BOOL bNoteFound = TRUE;
NSMutableDictionary *pCloudNoteDic = [pDataDictionary objectForKey:csLocalCreatedDate];
if (!pCloudNoteDic)
{
bNoteFound = FALSE;
}
NSMutableDictionary *pDic = [[NSMutableDictionary alloc] init];
[pDic setValue:[noteItem title] forKey:@"title"];
[pDic setValue:[noteItem content] forKey:@"content"];
[pDic setValue:[noteItem createDate] forKey:@"createDate"];
[pDic setValue:[noteItem modifyDate] forKey:@"modifyDate"];
[pDic setValue:@"FALSE" forKey:@"deletenote"];
if (bNoteFound)
{
NSString *csCloudCreatedDate = [[pCloudNoteDic valueForKey:@"createDate"] description];
NSString *csCloudModifiedDate = [[pCloudNoteDic valueForKey:@"modifyDate"] description];
NSString *csLocalModifiedDate = [[noteItem modifyDate] description];
if ([csCloudCreatedDate compare:csLocalCreatedDate] == NSOrderedSame)
{
// This means we need to modify/replace the object only if Modified dates are different
if ([csCloudModifiedDate compare:csLocalModifiedDate] == NSOrderedAscending)
{
// Replace object
//NSLog(@"Item Replaced");
[pDataDictionary setValue:pDic forKey:csLocalCreatedDate];
bShouldSyncWithCloud = true;
}
}
}
else
{
//insert object
[pDataDictionary setValue:pDic forKey:csLocalCreatedDate];
bShouldSyncWithCloud = true;
//NSLog(@"New Item Inserted");
//NSLog(@"Title:%@ CreateDate:%@ ModifyDate:%@ ToDelete:%@", [noteItem title], [noteItem createDate], [noteItem modifyDate], @"FALSE");
}
[pDic release];
pDic = nil;
} // Upload notes data on icloud (end)
NSMutableArray *pKeysToRemoveArray = [[NSMutableArray alloc] init];
// Download notes data from icloud (start)
if (bIsICloudDictionaryFound)
{
//NSLog(@"Downlaod start");
if (pDataDictionary && [pDataDictionary count]>0)
{
NSArray *pAllKeys = [pDataDictionary allKeys];
// Loop on all array items
for (int nArrayIndex=0; nArrayIndex < [pAllKeys count]; nArrayIndex++)
{
NSString *csKey = [pAllKeys objectAtIndex:nArrayIndex];
NSDictionary *pItemDic = [pDataDictionary objectForKey:csKey];
if (pItemDic)
{
NSString *csTitle = [pItemDic objectForKey:@"title"];
NSString *csContent = [pItemDic objectForKey:@"content"];
NSDate *nsCreateDate = [pItemDic objectForKey:@"createDate"];
NSDate *nsModifyDate = [pItemDic objectForKey:@"modifyDate"];
//NSLog(@"Title:%@ CreateDate:%@ ModifyDate:%@ ToDelete:%@", csTitle, [nsCreateDate description], [nsModifyDate description], [pItemDic objectForKey:@"deletenote"]);
BOOL bIsItemForDelete = [[pItemDic objectForKey:@"deletenote"] boolValue];
if (bIsItemForDelete)
{
// Delete from the array controller if it is available
int nNoteIndex = [self GetNoteIndexFromCreateDate:nsCreateDate];
if (nNoteIndex >= 0)
{
//NSLog(@"Item found in local array to delete");
NSArray *pNotesArary = [notesArrayController arrangedObjects];
NSManagedObject *currentObject = [pNotesArary objectAtIndex:nNoteIndex];
if (currentObject)
{
[[self managedObjectContext] deleteObject:currentObject];
[self renumberViewPositions];
}
}
else
{
// NSLog(@"Item not found in local array to delete");
}
// Delete any delete entry which is 10 days old (start)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *csModifyDateString = [pItemDic objectForKey:@"modifyDate"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *pModifyDate = [dateFormatter dateFromString:csModifyDateString];
BOOL bDeleteItem = [self IsItemNeedToRemoveFromDictonary:pModifyDate];
if (bDeleteItem)
{
[pKeysToRemoveArray addObject:csKey];
}
[dateFormatter release];
dateFormatter = nil;
}
else
{
int nNotesIndex = [self GetNoteIndexFromCreateDate:nsCreateDate];
if (nNotesIndex >= 0)
{
//NSLog(@"Item found in local array");
NSArray *pNotesArary = [notesArrayController arrangedObjects];
if (pNotesArary && [pNotesArary count] > 0)
{
Notes *noteItem = [pNotesArary objectAtIndex:nNotesIndex];
if (noteItem)
{
NSString *nsNoteModifyDate = [[noteItem modifyDate] description];
// Compare who has the recent date
if ([nsNoteModifyDate compare:[nsModifyDate description]] == NSOrderedAscending)
{
//NSLog(@"Update item");
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *csCreateDateString = [pItemDic objectForKey:@"createDate"];
NSString *csModifyDateString = [pItemDic objectForKey:@"modifyDate"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *pCreateDate = [dateFormatter dateFromString:csCreateDateString];
NSDate *pModifyDate = [dateFormatter dateFromString:csModifyDateString];
[noteItem setTitle:csTitle];
[noteItem setContent:csContent];
[noteItem setCreateDate:pCreateDate];
[noteItem setModifyDate:pModifyDate];
[dateFormatter release];
dateFormatter = nil;
}
}
}
}
else
{
//NSLog(@"Insert New item in local array");
// Enter new note to array
NSManagedObject *newItem = [NSEntityDescription
insertNewObjectForEntityForName:@"Notes"
inManagedObjectContext:[self
managedObjectContext]];
// Add new item's data
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *csCreateDateString = [pItemDic objectForKey:@"createDate"];
NSString *csModifyDateString = [pItemDic objectForKey:@"modifyDate"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *pCreateDate = [dateFormatter dateFromString:csCreateDateString];
NSDate *pModifyDate = [dateFormatter dateFromString:csModifyDateString];
[newItem setValue:csContent forKey:@"content"];
[newItem setValue:pCreateDate forKey:@"createDate"];
[newItem setValue:pModifyDate forKey:@"modifyDate"];
[newItem setValue:[NSNumber numberWithInt:endViewPosition] forKey:@"viewPosition"];
[self renumberViewPositions];
[dateFormatter release];
dateFormatter = nil;
}
}
}
}
}
else
{
//NSLog(@"Array not found");
}
} // Download notes data from icloud (end)
if (pKeysToRemoveArray && [pKeysToRemoveArray count]>0)
{
bShouldSyncWithCloud = true;
[pDataDictionary removeObjectsForKeys:pKeysToRemoveArray];
}
[pKeysToRemoveArray release];
pKeysToRemoveArray = nil;
if (bShouldSyncWithCloud)
{
// Write dictionary to nsstring and upload to icloud
NSString *csNotesItemsDictionary = [pDataDictionary description];
//NSLog(@"%@", csNotesItemsDictionary);
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:@"8W27B5T8XC.com.allendunahoo.Scrawl"];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:kFILENAME];
NSError *pError;
NotesDocument *pDocObj = [[NotesDocument alloc] init];
[pDocObj setNoteContent:csNotesItemsDictionary];
if (pDocObj)
{
[pDocObj saveToURL:ubiquitousPackage ofType:@"txt" forSaveOperation:NSSaveOperation error:&pError];
//NSLog(@"Svaing file");
}
}
}
bIsSyncInProcess = FALSE;
}
// Return -1 if note note found
// Return index of note that has same create date
- (int) GetNoteIndexFromCreateDate : (NSDate*)nsCreateDate
{
int nIndex = -1;
NSArray *pNotesArary = [notesArrayController arrangedObjects];
for (int n=0; n < [pNotesArary count]; n++)
{
Notes *noteItem = [pNotesArary objectAtIndex:n];
if (noteItem)
{
NSString *nsNoteCreateDate = [[noteItem createDate] description];
if ([nsNoteCreateDate compare:[nsCreateDate description]] == NSOrderedSame)
{
// Item found with same create date
nIndex = n;
break;
}
}
}
return nIndex;
}
- (void) StartProgress
{
[pProgressSpinner startAnimation:nil];
}
- (void) StopProgress
{
[pProgressSpinner stopAnimation:nil];
}
#pragma mark -
#pragma mark Methods for managing Core Data
/**
Returns the support directory for the application, used to store the Core Data
store file. This code uses a directory named "Notr" for
the content, either in the NSApplicationSupportDirectory location or (if the
former cannot be found), the system's temporary directory.
*/
- (NSString *)applicationSupportDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:@"Scrawl"];
}
/**
Creates, retains, and returns the managed object model for the application
by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel) return managedObjectModel;
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application. This
implementation will create and return a coordinator, having added the
store for the application to it. (The directory for the store is created,
if necessary.)
*/
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator
{
if (persistentStoreCoordinator)
return persistentStoreCoordinator;
NSManagedObjectModel *mom = [self managedObjectModel];
if (!mom)
{
NSAssert(NO, @"Managed object model is nil");
NSLog(@"%@:%s No model to generate a store from", [self class], _cmd);
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
if ( ![fileManager fileExistsAtPath:applicationSupportDirectory isDirectory:NULL] )
{
if (![fileManager createDirectoryAtPath:applicationSupportDirectory withIntermediateDirectories:NO attributes:nil
error:&error])
{
NSString *failureString = [[NSString alloc] initWithFormat:@"Failed to create App Support directory %@ : %@",
applicationSupportDirectory, error];
NSAssert(NO, (failureString));
NSLog(@"Error creating application support directory at %@ : %@",applicationSupportDirectory,error);
[failureString release];
return nil;
}
}
#ifndef DEBUG
NSURL *url = [[NSURL alloc] initFileURLWithPath:[applicationSupportDirectory stringByAppendingPathComponent:@"storedata"]];
#else
NSURL *url = [[NSURL alloc] initFileURLWithPath:[applicationSupportDirectory stringByAppendingPathComponent:@"storedata-dbg"]];
#endif
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: mom];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error])
{
[[NSApplication sharedApplication] presentError:error];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
return nil;
}
[url release];
return persistentStoreCoordinator;
}
/**
Returns the managed object context for the application (which is already
bound to the persistent store coordinator for the application.)
*/
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext) return managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
return managedObjectContext;
}
/**
Returns the NSUndoManager for the application. In this case, the manager
returned is that of the managed object context for the application.
*/
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
return [[self managedObjectContext] undoManager];
}
#pragma mark -
#pragma mark Interface Builder actions
/**
Performs the save action for the application, which is to send the save:
message to the application's managed object context. Any encountered errors
are presented to the user.
*/
- (IBAction) saveAction:(id)sender {
NSError *error = nil;
if (![[self managedObjectContext] commitEditing]) {
NSLog(@"%@:%s unable to commit editing before saving", [self class], _cmd);
}
if (![[self managedObjectContext] save:&error]) {
[[NSApplication sharedApplication] presentError:error];
}
}
- (IBAction)showMainWindow:(id)sender {
if (mainWindow)
{
[self closeMainWindow:self];
}
[self removeEmptyNotes];
bIsEditMode = FALSE;
[self showMainWindowWithView:mainView];
if([sender isMemberOfClass:[BWTransparentButton class]])
{
NSLog(@"Done button");
//[self performSelectorInBackground:@selector(UpLoadDataOnICloud) withObject:nil];
}
}
- (IBAction)closeMainWindow:(id)sender {
if (mainWindow)
{
[statusView setClicked:NO];
[statusView setNeedsDisplay:YES];
//[self closeWindowWithSlide:mainWindow];
[mainWindow endEditingFor:nil];
[mainWindow orderOut:self];
[mainWindow release];
mainWindow = nil;
// Check to see if there is a note with "IMPORTANT" in the title
// [self checkForImportantNote];
}
}
- (IBAction)closeMainWindowAndHide:(id)sender {
if (mainWindow) {
[self closeMainWindow:self];
// Check to see if there are any windows open. If not, hide.
for (NSWindow *window in [[NSApplication sharedApplication] windows]) {
if ([window isVisible] == YES) {
return;
}
[[NSApplication sharedApplication] hide:self];
}
}
}
- (IBAction)showEditor:(id)sender {
if ([[notesArrayController selectedObjects] count] > 0) {
if (mainWindow) {
[self closeMainWindow:self];
}
bIsEditMode = TRUE;
[self showMainWindowWithView:editView];
// If the content is "New Note", select it. Otherwise, move the insertion point to the start.
if ([[[notesArrayController selectedObjects] objectAtIndex:0] content] == @"New Note") {
[contentTextView selectAll:self];
}
else
{
[contentTextView setSelectedRange:NSMakeRange(0, 0)];
}
}
}
- (IBAction)showPreferences:(id)sender {
[self closeMainWindow:sender];
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
[preferencesWindow center];
[preferencesWindow makeKeyAndOrderFront:sender];
}
- (IBAction)showAbout:(id)sender {
[self closeMainWindow:sender];
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
[[NSApplication sharedApplication] orderFrontStandardAboutPanel:self];
}
- (IBAction)undo:(id)sender {
[[[mainWindow firstResponder] undoManager] undo];
[notesTableView reloadData];
}
- (IBAction)redo:(id)sender {
[[[mainWindow firstResponder] undoManager] redo];
[notesTableView reloadData];
}
- (IBAction)addNewItem:(id)sender {
[self addNewItemWithContent:@"New Note" select:YES];
if ([[[[NSUserDefaultsController sharedUserDefaultsController]
values] valueForKey:@"editOnCreate"] boolValue] == YES) {
[self showEditor:self];
}
}
- (IBAction)removeSelectedItems:(id)sender
{
[self saveAction:self];
NSArray *selectedItems = [notesArrayController selectedObjects];
int indexOfFirstSelectedObject = [notesArrayController selectionIndex];
BOOL bIsCloudAvailable = [self IsICloudAvailable];
int count;
for (count = 0; count < [selectedItems count]; count++)
{
// Wait till the remove items are cleared from delete dictionary
while (bIsRemovingNotesDictionaryItems) { }
NSManagedObject *currentObject = [selectedItems objectAtIndex:count];
NSDate *nsNoteCreateDate = [currentObject valueForKey:@"createDate"];
NSString *csContent = [currentObject valueForKey:@"content"];
// Maintain the dictionary for delete
if (bIsCloudAvailable)
{
[pDeleteNotesDictionary setValue:csContent forKey:[nsNoteCreateDate description]];
}
[[self managedObjectContext] deleteObject:currentObject];
}
[self renumberViewPositions];
if (indexOfFirstSelectedObject > [[notesArrayController arrangedObjects] count] - 1)
indexOfFirstSelectedObject--;
[notesArrayController setSelectionIndex:indexOfFirstSelectedObject];
//[self performSelectorInBackground:@selector(SyncData) withObject:nil];
[self startBackgroundJobOfSyncData];
}
- (IBAction)duplicateSelectedItem:(id)sender {
[self saveAction:self];
NSManagedObject *newItem = [NSEntityDescription
insertNewObjectForEntityForName:@"Notes"
inManagedObjectContext:[self
managedObjectContext]];
// Get the old item's data
Notes *oldItem = [[notesArrayController selectedObjects] objectAtIndex:0];
NSString *content = [oldItem content];
NSDate *createDate = [oldItem createDate];
NSDate *modifyDate = [oldItem modifyDate];
NSNumber *viewPosition = [oldItem viewPosition];
[newItem setValue:content forKey:@"content"];
[newItem setValue:createDate forKey:@"createDate"];
[newItem setValue:modifyDate forKey:@"modifyDate"];
[newItem setValue:viewPosition forKey:@"viewPosition"];
[self renumberViewPositions];
}
- (IBAction)renameItem:(id)sender {
if ([[notesArrayController selectedObjects] count] > 0)
{
[notesTableView editColumn:0 row:[notesTableView selectedRow] withEvent:nil select:NO];
}
}