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