2003/12/16 22:15:41
[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             throw new JSExn("invalid argument for xwt object method "+name+"()");
182         }
183
184         throw new JSExn("invalid number of arguments for xwt object method "+name+"()");
185     }
186
187     public Res url2res(String url) throws JSExn {
188         if (url.startsWith("http://")) return new Res.HTTP(url);
189         else if (url.startsWith("https://")) return new Res.HTTP(url);
190         else if (url.startsWith("data:")) return new Res.ByteArray(Base64.decode(url.substring(5)), null);
191         else if (url.startsWith("utf8:")) return new Res.ByteArray(url.substring(5).getBytes(), null);
192         else throw new JSExn("invalid resource specifier " + url);
193     }
194
195     public static void sleep(final int i) throws JSExn {
196         try {
197             final JS.UnpauseCallback callback = JS.pause();
198             final long currentTime = System.currentTimeMillis();
199             new Thread() { public void run() {
200                 try { Thread.sleep(i); } catch (InterruptedException e) { }
201                 Scheduler.add(callback);
202             } }.start();
203         } catch (JS.NotPauseableException npe) {
204             throw new JSExn("you cannot sleep or yield in the foreground thread");
205         }
206     }
207     
208     public static final JSMath xwtMath = new JSMath() {
209             private JS gs = new JSScope.Global();
210             public String toString() { return "XWTMATH"; }
211             public Object get(Object key) throws JSExn {
212                 //#switch(key)
213                 case "isNaN": return gs.get("isNaN");
214                 case "isFinite": return gs.get("isFinite");
215                 case "NaN": return gs.get("NaN");
216                 case "Infinity": return gs.get("Infinity");
217                 //#end
218                 return super.get(key);
219             }
220         };
221
222     public static final JS xwtString = new JS() {
223             private JS gs = new JSScope.Global();
224             public void put(Object key, Object val) { }
225             public Object get(Object key) throws JSExn {
226                 //#switch(key)
227                 case "parseInt": return gs.get("parseInt");
228                 case "parseFloat": return gs.get("parseFloat");
229                 case "decodeURI": return gs.get("decodeURI");
230                 case "decodeURIComponent": return gs.get("decodeURIComponent");
231                 case "encodeURI": return gs.get("encodeURI");
232                 case "encodeURIComponent": return gs.get("encodeURIComponent");
233                 case "escape": return gs.get("escape");
234                 case "unescape": return gs.get("unescape");
235                 case "fromCharCode": return gs.get("stringFromCharCode");
236                 //#end
237                 return null;
238             }
239         };
240
241     private class XMLHelper extends XML {
242         Vector obStack = new Vector();
243         public XMLHelper() { super(BUFFER_SIZE); }
244         public void startElement(XML.Element c) throws XML.SchemaException {
245             try {
246                 JS o = new JS();
247                 o.put("$name", c.localName);
248                 for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
249                 o.put("$numchildren", new Integer(0));
250                 obStack.addElement(o);
251             } catch (JSExn jse) {
252                 throw new Error("this should never happen");
253             }
254         }
255         public void endElement(XML.Element c) throws XML.SchemaException {
256             try {
257                 if (obStack.size() == 1) return;
258                 JS me = (JS)obStack.lastElement();
259                 obStack.setSize(obStack.size() - 1);
260                 JS parent = (JS)obStack.lastElement();
261                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
262                 parent.put("$numchildren", new Integer(numchildren + 1));
263                 parent.put(new Integer(numchildren), me);
264             } catch (JSExn jse) {
265                 throw new Error("this should never happen");
266             }
267         }
268         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
269             try {
270                 String s = new String(ch, start, length);
271                 JS parent = (JS)obStack.lastElement();
272                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
273                 Object lastChild = parent.get(new Integer(numchildren - 1));
274                 if (lastChild instanceof String) {
275                     parent.put(new Integer(numchildren - 1), lastChild + s);
276                 } else {
277                     parent.put("$numchildren", new Integer(numchildren + 1));
278                     parent.put(new Integer(numchildren), s);
279                 }
280             } catch (JSExn jse) {
281                 throw new Error("this should never happen");
282             }
283         }
284         public void whitespace(char[] ch, int start, int length) {}
285         public JS doParse(InputStream is) throws JSExn {
286             try { 
287                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
288                 parse(r);
289             } catch (XML.XMLException e) {
290                 throw new JSExn("error parsing XML: " + e.toString());
291             } catch (IOException e) {
292                 if (Log.on) Log.log(this, "IO Exception while reading from file");
293                 if (Log.on) Log.log(this, e);
294                 throw new JSExn("error reading from Resource");
295             }
296             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
297         }
298     }
299 }