forked from karelia/iMedia
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIMBLibraryController.m
1340 lines (982 loc) · 40.4 KB
/
IMBLibraryController.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
/*
iMedia Browser Framework <http://karelia.com/imedia/>
Copyright (c) 2005-2011 by Karelia Software et al.
iMedia Browser is based on code originally developed by Jason Terhorst,
further developed for Sandvox by Greg Hulands, Dan Wood, and Terrence Talbot.
The new architecture for version 2.0 was developed by Peter Baumgartner.
Contributions have also been made by Matt Gough, Martin Wennerberg and others
as indicated in source files.
The iMedia Browser Framework is licensed under the following terms:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in all or substantial portions of the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following
conditions:
Redistributions of source code must retain the original terms stated here,
including this list of conditions, the disclaimer noted below, and the
following copyright notice: Copyright (c) 2005-2011 by Karelia Software et al.
Redistributions in binary form must include, in an end-user-visible manner,
e.g., About window, Acknowledgments window, or similar, either a) the original
terms stated here, including this list of conditions, the disclaimer noted
below, and the aforementioned copyright notice, or b) the aforementioned
copyright notice and a link to karelia.com/imedia.
Neither the name of Karelia Software, nor Sandvox, nor the names of
contributors to iMedia Browser may be used to endorse or promote products
derived from the Software without prior and express written permission from
Karelia Software or individual contributors, as appropriate.
Disclaimer: THE SOFTWARE IS PROVIDED BY THE COPYRIGHT OWNER AND CONTRIBUTORS
"AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH, THE
SOFTWARE OR THE USE OF, OR OTHER DEALINGS IN, THE SOFTWARE.
*/
// Author: Peter Baumgartner
//----------------------------------------------------------------------------------------------------------------------
#pragma mark HEADERS
#import "IMBLibraryController.h"
#import "IMBParserController.h"
#import "IMBOperationQueue.h"
#import "IMBParser.h"
#import "IMBNode.h"
#import "IMBCommon.h"
#import "IMBConfig.h"
#import "IMBKQueue.h"
#import "IMBFSEventsWatcher.h"
#import "IMBImageFolderParser.h"
#import "IMBAudioFolderParser.h"
#import "IMBMovieFolderParser.h"
#import "NSWorkspace+iMedia.h"
//----------------------------------------------------------------------------------------------------------------------
#pragma mark CLASSES
@class IMBParser;
@class IMBNode;
//----------------------------------------------------------------------------------------------------------------------
#pragma mark CONSTANTS
NSString* kIMBNodesWillReloadNotification = @"IMBNodesWillReloadNotification";
NSString* kIMBNodesWillChangeNotification = @"IMBNodesWillChangeNotification";
NSString* kIMBNodesDidChangeNotification = @"IMBNodesDidChangeNotification";
//----------------------------------------------------------------------------------------------------------------------
#pragma mark GLOBALS
static NSMutableDictionary* sLibraryControllers = nil;
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
// Private subclasses of NSOperation. The controller uses these internally to get background work done, but
// we do not want to expose these operations to developers who use iMedia.framework in their applications...
@interface IMBLibraryOperation : NSOperation
{
@private
IMBLibraryController* _libraryController;
IMBParser* _parser;
IMBOptions _options;
IMBNode* _oldNode;
IMBNode* _newNode;
NSString* _parentNodeIdentifier;
}
@property (retain) IMBLibraryController* libraryController;
@property (retain) IMBParser* parser;
@property (assign) IMBOptions options;
@property (retain) IMBNode* oldNode;
@property (copy) IMBNode* newNode; // Copied so that background operation can modify the node
@property (copy) NSString* parentNodeIdentifier;
@end
@interface IMBCreateNodeOperation : IMBLibraryOperation
@end
@interface IMBPopulateNodeOperation : IMBLibraryOperation
@end
//----------------------------------------------------------------------------------------------------------------------
// Private controller methods...
@interface IMBLibraryController ()
- (void) _didCreateNode:(IMBNode*)inNode;
- (void) _didPopulateNode:(IMBNode*)inNode;
- (void) _replaceNode:(IMBNode*)inOldNode withNode:(IMBNode*)inNewNode parentNodeIdentifier:(NSString*)inParentNodeIdentifier;
- (void) _presentError:(NSError*)inError;
- (void) _coalescedUKKQueueCallback;
- (void) _coalescedFSEventsCallback;
- (void) _reloadNodesWithWatchedPath:(NSString*)inPath;
- (void) _reloadNodesWithWatchedPath:(NSString*)inPath nodes:(NSArray*)inNodes;
- (void) _unmountNodes:(NSArray*)inNodes onVolume:(NSString*)inVolume;
@end
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
// Pass the new nodes back to the main thread where the IMBLibraryController assumes ownership
// of them and discards the old nodes. The dictionary contains the following key/value pairs:
//
// IMBNode* newNode
// IMBNode* oldNode (optional)
// NSError* error (optional)
@implementation IMBLibraryOperation
@synthesize libraryController = _libraryController;
@synthesize parser = _parser;
@synthesize options = _options;
@synthesize oldNode = _oldNode;
@synthesize newNode = _newNode;
@synthesize parentNodeIdentifier = _parentNodeIdentifier;
// General purpose method to send back results to controller in the main thread...
- (void) performSelectorOnMainThread:(SEL)inSelector withObject:(id)inObject
{
[self.libraryController
performSelectorOnMainThread:inSelector
withObject:inObject
waitUntilDone:NO
modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
// Specialized method that bundles old and new node, as well as potential error...
- (void) doReplacement
{
if ([NSThread isMainThread])
{
[self.libraryController
_replaceNode:self.oldNode
withNode:self.newNode
parentNodeIdentifier:self.parentNodeIdentifier];
}
else
{
[self
performSelectorOnMainThread:_cmd
withObject:nil
waitUntilDone:NO
modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
}
// Cleanup...
- (void) dealloc
{
IMBRelease(_libraryController);
IMBRelease(_parser);
IMBRelease(_oldNode);
IMBRelease(_newNode);
IMBRelease(_parentNodeIdentifier);
[super dealloc];
}
@end
//----------------------------------------------------------------------------------------------------------------------
// Create a new node here in this background operation. When done, pass back the result to the libraryController
// in the main thread...
@implementation IMBCreateNodeOperation
- (void) main
{
NSError* error = nil;
// This was using _parser ivar directly before with indication given as to it being necessary, so I'm switching to the proper accessor to see if it fixes my crash - Mike Abdullah
IMBParser *parser = [self parser];
[parser willUseParser];
IMBNode* newNode = [parser nodeWithOldNode:self.oldNode options:self.options error:&error];
self.newNode = newNode;
if (error == nil)
{
[self performSelectorOnMainThread:@selector(_didCreateNode:) withObject:newNode];
[self doReplacement];
}
else
{
[self performSelectorOnMainThread:@selector(_presentError:) withObject:error];
}
}
@end
//----------------------------------------------------------------------------------------------------------------------
// Tell the parser to popuplate the node in this background operation. When done, pass back the result to
// the libraryController in the main thread. If nodes are collapsed or deselected in the user interface, a
// appropriate notification is sent out. Listen to these notifications and cancel any queued operations
// that are now obsolete...
@implementation IMBPopulateNodeOperation
- (void) main
{
if (self.isCancelled == NO)
{
NSError* error = nil;
// This was using _paser ivar directly before with indication given as to it being necessary, so I'm switching to the proper accessor to see if it fixes my crash - Mike Abdullah
IMBParser *parser = [self parser];
[parser willUseParser];
[parser populateNode:self.newNode options:self.options error:&error];
if (error == nil)
{
[self performSelectorOnMainThread:@selector(_didPopulateNode:) withObject:self.newNode];
[self doReplacement];
}
else
{
[self performSelectorOnMainThread:@selector(_presentError:) withObject:error];
}
}
}
// When a populating is cancelled we need to revert the node to its original state, so that it can be populated
// again at a later time. This requires resetting the loading state and the badgeType...
- (void) cancel
{
[super cancel];
self.oldNode.loading = NO;
self.oldNode.badgeTypeNormal = kIMBBadgeTypeNone;
}
@end
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
@implementation IMBLibraryController
@synthesize mediaType = _mediaType;
@synthesize rootNodes = _rootNodes;
@synthesize options = _options;
@synthesize delegate = _delegate;
@synthesize watcherUKKQueue = _watcherUKKQueue;
@synthesize watcherFSEvents = _watcherFSEvents;
@synthesize isReplacingNode = _isReplacingNode;
//----------------------------------------------------------------------------------------------------------------------
// Create a singleton instance per media type and store it in a global dictionary so that we can access it by type...
+ (IMBLibraryController*) sharedLibraryControllerWithMediaType:(NSString*)inMediaType
{
IMBLibraryController* controller = nil;
@synchronized(self)
{
if (sLibraryControllers == nil)
{
sLibraryControllers = [[NSMutableDictionary alloc] init];
}
controller = [sLibraryControllers objectForKey:inMediaType];
if (controller == nil)
{
controller = [[IMBLibraryController alloc] initWithMediaType:inMediaType];
[sLibraryControllers setObject:controller forKey:inMediaType];
[controller release];
}
}
return controller;
}
//----------------------------------------------------------------------------------------------------------------------
- (id) initWithMediaType:(NSString*)inMediaType
{
if (self = [super init])
{
self.mediaType = inMediaType;
self.rootNodes = [NSMutableArray array];
self.options = kIMBOptionNone;
// Initialize file system watching...
self.watcherUKKQueue = [[[IMBKQueue alloc] init] autorelease];
self.watcherUKKQueue.delegate = self;
self.watcherFSEvents = [[[IMBFSEventsWatcher alloc] init] autorelease];
self.watcherFSEvents.delegate = self;
_isReplacingNode = NO;
_watcherLock = [[NSRecursiveLock alloc] init];
_watcherUKKQueuePaths = [[NSMutableArray alloc] init];
_watcherFSEventsPaths = [[NSMutableArray alloc] init];
// When volume are unmounted we would like to be notified so that we can disable file watching for
// those paths...
[[[NSWorkspace imb_threadSafeWorkspace] notificationCenter]
addObserver:self
selector:@selector(_willUnmountVolume:)
name:NSWorkspaceWillUnmountNotification
object:nil];
[[[NSWorkspace imb_threadSafeWorkspace] notificationCenter]
addObserver:self
selector:@selector(_didMountVolume:)
name:NSWorkspaceDidMountNotification
object:nil];
}
return self;
}
- (void) dealloc
{
[[[NSWorkspace imb_threadSafeWorkspace] notificationCenter] removeObserver:self];
IMBRelease(_mediaType);
IMBRelease(_rootNodes);
IMBRelease(_watcherUKKQueue);
IMBRelease(_watcherFSEvents);
IMBRelease(_watcherLock);
IMBRelease(_watcherUKKQueuePaths);
IMBRelease(_watcherFSEventsPaths);
[super dealloc];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
#pragma mark Creating Nodes
// This method triggers a full reload of all nodes. First remove all existing nodes. Then iterate over all
// loaded parsers (for our media type) and tell them to load nodes in a background operation...
- (void) reload
{
[[NSNotificationCenter defaultCenter] postNotificationName:kIMBNodesWillReloadNotification object:self];
NSArray* parsers = [[IMBParserController sharedParserController] parsersForMediaType:self.mediaType];
[self willChangeValueForKey:@"rootNodes"];
[self.rootNodes removeAllObjects];
[self didChangeValueForKey:@"rootNodes"];
for (IMBParser* parser in parsers)
{
BOOL shouldCreateNode = YES;
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:shouldCreateNodeWithParser:)])
{
shouldCreateNode = [_delegate libraryController:self shouldCreateNodeWithParser:parser];
}
if (shouldCreateNode)
{
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:willCreateNodeWithParser:)])
{
[_delegate libraryController:self willCreateNodeWithParser:parser];
}
IMBCreateNodeOperation* operation = [[IMBCreateNodeOperation alloc] init];
operation.libraryController = self;
operation.parser = parser;
operation.options = self.options;
operation.oldNode = nil;
operation.parentNodeIdentifier = nil;
[[IMBOperationQueue sharedQueue] addOperation:operation];
[operation release];
}
}
}
//----------------------------------------------------------------------------------------------------------------------
// If the delegate allows reloading, then create a background operation that causes the parser to create a new node.
// Please note that this method causes the node (and all its subnodes) to be replaced at a later time in the main
// thread (once the background operation has concluded). Afterwards we have a different node instance! That way
// we can handle various different cases, like subnodes appearing/dissappearing, or objects appearing/disappearing.
- (void) reloadNode:(IMBNode*)inNode
{
[self reloadNode:inNode parser:inNode.parser];
}
- (void) reloadNode:(IMBNode*)inNode parser:(IMBParser*)inParser
{
BOOL shouldCreateNode = _isReplacingNode==NO;
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:shouldCreateNodeWithParser:)])
{
shouldCreateNode = [_delegate libraryController:self shouldCreateNodeWithParser:inNode.parser];
}
if (shouldCreateNode)
{
[[NSNotificationCenter defaultCenter] postNotificationName:kIMBNodesWillReloadNotification object:self];
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:willCreateNodeWithParser:)])
{
[_delegate libraryController:self willCreateNodeWithParser:inNode.parser];
}
inNode.loading = YES;
inNode.badgeTypeNormal = kIMBBadgeTypeLoading;
IMBCreateNodeOperation* operation = [[IMBCreateNodeOperation alloc] init];
operation.libraryController = self;
operation.parser = inParser;
operation.options = self.options;
operation.oldNode = inNode;
operation.parentNodeIdentifier = inNode.parentNode.identifier;
[[IMBOperationQueue sharedQueue] addOperation:operation];
[operation release];
}
}
//----------------------------------------------------------------------------------------------------------------------
// Check if the desired group node is already present. If yes return it, otherwise create and add it...
- (IMBNode*) _groupNodeForNewNode:(IMBNode*)inNewNode
{
NSUInteger groupType = inNewNode.groupType;
if (groupType == kIMBGroupTypeNone) return nil;
for (IMBNode* node in _rootNodes)
{
if (node.groupType == groupType)
{
return node;
}
}
IMBNode* groupNode = [[[IMBNode alloc] init] autorelease];
groupNode.group = YES;
groupNode.leaf = NO;
groupNode.parser = nil;
groupNode.subNodes = [NSMutableArray array];
groupNode.objects = [NSMutableArray array];
if (groupType == kIMBGroupTypeLibrary)
{
groupNode.groupType = kIMBGroupTypeLibrary;
groupNode.identifier = @"group://LIBRARIES";
groupNode.name = NSLocalizedStringWithDefaultValue(
@"IMBLibraryController.groupnode.libraries",
nil,IMBBundle(),
@"LIBRARIES",
@"group node display name");
}
else if (groupType == kIMBGroupTypeFolder)
{
groupNode.groupType = kIMBGroupTypeFolder;
groupNode.identifier = @"group://FOLDERS";
groupNode.name = NSLocalizedStringWithDefaultValue(
@"IMBLibraryController.groupnode.folders",
nil,IMBBundle(),
@"FOLDERS",
@"group node display name");
}
else if (groupType == kIMBGroupTypeSearches)
{
groupNode.groupType = kIMBGroupTypeSearches;
groupNode.identifier = @"group://SEARCHES";
groupNode.name = NSLocalizedStringWithDefaultValue(
@"IMBLibraryController.groupnode.searches",
nil,IMBBundle(),
@"SEARCHES",
@"group node display name");
}
else if (groupType == kIMBGroupTypeInternet)
{
groupNode.groupType = kIMBGroupTypeInternet;
groupNode.identifier = @"group://INTERNET";
groupNode.name = NSLocalizedStringWithDefaultValue(
@"IMBLibraryController.groupnode.internet",
nil,IMBBundle(),
@"INTERNET",
@"group node display name");
}
groupNode.parser = inNewNode.parser; // Important to make lookup in -[IMBNode indexPath] work correctly!
NSMutableArray* rootNodes = [NSMutableArray arrayWithArray:_rootNodes];
[rootNodes addObject:groupNode];
[rootNodes sortUsingSelector:@selector(compare:)];
self.rootNodes = rootNodes;
return groupNode;
}
//----------------------------------------------------------------------------------------------------------------------
// This method is called on the main thread as a result of any IMBLibraryOperation. We are given both the old
// and the new node. Replace the old with the new node. The node we are given here can be a root node or a node
// somewhere deep inside the tree. So we need to find the correct place where to put the new node. Note that the
// new node is registered with a file watcher (if desired) and the old node is unregistered...
- (void) _replaceNode:(NSDictionary*)inOldAndNewNode
{
IMBNode* oldNode = [inOldAndNewNode objectForKey:@"oldNode"];
IMBNode* newNode = [inOldAndNewNode objectForKey:@"newNode"];
NSString* parentNodeIdentifier = [inOldAndNewNode objectForKey:@"parentNodeIdentifier"];
[self _replaceNode:oldNode withNode:newNode parentNodeIdentifier:parentNodeIdentifier];
}
- (void) _replaceNode:(IMBNode*)inOldNode withNode:(IMBNode*)inNewNode parentNodeIdentifier:(NSString*)inParentNodeIdentifier
{
if (inOldNode == nil && inNewNode == nil) return;
// If we were given both old and new nodes, then the parentNode and identifiers must be the same.
// If not log an error and throw an exception because this is a programmer error...
// if (oldNode != nil && newNode != nil && oldNode.parentNode != newNode.parentNode && newNode.parentNode != nil)
// {
// NSLog(@"%s Error: parent of oldNode and newNode must be the same...",__FUNCTION__);
// [[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Error: parent of oldNode and newNode must be the same" userInfo:nil] raise];
// }
if (inOldNode != nil && inNewNode != nil && ! [inOldNode.identifier isEqual:inNewNode.identifier])
{
NSLog(@"%s Error: parent of oldNode and newNode must have same identifiers...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Error: parent of oldNode and newNode must have same identifiers" userInfo:nil] raise];
}
// Workaround for special behavior of IMBImageCaptureParser, which replaces root nodes several times
// as devices get hotplugged. We should probably remove this once IMBImageCaptureParser gets rewritten...
if (inOldNode == nil && inNewNode != nil)
{
IMBNode* node = [self nodeWithIdentifier:inNewNode.identifier];
if (node) inOldNode = node;
}
// Tell IMBUserInterfaceController that we are going to modify the data model...
_isReplacingNode = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:kIMBNodesWillChangeNotification object:self];
@try
{
// Find out where we are supposed to replace the old with the new node. We have three different cases:
// 1) Both old and new node are supplied, so we need to replace.
// 2) Only old node is supplied, so it needs to be removed.
// 3) Only new node is supplied so it needs to be inserted.
// We also have to distinguish between root of the tree and somewhere in the middle of the tree. Things
// are further complicated by the "group nodes" which are created dynamically in this method...
IMBNode* parentNode = [self nodeWithIdentifier:inParentNodeIdentifier];
BOOL shouldSortNodes = parentNode.isGroup;
if (parentNode == nil)
{
if ([IMBConfig showsGroupNodes])
{
if (inOldNode) parentNode = [self _groupNodeForNewNode:inOldNode];
else if (inNewNode) parentNode = [self _groupNodeForNewNode:inNewNode];
}
shouldSortNodes = YES;
}
NSMutableArray* nodes = parentNode!=nil ?
[NSMutableArray arrayWithArray:parentNode.subNodes] :
[NSMutableArray arrayWithArray:self.rootNodes];
// Remove the old node from the correct place (but remember its index). Also unregister from file watching...
NSUInteger index = NSNotFound;
NSString* watchedPath = nil;
if (inOldNode)
{
if (watchedPath = inOldNode.watchedPath)
{
if (inOldNode.watcherType == kIMBWatcherTypeKQueue)
[self.watcherUKKQueue removePath:watchedPath];
else if (inOldNode.watcherType == kIMBWatcherTypeFSEvent)
[self.watcherFSEvents removePath:watchedPath];
}
index = [nodes indexOfObjectIdenticalTo:inOldNode];
[nodes removeObjectIdenticalTo:inOldNode];
}
// Insert the new node at the same index. Optionally register the node for file watching...
if (inNewNode)
{
if (index == NSNotFound) index = nodes.count;
[nodes insertObject:inNewNode atIndex:index];
if (watchedPath = inNewNode.watchedPath)
{
if (inNewNode.watcherType == kIMBWatcherTypeKQueue)
[self.watcherUKKQueue addPath:watchedPath];
else if (inNewNode.watcherType == kIMBWatcherTypeFSEvent)
[self.watcherFSEvents addPath:watchedPath];
}
}
// Sort the nodes so that they always appear in the same (stable) order...
if (shouldSortNodes)
{
[nodes sortUsingSelector:@selector(compare:)];
}
// Do an "atomic" replace of the changed nodes array, thus only causing a single KVO notification.
// Please note the strange line setSubNodes:nil, which is a workaround for an nasty crashing bug deep
// inside NSTreeController, where we get a zombie NSTreeControllerTreeNode is some cases. Apparently
// the NSTreeController is very particular about us replacing the whole array in one go (maybe that
// isn't entirely KVO compliant), and it gets confused with its NSTreeControllerTreeNode objects.
// The extra line (setting the array to nil) seems to clear out all NSTreeControllerTreeNodes and
// then they get rebuilt with the next line. Until we rework our own stuff, we'll stick with this
// workaround...
if (parentNode)
{
[parentNode setSubNodes:nil]; // Important workaround. Do not remove!
[parentNode setSubNodes:nodes];
}
else
{
[self setRootNodes:nodes];
}
// Hide empty group nodes that do not have any subnodes We are not using fast enumeration here because
// we may need to mutate the array. Iteration backwards avoids index adjustment problems as we
// remove nodes...
NSMutableArray* rootNodes = [NSMutableArray arrayWithArray:self.rootNodes];
NSUInteger n = [rootNodes count];
for (NSInteger i=n-1; i>=0; i--)
{
IMBNode* node = [rootNodes objectAtIndex:i];
if (node.isGroup && node.subNodes.count==0)
{
[rootNodes removeObjectIdenticalTo:node];
}
}
NSUInteger m = [rootNodes count];
if (n != m)
{
[self setRootNodes:rootNodes];
}
// Since setSubNodes: is a copy setter we need to get a pointer to the new instance before turning
// off the loading state...
IMBNode* node = [self nodeWithIdentifier:inNewNode.identifier];
node.loading = NO;
node.badgeTypeNormal = kIMBBadgeTypeNone;
}
// We are now done...
@finally
{
_isReplacingNode = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:kIMBNodesDidChangeNotification object:self];
}
}
//----------------------------------------------------------------------------------------------------------------------
// This method is called on the main thread as a result of IMBCreateNodesOperation...
- (void) _didCreateNode:(IMBNode*)inNode
{
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:didCreateNode:withParser:)])
{
[_delegate libraryController:self didCreateNode:inNode withParser:inNode.parser];
}
inNode.loading = NO;
inNode.badgeTypeNormal = kIMBBadgeTypeNone;
}
//----------------------------------------------------------------------------------------------------------------------
// This method is called on the main thread incase an error has occurred in an IMBLibraryOperation...
- (void) _presentError:(NSError*)inError
{
[NSApp presentError:inError];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
#pragma mark Populating Nodes
// If a node doesn't have any subnodes yet, we need to create the subnodes lazily when this node is expanded.
// Also ask the delegate whether we are allowed to do so. Create an operation and put it on the queue to
// execute this job in the background.
// Please note the flag _isReplacingNode: It guards us from an unwanted recursion, as are being replaced in
// _replaceNode:, the delegate method outlineViewItemWillExpand: is automatically called - i.e. without the
// user actually clicking on a diclosure triangle. This seems to be some internal NSOutlineView behavior.
// Obviously we need to suppress populating in this case or we'll cause an endless loop...
- (void) populateNode:(IMBNode*)inNode
{
BOOL shouldPopulateNode =
// inNode.isPopulated==NO &&
(inNode.subNodes==nil || inNode.objects==nil) &&
inNode.isLoading==NO &&
_isReplacingNode==NO;
if (shouldPopulateNode)
{
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:willPopulateNode:)])
{
[_delegate libraryController:self willPopulateNode:inNode];
}
inNode.loading = YES;
inNode.badgeTypeNormal = kIMBBadgeTypeLoading;
IMBPopulateNodeOperation* operation = [[IMBPopulateNodeOperation alloc] init];
operation.libraryController = self;
operation.parser = inNode.parser;
operation.options = self.options;
operation.oldNode = inNode;
operation.newNode = inNode; // This will automatically create a copy!
operation.parentNodeIdentifier = inNode.parentNode.identifier;
[[IMBOperationQueue sharedQueue] addOperation:operation];
[operation release];
}
}
// Check all pending operation if there is a populate operation concerning the node in question. If yes, then
// cancel that one. Please note that this will probably have no effect if the operation is already executing -
// i.e. unless the parser class is cancel-aware and exits its inner loop early...
- (void) stopPopulatingNodeWithIdentifier:(NSString*)inNodeIdentifier
{
NSArray* operations = [[IMBOperationQueue sharedQueue] operations];
for (NSOperation* operation in operations)
{
if ([operation isKindOfClass:[IMBPopulateNodeOperation class]])
{
IMBPopulateNodeOperation* populateOperation = (IMBPopulateNodeOperation*)operation;
if ([populateOperation.oldNode.identifier isEqualToString:inNodeIdentifier])
{
[populateOperation cancel];
}
}
}
}
// Called back in the main thread as a result of IMBExpandNodeOperation...
- (void) _didPopulateNode:(IMBNode*)inNode
{
if (_delegate != nil && [_delegate respondsToSelector:@selector(libraryController:didPopulateNode:)])
{
[_delegate libraryController:self didPopulateNode:inNode];
}
inNode.loading = NO;
inNode.badgeTypeNormal = kIMBBadgeTypeNone;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark
#pragma mark File Watching
// A file watcher has fired for one of the paths we have registered. Since file watchers (especially UKKQueue can
// fire multiple times for a single change) we need to coalesce the calls. Please note that the parameter inPath
// is a different NSString instance every single time, so we cannot pass it as a param to the coalesced message
// (canceling wouldn't work). Instead we'll put it in an array, which is iterated in _coalescedFileWatcherCallback...
- (void) watcher:(id<IMBFileWatcher>)inWatcher receivedNotification:(NSString*)inNotificationName forPath:(NSString*)inPath
{
// NSLog(@"%s path=%@",__FUNCTION__,inPath);
if ([inNotificationName isEqualToString:IMBFileWatcherWriteNotification])
{
if (inWatcher == _watcherUKKQueue)
{
[_watcherLock lock];
if ([_watcherUKKQueuePaths indexOfObject:inPath] == NSNotFound) [_watcherUKKQueuePaths addObject:inPath];
[_watcherLock unlock];
SEL method = @selector(_coalescedUKKQueueCallback);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:method object:nil];
[self performSelector:method withObject:nil afterDelay:1.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
else if (inWatcher == _watcherFSEvents)
{
[_watcherLock lock];
if ([_watcherFSEventsPaths indexOfObject:inPath] == NSNotFound) [_watcherFSEventsPaths addObject:inPath];
[_watcherLock unlock];
SEL method = @selector(_coalescedFSEventsCallback);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:method object:nil];
[self performSelector:method withObject:nil afterDelay:1.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
}
}
// Given an array of paths, filter out all paths that are subpaths of others in the array.
// In other words only return the unique roots of a bunch of file system paths...
+ (NSArray*) _rootPathsForPaths:(NSArray*)inAllPaths
{
NSMutableArray* rootPaths = [NSMutableArray array];
for (NSString* newPath in inAllPaths)
{
// First eliminate any existing rootPaths that are subpaths of a new path...
NSUInteger n = [rootPaths count];
for (NSUInteger i=n-1; i>=0; i--)
{
NSString* rootPath = [rootPaths objectAtIndex:i];
if ([rootPath hasPrefix:newPath])
{
[rootPaths removeObjectAtIndex:i];
}
}
// Add a new path if it is not a subpath (or equal) of another existing path...
BOOL shouldAdd = YES;
for (NSString* rootPath in rootPaths)
{
if ([newPath hasPrefix:rootPath])
{
shouldAdd = NO;
break;
}
}
if (shouldAdd) [rootPaths addObject:newPath];
}
return (NSArray*) rootPaths;
}
// Pass the message on to the main thread...
- (void) _coalescedUKKQueueCallback
{
BOOL isMainThread = [NSThread isMainThread];
[_watcherLock lock];
for (NSString* path in _watcherUKKQueuePaths)
{
if (isMainThread) [self _reloadNodesWithWatchedPath:path];
else [self performSelectorOnMainThread:@selector(_reloadNodesWithWatchedPath:) withObject:path waitUntilDone:NO];
}
[_watcherUKKQueuePaths removeAllObjects];
[_watcherLock unlock];
}
- (void) _coalescedFSEventsCallback
{
BOOL isMainThread = [NSThread isMainThread];
[_watcherLock lock];
for (NSString* path in _watcherFSEventsPaths)
{
if (isMainThread) [self _reloadNodesWithWatchedPath:path];
else [self performSelectorOnMainThread:@selector(_reloadNodesWithWatchedPath:) withObject:path waitUntilDone:NO];
}
[_watcherFSEventsPaths removeAllObjects];