
#import "RemoteView.h"
#import "Controller.h"
#import "../../include/Puppeteer.h"
#import "../../include/WindowInfo.h"

extern id puppet;

@implementation RemoteView

- restoreCursor:(NXEvent *)theEvent
/*
 * Restore the mouse position.
 */
{
	NXPoint point;
	
	point = theEvent->location;
	[self convertPoint:&point fromView:NULL];
	[self lockFocus];
	PSsetmouse(point.x, point.y);
	NXPing();
	[self unlockFocus];

	return self;
}

- mouseDownOrDragged:(NXEvent *)theEvent
{
	NXPoint point = theEvent->location;
	int selectedWindow = [[NXApp delegate] selectedWindow];

	[self convertPoint:&point fromView:NULL];
	[puppet postMouseEvent:theEvent->type window:selectedWindow 
		flags:theEvent->flags x:point.x y:point.y 
		click:theEvent->data.mouse.click];
	[puppet ping];

	[self restoreCursor:theEvent];

	return self;
}

- mouseDown:(NXEvent *)theEvent
{
	NXPoint point = theEvent->location;
	NXRect wframe;
	int winNum;
	
	if ([[NXApp delegate] printMouseClicks]) {
		[self convertPoint:&point fromView:NULL];
		[puppetWindow getFrame:&wframe];
		winNum = [puppetWindow localWindowNumber];
		printf("Puppeteer: mouse down in window %d (w = %f, h = %f) at x = %f, y = %f\n", winNum, wframe.size.width, wframe.size.height, point.x, point.y);
	}
	
	[window addToEventMask:NX_MOUSEDRAGGEDMASK];
	
	[puppet postActivate:YES];
	
	[self mouseDownOrDragged:theEvent];
	
	return [super mouseDown:theEvent];
}

- mouseDragged:(NXEvent *)theEvent
{
	[self mouseDownOrDragged:theEvent];

	return [super mouseDragged:theEvent];
}

- mouseUp:(NXEvent *)theEvent
{
	NXPoint point = theEvent->location;
	int selectedWindow = [[NXApp delegate] selectedWindow];
	NXRect wframe;
	int winNum;

	[self convertPoint:&point fromView:NULL];
	if ([[NXApp delegate] printMouseClicks]) {
		[puppetWindow getFrame:&wframe];
		winNum = [puppetWindow localWindowNumber];
		printf("Puppeteer: mouse up in window %d (w = %f, h = %f) at x = %f, y = %f\n", winNum, wframe.size.width, wframe.size.height, point.x, point.y);
	}
	
	[puppet postMouseEvent:theEvent->type window:selectedWindow 
		flags:theEvent->flags x:point.x y:point.y
		click:theEvent->data.mouse.click];
	[puppet postActivate:NO];
	[puppet ping];
	[puppetWindow copyWindowToImage:image];
	[NXApp activateSelf:YES];
	[self display];
	[[NXApp delegate] reloadPopupList];
	
	[self restoreCursor:theEvent];
			
	return [super mouseUp:theEvent];
}

- setWindow:theWindow
{
	puppetWindow = theWindow;
	
	[self setImage:[puppetWindow windowImage]];
	
	return self;
}

- setImage:theImage
{
	NXSize theSize;
	
	image = theImage;
	[image getSize:&theSize];
	[self sizeTo:theSize.width:theSize.height];
	[self display];
	
	return self;
}

- drawSelf:(const NXRect *)rects :(int)count
{
	[image composite:NX_COPY toPoint:&(bounds.origin)];
    
	return self;
}

@end
