Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 083842e252
Fetching contributors…

Cannot retrieve contributors at this time

file 959 lines (786 sloc) 36.424 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
/*
The MIT License
Copyright (c) 2009 Matthew Ball
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 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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "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 OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#import "MBCoverFlowView.h"

#import "MBCoverFlowScroller.h"
#import "NSImage+MBCoverFlowAdditions.h"

#import <QuartzCore/QuartzCore.h>

// Constants
#define MBCoverFlowViewCellSpacing ([self itemSize].width/10)

const float MBCoverFlowViewPlaceholderHeight = 600;

const float MBCoverFlowViewTopMargin = 30.0;
const float MBCoverFlowViewBottomMargin = 20.0;
const float MBCoverFlowViewHorizontalMargin = 12.0;
#define MBCoverFlowViewContainerMinY (NSMaxY([self.accessoryController.view frame]) - 3*[self itemSize].height/4)

const float MBCoverFlowScrollerHorizontalMargin = 80.0;
const float MBCoverFlowScrollerVerticalSpacing = 16.0;

const float MBCoverFlowViewDefaultItemWidth = 140.0;
const float MBCoverFlowViewDefaultItemHeight = 100.0;

const float MBCoverFlowScrollMinimumDeltaThreshold = 0.4;

// Perspective parameters
const float MBCoverFlowViewPerspectiveCenterPosition = 100.0;
const float MBCoverFlowViewPerspectiveSidePosition = 0.0;
const float MBCoverFlowViewPerspectiveSideSpacingFactor = 0.75;
const float MBCoverFlowViewPerspectiveRowScaleFactor = 0.85;
const float MBCoverFlowViewPerspectiveAngle = 0.79;

// KVO
static NSString *MBCoverFlowViewImagePathContext;

// Key Codes
#define MBLeftArrowKeyCode 123
#define MBRightArrowKeyCode 124
#define MBReturnKeyCode 36

@interface MBCoverFlowView ()
- (float)_positionOfSelectedItem;
- (CALayer *)_insertLayerInScrollLayer;
- (void)_scrollerChange:(MBCoverFlowScroller *)scroller;
- (void)_refreshLayer:(CALayer *)layer;
- (void)_loadImageForLayer:(CALayer *)layer;
- (CALayer *)_layerForObject:(id)object;
- (void)_recachePlaceholder;
- (void)_setSelectionIndex:(NSInteger)index; // For two-way bindings
@end


@implementation MBCoverFlowView

@synthesize accessoryController=_accessoryController, selectionIndex=_selectionIndex,
            itemSize=_itemSize, content=_content, showsScrollbar=_showsScrollbar,
            autoresizesItems=_autoresizesItems, imageKeyPath=_imageKeyPath,
            placeholderIcon=_placeholderIcon, target=_target, action=_action;

@dynamic selectedObject;

#pragma mark -
#pragma mark Life Cycle

+ (void)initialize
{
[self exposeBinding:@"content"];
[self exposeBinding:@"selectionIndex"];
}

- (id)initWithFrame:(NSRect)frameRect
{
if (self = [super initWithFrame:frameRect]) {
_bindingInfo = [[NSMutableDictionary alloc] init];

_imageLoadQueue = [[NSOperationQueue alloc] init];
[_imageLoadQueue setMaxConcurrentOperationCount:1];

_placeholderIcon = [[NSImage imageNamed:NSImageNameQuickLookTemplate] retain];

_autoresizesItems = YES;

[self setAutoresizesSubviews:YES];

// Create the scroller
_scroller = [[MBCoverFlowScroller alloc] initWithFrame:NSMakeRect(10, 10, 400, 16)];
[_scroller setEnabled:YES];
[_scroller setTarget:self];
[_scroller setHidden:YES];
[_scroller setKnobProportion:1.0];
[_scroller setAction:@selector(_scrollerChange:)];
[self addSubview:_scroller];

_leftTransform = CATransform3DMakeRotation(-0.79, 0, -1, 0);
_rightTransform = CATransform3DMakeRotation(MBCoverFlowViewPerspectiveAngle, 0, -1, 0);

_itemSize = NSMakeSize(MBCoverFlowViewDefaultItemWidth, MBCoverFlowViewDefaultItemHeight);

CALayer *rootLayer = [CALayer layer];
rootLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
rootLayer.backgroundColor = CGColorGetConstantColor(kCGColorBlack);
[self setLayer:rootLayer];

_containerLayer = [CALayer layer];
_containerLayer.name = @"body";
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintWidth relativeTo:@"superlayer" attribute:kCAConstraintWidth offset:-20]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY offset:MBCoverFlowViewContainerMinY]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY offset:-10]];
[rootLayer addSublayer:_containerLayer];

_scrollLayer = [CAScrollLayer layer];
_scrollLayer.scrollMode = kCAScrollHorizontally;
_scrollLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
_scrollLayer.layoutManager = self;
[_containerLayer addSublayer:_scrollLayer];

// Create a gradient image to use for image shadows
CGRect gradientRect;
gradientRect.origin = CGPointZero;
gradientRect.size = NSSizeToCGSize([self itemSize]);
size_t bytesPerRow = 4*gradientRect.size.width;
void* bitmapData = malloc(bytesPerRow * gradientRect.size.height);
CGContextRef context = CGBitmapContextCreate(bitmapData, gradientRect.size.width,
gradientRect.size.height, 8, bytesPerRow,
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGImageAlphaPremultipliedFirst);
NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithDeviceWhite:0 alpha:0.6] endingColor:[NSColor colorWithDeviceWhite:0 alpha:1.0]];
NSGraphicsContext *nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:YES];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsContext];
[gradient drawInRect:NSMakeRect(0, 0, gradientRect.size.width, gradientRect.size.height) angle:90];
[NSGraphicsContext restoreGraphicsState];
_shadowImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
[gradient release];


/* create a pleasant gradient mask around our central layer.
We don't have to worry about re-creating these when the window
size changes because the images will be automatically interpolated
to their new sizes; and as gradients, they are very well suited to
interpolation. */
CALayer *maskLayer = [CALayer layer];
_leftGradientLayer = [CALayer layer];
_rightGradientLayer = [CALayer layer];
_bottomGradientLayer = [CALayer layer];

