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 implements JS.Cloneable {
21 public Ibex(Stream rr) { try { this.rr = bless(rr);} catch(JSExn e) { throw new Error("should never happen: " + e); } }
23 public JS resolveString(String str, boolean permitAbsolute) throws JSExn {
24 if (str.indexOf("://") != -1) {
25 if (permitAbsolute) return url2res(str);
26 throw new JSExn("absolute URL " + str + " not permitted here");
29 //JS ret = (JS)getAndTriggerTraps("");
32 while(str.indexOf('.') != -1) {
33 String path = str.substring(0, str.indexOf('.'));
34 str = str.substring(str.indexOf('.') + 1);
35 ret = ret.get(JS.S(path));
37 if (!"".equals(str)) ret = ret.get(JS.S(str));
41 /** lets us put multi-level get/put/call keys all in the same method */
42 private class Sub extends JS {
44 Sub(JS key) { this.key = key; }
45 public void put(JS key, JS val) throws JSExn { Ibex.this.put(JS.S(JS.toString(this.key) + "." + JS.toString(key)), val); }
46 public JS get(JS key) throws JSExn { return Ibex.this.get(JS.S(JS.toString(this.key) + "." + JS.toString(key))); }
47 public JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
48 return Ibex.this.callMethod(this.key, a0, a1, a2, rest, nargs);
50 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
51 return Ibex.this.callMethod(JS.S(JS.toString(this.key) + "." + JS.toString(method)), a0, a1, a2, rest, nargs);
54 private Cache subCache = new Cache(20);
55 private Sub getSub(JS key) {
56 Sub ret = (Sub)subCache.get(key);
57 if (ret == null) subCache.put(key, ret = new Sub(key));
61 public JS get(JS name) throws JSExn {
62 // FIXME: SHouldn't need this (just trap [""])
63 if (JS.isString(name) && JS.toString(name).length() == 0) return rr;
64 // FEATURE: Preprocessor hack to generate specialized JS instances (avoid all this string concatenation)
65 //#switch(JS.toString(name))
66 case "math": return ibexMath;
67 case "string": return ibexString;
68 case "date": return METHOD;
69 case "box": return new Box();
70 case "clone": return METHOD;
71 case "bless": return METHOD;
72 case "regexp": return METHOD;
73 case "ui": return getSub(name);
74 case "ui.font": return getSub(name);
75 case "ui.font.wait": return METHOD;
76 case "ui.font.width": return METHOD;
77 case "ui.font.height": return METHOD;
78 case "ui.font.sansserif": return Main.builtin.get(JS.S("fonts/vera/Vera.ttf"));
79 case "ui.font.monospace": return Main.builtin.get(JS.S("fonts/vera/VeraMono.ttf"));
80 case "ui.font.serif": return Main.builtin.get(JS.S("fonts/vera/VeraSe.ttf"));
81 case "ui.browser": return METHOD;
82 case "ui.mouse": return getSub(name);
83 case "ui.mouse.button":
84 if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
85 else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
86 else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
88 case "ui.key": return getSub(name);
89 case "ui.key.name": return getSub(name);
90 case "ui.key.name.alt": return JS.S(Platform.altKeyName());
91 case "ui.key.alt": return Surface.alt ? T : F;
92 case "ui.key.control": return Surface.control ? T : F;
93 case "ui.key.shift": return Surface.shift ? T : F;
94 case "ui.clipboard": return JS.S((String)Platform.getClipBoard());
95 case "ui.maxdim": return N(Short.MAX_VALUE);
96 case "ui.screen": return getSub(name);
97 case "ui.screen.width": return N(Platform.getScreenWidth());
98 case "ui.screen.height": return N(Platform.getScreenHeight());
99 case "undocumented": return getSub(name);
100 case "undocumented.initialOrigin": return JS.S(Main.origin);
101 case "undocumented.initialTemplate": return JS.S(Main.initialTemplate);
102 case "thread": return getSub(name);
103 case "thread.yield": return METHOD;
104 case "thread.sleep": return METHOD;
105 case "stream": return getSub(name);
106 case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
107 case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
108 case "stream.watch": return METHOD;
109 case "stream.unzip": return METHOD;
110 case "stream.uncab": return METHOD;
111 case "stream.cache": return METHOD;
112 case "stream.url": return METHOD;
113 case "stream.parse.html": return METHOD;
114 case "stream.parse.xml": return METHOD;
115 case "stream.parse.utf8": return METHOD;
116 case "net": return getSub(name);
117 case "net.rpc": return getSub(name);
118 case "net.rpc.xml": return METHOD;
119 case "net.rpc.soap": return METHOD;
120 case "log": return getSub(name);
121 case "log.debug": return METHOD;
122 case "log.info": return METHOD;
123 case "log.warn": return METHOD;
124 case "log.error": return METHOD;
125 case "crypto": return getSub(name);
126 case "crypto.rsa": return METHOD;
127 case "crypto.md5": return METHOD;
128 case "crypto.sha1": return METHOD;
129 case "crypto.rc4": return METHOD;
134 public void put(JS name, JS value) throws JSExn {
135 //#switch(JS.toString(name))
136 case "thread": Scheduler.add((Task)value); return;
137 case "ui.clipboard": Platform.setClipBoard(JS.toString(value)); return;
138 case "ui.frame": Platform.createSurface((Box)value, true, true); return;
139 case "ui.window": Platform.createSurface((Box)value, false, true); return;
140 case "undocumented.proxyAuthorization":
141 HTTP.Proxy.Authorization.authorization = value.toString();
142 HTTP.Proxy.Authorization.waitingForUser.release();
145 throw new JSExn("attempted to put unknown property: ibex."+name);
148 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
150 //#switch(JS.toString(name))
151 case "date": return new JSDate(a, b, c, rest, nargs);
152 case "net.rpc.soap": return new SOAP(JS.toString(a), "", JS.toString(b), JS.toString(c));
153 // FIXME support object dumping
154 case "log.debug": JS.debug(a== null ? "**null**" : JS.debugToString(a)); return null;
155 case "log.info": JS.info(a== null ? "**null**" : JS.debugToString(a)); return null;
156 case "log.warn": JS.warn(a== null ? "**null**" : JS.debugToString(a)); return null;
157 case "log.error": JS.error(a== null ? "**null**" : JS.debugToString(a)); return null;
162 //#switch(JS.toString(name))
163 case "thread.yield": sleep(0); return null;
167 //#switch(JS.toString(name))
169 if(a == null) throw new JSExn("can't clone the null value");
170 return ((JS)a).jsclone();
171 case "bless": return bless((JS)a);
172 case "ui.browser": Platform.newBrowserWindow(JS.toString(a)); return null;
173 case "stream.unzip": return a == null ? null : new Stream.Zip((Stream)a);
174 //case "stream.uncab": return a == null ? null : new Stream.Cab(a);
176 try { return a == null ? null : new Stream.CachedStream((Stream)a, "resources", true); }
177 catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
179 String url = JS.toString(a);
180 if (url.startsWith("http://")) return new Stream.HTTP(url);
181 else if (url.startsWith("https://")) return new Stream.HTTP(url);
182 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
183 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
184 else if (url.startsWith("file:")) {
186 Platform.fileDialog(url.substring(5), false);
188 throw new JSExn("invalid resource specifier " + url);
190 case "thread.sleep": sleep(JS.toInt(a)); return null;
191 case "regexp": return new JSRegexp(a, null);
192 case "net.rpc.xml": return new XMLRPC(JS.toString(a), "");
193 case "crypto.rsa": /* FEATURE */ return null;
194 case "crypto.md5": /* FEATURE */ return null;
195 case "crypto.sha1": /* FEATURE */ return null;
196 case "crypto.rc4": /* FEATURE */ return null;
197 case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
198 case "stream.parse.xml": if(a == null) return null; new XMLHelper(b).doParse(a); return null;
199 // FIXME backgrounding
200 case "stream.parse.utf8": if(a == null) return null;
201 try { return JS.S(new String(InputStreamToByteArray.convert(a.getInputStream()))); }
202 catch (Exception e) { Log.warn(this, e); }
206 //#switch(JS.toString(name))
207 case "stream.watch": return new Stream.ProgressWatcher((Stream)a, b);
208 case "regexp": return new JSRegexp(a, b);
211 //#switch(JS.toString(name))
212 case "ui.font.height": return N(Font.getFont(a, JS.toInt(b)).textheight(JS.toString(c)));
213 case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
214 case "ui.font.width": return N(Font.getFont(a, JS.toInt(b)).textwidth(JS.toString(c)));
218 } catch (RuntimeException e) {
219 // FIXME: maybe JSExn should take a second argument, Exception
220 Log.warn(this, "ibex."+name+"() threw: " + e);
221 throw new JSExn("invalid argument for ibex object method "+name+"()");
224 throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
227 public JS url2res(String url) throws JSExn {
228 if (url.startsWith("http://")) return new Stream.HTTP(url);
229 else if (url.startsWith("https://")) return new Stream.HTTP(url);
230 else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
231 else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
232 else throw new JSExn("invalid resource specifier " + url);
233 // FIXME support file:// via dialog boxes
236 public static void sleep(final int i) throws JSExn {
238 final JS.UnpauseCallback callback = JS.pause();
239 // FEATURE use a single sleeper thread
240 new Thread() { public void run() {
241 try { Thread.sleep(i); } catch (InterruptedException e) { }
242 Scheduler.add(callback);
244 } catch (JS.NotPauseableException npe) {
245 throw new JSExn("you cannot sleep or yield in the foreground thread");
249 public static final JS ibexMath = new JS() {
250 // FEATURE: find a cleaner way to do this
251 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
252 public JS get(JS key) throws JSExn {
253 //#switch(JS.toString(key))
254 case "isNaN": return METHOD;
255 case "isFinite": return METHOD;
256 case "NaN": return METHOD;
257 case "Infinity": return METHOD;
259 return MATH.get(key);
261 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
262 //#switch(JS.toString(name))
263 case "isNaN": return gs.callMethod(name,a,b,c,rest,nargs);
264 case "isFinite": return gs.callMethod(name,a,b,c,rest,nargs);
265 case "NaN": return gs.callMethod(name,a,b,c,rest,nargs);
266 case "Infinity": return gs.callMethod(name,a,b,c,rest,nargs);
268 return MATH.callMethod(name,a,b,c,rest,nargs);
272 public static final JS ibexString = new JS() {
273 private JS gs = /*new JSScope.Global();*/ null; // FIXME: Global scope
274 public JS get(JS key) throws JSExn {
275 //#switch(JS.toString(key))
276 case "parseInt": return METHOD;
277 case "parseFloat": return METHOD;
278 case "decodeURI": return METHOD;
279 case "decodeURIComponent": return METHOD;
280 case "encodeURI": return METHOD;
281 case "encodeURIComponent": return METHOD;
282 case "escape": return METHOD;
283 case "unescape": return METHOD;
284 case "fromCharCode": return METHOD;
286 return super.get(key);
288 public JS callMethod(JS name, JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
289 //#switch(JS.toString(name))
290 case "parseInt": return gs.callMethod(name,a,b,c,rest,nargs);
291 case "parseFloat": return gs.callMethod(name,a,b,c,rest,nargs);
292 case "decodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
293 case "decodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
294 case "encodeURI": return gs.callMethod(name,a,b,c,rest,nargs);
295 case "encodeURIComponent": return gs.callMethod(name,a,b,c,rest,nargs);
296 case "escape": return gs.callMethod(name,a,b,c,rest,nargs);
297 case "unescape": return gs.callMethod(name,a,b,c,rest,nargs);
298 case "fromCharCode": return gs.callMethod(name,a,b,c,rest,nargs);
300 return super.callMethod(name,a,b,c,rest,nargs);
304 private class XMLHelper extends XML {
305 private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
306 private JS characters, whitespace, endElement, startElement;
307 public XMLHelper(JS b) throws JSExn {
309 startElement = b.getAndTriggerTraps(JS.S("startElement"));
310 endElement = b.getAndTriggerTraps(JS.S("endElement"));
311 characters = b.getAndTriggerTraps(JS.S("characters"));
312 whitespace = b.getAndTriggerTraps(JS.S("whitespace"));
315 public void startElement(XML.Element c) throws XML.Exn { try {
316 JS attrs = new JS.O();
317 // FIXME attribute URIs? add an additional hash?
318 for(int i=0; i<c.getAttrLen(); i++) attrs.put(JS.S(c.getAttrKey(i)), JS.S(c.getAttrVal(i)));
319 startElement.call(JS.S(c.getLocalName()), attrs, JS.S(c.getUri()), null, 3);
320 } catch (JSExn jse) { throw new Wrapper(jse); } }
322 public void endElement(XML.Element c) throws XML.Exn { try {
323 endElement.call(JS.S(c.getLocalName()), JS.S(c.getUri()), null, null, 2);
324 } catch (JSExn jse) { throw new Wrapper(jse); } }
326 public void characters(char[] ch, int start, int length) throws XML.Exn { try {
327 characters.call(JS.S(new String(ch, start, length)), null, null, null, 1);
328 } catch (JSExn jse) { throw new Wrapper(jse); } }
330 public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
331 whitespace.call(JS.S(new String(ch, start, length)), null, null, null, 1);
332 } catch (JSExn jse) { throw new Wrapper(jse); } }
334 public void doParse(JS s) throws JSExn {
336 parse(new BufferedReader(new InputStreamReader(s.getInputStream())));
337 } catch (Wrapper e) {
339 } catch (XML.Exn e) {
340 throw new JSExn("error parsing XML: " + e.toString());
341 } catch (IOException e) {
342 if (Log.on) Log.info(this, "IO Exception while reading from file");
343 if (Log.on) Log.info(this, e);
344 throw new JSExn("error reading from Resource");
349 // FEATURE: move this into builtin.xwar
350 public Blessing bless(JS b) throws JSExn { return new Ibex.Blessing(b, this, null, null); }
351 // JS:FIXME: This doesn't properly handle traps
352 public static class Blessing extends JS.O {
354 private Template t = null;
355 public JS parentkey = null;
356 public Blessing parent = null;
358 private Hash cache = new Hash();
359 public Blessing(JS clonee, Ibex ibex, Blessing parent, JS parentkey) throws JSExn {
360 this.clonee = clonee; this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
361 public JS get(JS key) throws JSExn {
362 if (JS.isString(key) && JS.toString(key).equals("")) return getStatic();
363 if (cache.get(key) != null) return (JS)cache.get(key);
364 JS ret = new Blessing(clonee.get(key), ibex, this, key);
368 public static Blessing getBlessing(JS js) {
369 while (js instanceof JS.Clone && !(js instanceof Blessing)) js = ((JS.Clone)js).getClonee();
370 if (!(js instanceof Blessing)) return null;
373 // FEATURE: This is a gross hack
374 public InputStream getImage() throws JSExn {
376 InputStream in = getInputStream();
377 if (in != null) return in;
378 } catch (IOException e) { /* DELIBERATE */ }
379 String[] exts = new String[] { ".png", ".jpeg", ".gif" };
380 for (int i=0; i < exts.length; i++)
382 InputStream in = parent.get(JS.S(JS.toString(parentkey) + exts[i])).getInputStream();
383 if (in != null) return in;
384 } catch (IOException f) { /* DELIBERATE */ }
387 public JS getStatic() throws JSExn {
390 // FEATURE: Might want to handle the ".t" part better
391 JS res = parent.get(JS.S(JS.toString(parentkey) + ".t"));
392 t = Template.buildTemplate(description(), res, ibex);
394 return t != null ? t.staticObject : null;
395 } catch (Exception e) {
400 private String description() {
401 String s = JS.debugToString(parentkey);
402 for(Blessing b = parent; b.parentkey != null; b = b.parent) s = JS.debugToString(b.parentkey) + "." + s;
405 public JS call(JS a, JS b, JS c, JS[] rest, int nargs) throws JSExn {
406 if (nargs != 1) throw new JSExn("can only call a template with one arg");
408 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
409 if(!(a instanceof Box)) throw new JSExn("can only apply templates to boxes");
413 // FEATURE: This is a gross hack
414 Template getTemplate() throws JSExn {
416 if (t == null) throw new JSExn("No such template " + JS.debugToString(parentkey));
419 // JS:FIXME: Blessing shouldn't need to roll its own JS.Clone implementation
420 public InputStream getInputStream() throws IOException { return clonee.getInputStream(); }