Skip to content
This repository
tree: 980bd5fd52
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 644 lines (555 sloc) 22.807 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
//
// ArtworkViewController.m
// UIKit Artwork Extractor
//
// Created by Cédric Luthi on 19.02.10.
// Copyright Cédric Luthi 2010. All rights reserved.
//

#import "ArtworkViewController.h"
#import "ArtworkDetailViewController.h"
#import "AppDelegate.h"
#import "EmojiImageView.h"
#import "IPAArchive.h"

#import "FindSymbol.h"
#import <mach-o/dyld.h>

struct imageMapInfo
{
Class class;
int unknown1;
char *name;
int unknown2;
};

static NSString *systemLibraryPath()
{
static NSString *systemLibraryPath = nil;
if (systemLibraryPath)
return systemLibraryPath;

// Extract images from actual firmware if mounted instead of simulator
// Use https://github.com/kennytm/Miscellaneous/blob/master/ipsw_decrypt.py
for (NSString *volumeName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Volumes" error:NULL])
{
NSString *volumePath = [@"/Volumes" stringByAppendingPathComponent:volumeName];
NSString *systemVersionPath = [volumePath stringByAppendingPathComponent:@"/System/Library/CoreServices/SystemVersion.plist"];
NSDictionary *systemVersion = [NSDictionary dictionaryWithContentsOfFile:systemVersionPath];
NSString *productName = [systemVersion objectForKey:@"ProductName"];
NSString *productVersion = [systemVersion objectForKey:@"ProductVersion"];
if ([productName isEqualToString:@"iPhone OS"] && [productVersion hasPrefix:[UIDevice currentDevice].systemVersion])
{
NSString *wallpaperPath = [volumePath stringByAppendingPathComponent:@"/Library/Wallpaper"];
NSArray *wallpapers = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:wallpaperPath error:NULL];
NSString *model = [wallpapers count] == 1 ? [wallpapers lastObject] : @"iPhone";
if ([[UIDevice currentDevice].model hasPrefix:model])
{
systemLibraryPath = [volumePath retain];
return systemLibraryPath;
}
}
}

NSString *systemFrameworksPath = @"/System/Library/Frameworks";
for (NSBundle *framework in [NSBundle allFrameworks])
{
// So that it works on both simulator and device
NSString *frameworkName = [[framework bundlePath] lastPathComponent];
if ([frameworkName isEqualToString:@"Foundation.framework"])
{
systemFrameworksPath = [[framework bundlePath] stringByDeletingLastPathComponent];
break;
}
}

systemLibraryPath = [[systemFrameworksPath stringByDeletingLastPathComponent] retain];
return systemLibraryPath;
}

static NSString *pathWithScale(NSString *path, CGFloat scale)
{
if (scale > 1)
return [[[path stringByDeletingPathExtension] stringByAppendingFormat:@"@%gx", scale] stringByAppendingPathExtension:[path pathExtension]];
else
return path;
}

// Workaround http://www.openradar.me/8225750
static UIImage *imageWithContentsOfFile(NSString *path)
{
NSString *imagePathWithScale = pathWithScale(path, [[UIScreen mainScreen] scale]);
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePathWithScale])
return [UIImage imageWithContentsOfFile:imagePathWithScale];
else
return [UIImage imageWithContentsOfFile:path];
}


@interface ArtworkViewController ()
- (NSArray *) sectionTitles;
@end


@implementation ArtworkViewController

@synthesize progressView = _progressView;
@synthesize saveAllButton = _saveAllButton;
@synthesize bundles = _bundles;
@synthesize firstCellIndexPath = _firstCellIndexPath;
@synthesize saveCounter = _saveCounter;
@synthesize archive = _archive;

- (id) initWithArchive:(IPAArchive *)archive
{
if (!(self = [super initWithNibName:@"ArtworkViewController" bundle:nil]))
return nil;

self.archive = archive;
self.title = archive.appName;

return self;
}

- (void) dealloc
{
self.progressView = nil;
self.saveAllButton = nil;
self.bundles = nil;
self.firstCellIndexPath = nil;
[self.archive unload];
self.archive = nil;

[artwork release];

[super dealloc];
}

- (BOOL) isArtwork
{
return [self.title isEqualToString:@"Artwork"];
}

- (BOOL) isEmoji
{
return [self.title isEqualToString:@"Emoji"];
}

- (BOOL) isIPA
{
return self.archive != nil;
}