// left
gradientRect.origin = CGPointZero;
gradientRect.size.width = [self frame].size.width;
gradientRect.size.height = [self frame].size.height;
bytesPerRow = 4*gradientRect.size.width;
bitmapData = malloc(bytesPerRow * gradientRect.size.height);
context = CGBitmapContextCreate(bitmapData, gradientRect.size.width,
gradientRect.size.height, 8, bytesPerRow,
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGImageAlphaPremultipliedFirst);
gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithDeviceWhite:0. alpha:1.] endingColor:[NSColor colorWithDeviceWhite:0. alpha:0]];
nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:YES];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsContext];
[gradient drawInRect:NSMakeRect(0, 0, gradientRect.size.width, gradientRect.size.height) angle:0];
[NSGraphicsContext restoreGraphicsState];
CGImageRef gradientImage = CGBitmapContextCreateImage(context);
_leftGradientLayer.contents = (id)gradientImage;
CGContextRelease(context);
CGImageRelease(gradientImage);
free(bitmapData);

// right
bitmapData = malloc(bytesPerRow * gradientRect.size.height);
context = CGBitmapContextCreate(bitmapData, gradientRect.size.width,
gradientRect.size.height, 8, bytesPerRow,
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGImageAlphaPremultipliedFirst);
nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:YES];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsContext];
[gradient drawInRect:NSMakeRect(0, 0, gradientRect.size.width, gradientRect.size.height) angle:180];
[NSGraphicsContext restoreGraphicsState];
gradientImage = CGBitmapContextCreateImage(context);
_rightGradientLayer.contents = (id)gradientImage;
CGContextRelease(context);
CGImageRelease(gradientImage);
free(bitmapData);

// bottom
gradientRect.size.width = [self frame].size.width;
gradientRect.size.height = 32;
bytesPerRow = 4*gradientRect.size.width;
bitmapData = malloc(bytesPerRow * gradientRect.size.height);
context = CGBitmapContextCreate(bitmapData, gradientRect.size.width,
gradientRect.size.height, 8, bytesPerRow,
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGImageAlphaPremultipliedFirst);
nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:YES];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsContext];
[gradient drawInRect:NSMakeRect(0, 0, gradientRect.size.width, gradientRect.size.height) angle:90];
[NSGraphicsContext restoreGraphicsState];
gradientImage = CGBitmapContextCreateImage(context);
_bottomGradientLayer.contents = (id)gradientImage;
CGContextRelease(context);
CGImageRelease(gradientImage);
free(bitmapData);
[gradient release];

