/*
SRKeyBindingPref.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 "SRPrefDefaultKeys.h"
#import "SRKeyBindingPref.h"
#import "SRKeyBindingCell.h"

@interface SRKeyBindingPref (private)

// Menu key binding management
- (void)_updateMenuOutlineAsCurrent;

// Appeararnce
- (void)_clearMessage;

@end

@implementation SRKeyBindingPref

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

- (id)initWithBundle:(NSBundle*)bundle
{
    self = [super initWithBundle:bundle];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _usedKeyBindingDict = [[NSMutableDictionary dictionary] retain];
    
    // Update menu key bindings
    [self _updateMenuOutlineAsCurrent];
    
    return self;
}

- (void)awakeFromNib
{
    // Configure outline
    [_menuOutlineView setAutoresizesOutlineColumn:NO];
    
    // Set data cell
    NSTableColumn*  column;
    id                  oldCell;
    SRKeyBindingCell*   cell;
    column = [_menuOutlineView tableColumnWithIdentifier:@"key"];
    oldCell = [column dataCell];
    cell = [[SRKeyBindingCell alloc] init];
    [cell setFont:[oldCell font]];
    [column setDataCell:cell];
    [cell release];
    
    // Set content values
    id  content;
    content = [_objectController content];
    [content setValue:[NSNumber numberWithBool:NO] forKey:@"keyDeletable"];
    [content setValue:@"" forKey:@"message"];
}

- (void)dealloc
{
    [_usedKeyBindingDict release], _usedKeyBindingDict = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Menu key binding management --
//--------------------------------------------------------------//

- (void)setKeyBindingWithKeyEquivalent:(NSString*)keyEquivalent modifierFlags:(unsigned int)flags
{
    // Check modifier flags
    if (!(flags & NSCommandKeyMask)) {
        // Show message
        [[_objectController content] setValue:NSLocalizedString(@"A key binding requires command key", nil) 
                forKey:@"message"];
        return;
    }
    
    // Create key string
    NSString*   key;
    key = [HMKeyBinding visibleKeyBindingWithKeyEquivalent:keyEquivalent modifierFlags:flags];
    
    // Find in used key bindings
    NSString*   title;
    title = [_usedKeyBindingDict objectForKey:key];
    if (title) {
        // Show message
        NSString*   message;
        message = [NSString stringWithFormat:NSLocalizedString(@"%@ is used by '%@'", nil), key, title];
        
        [[_objectController content] setValue:message forKey:@"message"];
        return;
    }
    
    // Get editing menu item
    int                     row;
    NSMutableDictionary*    dict;
    NSMenuItem*             menuItem = nil;
    row = [_menuOutlineView selectedRow];
    if (row > 0) {
        dict = [[_menuOutlineView itemAtRow:row] performSelector:@selector(observedObject)];
        menuItem = [dict objectForKey:@"menuItem"];
    }
    if (!menuItem) {
        return;
    }
    
    // Get old key string
    NSString*       oldKey = nil;
    NSString*       oldKeyEquivalent;
    unsigned int    oldFlags;
    oldKeyEquivalent = [menuItem keyEquivalent];
    oldFlags = [menuItem keyEquivalentModifierMask];
    if ([oldKeyEquivalent length] > 0) {
        oldKey = [HMKeyBinding visibleKeyBindingWithKeyEquivalent:oldKeyEquivalent modifierFlags:oldFlags];
    }
    
    // Set key equivalent and modifier flags
    [menuItem setKeyEquivalent:keyEquivalent];
    [menuItem setKeyEquivalentModifierMask:flags];
    
    // Update outline
    [dict setObject:key forKey:@"key"];
    [_menuOutlineView reloadData];
    [[_menuOutlineView window] makeFirstResponder:_menuOutlineView];
    
    // Update used key bindings
    if (oldKey) {
        if ([_usedKeyBindingDict objectForKey:oldKey]) {
            [_usedKeyBindingDict removeObjectForKey:oldKey];
        }
    }
    
    title = [menuItem title];
    if ([title length] > 0) {
        [_usedKeyBindingDict setObject:title forKey:key];
    }
    
    // Clear message
    [self _clearMessage];
}

- (void)_updateMenuOutlineWithMenu:(NSMenu*)menu intoArray:(NSMutableArray*)array
{
    // Get menu items
    NSEnumerator*   enumerator;
    NSMenuItem*     menuItem;
    enumerator = [[menu itemArray] objectEnumerator];
    while (menuItem = [enumerator nextObject]) {
        // For separator
        if ([menuItem isSeparatorItem]) {
            continue;
        }
        
        // For submenu
        if ([menuItem hasSubmenu]) {
            // Create item
            NSMutableDictionary*    item;
            item = [NSMutableDictionary dictionary];
            
            // Get title
            NSString*   title = nil;
            if ([menuItem tag] == 100 /*SRShiiraTag*/) {
                // For appication menu
                title = [[[NSBundle bundleForClass:NSClassFromString(@"SRApplication")] 
                        infoDictionary] objectForKey:@"CFBundleName"];
            }
            else {
                title = [menuItem title];
            }
            if ([title length] == 0) {
                continue;
            }
            
            [item setObject:title forKey:@"action"];
            
            // Update with submenu
            NSMutableArray* children;
            children = [NSMutableArray array];
            [self _updateMenuOutlineWithMenu:[menuItem submenu] intoArray:children];
            if ([children count] == 0) {
                continue;
            }
            
            // Add children
            [item setObject:children forKey:@"children"];
            
            // Add item
            [array addObject:item];
            continue;
        }
        
        // Check action
        NSString*   actionStr;
        actionStr = NSStringFromSelector([menuItem action]);
        if (actionStr && [SRExceptionActions() containsObject:actionStr]) {
            continue;
        }
        
        // Get title
        NSString*   title;
        title = [menuItem title];
        if (!title || [title length] == 0) {
            continue;
        }
        
        // Get modifier key
        NSString*       keyEquivalent;
        unsigned int    flags;
        keyEquivalent = [menuItem keyEquivalent];
        flags = [menuItem keyEquivalentModifierMask];
        
        // Create outline item
        NSMutableDictionary*    item;
        NSString*               key = nil;
        item = [NSMutableDictionary dictionary];
        [item setObject:menuItem forKey:@"menuItem"];
        [item setObject:title forKey:@"action"];
        if ([keyEquivalent length] > 0) {
            key = [HMKeyBinding visibleKeyBindingWithKeyEquivalent:keyEquivalent modifierFlags:flags];
            [item setObject:key forKey:@"key"];
        }
        
        // Set to used key bindings dictionary
        if (key) {
            [_usedKeyBindingDict setObject:title forKey:key];
        }
        
        // Add item
        [array addObject:item];
    }
}

