//
//  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>

@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;
}

// maintains main window (e.g., window to which sheet is attached) for use by shouldUseActiveHighlight
- (void)viewDidMoveToWindow;
{
    mainWindow = [NSApp mainWindow];
    [super viewDidMoveToWindow];
}

- (BOOL)shouldUseActiveHighlight;
{
    return NO;
    // test cases: - XXX there should be a better way to do this
    // see <http://lists.apple.com/archives/cocoa-dev/2008/Mar/msg00036.html>
    // - About System Preferences...
    // - focused character palette
    // - Help menu search (Shortcut)
    // - menu extras
    NSWindow *keyWindow = [NSApp keyWindow], *thisWindow = [self window];
    if (keyWindow != thisWindow && [keyWindow isKindOfClass: [NSPanel class]])
	return NO; // exclude NSCarbonMenuWindow
    return [thisWindow firstResponder] == self && [NSApp mainWindow] == mainWindow;
}

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

    HIThemeMenuItemDrawInfo drawInfo = {0, kThemeMenuItemHierBackground | kThemeMenuItemPopUpBackground, kThemeMenuSelected};
    NSLog(@"firstResponder %@ key %@ isKey %d main %@", [[self window] firstResponder], [NSApp keyWindow], [[self window] isKeyWindow], [NSApp mainWindow]);
    if (![self shouldUseActiveHighlight]) {
	instrumentObjcMessageSends(YES);
	[super highlightSelectionInClipRect: clipRect];
	instrumentObjcMessageSends(NO);
	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
