1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
9 import org.ibex.util.*;
10 import org.ibex.graphics.*;
11 import org.ibex.plat.*;
12 import org.ibex.net.*;
13 import org.ibex.crypto.*;
15 /** Singleton class that provides all functionality in the ibex.* namespace */
16 public final class Ibex extends JS.Obj implements JS.Cloneable {
20 private static final JS.Method METHOD = new JS.Method();
22 public Ibex(Stream rr) { try { this.rr = bless(rr);} catch(JSExn e) { throw new Error("should never happen: " + e); } }
24 public JS resolveString(String str, boolean permitAbsolute) throws JSExn {
25 if (str.indexOf("://") != -1) {
26 if (permitAbsolute) return url2res(str);
27 throw new JSExn("absolute URL " + str + " not permitted here");
30 //JS ret = (JS)getAndTriggerTraps("");
33 while(str.indexOf('.') != -1) {
34 String path = str.substring(0, str.indexOf('.'));
35 str = str.substring(str.indexOf('.') + 1);
36 ret = ret.get(JSU.S(path));
38 if (!"".equals(str)) ret = ret.get(JSU.S(str));
42 /** lets us put multi-level get/put/call keys all in the same method */
43 private class Sub extends JS.Obj {
45 Sub(JS key) { this.key = key; }
46 public void put(JS key, JS val) throws JSExn { Ibex.this.put(JSU.S(JSU.toString(this.key) + "." + JSU.toString(key)), val); }
47 public JS get(JS key) throws JSExn { return Ibex.this.get(JSU.S(JSU.toString(this.key) + "." + JSU.toString(key))); }
48 public JS call(JS method, JS[] args) throws JSExn {
49 if (method == null) return super.call(null, args);
50 return Ibex.this.call(JSU.S(JSU.toString(this.key) + "." + JSU.toString(method)), args);
53 private Cache subCache = new Cache(20, true);
54 private Sub getSub(JS key) {
55 Sub ret = (Sub)subCache.get(key);
56 if (ret == null) subCache.put(key, ret = new Sub(key));
60 public JS get(JS name) throws JSExn {
61 // FIXME: SHouldn't need this (just trap [""])
62 if (JSU.isString(name) && JSU.toString(name).length() == 0) return rr;
63 // FEATURE: Preprocessor hack to generate specialized JS instances (avoid all this string concatenation)
64 //#switch(JSU.toString(name))
65 case "math": return ibexMath;
66 case "string": return ibexString;
67 case "date": return METHOD;
68 case "box": return new Box();
69 case "clone": return METHOD;
70 case "bless": return METHOD;
71 case "regexp": return METHOD;
72 case "ui": return getSub(name);
73 case "ui.font": return getSub(name);
74 case "ui.font.wait": return METHOD;
75 case "ui.font.width": return METHOD;
76 case "ui.font.height": return METHOD;
77 case "ui.font.sansserif": return Main.builtin.get(JSU.S("fonts/vera/Vera.ttf"));
78 case "ui.font.monospace": return Main.builtin.get(JSU.S("fonts/vera/VeraMono.ttf"));
79 case "ui.font.serif": return Main.builtin.get(JSU.S("fonts/vera/VeraSe.ttf"));
80 case "ui.browser": return METHOD;
81 case "ui.mouse": return getSub(name);
82 case "ui.mouse.button":
83 if (Surface.button1 && !Surface.button2 && !Surface.button3) return JSU.N(1);
84 else if (!Surface.button1 && Surface.button2 && !Surface.button3) return JSU.N(2);
85 else if (!Surface.button1 && !Surface.button2 && Surface.button3) return JSU.N(3);
87 case "ui.key": return getSub(name);
88 case "ui.key.name": return getSub(name);
89 case "ui.key.name.alt": return JSU.S(Platform.altKeyName());
90 case "ui.key.alt": return Surface.alt ? JSU.T : JSU.F;
91 case "ui.key.control": return Surface.control ? JSU.T : JSU.F;
92 case "ui.key.shift": return Surface.shift ? JSU.T : JSU.F;
93 case "ui.clipboard": return JSU.S((String)Platform.getClipBoard());
94 case "ui.maxdim": return JSU.N(Short.MAX_VALUE);
95 case "ui.screen": return getSub(name);
96 case "ui.screen.width": return JSU.N(Platform.getScreenWidth());
97 case "ui.screen.height": return JSU.N(Platform.getScreenHeight());
98 case "undocumented": return getSub(name);
99 case "undocumented.initialOrigin": return JSU.S(Main.origin);
100 case "undocumented.initialTemplate": return JSU.S(Main.initialTemplate);
101 case "thread": return getSub(name);
102 case "thread.yield": return METHOD;
103 case "thread.sleep": return METHOD;
104 case "stream": return getSub(name);
105 case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
106 case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
107 case "stream.watch": return METHOD;
108 case "stream.unzip": return METHOD;
109 case "stream.uncab": return METHOD;
110 case "stream.cache": return METHOD;
111 case "stream.url": return METHOD;
112 case "stream.parse.html": return METHOD;
113 case "stream.parse.xml": return METHOD;
114 case "stream.parse.utf8": return METHOD;
115 case "net": return getSub(name);
116 case "net.rpc": return getSub(name);
117 case "net.rpc.xml": return METHOD;
118 case "net.rpc.soap": return METHOD;
119 case "log": return getSub(name);
120 case "log.debug": return METHOD;
121 case "log.info": return METHOD;
122 case "log.warn": return METHOD;
123 case "log.error": return METHOD;
124 case "crypto": return getSub(name);
125 case "crypto.rsa": return METHOD;
126 case "crypto.md5": return METHOD;
127 case "crypto.sha1": return METHOD;
128 case "crypto.rc4": return METHOD;
133 public void put(JS name, JS value) throws JSExn {
134 //#switch(JSU.toString(name))
135 case "thread": Scheduler.add((Callable)value); return;
136 case "ui.clipboard": Platform.setClipBoard(JSU.toString(value)); return;
137 case "ui.frame": Platform.createSurface((Box)value, true, true); return;
138 case "ui.window": Platform.createSurface((Box)value, false, true); return;
139 case "undocumented.proxyAuthorization":
140 HTTP.Proxy.Authorization.authorization = value.toString();
141 HTTP.Proxy.Authorization.waitingForUser.release();
144 throw new JSExn("attempted to put unknown property: ibex."+name);
147 public JS call(JS method, JS[] args) throws JSExn {
149 //#switch(JSU.toString(method))
150 case "date": return new JSDate(args);
151 case "net.rpc.soap": return new SOAP(
152 args.length < 1 ? null : JSU.toString(args[0]),
154 args.length < 2 ? null : JSU.toString(args[1]),
155 args.length < 3 ? null : JSU.toString(args[2]));
156 // FIXME support object dumping
157 case "log.debug": JSU.debug(args.length < 1 ? "**null**" : JSU.str(args[0])); return null;
158 case "log.info": JSU.info(args.length < 1 ? "**null**" : JSU.str(args[0])); return null;
159 case "log.warn": JSU.warn(args.length < 1 ? "**null**" : JSU.str(args[0])); return null;
160 case "log.error": JSU.error(args.length < 1 ? "**null**" : JSU.str(args[0])); return null;
163 switch (args.length) {
165 //#switch(JSU.toString(method))
166 case "thread.yield": sleep(0); return null;
170 //#switch(JSU.toString(method))
172 if(args[0] == null) throw new JSExn("can't clone the null value");
173 return new JS.Clone((JS)args[0]);
174 case "bless": return bless((JS)args[0]);
175 case "ui.browser": Platform.newBrowserWindow(JSU.toString(args[0])); return null;
176 case "stream.unzip": return args[0] == null ? null : new Stream.Zip((Stream)args[0]);
177 //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
179 try { return args[0] == null ? null : new Stream.CachedStream((Stream)args[0], "resources", true); }
180 catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
182 String url = JSU.toString(args[0]);
183 if (url.startsWith("http://")) return new Stream.HTTP(url);
184 else if (url.startsWith("https://")) return new Stream.HTTP(url);
185 else if (url.startsWith("data:")) return new Stream.ByteArray(Encode.fromBase64(url.substring(5)), null);
186 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
187 else if (url.startsWith("file:")) {
189 Platform.fileDialog(url.substring(5), false);
191 throw new JSExn("invalid resource specifier " + url);
193 case "thread.sleep": sleep(JSU.toInt(args[0])); return null;
194 case "regexp": return new JSRegexp(args[0], null);
195 case "net.rpc.xml": return new XMLRPC(JSU.toString(args[0]), "");
196 case "crypto.rsa": /* FEATURE */ return null;
197 case "crypto.md5": /* FEATURE */ return null;
198 case "crypto.sha1": /* FEATURE */ return null;
199 case "crypto.rc4": /* FEATURE */ return null;
200 case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
201 case "stream.parse.xml": if(args[0] == null) return null; new XMLHelper(args[1]).doParse(args[0]); return null;
202 // FIXME backgrounding
203 case "stream.parse.utf8": if(args[0] == null) return null;
204 try { return JSU.S(new String(InputStreamToByteArray.convert(JSU.getInputStream(args[0])))); }
205 catch (Exception e) { Log.warn(this, e); }
209 //#switch(JSU.toString(method))
210 case "stream.watch": return new Stream.ProgressWatcher((Stream)args[0], args[1]);
211 case "regexp": return new JSRegexp(args[0], args[1]);
214 //#switch(JSU.toString(method))
215 case "ui.font.height": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textheight(JSU.toString(args[3])));
216 case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
217 case "ui.font.width": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textwidth(JSU.toString(args[3])));
221 } catch (RuntimeException e) {
222 // FIXME: maybe JSExn should take a second argument, Exception
223 Log.warn(this, "ibex."+method+"() threw: " + e);
224 throw new JSExn("invalid argument for ibex object method "+method+"()");
227 throw new JSExn("invalid number of arguments ("+args.length+") for ibex object method "+method+"()");
230 public JS url2res(String url) throws JSExn {
231 if (url.startsWith("http://")) return new Stream.HTTP(url);
232 else if (url.startsWith("https://")) return new Stream.HTTP(url);
233 else if (url.startsWith("data:")) return new Stream.ByteArray(Encode.fromBase64(url.substring(5)), null);
234 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
235 else throw new JSExn("invalid resource specifier " + url);
236 // FIXME support file:// via dialog boxes
239 public static void sleep(final int i) throws JSExn {
241 final Pausable callback = JSU.pause();
242 // FEATURE use a single sleeper thread
243 new Thread() { public void run() {
244 try { Thread.sleep(i); } catch (InterruptedException e) { }
245 Scheduler.add(callback);
247 } catch (Pausable.NotPausableException npe) {
248 throw new JSExn("you cannot sleep or yield in the foreground thread");
252 public static final JS ibexMath = new JS.Immutable() {
253 // FEATURE: find a cleaner way to do this
254 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
255 public JS get(JS key) throws JSExn {
256 //#switch(JSU.toString(key))
257 case "isNaN": return METHOD;
258 case "isFinite": return METHOD;
259 case "NaN": return METHOD;
260 case "Infinity": return METHOD;
262 return JSU.MATH.get(key);
264 public JS call(JS method, JS[] args) throws JSExn {
265 //#switch(JSU.toString(method))
266 case "isNaN": return gs.call(method, args);
267 case "isFinite": return gs.call(method, args);
268 case "NaN": return gs.call(method, args);
269 case "Infinity": return gs.call(method, args);
271 return JSU.MATH.call(method, args);
275 public static final JS ibexString = new JS.Obj() {
276 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
277 public JS get(JS key) throws JSExn {
278 //#switch(JSU.toString(key))
279 case "parseInt": return METHOD;
280 case "parseFloat": return METHOD;
281 case "decodeURI": return METHOD;
282 case "decodeURIComponent": return METHOD;
283 case "encodeURI": return METHOD;
284 case "encodeURIComponent": return METHOD;
285 case "escape": return METHOD;
286 case "unescape": return METHOD;
287 case "fromCharCode": return METHOD;
289 return super.get(key);
291 public JS callMethod(JS method, JS[] args) throws JSExn {
292 //#switch(JSU.toString(method))
293 case "parseInt": return gs.call(method, args);
294 case "parseFloat": return gs.call(method, args);
295 case "decodeURI": return gs.call(method, args);
296 case "decodeURIComponent": return gs.call(method, args);
297 case "encodeURI": return gs.call(method, args);
298 case "encodeURIComponent": return gs.call(method, args);
299 case "escape": return gs.call(method, args);
300 case "unescape": return gs.call(method, args);
301 case "fromCharCode": return gs.call(method, args);
303 return super.call(method, args);
307 private class XMLHelper extends XML {
308 private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
309 private JS characters, whitespace, endElement, startElement;
310 public XMLHelper(JS b) throws JSExn {
311 super(BUFFER_SIZE, true);
312 startElement = b.getAndTriggerTraps(JSU.S("startElement"));
313 endElement = b.getAndTriggerTraps(JSU.S("endElement"));
314 characters = b.getAndTriggerTraps(JSU.S("characters"));
315 whitespace = b.getAndTriggerTraps(JSU.S("whitespace"));
318 private final JS[] callargs1= new JS[1], callargs2= new JS[2], callargs3= new JS[3];
319 public void startElement(Tree.Element c) throws XML.Exn { try {
320 Tree.Attributes a = c.getAttributes();
321 JS attrs = new JS.Obj();
322 // FIXME attribute URIs? add an additional hash?
323 for(int i=0; i<a.attrSize(); i++) attrs.put(JSU.S(a.getKey(i)), JSU.S(a.getVal(i)));
324 callargs3[0] = JSU.S(c.getLocalName());
325 callargs3[1] = attrs;
326 callargs3[2] = JSU.S(c.getUri());
327 startElement.call(null, callargs3);
328 } catch (JSExn jse) { throw new Wrapper(jse);
329 } finally { callargs3[0] = callargs3[1] = callargs3[2] = null; } }
331 public void endElement(Tree.Element c) throws XML.Exn { try {
332 callargs2[0] = JSU.S(c.getLocalName());
333 callargs2[1] = JSU.S(c.getUri());
334 endElement.call(null, callargs2);
335 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs2[0] = callargs2[1] = null; } }
337 public void characters(char[] ch, int start, int length) throws XML.Exn { try {
338 callargs1[0] = JSU.S(new String(ch, start, length));
339 characters.call(null, callargs1);
340 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
342 public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
343 callargs1[0] = JSU.S(new String(ch, start, length));
344 whitespace.call(null, callargs1);
345 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
347 public void doParse(JS s) throws JSExn {
349 parse(new BufferedReader(new InputStreamReader(JSU.getInputStream(s))));
350 } catch (Wrapper e) {
352 } catch (XML.Exn e) {
353 throw new JSExn("error parsing XML: " + e.toString());
354 } catch (IOException e) {
355 if (Log.on) Log.info(this, "IO Exception while reading from file");
356 if (Log.on) Log.info(this, e);
357 throw new JSExn("error reading from Resource");
362 // FEATURE: move this into builtin.xwar
363 public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
364 // JS:FIXME: This doesn't properly handle traps
365 public static class Blessing extends JS.Obj {
367 private Template t = null;
368 public JS parentkey = null;
369 public Blessing parent = null;
371 private Basket.Map cache = new Basket.HashMap();
372 public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
373 this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
374 public JS get(JS key) throws JSExn {
375 if (JSU.isString(key) && JSU.toString(key).equals("")) return getStatic();
376 if (cache.get(key) != null) return (JS)cache.get(key);
377 JS ret = new Blessing(clonee.get(key), ibex, this, key);
381 public static Blessing getBlessing(JS js) {
382 // CHECKME: is unclone() good enough or do we need getClonee() in Cloneable?
383 while (js instanceof JS.Clone && !(js instanceof Blessing)) js = js.unclone();
384 if (!(js instanceof Blessing)) return null;
387 // FEATURE: This is a gross hack
388 public InputStream getImage() throws JSExn {
390 InputStream in = JSU.getInputStream(this);
391 if (in != null) return in;
392 //} catch (IOException e) { /* DELIBERATE */ }
393 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
394 for (int i=0; i < exts.length; i++) {
396 in = JSU.getInputStream(parent.get(JSU.S(JSU.toString(parentkey) + exts[i])));
397 if (in != null) return in;
398 //} catch (IOException f) { /* DELIBERATE */ }
402 public JS getStatic() throws JSExn {
405 // FEATURE: Might want to handle the ".t" part better
406 JS res = parent.get(JSU.S(JSU.toString(parentkey) + ".t"));
407 t = Template.buildTemplate(description(), res, ibex);
409 return t != null ? t.staticObject : null;
410 } catch (Exception e) {
415 private String description() {
416 String s = JSU.str(parentkey);
417 for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JSU.str(b.parentkey) + "." + s;
420 public JS call(JS method, JS[] args) throws JSExn {
421 if (method != null) return super.call(method, args);
422 if (args.length != 1) throw new JSExn("can only call a template with one arg");
424 if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));
425 if(!(args[0] instanceof Box)) throw new JSExn("can only apply templates to boxes");
426 t.apply((Box)args[0]);
429 // FEATURE: This is a gross hack
430 Template getTemplate() throws JSExn {
432 if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));
435 // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
436 //public InputStream getInputStream() throws JSExn, IOException { return clonee.getInputStream(); }