
#import "OriginalView.h"

@implementation OriginalView

- initFrame:(const NXRect *)frameRect
{
	[super initFrame:frameRect];
	bitmapData = (unsigned char *)malloc ((int)bounds.size.width *
		(int)bounds.size.height * 4 * sizeof (unsigned char) + 1024);
	buffer = [[NXImage alloc] initSize:&bounds.size];
	[buffer setUnique:YES];
	[buffer setCacheDepthBounded:NO];
	[buffer useCacheWithDepth:NX_TwentyFourBitRGBDepth];
	return self;
}

- free
{
	free (bitmapData);
	[image free];
	[buffer free];
	return [super free];
}

- open:sender
{
	id oldImage = image;
	id openPanel = [OpenPanel new];
	
	if ([openPanel runModalForTypes:[NXImage imageFileTypes]]) {
		image = [[NXImage alloc] initFromFile:[openPanel filename]];
		[image setDataRetained:YES];
		imageRep = [image lastRepresentation];
		if (imageRep) {
			[[self window] setTitleAsFilename:[openPanel filename]];
			[[[self window] orderFront:self] display];
			[optionsWindow makeKeyAndOrderFront:self];
			[oldImage free];
		} else {
			NXRunLocalizedAlertPanel (NULL, NULL,
				"Unable to open input file: %s.",
				NULL, NULL, NULL, [openPanel filename]);
			[image free];
		}
	}
	
	return self;
}

- (BOOL)imageLoaded
{
	if (imageRep)
		return YES;
	else
		return NO;
}

- setRotationInDegrees:(float)newDegrees
{
	degrees = newDegrees;
	return self;
}

- bitmap
{
	id bits = nil;
	
	[buffer lockFocus];
		bits = [[NXBitmapImageRep alloc] initData:bitmapData fromRect:&bounds];
	[buffer unlockFocus];
	
	return bits;
}

- drawSelf:(const NXRect *)rects :(int)rectCount
{
	float scale, major;
	NXSize imageSize;
	
	if (!imageRep) return self;
	
	[imageRep getSize:&imageSize];
	if (imageSize.width > imageSize.height)
		major = imageSize.width;
	else
		major = imageSize.height;
	
	scale = bounds.size.width / major;
	
	[buffer lockFocus];
		NXSetColor (NX_COLORCLEAR);
		NXRectFill (&bounds);

		PStranslate (bounds.size.width/2., bounds.size.height/2.);
		PSrotate (degrees);
		PSscale (scale, scale);
		PStranslate (-imageSize.width/2., -imageSize.height/2.);
		[imageRep draw];
	[buffer unlockFocus];
	
	NXSetColor (NX_COLORLTGRAY);
	NXRectFill (&bounds);
	[buffer composite:NX_SOVER toPoint:&bounds.origin];
	
	return self;
}

@end
