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