/* 
 * Mandel.m, subclass of Object, Jan. 1992
 * written by R. Pajarola
 * E-mail: rpajarol@iiic.ethz.ch
 */

#import "Mandel.h"
#import <appkit/Application.h>
#import <appkit/SavePanel.h>
#import <appkit/NXBitmapImageRep.h>
#import <streams/streams.h>

@implementation Mandel

- init
{
	[super init];
	
	/* Get the instance of a SavePanel
	 */
	savePanel = [SavePanel new];
	
	return self;
}

/* Constrain window resizing. The following values are somewhat arbitrary; */
/* they need to depend on the window style, and the actual size of the view */
/* within the window. */

#define MINWIDTH  510
#define MINHEIGHT 580

- windowWillResize:window toSize:(NXSize *)size
{
    if (size->width  < MINWIDTH)  size->width = MINWIDTH;
    if (size->height < MINHEIGHT) size->height = MINHEIGHT;
    return self;
}   

- displayInfoPanel:sender
{
    if (!infoPanel)
		[NXApp loadNibSection:"InfoPanel.nib" owner:self withNames:NO];

    [infoPanel makeKeyAndOrderFront:NULL];
    return self;
}

- displayHelpPanel:sender
{
    if (!helpPanel)
		[NXApp loadNibSection:"HelpPanel.nib" owner:self withNames:NO];

    [helpPanel makeKeyAndOrderFront:NULL];
    return self;
}

- saveRequest:sender
/* Get a correct filename with a .tiff extension.
 */
{
	const char	*filename;
	
	[savePanel setRequiredFileType:"tiff"];
	if (([savePanel runModal]) && (filename = [savePanel filename]))
		[self saveViewInPath:filename];
	
	return self;
}

- saveViewInPath:(const char *)name
/* Save method, implemented for the pictures computed by the MandelView
 * object.
 */
{
	int				width, height, bps, spp;
	BOOL			alpha, config;
	NXColorSpace	space;
	unsigned char	*data;
	id				image;
	NXStream		*stream;
	
	/* First allocate a new NXBitmapImageRep, then get the imagedata
	 * from the MandelView object and init the NXBitmapImageRep with it.
	 * Open a stream on a file(name), from the SavePanel, and save
	 * a TIFF representation from the image on this stream.
	 */
	if ((image = [NXBitmapImageRep alloc]) != nil){
		if ([myView getValues:&data :&width :&height :&bps :&spp :&alpha 
		:&config :&space]) {
			[image initData:data
				pixelsWide:width
				pixelsHigh:height
				bitsPerSample:bps
				samplesPerPixel:spp
				hasAlpha:alpha
				isPlanar:config
				colorSpace:space
				bytesPerRow:(width*spp*bps/8)
				bitsPerPixel:(spp*bps)];
			if ((stream = NXOpenMemory(NULL, 0, NX_WRITEONLY)) != NULL) {
				[image writeTIFF:stream];
				NXSaveToFile(stream, name);
				NXCloseMemory(stream, NX_FREEBUFFER);
			} else
				NXRunAlertPanel("Stream error !", "Cannot open a stream.",
				NULL, NULL, NULL);
		} else
			NXRunAlertPanel("View error !", "No image computed.",
			NULL, NULL, NULL);
		[image free];
	} else
		NXRunAlertPanel("Image error !", "Cannot allocate a BitmapImage.",
		NULL, NULL, NULL);

	return self;
}

@end
