/*
Pencil V1.0, Copyright 1994, 95 by Florian Marquardt.
This program may be distributed under the terms of the GNU general
public license (Start Pencil and select "Info>COPYING..." for a copy of the
license).
*/
#import "PencilInspector.h"
#import "PencilView.h"

#import <remote/NXConnection.h>
#import <remote/NXProxy.h>


extern BOOL globalOutlines;
BOOL globalTermination=NO;
BOOL load_at_start=NO;

@implementation PencilInspector
- appDidInit:sender
{
	[self initPopUpLists];
    	if (NXArgc > 1) {
	    [self openFile:NXArgv[1]];
    	} else  if(!load_at_start) [NXApp loadNibSection:"EmptyDocument.nib" owner:self];
	return self;
}

- (int)app:sender openFile:(const char *)path type:(const char *)type
/*
 * This method is performed whenever a user double-clicks on an icon
 * in the Workspace Manager representing a .pencil file.
 */
{
    if (type && !strcmp(type, "pencil")) {
	[self openFile:path];
	load_at_start=YES;
	return YES;
    }
    return NO;
}

- (BOOL)appAcceptsAnotherFile:(Application *)sender
{
    return YES;
}

- appWillTerminate:sender
{
	id list,listv;
	int i,j;

	globalTermination=YES;
	list=[NXApp windowList];
	for(i=[list count]-1;i>=0;i--)	{
		if(listv=[[[list objectAt:i] contentView] subviews])
		{
			for(j=[listv count]-1;j>=0;j--) if([[listv objectAt:j] isMemberOf:[PencilView class]])	break;
			if(j>=0)
			{
				[[list objectAt:i] performClose:self];
				if(!globalTermination)	break;
			}
		}
	}
	if(globalTermination)
		return self;
	else
		return nil;
}

- initPopUpLists
{
	char filename[500];
	NXStream *stream;
	char txt[300], name[300];
	int mode=0, n=-1;

	strcpy(filename, [[NXBundle mainBundle] directory]);
	strcat(filename, "/../pencilMethodDescriptions");
	stream=NXMapFile(filename, NX_READONLY);
	if(!stream)
	{
	strcpy(filename, [[NXBundle mainBundle] directory]);
	strcat(filename, "/pencilMethodDescriptions");
	stream=NXMapFile(filename, NX_READONLY);
	}
		if(stream)
		{
		while(NXScanf(stream, "%[^:]:%[^\n]\n",txt,name)>0)
		{
		if(!strcmp(txt, "PATHMETHODS")) { mode=0; n=-1; }
		else
		if(!strcmp(txt, "DRAWMETHODS")) { mode=1; n=-1; }
		else
		if(!strcmp(txt, "FILLMETHODS")) { mode=2; n=-1; }
		else
		if(!strcmp(txt, "STROKEMETHODS")) { mode=3; n=-1; }
		else
		{
		switch(mode)
		{
		case 0: [[[[[pathPopUp target] addItem:txt] setTarget:self] setAction:@selector(doChange:)] setTag:++n]; break;
		case 1:  [[[[[drawPopUp target] addItem:txt] setTarget:self] setAction:@selector(doChange:)] setTag:++n]; break;
		case 2: [[[[[fillPopUp target] addItem:txt] setTarget:self] setAction:@selector(doChange:)] setTag:++n]; break;
		case 3: [[[[[strokePopUp target] addItem:txt] setTarget:self] setAction:@selector(doChange:)] setTag:++n]; break;
		}
		[self addName:(char *)name to:mode]; 
		}
		}
		NXClose(stream);
		[self findName:namelist[0][0] in:0];
		[self findName:namelist[1][0] in:1];
		[self findName:namelist[2][0] in:2];
		[self findName:namelist[3][0] in:3];
		[[pathPopUp target] removeItemAt:0];
		[[drawPopUp target] removeItemAt:0];
		[[fillPopUp target] removeItemAt:0];
		[[strokePopUp target] removeItemAt:0];
		}
		else
		{
			NXRunAlertPanel("Alert", "Couldn't find pencilMethodDescriptions", "OK?!",NULL,NULL);
			[NXApp terminate:self];
		}
	return self;
}

- takeNew:sender
{
	if(view)
	{
	switch([sender tag])
	{
	case METHODNAME: [view setMethodname:[sender stringValue]]; break;
	case COLOR1: [view setColor1:[sender color]]; break;
	case COLOR2: [view setColor2:[sender color]]; break;
	case LINEWIDTH: [view setLineWidth:[sender floatValue]]; break;
	case DRAWMETHOD: [view setDrawingMethod:[sender stringValue]]; break;
	case FILLMETHOD: [view setFillMethod:[sender stringValue]]; break;
	case STROKEMETHOD: [view setStrokeMethod:[sender stringValue]]; break;
	case SPECIALATTRIBUTES: [view setSpecialAttributes:[sender stringValue]]; break;
	}
	}
    return self;
}

- giveSettings:(char **)name:(NXColor *)col1:(NXColor *)col2:(float *)lw:(char **)dm:(char **)fm:(char **)sm:(char **)ud
{
	*name=[methodname stringValue];
	*fm=[fillmethod stringValue];
	*dm=[drawmethod stringValue];
	*sm=[strokemethod stringValue];
	*ud=[special stringValue];
	*col1=[color1 color];
	*col2=[color2 color];
	*lw=[linewidth floatValue];
	return self;
}

- takeSettings:(char*)name:(NXColor)col1:(NXColor)col2:(float)lw:(char *)dm:(char *)fm:(char *)sm:(char *)ud
{
	[methodname setStringValue:name];
	[self findName:name in:0];
	[drawmethod setStringValue:dm];
	[self findName:dm in:1];
	[fillmethod setStringValue:fm];
	[self findName:fm in:2];
	[strokemethod setStringValue:sm];
	[self findName:sm in:3];
	[special setStringValue:ud];
	[color1 setColor:col1];
	[color2 setColor:col2];
	[linewidth setFloatValue:lw];
	return self;
}

