2004/01/07 20:37:32
[org.ibex.core.git] / src / org / xwt / XWT.java
index f3368c4..0572b66 100644 (file)
@@ -11,259 +11,303 @@ import org.xwt.translators.*;
 import org.bouncycastle.util.encoders.Base64;
 
 /** Singleton class that provides all functionality in the xwt.* namespace */
-public final class XWT extends JS.Obj {
+public final class XWT extends JS {
 
-    public Res resourceRoot = null;
+    public final Stream rr;
+    public XWT(Stream rr) { this.rr = rr; }
 
-    public static final XWT singleton = new XWT();
-    private final JS xwtMath = new XWTMath();
-    private final JS xwtString = new XWTString();
-
-    /** 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();
+    private Cache subCache = new Cache(20);
+    private Sub getSub(String s) {
+        Sub ret = (Sub)subCache.get(s);
+        if (ret == null) subCache.put(s, ret = new Sub(s));
+        return ret;
+    }
 
-    public Object get(Object name) {
-        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("clipboard")) return Platform.getClipBoard();
-        /* FIXME
-        else if (name.equals("static")) return .getStatic("");
-        */
-        else if (name.equals("origin")) return Main.origin;
-        else if (name.equals("maxdim")) return new Integer(Short.MAX_VALUE);
-        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("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("math")) return xwtMath;
-        else if (name.equals("string")) return xwtString;
-        else if (name.equals("parseInt")) return xwtString.get("parseInt");
-        else if (name.equals("parseFloat")) return xwtString.get("parseFloat");
-        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);
+    /** lets us put multi-level get/put/call keys all in the same method */
+    private class Sub extends JS {
+        String key;
+        Sub(String key) { this.key = key; }
+        public String toString() { return "XWTSUB " + key; }
+        public void put(Object key, Object val) throws JSExn { XWT.this.put(this.key + "." + key, val); }
+        public Object get(Object key) throws JSExn { return XWT.this.get(this.key + "." + key); }
+        public boolean coerceToBoolean() {
+            if (key.equals("ui.key.alt")) return Surface.alt ? true : false;
+            return super.coerceToBoolean();
+        }
+        public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
+            return XWT.this.callMethod(this.key, a0, a1, a2, rest, nargs);
+        }
+        public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
+            return XWT.this.callMethod(this.key + "." + method, a0, a1, a2, rest, nargs);
         }
-        else return super.get(name);
     }
 
