forked from karelia/iMedia
-
Notifications
You must be signed in to change notification settings - Fork 2
/
IMBAppleMediaParser.m
845 lines (615 loc) · 31 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
/*
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: Jörg Jacobsen
//----------------------------------------------------------------------------------------------------------------------
#pragma mark HEADERS
#import "IMBAppleMediaParser.h"
#import "NSFileManager+iMedia.h"
#import "IMBNode.h"
#import "IMBNodeObject.h"
#import "IMBiPhotoEventObjectViewController.h"
#import "IMBFaceObjectViewController.h"
#import "IMBImageViewController.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;
@end
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
@implementation IMBAppleMediaParser
@synthesize plist = _plist;
@synthesize modificationDate = _modificationDate;
//----------------------------------------------------------------------------------------------------------------------
#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];
NSNumber* photosDictIndex = nil;
NSDictionary *photosDict = [self allPhotosAlbumInAlbumList:oldAlbumList atIndex:&photosDictIndex];
if (photosDict && photosDictIndex)
{
// To insert events and faces into the album list we have to re-create it mutable style
NSMutableArray *newAlbumList = [NSMutableArray arrayWithArray:oldAlbumList];
// events album right before photos album
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];
[newAlbumList insertObject:events atIndex:[photosDictIndex unsignedIntegerValue]];
IMBRelease(events);
photosDictIndex = [NSNumber numberWithUnsignedInteger:[photosDictIndex unsignedIntegerValue] + 1];
}
// 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:[photosDictIndex unsignedIntegerValue] + 1];
IMBRelease(faces);
}
// 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 = (NSString*)self.mediaSource;
if ([[NSFileManager imb_threadSafeManager] fileExistsAtPath:path])
{
NSDictionary* metadata = [[NSFileManager imb_threadSafeManager] attributesOfItemAtPath:path error:&error];
NSDate* modificationDate = [metadata objectForKey:NSFileModificationDate];
@synchronized(self)
{
if ([self.modificationDate compare:modificationDate] == NSOrderedAscending)
{
self.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.plist = dict;
self.modificationDate = modificationDate;
}
result = [[_plist retain] autorelease];
}
}
return result;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Custom view controller support
- (NSViewController*) customObjectViewControllerForNode:(IMBNode*)inNode
{
// Use custom view for events
if ([self isEventsNode:inNode])
{
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
kIMBiPhotoNodeObjectTypeEvent, @"nodeObjectType", nil];
NSViewController* viewController = [[[IMBiPhotoEventObjectViewController alloc] initWithDelegate:self userInfo:userInfo] autorelease];
[viewController view];
return viewController;
}
if ([self isFacesNode:inNode])
{
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
kIMBiPhotoNodeObjectTypeFace, @"nodeObjectType", nil];
NSViewController* viewController = [[[IMBFaceObjectViewController alloc] initWithDelegate:self userInfo:userInfo] autorelease];
[viewController view];
return viewController;
}
return [super customObjectViewControllerForNode:inNode];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark IMBSkimmableObjectViewControllerDelegate
- (NSUInteger) childrenCountOfNodeObject:(IMBNodeObject*)inNodeObject userInfo:(NSDictionary*)inUserInfo
{
return [[inNodeObject.preliminaryMetadata objectForKey:@"PhotoCount"] integerValue];
}
- (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 this face's data describing its occurence in the inIndex'th image
NSDictionary* imageFaceMetadata = [[[inNodeObject preliminaryMetadata] objectForKey:@"ImageFaceMetadataList"] objectAtIndex:inIndex];
// Get this face's index inside of this image
NSNumber* faceIndex = [imageFaceMetadata objectForKey:@"face index"];
// Finally, get the path to this face's occurence
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
//----------------------------------------------------------------------------------------------------------------------
// 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
{
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;
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Image location
//----------------------------------------------------------------------------------------------------------------------
// 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];
// 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"];
}
imageFaceMetadata = [NSDictionary dictionaryWithObjectsAndKeys:
imageDictKey, @"image key",
[imageFaceDict objectForKey:@"face index"], @"face index",
[imageDict objectForKey:@"DateAsTimerInterval"], @"DateAsTimerInterval", 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"];
// Also provide key image key under an event-compatible key
[faceDict setObject:[faceDict objectForKey:@"key image"] forKey:@"KeyPhotoKey"];
// 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 = [NSMutableArray array];
// 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 alloc] initWithArray:inNode.objects];
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Setup the loop
NSUInteger index = 0;
NSString* faceKeyPhotoKey = nil;
NSString* path = nil;
IMBNodeObject* 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] init] autorelease];
subNode.leaf = [self isLeafAlbumType:subNodeType];
subNode.icon = [self iconForAlbumType:subNodeType];
subNode.name = subNodeName;
subNode.mediaSource = self.mediaSource;
subNode.parser = self;
// Keep a ref to face dictionary for potential later use
subNode.attributes = faceDict;
// 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 = [[IMBNodeObject 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.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 = (id)path;
object.name = subNode.name;
object.parser = self;
object.index = index++;
object.imageLocation = [self imagePathForFaceIndex:[faceDict objectForKey:@"key image face index"] inImageWithKey:faceKeyPhotoKey];
object.imageRepresentationType = [self requestedImageRepresentationType];
object.imageRepresentation = nil;
}
}
[pool drain];
inNode.subNodes = subNodes;
inNode.objects = objects;
[objects release];
}
#pragma mark -
#pragma mark Object description
+ (NSString*) objectCountFormatSingular
{
return [IMBImageViewController objectCountFormatSingular];
}
+ (NSString*) objectCountFormatPlural
{
return [IMBImageViewController objectCountFormatPlural];
}
//----------------------------------------------------------------------------------------------------------------------
// Events and Faces have other metadata than images or movies
- (NSString*) countableMetadataDescriptionForMetadata:(NSDictionary*)inMetadata
{
NSMutableString* metaDesc = [NSMutableString string];
NSNumber* count = [inMetadata objectForKey:@"PhotoCount"];
if (count)
{
NSString* formatString = [count intValue] > 1 ?
[[self class] objectCountFormatPlural] :
[[self class] objectCountFormatSingular];
[metaDesc appendFormat:formatString, [count intValue]];
}
NSNumber* dateAsTimerInterval = [inMetadata objectForKey:@"RollDateAsTimerInterval"];
if (dateAsTimerInterval)
{
[metaDesc imb_appendNewline];
NSDate* eventDate = [NSDate dateWithTimeIntervalSinceReferenceDate:[dateAsTimerInterval doubleValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateStyle:NSDateFormatterMediumStyle]; // medium date
[metaDesc appendFormat:@"%@", [formatter stringFromDate:eventDate]];
[formatter release];
}
return metaDesc;
}
//----------------------------------------------------------------------------------------------------------------------
// Convert metadata into a human readable string...
- (NSString*) metadataDescriptionForMetadata:(NSDictionary*)inMetadata
{
// Events and Faces have other metadata than images
if ([inMetadata objectForKey:@"PhotoCount"]) // Event, face, ...
{
return [self countableMetadataDescriptionForMetadata:inMetadata];
}
// Image
return [NSImage imb_imageMetadataDescriptionForMetadata:inMetadata];
}
//----------------------------------------------------------------------------------------------------------------------
#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;
}
return ALBUMS_ID_SPACE;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether an album of this type exposes a disclosure triangle or not.
- (BOOL) isLeafAlbumType:(NSString*)inType
{
return ![inType isEqualToString:@"Folder"] &&
![inType isEqualToString:@"Events"] &&
![inType isEqualToString:@"Faces"];
}
//----------------------------------------------------------------------------------------------------------------------
// Returns the standard album of all photos ("Photos") in its plist representation
- (NSDictionary*) allPhotosAlbumInAlbumList:(NSArray*)inAlbumList atIndex:(NSNumber**)outIndex
{
NSUInteger i, count = [inAlbumList count];
for (i = 0; i < count; i++)
{
NSDictionary* albumDict = [inAlbumList objectAtIndex:i];
if ([self isAllPhotosAlbum:albumDict])
{
*outIndex = [NSNumber numberWithUnsignedInteger:i];
return albumDict;
}
}
return nil;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns IKImageBrowserCGImageRepresentationType
- (NSString*) requestedImageRepresentationType
{
return IKImageBrowserCGImageRepresentationType;
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inNode is the events node
- (BOOL) isEventsNode:(IMBNode*)inNode
{
NSNumber* eventsId = [NSNumber numberWithUnsignedInt:EVENTS_NODE_ID];
NSString* eventsIdentifier = [self identifierForId:eventsId inSpace:EVENTS_ID_SPACE];
return [inNode.identifier isEqualToString:eventsIdentifier];
}
//----------------------------------------------------------------------------------------------------------------------
// Returns whether inNode is the faces node
- (BOOL) isFacesNode:(IMBNode*)inNode
{
NSNumber* facesId= [NSNumber numberWithUnsignedInt:FACES_NODE_ID];
NSString* facesIdentifier = [self identifierForId:facesId inSpace:FACES_ID_SPACE];
return [inNode.identifier isEqualToString:facesIdentifier];
}
@end