// the autoresizing mask allows it to change shape with the parent layer
maskLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
maskLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinX relativeTo:@"superlayer" attribute:kCAConstraintMinX]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxX relativeTo:@"superlayer" attribute:kCAConstraintMaxX scale:.5 offset:-[self itemSize].width / 2]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxX relativeTo:@"superlayer" attribute:kCAConstraintMaxX]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinX relativeTo:@"superlayer" attribute:kCAConstraintMaxX scale:.5 offset:[self itemSize].width / 2]];
[_bottomGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxX relativeTo:@"superlayer" attribute:kCAConstraintMaxX]];
[_bottomGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY]];
[_bottomGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinX relativeTo:@"superlayer" attribute:kCAConstraintMinX]];
[_bottomGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMinY offset:32]];

_bottomGradientLayer.masksToBounds = YES;

[maskLayer addSublayer:_rightGradientLayer];
[maskLayer addSublayer:_leftGradientLayer];
[maskLayer addSublayer:_bottomGradientLayer];
// we make it a sublayer rather than a mask so that the overlapping alpha will work correctly
// without the use of a compositing filter
[_containerLayer addSublayer:maskLayer];
}
return self;
}

- (void)dealloc
{
[_bindingInfo release];
[_scroller release];
[_scrollLayer release];
[_containerLayer release];
self.accessoryController = nil;
self.content = nil;
self.imageKeyPath = nil;
self.placeholderIcon = nil;
CGImageRelease(_placeholderRef);
CGImageRelease(_shadowImage);
[_imageLoadQueue release];
_imageLoadQueue = nil;
[super dealloc];
}

- (void)awakeFromNib
{
[self setWantsLayer:YES];
[self _recachePlaceholder];
}

#pragma mark -
#pragma mark Superclass Overrides

#pragma mark NSResponder

- (BOOL)acceptsFirstResponder
{
return YES;
}

- (void)keyDown:(NSEvent *)theEvent
{
switch ([theEvent keyCode]) {
case MBLeftArrowKeyCode:
[self _setSelectionIndex:(self.selectionIndex - 1)];
break;
case MBRightArrowKeyCode:
[self _setSelectionIndex:(self.selectionIndex + 1)];
break;
case MBReturnKeyCode:
if (self.target && self.action) {
[self.target performSelector:self.action withObject:self];
break;
}
default:
[super keyDown:theEvent];
break;
}
}

- (void)mouseDown:(NSEvent *)theEvent
{
if ([theEvent clickCount] == 2 && self.target && self.action) {
[self.target performSelector:self.action withObject:self];
}

NSPoint mouseLocation = [self convertPoint:[theEvent locationInWindow] fromView:nil];
NSInteger clickedIndex = [self indexOfItemAtPoint:mouseLocation];
if (clickedIndex != NSNotFound) {
[self _setSelectionIndex:clickedIndex];
}
}

- (void)scrollWheel:(NSEvent *)theEvent
{
if (fabs([theEvent deltaY]) > MBCoverFlowScrollMinimumDeltaThreshold) {
if ([theEvent deltaY] > 0) {
[self _setSelectionIndex:(self.selectionIndex - 1)];
} else {
[self _setSelectionIndex:(self.selectionIndex + 1)];
}
} else if (fabs([theEvent deltaX]) > MBCoverFlowScrollMinimumDeltaThreshold) {
if ([theEvent deltaX] > 0) {
[self _setSelectionIndex:(self.selectionIndex - 1)];
} else {
[self _setSelectionIndex:(self.selectionIndex + 1)];
}
}
}

#pragma mark NSView

- (void)viewWillMoveToSuperview:(NSView *)newSuperview
{
[self resizeSubviewsWithOldSize:[self frame].size];
}

- (void)resizeSubviewsWithOldSize:(NSSize)oldSize
{
float accessoryY = MBCoverFlowScrollerVerticalSpacing;

// Reposition the scroller
if (self.showsScrollbar) {
NSRect scrollerFrame = [_scroller frame];
scrollerFrame.size.width = [self frame].size.width - 2*MBCoverFlowScrollerHorizontalMargin;
scrollerFrame.origin.x = ([self frame].size.width - scrollerFrame.size.width)/2;
scrollerFrame.origin.y = MBCoverFlowViewBottomMargin;
[_scroller setFrame:scrollerFrame];
accessoryY += NSMaxY([_scroller frame]);
}

if (self.accessoryController.view) {
NSRect accessoryFrame = [self.accessoryController.view frame];
accessoryFrame.origin.x = floor(([self frame].size.width - accessoryFrame.size.width)/2);
accessoryFrame.origin.y = accessoryY;
[self.accessoryController.view setFrame:accessoryFrame];
}

_containerLayer.constraints = nil;
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintWidth relativeTo:@"superlayer" attribute:kCAConstraintWidth offset:-20]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY offset:MBCoverFlowViewContainerMinY]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY offset:-10]];