-    public void put(Object name, Object value) {
-        if (name.equals("thread") && value != null && value instanceof JS.Callable) ThreadMessage.newthread((JS.Callable)value);
-        else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
-        else if (name.equals("proxyAuthorization")) {
-            // FIXME: undocumented, possibly insecure
-            HTTP.Proxy.Authorization.authorization = value.toString();
-            HTTP.Proxy.Authorization.waitingForUser.release();
-        } else super.put(name, value);
+    public Object get(Object name) throws JSExn {
+        if (name instanceof String && ((String)name).length() == 0) return rr;
+        //#switch(name)
+        case "math": return xwtMath;
+        case "string": return xwtString;
+        case "date": return METHOD;
+        case "origin": return Main.origin;  // FIXME not in ref
+        case "box": return new Box();
+        case "apply": return METHOD;
+        case "graft": return METHOD;
+        case "clone": return METHOD;
+        case "regexp": return METHOD;
+        case "font": return getSub("font");
+        case "font.sansserif": return Main.builtin.get("fonts/vera/Vera.ttf");
+        case "font.monospace": return Main.builtin.get("fonts/vera/VeraMono.ttf");
+        case "font.serif": return Main.builtin.get("fonts/vera/VeraSe.ttf");
+        case "ui": return getSub("ui");
+        case "ui.browser": return METHOD;
+        case "ui.mouse": return getSub("ui.mouse");
+        case "ui.mouse.button":
+            if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
+            else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
+            else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
+            else return ZERO;
+        case "ui.key": return getSub("ui.key");
+        case "ui.key.alt": return getSub("ui.key.alt");
+        case "ui.key.alt.name": return Platform.altKeyName();
+        case "ui.key.control": return Surface.control ? T : F;
+        case "ui.key.shift": return Surface.shift ? T : F;
+        case "ui.clipboard": return Platform.getClipBoard();
+        case "ui.maxdim": return new Integer(Short.MAX_VALUE);
+        case "ui.screen": return getSub("ui.screen");
+        case "ui.screen.width": return new Integer(Platform.getScreenWidth());
+        case "ui.screen.height": return new Integer(Platform.getScreenHeight());
+        case "undocumented": return getSub("undocumented");
+        case "undocumented.internal": return getSub("undocumented.internal");
+        case "thread": return getSub("thread");
+        case "thread.yield": return METHOD;
+        case "thread.sleep": return METHOD;
+        case "stream": return getSub("stream");
+        case "stream.home": return url2res("file:" + System.getProperty("user.home"));
+        case "stream.temp": return url2res("file:" + System.getProperty("java.io.tempdir"));
+        case "stream.watch": return METHOD;
+        case "stream.unzip": return METHOD;
+        case "stream.uncab": return METHOD;
+        case "stream.cache": return METHOD;
+        case "stream.url": return METHOD;
+        case "stream.parse.html": return METHOD;
+        case "stream.parse.xml": return METHOD;
+        case "stream.parse.utf8": return METHOD;
+        case "rpc": return getSub("rpc");
+        case "rpc.xml": return METHOD;
+        case "rpc.soap": return METHOD;
+        case "log": return getSub("log");
+        case "log.debug": return METHOD;
+        case "log.info": return METHOD;
+        case "log.warn": return METHOD;
+        case "log.error": return METHOD;
+        case "crypto": return getSub("crypto");
+        case "crypto.rsa": return METHOD;
+        case "crypto.md5": return METHOD;
+        case "crypto.sha1": return METHOD;
+        case "crypto.rc4": return METHOD;
+        //#end
+        return super.get(name);
     }
 
-    public Object callMethod(Object method, JS.Array args, boolean checkOnly) {
-
-        if (method.equals("newBrowserWindow")) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args.length() != 1 || args.elementAt(0) == null) return null;
-            Platform.newBrowserWindow(args.elementAt(0).toString());
-            return null;
-
-        } else if (method.equals("yield")) {
-            if (checkOnly) return Boolean.TRUE;
-            sleep(0);
-            return null;
-
-        } else if (method.equals("load")) {
-            if (checkOnly) return Boolean.TRUE;
-            return Res.stringToRes(args.elementAt(0).toString());
-
-        } else if (method.equals("println")) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args.length() != 1) return null;
-            if (Log.on) Log.logJS(this, (args.elementAt(0) == null ? "**null**" : args.elementAt(0).toString()));
-            return null;
-
-        } else if (method.equals("date")) {
-            if (checkOnly) return Boolean.TRUE;
-            // FIXME
-            Log.log(XWT.class, "date not implemented");
-            return null;
-
-        } else if (method.equals("regexp")) {
-            if (checkOnly) return Boolean.TRUE;
-            return new Regexp(args);
-
-        } else if (method.equals("xmlrpc")) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args.length() != 1 || args.elementAt(0) == null) return null;
-            return new XMLRPC(args.elementAt(0).toString(), "");
+    public void put(Object name, final Object value) throws JSExn {
+        //#switch(name)
+        case "thread": Scheduler.add((JSFunction)value); return;
+        case "ui.clipboard": Platform.setClipBoard((String)value); return;
+        case "ui.frame":
+            Box b = (Box)value;
+            Surface s = Platform.createSurface(b,true, true);
+            if(b.get("titlebar") != null) s.setTitleBarText(JS.toString(b.get("titlebar")));
+            return;
+        case "ui.window": Platform.createSurface((Box)value, false, true); return;
+        case "undocumented.internal.proxyAuthorization":
+            HTTP.Proxy.Authorization.authorization = value.toString();
+            HTTP.Proxy.Authorization.waitingForUser.release(); return;
+        //#end
 
-        } else if (method.equals("soap")) {
-            if (checkOnly) return Boolean.TRUE;
-            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;
+        throw new JSExn("attempted to put unknown property: xwt."+name);
+    }
 
