270a3fe421da7d5bdb130fbf3068c9943a90b454
[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) { 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.println": return METHOD;
91         case "log.dump": return METHOD;
92         case "regexp": return METHOD;
93         case "rpc.xml": return METHOD;
94         case "rpc.soap": return METHOD;
95         case "crypto.rsa": return METHOD;
96         case "crypto.md5": return METHOD;
97         case "crypto.sha1": return METHOD;
98         case "crypto.rc4": return METHOD;
99         case "stream.parse.html": return METHOD;
100         case "stream.parse.xml": return METHOD;
101         case "stream.parse.utf8": return METHOD;
102         //#end
103         return super.get(name);
104     }
105
106     public void put(Object name, final Object value) {
107         //#switch(name)
108         case "thread": Scheduler.add((JSFunction)value);
109         case "ui.clipboard": Platform.setClipBoard((String)value);
110         case "ui.frame": Platform.createSurface((Box)value, true, true);
111         case "ui.window": Platform.createSurface((Box)value, false, true);
112         case "undocumented.internal.proxyAuthorization":
113             HTTP.Proxy.Authorization.authorization = value.toString();
114             HTTP.Proxy.Authorization.waitingForUser.release();
115         //#end
116     }
117
118     public Object callMethod(Object name, Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
119         if (name.equals("date")) return new JSDate(a, b, c, rest, nargs);
120         else if (nargs == 0 && name.equals("thread.yield")) { sleep(0); return null; }
121         else if (nargs == 2) {
122             //#switch(name)
123             case "res.watch": return new Res.ProgressWatcher((Res)a, (JSFunction)b);
124             case "soap": /* return new SOAP((String)a, "", (String)b, null); */
125             case "apply": Template.getTemplate((Res)b).apply((Box)a, XWT.this); return a;
126             //#end
127
128             /*
129         } else if (nargs == 3 && name.equals("soap")) {
130             if (name.equals("soap"))
131                 return new SOAP((String)a, "", (String)b, (String)c);
132             */
133
134         } else if (nargs == 1) {
135             //#switch(name)
136             case "ui.browser": Platform.newBrowserWindow((String)a); return null;
137             case "clone": return new XWT((Res)a);
138             case "res.unzip": return new Res.Zip((Res)a);
139             case "res.uncab": return new Res.Cab((Res)a);
140             case "res.cache": try { return new Res.CachedRes((Res)a, "resources", true); }
141                               catch (Res.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
142             case "res.url": return url2res((String)a);
143             case "thread.sleep": sleep(JS.toInt(a)); return null;
144             case "log.println": Log.logJS(this, a== null ? "**null**" : a.toString()); return null;
145             case "log.dump": Log.recursiveLog("","",a); return null;
146             case "regexp": return new JSRegexp(a, null);
147             case "rpc.xml": return new XMLRPC((String)a, "");
148             case "rpc.soap": /* return new SOAP((String)a, "", null, null); */
149             case "crypto.rsa": /* FEATURE */ break;
150             case "crypto.md5": /* FEATURE */ break;
151             case "crypto.sha1": /* FEATURE */ break;
152             case "crypto.rc4": /* FEATURE */ break;
153             case "stream.parse.html": /* FEATURE */ break;
154             case "stream.parse.xml": /* FEATURE */ break;
155             case "stream.parse.utf8": /* FEATURE */ break;
156             //#end
157         }
158         return null;
159     }
160
161     public Res url2res(String url) throws JSExn {
162         if (url.startsWith("http://")) return new Res.HTTP(url);
163         else if (url.startsWith("https://")) return new Res.HTTP(url);
164         else if (url.startsWith("data:")) return new Res.ByteArray(Base64.decode(url.substring(5)), null);
165         else if (url.startsWith("utf8:")) return new Res.ByteArray(url.substring(5).getBytes(), null);
166         else throw new JSExn("invalid resource specifier " + url);
167     }
168
169     public static void sleep(final int i) throws JSExn {
170         try {
171             final JS.UnpauseCallback callback = JS.pause();
172             final long currentTime = System.currentTimeMillis();
173             new Thread() { public void run() {
174                 try { Thread.sleep(i); } catch (InterruptedException e) { }
175                 Scheduler.add(callback);
176             } }.start();
177         } catch (JS.NotPauseableException npe) {
178             throw new JSExn("you cannot sleep or yield in the foreground thread");
179         }
180     }
181     
182     public static final JSMath xwtMath = new JSMath() {
183             private JS gs = new JSScope.Global();
184             public String toString() { return "XWTMATH"; }
185             public Object get(Object key) throws JSExn {
186                 //#switch(key)
187                 case "isNaN": return gs.get("isNaN");
188                 case "isFinite": return gs.get("isFinite");
189                 case "NaN": return gs.get("NaN");
190                 case "Infinity": return gs.get("Infinity");
191                 //#end
192                 return super.get(key);
193             }
194         };
195
196     public static final JS xwtString = new JS() {
197             private JS gs = new JSScope.Global();
198             public void put(Object key, Object val) { }
199             public Object get(Object key) throws JSExn {
200                 //#switch(key)
201                 case "parseInt": return gs.get("parseInt");
202                 case "parseFloat": return gs.get("parseFloat");
203                 case "decodeURI": return gs.get("decodeURI");
204                 case "decodeURIComponent": return gs.get("decodeURIComponent");
205                 case "encodeURI": return gs.get("encodeURI");
206                 case "encodeURIComponent": return gs.get("encodeURIComponent");
207                 case "escape": return gs.get("escape");
208                 case "unescape": return gs.get("unescape");
209                 case "fromCharCode": return gs.get("stringFromCharCode");
210                 //#end
211                 return null;
212             }
213         };
214
215     private class XMLHelper extends XML {
216         Vector obStack = new Vector();
217         public XMLHelper() { super(BUFFER_SIZE); }
218         public void startElement(XML.Element c) throws XML.SchemaException {
219             try {
220                 JS o = new JS();
221                 o.put("$name", c.localName);
222                 for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
223                 o.put("$numchildren", new Integer(0));
224                 obStack.addElement(o);
225             } catch (JSExn jse) {
226                 throw new Error("this should never happen");
227             }
228         }
229         public void endElement(XML.Element c) throws XML.SchemaException {
230             try {
231                 if (obStack.size() == 1) return;
232                 JS me = (JS)obStack.lastElement();
233                 obStack.setSize(obStack.size() - 1);
234                 JS parent = (JS)obStack.lastElement();
235                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
236                 parent.put("$numchildren", new Integer(numchildren + 1));
237                 parent.put(new Integer(numchildren), me);
238             } catch (JSExn jse) {
239                 throw new Error("this should never happen");
240             }
241         }
242         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
243             try {
244                 String s = new String(ch, start, length);
245                 JS parent = (JS)obStack.lastElement();
246                 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
247                 Object lastChild = parent.get(new Integer(numchildren - 1));
248                 if (lastChild instanceof String) {
249                     parent.put(new Integer(numchildren - 1), lastChild + s);
250                 } else {
251                     parent.put("$numchildren", new Integer(numchildren + 1));
252                     parent.put(new Integer(numchildren), s);
253                 }
254             } catch (JSExn jse) {
255                 throw new Error("this should never happen");
256             }
257         }
258         public void whitespace(char[] ch, int start, int length) {}
259         public JS doParse(InputStream is) throws JSExn {
260             try { 
261                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
262                 parse(r);
263             } catch (XML.XMLException e) {
264                 throw new JSExn("error parsing XML: " + e.toString());
265             } catch (IOException e) {
266                 if (Log.on) Log.log(this, "IO Exception while reading from file");
267                 if (Log.on) Log.log(this, e);
268                 throw new JSExn("error reading from Resource");
269             }
270             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
271         }
272     }
273 }