Source

Murky / Source / IconTextCell.m

Full commit
//
//  IconTextCell.m
//  Murky
//
//  Created by David Keegan on 1/5/10.
//  Copyright 2010 InScopeApps{+}. All rights reserved.
//

#import "IconTextCell.h"

void defineTextAndIconRects(NSRect cellRect, NSRect *imageRect, NSRect *stringRect, CGFloat stringHeight);

@implementation IconTextCell

@synthesize icon;

- (id)init {
    self = [super initTextCell:@""];
	
	self.icon = nil;
	
    [self setEditable:YES];
    [self setScrollable:YES];
    [self setLineBreakMode:NSLineBreakByTruncatingTail];
    
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
	IconTextCell *copy = [[IconTextCell allocWithZone:zone] init];
	[copy setAttributedStringValue:[self attributedStringValue]];
	[copy setIcon:self.icon];
	return copy;
}

- (NSColor *)textColor {
	if([self isHighlighted])
	{
		return [NSColor selectedMenuItemTextColor];
	}
	else
	{
		return [NSColor controlTextColor];
	}
}

- (void)drawInteriorWithFrame:(NSRect)aRect inView:(NSView *)controlView {
	NSRect imgRect, strRect;
	CGFloat strHeight = [[self attributedStringValue] size].height;
	defineTextAndIconRects(aRect, &imgRect, &strRect, strHeight);
	
	if([[self controlView] isFlipped])
	{
		[self.icon setFlipped:YES];
	}
	[self.icon drawInRect:imgRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0f];
	
	[[self attributedStringValue] drawInRect:strRect];
}

- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {
	NSRect imgRect, strRect;
	CGFloat strHeight = [[self attributedStringValue] size].height;
	defineTextAndIconRects(aRect, &imgRect, &strRect, strHeight);
	
	[super selectWithFrame:strRect inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
	[textObj setTextColor:[NSColor controlTextColor]];
}

- (void)setObjectValue:(id <NSCopying, NSObject>)object {
	// change this part to suit your own use...
	if([object isKindOfClass:[NSDictionary class]])
	{
		[self setStringValue:[(NSDictionary *)object valueForKey:@"name"]];
		[self setIcon:[NSUnarchiver unarchiveObjectWithData:[(NSDictionary *)object valueForKey:@"image"]]];
	}
	else
	{
		[super setObjectValue:object];
	}
	
}

- (void)dealloc {
	[icon release];
	[super dealloc];
}

@end

void defineTextAndIconRects(NSRect cellRect, NSRect *imageRect, NSRect *stringRect, CGFloat stringHeight) {
	CGFloat cellHeight = cellRect.size.height;
	
	NSDivideRect(cellRect, imageRect, stringRect, cellHeight, NSMinXEdge);
	
	*imageRect = NSInsetRect(*imageRect, 2.0f, 2.0f);
	*stringRect = NSInsetRect(*stringRect, 2.0f, 0.0f);
	
	stringRect -> origin.y += (stringRect -> size.height - stringHeight) / 2.0f;
	stringRect -> size.height = stringHeight;
}