-        } else if (method.equals("newBox")) {
-            if (checkOnly) return Boolean.TRUE;
-            return new Box();
+    public Object callMethod(Object name, Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
+        try {
+            //#switch(name)
+            case "date": return new JSDate(a, b, c, rest, nargs);
+            case "rpc.soap": return new SOAP((String)a, "", (String)b, (String)c);
+            case "graft":
+                if (a instanceof Box) throw new JSExn("can't graft onto Boxes");
+                if (a instanceof String) throw new JSExn("can't graft onto Strings");
+                if (a instanceof Number) throw new JSExn("can't graft onto Numbers");
+                if (a instanceof Stream) return new Stream.Graft((Stream)a, b, c);
+                // FEATURE: grafting onto JS
+                throw new JSExn("cannot graft onto "+a.getClass());
+            //#end
+            switch (nargs) {
+                case 0:
+                    //#switch(name)
+                    case "thread.yield": sleep(0); return null;
+                    //#end
+                    break;
+                case 1:
+                    //#switch(name)
+                    case "ui.browser": Platform.newBrowserWindow((String)a); return null;
+                    case "clone": return new XWT((Stream)a);
+                    case "stream.unzip": return new Stream.Zip((Stream)a);
+                    case "stream.uncab": return new Stream.Cab((Stream)a);
+                    case "stream.cache": try { return new Stream.CachedStream((Stream)a, "resources", true); }
+                                      catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
+                    case "stream.url": return url2res((String)a);
+                    case "thread.sleep": sleep(JS.toInt(a)); return null;
+                    case "log.debug":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
+                    case "log.info":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
+                    case "log.warn":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
+                    case "log.error":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
+                    case "regexp": return new JSRegexp(a, null);
+                    case "rpc.xml": return new XMLRPC((String)a, "");
+                    case "crypto.rsa": /* FEATURE */ return null;
+                    case "crypto.md5": /* FEATURE */ return null;
+                    case "crypto.sha1": /* FEATURE */ return null;
+                    case "crypto.rc4": /* FEATURE */ return null;
+                    case "stream.parse.html": /* FIXME */ return null;
+                    case "stream.parse.xml": /* FIXME -- SAX NOT DOM!! */ return null;
+                    case "stream.parse.utf8": /* FIXME */ return null;
+                    //#end
+                    break;
+                case 2:
+                    //#switch(name)
+                    case "stream.watch": return new Stream.ProgressWatcher((Stream)a, (JSFunction)b);
+                    case "apply":
+                        if (b instanceof Stream) Template.getTemplate((Stream)b).apply((Box)a, XWT.this);
+                        else {
+                            JS to = (JS)a, from = (JS)b; Object k;
+                            for (Enumeration e = from.keys(); e.hasMoreElements();) {
+                                k = e.nextElement(); to.put(k, from.get(k));
+                            }
+                        }
+                        return a;
+                    case "regexp": return new JSRegexp(a, b);
+                    //#end
+                    break;
+            }
+        } catch (RuntimeException e) {
+            // FIXME: maybe JSExn should take a second argument, Exception
+            Log.info(this, "xwt."+name+"() threw: " + e);
+            throw new JSExn("invalid argument for xwt object method "+name+"()");
+        }
 
-        } else if (method.equals("sleep")) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args != null && (args.length() != 1 || args.elementAt(0) == null)) return null;
-            int i = args == null ? 0 : Box.stoi(args.elementAt(0).toString());
-            sleep(i);
-            return null;
+        throw new JSExn("invalid number of arguments for xwt object method "+name+"()");
+    }
 
-        } else if (method.equals("openFile")) {
-            //FIXME
-            /*
-            if (checkOnly) return Boolean.TRUE;
-            if (args.length() != 1) return null;
-            String file = Platform.fileDialog(args.elementAt(0).toString(), false);
-            return file == null ? null : new ByteStream(file);
-            */
+    public Stream url2res(String url) throws JSExn {
+        if (url.startsWith("http://")) return new Stream.HTTP(url);
+        else if (url.startsWith("https://")) return new Stream.HTTP(url);
+        else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
+        else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
+        else throw new JSExn("invalid resource specifier " + url);
+        // FIXME support file:// via dialog boxes
+    }
 
-        } else if (method.equals("saveFile")) {
-            if (checkOnly) return Boolean.TRUE;
-            // FIXME
-            /*
-            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());
+    public static void sleep(final int i) throws JSExn {
+        try {
+            final JS.UnpauseCallback callback = JS.pause();
+            final long currentTime = System.currentTimeMillis();
+            new Thread() { public void run() {
+                try { Thread.sleep(i); } catch (InterruptedException e) { }
+                Scheduler.add(callback);
+            } }.start();
+        } catch (JS.NotPauseableException npe) {
+            throw new JSExn("you cannot sleep or yield in the foreground thread");
+        }
+    }
+    
+    public static final JSMath xwtMath = new JSMath() {
+            private JS gs = new JSScope.Global();
+            public String toString() { return "XWTMATH"; }
+            public Object get(Object key) throws JSExn {
+                //#switch(key)
+                case "isNaN": return gs.get("isNaN");
+                case "isFinite": return gs.get("isFinite");
+                case "NaN": return gs.get("NaN");
+                case "Infinity": return gs.get("Infinity");
+                //#end
+                return super.get(key);
             }
-            try {
-                ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
+        };
+
+    public static final JS xwtString = new JS() {
+            private JS gs = new JSScope.Global();
+            public void put(Object key, Object val) { }
+            public Object get(Object key) throws JSExn {
+                //#switch(key)
+                case "parseInt": return gs.get("parseInt");
+                case "parseFloat": return gs.get("parseFloat");
+                case "decodeURI": return gs.get("decodeURI");
+                case "decodeURIComponent": return gs.get("decodeURIComponent");
+                case "encodeURI": return gs.get("encodeURI");
+                case "encodeURIComponent": return gs.get("encodeURIComponent");
+                case "escape": return gs.get("escape");
+                case "unescape": return gs.get("unescape");
+                case "fromCharCode": return gs.get("stringFromCharCode");
+                //#end
                 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");
             }
-            */
+        };
 
