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