/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: HXClientView.m,v 1.9.2.4 2004/07/09 01:49:35 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#import "HXClientView.h"
#import "HXEventRecordUtils.h"
#import "HXClientEngine.h"
#import "HXClientPlayer.h"

@implementation HXClientView

#pragma mark -

- (id)initWithFrame:(NSRect)frameRect
{
	self = [super initWithFrame:frameRect];
	if ( self )
	{
		hasUserClicked = NO;
		
		isInSetFrame = 0;
		m_LastSetSizeWidth  = 0;
		m_LastSetSizeHeight = 0;
		[self updateSiteWindow];
	}
	return self;
}

- (void)dealloc
{
	if ( trackingRectTag )
	{
		[self removeTrackingRect:trackingRectTag];
		trackingRectTag = 0;
	}
	// Restore window port's origin to 0, 0. XXXSEH: This should be fixed in Helix.
	NSWindow* window = [self window];
	if ( window )
	{
		Rect portBounds;
		CGrafPtr windowPort = GetWindowPort( ( WindowRef ) [window windowRef] );
		GetPortBounds( windowPort, &portBounds );
		OffsetRect( &portBounds, -portBounds.left, -portBounds.top );
		SetPortBounds( windowPort, &portBounds );
	}
	[super dealloc];
}

- (void)setClientPlayer:(HXClientPlayer*)aClientPlayer
{
	clientPlayer = aClientPlayer;
}

- (HXClientPlayer*)clientPlayer
{
	return clientPlayer;
}

- (SHXClientWindow*)siteWindow
{
	return &m_SiteWindow;
}

#pragma mark -

- (void)updateSiteWindow
{
	NSWindow* window = [self window];
	if ( !window ) return; // Don't bother updating our m_SiteWindow if we're currently detached from a window.
	
	NSRect siteViewWindowRect = NSMakeRect( 0, 0, 0, 0 );
	NSSize contentViewSize = { 0, 0 };

	siteViewWindowRect = [self convertRect:[self bounds] toView:nil];
	contentViewSize = [[window contentView] bounds].size;
	
	m_SiteWindow.window = &m_SiteWindow.drawingContextKind;
	
	// XXXSEH: Investigate calling lockFocus before calling qdPort to ensure we have a non NULL port.
	void* qdPort = [self qdPort];
	if ( qdPort )
	{
		m_SiteWindow.drawingContextKind = kDrawingContextKindQuickDrawGrafPtr;
		m_SiteWindow.drawingContext = qdPort;
                
		m_SiteWindow.x = 0;
		m_SiteWindow.y = 0;
	}
	else
	{
		m_SiteWindow.drawingContextKind = kDrawingContextKindQuickDrawWindowPtr;
		m_SiteWindow.drawingContext = [window windowRef];

		m_SiteWindow.x = ( UInt32 ) siteViewWindowRect.origin.x;
		m_SiteWindow.y = ( UInt32 ) ( contentViewSize.height - ( siteViewWindowRect.origin.y + siteViewWindowRect.size.height ) );
	}
	m_SiteWindow.width  = ( UInt32 ) siteViewWindowRect.size.width;
	m_SiteWindow.height = ( UInt32 ) siteViewWindowRect.size.height;
	
	m_SiteWindow.clipRect.left   = m_SiteWindow.x;
	m_SiteWindow.clipRect.top    = m_SiteWindow.y;
	m_SiteWindow.clipRect.right  = m_SiteWindow.clipRect.left + m_SiteWindow.width;
	m_SiteWindow.clipRect.bottom = m_SiteWindow.clipRect.top  + m_SiteWindow.height;
	
// NSLog( [NSString stringWithFormat:@"updateSiteWindow: qdPort = %x, windowRef = %x, windowRef Port = %x, Origin = ( %lu, %lu ), Size = ( %lu, %lu ), clipRect = ( %ld, %ld, %ld, %ld )", qdPort, [window windowRef], GetWindowPort( ( WindowRef ) [window windowRef] ), m_SiteWindow.x, m_SiteWindow.y, m_SiteWindow.width, m_SiteWindow.height, m_SiteWindow.clipRect.left, m_SiteWindow.clipRect.top, m_SiteWindow.clipRect.right, m_SiteWindow.clipRect.bottom] );
}

- (void)drawRect:(NSRect)rect
{
// NSLog( @"HXClientView drawRect: origin = ( %f, %f ), size = ( %f, %f )", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height );
	[self updateSiteWindow];
	
	// XXXSEH: Since the CORE immediately blits within the SetSize() method,
	// the subsequent drawRect method call would cause a double blit.
	if ( ( m_LastSetSizeWidth != m_SiteWindow.width ) || ( m_LastSetSizeHeight != m_SiteWindow.height ) )
	{
		m_LastSetSizeWidth  = m_SiteWindow.width;
		m_LastSetSizeHeight = m_SiteWindow.height;
		NSSize newSize = { m_SiteWindow.width, m_SiteWindow.height };
		[clientPlayer setSize:newSize];
	}
	else
	{
		NSRect siteBounds = [self bounds];
		SHXClientRect siteRect;
		siteRect.left   = ( SInt32 ) ( rect.origin.x - siteBounds.origin.x );
		siteRect.top    = ( SInt32 ) ( siteBounds.size.height - ( ( rect.origin.y - siteBounds.origin.y ) + rect.size.height ) );
		siteRect.right  = siteRect.left + ( SInt32 ) rect.size.width;
		siteRect.bottom = siteRect.top  + ( SInt32 ) rect.size.height;
		[clientPlayer drawSite:siteRect];

		if ( [[self window] isKeyWindow] && [NSApp isActive] && [[self window] firstResponder] == self )
		{
			NSSetFocusRingStyle(NSFocusRingOnly);
			NSRectFill([self bounds]);
		}
	}
}

