// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+
package org.xwt;
import java.io.*;
import java.util.*;
+import org.xwt.js.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
/** A ByteStream encapsulates a <i>source</i> of a stream of bytes --
* currently either a local file or a Base64-encoded XMLRPC/SOAP element */
-
-public class ByteStream extends JSObject {
+public class ByteStream extends JS.Obj {
private byte[] bytes = null;
private File file = null;
private ByteStream() { setSeal(true); }
+ ByteStream(String filename) { this(); this.file = new File(filename); }
+ ByteStream(byte[] bytes) { this(); this.bytes = bytes; }
public String toString() { return "ByteStream, source=" + (file == null ? "memory" : file.getAbsolutePath()); }
- public String getClassName() { return "ByteStream"; }
-
- ByteStream(String filename) {
- this();
- this.file = new File(filename);
- }
- ByteStream(byte[] bytes) {
- this();
- this.bytes = bytes;
- }
-
- public Object get(String name, Scriptable start) {
- if (name == null) return null;
- else if (name.equals("getUTF")) return getUTF;
+ public Object get(Object name) {
+ if (name.equals("getUTF")) return getUTF;
else if (name.equals("getDOM")) return getDOM;
else if (name.equals("fileName")) return file == null ? null : file.getAbsolutePath();
else return null;
}
- /** Helper class for defining functions. */
- private abstract class JSFunction extends JSObject implements Function {
- JSFunction() { this.setSeal(true); }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- }
-
private class XMLHelper extends XML {
Vector obStack = new Vector();
public XMLHelper() { super(BUFFER_SIZE); }
public void startElement(XML.Element c) throws XML.SchemaException {
- JSObject o = new JSObject();
- o.put("$name", null, c.localName);
- for(int i=0; i<c.len; i++) o.put(c.keys[i], null, c.vals[i]);
- o.put("$numchildren", null, new Integer(0));
+ JS o = new JS.Obj();
+ o.put("$name", c.localName);
+ for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
+ o.put("$numchildren", new Integer(0));
obStack.addElement(o);
}
public void endElement(XML.Element c) throws XML.SchemaException {
if (obStack.size() == 1) return;
- JSObject me = (JSObject)obStack.lastElement();
+ JS me = (JS)obStack.lastElement();
obStack.setSize(obStack.size() - 1);
- JSObject parent = (JSObject)obStack.lastElement();
- int numchildren = ((Integer)parent.get("$numchildren", null)).intValue();
- parent.put("$numchildren", null, new Integer(numchildren + 1));
- parent.put(numchildren, null, me);
+ JS parent = (JS)obStack.lastElement();
+ int numchildren = ((Integer)parent.get("$numchildren")).intValue();
+ parent.put("$numchildren", new Integer(numchildren + 1));
+ parent.put(new Integer(numchildren), me);
}
public void characters(char[] ch, int start, int length) throws XML.SchemaException {
String s = new String(ch, start, length);
- JSObject parent = (JSObject)obStack.lastElement();
- int numchildren = ((Integer)parent.get("$numchildren", null)).intValue();
- Object lastChild = parent.get(numchildren - 1, null);
+ JS parent = (JS)obStack.lastElement();
+ int numchildren = ((Integer)parent.get("$numchildren")).intValue();
+ Object lastChild = parent.get(new Integer(numchildren - 1));
if (lastChild instanceof String) {
- parent.put(numchildren - 1, null, lastChild + s);
+ parent.put(new Integer(numchildren - 1), lastChild + s);
} else {
- parent.put("$numchildren", null, new Integer(numchildren + 1));
- parent.put(numchildren, null, s);
+ parent.put("$numchildren", new Integer(numchildren + 1));
+ parent.put(new Integer(numchildren), s);
}
}
public void whitespace(char[] ch, int start, int length) {}
- public Scriptable doParse() throws JavaScriptException {
+ public JS doParse() throws JS.Exn {
try {
InputStream is = getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
parse(r);
} catch (XML.XMLException e) {
- throw new JavaScriptException("error parsing XML: " + e.toString());
+ throw new JS.Exn("error parsing XML: " + e.toString());
} catch (IOException e) {
if (Log.on) Log.log(ByteStream.class, "IO Exception while reading from file");
if (Log.on) Log.log(ByteStream.class, e);
- throw new JavaScriptException("error reading from ByteStream");
+ throw new JS.Exn("error reading from ByteStream");
}
- return obStack.size() >= 1 ? (Scriptable)obStack.elementAt(0) : null;
+ return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
}
}
os.close();
}
- private final JSFunction getDOM = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 0) return null;
+ private final JS.Function getDOM = new JS.Function() {
+ public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 0) return null;
return new XMLHelper().doParse();
}
};
- private final JSFunction getUTF = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 0) return null;
+ private final JS.Function getUTF = new JS.Function() {
+ public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 0) return null;
try {
CharArrayWriter caw = new CharArrayWriter();
InputStream is = getInputStream();
} catch (IOException e) {
if (Log.on) Log.log(ByteStream.class, "IO Exception while reading from file");
if (Log.on) Log.log(ByteStream.class, e);
- throw new JavaScriptException("error while reading from ByteStream");
+ throw new JS.Exn("error while reading from ByteStream");
}
}
};
// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
package org.xwt;
-import org.xwt.util.*;
import java.util.*;
import java.net.*;
import java.io.*;
+import org.xwt.js.*;
+import org.xwt.util.*;
/*
- While entities are limited to a subset of Unicode characters ,
- numeric character references can specify any character. Numeric
- character references may be given in decimal or hexadecimal, though
- browser support is stronger for decimal references. Decimal
- references are of the form &#number; while hexadecimal references
- take the case-insensitive form &#xnumber;. Examples of numeric
- character references include © or © for the copyright
- symbol, Α or Α for the Greek capital letter alpha, and
- ا or ا for the Arabic letter ALEF.
-
- http://www.htmlhelp.com/reference/html40/entities/special.html
- http://www.htmlhelp.com/reference/html40/entities/symbols.html
- http://www.htmlhelp.com/reference/html40/entities/latin1.html
-*/
+ * While entities are limited to a subset of Unicode characters ,
+ * numeric character references can specify any character. Numeric
+ * character references may be given in decimal or hexadecimal, though
+ * browser support is stronger for decimal references. Decimal
+ * references are of the form &#number; while hexadecimal references
+ * take the case-insensitive form &#xnumber;. Examples of numeric
+ * character references include © or © for the copyright
+ * symbol, Α or Α for the Greek capital letter alpha, and
+ * ا or ا for the Arabic letter ALEF.
+ *
+ * http://www.htmlhelp.com/reference/html40/entities/special.html
+ * http://www.htmlhelp.com/reference/html40/entities/symbols.html
+ * http://www.htmlhelp.com/reference/html40/entities/latin1.html
+ */
/**
* This class parses an InputStream containing HTML and returns it
/** true iff we have encountered an LI more recently than the last OL/UL */
private static boolean withinLI = false;
- public static synchronized JSObject parseReader(Reader r) throws IOException {
+ public static synchronized JS parseReader(Reader r) throws IOException {
CharStream cs = new CharStream(r);
- JSObject h = new JSObject();
+ JS.Obj h = new JS.Obj();
withinLI = false;
h.put("$name", "html");
// continue until we get an EOFException
}
- Object[] ids = h.getIds();
+ Object[] ids = h.keys();
for(int i=0; i<ids.length; i++) {
Object el = h.get((String)ids[i]);
- if (el instanceof JSObject && "html".equals(((JSObject)el).get("$name")))
- return (JSObject)el;
+ if (el instanceof JS && "html".equals(((JS)el).get("$name")))
+ return (JS)el;
}
return h;
* facilitate correcting broken HTML. Otherwise, this returns
* null.
*/
- private static String parseElement(CharStream cs, JSObject h) throws IOException {
+ private static String parseElement(CharStream cs, JS h) throws IOException {
// scan element name
while(Character.isSpace(cs.peek())) cs.get();
String elementName = parseElementName(cs);
* positioned at the character immediately after the right
* bracket closing the start-tag
*/
- private static String parseBody(CharStream cs, JSObject h, String elementName) throws IOException {
+ private static String parseBody(CharStream cs, JS h, String elementName) throws IOException {
String cdata = "";
int length = h.get("$numchildren") == null ? 0 : Integer.parseInt(h.get("$numchildren").toString());
while(true) {
try {
// scan subelement
if (cs.peek() != '/') {
- JSObject kid = new JSObject();
+ JS kid = new JS.Obj();
closetag = parseElement(cs, kid);
h.put(String.valueOf(length), kid);
h.put("$numchildren", new Integer(++length));
import java.net.*;
import java.io.*;
import java.util.*;
+import org.xwt.js.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.crypto.digests.*;
if (Platform.detectProxy() == null) throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
if (Log.on) Log.log(this, " could not resolve host " + host + "; using xmlrpc.xwt.org to ensure security");
try {
- Object ret = new XMLRPC("http://xmlrpc.xwt.org/RPC2/", "dns.resolve").call(new Object[] { host });
+ JS.Array args = new JS.Array();
+ args.addElement(host);
+ Object ret = new XMLRPC("http://xmlrpc.xwt.org/RPC2/", "dns.resolve").call(args);
if (ret == null || !(ret instanceof String)) throw new Exception(" xmlrpc.xwt.org returned non-String: " + ret);
resolvedHosts.put(host, ret);
return;
}
/** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
- public Socket attemptPAC(Function pacFunc) {
+ public Socket attemptPAC(org.xwt.js.JS.Function pacFunc) {
+ throw new Error("not implemented");
+ // FIXME
+ /*
if (Log.verbose) Log.log(this, "evaluating PAC script");
String pac = null;
try {
- Object obj = pacFunc.call(Context.enter(), Proxy.proxyAutoConfigRootScope, null, new Object[] { url.toString(), url.getHost() });
+ Object obj = pacFunc.call(Proxy.proxyAutoConfigRootScope, null, new Object[] { url.toString(), url.getHost() });
if (Log.verbose) Log.log(this, " PAC script returned \"" + obj + "\"");
pac = obj.toString();
} catch (Throwable e) {
}
if (Log.on) Log.log(this, "all PAC results exhausted");
return null;
+ */
}
// HTTPException ///////////////////////////////////////////////////////////////////////////////////
- static class HTTPException extends IOException {
- public HTTPException(String s) { super(s); }
- }
+ static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
// HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
import java.util.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
/**
* A singleton class (one instance per JVM) that implements a queue
private static MessageQueueWatcher watcher = new MessageQueueWatcher();
// HACK for debugging purposes
- Function lastfunc = null;
+ Object lastfunc = null;
Message lastmessage = null;
/**
public void run() {
while(true) {
if ((m != null && m == MessageQueue.currentlyPerforming) || MessageQueue.working) {
- Context cx;
- String what;
- if (m == null) {
- cx = Context.getContextForThread(MessageQueue.singleton);
- what = "trap";
- } else if (m instanceof ThreadMessage) {
- ThreadMessage tm = (ThreadMessage)m;
- cx = Context.getContextForThread(tm);
+ String what, where;
+ if (m != null && m instanceof ThreadMessage) {
+ where = org.xwt.js.JS.getCurrentFunctionSourceName((ThreadMessage)m);
what = "background thread";
+ } else if (m != null) {
+ where = org.xwt.js.JS.getCurrentFunctionSourceName(MessageQueue.singleton);
+ what = "event trap";
} else {
- cx = Context.getContextForThread(MessageQueue.singleton);
+ where = org.xwt.js.JS.getCurrentFunctionSourceName(MessageQueue.singleton);
what = "script";
- }
- if (Log.on) Log.log(this, "note: executing same " + what + " for " + (System.currentTimeMillis() - t) / 1000 + "s" +
- " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
+ }
+ if (Log.on) Log.log(this, "note: executing same " + what +
+ " for " + (System.currentTimeMillis() - t) / 1000 + "s" +
+ " at " + where);
} else {
m = MessageQueue.currentlyPerforming;
t = System.currentTimeMillis();
if (Log.on) Log.log(Platform.class, "XWT VM detection: vendor = " + vendor);
if (Log.on) Log.log(Platform.class, " version = " + version);
if (Log.on) Log.log(Platform.class, " os = " + os_name + " [version " + os_version + "]");
- if (Log.on && Main.applet != null) Log.log(Platform.class, " browser = " + Main.applet.getParameter("browser"));
if (platform_class == null) {
if (Log.on) Log.log(Platform.class, "Unable to detect JVM");
protected void _running() {}
/** quits XWT */
- protected void _exit() {
- if (Main.applet == null) {
- System.exit(0);
- } else {
- // just block ourselves forever
- // FIXME
- new Semaphore().block();
- }
- }
+ protected void _exit() { System.exit(0); }
/** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
protected void _criticalAbort(String message) { _exit(); }
b.set(Box.size, 0, b.size(0) < Surface.scarPicture.getWidth() ? Surface.scarPicture.getWidth() : b.size(0));
b.set(Box.size, 1, b.size(1) < Surface.scarPicture.getHeight() ? Surface.scarPicture.getHeight() : b.size(1));
- Object titlebar = b.get("titlebar", null, true);
+ Object titlebar = b.get("titlebar", true);
if (titlebar != null) ret.setTitleBarText(titlebar.toString());
- Object icon = b.get("icon", null, true);
+ Object icon = b.get("icon", true);
if (icon != null && !"".equals(icon)) {
Picture pic = Box.getPicture(icon.toString());
if (pic != null) ret.setIcon(pic);
import java.net.*;
import java.io.*;
import java.util.*;
+import org.xwt.js.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
import org.bouncycastle.util.encoders.Base64;
/** encapsulates most of the proxy logic; some is shared in HTTP.java */
public String[] excluded = null;
/** the PAC script */
- public Function proxyAutoConfigFunction = null;
+ public JS.Function proxyAutoConfigFunction = null;
public static Proxy detectProxyViaManual() {
Proxy ret = new Proxy();
return ret;
}
- public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
-
- public static Function getProxyAutoConfigFunction(String url) {
+ //public static JS proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
+ public static JS.Function getProxyAutoConfigFunction(String url) {
+ throw new Error("not implemented");
+ // FIXME
+ /*
try {
Context cx = Context.enter();
cx.setOptimizationLevel(-1);
Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
scr.exec(cx, proxyAutoConfigRootScope);
- return (Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
+ return (JS.Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
} catch (Exception e) {
if (Log.on) {
Log.log(Platform.class, "WPAD detection failed due to:");
if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
- else if (e instanceof JavaScriptException) {
+ else if (e instanceof JS.Exn) {
try {
XWT.recursivePrintObject.call(Context.enter(), null, null, new Object[] {
- ((JavaScriptException)e).getValue() });
+ ((JS.Exn)e).getValue() });
} catch (Exception e2) {
Log.log(Platform.class, e);
}
}
return null;
}
+ */
}
// ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
-
- public static class ProxyAutoConfigRootScope extends ScriptableObject {
+ /*
+ public static class ProxyAutoConfigRootScope extends JSObject {
public String getClassName() { return "ProxyAutoConfigRootScope"; }
ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
- public Object get(String name, Scriptable start) {
+ public Object get(String name, JS start) {
if (name.equals("isPlainHostName")) return isPlainHostName;
else if (name.equals("dnsDomainIs")) return dnsDomainIs;
else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
else return super.get(name, start);
}
- private static final JSObject proxyConfigBindings = new JSObject();
- private static final JSObject ProxyConfig = new JSObject() {
- public Object get(String name, Scriptable start) {
+ private static final JS.Object proxyConfigBindings = new JS.Object();
+ private static final JS.Object ProxyConfig = new JS.Object() {
+ public Object get(String name, JS start) {
if (name.equals("bindings")) return proxyConfigBindings;
return null;
}
};
- private static abstract class JSFunction extends JSObject implements Function {
- JSFunction() { setSeal(true); }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- }
-
- private static final JSFunction isPlainHostName = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function isPlainHostName = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
}
};
- private static final JSFunction dnsDomainIs = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function dnsDomainIs = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
}
};
- private static final JSFunction localHostOrDomainIs = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function localHostOrDomainIs = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
return (args[0].toString().equals(args[1].toString()) ||
(args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
Boolean.TRUE : Boolean.FALSE;
}
};
- private static final JSFunction isResolvable = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function isResolvable = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
try {
return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
} catch (UnknownHostException e) {
}
};
- private static final JSFunction isInNet = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function isInNet = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
if (args.length != 3) return Boolean.FALSE;
try {
byte[] host = InetAddress.getByName(args[0].toString()).getAddress();
(host[3] & mask[3]) == net[3]) ?
Boolean.TRUE : Boolean.FALSE;
} catch (Exception e) {
- throw new JavaScriptException("exception in isInNet(): " + e);
+ throw new JS.Exn("exception in isInNet(): " + e);
}
}
};
- private static final JSFunction dnsResolve = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function dnsResolve = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
try {
return InetAddress.getByName(args[0].toString()).getHostAddress();
} catch (UnknownHostException e) {
}
};
- private static final JSFunction myIpAddress = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function myIpAddress = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
}
};
- private static final JSFunction dnsDomainLevels = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function dnsDomainLevels = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
String s = args[0].toString();
int i = 0;
while((i = s.indexOf('.', i)) != -1) i++;
return false;
}
- private static final JSFunction shExpMatch = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function shExpMatch = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
String[] arr = new String[st.countTokens()];
String s = args[0].toString();
public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
- private static final JSFunction weekdayRange = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ private static final JS.Function weekdayRange = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
Calendar c = new GregorianCalendar();
c.setTimeZone(tz);
}
};
- private static final JSFunction dateRange = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- throw new JavaScriptException("XWT does not support dateRange() in PAC scripts");
+ private static final JS.Function dateRange = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
+ throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
}
};
- private static final JSFunction timeRange = new JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- throw new JavaScriptException("XWT does not support timeRange() in PAC scripts");
+ private static final JS.Function timeRange = new JS.Function() {
+ public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
+ throw new JS.Exn("XWT does not support timeRange() in PAC scripts");
}
};
}
-
+ */
}
import java.util.zip.*;
import java.lang.*;
import java.applet.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
import org.xwt.util.*;
/**
if (name.endsWith(".xwt")) {
String name2 = name.substring(0, name.length() - 4);
Static.createStatic(name2.replace(File.separatorChar, '.'), false);
- usedPackages.put(JSObject.nodeNameToPackageName(name2.replace('/', '.')), new Object());
}
bytes.put(name.replace(File.separatorChar, '.'), file);
}
/** Load an archive from an inputstream. */
public static synchronized void loadArchive(InputStream is) throws IOException { loadArchive(is, 0, null); }
- public static synchronized void loadArchive(InputStream is, final int length, final Function callback) throws IOException {
+ public static synchronized void loadArchive(InputStream is, final int length, final JS.Function callback) throws IOException {
// random placeholder
Object thisArchive = new Object();
int ret = super.read(b, off, len);
if (clear && callback != null) {
clear = false;
- ThreadMessage.newthread(new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ ThreadMessage.newthread(new JS.Function() {
+ public Object _call(JS.Array args_) throws JS.Exn {
try {
- callback.call(cx, null, null, new Object[] { new Double(bytesDownloaded), new Double(length) });
+ JS.Array args = new JS.Array();
+ args.addElement(new Double(bytesDownloaded));
+ args.addElement(new Double(length));
+ callback.call(args);
} finally {
clear = true;
}
// placeholder so resolveResource() works properly
bytes.put(name.replace('/', '.'), new byte[] { });
name = name.substring(0, name.length() - 4);
-
- String packageName = JSObject.nodeNameToPackageName(name.replace('/', '.'));
- Object user = usedPackages.get(packageName);
- if (user != null && user != thisArchive) {
- if (Log.on) Log.log(Resources.class, "templates have already been loaded into " + packageName + "; refusing to load " + name);
- } else {
- usedPackages.put(packageName, thisArchive);
- Static.createStatic(name.replace('/', '.'), false);
- Template.buildTemplate(zis, name.replace('/', '.'), t);
- }
+ Static.createStatic(name.replace('/', '.'), false);
+ Template.buildTemplate(zis, name.replace('/', '.'), t);
} else {
bytes.put(name.replace('/', '.'), isToByteArray(zis));
import java.io.*;
import java.net.*;
import java.util.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
import org.xwt.util.*;
import org.bouncycastle.util.encoders.Base64;
String nameSpace = null;
/** When you get a property from an SOAP, it just returns another SOAP with the property name tacked onto methodname. */
- public Object get(String name, Scriptable start) {
+ public Object get(String name) {
return new SOAP(url.toString(), (methodname.equals("") ? "" : methodname + ".") + name, http, action, nameSpace);
}
if (name.equals("SOAP-ENV:Fault")) fault = true;
// add a generic struct; we'll change this if our type is different
- objects.addElement(new JSObject(false));
+ objects.addElement(new JS.Obj());
for(int i=0; i<keys.length; i++) {
String key = keys[i];
objects.addElement(null);
} else if (value.endsWith("arrayType") || value.endsWith("Array") || key.endsWith("arrayType")) {
objects.removeElementAt(objects.size() - 1);
- objects.addElement(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, new Object[] { } ));
+ objects.addElement(new JS.Array());
}
}
}
if (objects.size() < 2) return;
// our parent "should" be an aggregate type -- add ourselves to it.
- if (parent != null && parent instanceof NativeArray) {
+ if (parent != null && parent instanceof JS.Array) {
objects.removeElementAt(objects.size() - 1);
- ((NativeArray)parent).put((int)((NativeArray)parent).jsGet_length(), (NativeArray)parent, me);
+ ((JS.Array)parent).addElement(me);
- } else if (parent != null && parent instanceof Scriptable) {
+ } else if (parent != null && parent instanceof JS) {
objects.removeElementAt(objects.size() - 1);
- ((Scriptable)parent).put(name, (Scriptable)parent, me);
+ ((JS)parent).put(name, me);
}
}
/** Appends the SOAP representation of <code>o</code> to <code>sb</code> */
- void appendObject(String name, Object o, StringBuffer sb) throws JavaScriptException {
+ void appendObject(String name, Object o, StringBuffer sb) throws JS.Exn {
if (o instanceof Number) {
if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
sb.append(" <" + name + " xsi:type=\"xsd:int\">");
} catch (IOException e) {
if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via SOAP");
if (Log.on) Log.log(this, e);
- throw new JavaScriptException("caught IOException while attempting to send a ByteStream via SOAP");
+ throw new JS.Exn("caught IOException while attempting to send a ByteStream via SOAP");
}
} else if (o instanceof String) {
}
sb.append("</" + name + ">\r\n");
- } else if (o instanceof NativeArray) {
- NativeArray na = (NativeArray)o;
- sb.append(" <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + na.jsGet_length() + "]\">");
- for(int i=0; i<na.jsGet_length(); i++)
- appendObject("item", na.get(i, na), sb);
+ } else if (o instanceof JS.Array) {
+ JS.Array a = (JS.Array)o;
+ sb.append(" <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + a.length() + "]\">");
+ for(int i=0; i<a.length(); i++) appendObject("item", a.elementAt(i), sb);
sb.append("</" + name + ">\r\n");
- } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
- Scriptable s = (Scriptable)o;
+ } else if (o instanceof JS) {
+ JS j = (JS)o;
sb.append(" <" + name + ">");
- Object[] ids = s.getIds();
- for(int i=0; i<ids.length; i++)
- appendObject(ids[i].toString(), s.get(ids[i].toString(), s), sb);
+ Object[] ids = j.keys();
+ for(int i=0; i<ids.length; i++) appendObject(ids[i].toString(), j.get(ids[i].toString()), sb);
sb.append("</" + name + ">\r\n");
}
}
- protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
+ protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
// build up the request
StringBuffer content = new StringBuffer();
content.append("SOAPAction: " + action + "\r\n\r\n");
content.append(methodname);
content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
content.append(">\r\n");
- if (args.length > 0) {
- Object[] o = ((Scriptable)args[0]).getIds();
+ if (args.length() > 0) {
+ Object[] o = ((JS)args.elementAt(0)).keys();
for(int i=0; i<o.length; i++)
- appendObject(o[i].toString(), ((Scriptable)args[0]).get(o[i].toString(), (Scriptable)args[0]), content);
+ appendObject(o[i].toString(), ((JS)args.elementAt(0)).get(o[i].toString()), content);
}
content.append(" </" + methodname + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
return content.toString();
// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
package org.xwt;
-import org.mozilla.javascript.*;
-import org.xwt.util.*;
import java.util.*;
import java.net.*;
import java.text.*;
+import org.xwt.js.*;
+import org.xwt.util.*;
/**
* A helper class for properties of Box which require special
else if (s.equals("pink")) newcolor = pink;
else if (s.equals("yellow")) newcolor = yellow;
else if (s.equals("white")) newcolor = white;
- else if (Log.on) Log.log(this, "invalid color \"" + s + "\" at " +
- Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
+ else if (Log.on) Log.log(this, "invalid color \"" + s + "\" at " + JS.getCurrentFunctionSourceName());
if (newcolor == b.color) return;
b.color = newcolor;
b.dirty();
else if (s.equals("pink")) newtextcolor = pink;
else if (s.equals("yellow")) newtextcolor = yellow;
else if (s.equals("white")) newtextcolor = white;
- else if (Log.on) Log.log(this, "invalid color \"" + s + "\" at " +
- Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
-
+ else if (Log.on) Log.log(this, "invalid color \"" + s + "\" at " + JS.getCurrentFunctionSourceName());
if (newtextcolor == b.textcolor) return;
b.textcolor = newtextcolor;
b.dirty();
if (Log.on) Log.log(this,
"ISO Control characters are not permitted in box text strings; offending character is ASCII " +
((int)t.charAt(i)));
- /* FIXME: reinstate
return;
- */
}
- // FIXME: don't know why this is needed
+ // FEATURE: try removing the following line; it appears to be redundant
b.dirty();
-
b.text = t;
b.textupdate();
b.dirty();
specialBoxProperties.put("static", new SpecialBoxProperty() {
public Object get(Box b) {
- String cfsn = JSObject.getCurrentFunctionSourceName();
+ String cfsn = JS.getCurrentFunction().getSourceName();
for(int i=0; i<cfsn.length() - 1; i++)
if (cfsn.charAt(i) == '.' && (cfsn.charAt(i+1) == '_' || Character.isDigit(cfsn.charAt(i+1)))) {
cfsn = cfsn.substring(0, i);
specialBoxProperties.put("font", new SpecialBoxProperty() {
public Object get(Box b) { return b.font; }
public void put(Box b, Object value) {
- if (value == null) value = Platform.getDefaultFont();
- b.font = value.toString();
- b.textupdate();
+ b.font = value == null ? null : value.toString();
+ b.fontChanged();
b.dirty();
} });
public Object get(Box b) { return new Integer(b.getParent() == null || b.surface == null ? 0 : b.pos(0)); }
public void put(Box b, Object value) {
if (b.surface == null || b.getParent() == null) return;
- b.put("x", null, new Integer(stoi(value) - stoi(get(b.getParent()))));
+ b.put("x", new Integer(stoi(value) - stoi(get(b.getParent()))));
}
});
public Object get(Box b) { return new Integer(b.getParent() == null || b.surface == null ? 0 : b.pos(1)); }
public void put(Box b, Object value) {
if (b.surface == null || b.getParent() == null) return;
- b.put("y", null, new Integer(stoi(value) - stoi(get(b.getParent()))));
+ b.put("y", new Integer(stoi(value) - stoi(get(b.getParent()))));
}
});
for(Box c = b.prevSibling(); c != null; c = c.prevSibling()) {
Box siblingChild = c.whoIs(c.surface.mousex, c.surface.mousey);
if (siblingChild != null) {
- siblingChild.put(name, c, value);
+ siblingChild.put(name, value);
return;
}
}
if (b.getParent() != null)
- b.getParent().put(name, b.getParent(), value);
+ b.getParent().put(name, value);
}};
specialBoxProperties.put("Press1", mouseEventHandler);
}
/** helper that converts a String to a int according to JavaScript coercion rules */
- private static class Apply extends JSObject.JSFunction {
+ public static class Apply extends JS.Function {
Box b;
public Apply(Box b) { this.b = b; }
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ public Object _call(JS.Array args) throws JS.Exn {
// apply a template
- if (args[0] instanceof String) {
- String templatename = (String)args[0];
+ if (args.elementAt(0) instanceof String) {
+ String templatename = (String)args.elementAt(0);
Template t = Template.getTemplate(templatename, null);
if (t == null) {
- if (Log.on) Log.log(this, "template " + templatename + " not found at " +
- Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
+ if (Log.on) Log.log(this, "template " + templatename + " not found at " + JS.getFileAndLine());
} else {
if (ThreadMessage.suspendThread()) try {
- Function callback = args.length < 2 ? null : (Function)args[1];
+ JS.Function callback = args.length() < 2 ? null : (Function)args.elementAt(1);
t.apply(b, null, null, callback, 0, t.numUnits());
} finally {
ThreadMessage.resumeThread();
}
// apply a list of properties
- } else if (args[0] instanceof Scriptable && !(args[0] instanceof Box)) {
- // FIXME: need to ensure that this is putGlobally(), but still run traps...
- Scriptable s = (Scriptable)args[0];
- Object[] keys = s.getIds();
- for(int j=0; j<keys.length; j++) b.put(keys[j].toString(), null, s.get(keys[j].toString(), s));
+ } else if (args.elementAt(0) instanceof JS && !(args.elementAt(0) instanceof Box)) {
+ JS s = (JS)args.elementAt(0);
+ Object[] keys = s.keys();
+ for(int j=0; j<keys.length; j++) b.put(keys[j].toString(), s);
}
return b;
// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
package org.xwt;
+import org.xwt.js.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
/** implements objects in the xwt.static.* namespace */
-public class Static extends JSObject {
+public class Static extends JS.Scope {
public static Static getStatic(String resourcename) {
Template t = Template.getTemplate(resourcename, null);
public boolean ispackage = false;
private Static(String resourcename, boolean ispackage) {
- super(true);
+ super(null);
cache.put(resourcename, this);
this.resourcename = resourcename;
this.ispackage = ispackage;
/** creates a new static representing a package */
public Static(String resourcename) { this(resourcename, true); }
- public Object get(String name, Scriptable start) {
- if (name == null) return null;
-
- // hack since Rhino needs to be able to grab these functions to create new objects
- if (name.equals("Object")) return JSObject.defaultObjects.get("Object", null);
- if (name.equals("Array")) return JSObject.defaultObjects.get("Array", null);
- if (name.equals("Function")) return JSObject.defaultObjects.get("Function", null);
- if (name.equals("TypeError")) return JSObject.defaultObjects.get("TypeError", null);
-
- if ("xwt".equals(name))
- for(Scriptable cur = Context.enter().currentFunction; cur != null; cur = cur.getParentScope())
- if (cur == this) return XWT.singleton;
-
- if (!ispackage) return super.get(name, start);
+ public Object get(String name) {
+ if (!ispackage) return super.get(name);
return getStatic(resourcename + (resourcename.length() == 0 ? "" : ".") + name);
}
final Box who = root.whoIs(mousex, mousey);
MessageQueue.add(new Message() { public void perform() {
Platform.clipboardReadEnabled = true;
- root.put("Press3", null, Boolean.TRUE);
+ root.put("Press3", Boolean.TRUE);
Platform.clipboardReadEnabled = false;
}});
}
Box b = (Box)keywatchers.elementAt(i);
for(Box cur = b; cur != null; cur = cur.getParent())
if (cur.invisible) continue outer;
- b.put("KeyPressed", null, key);
+ b.put("KeyPressed", key);
}
Platform.clipboardReadEnabled = false;
}
Box b = (Box)keywatchers.elementAt(i);
for(Box cur = b; cur != null; cur = cur.getParent())
if (cur.invisible) continue outer;
- b.put("KeyReleased", null, key);
+ b.put("KeyReleased", key);
}
}});
}
// Root gets motion events outside itself (if trapped, of course)
if (root.is_trapped("Move") && !root.inside(oldmousex, oldmousey) && !root.inside(mousex, mousey) && (button1 || button2 || button3))
- root.put("Move", null, Boolean.TRUE);
+ root.put("Move", Boolean.TRUE);
root.Move(oldmousex, oldmousey, mousex, mousey);
if (!cursor.equals(oldcursor)) syncCursor();
root._size_1 = (int)height;
root.mark_for_prerender();
- root.put("SizeChange", null, Boolean.TRUE);
+ root.put("SizeChange", Boolean.TRUE);
}
while (root.needs_prerender || abort) {
MessageQueue.add(this);
}
- public void perform() { boxContainingMouse.put(name, root, value); }
+ public void perform() { boxContainingMouse.put(name, value); }
public String toString() { return "SimpleMessage [name=" + name + ", value=" + value + "]"; }
}
import java.util.zip.*;
import java.util.*;
import java.lang.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
import org.xwt.util.*;
/**
private boolean changed = false;
/** the script on the static node of this template, null if it has already been executed */
- private Script staticscript = null;
+ private JS.Script staticscript = null;
/** the script on this node */
- private Script script = null;
+ private JS.Script script = null;
/** during XML parsing, this holds the list of currently-parsed children; null otherwise */
private Vec childvect = new Vec();
* @param pboxes a vector of all box parents on which to put $-references
* @param ptemplates a vector of the nodeNames to recieve private references on the pboxes
*/
- void apply(Box b, Vec pboxes, Vec ptemplates, Function callback, int numerator, int denominator) {
+ void apply(Box b, Vec pboxes, Vec ptemplates, JS.Function callback, int numerator, int denominator) {
int original_numerator = numerator;
for(int i=0; i<pboxes.size(); i++) {
Box parent = (Box)pboxes.elementAt(i);
String parentNodeName = (String)ptemplates.elementAt(i);
- parent.putPrivately("$" + id, b, parentNodeName);
+ parent.put("$" + id, b);
}
if (script != null || (redirect != null && !"self".equals(redirect))) {
}
for (int i=0; children != null && i<children.length; i++) {
- b.put(Integer.MAX_VALUE, null, new Box(children[i], pboxes, ptemplates, callback, numerator, denominator));
+ b.put(Integer.MAX_VALUE, new Box(children[i], pboxes, ptemplates, callback, numerator, denominator));
numerator += children[i].numUnits();
}
// whom to redirect to; doesn't take effect until after script runs
Box redir = null;
- if (redirect != null && !"self".equals(redirect))
- redir = (Box)b.getPrivately("$" + redirect, nodeName);
+ if (redirect != null && !"self".equals(redirect)) redir = (Box)b.get("$" + redirect);
if (script != null) try {
- Context cx = Context.enter();
- script.exec(cx, b);
- } catch (EcmaError e) {
- if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown while instantiating " + nodeName + " at " + e.getSourceName() + ":" + e.getLineNumber());
- } catch (JavaScriptException e) {
+ JS.Array jsa = new JS.Array();
+ jsa.addElement(b);
+ script.call(jsa);
+ } catch (JS.Exn e) {
if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown while instantiating " + nodeName + " at " + e.sourceFile + ":" + e.line);
}
for(int i=0; keys != null && i<keys.length; i++) {
- Context.enter().interpreterSourceFile = nodeName;
- Context.enter().interpreterLine = startLine;
+ // FIXME: make sure that if exceptions are thrown in here, the line number of the offending XML is logged
if (keys[i] == null) { }
else if (keys[i].equals("border") || keys[i].equals("image") &&
!vals[i].toString().startsWith("http://") && !vals[i].toString().startsWith("https://")) {
String s = Resources.resolve(vals[i].toString() + ".png", importlist);
- if (s != null) b.put(keys[i], null, s.substring(0, s.length() - 4));
+ if (s != null) b.put(keys[i], s.substring(0, s.length() - 4));
else if (Log.on) Log.log(this, "unable to resolve image " + vals[i].toString() + " referenced in attributes of " + nodeName);
}
- else b.put(keys[i], null, vals[i]);
+ else b.put(keys[i], vals[i]);
}
if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
if (callback != null)
try {
- callback.call(Context.enter(), null, null, new Object[] { new Double(numerator), new Double(denominator) });
- } catch (EcmaError e) {
- if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from within progress callback at " + e.getSourceName() + ":" + e.getLineNumber());
- } catch (JavaScriptException e) {
- if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from within progress callback at " + e.sourceFile + ":" + e.line);
+ JS.Array args = new JS.Array();
+ args.addElement(new Double(numerator));
+ args.addElement(new Double(denominator));
+ callback.call(args);
+ } catch (JS.Exn e) {
+ if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
}
if (Thread.currentThread() instanceof ThreadMessage) try {
- XWT.yield.call(Context.enter(), null, null, null);
- } catch (JavaScriptException e) {
- if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from within yield at " + e.sourceFile + ":" + e.line);
+ XWT.sleep(0);
+ } catch (JS.Exn e) {
+ if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
}
}
}
/** adds a theme mapping, retemplatizing as needed */
- public static void retheme(Function callback) {
+ public static void retheme(JS.Function callback) {
XWF.flushXWFs();
// clear changed marker and relink
if (callback != null)
try {
- callback.call(Context.enter(), null, null, new Object[] { new Double(1.0), new Double(1.0) });
- } catch (EcmaError ex) {
- if (Log.on) Log.log(Template.class, "WARNING: uncaught interpreter exception: " + ex.getMessage());
- if (Log.on) Log.log(Template.class, " thrown from within progress callback at " + ex.getSourceName() + ":" + ex.getLineNumber());
- } catch (JavaScriptException ex) {
+ JS.Array args = new JS.Array();
+ args.addElement(new Double(1.0));
+ args.addElement(new Double(1.0));
+ callback.call(args);
+ } catch (JS.Exn ex) {
if (Log.on) Log.log(Template.class, "WARNING: uncaught ecmascript exception: " + ex.getMessage());
- if (Log.on) Log.log(Template.class, " thrown from within progress callback at " + ex.sourceFile + ":" + ex.line);
}
}
/** template reapplication procedure */
private static void reapply(Box b) {
+ throw new Error("not implemented");
+ /*
// Ref 7.5.1: check if we need to retemplatize
boolean retemplatize = false;
if (b.templatename != null) {
// Recurse
for(Box j = b.getChild(0); j != null; j = j.nextSibling()) reapply(j);
+ */
}
/** runs statics, resolves string references to other templates into actual Template instance references, and sets <tt>change</tt> as needed */
private void link(boolean force) {
if (staticscript != null) try {
- Scriptable s = Static.createStatic(nodeName, false);
+ JS.Scope s = Static.createStatic(nodeName, false);
if (staticscript != null) {
- Script temp = staticscript;
- ((InterpretedScript)temp).setParentScope(s); // so we know how to handle Static.get("xwt")
+ JS.Script temp = staticscript;
staticscript = null;
- temp.exec(Context.enter(), s);
+
+ // we layer a transparent scope over the Static so that we can catch requests for the xwt object
+ // yet not screw up paths that include a package called xwt (ie xwt.static.org.xwt.foo)
+ JS.Scope varScope = new JS.Scope(s) {
+ public boolean isTransparent() { return true; }
+ public Object get(Object key) {
+ if ("xwt".equals(key)) return XWT.singleton; else return super.get(key);
+ } };
+
+ JS.Array args = new JS.Array();
+ args.addElement(varScope);
+ temp.call(args);
}
- } catch (EcmaError e) {
- if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown while executing <static/> block for " + nodeName +
- " at " + e.getSourceName() + ":" + e.getLineNumber());
- } catch (JavaScriptException e) {
+ } catch (JS.Exn e) {
if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown while executing <static/> block for " + nodeName + " at " + e.sourceFile + ":" + e.line);
}
if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
}
}
- private Script genscript(boolean isstatic) {
- Script thisscript = null;
- Context cx = Context.enter();
- cx.setOptimizationLevel(-1);
-
+ private JS.Script genscript(boolean isstatic) {
+ JS.Script thisscript = null;
try {
- thisscript = cx.compileReader(null, new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start, null);
- } catch (EcmaError ee) {
- if (Log.on) Log.log(this, ee.getMessage() + " at " + ee.getSourceName() + ":" + ee.getLineNumber());
- thisscript = null;
- } catch (EvaluatorException ee) {
+ thisscript = JS.Script.parse(new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start);
+ } catch (JS.Exn ee) {
if (Log.on) Log.log(this, " ERROR: " + ee.getMessage());
thisscript = null;
} catch (IOException ioe) {
// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
package org.xwt;
-import org.xwt.util.*;
import java.util.*;
-import org.mozilla.javascript.*;
+import org.xwt.util.*;
+import org.xwt.js.*;
/**
* A background thread. All threads created with <tt>xwt.thread</tt>
private volatile static int threadcount = 0;
/** the JavaScript function that we are executing */
- volatile Function f;
+ volatile JS.Function f;
/** the ThreadMessage thread blocks on this before executing any JavaScript */
Semaphore go = new Semaphore();
private static Object[] emptyobj = new Object[] { };
/** creates a new thread to execute function <tt>f</tt> */
- public static synchronized void newthread(Function f) {
+ public static synchronized void newthread(JS.Function f) {
ThreadMessage ret = (ThreadMessage)spare.remove(false);
if (ret == null) {
if (threadcount < Platform.maxThreads()) ret = new ThreadMessage();
// put ourselves in the background
Thread thread = Thread.currentThread();
if (!(thread instanceof ThreadMessage)) {
- Context cx = Context.enter();
- if (Log.on) Log.log(ThreadMessage.class, "attempt to perform background-only operation in a foreground thread at " +
- cx.interpreterSourceFile + ":" + cx.interpreterLine);
+ if (Log.on) Log.log(ThreadMessage.class, "attempt to perform background-only operation in a foreground thread at " + JS.getCurrentFunctionSourceName());
return false;
}
ThreadMessage mythread = (ThreadMessage)thread;
public void run() {
try {
threadcount++;
- Context cx = Context.enter();
while (true) {
try {
go.block();
- f.call(cx, f.getParentScope(), f.getParentScope(), emptyobj);
- } catch (EcmaError e) {
- if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from background thread at " + e.getSourceName() + ":" + e.getLineNumber());
- } catch (JavaScriptException e) {
- if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from background thread at " + e.sourceFile + ":" + e.line);
+ f.call(new JS.Array());
+ } catch (JS.Exn e) {
+ if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
}
done.release();
synchronized(waiting) {
if (waiting.size() > 0) {
- f = (Function)waiting.remove(false);
+ f = (JS.Function)waiting.remove(false);
MessageQueue.add(this);
} else if (spare.size() < 10) {
spare.append(this);
// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
package org.xwt;
-import org.xwt.util.*;
import java.util.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
+import org.xwt.util.*;
/**
* This class encapsulates a single trap placed on a given node. The
private Box trapee = null;
/** If this trap was actually placed on a root proxy, this is a reference to the proxy */
- private Scriptable rp = null;
+ private JS rp = null;
/** the function for this trap */
- Function f = null;
+ JS.Function f = null;
/** the name of the property that this trap was placed on */
private String name = null;
* @param isreadtrap true iff this is a read (double-underscore) trap
* @param rp if this trap is being placed via a rootproxy, this is that proxy object.
*/
- static void addTrap(Box trapee, String name, Function f, boolean isreadtrap, Scriptable rp) {
+ static void addTrap(Box trapee, String name, JS.Function f, boolean isreadtrap, JS rp) {
if (PROHIBITED.get(name) != null || name.startsWith("xwt_")) {
Log.log(Trap.class, "Error: you cannot place traps on special property \"" + name + "\"");
}
// find out what script is currently running
- String placerNodeName = JSObject.getCurrentFunctionSourceName();
+ String placerNodeName = JS.getCurrentFunctionSourceName();
// check if this script has already placed a trap on this property
if (trapee.traps == null) trapee.traps = new Hash(10, 3);
public static Trap getTrap(Box b, String name) {
if (b.traps == null) return null;
- String currentFunctionNodeName = JSObject.getCurrentFunctionSourceName();
+ String currentFunctionNodeName = JS.getCurrentFunctionSourceName();
for(Trap cur = (Trap)b.traps.get(name); cur != null; cur = cur.next)
if (cur.placerNodeName.equals(currentFunctionNodeName))
return cur;
}
/** Called by Rhino's arguments.cascade. Note: cx will be null if this was invoked from perform() rather than from a script. */
- public static final Function cascadeFunction = new CascadeFunction();
- private static class CascadeFunction extends JSObject implements Function {
+ public static final CascadeFunction cascadeFunction = new CascadeFunction();
+ private static class CascadeFunction extends JS.Function {
CascadeFunction() { setSeal(true); }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) {
+ public Object _call(JS.Array args) { return _call(args, JS.getCurrentFunction()); }
+ public Object _call(JS.Array args, Function currentFunction) {
Trap currentTrap = TrapContext.get().currentTrap;
- if (currentTrap == null || (cx != null && Context.getCurrentContext().currentFunction != currentTrap.f)) {
+ /*
+ if (currentTrap == null || (currentFunction != currentTrap.f)) {
if (Log.on) Log.log(this, "attempt to cascade() by a function that was not invoked as a trap at " +
- cx.interpreterSourceFile + ":" + cx.interpreterLine);
+ currentFunction.getSourceName());
+ if (Log.on) Log.log(this, "currentfunction == " + currentFunction);
+ if (Log.on) Log.log(this, "currentTrap.f == " + currentTrap.f);
return null;
}
- if (args.length != 0) TrapContext.get().putCascadeHappened = true;
+ */
+ if (args.length() != 0) TrapContext.get().putCascadeHappened = true;
Trap t = currentTrap.next;
// if we've hit the end of the trap stack, just do a put(,,,true)
if (t == null) {
- if (args.length == 0) return currentTrap.trapee.get(currentTrap.name, currentTrap.trapee, true);
- currentTrap.trapee.put(currentTrap.name, currentTrap.trapee, args[0], true);
+ if (args.length() == 0) return currentTrap.trapee.get(currentTrap.name, true);
+ currentTrap.trapee.put(currentTrap.name, args.elementAt(0), true);
return null;
}
return t.perform(args);
else return current.name;
}
- /** removes all traps whose function's ultimate parent scope is <tt>b</tt>. Used for retheming */
- public static void removeAllTrapsByBox(Box b) {
- Enumeration e = allTraps.keys();
- while(e.hasMoreElements()) {
- Weak w = (Weak)e.nextElement();
- Trap t = (Trap)w.get();
- if (t == null) {
- allTraps.remove(w);
- continue;
- }
- for(Scriptable cur = t.f; cur != null; cur = cur.getParentScope()) {
- if (cur == b) {
- t.delete();
- break;
- }
- }
- }
- }
-
// Instance Methods //////////////////////////////////////////////////////////////////////////
private Trap() { allTraps.put(myWeak, dummy); }
/** perform this trap -- arg.length == 0 if this is a get; otherwise it contains a single element to be put */
- public Object perform(Object[] arg) {
+ public Object perform(JS.Array args) {
TrapContext tc = TrapContext.get();
// save both thread-locals on the stack and update their values
// invoke the trap function
try {
- if (!isreadtrap && arg.length == 0) return cascadeFunction.call(null, null, null, arg);
+ if (!isreadtrap && args.length() == 0) return cascadeFunction._call(args, f);
if (f == null) {
if (Log.verbose) Log.log(this, "debug: reclaimed a dangling trap on property " + name);
- Object ret = cascadeFunction.call(null, null, null, arg);
+ Object ret = cascadeFunction._call(args, f);
delete();
return ret;
}
- Object ret = f.call(Context.enter(), f.getParentScope(), f.getParentScope(), arg);
+ Object ret = f._call(args);
// autocascade if required
- if (arg.length > 0 && !isreadtrap && !tc.putCascadeHappened) cascadeFunction.call(null, null, null, arg);
+ if (args.length() > 0 && !isreadtrap && !tc.putCascadeHappened) cascadeFunction._call(args, f);
return ret;
- } catch (EcmaError e) {
- if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from within trap '" + name + "' at " + e.getSourceName() + ":" + e.getLineNumber());
- } catch (JavaScriptException e) {
- if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
- if (Log.on) Log.log(this, " thrown from within trap '" + name + "' at " + e.sourceFile + ":" + e.line);
+ } catch (JS.Exn e) {
+ if (Log.on) Log.log(this, e);
+
} finally {
// restore the thread-locals
tc.putCascadeHappened = save_putCascadeHappened;
import java.io.*;
import java.net.*;
import java.util.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
import org.xwt.util.*;
import org.bouncycastle.util.encoders.Base64;
/**
- * An XML-RPC client implemented as a Rhino JavaScript Host
- * Object. See the XWT spec for information on its behavior.
+ * An XML-RPC client implemented as a JavaScript Host Object. See the
+ * XWT spec for information on its behavior.
*
* NOTE: this client is EXTREMELY lenient in the responses it will
* accept; there are many, many invalid responses that it will
* convert.
* </ol>
*/
-class XMLRPC extends XML implements Function {
+class XMLRPC extends JS.Function {
+
+ public Object[] keys() { throw new Error("not implemented"); }
/** the url to connect to */
protected String url = null;
// Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
- public void startElement(XML.Element c) {
- content.reset();
- if (c.localName.equals("fault")) fault = true;
- else if (c.localName.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
- else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
- else if (c.localName.equals("value")) objects.addElement("");
+ private class Helper extends XML {
+ public Helper() { super(BUFFER_SIZE); }
+
+ public void startElement(XML.Element c) {
+ content.reset();
+ if (c.localName.equals("fault")) fault = true;
+ else if (c.localName.equals("struct")) objects.setElementAt(new JS.Obj(), objects.size() - 1);
+ else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
+ else if (c.localName.equals("value")) objects.addElement("");
+ }
+
+ public void endElement(XML.Element c) {
+
+ if (c.localName.equals("int") || c.localName.equals("i4"))
+ objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
+
+ else if (c.localName.equals("boolean"))
+ objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
+
+ else if (c.localName.equals("string"))
+ objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
+
+ else if (c.localName.equals("double"))
+ objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
+
+ else if (c.localName.equals("base64"))
+ objects.setElementAt(new ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
+
+ else if (c.localName.equals("name"))
+ objects.addElement(new String(content.getBuf(), 0, content.size()));
+
+ else if (c.localName.equals("value") && "".equals(objects.lastElement()))
+ objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
+
+ else if (c.localName.equals("dateTime.iso8601")) {
+ throw new Error("not implemented");
+ /*
+ String s = new String(content.getBuf(), 0, content.size());
+
+ // strip whitespace
+ int i=0;
+ while(Character.isWhitespace(s.charAt(i))) i++;
+ if (i > 0) s = s.substring(i);
+
+ try {
+ NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JS.Obj.defaultObjects, "Date");
+ double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
+ Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
+ Double.valueOf(s.substring(6, 8)).doubleValue(),
+ Double.valueOf(s.substring(9, 11)).doubleValue(),
+ Double.valueOf(s.substring(12, 14)).doubleValue(),
+ Double.valueOf(s.substring(15, 17)).doubleValue(),
+ (double)0
+ );
+ nd.jsFunction_setTime(NativeDate.internalUTC(date));
+ objects.setElementAt(nd, objects.size() - 1);
+
+ } catch (Exception e) {
+ if (Log.on) Log.log(this, "error parsing date : " + s);
+ if (Log.on) Log.log(this, e);
+ }
+ */
+
+ } else if (c.localName.equals("member")) {
+ Object memberValue = objects.elementAt(objects.size() - 1);
+ String memberName = (String)objects.elementAt(objects.size() - 2);
+ JS struct = (JS)objects.elementAt(objects.size() - 3);
+ struct.put(memberName, memberValue);
+ objects.setSize(objects.size() - 2);
+
+ } else if (c.localName.equals("data")) {
+ int i;
+ for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
+ JS.Array arr = new JS.Array();
+ for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
+ objects.setElementAt(arr, i);
+ objects.setSize(i + 1);
+
+ }
+
+ content.reset();
+ }
+
+ public void characters(char[] ch, int start, int length) {
+ try { content.write(ch, start, length); }
+ catch (Exception e) {
+ if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
+ if (Log.on) Log.log(this, e);
+ }
+ }
+
+ public void whitespace(char[] ch, int start, int length) {}
}
- public void endElement(XML.Element c) {
-
- if (c.localName.equals("int") || c.localName.equals("i4"))
- objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
-
- else if (c.localName.equals("boolean"))
- objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
-
- else if (c.localName.equals("string"))
- objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
-
- else if (c.localName.equals("double"))
- objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
-
- else if (c.localName.equals("base64"))
- objects.setElementAt(new ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
-
- else if (c.localName.equals("name"))
- objects.addElement(new String(content.getBuf(), 0, content.size()));
-
- else if (c.localName.equals("value") && "".equals(objects.lastElement()))
- objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
-
- else if (c.localName.equals("dateTime.iso8601")) {
- String s = new String(content.getBuf(), 0, content.size());
-
- // strip whitespace
- int i=0;
- while(Character.isWhitespace(s.charAt(i))) i++;
- if (i > 0) s = s.substring(i);
-
- try {
- NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
- double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
- Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
- Double.valueOf(s.substring(6, 8)).doubleValue(),
- Double.valueOf(s.substring(9, 11)).doubleValue(),
- Double.valueOf(s.substring(12, 14)).doubleValue(),
- Double.valueOf(s.substring(15, 17)).doubleValue(),
- (double)0
- );
- nd.jsFunction_setTime(NativeDate.internalUTC(date));
- objects.setElementAt(nd, objects.size() - 1);
-
- } catch (Exception e) {
- if (Log.on) Log.log(this, "error parsing date : " + s);
- if (Log.on) Log.log(this, e);
- }
-
- } else if (c.localName.equals("member")) {
- Object memberValue = objects.elementAt(objects.size() - 1);
- String memberName = (String)objects.elementAt(objects.size() - 2);
- Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
- struct.put(memberName, struct, memberValue);
- objects.setSize(objects.size() - 2);
-
- } else if (c.localName.equals("data")) {
- int i;
- for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
- Object[] arr = new Object[objects.size() - i - 1];
- for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
- objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
- objects.setSize(i + 1);
-
- }
-
- content.reset();
- }
-
- public void characters(char[] ch, int start, int length) {
- try { content.write(ch, start, length); }
- catch (Exception e) {
- if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
- if (Log.on) Log.log(this, e);
- }
- }
-
- public void whitespace(char[] ch, int start, int length) {}
-
// Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
/** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
- void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
+ void appendObject(Object o, StringBuffer sb) throws JS.Exn {
if (o == null) {
- throw new JavaScriptException("attempted to send a null value via XML-RPC");
+ throw new JS.Exn("attempted to send a null value via XML-RPC");
} else if (o instanceof Number) {
if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
} catch (IOException e) {
if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
if (Log.on) Log.log(this, e);
- throw new JavaScriptException("caught IOException while attempting to send a ByteStream via XML-RPC");
+ throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
}
} else if (o instanceof String) {
}
sb.append("</string></value>\n");
- } else if (o instanceof NativeDate) {
+ /*
+ } else if (o instanceof org.xwt.js.Date) {
sb.append(" <value><dateTime.iso8601>");
- NativeDate nd = (NativeDate)o;
+ FIXME
+ org.xwt.js.Date d = (org.xwt.js.Date)o;
Date d = new Date(nd.getRawTime());
sb.append(d.getYear() + 1900);
if (d.getMonth() + 1 < 10) sb.append('0');
if (d.getSeconds() < 10) sb.append('0');
sb.append(d.getSeconds());
sb.append("</dateTime.iso8601></value>\n");
+ */
- } else if (o instanceof NativeArray) {
- if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
+ } else if (o instanceof JS.Array) {
+ if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
tracker.put(o, Boolean.TRUE);
sb.append(" <value><array><data>\n");
- NativeArray na = (NativeArray)o;
- for(int i=0; i<na.jsGet_length(); i++)
- appendObject(na.get(i, na), sb);
+ JS.Array a = (JS.Array)o;
+ for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
sb.append(" </data></array></value>\n");
- } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
- if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
+ } else if (o instanceof JS) {
+ if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
tracker.put(o, Boolean.TRUE);
- Scriptable s = (Scriptable)o;
+ JS j = (JS)o;
sb.append(" <value><struct>\n");
- Object[] ids = s.getIds();
+ Object[] ids = j.keys();
for(int i=0; i<ids.length; i++) {
sb.append(" <member><name>" + ids[i] + "</name>\n");
- appendObject(s.get(ids[i].toString(), s), sb);
+ appendObject(j.get(ids[i].toString()), sb);
sb.append(" </member>\n");
}
sb.append(" </struct></value>\n");
} else {
- throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
+ throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
}
}
// this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
// behavior to use pipelining.
- public synchronized Object call(Object[] args) throws JavaScriptException, IOException {
+ public synchronized Object call2(JS.Array args) throws JS.Exn, IOException {
if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
if (tracker == null) tracker = new Hash();
}
}
- protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
+ protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
StringBuffer content = new StringBuffer();
content.append("\r\n");
content.append("<?xml version=\"1.0\"?>\n");
content.append(methodname);
content.append("</methodName>\n");
content.append(" <params>\n");
- for(int i=0; i<args.length; i++) {
+ for(int i=0; i<args.length(); i++) {
content.append(" <param>\n");
- appendObject(args[i], content);
+ appendObject(args.elementAt(i), content);
content.append(" </param>\n");
}
content.append(" </params>\n");
return content.toString();
}
- protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
+ protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
// parse XML reply
try {
- parse(br);
+ new Helper().parse(br);
} catch (XML.XMLException e) {
if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
- throw new JavaScriptException("reply from server was not well-formed XML: " + e);
+ throw new JS.Exn("reply from server was not well-formed XML: " + e);
}
- if (fault) throw new JavaScriptException(objects.elementAt(0));
+ if (fault) throw new JS.Exn(objects.elementAt(0));
if (objects.size() == 0) return null;
return objects.elementAt(0);
}
- public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
+ public final Object _call(JS.Array args) throws JS.Exn {
if (!ThreadMessage.suspendThread()) return null;
try {
- return call(args);
+ return call2(args);
} catch (IOException se) {
if (Log.on) Log.log(this, se);
- if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
- throw new JavaScriptException("socket exception: " + se);
-
- } catch (JavaScriptException jse) {
- Object val = jse.getValue();
- if (val instanceof String) {
- if (Log.on) Log.log(this, val.toString());
- if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
- }
+ throw new JS.Exn("socket exception: " + se);
+
+ } catch (JS.Exn jse) {
+ if (Log.on) Log.log(this, jse.toString());
throw jse;
} finally {
ThreadMessage.resumeThread();
}
/** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
- public Object get(String name, Scriptable start) {
+ public Object get(String name) {
return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name, http);
}
}
public XMLRPC(String url, String methodname, HTTP http) {
- super(BUFFER_SIZE);
-
this.http = http;
this.url = url;
this.methodname = methodname;
}
}
-
- // Methods Required by Rhino ////////////////////////////////////////////////////////
-
- public String getClassName() { return "XMLRPC"; }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- public void delete(String name) { }
- public Scriptable getParentScope() { return null; }
- public void setParentScope(Scriptable p) { }
- public boolean hasInstance(Scriptable value) { return false; }
- public Scriptable getPrototype() { return null; }
- public void setPrototype(Scriptable p) { }
- public void delete(int i) { }
- public Object getDefaultValue(Class hint) { return "XML-RPC"; }
- public void put(int i, Scriptable start, Object value) { }
- public Object get(int i, Scriptable start) { return null; }
- public void put(String name, Scriptable start, Object value) { }
- public boolean has(String name, Scriptable start) { return true; }
- public boolean has(int i, Scriptable start) { return false; }
- public Object[] getIds() { return new Object[] { }; }
-
}
import java.net.*;
import java.text.*;
import java.util.*;
+import org.xwt.js.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
import org.bouncycastle.util.encoders.Base64;
/** Singleton class that provides all functionality in the xwt.* namespace */
-public final class XWT extends JSObject {
+public final class XWT extends JS.Obj {
public static final XWT singleton = new XWT();
/** each key is a string representing a filename which the user has already given XWT permission to write to */
private static Hashtable safeFiles = new Hashtable();
- public String getClassName() { return "XWT"; }
- private XWT() { setSeal(true); }
-
- public Object get(String name, Scriptable start) {
- if (name == null) return null;
- else if (name.equals("maxdim")) return new Integer(Short.MAX_VALUE);
- else if (name.equals("parseFloat")) return JSObject.defaultObjects.get("parseFloat", null);
- else if (name.equals("parseInt")) return JSObject.defaultObjects.get("parseInt", null);
+ public Object get(Object name) {
+ if (name.equals("parseFloat")) throw new Error("not implemented");
+ else if (name.equals("parseInt")) throw new Error("not implemented");
else if (name.equals("alt")) return Surface.alt ? Boolean.TRUE : Boolean.FALSE;
else if (name.equals("control")) return Surface.control ? Boolean.TRUE : Boolean.FALSE;
else if (name.equals("shift")) return Surface.shift ? Boolean.TRUE : Boolean.FALSE;
- else if (name.equals("date")) return date;
- else if (name.equals("listfonts")) return listfonts;
- else if (name.equals("regexp")) return regexp;
- else if (name.equals("sleep")) return sleep;
- else if (name.equals("yield")) return yield;
- else if (name.equals("newBrowserWindow")) return newBrowserWindow;
- else if (name.equals("textwidth")) return textwidth;
- else if (name.equals("textheight")) return textheight;
- else if (name.equals("newBox")) return newBox;
- else if (name.equals("soap")) return soap;
- else if (name.equals("xmlrpc")) return xmlrpc;
- else if (name.equals("origin")) return Main.origin;
else if (name.equals("clipboard")) return Platform.getClipBoard();
- else if (name.equals("altKeyName")) return Platform.altKeyName();
- else if (name.equals("screenWidth")) return new Integer(Platform.getScreenWidth());
- else if (name.equals("screenHeight")) return new Integer(Platform.getScreenHeight());
- else if (name.equals("static")) return Static.getStatic("");
- else if (name.equals("theme")) return theme;
- else if (name.equals("openFile")) return openFile;
- else if (name.equals("saveFile")) return saveFile;
- else if (name.equals("saveFileAs")) return saveFileAs;
- else if (name.equals("utfEncode")) return utfEncode;
- else if (name.equals("fileSeparator")) return File.separator;
- else if (name.equals("homeDir")) return System.getProperty("user.home");
- else if (name.equals("tempDir")) return System.getProperty("java.io.tempdir");
- else if (name.equals("recursivePrintObject")) return recursivePrintObject;
- else if (name.equals("parseHTML")) return parseHTML;
+ else if (name.equals("static")) return Static.getStatic("");
else if (name.equals("button")) {
if (Surface.button1 && !Surface.button2 && !Surface.button3) return new Integer(1);
else if (!Surface.button1 && Surface.button2 && !Surface.button3) return new Integer(1);
else if (!Surface.button1 && !Surface.button2 && Surface.button3) return new Integer(1);
else return new Integer(0);
- }
- else if (name.equals("println")) return println;
- else if (name.equals("math")) return org.xwt.util.JSObject.defaultObjects.get("Math", null);
- else if (name.equals("loadArchive")) return loadArchive;
- else if (name.equals("prefetchImage")) return prefetchImage;
- else if (name.equals("prefs")) return prefs;
- else if (name.equals("encodeURI")) return JSObject.defaultObjects.get("encodeURI", null);
- else if (name.equals("encodeURIComponent")) return JSObject.defaultObjects.get("encodeURIComponent", null);
- else if (name.equals("decodeURI")) return JSObject.defaultObjects.get("decodeURI", null);
- else if (name.equals("decodeURIComponent")) return JSObject.defaultObjects.get("decodeURIComponent", null);
- else return super.get(name, start);
+ }
+ else if (name.equals("encodeURI")) throw new Error("not implemented");
+ else if (name.equals("encodeURIComponent")) throw new Error("not implemented");
+ else if (name.equals("decodeURI")) throw new Error("not implemented");
+ else if (name.equals("decodeURIComponent")) throw new Error("not implemented");
+ else return super.get(name);
}
- public void put(String name, Scriptable start, Object value) {
- if (name == null) return;
- else if (name.equals("thread") && value != null && value instanceof Function) ThreadMessage.newthread((Function)value);
+ public void put(Object name, Object value) {
+ if (name.equals("thread") && value != null && value instanceof JS.Function) ThreadMessage.newthread((JS.Function)value);
else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
-
- // FIXME: undocumented, possibly insecure
else if (name.equals("proxyAuthorization")) {
+ // FIXME: undocumented, possibly insecure
Proxy.Authorization.authorization = value.toString();
Proxy.Authorization.waitingForUser.release();
- }
-
- else super.put(name, start, value);
+ } else super.put(name, value);
}
-
- // Prefs Object //////////////////////////////////////////////////////////////////////////
-
- static Scriptable prefsRPC = new XMLRPC("http://megacz:mypassword@localhost/RPC2", "prefs");
-
- private static final JSObject prefs = new JSObject(false, true) {
- public Object get(String name, Scriptable start) {
- if (name.equals("get")) return prefsGet;
- else if (name.equals("list")) return prefsList;
- else if (name.equals("put")) return prefsPut;
- else return null;
- }
- };
-
- private static final JSObject.JSFunction prefsGet = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 1 || args[0] == null) return null;
+ private XWT() {
+ put("maxdim", new Integer(Short.MAX_VALUE));
+ put("origin", Main.origin);
+ put("altKeyName", Platform.altKeyName());
+ put("screenWidth", new Integer(Platform.getScreenWidth()));
+ put("screenHeight", new Integer(Platform.getScreenHeight()));
+ put("fileSeparator", File.separator);
+ put("homeDir", System.getProperty("user.home"));
+ put("tempDir", System.getProperty("java.io.tempdir"));
+
+ put("math", new JS.Obj() { public Object get(Object name) {
+ if ("ceil".equals(name)) return new JS.Function() { public Object _call(JS.Array args)
+ { if (args.elementAt(0) == null) return null;
+ return new Long((long)Math.ceil(Double.parseDouble(args.elementAt(0).toString()))); } };
+ else if ("floor".equals(name)) return new JS.Function() { public Object _call(JS.Array args)
+ { if (args.elementAt(0) == null) return null;
+ return new Long((long)Math.floor(Double.parseDouble(args.elementAt(0).toString()))); } };
+ else if ("round".equals(name)) return new JS.Function() { public Object _call(JS.Array args)
+ { if (args.elementAt(0) == null) return null;
+ return new Long((long)Math.round(Double.parseDouble(args.elementAt(0).toString()))); } };
+ else if ("abs".equals(name)) return new JS.Function() { public Object _call(JS.Array args)
+ { if (args.elementAt(0) == null) return null;
+ return new Long((long)Math.abs(Double.parseDouble(args.elementAt(0).toString()))); } };
+ else if ("min".equals(name)) return new JS.Function() { public Object _call(JS.Array args) {
+ if (args.length() < 2 || args.elementAt(0) == null || args.elementAt(1) == null) return args.elementAt(0);
+ return new Double(Math.min(((Number)args.elementAt(0)).doubleValue(),
+ ((Number)args.elementAt(1)).doubleValue())); } };
+ else if ("max".equals(name)) return new JS.Function() { public Object _call(JS.Array args) {
+ if (args.length() < 2) return args.elementAt(0);
+ return new Double(Math.max(((Number)args.elementAt(0)).doubleValue(),
+ ((Number)args.elementAt(1)).doubleValue())); } };
+ return null;
+ }});
+
+ put("newBrowserWindow", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 1 || args.elementAt(0) == null) return null;
+ Platform.newBrowserWindow(args.elementAt(0).toString());
+ return null;
+ }});
+
+ put("yield", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ sleep(0);
+ return null;
+ }});
+
+ put("theme", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 2) return null;
+ if (args.elementAt(0) == null || args.elementAt(1) == null) return null;
+ for(int i=1; i<args.length(); i++) {
+ if (args.elementAt(i) instanceof String) {
+ String from = (String)args.elementAt(0);
+ String to = (String)args.elementAt(i);
+ if (Log.on) Log.log(this, "retheming from " + from + " to " + to);
+ Resources.mapFrom.addElement(from);
+ Resources.mapTo.addElement(to);
+ }
+ }
+ JS.Function callback = args.elementAt(args.length() - 1) instanceof Function ?
+ (Function)args.elementAt(args.length() - 1) : null;
+ Template.retheme(callback);
+ return null;
+ }});
+
+ put("println", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 1) return null;
+ if (Log.on) Log.log(this, JS.getFileAndLine() + " " +
+ (args.elementAt(0) == null ? "null" : args.elementAt(0).toString()));
+ return null;
+ }});
+
+ put("date", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ Log.log(XWT.class, "date not implemented");
+ //throw new Error("not implemented");
+ return null;
+ }});
+
+ put("regexp", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ //throw new Error("not implemented");
+ Log.log(XWT.class, "regexp not implemented");
+ return null;
+ }});
+
+ put("listfonts", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ Object[] fonts = Platform.listFonts();
+ JS.Array ret = new JS.Array();
+ for(int i=0; i<fonts.length; i++) ret.addElement(fonts[i]);
+ return ret;
+ }});
+
+ put("theme", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ Log.log(XWT.class, "xwt.theme() not implemented...");
+ return null;
+ }});
+
+ put("xmlrpc", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 1 || args.elementAt(0) == null) return null;
+ return new XMLRPC(args.elementAt(0).toString(), "");
+ }});
+
+ put("soap", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() == 1 && args.elementAt(0) != null) return new SOAP(args.elementAt(0).toString(), "", null, null);
+ else if (args.length() == 2 && args.elementAt(0) != null && args.elementAt(1) != null)
+ return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), null);
+ else if (args.length() == 3 && args.elementAt(0) != null && args.elementAt(1) != null && args.elementAt(2) != null)
+ return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), args.elementAt(2).toString());
+ else return null;
+ }});
+
+ put("textwidth", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() < 1 || args.length() > 2) return null;
+ if (args.elementAt(0) == null || (args.length() == 2 && args.elementAt(1) == null)) return null;
+ String font = args.length() == 1 ? Platform.getDefaultFont() : args.elementAt(0).toString();
+ String text = args.length() == 1 ? args.elementAt(0).toString() : args.elementAt(1).toString();
+ XWF xwf = XWF.getXWF(font);
+ if (xwf == null) return new Integer(Platform.stringWidth(font, text));
+ else return new Integer(xwf.stringWidth(text));
+ }});
+
+ put("textheight", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() > 1) return null;
+ if (args.length() == 1 && args.elementAt(0) == null) return null;
+ String font = args.length() == 0 || args.elementAt(0) == null ? Platform.getDefaultFont() : args.elementAt(0).toString();
+ XWF xwf = XWF.getXWF(font);
+ if (xwf == null) return new Integer(Platform.getMaxAscent(font) + Platform.getMaxDescent(font));
+ else return new Integer(xwf.getMaxAscent() + xwf.getMaxDescent());
+ }});
+
+ put("newBox", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() > 0) Log.log(XWT.class, "DEPRECATED: xwt.newBox() with multiple arguments is deprecated; use xwt.newBox().apply()");
+ JS.Function callback = null;
+ for(int i=1; i<args.length(); i++)
+ if (args.elementAt(i) instanceof JS.Function && callback == null)
+ callback = (JS.Function)args.elementAt(i);
+ Box ret = new Box(args.length() == 0 || args.elementAt(0) == null ? "box" : args.elementAt(0).toString(),
+ Template.defaultImportList, callback);
+ for(int i=1; i<args.length(); i++)
+ if (args.elementAt(i) instanceof Box)
+ ret.put(ret.numChildren(), (Box)args.elementAt(i));
+ for(int i=1; i<args.length(); i++)
+ if (args.elementAt(i) instanceof JS && !(args.elementAt(i) instanceof Box) && !(args.elementAt(i) instanceof JS.Function)) {
+ JS s = (JS)args.elementAt(i);
+ Object[] keys = s.keys();
+ for(int j=0; j<keys.length; j++) ret.put(keys[j].toString(), s.get(keys[j].toString()));
+ }
+ return ret;
+ }});
+
+ put("sleep", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args != null && (args.length() != 1 || args.elementAt(0) == null)) return null;
+ int i = args == null ? 0 : SpecialBoxProperty.stoi(args.elementAt(0).toString());
+ sleep(i);
+ return null;
+ }});
+
+ put("openFile", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 1) return null;
+ String file = Platform.fileDialog(args.elementAt(0).toString(), false);
+ return file == null ? null : new ByteStream(file);
+ }});
+
+ put("saveFile", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 2) return null;
+ if (!(args.elementAt(1) instanceof ByteStream)) return null;
+ String file = args.elementAt(0).toString();
+ if (safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
+ file = Platform.fileDialog(file, true);
+ if (file == null) return null;
+ safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
+ }
+ try {
+ ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
+ return null;
+ } catch (IOException e) {
+ if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
+ if (Log.on) Log.log(ByteStream.class, e);
+ throw new JS.Exn("error while writing a ByteStream to a file");
+ }
+ }});
+
+ put("saveFileAs", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args.length() != 2) return null;
+ if (!(args.elementAt(1) instanceof ByteStream)) return null;
+ String file = args.elementAt(0).toString();
+ file = Platform.fileDialog(file, true);
+ if (file == null) return null;
+ safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
+ try {
+ ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
+ return null;
+ } catch (IOException e) {
+ if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
+ if (Log.on) Log.log(ByteStream.class, e);
+ throw new JS.Exn("error while writing a ByteStream to a file");
+ }
+ }});
+
+ put("utfEncode", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args == null || args.length() != 1) return null;
+ return new ByteStream(args.elementAt(0).toString().getBytes());
+ }});
+
+ put("parseHTML", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args == null || args.length() != 1 || args.elementAt(0) == null) return null;
try {
- return ((Function)prefsRPC.get("get", null)).call(cx, null, null, new Object[] { args[0] });
- } catch (JavaScriptException jse) {
- Object val = jse.getValue();
- if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
- return null;
- throw jse;
- } catch (Exception e) {
- // FIXME
- throw new JavaScriptException(e.toString());
- }
- }
- };
-
- private static final JSObject.JSFunction prefsPut = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length < 2 || args[0] == null) return null;
- try {
- return ((Function)prefsRPC.get("put", null)).call(cx, null, null, new Object[] { args[0].toString(), args[1] });
- } catch (JavaScriptException jse) {
- Object val = jse.getValue();
- if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
- return null;
- throw jse;
- } catch (Exception e) {
- // FIXME
- throw new JavaScriptException(e.toString());
- }
- }
- };
-
- private static final JSObject.JSFunction prefsList = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length < 2 || args[0] == null) return null;
- try {
- return ((Function)prefsRPC.get("list", null)).call(cx, null, null, new Object[] { args[0].toString(), args[1] });
- } catch (JavaScriptException jse) {
- Object val = jse.getValue();
- if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
- return null;
- throw jse;
- } catch (Exception e) {
- // FIXME
- throw new JavaScriptException(e.toString());
- }
- }
- };
-
- private static final JSObject.JSFunction prefsInvoke = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length < 2 || args[0] == null) return null;
- try {
- return ((Function)prefs.get("invoke")).call(cx, null, null, new Object[] { args[0].toString(), args[1], "megacz", "mypassword" });
- } catch (JavaScriptException jse) {
- Object val = jse.getValue();
- if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
- return null;
- throw jse;
- } catch (Exception e) {
- // FIXME
- throw new JavaScriptException(e.toString());
- }
- }
- };
-
-
-
- // JSFunction Instances ///////////////////////////////////////////////////////////////////
-
- private static final JSObject.JSFunction newBrowserWindow = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 1 || args[0] == null) return null;
- Platform.newBrowserWindow(args[0].toString());
- return null;
- }
- };
-
- public static final JSObject.JSFunction yield = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- sleep.call(cx, null, null, null);
- return null;
- }
- };
-
- private static final JSObject.JSFunction println = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length == 1)
- if (Log.on) {
- String source = cx.interpreterSourceFile;
- if (source.endsWith("._")) source = source.substring(0, source.length() - 2);
- Log.log(source, args[0] == null ? "null" : args[0].toString());
- }
- return null;
- }
- };
-
- private static final JSObject.JSFunction date = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- try { return Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date", args);
- } catch (Exception e) {
- if (Log.on) Log.log(this, "Exception in Context.newObject() -- this should never happen");
- if (Log.on) Log.log(this, e);
- return null;
- }
- }
- };
-
- private static final JSObject.JSFunction regexp = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- try { return Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "RegExp", args);
- } catch (Exception e) {
- if (Log.on) Log.log(this, "Exception in Context.newObject() -- this should never happen");
- if (Log.on) Log.log(this, e);
- return null;
- }
- }
- };
-
- private static final JSObject.JSFunction listfonts = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- return Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, Platform.listFonts());
- }
- };
-
- private static final JSObject.JSFunction theme = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 2) return null;
- if (args[0] == null || args[1] == null) return null;
-
- for(int i=1; i<args.length; i++) {
- if (args[i] instanceof String) {
- String from = (String)args[0];
- String to = (String)args[i];
- if (Log.on) Log.log(this, "retheming from " + from + " to " + to);
- Resources.mapFrom.addElement(from);
- Resources.mapTo.addElement(to);
- }
- }
-
- Function callback = args[args.length - 1] instanceof Function ? (Function)args[args.length - 1] : null;
- Template.retheme(callback);
- return null;
- }
- };
-
- private static final JSObject.JSFunction xmlrpc = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 1 || args[0] == null) return null;
- return new XMLRPC(args[0].toString(), "");
- }
- };
-
- private static final JSObject.JSFunction soap = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length == 1 && args[0] != null) return new SOAP(args[0].toString(), "", null, null);
- else if (args.length == 2 && args[0] != null && args[1] != null)
- return new SOAP(args[0].toString(), "", args[1].toString(), null);
- else if (args.length == 3 && args[0] != null && args[1] != null && args[2] != null)
- return new SOAP(args[0].toString(), "", args[1].toString(), args[2].toString());
- else return null;
- }
- };
-
- private static final JSObject.JSFunction textwidth = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException {
- if (args.length < 1 || args.length > 2) return null;
- if (args[0] == null || (args.length == 2 && args[1] == null)) return null;
- String font = args.length == 1 ? Platform.getDefaultFont() : args[0].toString();
- String text = args.length == 1 ? args[0].toString() : args[1].toString();
- XWF xwf = XWF.getXWF(font);
- if (xwf == null) return new Integer(Platform.stringWidth(font, text));
- else return new Integer(xwf.stringWidth(text));
- }
- };
-
-
- private static final JSObject.JSFunction textheight = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length > 1) return null;
- if (args.length == 1 && args[0] == null) return null;
- String font = args.length == 0 || args[0] == null ? Platform.getDefaultFont() : args[0].toString();
- XWF xwf = XWF.getXWF(font);
- if (xwf == null) return new Integer(Platform.getMaxAscent(font) + Platform.getMaxDescent(font));
- else return new Integer(xwf.getMaxAscent() + xwf.getMaxDescent());
- }
- };
-
- private static final JSObject.JSFunction newBox = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
-
- if (args.length > 0)
- if (Log.on) Log.log(XWT.class, "DEPRECATED: xwt.newBox() with multiple arguments is deprecated; use xwt.newBox().apply() " +
- Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
-
- Function callback = null;
- for(int i=1; i<args.length; i++)
- if (args[i] instanceof Function && callback == null)
- callback = (Function)args[i];
-
- Box ret = new Box(args.length == 0 || args[0] == null ? "box" : args[0].toString(), Template.defaultImportList, callback);
-
- for(int i=1; i<args.length; i++)
- if (args[i] instanceof Box)
- ret.put(ret.numChildren(), null, (Box)args[i]);
- for(int i=1; i<args.length; i++)
- if (args[i] instanceof Scriptable && !(args[i] instanceof Box) && !(args[i] instanceof Function)) {
- Scriptable s = (Scriptable)args[i];
- Object[] keys = s.getIds();
-
- // FIXME: need to ensure that this is putGlobally(), but still run traps...
- for(int j=0; j<keys.length; j++) ret.put(keys[j].toString(), null, s.get(keys[j].toString(), s));
- }
- return ret;
- }
- };
-
- private static final JSObject.JSFunction sleep = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args != null && (args.length != 1 || args[0] == null)) return null;
- int i = args == null ? 0 : SpecialBoxProperty.stoi(args[0].toString());
-
- Thread thread = Thread.currentThread();
- if (!(thread instanceof ThreadMessage)) {
- if (Log.on) Log.log(this, "cannot sleep() or yield() in the foreground thread");
- return null;
- }
- ThreadMessage mythread = (ThreadMessage)thread;
- mythread.done.release();
-
- if (i > 0) try { Thread.sleep(i); } catch (Exception e) { }
-
- MessageQueue.add(mythread);
- mythread.go.block();
- return null;
- }
- };
-
- private static final JSObject.JSFunction openFile = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 1) return null;
- String file = Platform.fileDialog(args[0].toString(), false);
- return file == null ? null : new ByteStream(file);
- }
- };
-
- private static final JSObject.JSFunction saveFile = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 2) return null;
- if (!(args[1] instanceof ByteStream)) return null;
- String file = args[0].toString();
- if (safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
- file = Platform.fileDialog(file, true);
- if (file == null) return null;
- safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
- }
- try {
- ((ByteStream)args[1]).writeTo(new FileOutputStream(file));
- return null;
- } catch (IOException e) {
- if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
- if (Log.on) Log.log(ByteStream.class, e);
- throw new JavaScriptException("error while writing a ByteStream to a file");
- }
- }
- };
-
- private static final JSObject.JSFunction saveFileAs = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args.length != 2) return null;
- if (!(args[1] instanceof ByteStream)) return null;
- String file = args[0].toString();
- file = Platform.fileDialog(file, true);
- if (file == null) return null;
- safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
- try {
- ((ByteStream)args[1]).writeTo(new FileOutputStream(file));
- return null;
- } catch (IOException e) {
- if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
- if (Log.on) Log.log(ByteStream.class, e);
- throw new JavaScriptException("error while writing a ByteStream to a file");
- }
- }
- };
-
- private static final JSObject.JSFunction utfEncode = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args == null || args.length != 1) return null;
- return new ByteStream(args[0].toString().getBytes());
- }
- };
-
-
- private static final JSObject.JSFunction parseHTML = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args == null || args.length != 1 || args[0] == null) return null;
- try {
- if (args[0] instanceof ByteStream) {
- return HTML.parseReader(new InputStreamReader(((ByteStream)args[0]).getInputStream()));
+ if (args.elementAt(0) instanceof ByteStream) {
+ return HTML.parseReader(new InputStreamReader(((ByteStream)args.elementAt(0)).getInputStream()));
} else {
- return HTML.parseReader(new StringReader(args[0].toString()));
+ return HTML.parseReader(new StringReader(args.elementAt(0).toString()));
}
} catch (IOException e) {
if (Log.on) Log.log(HTML.class, "IO Exception while parsing HTML");
if (Log.on) Log.log(HTML.class, e);
- throw new JavaScriptException("error while parsing HTML");
+ throw new JS.Exn("error while parsing HTML");
}
}
- };
+ });
- private static void recurse(String indent, String name, Object o, Context cx) {
- if (!name.equals("")) name += " : ";
+ put("recursivePrintObject", new JS.Function() { public Object _call(JS.Array args) {
+ if (args.length() != 1) return null;
+ recurse("", "", args.elementAt(0));
+ return null;
+ }});
- if (o == null) {
- Log.log(cx.interpreterSourceFile, indent + name + "<null>");
-
- } else if (o instanceof NativeArray) {
- Log.log(cx.interpreterSourceFile, indent + name + "<array>");
- NativeArray na = (NativeArray)o;
- for(int i=0; i<na.jsGet_length(); i++)
- recurse(indent + " ", i + "", na.get(i, null), cx);
-
- } else if (!(o instanceof NativeDate) && (o instanceof JSObject || o instanceof ScriptableObject)) {
- Log.log(cx.interpreterSourceFile, indent + name + "<object>");
- Scriptable s = (Scriptable)o;
- Object[] keys = s.getIds();
- for(int i=0; i<keys.length; i++)
- recurse(indent + " ", keys[i].toString(),
- keys[i] instanceof Integer ? s.get(((Integer)keys[i]).intValue(), null) : s.get(keys[i].toString(), null), cx);
-
- } else {
- Log.log(cx.interpreterSourceFile, indent + name + o);
-
- }
- }
-
- static final JSObject.JSFunction recursivePrintObject = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) {
- if (args == null || args.length != 1) return null;
- recurse("", "", args[0], cx);
- return null;
- }
- };
-
- private static final JSObject.JSFunction loadArchive = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ put("loadArchive", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
if (!ThreadMessage.suspendThread()) return null;
try {
- if (args == null || args.length < 1 || args[0] == null) return null;
- URL u = new URL(args[0].toString());
+ if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
+ URL u = new URL(args.elementAt(0).toString());
- Function callback = null;
- if (args.length == 2 && args[1] != null && args[1] instanceof Function) callback = (Function)args[1];
+ JS.Function callback = null;
+ if (args.length() == 2 && args.elementAt(1) != null && args.elementAt(1) instanceof JS.Function)
+ callback = (JS.Function)args.elementAt(1);
if (!u.getFile().endsWith(".xwar")) {
if (Log.on) Log.log(this, "Error: archive names must end with .xwar: " + u.getFile());
- throw new JavaScriptException("Error: archive names must end with .xwar: " + u.getFile());
+ throw new JS.Exn("Error: archive names must end with .xwar: " + u.getFile());
}
if (u.getProtocol().equals("http")) {
} else if (u.getProtocol().equals("file")) {
if (Main.originAddr != null) {
if (Log.on) Log.log(this, "scripts downloaded from the network may not load xwars from the local filesystem");
- throw new JavaScriptException("scripts downloaded from the network may not load xwars from the local filesystem");
+ throw new JS.Exn("scripts downloaded from the network may not load xwars from the local filesystem");
}
Resources.loadArchive(new FileInputStream(u.getFile()), (int)new File(u.getFile()).length(), callback);
} else {
if (Log.on) Log.log(this, "unknown protocol \"" + u.getProtocol() + "\"");
- throw new JavaScriptException("unknown protocol \"" + u.getProtocol() + "\"");
+ throw new JS.Exn("unknown protocol \"" + u.getProtocol() + "\"");
}
} catch (MalformedURLException me) {
- if (Log.on) Log.log(this, "Malformed URL: " + args[0]);
+ if (Log.on) Log.log(this, "Malformed URL: " + args.elementAt(0));
if (Log.on) Log.log(this, me);
- throw new JavaScriptException(me.toString());
+ throw new JS.Exn(me.toString());
} catch (IOException ioe) {
if (Log.on) Log.log(this, "IOException while loading archive:");
if (Log.on) Log.log(this, ioe);
- throw new JavaScriptException(ioe.toString());
+ throw new JS.Exn(ioe.toString());
} finally {
ThreadMessage.resumeThread();
}
return null;
}
- };
+ });
+
+ put("prefetchImage", new JS.Function() { public Object _call(JS.Array args) throws JS.Exn {
+ if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
+ Box.getImage(args.elementAt(0).toString(),
+ args.length() > 1 && args.elementAt(1) instanceof JS.Function ? (JS.Function)args.elementAt(1) : null);
+ return null;
+ }});
+ }
- private static final JSObject.JSFunction prefetchImage = new JSObject.JSFunction() {
- public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
- if (args == null || args.length < 1 || args[0] == null) return null;
- Box.getImage(args[0].toString(), args.length > 1 && args[1] instanceof Function ? (Function)args[1] : null);
- return null;
- }
- };
+ private static void recurse(String indent, String name, Object o) {
+ if (!name.equals("")) name += " : ";
+ if (o == null) {
+ Log.log(JS.getCurrentFunction().getSourceName(), indent + name + "<null>");
+
+ } else if (o instanceof JS.Array) {
+ Log.log(JS.getCurrentFunction().getSourceName(), indent + name + "<array>");
+ JS.Array na = (JS.Array)o;
+ for(int i=0; i<na.length(); i++)
+ recurse(indent + " ", i + "", na.elementAt(i));
+
+ } else if (o instanceof JS) {
+ Log.log(JS.getCurrentFunction().getSourceName(), indent + name + "<object>");
+ JS s = (JS)o;
+ Object[] keys = s.keys();
+ for(int i=0; i<keys.length; i++)
+ recurse(indent + " ", keys[i].toString(),
+ (keys[i] instanceof Integer) ?
+ s.get(((Integer)keys[i])) : s.get(keys[i].toString()));
+
+ } else {
+ Log.log(JS.getCurrentFunction().getSourceName(), indent + name + o);
+
+ }
+ }
+
+
+ public static void sleep(int i) {
+ Thread thread = Thread.currentThread();
+ if (!(thread instanceof ThreadMessage)) {
+ if (Log.on) Log.log(XWT.class, "cannot sleep() or yield() in the foreground thread");
+ } else {
+ ThreadMessage mythread = (ThreadMessage)thread;
+ mythread.done.release();
+ if (i > 0) try { Thread.sleep(i); } catch (Exception e) { }
+ MessageQueue.add(mythread);
+ mythread.go.block();
+ }
+ }
}
+
+
+
import org.xwt.*;
import org.xwt.util.*;
-import org.mozilla.javascript.*;
import java.net.*;
import java.io.*;
import java.util.*;
protected boolean _supressDirtyOnResize() { return true; }
protected void postInit() {
- if (Log.on) Log.log(Platform.class, " color depth = " +
- Toolkit.getDefaultToolkit().getColorModel().getPixelSize() + "bpp");
+ if (Log.on) Log.log(Platform.class, " color depth = " + Toolkit.getDefaultToolkit().getColorModel().getPixelSize() + "bpp");
}
protected void _criticalAbort(String message) {
+++ /dev/null
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
-package org.xwt.plat;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.awt.image.*;
-import java.awt.datatransfer.*;
-import java.net.*;
-import java.io.*;
-import java.util.*;
-import org.xwt.util.*;
-import org.xwt.*;
-import java.lang.reflect.*;
-
-
-/** Platform class for most reasonable Java1.2+ JVMs */
-public class Java12 extends AWT {
-
- public Java12() {
- // disable the focus manager so we can intercept the tab key
- javax.swing.FocusManager.setCurrentManager(new javax.swing.FocusManager() {
- public void processKeyEvent(Component focusedComponent, KeyEvent anEvent) { }
- public void focusPreviousComponent(Component aComponent) { }
- public void focusNextComponent(Component aComponent) { }
- });
- }
-
- /** this is done with reflection in case a new version of the plugin comes out that doesn't let us pull the sun.plugin.* trick */
- protected synchronized org.xwt.Proxy _detectProxy() {
- return (org.xwt.Proxy)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() {
- try {
- org.xwt.Proxy pi = new org.xwt.Proxy();
-
- Class PluginProxyHandler = Class.forName("sun.plugin.protocol.PluginProxyHandler");
- Method getDefaultProxyHandler = PluginProxyHandler.getMethod("getDefaultProxyHandler", new Class[] { });
- Object proxyHandler = getDefaultProxyHandler.invoke(null, new Object[] { });
-
- Class ProxyHandler = Class.forName("sun.plugin.protocol.ProxyHandler");
- Method getProxyInfo = ProxyHandler.getMethod("getProxyInfo", new Class[] { URL.class });
- Object proxyInfo = getProxyInfo.invoke(proxyHandler, new Object[] { new URL("http://www.xwt.org") });
-
- Class ProxyInfo = Class.forName("sun.plugin.protocol.ProxyInfo");
-
- if (((Boolean)ProxyInfo.getMethod("isSocksUsed", new Class[] { }).invoke(proxyInfo, new Object[] { })).booleanValue()) {
- pi.socksProxyHost =
- (String)ProxyInfo.getMethod("getSocksProxy", new Class[] { }).invoke(proxyInfo, new Object[] { });
- pi.socksProxyPort =
- ((Integer)ProxyInfo.getMethod("getSocksPort", new Class[] { }).invoke(proxyInfo, new Object[] { })).intValue();
- }
-
- if (((Boolean)ProxyInfo.getMethod("isProxyUsed", new Class[] { }).invoke(proxyInfo, new Object[] { })).booleanValue()) {
- pi.httpProxyHost =
- (String)ProxyInfo.getMethod("getProxy", new Class[] { }).invoke(proxyInfo, new Object[] { });
- pi.httpProxyPort =
- ((Integer)ProxyInfo.getMethod("getPort", new Class[] { }).invoke(proxyInfo, new Object[] { })).intValue();
- }
-
- if (pi.httpProxyHost != null || pi.socksProxyHost != null) return pi;
- else return null;
-
- } catch (Throwable e) {
- if (Log.on) Log.log(this, "exception while querying sun.plugin.protocol.PluginProxyHandler: " + e);
- return null;
- }
- }});
- }
-
- protected Socket __getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
- return super._getSocket(host, port, ssl, negotiate);
- }
- protected Socket _getSocket(final String host, final int port, final boolean ssl, final boolean negotiate) throws IOException {
- return (Socket)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() {
- try {
- return __getSocket(host, port, ssl, negotiate);
- } catch (Exception e) {
- if (Log.on) Log.log(Java12.class, "Error attempting to create socket");
- if (Log.on) Log.log(Java12.class, e);
- return null;
- }
- }
- });
- }
-
- protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return new Java12DoubleBuffer(w, h); }
- protected Surface _createSurface(final Box root, final boolean framed) {
- return (Surface)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() { return new Java12Surface(root, framed); }
- });
- }
-
- // Inner Classes //////////////////////////////////////////////////////////////////
-
- private static Cursor invisibleCursor =
- Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(2, 2, BufferedImage.TYPE_INT_ARGB),
- new Point(1, 1), "invisible");
-
- protected static class Java12Surface extends AWTSurface {
-
- public Java12Surface(Box root, boolean framed) { super(root, framed); }
- public void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
- if (ourGraphics == null) {
- ourGraphics = window.getGraphics();
-
- // sometimes jdk1.4 doesn't set the clip properly when we're in the middle of a resize
- ourGraphics.setClip(insets.left, insets.top, width + insets.left, height + insets.top);
- }
- _doDrawImage(ourGraphics, ((AWTDoubleBuffer)s).i, dx + insets.left, dy + insets.top, dx2 + insets.left, dy2 + insets.top,
- sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
- }
-
- protected void _setMinimized(boolean b) {
- if (frame == null) {
- if (Log.on) Log.log(this, "JDK 1.2 can only minimize frames, not windows");
- return;
- }
- if (b) frame.setState(java.awt.Frame.ICONIFIED);
- else frame.setState(java.awt.Frame.NORMAL);
- }
-
- public void syncCursor() {
- if (cursor.equals("invisible")) window.setCursor(invisibleCursor);
- else super.syncCursor();
- }
- }
-
- protected static class Java12DoubleBuffer extends AWTDoubleBuffer {
- private static ColorModel cm = Toolkit.getDefaultToolkit().getColorModel();
- private static Hashtable emptyHashtable = new Hashtable();
- private static short[] sbank = null;
- private static int[] ibank = null;
- private static byte[] bbank = null;
- private static int bank_start = 0;
-
- public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
- _doDrawImage(g, ((AWTPicture)source).i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
- }
-
- public Java12DoubleBuffer(int w, int h) {
- SampleModel sm = cm.createCompatibleSampleModel(w, h);
- int numSamples = w * h * sm.getNumDataElements();
- DataBuffer buf = null;
- if (sm.getDataType() == DataBuffer.TYPE_USHORT) {
- if (sbank == null || numSamples > 512 * 512 / 3) {
- buf = new DataBufferUShort(numSamples);
- } else {
- if (numSamples > sbank.length - bank_start) {
- bank_start = 0;
- sbank = new short[512 * 512];
- }
- buf = new DataBufferUShort(sbank, numSamples, bank_start);
- bank_start += numSamples;
- }
- } else if (sm.getDataType() == DataBuffer.TYPE_BYTE) {
- if (bbank == null || numSamples > 512 * 512 / 3) {
- buf = new DataBufferByte(numSamples);
- } else {
- if (numSamples > bbank.length - bank_start) {
- bank_start = 0;
- bbank = new byte[512 * 512];
- }
- buf = new DataBufferByte(bbank, numSamples, bank_start);
- bank_start += numSamples;
- }
- } else if (sm.getDataType() == DataBuffer.TYPE_INT) {
- if (ibank == null || numSamples > 512 * 512 / 3) {
- buf = new DataBufferInt(numSamples);
- } else {
- if (numSamples > ibank.length - bank_start) {
- bank_start = 0;
- ibank = new int[512 * 512];
- }
- buf = new DataBufferInt(ibank, numSamples, bank_start);
- bank_start += numSamples;
- }
- }
- i = new BufferedImage(cm, Raster.createWritableRaster(sm, buf, null), false, emptyHashtable);
- g = i.getGraphics();
- }
- }
-
- /** used to avoid garbage creation with getClipBounds() */
- private static Rectangle clipBounds = new Rectangle();
-
- protected static void _doDrawImage(Graphics g, Image i, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver o) {
- if (dx1 == dx2 || dy1 == dy2) return;
- g.drawImage(i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, o);
- }
-
- protected org.xwt.Weak _getWeak(Object o) { return new Java12Weak(o); }
- private static class Java12Weak extends java.lang.ref.WeakReference implements org.xwt.Weak {
- public Java12Weak(Object o) { super(o); }
- }
-
- private String __getClipBoard() { return super._getClipBoard(); }
- protected String _getClipBoard() {
- return (String)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() { return __getClipBoard(); }
- });
- }
-
- private void __setClipBoard(String s) { super._setClipBoard(s); }
- protected void _setClipBoard(final String s) {
- java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
- public Object run() {
- __setClipBoard(s);
- return null;
- }
- });
- }
-
- protected String getDescriptiveName() { return "Java 1.2+ JVM"; }
-
- protected void _newBrowserWindow(String url) {
- if (Main.applet == null) {
- if (Log.on) Log.log(this, "Main.applet is null; cannot invoke showDocument()");
- return;
- }
- if (Log.on) Log.log(this, "asking browser to show URL " + url);
- try {
- Main.applet.getAppletContext().showDocument(new URL(url), "_blank");
- } catch (MalformedURLException e) {
- if (Log.on) Log.log(this, e);
- }
- }
-
-}
+++ /dev/null
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
-package org.xwt.util;
-
-import org.mozilla.javascript.*;
-import java.net.*;
-import java.io.*;
-import java.util.*;
-import org.xwt.*;
-
-/** Simple implementation of a JavaScript host object.
- *
- * If privateVars is set, then any "var" declaration issued on this
- * scope will create a variable visible only to scripts from the same
- * directory (package) as the script that made the declaration.
- *
- * This is implemented by making JSObject.Top the ultimate
- * parentScope of all privateVars-style JSObjects. Puts to JSObjects
- * which are var-decls will not climb the scope chain, and will be
- * put directly to the JSObject. Puts which are <i>not</i> var-decls
- * will climb the scope chain and will be put to Top, which will then
- * re-put the value to the JSObject as a global.
- */
-public class JSObject implements Scriptable {
-
- // Static Data ///////////////////////////////////////////////////////////////////////
-
- /** helper; retrieves the 'source code filename' (usually the nodeName) of the currently-executing function in this thread */
- public static String getCurrentFunctionSourceName() {
- Context cx = Context.getCurrentContext();
- if (cx == null) {
- if (Log.on) Log.log(JSObject.class, "Context.getCurrentContext() is null in getCurrentFunctionSourceName()");
- return "unknown";
- }
- Function cf = cx.currentFunction;
- if (cf == null) return null;
- return (cf instanceof InterpretedFunction) ?
- ((InterpretedFunction)cf).getSourceName() : ((InterpretedScript)cf).getSourceName();
- }
-
- /** cache for nodeNameToPackageName(); prevents creation of zillions of String objects */
- private static Hash nodeNameToPackageNameHash = new Hash(1000, 2);
-
- /** converts a nodeName (source code filename) into the 'package name' (resource name of its directory) */
- public static String nodeNameToPackageName(String nodeName) {
- if (nodeName == null) return null;
- String ret = (String)nodeNameToPackageNameHash.get(nodeName);
- if (ret != null) return ret;
- ret = nodeName;
- for(int i=0; i<ret.length() - 1; i++)
- if (ret.charAt(i) == '.' && (ret.charAt(i + 1) == '_' || Character.isDigit(ret.charAt(i + 1)))) {
- ret = ret.substring(0, i);
- break;
- }
- if (ret.lastIndexOf('.') != -1)
- ret = ret.substring(0, ret.lastIndexOf('.'));
- ret = ret.intern();
- nodeNameToPackageNameHash.put(nodeName, ret);
- return ret;
- }
-
- /** this holds a scope which has been initialized with the standard ECMA objects */
- public static Scriptable defaultObjects = Context.enter().initStandardObjects(null);
-
- // Instance Data ///////////////////////////////////////////////////////////////////////
-
- /** The properties that holds our scope */
- protected Hash properties = null;
-
- /** If true, put()s and delete()s are prohibited */
- boolean sealed = false;
-
- /** If true, variables declared with 'var' become visible only to scripts from the same
- * directory/package as the one which created the variable
- */
- boolean privateVars = false;
-
- public JSObject() { }
- public JSObject(boolean privateVars) { this.privateVars = privateVars; }
- public JSObject(boolean privateVars, boolean sealed) { this.privateVars = privateVars; setSeal(sealed); }
-
- public Object get(String name) { return get(name, null); }
- public Object get(String name, Scriptable start) {
- if (name == null || name.equals("") || properties == null) return null;
-
- Object ret = properties.get(name, nodeNameToPackageName(getCurrentFunctionSourceName()));
- if (ret == NOT_FOUND) return null;
- if (ret != null) return ret;
- return properties.get(name, null);
- }
-
- /** returns the package-private variable <tt>name</tt> associated with <tt>nodeName</tt> */
- public Object getPrivately(String name, String nodeName) {
- return properties == null ? null : properties.get(name, nodeNameToPackageName(nodeName));
- }
-
- /** puts a property as a private variable, accessible only to scripts in the source code file <tt>nodeName</tt> */
- public void putPrivately(String name, Object value, String nodeName) {
- if (!privateVars) {
- putGlobally(name, null, value);
- return;
- }
- if (properties == null) properties = new Hash();
-
- // we use NOT_FOUND to mark a variable which exists as a script-local, yet has a value of null
- if (value == null) value = NOT_FOUND;
- properties.put(name, nodeNameToPackageName(nodeName), value);
- }
-
- /** forces a property to be put globally -- accessible to all scripts */
- public void putGlobally(String name, Scriptable start, Object value) {
- if (name == null || name.equals("")) return;
- if (properties == null) properties = new Hash();
- properties.put(name, null, value);
- }
-
- /**
- * if a put is made directly to us (rather than cascading up to
- * Top), by a script for whom we are in the ultimate parent
- * scope, it must be a var-declaration
- */
- public void put(String name, Object value) { put(name, null, value); }
- public void put(String name, Scriptable start, Object value) {
- if (sealed) return;
- if (name == null || name.equals("")) return;
-
- if (getPrivately(name, getCurrentFunctionSourceName()) != null)
- putPrivately(name, value, getCurrentFunctionSourceName());
-
- for(Scriptable cur = Context.enter().currentFunction; cur != null; cur = cur.getParentScope())
- if (cur == this) {
- putPrivately(name, value, getCurrentFunctionSourceName());
- return;
- }
- putGlobally(name, start, value);
- }
-
- /** if privateVars is enabled, we always return false, to see if the put propagates up to Top */
- public boolean has(String name, Scriptable start) {
- if (!privateVars) return properties != null && properties.get(name) != null;
- Top.lastByThread.put(Thread.currentThread(), this);
- return false;
- }
-
- public Object[] getIds() {
- if (properties == null) return new Object[] { };
- else return properties.keys();
- }
-
- /** Parent scope of all JSObjects; we use the has(String) method on this object to determine if a put represents a var-declaration or a plain 'ol put */
- private static class Top implements Scriptable {
-
- /** Last JSObject to perform a has(), keyed by thread.
- * Assumes that every Top.has() is immediately preceded by a JSObject.has() in the same thread
- */
- public static Hash lastByThread = new Hash();
-
- public static Top singleton = new Top();
- private Top() { }
-
- public boolean has(String name, Scriptable start) { return true; }
- public void put(String name, Scriptable start, Object value) {
- JSObject last = (JSObject)lastByThread.get(Thread.currentThread());
- if (last.properties != null && last.properties.get(name, nodeNameToPackageName(getCurrentFunctionSourceName())) != null)
- last.put(name, start, value);
- else last.putGlobally(name, start, value);
- }
-
- public Object get(String name, Scriptable start) {
-
- // hack since Rhino needs to be able to grab these functions to create new objects
- if (name.equals("Object")) return JSObject.defaultObjects.get("Object", null);
- if (name.equals("Array")) return JSObject.defaultObjects.get("Array", null);
- if (name.equals("Function")) return JSObject.defaultObjects.get("Function", null);
- if (name.equals("TypeError")) return JSObject.defaultObjects.get("TypeError", null);
- if (name.equals("ConversionError")) return JSObject.defaultObjects.get("ConversionError", null);
- return ((JSObject)lastByThread.get(Thread.currentThread())).get(name, start);
- }
-
- // Trivial methods
- public String getClassName() { return "Top"; }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- public void delete(String name) { }
- public Scriptable getParentScope() { return null; }
- public void setParentScope(Scriptable p) { }
- public boolean hasInstance(Scriptable value) { return false; }
- public Scriptable getPrototype() { return null; }
- public void setPrototype(Scriptable p) { }
- public void delete(int i) { }
- public Object getDefaultValue(Class hint) { return "Top"; }
- public void put(int i, Scriptable start, Object value) { put(String.valueOf(i), start, value); }
- public Object get(int i, Scriptable start) { return get(String.valueOf(i), start); }
- public boolean has(int i, Scriptable start) { return has(String.valueOf(i), start); }
- public Object[] getIds() { return new Object[] { }; }
-
- }
-
- // Helper class for defining functions. //////////////////////////////////////
-
- public static abstract class JSFunction extends JSObject implements Function {
- public JSFunction() { setSeal(true); }
- public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
- }
-
- // Trivial Methods ///////////////////////////////////////////////////////////
-
- public void setSeal(boolean doseal) { sealed = doseal; }
- public void flush() { if (properties != null) properties.clear(); }
- public void delete(String name) { if (Log.on) Log.log(this, "JSObject.delete() should not be reachable"); }
- public void delete(int i) { if (Log.on) Log.log(this, "JSObject.delete() should not be reachable"); }
- public Scriptable getParentScope() { return privateVars ? Top.singleton : null; }
- public void setParentScope(Scriptable p) { }
- public boolean hasInstance(Scriptable value) { return false; }
- public Scriptable getPrototype() { return null; }
- public void setPrototype(Scriptable p) { }
- public String getClassName() { return this.getClass().getName(); }
- public Object getDefaultValue(Class hint) { return toString(); }
- public void put(int i, Scriptable start, Object value) { put(String.valueOf(i), start, value); }
- public Object get(int i, Scriptable start) { return get(String.valueOf(i), start); }
- public boolean has(int i, Scriptable start) { return has(String.valueOf(i), start); }
-
-}
-