- (NSDictionary *) artwork
{
if (artwork)
return artwork;

Class UIKeyboardEmojiImages = NSClassFromString(@"UIKeyboardEmojiImages"); // iOS 3 only
[UIKeyboardEmojiImages performSelector:@selector(mapImagesIfNecessary)];

NSArray *keys = nil;
NSDictionary *emojiMap = nil;
if ([self isEmoji])
{
Class UIKeyboardEmojiFactory = NSClassFromString(@"UIKeyboardEmojiFactory");
id emojiFactory = [[[UIKeyboardEmojiFactory alloc] init] autorelease];
@try
{
emojiMap = [emojiFactory valueForKey:@"emojiMap"];
keys = [emojiMap allKeys];
}
@catch (NSException *exception)
{
Class UIKeyboardEmojiCategoryController = NSClassFromString(@"UIKeyboardEmojiCategoryController");
Class UIKeyboardEmojiFactory = NSClassFromString(@"UIKeyboardEmojiFactory");
id emojiController = [[[UIKeyboardEmojiFactory alloc] init] autorelease];
id keyboardEmojiCategoryController = [[UIKeyboardEmojiCategoryController alloc] performSelector:@selector(initWithController:) withObject:emojiController];
NSArray *categories = [NSArray arrayWithObjects:@"People", @"Nature", @"Objects", @"Places", @"Symbols", nil];
for (NSString *category in categories)
{
NSMutableArray *categoryList = [NSMutableArray array];
NSString *categoryKey = [@"UIKeyboardEmojiCategory" stringByAppendingString:category];
id keyboardEmojiCategory = [keyboardEmojiCategoryController performSelector:@selector(categoryForKey:) withObject:categoryKey];
for (id emoji in [keyboardEmojiCategory valueForKey:@"emoji"])
{
NSMutableString *name = (NSMutableString *)CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef)[emoji valueForKey:@"key"]);
CFStringTransform((CFMutableStringRef)name, NULL, kCFStringTransformToUnicodeName, false);
[name replaceOccurrencesOfString:@"\\N" withString:@"" options:0 range:NSMakeRange(0, [name length])];
[name replaceOccurrencesOfString:@"{" withString:@"" options:0 range:NSMakeRange(0, [name length])];
[name replaceOccurrencesOfString:@"}" withString:@"" options:0 range:NSMakeRange(0, [name length])];

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"EmojiCell"] autorelease];
cell.textLabel.text = [[[(NSMutableString *)name autorelease] capitalizedString] stringByAppendingPathExtension:@"png"];
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.accessoryView = [[[EmojiImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24) emoji:emoji] autorelease];

[categoryList addObject:cell];
}
[self.bundles setObject:categoryList forKey:category];
}
}
}
else if ([self isIPA])
{
keys = nil;
}
else
{
for(uint32_t i = 0; i < _dyld_image_count(); i++)
{
if (strstr(_dyld_get_image_name(i), "UIKit.framework"))
{
struct mach_header* header = (struct mach_header*)_dyld_get_image_header(i);
NSMutableDictionary **__mappedImages = FindSymbol(header, "___mappedImages");
NSMutableDictionary **__images = FindSymbol(header, "___images");

NSString *deviceModel = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone";
NSString *imageMapNamesSymbol = [NSString stringWithFormat:@"_ImageMapNames_Shared_%gx_%@", [[UIScreen mainScreen] scale], deviceModel];
BOOL isVersion5OrLater = [UIImage instancesRespondToSelector:@selector(CIImage)];
if (isVersion5OrLater)
imageMapNamesSymbol = [NSString stringWithFormat:@"_ImageMapNames_Shared_%gx", [[UIScreen mainScreen] scale]];
struct imageMapInfo **imageMapNames = FindSymbol(header, [imageMapNamesSymbol UTF8String]);

// Force loading all images (iOS 4 only)
if (imageMapNames)
{
// iOS 4.1
while (*imageMapNames)
{
struct imageMapInfo *imageInfo = *imageMapNames++;
NSString *imageName = [NSString stringWithUTF8String:imageInfo->name];
(void)[UIImage performSelector:@selector(kitImageNamed:) withObject:imageName];
}
}
else
{
// iOS 4.0
int *__sharedImageSets = FindSymbol(header, "___sharedImageSets");
if (__sharedImageSets)
{
NSString **sharedImageNames = (NSString**)(*(int*)(__sharedImageSets + 4));
NSUInteger sharedImageCount = (*(int*)(__sharedImageSets + 5));
if (sharedImageNames)
{
for (int i = 0; i < sharedImageCount; i++)
{
NSString *imageName = sharedImageNames[i];
(void)[UIImage performSelector:@selector(kitImageNamed:) withObject:imageName];
}
}
}
}

if (__mappedImages)
keys = [*__mappedImages allKeys]; // iOS 3
else if (__images)
keys = [*__images allKeys]; // iOS 4

break;
}
}
}

