package org.jsgene.script;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashMap;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.jsgene.EntryPoint;
import org.jsgene.graphics.*;
import org.jsgene.util.*;
public class ScriptManager
{
public Context context;
public Scriptable scope;
HashMap<String, Script> loadedScripts;
public ScriptManager()
{
context = Context.enter();
context.setErrorReporter(new ErrorLogger());
scope = context.initStandardObjects();
try
{
ScriptableObject.defineClass(scope, Color.class);
ScriptableObject.defineClass(scope, Logger.class);
ScriptableObject.defineClass(scope, Scripter.class);
if(EntryPoint.windowType == "native")
{
ScriptableObject.defineClass(scope, SWINGNativeFrame.class);
}
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
// Set some globals
context.evaluateString(scope, "var console = new Console();", "Create console", 1, null);
context.evaluateString(scope, "var scripter = new Scripter();", "Create scripter", 1, null);
loadedScripts = new HashMap<String, Script>();
}
public void loadScript(String filename)
{
try
{
URL loc = this.getClass().getResource("/scripts/" + filename);
BufferedReader br = new BufferedReader(new InputStreamReader(loc.openStream()));
String script = "";
String line = br.readLine();
while(line != null)
{
script += line + "\n";
line = br.readLine();
}
br.close();
loadScript(filename, script, 1);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void loadScript(String filename, String script)
{
loadScript(filename, script, 1);
}
public void loadScript(String filename, String script, int line)
{
Script s = context.compileString(script, filename, line, null);
if(s == null)
{
context.reportRuntimeError("Failed to load script", script, -1, "", -1);
}
loadedScripts.put(filename, s);
}
public void executeScript(String filename)
{
Script s = loadedScripts.get(filename);
try
{
s.exec(context, scope);
}
catch(Exception e)
{
context.reportRuntimeError("Error in script", filename, -1, "", -1);
}
}
}