#import <objc/Object.h>
#import <appkit/appkit.h>
#import "Controller.h"
#import "MiniView.h"
#import "ImageScrollView.h"

id miniView;

void getAppDirectory (char *appDirectory)
{
    FILE *process;
    char command[256];
    char *suffix;

    strcpy (appDirectory,NXArgv[0]);
    if (appDirectory[0] == '/') { 		/* if absolute path */
        if (suffix = rindex(appDirectory,'/')) 
            *suffix  = '\0'; 			/* remove executable name */
    } else {
	sprintf(command,"which '%s'\n",NXArgv[0]);
	process=popen(command,"r");
	fscanf(process,"%s",appDirectory);
	pclose(process);
	if (suffix = rindex(appDirectory,'/')) 
	    *suffix  = '\0'; 			/* remove executable name */
	chdir(appDirectory);
	getwd(appDirectory);
    }  
}

static BOOL getOpenPath(char *buf, char const *theType)
{
    static id	openPanel = nil;
    char const *fileTypes[2] = {0,0};

    if (!openPanel)
        openPanel = [OpenPanel new];
    if (theType && *theType)
	fileTypes[0] = theType;
    [NXApp setAutoupdate:NO];
    if ([openPanel runModalForTypes:fileTypes]) {
	strcpy(buf,[openPanel filename]);
	[NXApp setAutoupdate:YES];
	return YES;
    } else {
	[NXApp setAutoupdate:YES];
	return NO;
    }
}


/**************************************************************************/


@implementation Controller

- appDidInit:sender
{
	char path[MAXPATHLEN + 1];

    [[imageScrollViewPtr window] makeKeyAndOrderFront:NULL];

/* Display copyright tiff if it exists. */
    getAppDirectory(path);
    strcat(path,"/");
    strcat(path, "Copyright.tiff");
    [imageScrollViewPtr displayImage:path];
    [[imageScrollViewPtr window] makeKeyAndOrderFront:self];
    miniView = [imageScrollViewPtr miniView];
    return self;
}

- open:sender
{
    char pathname[MAXPATHLEN + 1];

    if (getOpenPath(pathname,"tiff"))
	[imageScrollViewPtr displayImage:pathname];
    return self;
}

- MiniViewToggle:sender
{
	if ([sender state]) {
		[imageScrollViewPtr setMiniView:NULL];
		[miniView setImageScrollView:NULL];
		[miniView freeMiniImage];
		[miniView display];
	}
	else {
		[imageScrollViewPtr setMiniView:miniView];
		[miniView setImageScrollView:imageScrollViewPtr];
		[miniView initImage];
		[imageScrollViewPtr tile];
	}
	return self;
}

@end
