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