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