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