//
//  ICeCoffEEMenuOutlineView.m
//  ICeCoffEE
//
//  Created by Nicholas Riley on 3/2/08.
//  Copyright 2008 Nicholas Riley. All rights reserved.
//

#import "ICeCoffEEMenuOutlineView.h"
#import <Carbon/Carbon.h>

// Tiger or later, indicates whether highlighted row should draw as active
@interface NSWindow (IC_KeyboardFocus)
- (BOOL)_isKeyWindowIgnoringFocus;
@end

BOOL ICCF_ViewHasKeyboardFocus(NSView *view) {
    NSWindow *window = [view window];
    if ([window firstResponder] != view)
	return NO;
    
    if ([window respondsToSelector: @selector(_isKeyWindowIgnoringFocus)])
	return [window _isKeyWindowIgnoringFocus];
    
    // XXX is there a documented way to do this?
    // see <http://lists.apple.com/archives/cocoa-dev/2008/Mar/msg00036.html>
    
    // test cases:
    // - About System Preferences...
    // - focused character palette
    // - Help menu search (Shortcut)
    // - menu extras
    NSWindow *keyWindow = [NSApp keyWindow];
    if (window != keyWindow && (keyWindow == nil || [keyWindow isKindOfClass: [NSPanel class]]))
	return NO; // exclude NSCarbonMenuWindow
    
    return YES;
}

@implementation ICeCoffEEMenuOutlineView

// undocumented, Leopard-only, only way I can figure out to bypass inter-cell navigation
- (BOOL)canFocusCell:(NSCell *)cell atTableColumn:(NSTableColumn *)tableColumn row:(int)row;
{
    return NO;
}

- (void)highlightSelectionInClipRect:(NSRect)clipRect;
{
    NSRange rows = [self rowsInRect: clipRect];
    unsigned maxRow = NSMaxRange(rows);

    HIThemeMenuItemDrawInfo drawInfo = {0, kThemeMenuItemHierBackground | kThemeMenuItemPopUpBackground, kThemeMenuSelected};
    if (!ICCF_ViewHasKeyboardFocus(self)) {
	[super highlightSelectionInClipRect: clipRect];
	return;
    }
    
    for (unsigned row = rows.location ; row < maxRow ; ++row) {
	if (![self isRowSelected: row])
	    continue;
	
	NSRect rowRect = [self rectOfRow: row];
	rowRect.size.height += 2;
	if (NSIntersectsRect(rowRect, clipRect)) {
	    OSStatus err = HIThemeDrawMenuItem((HIRect *)&clipRect,
					       (HIRect *)&rowRect,
					       &drawInfo,  
					       (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort],
					       kHIThemeOrientationInverted,
					       (HIRect *)&rowRect);
	    if (err != noErr) {
		[super highlightSelectionInClipRect: clipRect];
		return;
	    }
	}
    }
}

@end