#pragma mark -

- (void)setFrameOrigin:(NSPoint)newOrigin
{
	if ( NSEqualPoints( newOrigin, [self frame].origin ) ) return;

	[super setFrameOrigin:newOrigin];
	if ( !isInSetFrame )
	{
		[self updateSiteWindow];
	}
}

- (void)setFrameSize:(NSSize)newSize
{
	if ( NSEqualSizes( newSize, [self frame].size ) ) return;

	[super setFrameSize:newSize];
	if ( !isInSetFrame )
	{
		[self updateSiteWindow];
	}
}

- (void)setFrame:(NSRect)frameRect
{
	if ( NSEqualRects( frameRect, [self frame] ) ) return;

	isInSetFrame++;
	[super setFrame:frameRect];
	isInSetFrame--;
	if ( !isInSetFrame )
	{
		[self updateSiteWindow];
	}
}

- (void)setFrameRotation:(float)angle
{
	if ( angle == [self frameRotation] ) return;

	[super setFrameRotation:angle];
	[self updateSiteWindow];
}

#pragma mark -

- (void)viewWillMoveToWindow:(NSWindow *)newWindow
{
	if ( trackingRectTag )
	{
		[self removeTrackingRect:trackingRectTag];
		trackingRectTag = 0;
	}
	[super viewWillMoveToWindow:newWindow];
}

- (void)viewDidMoveToWindow
{
	[super viewDidMoveToWindow];
	[self updateSiteWindow];
}

- (void)resetCursorRects
{
	[super resetCursorRects];
	[self establishTrackingRect];
}

- (BOOL)isMouseInsideBounds:(NSRect)bounds
{
	NSPoint mouseLoc = [self convertPoint:[[self window] mouseLocationOutsideOfEventStream] fromView:nil];
	BOOL isMouseInsideBounds = NSMouseInRect( mouseLoc, bounds, NO );
	return isMouseInsideBounds;
}

- (void)establishTrackingRect
{
	if ( trackingRectTag )
	{
		[self removeTrackingRect:trackingRectTag];
		trackingRectTag = 0;
	}
	NSRect bounds = [self bounds];
	BOOL isMouseInsideMe = [self isMouseInsideBounds:bounds];
	trackingRectTag = [self addTrackingRect:bounds
									  owner:self
								   userData:nil
							   assumeInside:isMouseInsideMe];
}

#pragma mark -

- (void)passEventToEngine:(NSEvent *)theEvent
{
	HXClientEngine* clientEngine = [HXClientEngine sharedClientEngineNoCreate];
	if ( clientEngine )
	{
		EventRecord classicEvent;
		[HXEventRecordUtils convertEvent:theEvent toEventRecord:&classicEvent];
			
		[clientEngine handleClassicEvent:&classicEvent];
	}
}

#pragma mark -

- (void)setFocusWithMouseDown
{
	hasUserClicked = YES;

	[[self window] makeFirstResponder:self];
}

- (BOOL)acceptsFirstResponder
{
	return hasUserClicked;
}

- (BOOL)becomeFirstResponder
{
	[self setKeyboardFocusRingNeedsDisplayInRect:[self bounds]];
	return YES;
}

- (BOOL)resignFirstResponder
{
	[self setKeyboardFocusRingNeedsDisplayInRect:[self bounds]];
	return YES;
}

- (void)keyDown:(NSEvent *)theEvent
{
	if ( [[theEvent characters] hasPrefix:@"\t"]
	  || [[theEvent characters] characterAtIndex:0] == 0x19 ) // 0x19 is shift tab, apparently
	{
		// tab key or shift tab pressed;
		// too bad charactersIgnoringModifiers doesn't ignore the shift for us
		[super keyDown:theEvent];
	}
	else
	{
		[self passEventToEngine:theEvent];
	}
}

#pragma mark -

- (void)mouseEntered:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)mouseExited:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)mouseDown:(NSEvent *)theEvent
{
	[self setFocusWithMouseDown];

	[self passEventToEngine:theEvent];
}

- (void)rightMouseDown:(NSEvent *)theEvent
{
	[self setFocusWithMouseDown];

	[self passEventToEngine:theEvent];
}

- (void)otherMouseDown:(NSEvent *)theEvent
{
	[self setFocusWithMouseDown];
	
	[self passEventToEngine:theEvent];
}

- (void)mouseUp:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)rightMouseUp:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)otherMouseUp:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)mouseMoved:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)mouseDragged:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)rightMouseDragged:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (void)otherMouseDragged:(NSEvent *)theEvent
{
	[self passEventToEngine:theEvent];
}

- (BOOL)mouseDownCanMoveWindow
{
	return NO;
}
@end