- (void)_updateMenuOutlineAsCurrent
{
    // Get content
    id  content;
    content = [_menuTreeController content];
    [content removeAllObjects];
    
    // Remove old used key bindings
    [_usedKeyBindingDict removeAllObjects];
    
    // Update with main menu
    [self _updateMenuOutlineWithMenu:[[NSApplication sharedApplication] mainMenu] 
            intoArray:content];
    [_menuOutlineView reloadData];
    
    // Reserve 'cmd+1' to 'cmd+0' for bookmark
    int i;
    for (i = 0; i < 10; i++) {
        NSString*   key;
        key = [HMKeyBinding visibleKeyBindingWithKeyEquivalent:[NSString stringWithFormat:@"%d", i] 
                modifierFlags:NSCommandKeyMask];
        [_usedKeyBindingDict setObject:NSLocalizedString(@"Bookmark", nil) forKey:key];
    }
}

//--------------------------------------------------------------//
#pragma mark -- Appearance --
//--------------------------------------------------------------//

- (void)_clearMessage
{
    // Clear message
    id  content;
    content = [_objectController content];
    if ([[content valueForKey:@"message"] length] > 0) {
        [content setValue:@"" forKey:@"message"];
    }
}

//--------------------------------------------------------------//
#pragma mark -- Action --
//--------------------------------------------------------------//

- (void)deleteKeyBindingAction:(id)sender
{
    // Delete current key binding
    [self setKeyBindingWithKeyEquivalent:@"" modifierFlags:0];
}

//--------------------------------------------------------------//
#pragma mark -- NSOutlineView delegate --
//--------------------------------------------------------------//

- (BOOL)outlineView:(NSOutlineView*)outlineView 
        shouldEditTableColumn:(NSTableColumn*)tableColumn 
        item:(id)item
{
    // Do't allow edit submenu
    if ([outlineView isExpandable:item]) {
        return NO;
    }
    
    // Make delete button enable
    id  content;
    content = [_objectController content];
    [content setValue:[NSNumber numberWithBool:YES] forKey:@"keyDeletable"];
    
    // Notify to start key binding editing
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRKeyBindingStartEditing object:self];
    
    return YES;
}

- (void)outlineViewEndEditing:(NSOutlineView*)outlineView
{
    // Make delete button disable
    id  content;
    content = [_objectController content];
    [content setValue:[NSNumber numberWithBool:NO] forKey:@"keyDeletable"];
    
    // Notify to end key binding editing
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRKeyBindingEndEditing object:self];
}

- (void)outlineViewSelectionDidChange:(NSNotification*)notification
{
    // Clear message
    [self _clearMessage];
}

@end