artwork = [[NSMutableDictionary alloc] init];
for (NSString *key in keys)
{
NSString *imageName = nil;
UIImage *image = nil;

if ([self isEmoji])
{
id emoji = [emojiMap objectForKey:key];
imageName = [emoji valueForKey:@"imageName"];
image = [emoji valueForKey:@"image"];
}
else
{
imageName = key;
image = [UIImage performSelector:@selector(kitImageNamed:) withObject:key]; // calls _UIImageWithName
}

[artwork setObject:image forKey:imageName];
}

return artwork;
}

- (NSArray *) allCells
{
NSMutableArray *allCells = [NSMutableArray array];
for (NSArray *cells in [self.bundles allValues])
[allCells addObjectsFromArray:cells];
return allCells;
}

- (void) addImage:(UIImage *)image filePath:(NSString *)filePath
{
NSString *oppositeInterfaceIdiomSuffix = [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone ? @"~ipad" : @"~iphone";
if ([filePath rangeOfString:oppositeInterfaceIdiomSuffix].location != NSNotFound)
return;

NSString *fileName = [[filePath lastPathComponent] stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"@%gx", image.scale] withString:@""];
NSString *bundlePath = [filePath stringByDeletingLastPathComponent];
NSString *bundleName = [bundlePath lastPathComponent];
if ([bundleName length] == 0) // Extracted from .artwork file, has no actual path
bundleName = [self isEmoji] ? @"Emoji" : @"Shared";

// We already have higher resolution emoji
if ([bundleName isEqualToString:@"WebCore.framework"] && [fileName hasPrefix:@"emoji"])
return;

for (UITableViewCell *cell in [self allCells])
{
if ([cell.textLabel.text caseInsensitiveCompare:fileName] == NSOrderedSame)
{
NSData *file1Data = [NSData dataWithContentsOfFile:cell.detailTextLabel.text];
NSData *file2Data = [NSData dataWithContentsOfFile:filePath];
if ([file1Data isEqualToData:file2Data]) // Filter out exact duplicates
return;
}
}

// There are only a few settings bundles, so group them
if ([bundleName rangeOfString:@"Settings"].location != NSNotFound)
{
fileName = [NSString stringWithFormat:@"%@_%@", [bundleName stringByDeletingPathExtension], fileName];
bundleName = @"Settings";
}

NSString *appBundleName = [[bundlePath stringByDeletingLastPathComponent] lastPathComponent];
if ([appBundleName isEqualToString:@"Compass.app"])
{
fileName = [NSString stringWithFormat:@"%@_%@", [bundleName stringByDeletingPathExtension], fileName];
bundleName = @"Compass.app";
}

if ([filePath rangeOfString:@"GKWelcomeToGameCenter"].location != NSNotFound)
{
fileName = [NSString stringWithFormat:@"%@_%@", [bundleName stringByDeletingPathExtension], fileName];
bundleName = @"Game Center~ipad.app";
}

if ([filePath rangeOfString:@"_CARRIER_"].location != NSNotFound)
{
bundleName = @"Carriers";
}

if (![self.bundles objectForKey:bundleName])
[self.bundles setObject:[NSMutableArray array] forKey:bundleName];

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ImageCell"] autorelease];
cell.textLabel.text = fileName;
cell.textLabel.font = [UIFont systemFontOfSize:12];
// Just because I'm too lazy to subclass UITableViewCell and I need to store the full path for duplicates comparison
cell.detailTextLabel.text = filePath;
cell.detailTextLabel.font = [UIFont systemFontOfSize:FLT_EPSILON];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
CGFloat sizeX = CGRectGetHeight(cell.frame) - 4 - ((int)image.size.width % 2);
CGFloat sizeY = CGRectGetHeight(cell.frame) - 4 - ((int)image.size.height % 2);
imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, sizeX, sizeY);
if (image.size.height > sizeY || image.size.width > sizeX)
imageView.contentMode = UIViewContentModeScaleAspectFit;
else
imageView.contentMode = UIViewContentModeCenter;
cell.accessoryView = imageView;

NSMutableArray *cells = [self.bundles objectForKey:bundleName];
[cells addObject:cell];

