/*
HMMenuButton.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "HMMenuButton.h"

@implementation HMMenuButton

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

- (void)dealloc
{
    [_timer invalidate], _timer = nil;
    [_menuFont release], _menuFont = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- One click operation --
//--------------------------------------------------------------//

- (BOOL)isOneClickOperation
{
    return _oneClickOp;
}

- (void)setOneClickOperation:(BOOL)oneClickOp
{
    _oneClickOp = oneClickOp;
}

//--------------------------------------------------------------//
#pragma mark -- Menu font --
//--------------------------------------------------------------//

- (NSFont*)menuFont
{
    return _menuFont;
}

- (void)setMenuFont:(NSFont*)menuFont
{
    [_menuFont release];
    _menuFont = [menuFont retain];
}

//--------------------------------------------------------------//
#pragma mark -- Delegate --
//--------------------------------------------------------------//

- (id)delegate
{
    return _delegate;
}

- (void)setDelegate:(id)delegate
{
    _delegate = delegate;
}

//--------------------------------------------------------------//
#pragma mark -- Menu handling --
//--------------------------------------------------------------//

- (void)_showMenuWithEvent:(NSEvent*)event
{
    // Get menu
    NSMenu* menu = nil;
    if ([_delegate respondsToSelector:@selector(menuButton:menuForEvent:)]) {
        menu = [_delegate menuButton:self menuForEvent:event];
    }
    if (!menu) {
        menu = [self menu];
    }
    if (!menu) {
        return;
    }
    
    // Set target
    id              target;
    NSEnumerator*   enumerator;
    NSMenuItem*     item;
    target = [self target];
    enumerator = [[menu itemArray] objectEnumerator];
    while (item = [enumerator nextObject]) {
        if ([item target] != target) {
            [item setTarget:target];
        }
    }
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(_menuDidEndTracking:) 
            name:NSMenuDidEndTrackingNotification object:menu];
    
    // Set highlight
    id  cell;
    cell = [self cell];
    if (![cell isHighlighted]) {
        [cell setHighlighted:YES];
    }
    
    // Decide menu font
    NSFont* menuFont;
    menuFont = _menuFont;
    if (!menuFont) {
        menuFont = [self font];
    }
    
    // Show context menu
    NSRect      frame;
    NSPoint     point;
    NSEvent*    popupEvent;
    frame = [self frame];
    if ([self isFlipped]) {
        point.x = 0;
        point.y = frame.size.height + 3;
    }
    else {
        point.x = 0;
        point.y = -3;
    }
    point = [self convertPoint:point toView:nil];
    popupEvent = [NSEvent mouseEventWithType:NSLeftMouseDown 
            location:point 
            modifierFlags:0 
            timestamp:0 
            windowNumber:[[self window] windowNumber] 
            context:[NSGraphicsContext currentContext] 
            eventNumber:0 
            clickCount:1 
            pressure:0];
    [NSMenu popUpContextMenu:menu withEvent:popupEvent forView:self withFont:menuFont];
}

- (void)mouseDown:(NSEvent*)event
{
    // Check enabled
    if (![self isEnabled]) {
        [super mouseDown:event];
        return;
    }
    
    // Check menu
    if (![self menu] && ![_delegate respondsToSelector:@selector(menuButton:menuForEvent:)]) {
        [super mouseDown:event];
        return;
    }
    
    // Start timer for one click operation
    if (_oneClickOp) {
        if ([_timer isValid]) {
            [_timer invalidate];
            _timer = nil;
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5f 
                target:self selector:@selector(_timerFired:) userInfo:nil repeats:NO];
        
        // Highlight self
        id  cell;
        cell = [self cell];
        if (![cell isHighlighted]) {
            [cell setHighlighted:YES];
            [self setNeedsDisplay:YES];
        }
        
        return;
    }
    
    // Show menu
    [self _showMenuWithEvent:event];
}

- (void)mouseUp:(NSEvent*)event
{
    // Stop timer
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
        
        // Clear highlight
        id  cell;
        cell = [self cell];
        if ([cell isHighlighted]) {
            [cell setHighlighted:NO];
            [self setNeedsDisplay:YES];
        }
        
        // Send action
        [self sendAction:[self action] to:[self target]];
        
        return;
    }
    
    [super mouseUp:event];
}

- (void)_timerFired:(NSTimer*)timer
{
    // Set nil
    _timer = nil;
    
    // Show menu
    [self _showMenuWithEvent:nil];
}

- (void)_menuDidEndTracking:(NSNotification*)notification
{
    // Clear highlight
    id  cell;
    cell = [self cell];
    if ([cell isHighlighted]) {
        [cell setHighlighted:NO];
        [self setNeedsDisplay:YES];
    }
    
    // Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
