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(Fountain 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.vera;
78 case "ui.font.monospace": return Main.vera;
79 case "ui.font.serif": return Main.vera;
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": Platform.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 Fountain.Zip((Fountain)args[0]);
177 //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
179 //try { return args[0] == null ? null : new Fountain.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 Fountain.HTTP(url);
184 else if (url.startsWith("https://")) return new Fountain.HTTP(url);
185 else if (url.startsWith("data:")) return new Fountain.ByteArray(Encode.fromBase64(url.substring(5)), null);
186 else if (url.startsWith("utf8:")) return new Fountain.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))
211 final JS func = args[1];
212 return new Fountain.ProgressWatcher((Fountain)args[0],
214 public Object run(Object o) throws Exception {
216 return func.call(null, args);
219 case "regexp": return new JSRegexp(args[0], args[1]);
222 //#switch(JSU.toString(method))
223 case "ui.font.height": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textheight(JSU.toString(args[3])));
224 case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
225 case "ui.font.width": return JSU.N(Font.getFont(args[0], JSU.toInt(args[1])).textwidth(JSU.toString(args[3])));
229 } catch (RuntimeException e) {
230 // FIXME: maybe JSExn should take a second argument, Exception
231 Log.warn(this, "ibex."+method+"() threw: " + e);
232 throw new JSExn("invalid argument for ibex object method "+method+"()");
235 throw new JSExn("invalid number of arguments ("+args.length+") for ibex object method "+method+"()");
238 public JS url2res(String url) throws JSExn {
239 if (url.startsWith("http://")) return new Fountain.HTTP(url);
240 else if (url.startsWith("https://")) return new Fountain.HTTP(url);
241 else if (url.startsWith("data:")) return new Fountain.ByteArray(Encode.fromBase64(url.substring(5)), null);
242 else if (url.startsWith("utf8:")) return new Fountain.ByteArray(url.substring(5).getBytes(), null);
243 else throw new JSExn("invalid resource specifier " + url);
244 // FIXME support file:// via dialog boxes
247 public static void sleep(final int i) throws JSExn {
249 final Pausable callback = JSU.pause();
250 // FEATURE use a single sleeper thread
251 new Thread() { public void run() {
252 try { Thread.sleep(i); } catch (InterruptedException e) { }
253 Platform.Scheduler.add(callback);
255 } catch (Pausable.NotPausableException npe) {
256 throw new JSExn("you cannot sleep or yield in the foreground thread");
260 public static final JS ibexMath = new JS.Immutable() {
261 // FEATURE: find a cleaner way to do this
262 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
263 public JS get(JS key) throws JSExn {
264 //#switch(JSU.toString(key))
265 case "isNaN": return METHOD;
266 case "isFinite": return METHOD;
267 case "NaN": return METHOD;
268 case "Infinity": return METHOD;
270 return JSU.MATH.get(key);
272 public JS call(JS method, JS[] args) throws JSExn {
273 //#switch(JSU.toString(method))
274 case "isNaN": return gs.call(method, args);
275 case "isFinite": return gs.call(method, args);
276 case "NaN": return gs.call(method, args);
277 case "Infinity": return gs.call(method, args);
279 return JSU.MATH.call(method, args);
283 public static final JS ibexString = new JS.Obj() {
284 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
285 public JS get(JS key) throws JSExn {
286 //#switch(JSU.toString(key))
287 case "parseInt": return METHOD;
288 case "parseFloat": return METHOD;
289 case "decodeURI": return METHOD;
290 case "decodeURIComponent": return METHOD;
291 case "encodeURI": return METHOD;
292 case "encodeURIComponent": return METHOD;
293 case "escape": return METHOD;
294 case "unescape": return METHOD;
295 case "fromCharCode": return METHOD;
297 return super.get(key);
299 public JS callMethod(JS method, JS[] args) throws JSExn {
300 //#switch(JSU.toString(method))
301 case "parseInt": return gs.call(method, args);
302 case "parseFloat": return gs.call(method, args);
303 case "decodeURI": return gs.call(method, args);
304 case "decodeURIComponent": return gs.call(method, args);
305 case "encodeURI": return gs.call(method, args);
306 case "encodeURIComponent": return gs.call(method, args);
307 case "escape": return gs.call(method, args);
308 case "unescape": return gs.call(method, args);
309 case "fromCharCode": return gs.call(method, args);
311 return super.call(method, args);
315 private class XMLHelper extends XML {
316 private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
317 private JS characters, whitespace, endElement, startElement;
318 public XMLHelper(JS b) throws JSExn {
319 super(BUFFER_SIZE, true);
320 startElement = b.getAndTriggerTraps(JSU.S("startElement"));
321 endElement = b.getAndTriggerTraps(JSU.S("endElement"));
322 characters = b.getAndTriggerTraps(JSU.S("characters"));
323 whitespace = b.getAndTriggerTraps(JSU.S("whitespace"));
326 private final JS[] callargs1= new JS[1], callargs2= new JS[2], callargs3= new JS[3];
327 public void startElement(Tree.Element c) throws XML.Exn { try {
328 Tree.Attributes a = c.getAttributes();
329 JS attrs = new JS.Obj();
330 // FIXME attribute URIs? add an additional hash?
331 for(int i=0; i<a.attrSize(); i++) attrs.put(JSU.S(a.getKey(i)), JSU.S(a.getVal(i)));
332 callargs3[0] = JSU.S(c.getLocalName());
333 callargs3[1] = attrs;
334 callargs3[2] = JSU.S(c.getUri());
335 startElement.call(null, callargs3);
336 } catch (JSExn jse) { throw new Wrapper(jse);
337 } finally { callargs3[0] = callargs3[1] = callargs3[2] = null; } }
339 public void endElement(Tree.Element c) throws XML.Exn { try {
340 callargs2[0] = JSU.S(c.getLocalName());
341 callargs2[1] = JSU.S(c.getUri());
342 endElement.call(null, callargs2);
343 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs2[0] = callargs2[1] = null; } }
345 public void characters(char[] ch, int start, int length) throws XML.Exn { try {
346 callargs1[0] = JSU.S(new String(ch, start, length));
347 characters.call(null, callargs1);
348 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
350 public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
351 callargs1[0] = JSU.S(new String(ch, start, length));
352 whitespace.call(null, callargs1);
353 } catch (JSExn jse) { throw new Wrapper(jse); } finally { callargs1[0] = null; } }
355 public void doParse(JS s) throws JSExn {
357 parse(new BufferedReader(new InputStreamReader(JSU.getInputStream(s))));
358 } catch (Wrapper e) {
360 } catch (XML.Exn e) {
361 throw new JSExn("error parsing XML: " + e.toString());
362 } catch (IOException e) {
363 if (Log.on) Log.info(this, "IO Exception while reading from file");
364 if (Log.on) Log.info(this, e);
365 throw new JSExn("error reading from Resource");
370 // FEATURE: move this into builtin.xwar
371 public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
372 // JS:FIXME: This doesn't properly handle traps
373 public static class Blessing extends JS.Clone {
375 private Template t = null;
376 public JS parentkey = null;
377 public Blessing parent = null;
379 private Basket.Map cache = new Basket.Hash();
380 public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
381 super(clonee); this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
382 public JS get(JS key) throws JSExn {
383 if (JSU.isString(key) && JSU.toString(key).equals("")) return getStatic();
384 if (cache.get(key) != null) return (JS)cache.get(key);
385 JS ret = new Blessing(super.get(key), ibex, this, key);
389 public static Blessing getBlessing(JS js) {
390 while (js instanceof JS.Clone && !(js instanceof Blessing)) js = js.unclone();
391 if (!(js instanceof Blessing)) return null;
394 // FEATURE: This is a gross hack
395 public InputStream getImage() throws JSExn {
397 InputStream in = JSU.getInputStream(this);
398 if (in != null) return in;
399 } catch (IOException e) { /* DELIBERATE */ }
400 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
401 for (int i=0; i < exts.length; i++) {
403 InputStream in = JSU.getInputStream(parent.get(JSU.S(JSU.toString(parentkey) + exts[i])));
404 if (in != null) return in;
405 } catch (IOException f) { /* DELIBERATE */ }
409 public JS getStatic() throws JSExn {
412 // FEATURE: Might want to handle the ".t" part better
413 JS res = parent.get(JSU.S(JSU.toString(parentkey) + ".t"));
414 t = Template.buildTemplate(description(), res, ibex);
416 return t != null ? t.staticObject : null;
417 } catch (Exception e) {
422 private String description() {
423 String s = JSU.str(parentkey);
424 for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JSU.str(b.parentkey) + "." + s;
427 public JS call(JS method, JS[] args) throws JSExn {
428 if (method != null) return super.call(method, args);
429 if (args.length != 1) throw new JSExn("can only call a template with one arg");
431 if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));
432 if(!(args[0] instanceof Box)) throw new JSExn("can only apply templates to boxes");
433 t.apply((Box)args[0]);
436 // FEATURE: This is a gross hack
437 Template getTemplate() throws JSExn {
439 if (t == null) throw new JSExn("No such template " + JSU.str(parentkey));