All Downloads are FREE. Search and download functionalities are using the official Maven repository.

.1.48v.source-code.JavaScriptEvaluator Maven / Gradle / Ivy

Go to download

ImageJ is an open source Java image processing program inspired by NIH Image for the Macintosh.

There is a newer version: 1.54p
Show newest version
import ij.plugin.*;
import ij.*;
import ij.plugin.frame.Editor;
import javax.script.*;

/** Implements the macro editor's Macros/Evaluate JavaScript command 
    on Linux and Windows systems running Java 1.6 or later. This command is
    implemented as a separately compilable plugin so that the ImageJ core
    can continue to be compiled using Java 1.4 and Java 1.5. The JavaScript
    plugin at 
    is used to evaluate JavaScript on Macs and on systems running versions
    of Java earlier than 1.6. */
public class JavaScriptEvaluator implements PlugIn, Runnable  {
	private Thread thread;
	private String script;
	private Object result;

	// run script in separate thread
	public void run(String script) {
		if (script.equals("")) return;
		if (!IJ.isJava16())
			{IJ.error("Java 1.6 or later required"); return;}
		this.script = script;
		thread = new Thread(this, "JavaScript"); 
		thread.setPriority(Math.max(thread.getPriority()-2, Thread.MIN_PRIORITY));
		thread.start();
	}

	// run script in current thread
	public String run(String script, String arg) {
		this.script = script;
		run();
		return null;
	}

	public void run() {
		result = null;
		Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
		try {
			ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
			ScriptEngine engine = scriptEngineManager.getEngineByName("ECMAScript");
			if (engine == null)
				{IJ.error("Could not find JavaScript engine"); return;}
			result = engine.eval(script);
		} catch(Throwable e) {
			String msg = e.getMessage();
			if (msg.startsWith("sun.org.mozilla.javascript.internal.EcmaError: "))
				msg = msg.substring(47, msg.length());
			if (msg.startsWith("sun.org.mozilla.javascript.internal.EvaluatorException"))
				msg = "Error"+msg.substring(54, msg.length());
			if (msg.indexOf("Macro canceled")==-1)
				IJ.log(msg);
		}
	}
	
	public String toString() {
		return result!=null?""+result:"";
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy