BWToolkit / BWToolbarPullDownItem.m

Full commit
//  BWToolbarPullDownItem.m
//  BWToolkit
//  Created by Mike Abdullah on 14/01/2010.
//  All code is provided under the New BSD license.

#import "BWToolbarPullDownItem.h"

#import "BWIWorkPopUpButton.h"

@implementation BWToolbarPullDownItem

- (id)initWithItemIdentifier:(NSString *)itemIdentifier;
    [super initWithItemIdentifier:itemIdentifier];
    // Prepare basic pull-down button
    _popUpButton = [[BWIWorkPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:YES];
    NSPopUpButtonCell *cell = [_popUpButton cell];
    [_popUpButton setBezelStyle:NSSmallSquareBezelStyle];   // otherwise menu covers bottom bit of button
    [cell setArrowPosition:NSPopUpArrowAtBottom];
    [_popUpButton setBordered:NO];
    [cell setImageScaling:NSImageScaleProportionallyDown];
    [_popUpButton setFont:[NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]]];
    [cell setControlSize:NSSmallControlSize];
    // Ensure there is a single item to generate cell appearance from
    if ([[_popUpButton itemArray] count] == 0) [_popUpButton addItemWithTitle:@""];
    [self setView:_popUpButton];
    return self;

- (void)dealloc
    [_popUpButton release];
    [super dealloc];

#pragma mark Properties

- (void)setImage:(NSImage *)anImage
    // NSToolbarItem would normally forward this on to its view. That would be fine, but NSPopUpButton ignores -setImage: so handle it ourself
    [[[self popUpButton] itemAtIndex:0] setImage:anImage];

- (NSSize)minSize
    NSSize result;
    result.height = ([[self toolbar] sizeMode] == NSToolbarSizeModeSmall) ? 24.0f : 32.0f;
    result.width = result.height + 8;   // to account for arrow
    return result;

@synthesize popUpButton = _popUpButton;

- (NSMenuItem *)menuFormRepresentation
    NSMenuItem *result = [super menuFormRepresentation];
    // Use a submenu to display the button's items
    NSMenu *submenu = [[[self popUpButton] menu] copy];
    [result setSubmenu:submenu];
    [submenu release];
    [result setAction:[self action]]; // otherwise submenu ony appears after mouse is held down
    return result;