- addName:(char *)nm to:(int)lis
{
	if(namelist[lis])	namelist[lis]=(char **)realloc(namelist[lis], sizeof(char *)*(++namelistcount[lis])); else
	namelist[lis]=(char **)malloc(sizeof(char *)*(namelistcount[lis]=1));
	namelist[lis][namelistcount[lis]-1]=(char *)malloc(sizeof(char)*(strlen(nm)+1));
	strcpy(namelist[lis][namelistcount[lis]-1], nm);
	return self;
}

- findName:(char *)nm in:(int)l
{
	int i;

	if(namelist[l])
	{
	for(i=0;i<namelistcount[l];i++) if(!strcmp(nm, (namelist[l])[i])) break;
	if(i<namelistcount[l])
		switch(l)
		{
		case 0: [[[pathPopUp target] itemList] selectCellWithTag:i]; [pathPopUp setTitle:[[[[pathPopUp target] itemList] selectedCell] title]]; break;
		case 1: [[[drawPopUp target] itemList] selectCellWithTag:i]; [drawPopUp setTitle:[[[[drawPopUp target] itemList] selectedCell] title]];break;
		case 2: [[[fillPopUp target] itemList] selectCellWithTag:i]; [fillPopUp setTitle:[[[[fillPopUp target] itemList] selectedCell] title]];break;
		case 3: [[[strokePopUp target] itemList] selectCellWithTag:i]; [strokePopUp setTitle:[[[[strokePopUp target] itemList] selectedCell] title]];break;
		}
	}
	return self;
}

- doChange:sender
{
	int mode=0, tag;

	tag=[[sender selectedCell] tag];
	sender=[sender window];
	if(sender==[pathPopUp target]) mode=0;
	if(sender==[drawPopUp target]) mode=1;
	if(sender==[fillPopUp target]) mode=2;
	if(sender==[strokePopUp target]) mode=3;
	switch(mode)
	{
	case 0: if(view) [view setMethodname:(namelist[mode])[tag]]; [methodname setStringValue:(namelist[mode])[tag]]; break;
	case 1: if(view) [view setDrawingMethod:(namelist[mode])[tag]]; [drawmethod setStringValue:(namelist[mode])[tag]]; break;
	case 2: if(view) [view setFillMethod:(namelist[mode])[tag]]; [fillmethod setStringValue:(namelist[mode])[tag]]; break;
	case 3: if(view) [view setStrokeMethod:(namelist[mode])[tag]]; [strokemethod setStringValue:(namelist[mode])[tag]]; break;
	}
	return self;
}
- athreshField { return aField; }
- sthreshField { return sField; }
- creationType { return cType; }
- inspectForView:(id)v { view=v; 	[view giveCustomTo:customPS];
return self; }
#define FOR(a) if(view) return [view a :sender]; else return self
- toFront:sender { FOR(toFront); }
- toBack:sender { FOR(toBack); }
- insertPoint:sender { FOR(insertPoint); }
- insertNextPoint:sender { FOR(insertNextPoint); }
- deletePoint:sender { FOR(deletePoint); }
- deleteGraphic:sender { FOR(deleteGraphic); }
- saveAs:sender { FOR(saveAs); }
- save:sender { FOR(save); }
- toCharP:sender { FOR(convertToCharPath); }
- print:sender { if(view) return [view printPSCode:sender]; else return self; }
- open:sender
{
	const char *types[]={ "pencil", NULL };

	if([[OpenPanel new] runModalForTypes:types]==NX_OKTAG)
	{
		[self openFile:[[OpenPanel new] filename]];
	}
	return self;
}
- openFile:(char *)name
{
	[NXApp loadNibSection:"EmptyDocument.nib" owner:self];
	[view readFromFilename:name];
	[view giveCustomTo:customPS];
	return self;
}

- new:sender
{
	[NXApp loadNibSection:"EmptyDocument.nib" owner:self];
	[customPS setText:""];
	return self;
}

- viewVanished:(id)v
{
	if(view==v)
	{
		view=nil;
		[customPS setText:""];
	}
	return self;
}

- executeCustom:sender
{
	if(view) [view takeCustomFrom:customPS];
	return self;
}

- setDrawOutlines:sender { globalOutlines=[sender state] ? YES:NO; if(view) [view displayWithCurrentGraphic]; return self; }

- copyAsPostScript:sender { if(view) [view copyAsPostScript:sender]; return self; }

- clearUserDef:sender
{
	[special setStringValue:""];
	if(sender)
		if(view) { [view takeCustomFrom:customPS]; [view displayWithCurrentGraphic]; }
	return self;
}

- setUserDef:(char *)udef
{
	[special setStringValue:udef];
	return self;
}

- importImage:sender
{
	if(view) [view importImage:sender];
	return self;
}

- registerAsTCLServer:sender
{
		if(!TCLconn)
		{
			TCLconn=[NXConnection registerRoot: self withName:"pencilTCLServer"];
			[TCLconn runFromAppKit];
		}
}

- (char *)performCommand:(const char *)cmd
{
	if(!strcmp(cmd,"new")) { [self new:self]; return "1"; }
	if(!strncmp(cmd, "open", 4)) {
		char name[400];
		sscanf(cmd, "open %s", name);
		[NXApp loadNibSection:"EmptyDocument.nib" owner:self];
		[view readFromFilename:name];
		[view giveCustomTo:customPS];
		return "1";
	}
	if(view) return([view performCommand:(const char *)cmd]);
		else return "failed";
}
@end