self.selectionIndex = self.selectionIndex;
}

- (BOOL)mouseDownCanMoveWindow
{
return NO;
}

#pragma mark -
#pragma mark Subclass Methods

#pragma mark Loading Data

- (void)setContent:(NSArray *)newContents
{
if ([newContents isEqualToArray:self.content]) {
return;
}

NSArray *oldContent = [self.content retain];

if (_content) {
[_content release];
_content = nil;
}

if (newContents != nil) {
_content = [newContents copy];
}

// Add any new items
NSMutableArray *itemsToAdd = [self.content mutableCopy];
[itemsToAdd removeObjectsInArray:oldContent];

for (NSObject *object in itemsToAdd) {
CALayer *layer = [self _insertLayerInScrollLayer];
[layer setValue:object forKey:@"representedObject"];
if (self.imageKeyPath) {
[object addObserver:self forKeyPath:self.imageKeyPath options:0 context:&MBCoverFlowViewImagePathContext];
}
[self _refreshLayer:layer];
}
[itemsToAdd release];

// Remove any items which are no longer present
NSMutableArray *itemsToRemove = [oldContent mutableCopy];
[itemsToRemove removeObjectsInArray:self.content];
for (NSObject *object in itemsToRemove) {
CALayer *layer = [self _layerForObject:object];
if (self.imageKeyPath) {
[[layer valueForKey:@"representedObject"] removeObserver:self forKeyPath:self.imageKeyPath];
}
[layer removeFromSuperlayer];
}
[itemsToRemove release];

[oldContent release];

// Update the layer indices
for (CALayer *layer in [_scrollLayer sublayers]) {
[layer setValue:[NSNumber numberWithInteger:[self.content indexOfObject:[layer valueForKey:@"representedObject"]]] forKey:@"index"];
}

[_scroller setNumberOfIncrements:fmax([self.content count]-1, 0)];
self.selectionIndex = self.selectionIndex;
}

- (void)setImageKeyPath:(NSString *)keyPath
{
if (_imageKeyPath) {
// Remove any observations for the existing key path
for (NSObject *object in self.content) {
[object removeObserver:self forKeyPath:self.imageKeyPath];
}

[_imageKeyPath release];
_imageKeyPath = nil;
}

if (keyPath) {
_imageKeyPath = [keyPath copy];
}

// Refresh all the layers with images at the new key path
for (CALayer *layer in [_scrollLayer sublayers]) {
if (self.imageKeyPath) {
[[layer valueForKey:@"representedObject"] addObserver:self forKeyPath:self.imageKeyPath options:0 context:&MBCoverFlowViewImagePathContext];
}
[self _refreshLayer:layer];
}
}

#pragma mark Setting Display Attributes

- (void)setAutoresizesItems:(BOOL)flag
{
_autoresizesItems = flag;
[self resizeSubviewsWithOldSize:[self frame].size];
}

- (NSSize)itemSize
{
if (!self.autoresizesItems) {
return _itemSize;
}

float origin = MBCoverFlowViewBottomMargin;

if (self.showsScrollbar) {
origin += [_scroller frame].size.height + MBCoverFlowScrollerVerticalSpacing;
}

if (self.accessoryController.view) {
NSRect accessoryFrame = [self.accessoryController.view frame];
origin += accessoryFrame.size.height;
}

NSSize size;
size.height = fmax(([self frame].size.height - origin) - [self frame].size.height/3, 1.0f);
size.width = size.height * _itemSize.width / _itemSize.height;

// Make sure it's integral
size.height = floor(size.height);
size.width = floor(size.width);

return size;
}

