
/* Generated by Interface Builder */

#import "ImageView.h"

@implementation ImageView

- initFrame:(const NXRect *)frm			// initialize instance
{
    [super initFrame:frm];
    origin.x = 0;
    origin.y = 0;
    xsize = 0;
    ysize = 0;
    return self;
}

-(int)tag
{
    return 69;
}

- (BOOL)loadFile:(const char *)name x:(int)winX y:(int)winY	// load pic
{
    id imageRep;
    int file, numread, i;
    unsigned long amount, rdt, ys, xs;
    unsigned char lengths[16];
    unsigned char *dataArray;

    file = open(name, O_RDONLY, 0666);
    if (!file) { printf("File open error...\n"); return NO;}
   
    numread = read(file, lengths, 8);
    if (numread != 8) {printf("Read error...aborting.\n"); return NO;}
    xsize = 0; ysize = 0;
    for (i=0; i<4; i++) {
        xsize *= 256;
        xsize += lengths[i];
    }
    for (i=0; i<4; i++) {
        ysize *= 256;
        ysize += lengths[i];
    }
    
    imageRep = [[NXBitmapImageRep alloc] initData:NULL
    		pixelsWide:xsize pixelsHigh:ysize
		bitsPerSample:8 samplesPerPixel:3
		hasAlpha:NO isPlanar:NO colorSpace:NX_RGBColorSpace
		bytesPerRow:xsize*3 bitsPerPixel:0];
    if (imageRep == nil) { printf("Couldn't create ImageRep."); return NO; }
    dataArray = [imageRep data];
    
    amount = xsize*ysize*3;
    if ((rdt = read(file, dataArray++, amount)) != amount) {
 	printf("Reading data error.\n");
    }

    if (close(file)) { printf("File close error...\n"); }
    ys = ((ysize > 512) ? 512 : ysize);
    xs = ((xsize > 512) ? 512 : xsize);
    [self sizeTo:xsize :ysize];
    [[self window] sizeWindow:(xs+19) :(ys+19)];
    [[self window] moveTo:(winX) :(winY-ys+129)];
    image = [[NXImage alloc] initSize:&bounds.size];
    if (NO == [image useRepresentation:imageRep]) {
        printf("Couldn't use imageRep.\n");
	return NO;
    }
    [self update];
    [[self window] makeKeyAndOrderFront:self];
    return YES;
}

- (BOOL)saveFile:(const char *)name	 // save pic
{
    int fd;
    NXStream *stream;
    
    fd = open(name, O_CREAT | O_WRONLY | O_TRUNC, 0666);
    if (!fd) { printf("Error opening save file %s.\n", name); }
    stream = NXOpenFile(fd, NX_WRITEONLY);
    if (stream == NULL) { printf("Error opening save stream.\n"); }
    [image writeTIFF:stream];
    NXFlush(stream);
    NXClose(stream);
    close(fd);
    return YES;
}

- drawSelf:(NXRect *)rects :(int)rectCount  	// standard rendering method
{
    [self lockFocus];
    PSsetgray(NX_BLACK);
    NXRectFill(&bounds);
    [image composite:NX_COPY toPoint:&origin];
    [[self window] flushWindow];
    [self unlockFocus];
    return self;
}

- windowWillResize:sender toSize:(NXSize *)newFrame	// to control max size
{
    if (newFrame->width > (xsize + 21)) newFrame->width = xsize + 21;
    if (newFrame->height > (ysize + 51)) newFrame->height = ysize + 51;
    if (newFrame->width < 64) newFrame->width = 64;
    if (newFrame->height < 118) newFrame->height = 118;
    return self;
}

@end
