/*
SRToolbarItem.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 "SRBrowserController.h"
#import "SRPageController.h"

#import "SRToolbarItem.h"

// Consntant
int SRToobarItemMaxMenuNumber = 128;

@implementation SRToolbarItemViewerEx

static NSTimer* _timer;

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

+ (void)load
{
    [self poseAsClass:[NSToolbarItemViewer class]];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_timer invalidate], _timer = nil;
    
    [super dealloc];
}

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

- (BOOL)_hasMenu
{
    // Create array of identifier which have menu
    static NSArray* _menuItemIdentifiers = nil;
    if (!_menuItemIdentifiers) {
        _menuItemIdentifiers = [[NSArray arrayWithObjects:
            SRBrowserGoBackItem, SRBrowserGoForwardItem, nil] retain];
    }
    
    // Check identifier
    id  item = nil;
    id  itemIdentifier = nil;
    if ([self respondsToSelector:@selector(item)]) {
        item = [self item];
        if ([item respondsToSelector:@selector(itemIdentifier)]) {
            itemIdentifier = [item itemIdentifier];
        }
    }
    if (![_menuItemIdentifiers containsObject:itemIdentifier]) {
        return NO;
    }
    
    // Check is enabled
    if (![item isEnabled]) {
        return NO;
    }
    
    return YES;
}

- (NSMenu*)_menu
{
    // Get identifier
    id  itemIdentifier = nil;
    if ([self respondsToSelector:@selector(item)]) {
        id  item;
        item = [self item];
        if ([item respondsToSelector:@selector(itemIdentifier)]) {
            itemIdentifier = [item itemIdentifier];
        }
    }
    if (!itemIdentifier) {
        return nil;
    }
    
    // Create menu
    NSMenu* menu;
    menu = [[NSMenu alloc] init];
    [menu setDelegate:self];
    [menu autorelease];
    
    return menu;
}

- (NSMenu*)menuForEvent:(NSEvent*)event
{
    if (![self _hasMenu]) {
        return [super menuForEvent:event];
    }
    
    return [self _menu];
}

- (void)_showMenu
{
    // Get menu
    NSMenu* menu;
    menu = [self _menu];
    if (!menu) {
        return;
    }
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(_menuDidEndTracking:) 
            name:NSMenuDidEndTrackingNotification object:menu];
    
    // Set highlight
    [self _setHighlighted:YES displayNow:YES];
    
    // 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];
}

- (void)mouseDown:(NSEvent*)event
{
    // Check has menu
    if (![self _hasMenu]) {
        [super mouseDown:event];
        return;
    }
    
    // Highlight itself
    if ([self respondsToSelector:@selector(_setHighlighted:displayNow:)]) {
        [self _setHighlighted:YES displayNow:YES];
    }
    
    // Start timer
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5f 
            target:self selector:@selector(_timerFired:) userInfo:nil repeats:NO];
}

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

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

- (void)_menuDidEndTracking:(NSNotification*)notification
{
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    
    // Remove notification
    [center removeObserver:self 
            name:NSMenuDidEndTrackingNotification 
            object:[notification object]];
    
    // Make highlight off
    if ([self respondsToSelector:@selector(_setHighlighted:displayNow:)]) {
        [self _setHighlighted:NO displayNow:YES];
    }
}

//--------------------------------------------------------------//
#pragma mark -- NSMenu delegate --
//--------------------------------------------------------------//

- (int)numberOfItemsInMenu:(NSMenu*)menu
{
    // Get web view
    id          windowController;
    WebView*    webView = nil;
    windowController = [[self window] windowController];
    if ([windowController isKindOfClass:[SRBrowserController class]]) {
        webView = [[windowController selectedPageController] webView];
    }
    if (!webView) {
        return nil;
    }
    
    // Get back or forward list count
    id  identifier;
    int number = 0;
    identifier = [[self item] itemIdentifier];
    if ([identifier isEqualToString:SRBrowserGoBackItem]) {
        number = [[webView backForwardList] backListCount];
    }
    if ([identifier isEqualToString:SRBrowserGoForwardItem]) {
        number = [[webView backForwardList] forwardListCount];
    }
    
    if (number > SRToobarItemMaxMenuNumber) {
        number = SRToobarItemMaxMenuNumber;
    }
    
    return number;
}

- (BOOL)menu:(NSMenu*)menu updateItem:(NSMenuItem*)item 
        atIndex:(int)index shouldCancel:(BOOL)shouldCancel
{
    // Get web view
    id          windowController;
    WebView*    webView = nil;
    windowController = [[self window] windowController];
    if ([windowController isKindOfClass:[SRBrowserController class]]) {
        webView = [[windowController selectedPageController] webView];
    }
    if (!webView) {
        return nil;
    }
    
    // Get history item
    id              identifier;
    WebHistoryItem* historyItem = nil;
    identifier = [[self item] itemIdentifier];
    if ([identifier isEqualToString:SRBrowserGoBackItem]) {
        historyItem = [[webView backForwardList] itemAtIndex:-1 * (index + 1)];
    }
    if ([identifier isEqualToString:SRBrowserGoForwardItem]) {
        historyItem = [[webView backForwardList] itemAtIndex:index + 1];
    }
    
    if (!historyItem) {
        return NO;
    }
    
    // Update menu item
    NSString*   title;
    title = [historyItem title];
    if (!title || [title length] == 0) {
        title = [historyItem URLString];
    }
    if (!title || [title length] == 0) {
        title = NSLocalizedString(@"(Untitled)", nil);
    }
    title = HMTruncateString(title, 64, NSLineBreakByTruncatingTail);
    [item setTitle:title];
    [item setImage:[historyItem icon]];
    [item setAction:@selector(openHistoryItemAction:)];
    [item setRepresentedObject:historyItem];
    
    return YES;
}

@end

#pragma mark -

@implementation SRToolbarViewEx

+ (void)load
{
    [self poseAsClass:[NSToolbarView class]];
}

- (NSMenu*)menuForEvent:(NSEvent*)event
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    NSMenu* menu;
    menu = [super menuForEvent:event];
    
    id<NSMenuItem>  item;
    
    // Check toolbar display mode
    NSToolbarDisplayMode    displayMode;
    displayMode = [_toolbar displayMode];
    if (displayMode != 0) {
        item = [menu itemWithTag:displayMode];
        if (item && [item state] != NSOnState) {
            [item setState:NSOnState];
        }
    }
    
    // Check toolbar size mode
    NSToolbarSizeMode   sizeMode;
    sizeMode = [_toolbar sizeMode];
    if (sizeMode == NSToolbarSizeModeSmall) {
        item = [menu itemAtIndex:4]; // Menu item for size mode
        if (item && [item state] != NSOnState) {
            [item setState:NSOnState];
        }
    }
    
    return menu;
}

@end