NSString *progress = [NSString stringWithFormat:@"%@ (%u)", [bundleName stringByDeletingPathExtension], [cells count]];
[self.navigationItem performSelectorOnMainThread:@selector(setTitle:) withObject:progress waitUntilDone:NO];
}

- (void) loadImages
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

for (NSString *imageName in [[self.artwork allKeys] sortedArrayUsingSelector:@selector(compare:)])
[self addImage:[self.artwork objectForKey:imageName] filePath:imageName];

if ([self isArtwork])
{
for (NSString *relativePath in [[NSFileManager defaultManager] enumeratorAtPath:systemLibraryPath()])
{
BOOL scale1 = [UIScreen mainScreen].scale == 1 && [[relativePath lowercaseString] rangeOfString:@"@2x"].location == NSNotFound;
BOOL scale2 = [UIScreen mainScreen].scale == 2 && [[relativePath lowercaseString] rangeOfString:@"@2x"].location != NSNotFound;
if ([relativePath hasSuffix:@"png"] && (scale1 || scale2))
{
NSString *filePath = [systemLibraryPath() stringByAppendingPathComponent:relativePath];
[self addImage:imageWithContentsOfFile(filePath) filePath:filePath];
}
}
}
else if ([self isIPA])
{
for (NSString *imageName in self.archive.imageNames)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL scale1 = [UIScreen mainScreen].scale == 1 && [[imageName lowercaseString] rangeOfString:@"@2x"].location == NSNotFound;
BOOL scale2 = [UIScreen mainScreen].scale == 2 && [[imageName lowercaseString] rangeOfString:@"@2x"].location != NSNotFound;
if ([imageName hasSuffix:@"png"] && (scale1 || scale2))
{
[self addImage:[self.archive imageNamed:imageName] filePath:imageName];
}
[pool drain];
}
}

[self performSelectorOnMainThread:@selector(imagesDidLoad) withObject:nil waitUntilDone:NO];

[pool drain];
}

- (void) imagesDidLoad
{
self.tableView.hidden = NO;
self.navigationItem.title = self.title;
self.navigationItem.rightBarButtonItem = self.saveAllButton;

[self.tableView reloadData];
}

- (void) viewDidLoad
{
self.progressView.frame = CGRectMake(10, 17, 90, 11);
self.progressView.hidden = YES;
[self.navigationController.navigationBar addSubview:self.progressView];
self.tableView.hidden = YES;

if ([self isEmoji])
self.tableView.tableHeaderView = nil; // removes search bar

self.bundles = [NSMutableDictionary dictionary];

[self performSelectorInBackground:@selector(loadImages) withObject:nil];
}

- (void) viewDidUnload
{
self.progressView = nil;
self.saveAllButton = nil;
self.bundles = nil;
}

- (void) saveImage:(NSDictionary *)imageInfo
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
UIImage *image = [imageInfo objectForKey:@"image"];
NSString *imageName = [imageInfo objectForKey:@"name"];
NSString *bundleName = [[imageInfo objectForKey:@"bundleName"] stringByReplacingOccurrencesOfString:@"." withString:@" "];
if (self.archive.appName && [[self sectionTitles] count] > 1)
bundleName = [self.archive.appName stringByAppendingPathComponent:bundleName];
else if ([self isEmoji])
bundleName = [@"Emoji" stringByAppendingPathComponent:bundleName];
NSString *imagePath = [[appDelegate saveDirectory:bundleName] stringByAppendingPathComponent:pathWithScale(imageName, [image scale])];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
[self performSelectorOnMainThread:@selector(incrementSaveCounter) withObject:nil waitUntilDone:YES];
[pool drain];
}

- (NSArray *) sectionKeys
{
return [[self.bundles allKeys] sortedArrayUsingSelector:@selector(localizedCompare:)];
}

- (IBAction) saveAll
{
self.saveCounter = 0;
self.progressView.hidden = NO;
self.saveAllButton.enabled = NO;
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue setMaxConcurrentOperationCount:4];
for (NSString *bundleName in [self sectionKeys])
{
for (UITableViewCell *cell in [self.bundles objectForKey:bundleName])
{
NSDictionary *imageInfo = [NSDictionary dictionaryWithObjectsAndKeys:((UIImageView*)cell.accessoryView).image, @"image", cell.textLabel.text, @"name", bundleName, @"bundleName", nil];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(saveImage:) object:imageInfo];
[queue addOperation:operation];
[operation release];
}
}
}

