forked from iMediaSandboxing/iMedia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IMBAppleMediaParser.m
1166 lines (842 loc) · 44.7 KB
/
IMBAppleMediaParser.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-2012 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-2012 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: Jörg Jacobsen
//----------------------------------------------------------------------------------------------------------------------
#pragma mark HEADERS
#import "IMBAppleMediaParser+iMediaPrivate.h"
#import "NSWorkspace+iMedia.h"
#import "NSFileManager+iMedia.h"
#import "IMBNode.h"
#import "IMBFaceNodeObject.h"
//#import "IMBiPhotoEventObjectViewController.h"
//#import "IMBFaceObjectViewController.h"
#import "IMBImageObjectViewController.h"
#import "NSImage+iMedia.h"
#import "NSString+iMedia.h"
//----------------------------------------------------------------------------------------------------------------------
#pragma mark CONSTANTS
// node object types of interest for skimming
NSString* const kIMBiPhotoNodeObjectTypeEvent = @"events";
NSString* const kIMBiPhotoNodeObjectTypeFace = @"faces";
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
@interface IMBAppleMediaParser ()
- (NSString*) imagePathForImageKey:(NSString*)inImageKey;
- (NSString*) imagePathForFaceIndex:(NSNumber*)inFaceIndex inImageWithKey:(NSString*)inImageKey;
- (BOOL) supportsPhotoStreamFeatureInVersion:(NSString *)inVersion;
- (NSString *) rootNodeIdentifier;
@property (retain) NSDictionary* atomic_plist;
@property (retain,readwrite) NSDate* modificationDate;
@end
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
@implementation IMBAppleMediaParser
@synthesize appPath = _appPath;
@synthesize atomic_plist = _plist;
@synthesize modificationDate = _modificationDate;
@synthesize shouldDisplayLibraryName = _shouldDisplayLibraryName;
//----------------------------------------------------------------------------------------------------------------------
- (void) dealloc
{
IMBRelease(_appPath);
IMBRelease(_plist);
IMBRelease(_modificationDate);
[super dealloc];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Parsing
//----------------------------------------------------------------------------------------------------------------------
// iPhoto and Aperture do not include events nor faces in the album list. To let events or faces also be shown
// in the browser we let events (aka rolls) and faces pose as albums in the album list.
- (void) addSpecialAlbumsToAlbumsInLibrary:(NSMutableDictionary*)inLibraryDict
{
NSArray* oldAlbumList = [inLibraryDict objectForKey:@"List of Albums"];
if (oldAlbumList != nil && [oldAlbumList count]>0)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// To insert new albums like events and faces into the album list we have to re-create it mutable style
NSMutableArray *newAlbumList = [NSMutableArray arrayWithArray:oldAlbumList];
NSUInteger insertionIndex = [self indexOfAllPhotosAlbumInAlbumList:oldAlbumList];
NSDictionary *photosDict = nil;
NSDictionary *eventsDict = nil;
// Starting Aperture 3.3 there is no "Photos" album in ApertureData.xml anymore, so we must reconstruct it ourselves
if (insertionIndex == NSNotFound)
{
// Photos album right after Projects in Aperture (Projects synonym to Events)
// Photos album in iPhoto should be already there
insertionIndex = [self indexOfEventsAlbumInAlbumList:oldAlbumList];
if (insertionIndex != NSNotFound &&
(eventsDict = [oldAlbumList objectAtIndex:insertionIndex]))
{
NSNumber *allPhotosId = [NSNumber numberWithUnsignedInt:ALL_PHOTOS_NODE_ID];
NSString *allPhotosName = NSLocalizedStringWithDefaultValue(@"IMB.ApertureParser.allPhotos", nil, IMBBundle(), @"Photos", @"All photos node shown in Aperture library");
NSDictionary* allPhotos = [[NSDictionary alloc] initWithObjectsAndKeys:
allPhotosId, @"AlbumId",
allPhotosName, @"AlbumName",
@"94", @"Album Type",
[eventsDict objectForKey:@"Parent"], @"Parent", nil];
// events album right before photos album
[newAlbumList insertObject:allPhotos atIndex:insertionIndex];
IMBRelease(allPhotos);
insertionIndex++;
}
}
// Starting Aperture 3.3 there is no "Photos" album in ApertureData.xml anymore, so we must reconstruct it ourselves
if (insertionIndex == NSNotFound)
{
// Photos album right after Projects in Aperture (Projects synonym to Events)
// Photos album in iPhoto should be already there
insertionIndex = [self indexOfEventsAlbumInAlbumList:oldAlbumList];
if (insertionIndex != NSNotFound &&
(eventsDict = [oldAlbumList objectAtIndex:insertionIndex]))
{
NSNumber *allPhotosId = [NSNumber numberWithUnsignedInt:ALL_PHOTOS_NODE_ID];
NSString *allPhotosName = NSLocalizedStringWithDefaultValue(@"IMB.ApertureParser.allPhotos", nil, IMBBundle(), @"Photos", @"All photos node shown in Aperture library");
NSDictionary* allPhotos = [[NSDictionary alloc] initWithObjectsAndKeys:
allPhotosId, @"AlbumId",
allPhotosName, @"AlbumName",
@"94", @"Album Type",
[eventsDict objectForKey:@"Parent"], @"Parent", nil];
// events album right before photos album
[newAlbumList insertObject:allPhotos atIndex:insertionIndex];
IMBRelease(allPhotos);
insertionIndex++;
}
}
if (insertionIndex != NSNotFound &&
(photosDict = [oldAlbumList objectAtIndex:insertionIndex]))
{
// Events
if ([inLibraryDict objectForKey:@"List of Rolls"])
{
NSNumber *eventsId = [NSNumber numberWithUnsignedInt:EVENTS_NODE_ID];
NSString *eventsName = NSLocalizedStringWithDefaultValue(@"IMB.iPhotoParser.events", nil, IMBBundle(), @"Events", @"Events node shown in iPhoto library");
NSDictionary* events = [[NSDictionary alloc] initWithObjectsAndKeys:
eventsId, @"AlbumId",
eventsName, @"AlbumName",
@"Events", @"Album Type",
[photosDict objectForKey:@"Parent"], @"Parent", nil];
// events album right before photos album
[newAlbumList insertObject:events atIndex:insertionIndex];
IMBRelease(events);
insertionIndex++;
}
// Faces album right after photos album
if ([inLibraryDict objectForKey:@"List of Faces"])
{
NSNumber *facesId = [NSNumber numberWithUnsignedInt:FACES_NODE_ID];
NSString *facesName = NSLocalizedStringWithDefaultValue(@"IMB.iPhotoParser.faces", nil, IMBBundle(), @"Faces", @"Faces node shown in iPhoto library");
NSDictionary* faces = [[NSDictionary alloc] initWithObjectsAndKeys:
facesId, @"AlbumId",
facesName, @"AlbumName",
@"Faces", @"Album Type",
[photosDict objectForKey:@"Parent"], @"Parent", nil];
[newAlbumList insertObject:faces atIndex:insertionIndex + 1];
IMBRelease(faces);
}
}
// Photo Stream album right before Flagged album
insertionIndex = [self indexOfFlaggedAlbumInAlbumList:newAlbumList];
if ([self supportsPhotoStreamFeatureInVersion:[inLibraryDict objectForKey:@"Application Version"]] &&
insertionIndex != NSNotFound)
{
NSNumber *albumId = [NSNumber numberWithUnsignedInt:PHOTO_STREAM_NODE_ID];
NSString *albumName = NSLocalizedStringWithDefaultValue(@"IMB.iPhotoParser.photostream", nil, IMBBundle(), @"Photo Stream", @"Photo Stream node shown in iPhoto library");
NSDictionary* album = [[NSDictionary alloc] initWithObjectsAndKeys:
albumId, @"AlbumId",
albumName, @"AlbumName",
@"Photo Stream", @"Album Type",
[photosDict objectForKey:@"Parent"], @"Parent", nil];
[newAlbumList insertObject:album atIndex:insertionIndex];
IMBRelease(album);
}
// Replace the old albums array.
[inLibraryDict setValue:newAlbumList forKey:@"List of Albums"];
[pool drain];
}
}
//----------------------------------------------------------------------------------------------------------------------
// Load the XML file into a plist lazily (on demand). If we notice that an existing cached plist is out-of-date
// we get rid of it and load it anew...
- (NSDictionary*) plist
{
NSDictionary* result = nil;
NSError* error = nil;
NSString* path = [self.mediaSource path];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSDictionary* metadata = [fileManager attributesOfItemAtPath:path error:&error];
[fileManager release];
// NSLog(@"%@ metadata:\n%@", path, metadata);
if (metadata)
{
NSDate* modificationDate = [metadata objectForKey:NSFileModificationDate];
@synchronized(self)
{
if ([self.modificationDate compare:modificationDate] == NSOrderedAscending)
{
self.atomic_plist = nil;
}
if (_plist == nil)
{
// Since we want to add events and faces to the list of albums we will need
// to modify the album data dictionary (see further down below)
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
// WORKAROUND
if (dict == nil || 0 == dict.count) // unable to read. possibly due to unencoded '&'. rdar://7469235
{
NSData *data = [NSData dataWithContentsOfFile:path];
if (data)
{
NSString *eString = nil;
NSError *e = nil;
@try
{
NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithData:data
options:NSXMLDocumentTidyXML error:&e];
dict = [NSPropertyListSerialization
propertyListFromData:[xmlDoc XMLData]
mutabilityOption:0 // Apple doc: The opt parameter is currently unused and should be set to 0.
format:NULL errorDescription:&eString];
[xmlDoc release];
// the assignment to 'dict' in the code above yields
// a mutable dictionary as this code snippet would reveal:
// Class dictClass = [dict classForCoder];
// NSLog(@"Dictionary class: %@", [dictClass description]);
}
@catch(NSException *e)
{
NSLog(@"%s %@", __FUNCTION__, e);
}
// When we start targetting 10.6, we should use propertyListWithData:options:format:error:
}
}
// If there is an AlbumData.xml file, there should be something inside!
if (dict == nil || 0 == dict.count)
{
NSLog (@"The iPhoto or Aperture XML file seems to be empty. This is an unhealthy condition!");
}
// Since this parser confines itself to deal with the "List of Albums" only
// we add an events node to the album list to incorporate events in the browser.
// This is why we need a mutable library dictionary.
if (dict)
{
[self addSpecialAlbumsToAlbumsInLibrary:dict];
}
self.atomic_plist = dict;
self.modificationDate = modificationDate;
}
result = self.atomic_plist;
}
}
return result;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark IMBParserProtocol
//----------------------------------------------------------------------------------------------------------------------
//
- (IMBNode*) unpopulatedTopLevelNode:(NSError**)outError
{
NSImage* icon = [[NSWorkspace imb_threadSafeWorkspace] iconForFile:self.appPath];
[icon setScalesWhenResized:YES];
[icon setSize:NSMakeSize(16.0,16.0)];
IMBNode* node = [[[IMBNode alloc] initWithParser:self topLevel:YES] autorelease];
// NSLog(@"Node %@ is %@accessible", node, node.isAccessible ? @"" : @"NOT ");
node.icon = icon;
node.name = [[self class] libraryName];
node.identifier = [self rootNodeIdentifier];
node.groupType = kIMBGroupTypeLibrary;
node.isLeafNode = NO;
if (node.isTopLevelNode)
{
if (self.shouldDisplayLibraryName)
{
NSString* path = (NSString*)[node.mediaSource path];
NSString* libraryName = [[[path stringByDeletingLastPathComponent] lastPathComponent] stringByDeletingPathExtension];
node.name = [NSString stringWithFormat:@"%@ (%@)",node.name, libraryName];
} else {
node.name = [NSString stringWithFormat:@"%@",node.name];
}
}
// Enable FSEvents based file watching for root nodes...
node.watcherType = kIMBWatcherTypeFSEvent;
NSURL* url = self.mediaSource;
NSString* path = [[url path] stringByDeletingLastPathComponent];
node.watchedPath = path;
// JUST TEMP: remove these 2 lines later...
// NSDictionary* plist = [NSDictionary dictionaryWithContentsOfURL:self.mediaSource];
// node.attributes = plist;
return node;
}
//----------------------------------------------------------------------------------------------------------------------
//
- (void) reloadNode:(IMBNode*)inNode error:(NSError**)outError
{
}
//----------------------------------------------------------------------------------------------------------------------
//
- (NSDictionary*) metadataForObject:(IMBObject*)inObject error:(NSError**)outError
{
if (outError) *outError = nil;
NSMutableDictionary* metadata = [NSMutableDictionary dictionaryWithDictionary:inObject.preliminaryMetadata];
// Do not load (key) image specific metadata for node objects
// because it doesn't represent the nature of the object well enough.
if (![inObject isKindOfClass:[IMBNodeObject class]])
{
[metadata addEntriesFromDictionary:[NSImage imb_metadataFromImageAtURL:inObject.URL checkSpotlightComments:NO]];
}
// JJ TODO: How about keywords? Only for iPhoto or also for Aperture?
return metadata;
}
//----------------------------------------------------------------------------------------------------------------------
// Since we know that we have local files we can use the helper method supplied by the base class...
- (NSData*) bookmarkForObject:(IMBObject*)inObject error:(NSError**)outError
{
return [self bookmarkForLocalFileObject:inObject error:outError];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark IMBSkimmableObjectViewControllerDelegate
- (NSUInteger) childrenCountOfNodeObject:(IMBNodeObject*)inNodeObject userInfo:(NSDictionary*)inUserInfo
{
// return [[inNodeObject.preliminaryMetadata objectForKey:@"PhotoCount"] integerValue];
return [[inNodeObject.preliminaryMetadata objectForKey:@"KeyList"] count]; // More reliable for Aperture! Avoids out-of-bounds exceptions.
}
- (NSString*) imagePathForChildOfNodeObject:(IMBNodeObject*)inNodeObject atIndex:(NSUInteger)inIndex userInfo:(NSDictionary*)inUserInfo
{
NSString* imageKey = [[inNodeObject.preliminaryMetadata objectForKey:@"KeyList"] objectAtIndex:inIndex];
// Faces
if ([[inUserInfo objectForKey:@"nodeObjectType"] isEqualToString:kIMBiPhotoNodeObjectTypeFace])
{
// Get the metadata of the nth image in which this face occurs
NSDictionary* imageFaceMetadata = [[[inNodeObject preliminaryMetadata] objectForKey:@"ImageFaceMetadataList"] objectAtIndex:inIndex];
// What is the number of this face inside of this image?
NSNumber* faceIndex = [imageFaceMetadata objectForKey:@"face index"];
// A clipped image of this face in this image is stored in the filesystem
NSString* imagePath = [self imagePathForFaceIndex:faceIndex inImageWithKey:imageKey];
//NSLog(@"Skimming controller asked delegate for image path and receives: %@", imagePath);
return imagePath;
}
// Events
return [self imagePathForImageKey:imageKey];
}
- (NSString*) imagePathForKeyChildOfNodeObject:(IMBNodeObject*)inNodeObject userInfo:(NSDictionary*)inUserInfo
{
NSString* imageKey = [inNodeObject.preliminaryMetadata objectForKey:@"KeyPhotoKey"];
// Faces
if ([[inUserInfo objectForKey:@"nodeObjectType"] isEqualToString:kIMBiPhotoNodeObjectTypeFace])
{
// Get this face's index inside of this image
NSNumber* faceIndex = [[inNodeObject preliminaryMetadata] objectForKey:@"key image face index"];
// Get the path to this face's occurence
NSString* imagePath = [self imagePathForFaceIndex:faceIndex inImageWithKey:imageKey];
return imagePath;
}
// Events
return [self imagePathForImageKey:imageKey];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark To be subclassed
//----------------------------------------------------------------------------------------------------------------------
// Returns name of library. Must be subclassed.
+ (NSString*) libraryName
{
NSString *errMsg = [NSString stringWithFormat:@"%s: Please use a custom subclass of %@...", (char *)_cmd, [self className]];
NSLog(@"%@", errMsg);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:errMsg userInfo:nil] raise];
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns the identifier of the root node. Must be subclassed.
- (NSString*) rootNodeIdentifier
{
NSString *errMsg = [NSString stringWithFormat:@"%s: Please use a custom subclass of %@...", (char *)_cmd, [self className]];
NSLog(@"%@", errMsg);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:errMsg userInfo:nil] raise];
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// Create an identifier from the provided id and id space. An example is "IMBiPhotoParser://FaceId/17"...
- (NSString*) identifierForId:(NSNumber*) inId inSpace:(NSString*) inIdSpace
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// returns whether this album type should be used. Must be subclassed.
- (BOOL) shouldUseAlbumType:(NSString*)inAlbumType
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inAlbumDict should be used. Must be subclassed.
- (BOOL) shouldUseAlbum:(NSDictionary*)inAlbumDict images:(NSDictionary*)inImages
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns a dictionary that contains the "true" KeyList, KeyPhotoKey and PhotoCount values for the provided node.
// (The values provided by the according dictionary in .plist are mostly wrong because we separate node children by
// media types 'Image' and 'Movie' into different views.) Must be subclassed.
- (NSDictionary*) childrenInfoForNode:(IMBNode*)inNode images:(NSDictionary*)inImages
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns an icon for an album of this type. Must be subclassed.
- (NSImage*) iconForAlbumType:(NSString*)inType highlight:(BOOL)inHighlight
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inAlbumDict is the "Photos" album. Must be subclassed.
- (BOOL) isAllPhotosAlbum:(NSDictionary*)inAlbumDict
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inAlbumDict is the "Events" (aka "Projects") album. Must be subclassed.
- (BOOL) isEventsAlbum:(NSDictionary*)inAlbumDict
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inAlbumDict is the "Flagged" album. Must be subclassed.
- (BOOL) isFlaggedAlbum:(NSDictionary*)inAlbumDict
{
NSLog(@"%s Please use a custom subclass of IMBAppleMediaParser...",__FUNCTION__);
[[NSException exceptionWithName:@"IMBProgrammerError" reason:@"Please use a custom subclass of IMBAppleMediaParser" userInfo:nil] raise];
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether the parser supports Apple's Photo Stream feature
// (which is usually dependent on the data delivered through AlbumData.xml or ApertureData.xml respectively)
- (BOOL) supportsPhotoStreamFeatureInVersion:(NSString *)inVersion
{
return NO;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Image location
- (id)thumbnailForObject:(IMBObject *)inObject error:(NSError **)outError
{
// imageLocation of a skimmable node object might be out of sync with its current skimming index
// (the image location for a skimming index must only be set where the parser is available)
if ([inObject isKindOfClass:NSClassFromString(@"IMBSkimmableObject")])
{
IMBSkimmableObject *skimmableObject = (IMBSkimmableObject *)inObject;
skimmableObject.imageLocation = [skimmableObject imageLocationForCurrentSkimmingIndex];
}
// IKImageBrowser can also deal with NSData type (IKImageBrowserNSDataRepresentationType)
if (inObject.imageLocation)
{
NSURL* url = (NSURL*)inObject.imageLocation;
if ([inObject.imageRepresentationType isEqualToString:IKImageBrowserCGImageRepresentationType])
{
return (id)[self thumbnailFromLocalImageFileForObject:inObject error:outError];
} else {
inObject.imageRepresentationType = IKImageBrowserNSDataRepresentationType;
NSData* data = [NSData dataWithContentsOfURL:url];
return data;
}
}
else
{
return (id)[self thumbnailFromLocalImageFileForObject:inObject error:outError];
}
}
//----------------------------------------------------------------------------------------------------------------------
// The image location represents an image path to the image to be used for display inside of the browser (a preview of
// of the original image). By default we use the path to the image's thumbnail (key: "ThumbPath").
// Subclass for distinct behavior.
- (NSString*) imageLocationForObject:(NSDictionary*)inObjectDict
{
return [inObjectDict objectForKey:@"ThumbPath"];
}
//----------------------------------------------------------------------------------------------------------------------
// Returns the image location for the image represented by inImageKey in the master image list (aka dictionary)
- (NSString*) imagePathForImageKey:(NSString*)inImageKey
{
NSDictionary* images = [[self plist] objectForKey:@"Master Image List"];
NSDictionary* imageDict = [images objectForKey:inImageKey];
NSString* imagePath = [self imageLocationForObject:imageDict];
return imagePath;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns the image location for the clipped face in the image represented by inImageKey in the master image list
// (aka dictionary)
- (NSString*) imagePathForFaceIndex:(NSNumber*)inFaceIndex inImageWithKey:(NSString*)inImageKey
{
NSString* imagePath = [self imagePathForImageKey:inImageKey];
return [NSString stringWithFormat:@"%@_face%@.%@",
[imagePath stringByDeletingPathExtension],
inFaceIndex,
[imagePath pathExtension]];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Subnode creation and node population
//----------------------------------------------------------------------------------------------------------------------
// Returns array of all face dictionaries (sorted by name). These are also enriched by several keys:
// ImageFaceMetadataList: list of meta info of face occurences in images (sorted by date)
// KeyPhotoKey: key of key image ('KeyPhotoKey' is an event-compatible key)
// KeyList: list of all images in which a face occurs (sorted by date)
- (NSArray*) faces:(NSDictionary*)inFaces collectedFromImages:(NSDictionary*)inImages
{
// Need the enriched copy mutable style
NSMutableDictionary* facesDict = [NSMutableDictionary dictionaryWithDictionary:inFaces];
// Collect all occurences faces. We iterate over master images because only there AlbumData.xml
// stores occurences of faces.
NSArray* facesOnImage = nil;
NSDictionary* imageDict = nil;
NSMutableDictionary* faceDict = nil; // Will need to add keys like "KeyList" to dictionary
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
for (NSString* imageDictKey in [inImages keyEnumerator])
{
imageDict = [inImages objectForKey:imageDictKey];
// Get all known faces that appear on this image
facesOnImage = [imageDict objectForKey:@"Faces"];
NSString* imageFaceKey = nil;
NSMutableArray* imageFaceMetadataList = nil;
NSDictionary* imageFaceMetadata = nil;
for (NSDictionary* imageFaceDict in facesOnImage)
{
// Get face dictionary for given face key.
// Face dictionary will be the basis of our subnode to be created.
imageFaceKey = [imageFaceDict objectForKey:@"face key"];
faceDict = [facesDict objectForKey:imageFaceKey];
// It might well be that found face in image is now longer known...
if (faceDict)
{
// Coming here we found a face on an image and this face is known.
// Now add some key/value pairs to face dictionary
// First convert to a mutable dictionary to be able to add the extra pairs
faceDict = [NSMutableDictionary dictionaryWithDictionary:faceDict];
[facesDict setObject:faceDict forKey:imageFaceKey];
// Provide key image key under event-compatible key "KeyPhotoKey" once current image matches.
// NOTE: iPhoto 9.4 changed the value stored under "key image" from image key to image GUID.
NSString* keyImage = [faceDict objectForKey:@"key image"];
NSString* imageGUID = [imageDict objectForKey:@"GUID"];
if ((imageGUID && [imageGUID isEqualToString:keyImage]) || // Should be YES once for >= iPhoto 9.4
[imageDictKey isEqualToString:keyImage]) // Should be YES once for < iPhoto 9.4
{
[faceDict setObject:imageDictKey forKey:@"KeyPhotoKey"];
}
// Add image face meta data to this face (need this later)
// (Create meta data list when first occurence of face in some image is detected)
imageFaceMetadataList = [faceDict objectForKey:@"ImageFaceMetadataList"];
if (!imageFaceMetadataList)
{
imageFaceMetadataList = [NSMutableArray array];
[faceDict setObject:imageFaceMetadataList forKey:@"ImageFaceMetadataList"];
}
NSNumber *faceIndex = [imageFaceDict objectForKey:@"face index"];
NSString *path = [self imagePathForFaceIndex:faceIndex inImageWithKey:imageDictKey];
imageFaceMetadata = [NSDictionary dictionaryWithObjectsAndKeys:
imageDictKey, @"image key",
faceIndex, @"face index",
[imageDict objectForKey:@"DateAsTimerInterval"], @"DateAsTimerInterval",
path, @"path",
nil];
[imageFaceMetadataList addObject:imageFaceMetadata];
} else {
// We found a face in a master image but that face is not associated
// with a known face anymore. Just skip this one.
//NSLog(@"Found unknown face with ID %@ in image %@", faceKey, imageDictKey);
}
}
}
// For each face dictionary sort associated images by date (this is how iPhoto displays them)
NSSortDescriptor* dateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DateAsTimerInterval" ascending:YES];
NSArray* sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
[dateDescriptor release];
NSArray* imageFaceMetadataList = nil;
for (NSString* faceKey in [facesDict keyEnumerator])
{
faceDict = [facesDict objectForKey:faceKey];
// Sort images related to face by date
imageFaceMetadataList = [faceDict objectForKey:@"ImageFaceMetadataList"];
if (imageFaceMetadataList)
{
imageFaceMetadataList = [imageFaceMetadataList sortedArrayUsingDescriptors:sortDescriptors];
} else {
// Obviously a metadata list has yet not been created for this face.
// Given the code further above this really means that this face does not appear
// on any image. This should probably not be but there were crash logs indicating just this.
// Create an empty metadata list to avoid crash.
imageFaceMetadataList = [NSArray array];
}
[faceDict setObject:imageFaceMetadataList forKey:@"ImageFaceMetadataList"]; // JJ/2012-09-21: again?????
// Also store a sorted key list in face dictionary
[faceDict setObject:[imageFaceMetadataList valueForKey:@"image key"] forKey:@"KeyList"];
}
[pool drain];
// Sort faces dictionary by names (this is how iPhoto displays faces)
NSSortDescriptor* nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:nameDescriptor];
[nameDescriptor release];
NSArray* sortedFaces = [[facesDict allValues] sortedArrayUsingDescriptors:sortDescriptors];
return sortedFaces;
}
//----------------------------------------------------------------------------------------------------------------------
// Populate faces node and create corresponding subnodes that each represent a single face
- (void) populateFacesNode:(IMBNode*)inNode
withFaces:(NSDictionary*)inFaces
images:(NSDictionary*)inImages
{
// Pull all information on faces from faces dictionary and face occurences in images
// into a faces array (sorted by name)...
NSArray* sortedFaces = [self faces:inFaces collectedFromImages:inImages];
// Create the subNodes array on demand - even if turns out to be empty after exiting this method,
// because without creating an array we would cause an endless loop...
NSMutableArray* subnodes = [inNode mutableArrayForPopulatingSubnodes];
// Create the objects array on demand - even if turns out to be empty after exiting this method, because
// without creating an array we would cause an endless loop...
NSMutableArray* objects = [NSMutableArray array];
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Setup the loop
NSUInteger index = 0;
NSString* faceKeyPhotoKey = nil;
NSString* path = nil;
NSString* thumbnailPath = nil;
IMBFaceNodeObject* object = nil;
NSString* subNodeType = @"Face";
for (NSDictionary* faceDict in sortedFaces)
{
NSString* subnodeName = [faceDict objectForKey:@"name"];
if ([self shouldUseAlbumType:subNodeType] &&
[self shouldUseAlbum:faceDict images:inImages])
{
// Create subnode for this node...
IMBNode* subnode = [[[IMBNode alloc] initWithParser:self topLevel:NO] autorelease];
subnode.isLeafNode = [self isLeafAlbumType:subNodeType];
subnode.icon = [self iconForAlbumType:subNodeType highlight:NO];
subnode.highlightIcon = [self iconForAlbumType:subNodeType highlight:YES];
subnode.name = subnodeName;
subnode.isIncludedInPopup = NO;
subnode.watchedPath = inNode.watchedPath; // These two lines are important to make file watching work for nested
subnode.watcherType = kIMBWatcherTypeNone; // subfolders. See IMBLibraryController _reloadNodesWithWatchedPath:
// Keep a ref to face dictionary for potential later use
subnode.attributes = [NSDictionary dictionaryWithObjectsAndKeys:
faceDict, @"nodeSource",
[self nodeTypeForNode:subnode], @"nodeType", nil];
// Set the node's identifier. This is needed later to link it to the correct parent node.
// Note that a faces dictionary always has a "key" key...
NSNumber* subnodeId = [faceDict objectForKey:@"key"];
subnode.identifier = [self identifierForId:subnodeId inSpace:FACES_ID_SPACE];
// Add the new subnode to its parent (inRootNode)...
[subnodes addObject:subnode];
// Now create the visual object and link it to subnode just created
object = [[IMBFaceNodeObject alloc] init];
[objects addObject:object];
[object release];
// Adjust keys "KeyPhotoKey", "KeyList", and "PhotoCount" in metadata dictionary
// because movies and images are not jointly displayed in iMedia browser...
NSMutableDictionary* preliminaryMetadata = [NSMutableDictionary dictionaryWithDictionary:faceDict];
[preliminaryMetadata addEntriesFromDictionary:[self childrenInfoForNode:subnode images:inImages]];
object.preliminaryMetadata = preliminaryMetadata; // This metadata from the XML file is available immediately
[object resetCurrentSkimmingIndex]; // Must be done *after* preliminaryMetadata is set
object.metadata = nil; // Build lazily when needed (takes longer)
object.metadataDescription = nil; // Build lazily when needed (takes longer)
// Obtain key photo dictionary (key photo is displayed while not skimming)...
faceKeyPhotoKey = [object.preliminaryMetadata objectForKey:@"KeyPhotoKey"];
NSDictionary* keyPhotoDict = [inImages objectForKey:faceKeyPhotoKey];
path = [keyPhotoDict objectForKey:@"ImagePath"];
object.representedNodeIdentifier = subnode.identifier;
object.location = [NSURL fileURLWithPath:path isDirectory:NO];
object.name = subnode.name;
object.parserIdentifier = [self identifier];
object.index = index++;
thumbnailPath = [self imagePathForFaceIndex:[faceDict objectForKey:@"key image face index"]
inImageWithKey:faceKeyPhotoKey];
object.imageLocation = (id)[NSURL fileURLWithPath:thumbnailPath isDirectory:NO];
object.imageRepresentationType = [self requestedImageRepresentationType];
object.imageRepresentation = nil;
}
}
[pool drain];
inNode.objects = objects;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Convenience
//----------------------------------------------------------------------------------------------------------------------
// Returns events id space (EVENTS_ID_SPACE) for album types "Face" and "Faces".
// Returns faces id space (FACES_ID_SPACE) for album types "Face" and "Faces".
// Otherwise returns the albums id space (ALBUMS_ID_SPACE).
- (NSString*) idSpaceForAlbumType:(NSString*) inAlbumType
{
if ([inAlbumType isEqualToString:@"Event"] || [inAlbumType isEqualToString:@"Events"])
{
return EVENTS_ID_SPACE;
} else if ([inAlbumType isEqualToString:@"Face"] || [inAlbumType isEqualToString:@"Faces"])
{
return FACES_ID_SPACE;
} else if ([inAlbumType isEqualToString:@"Photo Stream"])
{
return PHOTO_STREAM_ID_SPACE;