2004/01/13 03:56:00
[org.ibex.core.git] / src / org / xwt / XWT.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.net.*;
6 import java.text.*;
7 import java.util.*;
8 import org.xwt.js.*;
9 import org.xwt.util.*;
10 import org.xwt.translators.*;
11 import org.bouncycastle.util.encoders.Base64;
12
13 /** Singleton class that provides all functionality in the xwt.* namespace */
14 public final class XWT extends JS {
15
16     public final Stream rr;
17     public XWT(Stream rr) { this.rr = rr; }
18
19     private Cache subCache = new Cache(20);
20     private Sub getSub(String s) {
21         Sub ret = (Sub)subCache.get(s);
22         if (ret == null) subCache.put(s, ret = new Sub(s));
23         return ret;
24     }
25
26     /** lets us put multi-level get/put/call keys all in the same method */
27     private class Sub extends JS {
28         String key;
29         Sub(String key) { this.key = key; }
30         public String toString() { return "XWTSUB " + key; }
31         public void put(Object key, Object val) throws JSExn { XWT.this.put(this.key + "." + key, val); }
32         public Object get(Object key) throws JSExn { return XWT.this.get(this.key + "." + key); }
33         public boolean coerceToBoolean() {
34             if (key.equals("ui.key.alt")) return Surface.alt ? true : false;
35             return super.coerceToBoolean();
36         }
37         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
38             return XWT.this.callMethod(this.key, a0, a1, a2, rest, nargs);
39         }
40         public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
41             return XWT.this.callMethod(this.key + "." + method, a0, a1, a2, rest, nargs);
42         }
43     }
44
45     public Object get(Object name) throws JSExn {
46         if (name instanceof String && ((String)name).length() == 0) return rr;
47         //#switch(name)
48         case "math": return xwtMath;
49         case "string": return xwtString;
50         case "date": return METHOD;
51         case "origin": return Main.origin;  // FIXME not in ref
52         case "box": return new Box();
53         case "apply": return METHOD;
54         case "graft": return METHOD;
55         case "clone": return METHOD;
56         case "regexp": return METHOD;
57         case "ui.font": return getSub("ui.font");
58         case "ui.font.sansserif": return Main.builtin.get("fonts/vera/Vera.ttf");
59         case "ui.font.monospace": return Main.builtin.get("fonts/vera/VeraMono.ttf");
60         case "ui.font.serif": return Main.builtin.get("fonts/vera/VeraSe.ttf");
61         case "ui": return getSub("ui");
62         case "ui.browser": return METHOD;
63         case "ui.mouse": return getSub("ui.mouse");
64         case "ui.mouse.button":
65             if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
66             else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
67             else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
68             else return ZERO;
69         case "ui.key": return getSub("ui.key");
70         case "ui.key.alt": return getSub("ui.key.alt");
71         case "ui.key.alt.name": return Platform.altKeyName();
72         case "ui.key.control": return Surface.control ? T : F;
73         case "ui.key.shift": return Surface.shift ? T : F;
74         case "ui.clipboard": return Platform.getClipBoard();
75         case "ui.maxdim": return new Integer(Short.MAX_VALUE);
76         case "ui.screen": return getSub("ui.screen");
77         case "ui.screen.width": return new Integer(Platform.getScreenWidth());
78         case "ui.screen.height": return new Integer(Platform.getScreenHeight());
79         case "undocumented": return getSub("undocumented");
80         case "undocumented.internal": return getSub("undocumented.internal");
81         case "thread": return getSub("thread");
82         case "thread.yield": return METHOD;
83         case "thread.sleep": return METHOD;
84         case "stream": return getSub("stream");
85         case "stream.home": return url2res("file:" + System.getProperty("user.home"));
86         case "stream.temp": return url2res("file:" + System.getProperty("java.io.tempdir"));
87         case "stream.watch": return METHOD;
88         case "stream.unzip": return METHOD;
89         case "stream.uncab": return METHOD;
90         case "stream.cache": return METHOD;
91         case "stream.url": return METHOD;
92         case "stream.parse.html": return METHOD;
93         case "stream.parse.xml": return METHOD;
94         case "stream.parse.utf8": return METHOD;
95         case "net": return getSub("net");
96         case "net.rpc": return getSub("net.rpc");
97         case "net.rpc.xml": return METHOD;
98         case "net.rpc.soap": return METHOD;
99         case "log": return getSub("log");
100         case "log.debug": return METHOD;
101         case "log.info": return METHOD;
102         case "log.warn": return METHOD;
103         case "log.error": return METHOD;
104         case "crypto": return getSub("crypto");
105         case "crypto.rsa": return METHOD;
106         case "crypto.md5": return METHOD;
107         case "crypto.sha1": return METHOD;
108         case "crypto.rc4": return METHOD;
109         //#end
110         return super.get(name);
111     }
112
113     public void put(Object name, final Object value) throws JSExn {
114         //#switch(name)
115         case "thread": Scheduler.add((JSFunction)value); return;
116         case "ui.clipboard": Platform.setClipBoard((String)value); return;
117         case "ui.frame":
118             Box b = (Box)value;
119             Surface s = Platform.createSurface(b,true, true);
120             if(b.get("titlebar") != null) s.setTitleBarText(JS.toString(b.get("titlebar")));
121             return;
122         case "ui.window": Platform.createSurface((Box)value, false, true); return;
123         case "undocumented.internal.proxyAuthorization":
124             HTTP.Proxy.Authorization.authorization = value.toString();
125             HTTP.Proxy.Authorization.waitingForUser.release(); return;
126         //#end
127
128         throw new JSExn("attempted to put unknown property: xwt."+name);
129     }
130
131     public Object callMethod(Object name, Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
132         try {
133             //#switch(name)
134             case "date": return new JSDate(a, b, c, rest, nargs);
135             case "rpc.soap": return new SOAP((String)a, "", (String)b, (String)c);
136             case "graft":
137                 if (a instanceof Box) throw new JSExn("can't graft onto Boxes");
138                 if (a instanceof String) throw new JSExn("can't graft onto Strings");
139                 if (a instanceof Number) throw new JSExn("can't graft onto Numbers");
140                 if (a instanceof Stream) return new Stream.Graft((Stream)a, b, c);
141                 // FEATURE: grafting onto JS
142                 throw new JSExn("cannot graft onto "+a.getClass());
143             //#end
144  
145             switch (nargs) {
146                 case 0:
147                     //#switch(name)
148                     case "thread.yield": sleep(0); return null;
149                     //#end
150                     break;
151                 case 1:
152                     //#switch(name)
153                     case "ui.browser": Platform.newBrowserWindow((String)a); return null;
154                     case "clone": return new XWT((Stream)a);
155                     case "stream.unzip": return new Stream.Zip((Stream)a);
156                     case "stream.uncab": return new Stream.Cab((Stream)a);
157                     case "stream.cache": try { return new Stream.CachedStream((Stream)a, "resources", true); }
158                                       catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
159                     case "stream.url": return url2res((String)a);
160                     case "thread.sleep": sleep(JS.toInt(a)); return null;
161                     case "log.debug":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
162                     case "log.info":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
163                     case "log.warn":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
164                     case "log.error":   JS.log(this, a== null ? "**null**" : a.toString()); return null;
165                     case "regexp": return new JSRegexp(a, null);
166                     case "rpc.xml": return new XMLRPC((String)a, "");
167                     case "crypto.rsa": /* FEATURE */ return null;
168                     case "crypto.md5": /* FEATURE */ return null;
169                     case "crypto.sha1": /* FEATURE */ return null;
170                     case "crypto.rc4": /* FEATURE */ return null;
171                     case "stream.parse.html": /* FIXME */ return null;
172                     case "stream.parse.xml": /* FIXME -- SAX NOT DOM!! */ return null;
173                     case "stream.parse.utf8": /* FIXME */ return null;
174                     //#end
175                     break;
176                 case 2:
177                     //#switch(name)
178                     case "stream.watch": return new Stream.ProgressWatcher((Stream)a, (JSFunction)b);
179                     case "apply":
180                         if (b instanceof Stream) Template.getTemplate((Stream)b).apply((Box)a, XWT.this);
181                         else {
182                             JS to = (JS)a, from = (JS)b; Object k;
183                             for (Enumeration e = from.keys(); e.hasMoreElements();) {
184                                 k = e.nextElement(); to.put(k, from.get(k));
185                             }
186                         }
187                         return a;
188                     case "regexp": return new JSRegexp(a, b);
189                     //#end
190                     break;
191             }
192         } catch (RuntimeException e) {
193             // FIXME: maybe JSExn should take a second argument, Exception
194             Log.info(this, "xwt."+name+"() threw: " + e);
195             throw new JSExn("invalid argument for xwt object method "+name+"()");
196         }
197
198         throw new JSExn("invalid number of arguments for xwt object method "+name+"()");
199     }
200
201     public Stream url2res(String url) throws JSExn {
202         if (url.startsWith("http://")) return new Stream.HTTP(url);
203         else if (url.startsWith("https://")) return new Stream.HTTP(url);
204         else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
205         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
206         else throw new JSExn("invalid resource specifier " + url);
207         // FIXME support file:// via dialog boxes
208     }
209
210     public static void sleep(final int i) throws JSExn {
211         try {
212             final JS.UnpauseCallback callback = JS.pause();
213             final long currentTime = System.currentTimeMillis();
214             new Thread() { public void run() {
215                 try { Thread.sleep(i); } catch (InterruptedException e) { }
216                 Scheduler.add(callback);
217             } }.start();
218         } catch (JS.NotPauseableException npe) {
219             throw new JSExn("you cannot sleep or yield in the foreground thread");
220         }
221     }
222     
223     public static final JSMath xwtMath = new JSMath() {
224             private JS gs = new JSScope.Global();
225             public String toString() { return "XWTMATH"; }
226             public Object get(Object key) throws JSExn {
227                 //#switch(key)
228                 case "isNaN": return gs.get("isNaN");
229                 case "isFinite": return gs.get("isFinite");
230                 case "NaN": return gs.get("NaN");
231                 case "Infinity": return gs.get("Infinity");
232                 //#end
233                 return super.get(key);
234             }
235         };
236
237     public static final JS xwtString = new JS() {
238             private JS gs = new JSScope.Global();
239             public void put(Object key, Object val) { }
240             public Object get(Object key) throws JSExn {
241                 //#switch(key)
242                 case "parseInt": return gs.get("parseInt");
243                 case "parseFloat": return gs.get("parseFloat");
244                 case "decodeURI": return gs.get("decodeURI");
245                 case "decodeURIComponent": return gs.get("decodeURIComponent");
246                 case "encodeURI": return gs.get("encodeURI");
247                 case "encodeURIComponent": return gs.get("encodeURIComponent");
248                 case "escape": return gs.get("escape");
249                 case "unescape": return gs.get("unescape");
250                 case "fromCharCode": return gs.get("stringFromCharCode");
251                 //#end
252                 return null;
253             }
254         };
255
256     private class XMLHelper extends XML {
257         Vector obStack = new Vector();
258         public XMLHelper() { super(BUFFER_SIZE); }
259         public void startElement(XML.Element c) throws XML.Exn {
260             try {
261                 JS o = new JS();
262                 o.put("$name", c.getLocalName());
263                 for(int i=0; i < c.getAttrLen(); i++) o.put(c.getAttrKey(i), c.getAttrVal(i));
264                 o.put("$numchildren", new Integer(0));
265                 obStack.addElement(o);
266             } catch (JSExn jse) {
267                 throw new Error("this should never happen");
268             }
269         }
270         public void endElement(XML.Element c) throws XML.Exn {
271             try {
272                 if (obStack.size() == 1) return;
273                 JS me = (JS)obStack.lastElement();
274                 obStack.setSize(obStack.size() - 1);
275                 JS parent = (JS)obStack.lastElement();
276                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
277                 parent.put("$numchildren", new Integer(numchildren + 1));
278                 parent.put(new Integer(numchildren), me);
279             } catch (JSExn jse) {
280                 throw new Error("this should never happen");
281             }
282         }
283         public void characters(char[] ch, int start, int length) throws XML.Exn {
284             try {
285                 String s = new String(ch, start, length);
286                 JS parent = (JS)obStack.lastElement();
287                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
288                 Object lastChild = parent.get(new Integer(numchildren - 1));
289                 if (lastChild instanceof String) {
290                     parent.put(new Integer(numchildren - 1), lastChild + s);
291                 } else {
292                     parent.put("$numchildren", new Integer(numchildren + 1));
293                     parent.put(new Integer(numchildren), s);
294                 }
295             } catch (JSExn jse) {
296                 throw new Error("this should never happen");
297             }
298         }
299         public void whitespace(char[] ch, int start, int length) {}
300         public JS doParse(InputStream is) throws JSExn {
301             try { 
302                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
303                 parse(r);
304             } catch (XML.Exn e) {
305                 throw new JSExn("error parsing XML: " + e.toString());
306             } catch (IOException e) {
307                 if (Log.on) Log.info(this, "IO Exception while reading from file");
308                 if (Log.on) Log.info(this, e);
309                 throw new JSExn("error reading from Resource");
310             }
311             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
312         }
313     }
314 }