
#import "OutputView.h"

@implementation OutputView

- clearOutputImage
{
	[outputImage lockFocus];
		NXSetColor (NX_COLORCLEAR);
		NXRectFill (&bounds);
	[outputImage unlockFocus];
	
	return self;
}

- initFrame:(const NXRect *)frameRect
{
	[super initFrame:frameRect];
	outputImage = [[NXImage alloc] initSize:&frame.size];
	[outputImage setUnique:YES];
	[outputImage setCacheDepthBounded:NO];
	[outputImage useCacheWithDepth:NX_TwentyFourBitRGBDepth];
	[self clearOutputImage];
	
	return self;
}

- free
{
	[outputImage free];
	return [super free];
}

- showNotCompleteAlert
{
	NXRunLocalizedAlertPanel (NULL, NULL,
		"A complete image series is not available.", NULL, NULL, NULL);
	return self;
}

- save:sender
{
	int fd;
	NXStream *stream;

	if (!seriesComplete) {
		[self showNotCompleteAlert];
		return nil;
	}

	if (outputFilename) {
		[[self window] setTitleAsFilename:outputFilename];
		fd = creat (outputFilename, 0644);
		stream = NXOpenFile (fd, NX_WRITEONLY);
		[outputImage writeTIFF:stream allRepresentations:NO
			usingCompression:NX_TIFF_COMPRESSION_LZW andFactor:0.];
		NXClose (stream);
		close (fd);
	} else
		[self saveAs:self];
	
	return self;
}

- saveAs:sender
{
	id savePanel;
	
	if (!seriesComplete) {
		[self showNotCompleteAlert];
		return nil;
	}
	
	savePanel = [SavePanel new];
	if ([[savePanel setRequiredFileType:"tiff"] runModal]) {
		outputFilename = [savePanel filename];
		if (outputFilename) [self save:self];
	}
	
	return self;
}

- beginSeriesOfFrames:(int)newNumFrames withSize:(int)newFrameSize
{
	NXCoord width, height;
	
	numFrames = newNumFrames;
	frameSize = newFrameSize;
	currentFrame = 0;
	seriesComplete = NO;
	[saveMenuItem setEnabled:NO];
	[saveAsMenuItem setEnabled:NO];
	
	width = (numFrames > 4) ?
		(NXCoord)frameSize * 4. :
		(NXCoord)frameSize * numFrames;
	height = ((numFrames + 3) / 4) * (NXCoord)frameSize;
	[self sizeTo:width :height];
	
	return self;
}

- addFrame:newBitmap
{
	if (seriesComplete) {
		[newBitmap free];
		return nil;
	}
	
	[outputImage lockFocus];
		PStranslate ((float)(currentFrame % 4) * (float)frameSize, 
			(float)(currentFrame / 4) * (float)frameSize);
		[newBitmap draw];
	[outputImage unlockFocus];
	
	[newBitmap free];
	
	currentFrame++;
	if (currentFrame == numFrames) {
		seriesComplete = YES;
		[saveMenuItem setEnabled:YES];
		[saveAsMenuItem setEnabled:YES];
	}
	
	return self;
}

- (int)nextFrame
{
	return currentFrame;
}

- (int)numFrames
{
	return numFrames;
}

- (BOOL)seriesComplete
{
	return seriesComplete;
}

- sizeTo:(NXCoord)width :(NXCoord)height
{
	NXSize newSize = {width, height};
	
	[super sizeTo:width :height];
	[outputImage setSize:&newSize];
	[self clearOutputImage];
	
	return self;
}

- drawSelf:(const NXRect *)rects :(int)rectCount
{
	NXSetColor (NX_COLORLTGRAY);
	NXRectFill (&bounds);
	[outputImage composite:NX_SOVER toPoint:&bounds.origin];
	return self;
}

@end