- (void)setItemSize:(NSSize)newSize
{
if (newSize.width <= 0) {
newSize.width = MBCoverFlowViewDefaultItemWidth;
}

if (newSize.height <= 0) {
newSize.height = MBCoverFlowViewDefaultItemHeight;
}

_itemSize = newSize;

// Update all the various constraints which depend on the item size
_containerLayer.constraints = nil;
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintWidth relativeTo:@"superlayer" attribute:kCAConstraintWidth offset:-20]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY offset:MBCoverFlowViewContainerMinY]];
[_containerLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY offset:-10]];

_leftGradientLayer.constraints = nil;
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinX relativeTo:@"superlayer" attribute:kCAConstraintMinX]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY]];
[_leftGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxX relativeTo:@"superlayer" attribute:kCAConstraintMaxX scale:.5 offset:-[self itemSize].width / 2]];
_rightGradientLayer.constraints = nil;
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxX relativeTo:@"superlayer" attribute:kCAConstraintMaxX]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinY relativeTo:@"superlayer" attribute:kCAConstraintMinY]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMaxY relativeTo:@"superlayer" attribute:kCAConstraintMaxY]];
[_rightGradientLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMinX relativeTo:@"superlayer" attribute:kCAConstraintMaxX scale:.5 offset:[self itemSize].width / 2]];

// Update the view
[self _recachePlaceholder];
[self.layer setNeedsLayout];

CALayer *layer = [[_scrollLayer sublayers] objectAtIndex:self.selectionIndex];
CGRect layerFrame = [layer frame];

// Scroll so the selected item is centered
[_scrollLayer scrollToPoint:CGPointMake([self _positionOfSelectedItem], layerFrame.origin.y)];

}

- (void)setShowsScrollbar:(BOOL)flag
{
_showsScrollbar = flag;
[_scroller setHidden:!flag];
[self resizeSubviewsWithOldSize:[self frame].size];
}

- (void)setAccessoryController:(NSViewController *)aController
{
if (aController == self.accessoryController)
return;

if (self.accessoryController != nil) {
[self.accessoryController.view removeFromSuperview];
[self.accessoryController unbind:@"representedObject"];
[_accessoryController release];
_accessoryController = nil;
[self setNextResponder:nil];
}

if (aController != nil) {
_accessoryController = [aController retain];
[self addSubview:self.accessoryController.view];
[self.accessoryController setNextResponder:[self nextResponder]];
[self setNextResponder:self.accessoryController];
[self.accessoryController bind:@"representedObject" toObject:self withKeyPath:@"selectedObject" options:nil];
}

[self resizeSubviewsWithOldSize:[self frame].size];
}

#pragma mark Managing the Selection

- (void)setSelectionIndex:(NSInteger)newIndex
{
if (newIndex >= [[_scrollLayer sublayers] count] || newIndex < 0) {
return;
}

if ([[NSApp currentEvent] modifierFlags] & (NSAlphaShiftKeyMask|NSShiftKeyMask))
[CATransaction setValue:[NSNumber numberWithFloat:2.1f] forKey:@"animationDuration"];
else
[CATransaction setValue:[NSNumber numberWithFloat:0.7f] forKey:@"animationDuration"];

_selectionIndex = newIndex;
[_scrollLayer layoutIfNeeded];

CALayer *layer = [[_scrollLayer sublayers] objectAtIndex:self.selectionIndex];
CGRect layerFrame = [layer frame];

// Scroll so the selected item is centered
[_scrollLayer scrollToPoint:CGPointMake([self _positionOfSelectedItem], layerFrame.origin.y)];
[_scroller setIntegerValue:self.selectionIndex];
}

- (id)selectedObject
{
if ([self.content count] == 0 || self.selectionIndex >= [self.content count]) {
return nil;
}

return [self.content objectAtIndex:self.selectionIndex];
}

- (void)setSelectedObject:(id)anObject
{
if (![self.content containsObject:anObject]) {
NSLog(@"[MBCoverFlowView setSelectedObject:] -- The view does not contain the specified object.");
return;
}

[self _setSelectionIndex:[self.content indexOfObject:anObject]];
}

#pragma mark Layout Support

- (NSInteger)indexOfItemAtPoint:(NSPoint)aPoint
{
// Check the selected item first
if (NSPointInRect(aPoint, [self rectForItemAtIndex:self.selectionIndex])) {
return self.selectionIndex;
}

// Check the items to the left, in descending order
NSInteger index = self.selectionIndex-1;
while (index >= 0) {
NSRect layerRect = [self rectForItemAtIndex:index];
if (NSPointInRect(aPoint, layerRect)) {
return index;
}
index--;
}

// Check the items to the right, in ascending order
index = self.selectionIndex+1;
while (index < [self.content count]) {
NSRect layerRect = [self rectForItemAtIndex:index];
if (NSPointInRect(aPoint, layerRect)) {
return index;
}
index++;
}

return NSNotFound;
}

