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 a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
49 return Ibex.this.callMethod(this.key, a0, a1, a2, rest, nargs);
51 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
52 return Ibex.this.callMethod(JSU.S(JSU.toString(this.key) + "." + JSU.toString(method)), a0, a1, a2, rest, nargs);
55 private Cache subCache = new Cache(20);
56 private Sub getSub(JS key) {
57 Sub ret = (Sub)subCache.get(key);
58 if (ret == null) subCache.put(key, ret = new Sub(key));
62 public JS get(JS name) throws JSExn {
63 // FIXME: SHouldn't need this (just trap [""])
64 if (JS.isString(name) && JSU.toString(name).length() == 0) return rr;
65 // FEATURE: Preprocessor hack to generate specialized JS instances (avoid all this string concatenation)
66 //#switch(JSU.toString(name))
67 case "math": return ibexMath;
68 case "string": return ibexString;
69 case "date": return METHOD;
70 case "box": return new Box();
71 case "clone": return METHOD;
72 case "bless": return METHOD;
73 case "regexp": return METHOD;
74 case "ui": return getSub(name);
75 case "ui.font": return getSub(name);
76 case "ui.font.wait": return METHOD;
77 case "ui.font.width": return METHOD;
78 case "ui.font.height": return METHOD;
79 case "ui.font.sansserif": return Main.builtin.get(JSU.S("fonts/vera/Vera.ttf"));
80 case "ui.font.monospace": return Main.builtin.get(JSU.S("fonts/vera/VeraMono.ttf"));
81 case "ui.font.serif": return Main.builtin.get(JSU.S("fonts/vera/VeraSe.ttf"));
82 case "ui.browser": return METHOD;
83 case "ui.mouse": return getSub(name);
84 case "ui.mouse.button":
85 if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
86 else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
87 else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
89 case "ui.key": return getSub(name);
90 case "ui.key.name": return getSub(name);
91 case "ui.key.name.alt": return JSU.S(Platform.altKeyName());
92 case "ui.key.alt": return Surface.alt ? JSU.T : JSU.F;
93 case "ui.key.control": return Surface.control ? JSU.T : JSU.F;
94 case "ui.key.shift": return Surface.shift ? JSU.T : JSU.F;
95 case "ui.clipboard": return JSU.S((String)Platform.getClipBoard());
96 case "ui.maxdim": return N(Short.MAX_VALUE);
97 case "ui.screen": return getSub(name);
98 case "ui.screen.width": return N(Platform.getScreenWidth());
99 case "ui.screen.height": return N(Platform.getScreenHeight());
100 case "undocumented": return getSub(name);
101 case "undocumented.initialOrigin": return JSU.S(Main.origin);
102 case "undocumented.initialTemplate": return JSU.S(Main.initialTemplate);
103 case "thread": return getSub(name);
104 case "thread.yield": return METHOD;
105 case "thread.sleep": return METHOD;
106 case "stream": return getSub(name);
107 case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
108 case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
109 case "stream.watch": return METHOD;
110 case "stream.unzip": return METHOD;
111 case "stream.uncab": return METHOD;
112 case "stream.cache": return METHOD;
113 case "stream.url": return METHOD;
114 case "stream.parse.html": return METHOD;
115 case "stream.parse.xml": return METHOD;
116 case "stream.parse.utf8": return METHOD;
117 case "net": return getSub(name);
118 case "net.rpc": return getSub(name);
119 case "net.rpc.xml": return METHOD;
120 case "net.rpc.soap": return METHOD;
121 case "log": return getSub(name);
122 case "log.debug": return METHOD;
123 case "log.info": return METHOD;
124 case "log.warn": return METHOD;
125 case "log.error": return METHOD;
126 case "crypto": return getSub(name);
127 case "crypto.rsa": return METHOD;
128 case "crypto.md5": return METHOD;
129 case "crypto.sha1": return METHOD;
130 case "crypto.rc4": return METHOD;
135 public void put(JS name, JS value) throws JSExn {
136 //#switch(JSU.toString(name))
137 case "thread": Scheduler.add((Task)value); return;
138 case "ui.clipboard": Platform.setClipBoard(JSU.toString(value)); return;
139 case "ui.frame": Platform.createSurface((Box)value, true, true); return;
140 case "ui.window": Platform.createSurface((Box)value, false, true); return;
141 case "undocumented.proxyAuthorization":
142 HTTP.Proxy.Authorization.authorization = value.toString();
143 HTTP.Proxy.Authorization.waitingForUser.release();
146 throw new JSExn("attempted to put unknown property: ibex."+name);
149 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
151 //#switch(JSU.toString(name))
152 case "date": return new JSDate(a, b, c, rest, nargs);
153 case "net.rpc.soap": return new SOAP(JSU.toString(a), "", JSU.toString(b), JSU.toString(c));
154 // FIXME support object dumping
155 case "log.debug": JS.debug(a== null ? "**null**" : JS.debugToString(a)); return null;
156 case "log.info": JS.info(a== null ? "**null**" : JS.debugToString(a)); return null;
157 case "log.warn": JS.warn(a== null ? "**null**" : JS.debugToString(a)); return null;
158 case "log.error": JS.error(a== null ? "**null**" : JS.debugToString(a)); return null;
163 //#switch(JSU.toString(name))
164 case "thread.yield": sleep(0); return null;
168 //#switch(JSU.toString(name))
170 if(a == null) throw new JSExn("can't clone the null value");
171 return ((JS)a).jsclone();
172 case "bless": return bless((JS)a);
173 case "ui.browser": Platform.newBrowserWindow(JSU.toString(a)); return null;
174 case "stream.unzip": return a == null ? null : new Stream.Zip((Stream)a);
175 //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
177 try { return a == null ? null : new Stream.CachedStream((Stream)a, "resources", true); }
178 catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
180 String url = JSU.toString(a);
181 if (url.startsWith("http://")) return new Stream.HTTP(url);
182 else if (url.startsWith("https://")) return new Stream.HTTP(url);
183 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
184 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
185 else if (url.startsWith("file:")) {
187 Platform.fileDialog(url.substring(5), false);
189 throw new JSExn("invalid resource specifier " + url);
191 case "thread.sleep": sleep(JS.toInt(a)); return null;
192 case "regexp": return new JSRegexp(a, null);
193 case "net.rpc.xml": return new XMLRPC(JSU.toString(a), "");
194 case "crypto.rsa": /* FEATURE */ return null;
195 case "crypto.md5": /* FEATURE */ return null;
196 case "crypto.sha1": /* FEATURE */ return null;
197 case "crypto.rc4": /* FEATURE */ return null;
198 case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
199 case "stream.parse.xml": if(a == null) return null; new XMLHelper(b).doParse(a); return null;
200 // FIXME backgrounding
201 case "stream.parse.utf8": if(a == null) return null;
202 try { return JSU.S(new String(InputStreamToByteArray.convert(a.getInputStream()))); }
203 catch (Exception e) { Log.warn(this, e); }
207 //#switch(JSU.toString(name))
208 case "stream.watch": return new Stream.ProgressWatcher((Stream)a, b);
209 case "regexp": return new JSRegexp(a, b);
212 //#switch(JSU.toString(name))
213 case "ui.font.height": return N(Font.getFont(a, JS.toInt(b)).textheight(JSU.toString(c)));
214 case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
215 case "ui.font.width": return N(Font.getFont(a, JS.toInt(b)).textwidth(JSU.toString(c)));
219 } catch (RuntimeException e) {
220 // FIXME: maybe JSExn should take a second argument, Exception
221 Log.warn(this, "ibex."+name+"() threw: " + e);
222 throw new JSExn("invalid argument for ibex object method "+name+"()");
225 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
228 public JS url2res(String url) throws JSExn {
229 if (url.startsWith("http://")) return new Stream.HTTP(url);
230 else if (url.startsWith("https://")) return new Stream.HTTP(url);
231 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
232 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
233 else throw new JSExn("invalid resource specifier " + url);
234 // FIXME support file:// via dialog boxes
237 public static void sleep(final int i) throws JSExn {
239 final JS.UnpauseCallback callback = JS.pause();
240 // FEATURE use a single sleeper thread
241 new Thread() { public void run() {
242 try { Thread.sleep(i); } catch (InterruptedException e) { }
243 Scheduler.add(callback);
245 } catch (JSU.NotPauseableException npe) {
246 throw new JSExn("you cannot sleep or yield in the foreground thread");
250 public static final JS ibexMath = new JS.Obj() {
251 // FEATURE: find a cleaner way to do this
252 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
253 public JS get(JS key) throws JSExn {
254 //#switch(JSU.toString(key))
255 case "isNaN": return METHOD;
256 case "isFinite": return METHOD;
257 case "NaN": return METHOD;
258 case "Infinity": return METHOD;
260 return MATH.get(key);
262 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
263 //#switch(JSU.toString(name))
264 case "isNaN": return gs.callMethod(name,a,b,c,rest,nargs);
265 case "isFinite": return gs.callMethod(name,a,b,c,rest,nargs);
266 case "NaN": return gs.callMethod(name,a,b,c,rest,nargs);
267 case "Infinity": return gs.callMethod(name,a,b,c,rest,nargs);
269 return MATH.callMethod(name,a,b,c,rest,nargs);
273 public static final JS ibexString = new JS.Obj() {
274 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
275 public JS get(JS key) throws JSExn {
276 //#switch(JSU.toString(key))
277 case "parseInt": return METHOD;
278 case "parseFloat": return METHOD;
279 case "decodeURI": return METHOD;
280 case "decodeURIComponent": return METHOD;
281 case "encodeURI": return METHOD;
282 case "encodeURIComponent": return METHOD;
283 case "escape": return METHOD;
284 case "unescape": return METHOD;
285 case "fromCharCode": return METHOD;
287 return super.get(key);
289 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
290 //#switch(JSU.toString(name))
291 case "parseInt": return gs.callMethod(name,a,b,c,rest,nargs);
292 case "parseFloat": return gs.callMethod(name,a,b,c,rest,nargs);
293 case "decodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
294 case "decodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
295 case "encodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
296 case "encodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
297 case "escape": return gs.callMethod(name,a,b,c,rest,nargs);
298 case "unescape": return gs.callMethod(name,a,b,c,rest,nargs);
299 case "fromCharCode": return gs.callMethod(name,a,b,c,rest,nargs);
301 return super.callMethod(name,a,b,c,rest,nargs);
305 private class XMLHelper extends XML {
306 private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
307 private JS characters, whitespace, endElement, startElement;
308 public XMLHelper(JS b) throws JSExn {
310 startElement = b.getAndTriggerTraps(JSU.S("startElement"));
311 endElement = b.getAndTriggerTraps(JSU.S("endElement"));
312 characters = b.getAndTriggerTraps(JSU.S("characters"));
313 whitespace = b.getAndTriggerTraps(JSU.S("whitespace"));
316 public void startElement(XML.Element c) throws XML.Exn { try {
317 JS attrs = new JS.O();
318 // FIXME attribute URIs? add an additional hash?
319 for(int i=0; i<c.getAttrLen(); i++) attrs.put(JSU.S(c.getAttrKey(i)), JSU.S(c.getAttrVal(i)));
320 startElement.call(JSU.S(c.getLocalName()), attrs, JSU.S(c.getUri()), null, 3);
321 } catch (JSExn jse) { throw new Wrapper(jse); } }
323 public void endElement(XML.Element c) throws XML.Exn { try {
324 endElement.call(JSU.S(c.getLocalName()), JSU.S(c.getUri()), null, null, 2);
325 } catch (JSExn jse) { throw new Wrapper(jse); } }
327 public void characters(char[] ch, int start, int length) throws XML.Exn { try {
328 characters.call(JSU.S(new String(ch, start, length)), null, null, null, 1);
329 } catch (JSExn jse) { throw new Wrapper(jse); } }
331 public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
332 whitespace.call(JSU.S(new String(ch, start, length)), null, null, null, 1);
333 } catch (JSExn jse) { throw new Wrapper(jse); } }
335 public void doParse(JS s) throws JSExn {
337 parse(new BufferedReader(new InputStreamReader(s.getInputStream())));
338 } catch (Wrapper e) {
340 } catch (XML.Exn e) {
341 throw new JSExn("error parsing XML: " + e.toString());
342 } catch (IOException e) {
343 if (Log.on) Log.info(this, "IO Exception while reading from file");
344 if (Log.on) Log.info(this, e);
345 throw new JSExn("error reading from Resource");
350 // FEATURE: move this into builtin.xwar
351 public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
352 // JS:FIXME: This doesn't properly handle traps
353 public static class Blessing extends JS.Obj {
355 private Template t = null;
356 public JS parentkey = null;
357 public Blessing parent = null;
359 private Hash cache = new Hash();
360 public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
361 this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
362 public JS get(JS key) throws JSExn {
363 if (JS.isString(key) && JSU.toString(key).equals("")) return getStatic();
364 if (cache.get(key) != null) return (JS)cache.get(key);
365 JS ret = new Blessing(clonee.get(key), ibex, this, key);
369 public static Blessing getBlessing(JS js) {
370 while (js instanceof JS.Clone && !(js instanceof Blessing)) js = ((JS.Clone)js).getClonee();
371 if (!(js instanceof Blessing)) return null;
374 // FEATURE: This is a gross hack
375 public InputStream getImage() throws JSExn {
377 InputStream in = getInputStream();
378 if (in != null) return in;
379 } catch (IOException e) { /* DELIBERATE */ }
380 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
381 for (int i=0; i < exts.length; i++)
383 InputStream in = parent.get(JSU.S(JSU.toString(parentkey) + exts[i])).getInputStream();
384 if (in != null) return in;
385 } catch (IOException f) { /* DELIBERATE */ }
388 public JS getStatic() throws JSExn {
391 // FEATURE: Might want to handle the ".t" part better
392 JS res = parent.get(JSU.S(JSU.toString(parentkey) + ".t"));
393 t = Template.buildTemplate(description(), res, ibex);
395 return t != null ? t.staticObject : null;
396 } catch (Exception e) {
401 private String description() {
402 String s = JS.debugToString(parentkey);
403 for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JS.debugToString(b.parentkey) + "." + s;
406 public JS call(JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
407 if (nargs != 1) throw new JSExn("can only call a template with one arg");
409 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
410 if(!(a instanceof Box)) throw new JSExn("can only apply templates to boxes");
414 // FEATURE: This is a gross hack
415 Template getTemplate() throws JSExn {
417 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
420 // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
421 public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }