This repository was archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.m
More file actions
1514 lines (1180 loc) · 39.8 KB
/
AppDelegate.m
File metadata and controls
1514 lines (1180 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// AppDelegate.m
// Violet
//
#import "AppDelegate.h"
#import "CCPathMonitor.h"
#import "CCGroupNode.h"
#import "CCDeviceGroupNode.h"
#import "CCItemNode.h"
#import "CCDeviceItemNode.h"
#import "CCLibrary.h"
#import "CCNetworkReachability.h"
#import "CCOutlineView.h"
#define DevicesDisabled
static NSString * const LibraryItemName = @"Library";
static NSString * const DevicesItemName = @"Devices";
static NSString * const CCPasteboardType = @"CCPasteboardType";
static NSString * const CCDefaultSeletionKey = @"CCDefaultSeletionKey";
static NSString * const CCDefaultLibraryPathKey = @"CCDefaultLibraryPathKey";
static NSString * const CCKnownLibrariesKey = @"CCKnownLibrariesKey";
static NSString * const CCHasLaunchedBefore = @"CCHasLaunchedBefore";
static NSString * const CCDevicePath = @"/Volumes";
static const CGFloat SplitViewDividerMin = 175.0;
static const CGFloat SplitViewDividerMax = 450.0;
static const NSInteger LibraryItemSortIndex = 10;
static const NSInteger DevicesItemSortIndex = NSIntegerMax;
@interface AppDelegate (Private)
- (void)_debugDeleteGroups;
- (void)_debugAddNodes;
- (void)searchQueryNoteHandler:(NSNotification *)note;
- (void)searchForKnownLibraries;
- (void)stopSearchForKnownLibraries;
- (void)runLibraryChooser;
- (void)runPreferencesChanger;
- (void)deleteDeviceNode:(CCNode *)node;
- (void)pathOfInterestChanged:(NSNotification *)note;
- (void)reachabilityChanged:(NSNotification* )note;
- (void)recalculateSortIndexes;
- (NSArray *)sortDescriptors;
- (void)ensureDeviceGroupExists;
- (void)ensureSpecialGroups;
- (void)cleanStaleDeviceNodes;
+ (NSArray *)acceptedDragTypes;
+ (NSArray *)acceptedFilenameExtensions;
@end
@implementation AppDelegate
@synthesize window;
@synthesize sourceList;
@synthesize sourceListNameColumn;
@synthesize sourceListScrollView;
@synthesize libraryChooserWindow;
@synthesize libraryChooserTable;
@synthesize libraryChooserChooseButton;
@synthesize libraryChooserKnownPaths;
@synthesize searchInProgressIndicator;
@synthesize libraryChooserNameTableColumn;
@synthesize libraryChooserPathTableColumn;
@synthesize preferencesWindow;
#pragma mark Debug
- (void)_debugDeleteGroups
{
NSManagedObjectContext * context = [self managedObjectContext];
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:@"GroupNode" inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id object in result)
{
[context deleteObject:object];
}
}
- (void)_debugAddNodes
{
CCItemNode *item = [CCItemNode itemNode];
[item setName:@"Random Item 1"];
[item setSortIndex:[NSNumber numberWithInteger:0]];
[_libraryNode addChild:item];
item = [CCItemNode itemNode];
[item setName:@"Random Item 2"];
[item setSortIndex:[NSNumber numberWithInteger:2000]];
[_libraryNode addChild:item];
item = [CCItemNode itemNode];
[item setName:@"Random Iwwwwwwwwwwwwwwwwwwwwwtem 3"];
[item setSortIndex:[NSNumber numberWithInteger:3000]];
[_libraryNode addChild:item];
CCGroupNode *g = [CCGroupNode groupNode];
[g setName:@"A Group"];
[_libraryNode addChild:g];
[g setSortIndex:[NSNumber numberWithInteger:5000]];
item = [CCItemNode itemNode];
[item setName:@"Random Item 33"];
[item setSortIndex:[NSNumber numberWithInteger:3000]];
[g addChild:item];
g = [CCGroupNode groupNode];
[g setName:@"Another Group33333333333qweqweqw1223"];
[_libraryNode addChild:g];
[g setSortIndex:[NSNumber numberWithInteger:8000]];
item = [CCItemNode itemNode];
[item setName:@"Random Item s"];
[item setSortIndex:[NSNumber numberWithInteger:3000]];
[g addChild:item];
g = [CCGroupNode groupNode];
[g setName:@"Third Group"];
[_libraryNode addChild:g];
[g setSortIndex:[NSNumber numberWithInteger:8000]];
item = [CCItemNode itemNode];
[item setName:@"Random Item 4"];
[item setSortIndex:[NSNumber numberWithInteger:3000]];
[g addChild:item];
}
#pragma mark -
#pragma mark Library Chooser
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([object isEqual:_query])
{
NSMutableArray *array = [NSMutableArray array];
for(NSMetadataItem *item in [_query results])
{
[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:[item valueForAttribute:(NSString *)kMDItemDisplayName], @"name",
[item valueForAttribute:(NSString *)kMDItemPath], @"path", nil]];
}
[self setLibraryChooserKnownPaths:array];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:CCKnownLibrariesKey];
[libraryChooserTable reloadData];
}
}
- (void)searchQueryNoteHandler:(NSNotification *)note
{
id object = [note object];
if([object isEqualTo:_query])
{
[self stopSearchForKnownLibraries];
}
}
- (void)searchForKnownLibraries
{
NSArray *defaults = [[NSUserDefaults standardUserDefaults] objectForKey:CCKnownLibrariesKey];
if([defaults count] > 0)
{
NSMutableArray *valid = [NSMutableArray array];
for(NSDictionary *library in defaults)
{
if([[NSFileManager defaultManager] fileExistsAtPath:[library objectForKey:@"path"]])
{
[valid addObject:library];
}
}
[self setLibraryChooserKnownPaths:valid];
[libraryChooserTable reloadData];
}
_query = [[NSMetadataQuery alloc] init];
NSString *libaryFormat = [NSString stringWithFormat:@"*.%@", [CCLibrary libraryExtension]];
id predicate = [NSPredicate predicateWithFormat:@"(kMDItemFSName like[c] %@)", libaryFormat];
[_query setPredicate:predicate];
[_query setSearchScopes:[NSArray arrayWithObject:NSHomeDirectory()]];
[_query addObserver:self forKeyPath:@"results" options:0 context:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(searchQueryNoteHandler:)
name:NSMetadataQueryDidFinishGatheringNotification
object:_query];
[_query startQuery];
[searchInProgressIndicator startAnimation:self];
}
- (void)stopSearchForKnownLibraries
{
if([_query isStarted])
{
[_query stopQuery];
[_query release];
_query = nil;
}
[searchInProgressIndicator stopAnimation:self];
}
- (void)runLibraryChooser
{
_chooserCompleted = NO;
[self searchForKnownLibraries];
NSModalSession session = [NSApp beginModalSessionForWindow:libraryChooserWindow];
while(!_chooserCompleted)
{
if ([NSApp runModalSession:session] != NSRunContinuesResponse)
{
if(!_chooserCompleted)
{
// Other dialogs can bump us out of our modal session before we want to leave
// We just keep starting sessions until we're ready to leave
[NSApp beginModalSessionForWindow:libraryChooserWindow];
}
else
{
break;
}
}
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];
}
[NSApp endModalSession:session];
[self setLibraryChooserWindow:nil];
[self stopSearchForKnownLibraries];
}
#pragma mark -
#pragma mark Preferences
- (void)runPreferencesChanger
{
_preferenceChangesCompleted = NO;
[preferencesWindow center];
NSModalSession session = [NSApp beginModalSessionForWindow:preferencesWindow];
while(!_preferenceChangesCompleted)
{
if ([NSApp runModalSession:session] != NSRunContinuesResponse)
{
if(!_preferenceChangesCompleted)
{
// Other dialogs can bump us out of our modal session before we want to leave
// We just keep starting sessions until we're ready to leave
[NSApp beginModalSessionForWindow:preferencesWindow];
}
else
{
break;
}
}
}
[NSApp endModalSession:session];
}
#pragma mark -
#pragma mark Basics
- (void)awakeFromNib
{
NSNumber *hasLaunchedBefore = [[NSUserDefaults standardUserDefaults] objectForKey:CCHasLaunchedBefore];
if(!hasLaunchedBefore)
{
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:CCHasLaunchedBefore];
}
_preferenceChangesCompleted = YES;
_chooserCompleted = YES;
_isFirstLaunch = ![hasLaunchedBefore boolValue];
_createNewLibrary = _isFirstLaunch;
_libraryNode = nil;
libraryChooserKnownPaths = nil;
_monitor = nil;
_internetReach = nil;
_selectedLibraryPath = [[NSUserDefaults standardUserDefaults] objectForKey:CCDefaultLibraryPathKey];
_library = [[CCLibrary alloc] init];
// Double click on the chooser table to chose an library
[libraryChooserTable setDoubleAction:@selector(choose:)];
[sourceList registerForDraggedTypes:[AppDelegate acceptedDragTypes]];
}
- (void)dealloc
{
[_monitor release];
[_internetReach release];
[_library release];
[_selectedLibraryPath release];
[libraryChooserKnownPaths release];
[_libraryNode release];
[window release];
[sourceList release];
[sourceListNameColumn release];
[sourceListScrollView release];
[treeController release];
[libraryChooserWindow release];
[managedObjectContext release];
[persistentStoreCoordinator release];
[managedObjectModel release];
[super dealloc];
}
#pragma mark -
#pragma mark NSApplicationDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)note
{
CGEventRef event = CGEventCreate(NULL);
CGEventFlags flags = CGEventGetFlags(event);
CFRelease(event);
if (flags & kCGEventFlagMaskAlternate)
{
[self runLibraryChooser];
}
while(![[NSFileManager defaultManager] fileExistsAtPath:_selectedLibraryPath] && !_createNewLibrary)
{
[self runLibraryChooser];
}
[_library openLibraryAtPath:_selectedLibraryPath createIfMissing:_createNewLibrary];
if(_isFirstLaunch)
{
[window center];
}
[window makeKeyAndOrderFront:self];
treeController = [[NSTreeController alloc] initWithContent:nil];
[treeController setManagedObjectContext:[self managedObjectContext]];
[treeController setChildrenKeyPath:@"children"];
[treeController setEntityName:@"Node"];
[treeController setFetchPredicate:[NSPredicate predicateWithFormat:@"parent == nil"]];
[treeController setAutomaticallyPreparesContent:YES];
[treeController setAvoidsEmptySelection:NO];
[treeController bind:@"managedObjectContext" toObject:self withKeyPath:@"managedObjectContext" options:nil];
[treeController bind:@"sortDescriptors" toObject:self withKeyPath:@"sortDescriptors" options:nil];
// Not sure how to get the tree controller to work without this
[treeController prepareContent];
[sourceListNameColumn bind:@"value" toObject:treeController withKeyPath:@"arrangedObjects.name" options:nil];
[sourceList reloadData];
// [self _debugDeleteGroups];
[self cleanStaleDeviceNodes];
[self ensureSpecialGroups];
// [self _debugAddNodes];
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:CCDefaultSeletionKey];
NSIndexPath *path = nil;
if([array count] > 0)
{
path = [NSIndexPath indexPathWithIndex:[[array objectAtIndex:0] integerValue]];
for(NSUInteger i=1; i<[array count]; i++)
{
path = [path indexPathByAddingIndex:[[array objectAtIndex:i] integerValue]];
}
}
else
{
path = [NSIndexPath indexPathWithIndex:-1];
}
// Performing the selection right now doesn't seem to work
[treeController performSelector:@selector(setSelectionIndexPaths:) withObject:[NSArray arrayWithObject:path] afterDelay:0.0];
// Observer network changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:CCNetworkReachabilityChangeNotification object:nil];
_internetReach = [[CCNetworkReachability reachabilityForHost:nil] retain];
[_internetReach startNotifier];
#ifndef DevicesDisabled
// Observe path changes where devices are mounted
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pathOfInterestChanged:) name:CCPathOfInterestChangedNotification object:nil];
_monitor = [[CCPathMonitor alloc] initWithPath:CCDevicePath];
[_monitor startNotifier];
#endif // DevicesDisabled
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
return YES;
}
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
[_internetReach stopNotifier];
NSMutableArray *index = [NSMutableArray array];
NSIndexPath *indexPath = [treeController selectionIndexPath];
for(NSUInteger i=0; i<[indexPath length]; i++)
{
[index addObject:[NSNumber numberWithInteger:[indexPath indexAtPosition:i]]];
}
if([index count] > 0)
{
[[NSUserDefaults standardUserDefaults] setObject:index forKey:CCDefaultSeletionKey];
}
[[NSUserDefaults standardUserDefaults] setObject:[_library path] forKey:CCDefaultLibraryPathKey];
}
/**
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;
}
#pragma mark -
#pragma mark Device Changes
- (void)pathOfInterestChanged:(NSNotification *)note
{
id object = [note object];
if([object isKindOfClass:[NSString class]])
{
NSString *item = (NSString *)object;
if([[NSFileManager defaultManager] fileExistsAtPath:item])
{
DeviceType type = [_monitor deviceTypeForPath:item];
type = type;
}
else
{
// Need to add code to validate the device
for(id object in [_devices children])
{
if(([object isKindOfClass:[CCDeviceItemNode class]] && [(CCDeviceItemNode *)object isDeviceNode])
||([object isKindOfClass:[CCDeviceGroupNode class]] && [(CCDeviceGroupNode *)object isDeviceNode]))
{
NSString *path = [(CCDeviceItemNode *)object path];
if(![[NSFileManager defaultManager] fileExistsAtPath:path])
{
[self deleteDeviceNode:object];
}
}
}
}
}
[[self managedObjectContext] processPendingChanges];
if(_devices && [[_devices children] count] < 1)
{
[[self managedObjectContext] deleteObject:_devices];
_devices = nil;
}
[self recalculateSortIndexes];
[sourceList reloadData];
}
- (void)deleteDeviceNode:(CCNode *)node
{
if(![node isDeviceNode])
{
return;
}
[[self managedObjectContext] deleteObject:node];
}
#pragma mark -
#pragma mark Network Reachability
- (void)reachabilityChanged:(NSNotification* )note
{
id object = [note object];
if([object isKindOfClass:[CCNetworkReachability class]])
{
CCNetworkReachability *reach = (CCNetworkReachability *)object;
if(reach == _internetReach)
{
if([reach connectionAvailable])
{
NSLog(@"Internet connection available");
}
else
{
NSLog(@"Internet connection not available");
}
}
}
}
#pragma mark -
#pragma mark Sorting
- (void)recalculateSortIndexes
{
NSMutableArray *mutableArray = [NSMutableArray array];
[_libraryNode setSortIndex:[NSNumber numberWithInteger:LibraryItemSortIndex]];
for (CCNode *node in [[_libraryNode children] sortedArrayUsingDescriptors:[self sortDescriptors]])
{
[mutableArray addObject:node];
if([node isKindOfClass:[CCGroupNode class]])
{
NSSet *children = [(CCGroupNode *)node children];
if([children count] > 0)
{
NSArray *array = [children sortedArrayUsingDescriptors:[self sortDescriptors]];
[mutableArray addObjectsFromArray:array];
}
}
}
[mutableArray sortUsingDescriptors:[self sortDescriptors]];
for(NSUInteger i=0; i<[mutableArray count]; i++)
{
[[mutableArray objectAtIndex:i] setSortIndex:[NSNumber numberWithInteger:(i+1)*2]];
}
[treeController rearrangeObjects];
}
- (NSArray *)sortDescriptors;
{
return [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"sortIndex" ascending:YES] autorelease]];
}
#pragma mark -
#pragma mark Core Data Object Managment
- (void)ensureDeviceGroupExists
{
if(_devices)
{
return;
}
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:@"GroupNode" inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id item in result)
{
if([item isSpecialGroup])
{
if([[item name] isEqualToString:DevicesItemName])
{
_devices = [item retain];
}
}
}
if(!_devices)
{
_devices = [CCDeviceGroupNode groupNode];
[_devices setName:DevicesItemName];
[_devices setIsExpanded:[NSNumber numberWithBool:YES]];
[_devices setIsSpecialGroup:[NSNumber numberWithBool:YES]];
[_devices setSortIndex:[NSNumber numberWithInteger:DevicesItemSortIndex]];
[_devices setParent:nil];
}
}
- (void)ensureSpecialGroups
{
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:@"GroupNode" inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id item in result)
{
if([item isSpecialGroup])
{
if([[item name] isEqualToString:LibraryItemName])
{
_libraryNode = [item retain];
}
}
}
if(!_libraryNode)
{
_libraryNode = [CCGroupNode groupNode];
[_libraryNode setName:LibraryItemName];
[_libraryNode setIsExpanded:[NSNumber numberWithBool:YES]];
[_libraryNode setIsSpecialGroup:[NSNumber numberWithBool:YES]];
[_libraryNode setSortIndex:[NSNumber numberWithInteger:LibraryItemSortIndex]];
[_libraryNode setParent:nil];
}
}
- (void)cleanStaleDeviceNodes
{
NSManagedObjectContext * context = [self managedObjectContext];
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:@"Node" inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id object in result)
{
if([object isKindOfClass:[CCNode class]] && [(CCNode *)object isDeviceNode])
{
NSLog(@"Deleting %@", object);
[context deleteObject:object];
}
}
}
#pragma mark -
#pragma mark Preferences Changer IBActions
- (IBAction)showPreferences:(id)sender
{
[self runPreferencesChanger];
}
- (IBAction)preferencesChangesDone:(id)sender
{
_preferenceChangesCompleted = YES;
[preferencesWindow close];
[NSApp stopModal];
}
#pragma mark -
#pragma mark Library Chooser IBActions
- (IBAction)chooseOther:(id)sender
{
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowsMultipleSelection:NO];
[panel setAllowedFileTypes:[NSArray arrayWithObject:[CCLibrary libraryExtension]]];
[panel beginSheetForDirectory:[CCLibrary documentsDirectory]
file:nil
modalForWindow:libraryChooserWindow
modalDelegate:self
didEndSelector:@selector(libraryChooserOpenPanelDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
- (void)libraryChooserOpenPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
if(returnCode == NSAlertDefaultReturn)
{
NSArray *urls = [panel URLs];
if([urls count] != 1)
{
NSLog(@"[Error] this shouldn't happen");
}
else
{
_selectedLibraryPath = [[[urls objectAtIndex:0] path] retain];
_chooserCompleted = YES;
[window makeKeyAndOrderFront:self];
[libraryChooserWindow close];
[NSApp stopModal];
}
}
}
- (IBAction)choose:(id)sender
{
NSInteger row = [libraryChooserTable selectedRow];
if(row >= 0 && row < [libraryChooserKnownPaths count])
{
_selectedLibraryPath = [[libraryChooserKnownPaths objectAtIndex:row] objectForKey:@"path"];
_chooserCompleted = YES;
[window makeKeyAndOrderFront:self];
[libraryChooserWindow close];
[NSApp stopModal];
}
}
- (IBAction)createNew:(id)sender
{
NSLog(@"Not yet implemented: <%@ %@>", [self class], NSStringFromSelector(_cmd));
NSSavePanel *panel = [NSSavePanel savePanel];
[panel setAllowedFileTypes:[NSArray arrayWithObject:[CCLibrary libraryExtension]]];
[panel beginSheetForDirectory:[CCLibrary documentsDirectory]
file:nil
modalForWindow:libraryChooserWindow
modalDelegate:self
didEndSelector:@selector(libraryChooserSavePanelDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
- (void)libraryChooserSavePanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
if(returnCode == NSAlertDefaultReturn)
{
NSArray *urls = [panel URLs];
NSLog(@"urls: %@", urls);
if([urls count] != 1)
{
NSLog(@"[Error] this shouldn't happen");
}
else
{
_createNewLibrary = YES;
_chooserCompleted = YES;
_selectedLibraryPath = [[[urls objectAtIndex:0] path] retain];
[window makeKeyAndOrderFront:self];
[libraryChooserWindow close];
[NSApp stopModal];
}
}
}
#pragma mark IBActions
- (IBAction)addItem:(id)sender
{
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowsMultipleSelection:NO];
[panel setAllowedFileTypes:[NSArray arrayWithObject:@"pdf"]];
[panel beginSheetForDirectory:[CCLibrary homeDirectory]
file:nil
modalForWindow:window
modalDelegate:self
didEndSelector:@selector(addItemOpenPanelDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
- (void)addItemOpenPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
if(returnCode == NSAlertDefaultReturn)
{
NSArray *urls = [panel URLs];
NSLog(@"urls: %@", urls);
if([urls count] != 1)
{
NSLog(@"[Error] this shouldn't happen");
}
else
{
NSString *file = [[urls objectAtIndex:0] path];
NSString *addedPath = [_library addFileToLibrary:file];
if(addedPath)
{
NSLog(@"Added item at path: %@", addedPath);
CCItemNode *item = [CCItemNode itemNode];
[item setName:[[addedPath lastPathComponent] stringByDeletingPathExtension]];
[item setPath:addedPath];
[_libraryNode addChild:item];
}
}
}
}
- (IBAction)addGroup:(id)sender
{
NSArray *selected = [treeController selectedObjects];
CCGroupNode *parent = _libraryNode;
if([selected count] == 1)
{
id object = [selected lastObject];
if([object isKindOfClass:[CCGroupNode class]])
{
parent = (CCGroupNode *)object;
}
else if([object isKindOfClass:[CCItemNode class]])
{
CCNode *node = [(CCItemNode *)object parent];
if([node isKindOfClass:[CCGroupNode class]])
{
parent = (CCGroupNode *)node;
}
}
}
CCGroupNode *group = [CCGroupNode groupNode];
[group setName:@"New Group"];
[parent addChild:group];
[parent setIsExpanded:[NSNumber numberWithBool:YES]];
[self recalculateSortIndexes];
}
- (IBAction)delete:(id)sender
{
NSArray *selected = [treeController selectedObjects];
if([selected count] > 0)
{
NSBeginAlertSheet(@"Do you really want to delete the selected item?",
@"Delete",
nil,
@"Cancel",
window,
self,
@selector(deleteSheetEnded:returnCode:contextInfo:),
NULL,
selected,
@"There is no undo for this operation.");
}
}
- (void)deleteSheetEnded:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
if(returnCode == NSAlertDefaultReturn)
{
if(contextInfo && [(id)contextInfo isKindOfClass:[NSArray class]])
{
NSArray *selected = (NSArray *)contextInfo;
for(id object in selected)
{
if ([object isKindOfClass:[CCNode class]] && !([(CCNode *)object isGroupNode] && [[(CCGroupNode *)object isSpecialGroup] boolValue]))
{
if([(CCNode *)object isDeviceNode])
{
NSLog(@"Deleting from devices is not implemented yet");
}
else
{
[[self managedObjectContext] deleteObject:object];
}
}
}
[self recalculateSortIndexes];
}
}
}
- (IBAction)export:(id)sender
{
NSLog(@"Not yet implemented: <%@ %@>", [self class], NSStringFromSelector(_cmd));
NSLog(@"Should export node: %@", [sourceList clickedNode]);
}
/**
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];
}
}
#pragma mark -
#pragma mark Drag and Drop
+ (NSArray *)acceptedDragTypes
{