// FIXME: The frame returned is not quite wide enough. Don't know why -- probably due to the transforms
- (NSRect)rectForItemAtIndex:(NSInteger)index
{
if (index < 0 || index >= [self.content count]) {
return NSZeroRect;
}

CALayer *layer = [self _layerForObject:[self.content objectAtIndex:index]];
CALayer *imageLayer = [[layer sublayers] objectAtIndex:0];

CGRect frame = [imageLayer convertRect:[imageLayer frame] toLayer:self.layer];
return NSRectFromCGRect(frame);
}

#pragma mark -
#pragma mark Private Methods

- (CALayer *)_insertLayerInScrollLayer
{
/* this enables a perspective transform. The value of zDistance
affects the sharpness of the transform */
float zDistance = 420.;
CATransform3D sublayerTransform = CATransform3DIdentity;
sublayerTransform.m34 = 1. / -zDistance;

CALayer *layer = [CALayer layer];
CALayer *imageLayer = [CALayer layer];

CGRect frame;
frame.origin = CGPointZero;
frame.size = NSSizeToCGSize([self itemSize]);

[imageLayer setBounds:frame];
imageLayer.contents = (id)_placeholderRef;
imageLayer.name = @"image";

[layer setBounds:frame];
[layer setValue:[NSNumber numberWithInteger:[[_scrollLayer sublayers] count]] forKey:@"index"];
[layer setSublayers:[NSArray arrayWithObject:imageLayer]];
[layer setSublayerTransform:sublayerTransform];
[layer setValue:[NSNumber numberWithBool:NO] forKey:@"hasImage"];

CALayer *reflectionLayer = [CALayer layer];
frame.origin.y = -frame.size.height;
[reflectionLayer setFrame:frame];
reflectionLayer.name = @"reflection";
reflectionLayer.transform = CATransform3DMakeScale(1, -1, 1);
reflectionLayer.contents = (id)_placeholderRef;
[imageLayer addSublayer:reflectionLayer];

CALayer *gradientLayer = [CALayer layer];
frame.origin.y += frame.size.height;
frame.origin.x -= 1.0;
frame.size.height += 2.0;
frame.size.width += 2.0;
[gradientLayer setFrame:frame];
[gradientLayer setContents:(id)_shadowImage];
gradientLayer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable;
[reflectionLayer addSublayer:gradientLayer];

[_scrollLayer addSublayer:layer];

return layer;
}

- (float)_positionOfSelectedItem
{
// this is the same math used in layoutSublayersOfLayer:, before tweaking
return floor(MBCoverFlowViewHorizontalMargin + .5*([_scrollLayer bounds].size.width - [self itemSize].width * [[_scrollLayer sublayers] count] - MBCoverFlowViewCellSpacing * ([[_scrollLayer sublayers] count] - 1))) + self.selectionIndex * ([self itemSize].width + MBCoverFlowViewCellSpacing) - .5 * [_scrollLayer bounds].size.width + .5 * [self itemSize].width;
}

- (void)_scrollerChange:(MBCoverFlowScroller *)sender
{
NSScrollerPart clickedPart = [sender hitPart];
if (clickedPart == NSScrollerIncrementLine) {
[self _setSelectionIndex:(self.selectionIndex + 1)];
} else if (clickedPart == NSScrollerDecrementLine) {
[self _setSelectionIndex:(self.selectionIndex - 1)];
} else if (clickedPart == NSScrollerKnob) {
[self _setSelectionIndex:[sender integerValue]];
}
}

- (void)_refreshLayer:(CALayer *)layer
{
NSObject *object = [layer valueForKey:@"representedObject"];
NSInteger index = [self.content indexOfObject:object];

[layer setValue:[NSNumber numberWithInteger:index] forKey:@"index"];
[layer setValue:[NSNumber numberWithBool:NO] forKey:@"hasImage"];

// Create the operation
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_loadImageForLayer:) object:layer];
[_imageLoadQueue addOperation:operation];
[operation release];
}

