/*
SRMainWindow.m

Author: Makoto Kinoshita

Copyright 2004 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 "SRDefaultsKey.h"

#import "SRMainWindowController.h"

#import "SRMainWindow.h"

@interface NSWindow (bottomCorner)
- (void)setBottomCornerRounded:(BOOL)flag;
@end

@implementation SRMainWindow

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

+ (NSButton*)standardWindowButton:(NSWindowButton)button 
        forStyleMask:(unsigned int)styleMask
{
    // Ignore NSWindowDocumentIconButton button
    if (button == NSWindowDocumentIconButton) {
        return nil;
    }
    
    return [super standardWindowButton:button forStyleMask:styleMask];
}

- (id)initWithContentRect:(NSRect)contentRect 
        styleMask:(unsigned int)styleMask 
        backing:(NSBackingStoreType)backingType 
        defer:(BOOL)flag
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    // Get texture type
    int texture;
    texture = [defaults integerForKey:SRIconTexture];
    
    // Set style mask
    if (texture == SRIconTextureMetal && !(styleMask & NSTexturedBackgroundWindowMask)) {
        styleMask |= NSTexturedBackgroundWindowMask;
    }
    
    // Use unified title and toolbar window
    BOOL    unified;
    unified = [defaults integerForKey:SRIconUnified];
    if (unified) {
        styleMask |= NSUnifiedTitleAndToolbarWindowMask;
    }
    
    // Invoke super
    self = [super initWithContentRect:contentRect 
        styleMask:styleMask 
        backing:backingType 
        defer:flag];
    if (!self) {
        return nil;
    }
    
    // Set bottom corner rounded
    if (texture == SRIconTextureMetal) {
        [self setBottomCornerRounded:NO];
    }
    
    return self;
}

- (BOOL)makeFirstResponder:(NSResponder *)aResponder
{
    //do not allow makeFirstResponder hidden WebView.
    //tab-ushiro de hiraite sugu tojiru to otiru bug no shuusei.
    //toriaezu otinaku natta
    //sideBar ni WebView wo tukattari suruto tyousei ga hituyou kamo??
    if([aResponder isMemberOfClass:[WebFrameView class]]){
        if([(WebFrameView*)aResponder window]!=self){
            return NO;
        }
    }
    return [super makeFirstResponder:aResponder];
}

- (BOOL)performKeyEquivalent:(NSEvent*)event
{
    if ([event type] == NSKeyDown) {
        // Get modifier flags and key code
        unsigned    modifierFlags;
        unsigned    cmdFlag, optFlag, shiftFlag;
        short       keyCode;
        NSString*   characters;
        unichar     unicodeChar = 0;
        modifierFlags = [event modifierFlags];
        cmdFlag = modifierFlags & NSCommandKeyMask;
        optFlag = modifierFlags & NSAlternateKeyMask;
        shiftFlag = modifierFlags & NSShiftKeyMask;
        keyCode = [event keyCode];
        characters = [event characters];
        if (characters && [characters length] > 0) {
            unicodeChar = [characters characterAtIndex:0];
        }
        
        // For cmd + enter
        if (cmdFlag && !optFlag && !shiftFlag && (keyCode == 0x24 /* return */ || 
                                                  keyCode == 0x4c /* enter */))
        {
            event = [NSEvent keyEventWithType:[event type] 
                    location:[event locationInWindow] 
                    modifierFlags:0 
                    timestamp:[event timestamp] 
                    windowNumber:[event windowNumber] 
                    context:[event context] 
                    characters:[event charactersIgnoringModifiers] 
                    charactersIgnoringModifiers:[event charactersIgnoringModifiers] 
                    isARepeat:[event isARepeat] 
                    keyCode:[event keyCode]];
            
            // Notifies to first reponder
            [[self firstResponder] keyDown:event];
            return YES;
        }
        
        // For cmd + enter + shift
        if (cmdFlag && !optFlag && shiftFlag && (keyCode == 0x24 /* return */ || 
                                                  keyCode == 0x4c /* enter */))
        {
            event = [NSEvent keyEventWithType:[event type] 
                    location:[event locationInWindow] 
                    modifierFlags:0 
                    timestamp:[event timestamp] 
                    windowNumber:[event windowNumber] 
                    context:[event context] 
                    characters:[event charactersIgnoringModifiers] 
                    charactersIgnoringModifiers:[event charactersIgnoringModifiers] 
                    isARepeat:[event isARepeat] 
                    keyCode:[event keyCode]];
            
            // Notifies to first reponder
            [[self firstResponder] keyDown:event];
            return YES;
        }
        
        // For cmd + '='
        if (cmdFlag && !optFlag && !shiftFlag && [characters isEqualToString:@"="]) {
            event = [NSEvent keyEventWithType:[event type] 
                    location:[event locationInWindow] 
                    modifierFlags:[event modifierFlags] 
                    timestamp:[event timestamp] 
                    windowNumber:[event windowNumber] 
                    context:[event context] 
                    characters:@"+" 
                    charactersIgnoringModifiers:@"+" 
                    isARepeat:[event isARepeat] 
                    keyCode:[event keyCode]];
            
            // Notifies to first reponder
            [[self firstResponder] keyDown:event];
            return YES;
        }
        
        // For cmd + shift + left arrow
        if (cmdFlag && !optFlag && shiftFlag && unicodeChar == NSLeftArrowFunctionKey) {
            id  windowController;
            windowController = [self windowController];
            if ([windowController isKindOfClass:[SRMainWindowController class]]) {
                [windowController previousTabAction:self];
                return YES;
            }
        }
        
        // For cmd + shift + right arrow
        if (cmdFlag && !optFlag && shiftFlag && unicodeChar == NSRightArrowFunctionKey) {
            id  windowController;
            windowController = [self windowController];
            if ([windowController isKindOfClass:[SRMainWindowController class]]) {
                [windowController nextTabAction:self];
                return YES;
            }
        }
        
        // For cmd + '0' ~ '9'
        if (cmdFlag && unicodeChar >= '0' && unicodeChar <= '9') {
            id  windowController;
            windowController = [self windowController];
            if ([windowController isKindOfClass:[SRMainWindowController class]]) {
                [windowController openBookmarkBarAtAction:event];
                return YES;
            }
        }
        
        // For esc
        if (unicodeChar == 0x1b /* esc */) {
            id  windowController;
            windowController = [self windowController];
            if ([windowController isKindOfClass:[SRMainWindowController class]]) {
                if ([windowController isFullScreenMode]) {
                    [windowController escapeFromFullScreenMode];
                    return YES;
                }
            }
        }
    }
    
    return [super performKeyEquivalent:event];
}

@end
