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