- (void)_loadImageForLayer:(CALayer *)layer
{
@try {
NSImage *image;
NSObject *object = [layer valueForKey:@"representedObject"];

if (self.imageKeyPath != nil) {
image = [object valueForKeyPath:self.imageKeyPath];
} else if ([object isKindOfClass:[NSImage class]]) {
image = (NSImage *)object;
}

if ([image isKindOfClass:[NSData class]]) {
image = [[[NSImage alloc] initWithData:(NSData *)image] autorelease];
}

CGImageRef imageRef;

if (!image) {
imageRef = CGImageRetain(_placeholderRef);
[layer setValue:[NSNumber numberWithBool:NO] forKey:@"hasImage"];
} else {
imageRef = [image imageRefCopy];
[layer setValue:[NSNumber numberWithBool:YES] forKey:@"hasImage"];
}

CALayer *imageLayer = [[layer sublayers] objectAtIndex:0];
CALayer *reflectionLayer = [[imageLayer sublayers] objectAtIndex:0];

imageLayer.contents = (id)imageRef;
reflectionLayer.contents = (id)imageRef;
imageLayer.backgroundColor = NULL;
reflectionLayer.backgroundColor = NULL;
CGImageRelease(imageRef);
} @catch (NSException *e) {
// If the key path isn't valid, do nothing
}
}

- (CALayer *)_layerForObject:(id)object
{
for (CALayer *layer in [_scrollLayer sublayers]) {
if ([object isEqual:[layer valueForKey:@"representedObject"]]) {
return layer;
}
}
return nil;
}

