/* Hippo Graphic View
 * a subclass of GraphicView in /NextDeveloper/Examples/Draw
 * to add or over-ride so that it can handle hippo Graphic objects
 *
 * This category handles compiling and running an Obj-C routine to
 * create and manipulate plots
 *
 * Copyright (C)  1993  The Board of Trustees of
 * The Leland Stanford Junior University.  All Rights Reserved.
 */

#import "HGraphicView.h"
#import "HFunction.h"
#import "HDrawApp.h"
#import "InspectTuple.h"
#import "Draw.subproj/draw.h"

const char hgvScript_m_rcsid[] = "$Id: hgvScript.m,v 2.1 1994/01/05 02:23:21 rensing Exp $";

@interface HGraphicView(Private)
- runScript: (const char *)file;
@end

@implementation HGraphicView(Script)

- executeScript:sender
{
     OpenPanel *openpanel = [[OpenPanel new] allowMultipleFiles:NO];
     const char *const 	fileTypes[2] = { "m", NULL };
     const char *file;
     
     if ([openpanel runModalForTypes:fileTypes]) {
	  file = [openpanel filename];
	  if (file) {
	       if (NXRunAlertPanel("Save before scripting warning",
			 "Do you want to save the document before running?",
				 "Yes", "No", NULL)
		   == NX_ALERTDEFAULT)
	       {
		    [[drawInstance currentDocument] save: nil];
	       }
	       [self runScript: file];
	  }
     }
     return self;
}

@end

@implementation HGraphicView(Private)

- runScript: (const char *)file
{
     HFunction *func;
     int rc;
     void (*fp)(HGraphicView *, HTuple *);
     char *ptr;
     char inclpath[MAXPATHLEN+3] = "-I";
    
     /* 
      * first, create an HFunction to handle the mechanics of compiling and
      * loading a function.
      */
     func = [[HFunction alloc] init];
     [func setFileName: file];
     [func setLanguage: OBJECTIVE_C ];
     [func setFunctionName: "hscript" ];
     [func setOutputDir: "/tmp"];
     
     /* ask the main bundle for the path to the needed include files */
     if ( ! [[NXBundle mainBundle] getPath:(inclpath+2)
	     forResource:"Plot"  ofType:"h"] ) {
	  NXRunAlertPanel( "Error",
			  "Can not find needed include files in HippoDraw.app",
			  "OK", NULL, NULL );
	  return NULL;
     }
     ptr = strrchr(inclpath, '/');
     *ptr = '\0';
     [func setCompileFlags: inclpath ];
     
     /*
      * compile and link the function
      */
     rc = [func compile];
     if (rc == 0) 
	  rc = [func link];
     if (rc == 0)
     {
         fp = [func funcPointer];
         if (fp)
	 {
	      HTuple *currTuple = [[[hippoDraw inspectTuple] updateView]
				   currentHTuple];
	      (*fp)(self, currTuple);
	 }
         [func unload];			/* if the function loaded, unload it */
     }
     [func free];
     
     return self;
}

@end