- (void) incrementSaveCounter
{
self.saveCounter++;
NSUInteger count = [[self allCells] count];
if (self.saveCounter == count)
{
self.progressView.hidden = YES;
self.saveAllButton.enabled = YES;
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSString *message = [NSString stringWithFormat:@"Artwork has been saved into\n\"%@\"", [[appDelegate saveDirectory:nil] stringByAbbreviatingWithTildeInPath]];
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Open", nil] autorelease];
[alertView show];
}
self.progressView.progress = ((CGFloat)self.saveCounter / (CGFloat)count);
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.cancelButtonIndex == buttonIndex)
return;

AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSString *openCommand = [NSString stringWithFormat:@"/usr/bin/open \"%@\"", [appDelegate saveDirectory:nil]];
system([openCommand fileSystemRepresentation]);
}

// MARK: -
// MARK: Table View Data Source

- (NSArray *) filteredCells
{
NSString *searchText = [NSString stringWithFormat:@"*%@*", [self.searchDisplayController.searchBar.text lowercaseString]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"textLabel.text.lowercaseString LIKE %@", searchText];
NSArray *filteredCells = [[self allCells] filteredArrayUsingPredicate:predicate];
return filteredCells;
}

- (NSArray *) sectionTitles
{
NSMutableArray *sectionTitles = [NSMutableArray array];
for (NSString *bundleName in [self sectionKeys])
{
NSArray *cells = [self.bundles objectForKey:bundleName];
NSString *sectionTitle = [NSString stringWithFormat:@"%@ (%d)", bundleName, [cells count]];
[sectionTitles addObject:sectionTitle];
}
return sectionTitles;
}

- (NSArray *) cellsInSection:(NSUInteger)section
{
if ([[self sectionKeys] count] == 0)
return nil;

NSString *bundleName = [[self sectionKeys] objectAtIndex:section];
return [self.bundles objectForKey:bundleName];
}

// MARK: Section titles

- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSArray *sectionTitles = [self sectionTitles];
if (![self isEmoji] && tableView == self.tableView && [sectionTitles count] > 1)
{
NSMutableArray *sectionIndexTitles = [NSMutableArray array];
for (NSString *title in sectionTitles)
[sectionIndexTitles addObject:[title substringToIndex:2]];
return sectionIndexTitles;
}
else
return nil;
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
NSArray *sectionTitles = [self sectionTitles];
if (tableView == self.tableView && [sectionTitles count] > 1)
return [sectionTitles objectAtIndex:section];
else
return nil;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == self.tableView)
return [[self.bundles allKeys] count];
else
return 1;
}

// MARK: Cells

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView)
return [[self cellsInSection:section] count];
else
return [[self filteredCells] count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.tableView)
return [[self cellsInSection:indexPath.section] objectAtIndex:indexPath.row];
else
return [[self filteredCells] objectAtIndex:indexPath.row];
}

// MARK: -
// MARK: Table View Delegate

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *bundleName = @"Unknown";
for (bundleName in self.bundles)
{
if ([[self.bundles objectForKey:bundleName] containsObject:cell])
break;
}
NSDictionary *imageInfo = [NSDictionary dictionaryWithObjectsAndKeys:((UIImageView*)cell.accessoryView).image, @"image", cell.textLabel.text, @"name", bundleName, @"bundleName", nil];
ArtworkDetailViewController *artworkDetailViewController = [[ArtworkDetailViewController alloc] initWithImageInfo:imageInfo];
[self.navigationController pushViewController:artworkDetailViewController animated:YES];
[artworkDetailViewController release];
}

// MARK: -
// MARK: Search Display Delegate

- (void) searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.backgroundColor = self.tableView.backgroundColor;
}

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
[self.tableView reloadData];

NSArray *indexPathsForVisibleRows = [controller.searchResultsTableView indexPathsForVisibleRows];
UITableViewCell *firstVisibleCell = nil;
if ([indexPathsForVisibleRows count] > 0)
firstVisibleCell = [controller.searchResultsTableView cellForRowAtIndexPath:[indexPathsForVisibleRows objectAtIndex:0]];

if (firstVisibleCell)
{
NSUInteger section = 0;
NSUInteger row = 0;
for (NSString *bundleName in [self sectionKeys])
{
NSArray *cells = [self.bundles objectForKey:bundleName];
row = [cells indexOfObject:firstVisibleCell];
if (row != NSNotFound)
break;
section++;
}
self.firstCellIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
}
else
self.firstCellIndexPath = nil;
}

- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[self.tableView scrollToRowAtIndexPath:self.firstCellIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

@end
Something went wrong with that request. Please try again.