/*
SRAppDelegate.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 "SRAppController.h"
#import "SRApplication.h"
#import "SRTabExposeController.h"

#import "SRMenu.h"

#import "SRPrefDefaultKeys.h"
#import "SRKeyBindingPref.h"

@implementation SRApplication

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

- (id)init
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _isKeyBindingEditing = NO;
    _keyBindingController = nil;
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyBindingStartEditing:) 
            name:SRKeyBindingStartEditing object:nil];
    [center addObserver:self selector:@selector(keyBindingEndEditing:) 
            name:SRKeyBindingEndEditing object:nil];
    
    return self;
}

- (void)dealloc
{
    // Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Event handling --
//--------------------------------------------------------------//

- (void)sendEvent:(NSEvent*)event
{
    // Check current mode
    if (![SRTabExposeController isExposing] && !_isKeyBindingEditing) {
        [super sendEvent:event];
        return;
    }
    
    // Get event type
    NSEventType type;
    type = [event type];
    
    // For tab expose
    if ([SRTabExposeController isExposing]) {
        // Pass mouse move event to expose controller
        if (type == NSMouseMoved) {
            [[SRTabExposeController currentController] mouseMoved:event];
            return;
        }
        
        // Ignore key event except deexpose request
        if (type == NSKeyDown || type == NSKeyUp) {
            // Get expose character
            NSString*   keyEquivalent;
            unichar     c;
            keyEquivalent = [[SRWindowMenu() itemWithTag:SRShowAllTabsTag] 
                    keyEquivalent];
            c = [keyEquivalent characterAtIndex:0];
            
            // Deexpose
            if ([[event characters] characterAtIndex:0] == c) {
                [super sendEvent:event];
                return;
            }
            
            // Ignore key event
            return;
        }
    }
    
    // For key binding editing
    if (_isKeyBindingEditing && _keyBindingController) {
        // For key down
        if (type == NSKeyDown) {
            // Get characters
            NSString*       characters;
            characters = [event charactersIgnoringModifiers];
            if ([characters length] > 0) {
                // Get unichar and modifier flags
                unichar         ch;
                unsigned int    flags;
                ch = [characters characterAtIndex:0];
                flags = [event modifierFlags];
                
                // Check shift key
                static NSCharacterSet*  _charactersWithShiftKey = nil;
                if (!_charactersWithShiftKey) {
                    _charactersWithShiftKey = [[NSCharacterSet 
                            characterSetWithCharactersInString:@"`~!@#$%^&()_{}|\":<>?=/*-+.'"] retain];
                }
                if ([_charactersWithShiftKey characterIsMember:ch] && (flags & NSShiftKeyMask)) {
                    flags ^= NSShiftKeyMask;
                }
                
                // Set new key binding
                [_keyBindingController setKeyBindingWithKeyEquivalent:characters modifierFlags:flags];
            }
            
            return;
        }
    }
    
    [super sendEvent:event];
}

- (BOOL)_handleKeyEquivalent:(NSEvent*)event
{
    BOOL    result;
    result = [super _handleKeyEquivalent:event];
    if (!result) {
        // Send to application delegate
        id  delegate;
        delegate = [self delegate];
        if (delegate && [delegate respondsToSelector:@selector(performKeyEquivalent:)]) {
            result = [delegate performKeyEquivalent:event];
        }
    }
    
    return result;
}

//--------------------------------------------------------------//
#pragma mark -- About panel --
//--------------------------------------------------------------//

- (void)orderFrontStandardAboutPanel:(id)sender
{
    if ([[self delegate] respondsToSelector:@selector(orderFrontStandardAboutPanel:)]) {
        [[self delegate] orderFrontStandardAboutPanel:sender];
    }
}

//--------------------------------------------------------------//
#pragma mark -- SRKeyBindingPref notification --
//--------------------------------------------------------------//

- (void)keyBindingStartEditing:(NSNotification*)notification
{
    // Set key binding editing mode
    _isKeyBindingEditing = YES;
    _keyBindingController = [notification object];
}

- (void)keyBindingEndEditing:(NSNotification*)notification
{
    // Clear key binding editing mode
    _isKeyBindingEditing = NO;
    _keyBindingController = nil;
}

@end
