fix infinite loop
[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(Stream 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[] args) throws JSExn { return Ibex.this.call(this.key, args); }
49         public JS call(JS method, JS[] args) throws JSExn {
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": 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 Stream.Zip((Stream)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 Stream.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 Stream.HTTP(url);
184                         else if (url.startsWith("https://")) return new Stream.HTTP(url);
185                         else if (url.startsWith("data:")) return new Stream.ByteArray(Encode.fromBase64(url.substring(5)), null);
186                         else if (url.startsWith("utf8:")) return new Stream.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(args[0].getInputStream()))); }
205                                               catch (Exception e) { Log.warn(this, e); }
206                     //#end
207                     break;
208                 case 2:
209                     //#switch(JSU.toString(method))
210                     case "stream.watch": return new Stream.ProgressWatcher((Stream)args[0], args[1]);
211                     case "regexp": return new JSRegexp(args[0], args[1]);
212                     //#end
213                 case 3:
214                     //#switch(JSU.toString(method))
215                     case "ui.font.height": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textheight(JSU.toString(args[3])));
216                     case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
217                     case "ui.font.width": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textwidth(JSU.toString(args[3])));
218                     //#end
219                     break;
220             }
221         } catch (RuntimeException e) {
222             // FIXME: maybe JSExn should take a second argument, Exception
223             Log.warn(this, "ibex."+method+"() threw: " + e);
224             throw new JSExn("invalid argument for ibex object method "+method+"()");
225         }
226
227         throw new JSExn("invalid number of arguments ("+args.length+") for ibex object method "+method+"()");
228     }
229
230     public JS url2res(String url) throws JSExn {
231         if (url.startsWith("http://")) return new Stream.HTTP(url);
232         else if (url.startsWith("https://")) return new Stream.HTTP(url);
233         else if (url.startsWith("data:")) return new Stream.ByteArray(Encode.fromBase64(url.substring(5)), null);
234         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
235         else throw new JSExn("invalid resource specifier " + url);
236         // FIXME support file:// via dialog boxes
237     }
238
239     public static void sleep(final int i) throws JSExn {
240         try {
241             final Pausable callback = JSU.pause();
242             // FEATURE use a single sleeper thread
243             new Thread() { public void run() {
244                 try { Thread.sleep(i); } catch (InterruptedException e) { }
245                 Scheduler.add(callback);
246             } }.start();
247         } catch (Pausable.NotPausableException npe) {
248             throw new JSExn("you cannot sleep or yield in the foreground thread");
249         }
250     }
251     
252     public static final JS ibexMath = new JS.Immutable() {
253             // FEATURE: find a cleaner way to do this
254             private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
255             public JS get(JS key) throws JSExn {
256                 //#switch(JSU.toString(key))
257                 case "isNaN": return METHOD;
258                 case "isFinite": return METHOD;
259                 case "NaN": return METHOD;
260                 case "Infinity": return METHOD;
261                 //#end
262                 return JSU.MATH.get(key);
263             }
264             public JS call(JS method, JS[] args) throws JSExn {
265                 //#switch(JSU.toString(method))
266                 case "isNaN": return gs.call(method, args);
267                 case "isFinite": return gs.call(method, args);
268                 case "NaN": return gs.call(method, args);
269                 case "Infinity": return gs.call(method, args);
270                 //#end
271                 return JSU.MATH.call(method, args);
272             }
273     };
274
275     public static final JS ibexString = new JS.Obj() {
276             private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
277             public JS get(JS key) throws JSExn {
278                 //#switch(JSU.toString(key))
279                 case "parseInt": return METHOD;
280                 case "parseFloat": return METHOD;
281                 case "decodeURI": return METHOD;
282                 case "decodeURIComponent": return METHOD;
283                 case "encodeURI": return METHOD;
284                 case "encodeURIComponent": return METHOD;
285                 case "escape": return METHOD;
286                 case "unescape": return METHOD;
287                 case "fromCharCode": return METHOD;
288                 //#end
289                 return super.get(key);
290             }
291             public JS callMethod(JS method, JS[] args) throws JSExn {
292                 //#switch(JSU.toString(method))
293                 case "parseInt": return gs.call(method, args);
294                 case "parseFloat": return gs.call(method, args);
295                 case "decodeURI": return gs.call(method, args);
296                 case "decodeURIComponent": return gs.call(method, args);
297                 case "encodeURI": return gs.call(method, args);
298                 case "encodeURIComponent": return gs.call(method, args);
299                 case "escape": return gs.call(method, args);
300                 case "unescape": return gs.call(method, args);
301                 case "fromCharCode": return gs.call(method, args);
302                 //#end
303                 return super.call(method, args);
304             }
305     };
306
307     private class XMLHelper extends XML {
308         private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
309         private JS characters, whitespace, endElement, startElement;
310         public XMLHelper(JS b) throws JSExn {
311             super(BUFFER_SIZE, true);
312             startElement = b.getAndTriggerTraps(JSU.S("startElement"));
313             endElement   = b.getAndTriggerTraps(JSU.S("endElement"));
314             characters   = b.getAndTriggerTraps(JSU.S("characters"));
315             whitespace   = b.getAndTriggerTraps(JSU.S("whitespace"));
316         }
317
318         private final JS[] callargs1= new JS[1], callargs2= new JS[2], callargs3= new JS[3];
319         public void startElement(Tree.Element c) throws XML.Exn { try {
320                 Tree.Attributes a = c.getAttributes();
321                 JS attrs = new JS.Obj();
322                 // FIXME attribute URIs? add an additional hash?
323                 for(int i=0; i<a.attrSize(); i++) attrs.put(JSU.S(a.getKey(i)), JSU.S(a.getVal(i)));
324                 callargs3[0] = JSU.S(c.getLocalName());
325                 callargs3[1] = attrs;
326                 callargs3[2] = JSU.S(c.getUri());
327                 startElement.call(callargs3);
328         } catch (JSExn jse) { throw new Wrapper(jse);
329         } finally { callargs3[0] = callargs3[1] = callargs3[2] = null; } }
330
331         public void endElement(Tree.Element c) throws XML.Exn { try {
332                 callargs2[0] = JSU.S(c.getLocalName());
333                 callargs2[1] = JSU.S(c.getUri());
334                 endElement.call(callargs2);
335         } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs2[0] = callargs2[1] = null; } }
336
337         public void characters(char[] ch, int start, int length) throws XML.Exn { try {
338                 callargs1[0] = JSU.S(new String(ch, start, length));
339                 characters.call(callargs1);
340         } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
341
342         public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
343                 callargs1[0] = JSU.S(new String(ch, start, length));
344                 whitespace.call(callargs1);
345         } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
346
347         public void doParse(JS s) throws JSExn {
348             try { 
349                 parse(new BufferedReader(new InputStreamReader(s.getInputStream())));
350             } catch (Wrapper e) {
351                 throw e.wrapee;
352             } catch (XML.Exn e) {
353                 throw new JSExn("error parsing XML: " + e.toString());
354             } catch (IOException e) {
355                 if (Log.on) Log.info(this, "IO Exception while reading from file");
356                 if (Log.on) Log.info(this, e);
357                 throw new JSExn("error reading from Resource");
358             }
359         }
360     }
361
362     // FEATURE: move this into builtin.xwar
363     public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
364     // JS:FIXME: This doesn't properly handle traps
365     public static class Blessing extends JS.Obj {
366         private Ibex ibex;
367         private Template t = null;
368         public JS parentkey = null;
369         public Blessing parent = null;
370         public JS clonee;
371         private Basket.Map cache = new Basket.HashMap(); 
372         public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
373             this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
374         public JS get(JS key) throws JSExn {
375             if (JSU.isString(key) && JSU.toString(key).equals("")) return getStatic();
376             if (cache.get(key) != null) return (JS)cache.get(key);
377             JS ret = new Blessing(clonee.get(key), ibex, this, key);
378             cache.put(key, ret);
379             return ret;
380         }
381         public static Blessing getBlessing(JS js) {
382             // CHECKME: is unclone() good enough or do we need getClonee() in Cloneable?
383             while (js instanceof JS.Clone && !(js instanceof Blessing)) js = js.unclone();
384             if (!(js instanceof Blessing)) return null;
385             return (Blessing)js;
386         }
387         // FEATURE: This is a gross hack
388         public InputStream getImage() throws JSExn {
389             try {
390                 InputStream in = getInputStream();
391                 if (in != null) return in;
392             } catch (IOException e) { /* DELIBERATE */ }
393             String[] exts = new String[] { ".png", ".jpeg", ".gif" };
394             for (int i=0; i < exts.length; i++)
395                 try {
396                     InputStream in = parent.get(JSU.S(JSU.toString(parentkey) + exts[i])).getInputStream();
397                     if (in != null) return in;
398                 } catch (IOException f) { /* DELIBERATE */ }
399             return null;
400         }
401         public JS getStatic() throws JSExn {
402             try {
403                 if (t == null) {
404                     // FEATURE: Might want to handle the ".t" part better
405                     JS res = parent.get(JSU.S(JSU.toString(parentkey) + ".t"));
406                     t = Template.buildTemplate(description(), res, ibex);
407                 }
408                 return t != null ? t.staticObject : null;
409             } catch (Exception e) {
410                 Log.error(this, e);
411                 return null;
412             }
413         }
414         private String description() {
415             String s = JSU.str(parentkey);
416             for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JSU.str(b.parentkey) + "." + s;
417             return s;
418         }
419         public JS call(JS[] args) throws JSExn {
420             if (args.length != 1) throw new JSExn("can only call a template with one arg");
421             getStatic();
422             if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));
423             if(!(args[0] instanceof Box)) throw new JSExn("can only apply templates to boxes");
424             t.apply((Box)args[0]);
425             return args[0];
426         }
427         // FEATURE: This is a gross hack
428         Template getTemplate()  throws JSExn {
429             getStatic();
430             if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));
431             return t;
432         }
433         // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
434         public InputStream getInputStream() throws JSExn, IOException { return clonee.getInputStream(); }
435     }
436
437 }