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 if (!"".equals(str)) 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.wait": return METHOD;
68 case "ui.font.width": return METHOD;
69 case "ui.font.height": return METHOD;
70 case "ui.font.sansserif": return Main.builtin.get("fonts/vera/Vera.ttf");
71 case "ui.font.monospace": return Main.builtin.get("fonts/vera/VeraMono.ttf");
72 case "ui.font.serif": return Main.builtin.get("fonts/vera/VeraSe.ttf");
73 case "ui.browser": return METHOD;
74 case "ui.mouse": return getSub("ui.mouse");
75 case "ui.mouse.button":
76 if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
77 else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
78 else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
80 case "ui.key": return getSub("ui.key");
81 case "ui.key.name": return getSub("ui.key.name");
82 case "ui.key.name.alt": return Platform.altKeyName();
83 case "ui.key.alt": return Surface.alt ? T : F;
84 case "ui.key.control": return Surface.control ? T : F;
85 case "ui.key.shift": return Surface.shift ? T : F;
86 case "ui.clipboard": return Platform.getClipBoard();
87 case "ui.maxdim": return N(Short.MAX_VALUE);
88 case "ui.screen": return getSub("ui.screen");
89 case "ui.screen.width": return N(Platform.getScreenWidth());
90 case "ui.screen.height": return N(Platform.getScreenHeight());
91 case "undocumented": return getSub("undocumented");
92 case "undocumented.initialOrigin": return Main.origin;
93 case "undocumented.initialTemplate": return Main.initialTemplate;
94 case "thread": return getSub("thread");
95 case "thread.yield": return METHOD;
96 case "thread.sleep": return METHOD;
97 case "stream": return getSub("stream");
98 case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
99 case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
100 case "stream.watch": return METHOD;
101 case "stream.unzip": return METHOD;
102 case "stream.uncab": return METHOD;
103 case "stream.cache": return METHOD;
104 case "stream.url": return METHOD;
105 case "stream.parse.html": return METHOD;
106 case "stream.parse.xml": return METHOD;
107 case "stream.parse.utf8": return METHOD;
108 case "net": return getSub("net");
109 case "net.rpc": return getSub("net.rpc");
110 case "net.rpc.xml": return METHOD;
111 case "net.rpc.soap": return METHOD;
112 case "log": return getSub("log");
113 case "log.debug": return METHOD;
114 case "log.info": return METHOD;
115 case "log.warn": return METHOD;
116 case "log.error": return METHOD;
117 case "crypto": return getSub("crypto");
118 case "crypto.rsa": return METHOD;
119 case "crypto.md5": return METHOD;
120 case "crypto.sha1": return METHOD;
121 case "crypto.rc4": return METHOD;
123 return super.get(name);
126 public void put(Object name, final Object value) throws JSExn {
128 case "thread": Scheduler.add((Scheduler.Task)value); return;
129 case "ui.clipboard": Platform.setClipBoard((String)value); return;
130 case "ui.frame": Platform.createSurface((Box)value, true, true); return;
131 case "ui.window": Platform.createSurface((Box)value, false, true); return;
132 case "undocumented.proxyAuthorization":
133 HTTP.Proxy.Authorization.authorization = value.toString();
134 HTTP.Proxy.Authorization.waitingForUser.release();
137 throw new JSExn("attempted to put unknown property: ibex."+name);
140 public Object callMethod(Object name, Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
143 case "date": return new JSDate(a, b, c, rest, nargs);
144 case "net.rpc.soap": return new SOAP((String)a, "", (String)b, (String)c);
145 // FIXME support object dumping
146 case "log.debug": JS.debug(a== null ? "**null**" : a.toString()); return null;
147 case "log.info": JS.info(a== null ? "**null**" : a.toString()); return null;
148 case "log.warn": JS.warn(a== null ? "**null**" : a.toString()); return null;
149 case "log.error": JS.error(a== null ? "**null**" : a.toString()); return null;
155 case "thread.yield": sleep(0); return null;
161 if (!(a instanceof JS.Cloneable)) throw new JSExn("cannot clone a " + a.getClass().getName());
162 return ((JS.Cloneable)a).jsclone();
163 case "bless": return bless((JS)a);
164 case "ui.browser": Platform.newBrowserWindow((String)a); return null;
165 case "stream.unzip": return new Stream.Zip((Stream)a);
166 case "stream.uncab": return new Stream.Cab((Stream)a);
168 try { return new Stream.CachedStream((Stream)a, "resources", true); }
169 catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
171 String url = (String)a;
172 if (url.startsWith("http://")) return new Stream.HTTP(url);
173 else if (url.startsWith("https://")) return new Stream.HTTP(url);
174 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
175 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
176 else if (url.startsWith("file:")) {
178 Platform.fileDialog(url.substring(5), false);
180 throw new JSExn("invalid resource specifier " + url);
182 case "thread.sleep": sleep(JS.toInt(a)); return null;
183 case "regexp": return new JSRegexp(a, null);
184 case "net.rpc.xml": return new XMLRPC((String)a, "");
185 case "crypto.rsa": /* FEATURE */ return null;
186 case "crypto.md5": /* FEATURE */ return null;
187 case "crypto.sha1": /* FEATURE */ return null;
188 case "crypto.rc4": /* FEATURE */ return null;
189 case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
190 case "stream.parse.xml": new XMLHelper((JS)b).doParse((JS)a); return null;
191 // FIXME backgrounding
192 case "stream.parse.utf8": try { return new String(InputStreamToByteArray.convert(Stream.getInputStream(a))); }
193 catch (Exception e) { Log.warn(this, e); }
198 case "stream.watch": return new Stream.ProgressWatcher((Stream)a, (JS)b);
199 case "regexp": return new JSRegexp(a, b);
203 case "ui.font.height": return N(Font.getFont((Stream)a, JS.toInt(b)).textheight((String)c));
206 JS.UnpauseCallback callback = JS.pause();
207 Font font = Font.getFont((Stream)a, JS.toInt(b));
208 if (font.rasterizeGlyphs((String)c, null, 0,0,0,0,0,0,0, callback) != -1) Scheduler.add(callback);
209 } catch (JS.NotPauseableException npe) {
210 JS.error("can't wait for a font in a foreground thread");
213 case "ui.font.width": return N(Font.getFont((Stream)a, JS.toInt(b)).textwidth((String)c));
217 } catch (RuntimeException e) {
218 // FIXME: maybe JSExn should take a second argument, Exception
219 Log.warn(this, "ibex."+name+"() threw: " + e);
220 throw new JSExn("invalid argument for ibex object method "+name+"()");
223 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
226 public Stream url2res(String url) throws JSExn {
227 if (url.startsWith("http://")) return new Stream.HTTP(url);
228 else if (url.startsWith("https://")) return new Stream.HTTP(url);
229 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
230 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
231 else throw new JSExn("invalid resource specifier " + url);
232 // FIXME support file:// via dialog boxes
235 public static void sleep(final int i) throws JSExn {
237 final JS.UnpauseCallback callback = JS.pause();
238 // FEATURE use a single sleeper thread
239 new Thread() { public void run() {
240 try { Thread.sleep(i); } catch (InterruptedException e) { }
241 Scheduler.add(callback);
243 } catch (JS.NotPauseableException npe) {
244 throw new JSExn("you cannot sleep or yield in the foreground thread");
248 public static final JSMath ibexMath = new JSMath() {
249 private JS gs = new JSScope.Global();
250 public Object get(Object key) throws JSExn {
252 case "isNaN": return gs.get("isNaN");
253 case "isFinite": return gs.get("isFinite");
254 case "NaN": return gs.get("NaN");
255 case "Infinity": return gs.get("Infinity");
257 return super.get(key);
261 public static final JS ibexString = new JS() {
262 private JS gs = new JSScope.Global();
263 public void put(Object key, Object val) { }
264 public Object get(Object key) throws JSExn {
266 case "parseInt": return gs.get("parseInt");
267 case "parseFloat": return gs.get("parseFloat");
268 case "decodeURI": return gs.get("decodeURI");
269 case "decodeURIComponent": return gs.get("decodeURIComponent");
270 case "encodeURI": return gs.get("encodeURI");
271 case "encodeURIComponent": return gs.get("encodeURIComponent");
272 case "escape": return gs.get("escape");
273 case "unescape": return gs.get("unescape");
274 case "fromCharCode": return gs.get("stringFromCharCode");
280 private class XMLHelper extends XML {
281 private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
282 private JS characters, whitespace, endElement, startElement;
283 public XMLHelper(JS b) throws JSExn {
285 startElement = (JS)b.getAndTriggerTraps("startElement");
286 endElement = (JS)b.getAndTriggerTraps("endElement");
287 characters = (JS)b.getAndTriggerTraps("characters");
288 whitespace = (JS)b.getAndTriggerTraps("whitespace");
291 public void startElement(XML.Element c) throws XML.Exn { try {
293 // FIXME attribute URIs? add an additional hash?
294 for(int i=0; i<c.getAttrLen(); i++) attrs.put(c.getAttrKey(i), c.getAttrVal(i));
295 startElement.call(c.getLocalName(), attrs, c.getUri(), null, 3);
296 } catch (JSExn jse) { throw new Wrapper(jse); } }
298 public void endElement(XML.Element c) throws XML.Exn { try {
299 endElement.call(c.getLocalName(), c.getUri(), null, null, 2);
300 } catch (JSExn jse) { throw new Wrapper(jse); } }
302 public void characters(char[] ch, int start, int length) throws XML.Exn { try {
303 characters.call(new String(ch, start, length), null, null, null, 1);
304 } catch (JSExn jse) { throw new Wrapper(jse); } }
306 public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
307 whitespace.call(new String(ch, start, length), null, null, null, 1);
308 } catch (JSExn jse) { throw new Wrapper(jse); } }
310 public void doParse(JS s) throws JSExn {
312 parse(new BufferedReader(new InputStreamReader(Stream.getInputStream(s))));
313 } catch (Wrapper e) {
315 } catch (XML.Exn e) {
316 throw new JSExn("error parsing XML: " + e.toString());
317 } catch (IOException e) {
318 if (Log.on) Log.info(this, "IO Exception while reading from file");
319 if (Log.on) Log.info(this, e);
320 throw new JSExn("error reading from Resource");
325 // FEATURE: move this into builtin.xwar
326 public Blessing bless(JS b) { return new Ibex.Blessing((JS.Cloneable)b, this, null, null); }
327 public static class Blessing extends JS.Clone {
329 private Template t = null;
330 public Object parentkey = null;
331 public Blessing parent = null;
332 public Blessing(JS.Cloneable clonee, Ibex ibex, Blessing parent, Object parentkey) {
333 super(clonee); this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
334 public Object get(Object key) throws JSExn {
335 return key.equals("") ? ((Object)getStatic()) : (new Blessing((JS.Cloneable)clonee.get(key), ibex, this, key));
337 public static Blessing getBlessing(Object o) {
338 if (!(o instanceof JS)) return null;
340 while (js instanceof JS.Clone && !(js instanceof Blessing)) js = ((JS.Clone)js).getClonee();
341 if (!(js instanceof Blessing)) return null;
344 public InputStream getImage() throws JSExn {
346 InputStream in = Stream.getInputStream(this);
347 if (in != null) return in;
348 } catch (IOException e) { /* DELIBERATE */ }
349 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
350 for (int i=0; i < exts.length; i++)
352 InputStream in = Stream.getInputStream(parent.get(parentkey + exts[i]));
353 if (in != null) return in;
354 } catch (IOException f) { /* DELIBERATE */ }
357 public JSScope getStatic() {
360 System.out.println("parentkey.t == " + parentkey + ".t");
362 t = Template.buildTemplate(parentkey + ".t", parent.get(parentkey + ".t"), ibex);
363 return t.staticScope;
364 } catch (Exception e) {
369 public Object call(Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
371 if (nargs != 1 && nargs != 9999) throw new JSExn("FIXME can only call with one arg");
373 if (t == null) throw new JSExn("No such template " + parentkey);
374 if (nargs == 9999) return t;