270e138a513cdf995a5a994087008c29467f70ea
[org.ibex.core.git] / src / org / ibex / core / Ibex.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.core;
6
7 import java.io.*;
8 import org.ibex.js.*;
9 import org.ibex.util.*;
10 import org.ibex.graphics.*;
11 import org.ibex.plat.*;
12 import org.ibex.net.*;
13 import org.ibex.crypto.*;
14
15 /** Singleton class that provides all functionality in the ibex.* namespace */
16 public final class Ibex extends JS implements JS.Cloneable {
17
18     // FIXME remove this
19     private final JS rr;
20
21     public Ibex(Stream rr) { try { this.rr = bless(rr);} catch(JSExn e) { throw new Error("should never happen: " + e); } }
22
23     public JS resolveString(String str, boolean permitAbsolute) throws JSExn {
24         if (str.indexOf("://") != -1) {
25             if (permitAbsolute) return url2res(str);
26             throw new JSExn("absolute URL " + str + " not permitted here");
27         }
28         // root-relative
29         //JS ret = (JS)getAndTriggerTraps("");
30         //FIXME
31         JS ret = rr;
32         while(str.indexOf('.') != -1) {
33             String path = str.substring(0, str.indexOf('.'));
34             str = str.substring(str.indexOf('.') + 1);
35             ret = ret.get(JS.S(path));
36         }
37         if (!"".equals(str)) ret = ret.get(JS.S(str));
38         return ret;
39     }
40
41     /** lets us put multi-level get/put/call keys all in the same method */
42     private class Sub extends JS {
43         JS key;
44         Sub(JS key) { this.key = key; }
45         public void put(JS key, JS val) throws JSExn { Ibex.this.put(JS.S(JS.toString(this.key) + "." + JS.toString(key)), val); }
46         public JS get(JS key) throws JSExn { return Ibex.this.get(JS.S(JS.toString(this.key) + "." + JS.toString(key))); }
47         public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
48             return Ibex.this.callMethod(this.key, a0, a1, a2, rest, nargs);
49         }
50         public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
51             return Ibex.this.callMethod(JS.S(JS.toString(this.key) + "." + JS.toString(method)), a0, a1, a2, rest, nargs);
52         }
53     }
54     private Cache subCache = new Cache(20);
55     private Sub getSub(JS key) {
56         Sub ret = (Sub)subCache.get(key);
57         if (ret == null) subCache.put(key, ret = new Sub(key));
58         return ret;
59     }
60
61     public JS get(JS name) throws JSExn {
62         // FIXME: SHouldn't need this (just trap [""])
63         if (JS.isString(name) && JS.toString(name).length() == 0) return rr;
64         // FEATURE: Preprocessor hack to generate specialized JS instances (avoid all this string concatenation)
65         //#switch(JS.toString(name))
66         case "math": return ibexMath;
67         case "string": return ibexString;
68         case "date": return METHOD;
69         case "box": return new Box();
70         case "clone": return METHOD;
71         case "bless": return METHOD;
72         case "regexp": return METHOD;
73         case "ui": return getSub(name);
74         case "ui.font": return getSub(name);
75         case "ui.font.wait": return METHOD;
76         case "ui.font.width": return METHOD;
77         case "ui.font.height": return METHOD;
78         case "ui.font.sansserif": return Main.builtin.get(JS.S("fonts/vera/Vera.ttf"));
79         case "ui.font.monospace": return Main.builtin.get(JS.S("fonts/vera/VeraMono.ttf"));
80         case "ui.font.serif": return Main.builtin.get(JS.S("fonts/vera/VeraSe.ttf"));
81         case "ui.browser": return METHOD;
82         case "ui.mouse": return getSub(name);
83         case "ui.mouse.button":
84             if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
85             else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
86             else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
87             else return ZERO;
88         case "ui.key": return getSub(name);
89         case "ui.key.name": return getSub(name);
90         case "ui.key.name.alt": return JS.S(Platform.altKeyName());
91         case "ui.key.alt": return Surface.alt ? T : F;
92         case "ui.key.control": return Surface.control ? T : F;
93         case "ui.key.shift": return Surface.shift ? T : F;
94         case "ui.clipboard": return JS.S((String)Platform.getClipBoard());
95         case "ui.maxdim": return N(Short.MAX_VALUE);
96         case "ui.screen": return getSub(name);
97         case "ui.screen.width": return N(Platform.getScreenWidth());
98         case "ui.screen.height": return N(Platform.getScreenHeight());
99         case "undocumented": return getSub(name);
100         case "undocumented.initialOrigin": return JS.S(Main.origin);
101         case "undocumented.initialTemplate": return JS.S(Main.initialTemplate);
102         case "thread": return getSub(name);
103         case "thread.yield": return METHOD;
104         case "thread.sleep": return METHOD;
105         case "stream": return getSub(name);
106         case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
107         case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
108         case "stream.watch": return METHOD;
109         case "stream.unzip": return METHOD;
110         case "stream.uncab": return METHOD;
111         case "stream.cache": return METHOD;
112         case "stream.url": return METHOD;
113         case "stream.parse.html": return METHOD;
114         case "stream.parse.xml": return METHOD;
115         case "stream.parse.utf8": return METHOD;
116         case "net": return getSub(name);
117         case "net.rpc": return getSub(name);
118         case "net.rpc.xml": return METHOD;
119         case "net.rpc.soap": return METHOD;
120         case "log": return getSub(name);
121         case "log.debug": return METHOD;
122         case "log.info": return METHOD;
123         case "log.warn": return METHOD;
124         case "log.error": return METHOD;
125         case "crypto": return getSub(name);
126         case "crypto.rsa": return METHOD;
127         case "crypto.md5": return METHOD;
128         case "crypto.sha1": return METHOD;
129         case "crypto.rc4": return METHOD;
130         //#end
131         return null;
132     }
133
134     public void put(JS name, JS value) throws JSExn {
135         //#switch(JS.toString(name))
136         case "thread": Scheduler.add((Task)value); return;
137         case "ui.clipboard": Platform.setClipBoard(JS.toString(value)); return;
138         case "ui.frame": Platform.createSurface((Box)value, true, true); return;
139         case "ui.window": Platform.createSurface((Box)value, false, true); return;
140         case "undocumented.proxyAuthorization":
141             HTTP.Proxy.Authorization.authorization = value.toString();
142             HTTP.Proxy.Authorization.waitingForUser.release();
143             return;
144         //#end
145         throw new JSExn("attempted to put unknown property: ibex."+name);
146     }
147
148     public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
149         try {
150             //#switch(JS.toString(name))
151             case "date": return new JSDate(a, b, c, rest, nargs);
152             case "net.rpc.soap": return new SOAP(JS.toString(a), "", JS.toString(b), JS.toString(c));
153                 // FIXME support object dumping
154             case "log.debug":    JS.debug(a== null ? "**null**" : JS.debugToString(a)); return null;
155             case "log.info":     JS.info(a== null ? "**null**" : JS.debugToString(a)); return null;
156             case "log.warn":     JS.warn(a== null ? "**null**" : JS.debugToString(a)); return null;
157             case "log.error":    JS.error(a== null ? "**null**" : JS.debugToString(a)); return null;
158             //#end
159  
160             switch (nargs) {
161                 case 0:
162                     //#switch(JS.toString(name))
163                     case "thread.yield": sleep(0); return null;
164                     //#end
165                     break;
166                 case 1:
167                     //#switch(JS.toString(name))
168                     case "clone":
169                         if(a == null) throw new JSExn("can't clone the null value");
170                         return ((JS)a).jsclone();
171                     case "bless": return bless((JS)a);
172                     case "ui.browser": Platform.newBrowserWindow(JS.toString(a)); return null;
173                     case "stream.unzip": return a == null ? null : new Stream.Zip((Stream)a);
174                         //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
175                     case "stream.cache":
176                         try { return a == null ? null : new Stream.CachedStream((Stream)a, "resources", true); }
177                         catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
178                     case "stream.url": {
179                         String url = JS.toString(a);
180                         if (url.startsWith("http://")) return new Stream.HTTP(url);
181                         else if (url.startsWith("https://")) return new Stream.HTTP(url);
182                         else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
183                         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
184                         else if (url.startsWith("file:")) {
185                             // FIXME
186                             Platform.fileDialog(url.substring(5), false);
187                         }
188                         throw new JSExn("invalid resource specifier " + url);
189                     }
190                     case "thread.sleep": sleep(JS.toInt(a)); return null;
191                     case "regexp": return new JSRegexp(a, null);
192                     case "net.rpc.xml": return new XMLRPC(JS.toString(a), "");
193                     case "crypto.rsa": /* FEATURE */ return null;
194                     case "crypto.md5": /* FEATURE */ return null;
195                     case "crypto.sha1": /* FEATURE */ return null;
196                     case "crypto.rc4": /* FEATURE */ return null;
197                     case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
198                     case "stream.parse.xml": if(a == null) return null; new XMLHelper(b).doParse(a); return null;
199                         // FIXME backgrounding
200                     case "stream.parse.utf8": if(a == null) return null;
201                                               try { return JS.S(new String(InputStreamToByteArray.convert(a.getInputStream()))); }
202                                               catch (Exception e) { Log.warn(this, e); }
203                     //#end
204                     break;
205                 case 2:
206                     //#switch(JS.toString(name))
207                     case "stream.watch": return new Stream.ProgressWatcher((Stream)a, b);
208                     case "regexp": return new JSRegexp(a, b);
209                     //#end
210                 case 3:
211                     //#switch(JS.toString(name))
212                     case "ui.font.height": return N(Font.getFont(a, JS.toInt(b)).textheight(JS.toString(c)));
213                     case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
214                     case "ui.font.width": return N(Font.getFont(a, JS.toInt(b)).textwidth(JS.toString(c)));
215                     //#end
216                     break;
217             }
218         } catch (RuntimeException e) {
219             // FIXME: maybe JSExn should take a second argument, Exception
220             Log.warn(this, "ibex."+name+"() threw: " + e);
221             throw new JSExn("invalid argument for ibex object method "+name+"()");
222         }
223
224         throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
225     }
226
227     public JS url2res(String url) throws JSExn {
228         if (url.startsWith("http://")) return new Stream.HTTP(url);
229         else if (url.startsWith("https://")) return new Stream.HTTP(url);
230         else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
231         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
232         else throw new JSExn("invalid resource specifier " + url);
233         // FIXME support file:// via dialog boxes
234     }
235
236     public static void sleep(final int i) throws JSExn {
237         try {
238             final JS.UnpauseCallback callback = JS.pause();
239             // FEATURE use a single sleeper thread
240             new Thread() { public void run() {
241                 try { Thread.sleep(i); } catch (InterruptedException e) { }
242                 Scheduler.add(callback);
243             } }.start();
244         } catch (JS.NotPauseableException npe) {
245             throw new JSExn("you cannot sleep or yield in the foreground thread");
246         }
247     }
248     
249     public static final JS ibexMath = new JS() {
250             // FEATURE: find a cleaner way to do this
251             private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
252             public JS get(JS key) throws JSExn {
253                 //#switch(JS.toString(key))
254                 case "isNaN": return METHOD;
255                 case "isFinite": return METHOD;
256                 case "NaN": return METHOD;
257                 case "Infinity": return METHOD;
258                 //#end
259                 return MATH.get(key);
260             }
261             public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
262                 //#switch(JS.toString(name))
263                 case "isNaN": return gs.callMethod(name,a,b,c,rest,nargs);
264                 case "isFinite": return gs.callMethod(name,a,b,c,rest,nargs);
265                 case "NaN": return gs.callMethod(name,a,b,c,rest,nargs);
266                 case "Infinity": return gs.callMethod(name,a,b,c,rest,nargs);
267                 //#end
268                 return MATH.callMethod(name,a,b,c,rest,nargs);
269             }
270     };
271
272     public static final JS ibexString = new JS() {
273             private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
274             public JS get(JS key) throws JSExn {
275                 //#switch(JS.toString(key))
276                 case "parseInt": return METHOD;
277                 case "parseFloat": return METHOD;
278                 case "decodeURI": return METHOD;
279                 case "decodeURIComponent": return METHOD;
280                 case "encodeURI": return METHOD;
281                 case "encodeURIComponent": return METHOD;
282                 case "escape": return METHOD;
283                 case "unescape": return METHOD;
284                 case "fromCharCode": return METHOD;
285                 //#end
286                 return super.get(key);
287             }
288             public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
289                 //#switch(JS.toString(name))
290                 case "parseInt": return gs.callMethod(name,a,b,c,rest,nargs);
291                 case "parseFloat": return gs.callMethod(name,a,b,c,rest,nargs);
292                 case "decodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
293                 case "decodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
294                 case "encodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
295                 case "encodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
296                 case "escape": return gs.callMethod(name,a,b,c,rest,nargs);
297                 case "unescape": return gs.callMethod(name,a,b,c,rest,nargs);
298                 case "fromCharCode": return gs.callMethod(name,a,b,c,rest,nargs);
299                 //#end
300                 return super.callMethod(name,a,b,c,rest,nargs);
301             }
302     };
303
304     private class XMLHelper extends XML {
305         private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
306         private JS characters, whitespace, endElement, startElement;
307         public XMLHelper(JS b) throws JSExn {
308             super(BUFFER_SIZE);
309             startElement = b.getAndTriggerTraps(JS.S("startElement"));
310             endElement   = b.getAndTriggerTraps(JS.S("endElement"));
311             characters   = b.getAndTriggerTraps(JS.S("characters"));
312             whitespace   = b.getAndTriggerTraps(JS.S("whitespace"));
313         }
314
315         public void startElement(XML.Element c) throws XML.Exn { try {
316                 JS attrs = new JS.O();
317                 // FIXME attribute URIs? add an additional hash?
318                 for(int i=0; i<c.getAttrLen(); i++) attrs.put(JS.S(c.getAttrKey(i)), JS.S(c.getAttrVal(i)));
319                 startElement.call(JS.S(c.getLocalName()), attrs, JS.S(c.getUri()), null, 3);
320         } catch (JSExn jse) { throw new Wrapper(jse); } }
321
322         public void endElement(XML.Element c) throws XML.Exn { try {
323                 endElement.call(JS.S(c.getLocalName()), JS.S(c.getUri()), null, null, 2);
324         } catch (JSExn jse) { throw new Wrapper(jse); } }
325
326         public void characters(char[] ch, int start, int length) throws XML.Exn { try {
327                 characters.call(JS.S(new String(ch, start, length)), null, null, null, 1);
328         } catch (JSExn jse) { throw new Wrapper(jse); } }
329
330         public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
331                 whitespace.call(JS.S(new String(ch, start, length)), null, null, null, 1);
332         } catch (JSExn jse) { throw new Wrapper(jse); } }
333
334         public void doParse(JS s) throws JSExn {
335             try { 
336                 parse(new BufferedReader(new InputStreamReader(s.getInputStream())));
337             } catch (Wrapper e) {
338                 throw e.wrapee;
339             } catch (XML.Exn e) {
340                 throw new JSExn("error parsing XML: " + e.toString());
341             } catch (IOException e) {
342                 if (Log.on) Log.info(this, "IO Exception while reading from file");
343                 if (Log.on) Log.info(this, e);
344                 throw new JSExn("error reading from Resource");
345             }
346         }
347     }
348
349     // FEATURE: move this into builtin.xwar
350     public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
351     // JS:FIXME: This doesn't properly handle traps
352     public static class Blessing extends JS.O {
353         private Ibex ibex;
354         private Template t = null;
355         public JS parentkey = null;
356         public Blessing parent = null;
357         public JS clonee;
358         private Hash cache = new Hash();
359         public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
360             this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
361         public JS get(JS key) throws JSExn {
362             if (JS.isString(key) && JS.toString(key).equals("")) return getStatic();
363             if (cache.get(key) != null) return (JS)cache.get(key);
364             JS ret = new Blessing(clonee.get(key), ibex, this, key);
365             cache.put(key, ret);
366             return ret;
367         }
368         public static Blessing getBlessing(JS js) {
369             while (js instanceof JS.Clone && !(js instanceof Blessing)) js = ((JS.Clone)js).getClonee();
370             if (!(js instanceof Blessing)) return null;
371             return (Blessing)js;
372         }
373         // FEATURE: This is a gross hack
374         public InputStream getImage() throws JSExn {
375             try {
376                 InputStream in = getInputStream();
377                 if (in != null) return in;
378             } catch (IOException e) { /* DELIBERATE */ }
379             String[] exts = new String[] { ".png", ".jpeg", ".gif" };
380             for (int i=0; i < exts.length; i++)
381                 try {
382                     InputStream in = parent.get(JS.S(JS.toString(parentkey) + exts[i])).getInputStream();
383                     if (in != null) return in;
384                 } catch (IOException f) { /* DELIBERATE */ }
385             return null;
386         }
387         public JS getStatic() throws JSExn {
388             try {
389                 if (t == null) {
390                     // FEATURE: Might want to handle the ".t" part better
391                     JS res = parent.get(JS.S(JS.toString(parentkey) + ".t"));
392                     t = Template.buildTemplate(description(), res, ibex);
393                 }
394                 return t != null ? t.staticObject : null;
395             } catch (Exception e) {
396                 Log.error(this, e);
397                 return null;
398             }
399         }
400         private String description() {
401             String s = JS.debugToString(parentkey);
402             for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JS.debugToString(b.parentkey) + "." + s;
403             return s;
404         }
405         public JS call(JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
406             if (nargs != 1) throw new JSExn("can only call a template with one arg");
407             getStatic();
408             if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
409             if(!(a instanceof Box)) throw new JSExn("can only apply templates to boxes");
410             t.apply((Box)a);
411             return a;
412         }
413         // FEATURE: This is a gross hack
414         Template getTemplate()  throws JSExn {
415             getStatic();
416             if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
417             return t;
418         }
419         // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
420         public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }
421     }
422
423 }