- (void)_recachePlaceholder
{
CGImageRelease(_placeholderRef);

NSSize itemSize = self.itemSize;
NSSize placeholderSize;
placeholderSize.height = MBCoverFlowViewPlaceholderHeight;
placeholderSize.width = itemSize.width * placeholderSize.height/itemSize.height;

NSImage *placeholder = [[NSImage alloc] initWithSize:placeholderSize];
[placeholder lockFocus];
NSColor *topColor = [NSColor colorWithCalibratedWhite:0.15 alpha:1.0];
NSColor *bottomColor = [NSColor colorWithCalibratedWhite:0.0 alpha:1.0];
NSGradient *gradient = [[NSGradient alloc] initWithStartingColor:topColor endingColor:bottomColor];
[gradient drawInRect:NSMakeRect(0, 0, placeholderSize.width, placeholderSize.height) relativeCenterPosition:NSMakePoint(0, 1)];
[gradient release];

// Draw the top bevel line
NSColor *bevelColor = [NSColor colorWithCalibratedWhite:0.3 alpha:1.0];
[bevelColor set];
NSRectFill(NSMakeRect(0, placeholderSize.height-5.0, placeholderSize.width, 5.0));

NSColor *bottomBevelColor = [NSColor colorWithCalibratedWhite:0.1 alpha:1.0];
[bottomBevelColor set];
NSRectFill(NSMakeRect(0, 0, placeholderSize.width, 5.0));

// Draw the placeholder icon
if (self.placeholderIcon) {
NSRect iconRect;
iconRect.size.height = placeholderSize.height/2;
iconRect.size.width = iconRect.size.height * [self placeholderIcon].size.width/[self placeholderIcon].size.height;

if (iconRect.size.width > placeholderSize.width * 0.666) {
iconRect.size.width = placeholderSize.width/2;
iconRect.size.height = iconRect.size.width * [self placeholderIcon].size.height/[self placeholderIcon].size.width;
}

iconRect.origin.x = (placeholderSize.width - iconRect.size.width)/2;
iconRect.origin.y = (placeholderSize.height - iconRect.size.height)/2;

NSImage *icon = [[NSImage alloc] initWithSize:iconRect.size];
[icon lockFocus];
NSColor *iconTopColor = [NSColor colorWithCalibratedRed:0.380 green:0.400 blue:0.427 alpha:1.0];
NSColor *iconBottomColor = [NSColor colorWithCalibratedRed:0.224 green:0.255 blue:0.302 alpha:1.0];
NSGradient *iconGradient = [[NSGradient alloc] initWithStartingColor:iconTopColor endingColor:iconBottomColor];
[iconGradient drawInRect:NSMakeRect(0, 0, iconRect.size.width, iconRect.size.width) angle:-90.0];
[iconGradient release];
[self.placeholderIcon drawInRect:NSMakeRect(0, 0, iconRect.size.width, iconRect.size.height) fromRect:NSZeroRect operation:NSCompositeDestinationIn fraction:1.0];
[icon unlockFocus];

[icon drawInRect:iconRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
[icon release];
}

[placeholder unlockFocus];

_placeholderRef = [placeholder imageRefCopy];

// Update the placeholder for all necessary items
for (CALayer *layer in [_scrollLayer sublayers]) {
if (![[layer valueForKey:@"hasImage"] boolValue]) {
CALayer *imageLayer = [[self.layer sublayers] objectAtIndex:0];
CALayer *reflectionLayer = [[imageLayer sublayers] objectAtIndex:0];
imageLayer.contents = (id)_placeholderRef;
reflectionLayer.contents = (id)_placeholderRef;
}
}

[placeholder release];
}

- (void)_setSelectionIndex:(NSInteger)index
{
if (index < 0) {
index = 0;
} else if (index >= [self.content count]) {
index = [self.content count] - 1;
}

if ([self infoForBinding:@"selectionIndex"]) {
id container = [[self infoForBinding:@"selectionIndex"] objectForKey:NSObservedObjectKey];
NSString *keyPath = [[self infoForBinding:@"selectionIndex"] objectForKey:NSObservedKeyPathKey];
[container setValue:[NSNumber numberWithInteger:index] forKey:keyPath];
return;
}

self.selectionIndex = index;
}

#pragma mark -
#pragma mark Protocol Methods

#pragma mark CALayoutManager

- (void)layoutSublayersOfLayer:(CALayer *)layer
{
float margin = floor(MBCoverFlowViewHorizontalMargin + ([layer bounds].size.width - [self itemSize].width * [[layer sublayers] count] - MBCoverFlowViewCellSpacing * ([[layer sublayers] count]-1)) * 0.5);

for (CALayer *sublayer in [layer sublayers]) {
CALayer *imageLayer = [[sublayer sublayers] objectAtIndex:0];
CALayer *reflectionLayer = [[imageLayer sublayers] objectAtIndex:0];

NSUInteger index = [[sublayer valueForKey:@"index"] integerValue];
CGRect frame;
frame.size = NSSizeToCGSize([self itemSize]);
frame.origin.x = margin + index * ([self itemSize].width + MBCoverFlowViewCellSpacing);
frame.origin.y = frame.size.height;

CGRect imageFrame = frame;
imageFrame.origin = CGPointZero;

CGRect reflectionFrame = imageFrame;
reflectionFrame.origin.y = -frame.size.height;

CGRect gradientFrame = reflectionFrame;
gradientFrame.origin.y = 0;

// Create the perspective effect
if (index < self.selectionIndex) {
// Left
frame.origin.x += [self itemSize].width * MBCoverFlowViewPerspectiveSideSpacingFactor * (float)(self.selectionIndex - index - MBCoverFlowViewPerspectiveRowScaleFactor);
imageLayer.transform = _leftTransform;
imageLayer.zPosition = MBCoverFlowViewPerspectiveSidePosition;
sublayer.zPosition = MBCoverFlowViewPerspectiveSidePosition - 0.1 * (self.selectionIndex - index);
} else if (index > self.selectionIndex) {
// Right
frame.origin.x -= [self itemSize].width * MBCoverFlowViewPerspectiveSideSpacingFactor * (float)(index - self.selectionIndex - MBCoverFlowViewPerspectiveRowScaleFactor);
imageLayer.transform = _rightTransform;
imageLayer.zPosition = MBCoverFlowViewPerspectiveSidePosition;
sublayer.zPosition = MBCoverFlowViewPerspectiveSidePosition - 0.1 * (index - self.selectionIndex);
} else {
// Center
imageLayer.transform = CATransform3DIdentity;
imageLayer.zPosition = MBCoverFlowViewPerspectiveCenterPosition;
sublayer.zPosition = MBCoverFlowViewPerspectiveSidePosition;
}

[sublayer setFrame:frame];
[imageLayer setFrame:imageFrame];
[reflectionLayer setFrame:reflectionFrame];
[reflectionLayer setBounds:CGRectMake(0, 0, [reflectionLayer bounds].size.width, [reflectionLayer bounds].size.height)];
}
}

#pragma mark NSKeyValueObserving

+ (NSSet *)keyPathsForValuesAffectingSelectedObject
{
return [NSSet setWithObjects:@"selectionIndex", nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &MBCoverFlowViewImagePathContext) {
[self _refreshLayer:[self _layerForObject:object]];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}

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