-        } else if (method.equals("saveFileAs")) {
-            // FIXME
-            /*
-            if (checkOnly) return Boolean.TRUE;
-            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());
+    private class XMLHelper extends XML {
+        Vector obStack = new Vector();
+        public XMLHelper() { super(BUFFER_SIZE); }
+        public void startElement(XML.Element c) throws XML.Exn {
             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");
+                JS o = new JS();
+                o.put("$name", c.getLocalName());
+                for(int i=0; i < c.getAttrLen(); i++) o.put(c.getAttrKey(i), c.getAttrVal(i));
+                o.put("$numchildren", new Integer(0));
+                obStack.addElement(o);
+            } catch (JSExn jse) {
+                throw new Error("this should never happen");
             }
-            */
-
-        } else if (method.equals("parseHTML")) {
-            if (checkOnly) return Boolean.TRUE;
-                if (args == null || args.length() != 1 || args.elementAt(0) == null) return null;
-                try {
-                    if (args.elementAt(0) instanceof Res) {
-                        return HTML.parseReader(new InputStreamReader(((Res)args.elementAt(0)).getInputStream()));
-                    } else {
-                        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 JS.Exn("error while parsing HTML");
-                }
-
-        } else if (method.equals("recursivePrintObject")) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args.length() != 1) return null;
-            recurse("", "", args.elementAt(0));
-            return null;
         }
-            
-        if (checkOnly) return Boolean.FALSE;
-        return null;
-    }
-
-    private static void recurse(String indent, String name, Object o) {
-        if (!name.equals("")) name += " : ";
-
-        if (o == null) {
-            Log.logJS(indent + name + "<null>");
-
-        } else if (o instanceof JS.Array) {
-            Log.logJS(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.logJS(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.logJS(indent + name + o);
-
-        }
-    }
-
-    public static void sleep(int i) {
-        java.lang.Thread thread = java.lang.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 { java.lang.Thread.sleep(i); } catch (Exception e) { }
-            Message.Q.add(mythread);
-            mythread.go.block();
-        }
-    }
-    
-    private static class XWTMath extends JS.Obj {
-        public XWTMath() {
-            JS gs = new JS.GlobalScope();
-            put("isNaN",gs.get("isNaN"));
-            put("isFinite",gs.get("isFinite"));
-            put("NaN",gs.get("NaN"));
-            put("Infinity",gs.get("Infinity"));
-            setSeal(true);
+        public void endElement(XML.Element c) throws XML.Exn {
+            try {
+                if (obStack.size() == 1) return;
+                JS me = (JS)obStack.lastElement();
+                obStack.setSize(obStack.size() - 1);
+                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);
+            } catch (JSExn jse) {
+                throw new Error("this should never happen");
+            }
         }
-        public Object get(Object key) {
-            Object ret = super.get(key);
-            if(ret == null) ret = JS.Math.get(key);
-            return ret;
+        public void characters(char[] ch, int start, int length) throws XML.Exn {
+            try {
+                String s = new String(ch, start, length);
+                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(new Integer(numchildren - 1), lastChild + s);
+                } else {
+                    parent.put("$numchildren", new Integer(numchildren + 1));
+                    parent.put(new Integer(numchildren), s);
+                }
+            } catch (JSExn jse) {
+                throw new Error("this should never happen");
+            }
         }
-    }
-    private static class XWTString extends JS.Obj {
-        public XWTString() {
-            JS gs = new JS.GlobalScope();
-            put("parseInt",gs.get("parseInt"));
-            put("parseFloat",gs.get("parseFloat"));
-            put("decodeURI",gs.get("decodeURI"));
-            put("decodeURIComponent",gs.get("decodeURIComponent"));
-            put("encodeURI",gs.get("encodeURI"));
-            put("encodeURIComponent",gs.get("encodeURIComponent"));
-            put("escape",gs.get("escape"));
-            put("unescape",gs.get("unescape"));
-            put("fromCharCode",gs.get("stringFromCharCode"));
-            setSeal(true);
+        public void whitespace(char[] ch, int start, int length) {}
+        public JS doParse(InputStream is) throws JSExn {
+            try { 
+                BufferedReader r = new BufferedReader(new InputStreamReader(is));
+                parse(r);
+            } catch (XML.Exn e) {
+                throw new JSExn("error parsing XML: " + e.toString());
+            } catch (IOException e) {
+                if (Log.on) Log.info(this, "IO Exception while reading from file");
+                if (Log.on) Log.info(this, e);
+                throw new JSExn("error reading from Resource");
+            }
+            return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
         }
     }
 }