1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
6 import org.ibex.util.*;
7 import org.ibex.graphics.*;
8 import org.ibex.plat.*;
10 import org.ibex.crypto.*;
12 /** Singleton class that provides all functionality in the ibex.* namespace */
13 public final class Ibex extends JS implements JS.Cloneable {
18 public Ibex(Stream rr) { try { this.rr = bless(rr);} catch(JSExn e) { throw new Error("should never happen: " + e); } }
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");
26 //JS ret = (JS)getAndTriggerTraps("");
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));
34 if (!"".equals(str)) ret = ret.get(JS.S(str));
38 /** lets us put multi-level get/put/call keys all in the same method */
39 private class Sub extends JS {
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);
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);
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));
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 //#switch(JS.toString(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);
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;
131 public void put(JS name, JS value) throws JSExn {
132 //#switch(JS.toString(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();
142 throw new JSExn("attempted to put unknown property: ibex."+name);
145 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
147 //#switch(JS.toString(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;
159 //#switch(JS.toString(name))
160 case "thread.yield": sleep(0); return null;
164 //#switch(JS.toString(name))
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((Stream)a);
171 //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
173 try { return a == null ? null : new Stream.CachedStream((Stream)a, "resources", true); }
174 catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
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:")) {
183 Platform.fileDialog(url.substring(5), false);
185 throw new JSExn("invalid resource specifier " + url);
187 case "thread.sleep": sleep(JS.toInt(a)); return null;
188 case "regexp": return new JSRegexp(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); }
203 //#switch(JS.toString(name))
204 case "stream.watch": return new Stream.ProgressWatcher((Stream)a, b);
205 case "regexp": return new JSRegexp(a, b);
208 //#switch(JS.toString(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)));
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+"()");
221 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
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
233 public static void sleep(final int i) throws JSExn {
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);
241 } catch (JS.NotPauseableException npe) {
242 throw new JSExn("you cannot sleep or yield in the foreground thread");
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 //#switch(JS.toString(key))
251 case "isNaN": return METHOD;
252 case "isFinite": return METHOD;
253 case "NaN": return METHOD;
254 case "Infinity": return METHOD;
256 return MATH.get(key);
258 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
259 //#switch(JS.toString(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);
265 return MATH.callMethod(name,a,b,c,rest,nargs);
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 //#switch(JS.toString(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;
283 return super.get(key);
285 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
286 //#switch(JS.toString(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);
297 return super.callMethod(name,a,b,c,rest,nargs);
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 {
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"));
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); } }
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); } }
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); } }
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); } }
331 public void doParse(JS s) throws JSExn {
333 parse(new BufferedReader(new InputStreamReader(s.getInputStream())));
334 } catch (Wrapper e) {
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");
346 // FEATURE: move this into builtin.xwar
347 public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
348 // JS:FIXME: This doesn't properly handle traps
349 public static class Blessing extends JS.O {
351 private Template t = null;
352 public JS parentkey = null;
353 public Blessing parent = null;
355 private Hash cache = new Hash();
356 public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
357 this.clonee = 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);
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;
370 // FEATURE: This is a gross hack
371 public InputStream getImage() throws JSExn {
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++)
379 InputStream in = parent.get(JS.S(JS.toString(parentkey) + exts[i])).getInputStream();
380 if (in != null) return in;
381 } catch (IOException f) { /* DELIBERATE */ }
384 public JS getStatic() throws JSExn {
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);
391 return t != null ? t.staticObject : null;
392 } catch (Exception e) {
397 private String description() {
398 String s = JS.debugToString(parentkey);
399 for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JS.debugToString(b.parentkey) + "." + s;
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");
405 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
406 if(!(a instanceof Box)) throw new JSExn("can only apply templates to boxes");
410 // FEATURE: This is a gross hack
411 Template getTemplate() throws JSExn {
413 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
416 // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
417 public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }