fonts now rendered immediately on-demand
[org.ibex.core.git] / src / org / ibex / Ibex.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3
4 import java.io.*;
5 import org.ibex.js.*;
6 import org.ibex.util.*;
7 import org.bouncycastle.util.encoders.Base64;
8
9 /** Singleton class that provides all functionality in the ibex.* namespace */
10 public final class Ibex extends JS.Cloneable {
11
12     // FIXME remove this
13     private final JS rr;
14
15     public Ibex(Stream rr) { this.rr = bless(rr); }
16
17     public JS resolveString(String str, boolean permitAbsolute) throws JSExn {
18         if (str.indexOf("://") != -1) {
19             if (permitAbsolute) return (Stream)url2res(str);
20             throw new JSExn("absolute URL " + str + " not permitted here");
21         }
22         // root-relative
23         //JS ret = (JS)getAndTriggerTraps("");
24         //FIXME
25         JS ret = rr;
26         while(str.indexOf('.') != -1) {
27             String path = str.substring(0, str.indexOf('.'));
28             str = str.substring(str.indexOf('.') + 1);
29             ret = (JS)ret.get(path);
30         }
31         if (!"".equals(str)) ret = (JS)ret.get(str);
32         return ret;
33     }
34
35     /** lets us put multi-level get/put/call keys all in the same method */
36     private class Sub extends JS {
37         String key;
38         Sub(String key) { this.key = key; }
39         public void put(Object key, Object val) throws JSExn { Ibex.this.put(this.key + "." + key, val); }
40         public Object get(Object key) throws JSExn { return Ibex.this.get(this.key + "." + key); }
41         public Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
42             return Ibex.this.callMethod(this.key, a0, a1, a2, rest, nargs);
43         }
44         public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
45             return Ibex.this.callMethod(this.key + "." + method, a0, a1, a2, rest, nargs);
46         }
47     }
48     private Cache subCache = new Cache(20);
49     private Sub getSub(String s) {
50         Sub ret = (Sub)subCache.get(s);
51         if (ret == null) subCache.put(s, ret = new Sub(s));
52         return ret;
53     }
54
55     public Object get(Object name) throws JSExn {
56         if (name instanceof String && ((String)name).length() == 0) return rr;
57         //#switch(name)
58         case "math": return ibexMath;
59         case "string": return ibexString;
60         case "date": return METHOD;
61         case "box": return new Box();
62         case "clone": return METHOD;
63         case "bless": return METHOD;
64         case "regexp": return METHOD;
65         case "ui": return getSub("ui");
66         case "ui.font": return getSub("ui.font");
67         case "ui.font.wait": return METHOD;
68         case "ui.font.width": return METHOD;
69         case "ui.font.height": return METHOD;
70         case "ui.font.sansserif": return Main.builtin.get("fonts/vera/Vera.ttf");
71         case "ui.font.monospace": return Main.builtin.get("fonts/vera/VeraMono.ttf");
72         case "ui.font.serif": return Main.builtin.get("fonts/vera/VeraSe.ttf");
73         case "ui.browser": return METHOD;
74         case "ui.mouse": return getSub("ui.mouse");
75         case "ui.mouse.button":
76             if (Surface.button1 && !Surface.button2 && !Surface.button3) return N(1);
77             else if (!Surface.button1 && Surface.button2 && !Surface.button3) return N(2);
78             else if (!Surface.button1 && !Surface.button2 && Surface.button3) return N(3);
79             else return ZERO;
80         case "ui.key": return getSub("ui.key");
81         case "ui.key.name": return getSub("ui.key.name");
82         case "ui.key.name.alt": return Platform.altKeyName();
83         case "ui.key.alt": return Surface.alt ? T : F;
84         case "ui.key.control": return Surface.control ? T : F;
85         case "ui.key.shift": return Surface.shift ? T : F;
86         case "ui.clipboard": return Platform.getClipBoard();
87         case "ui.maxdim": return N(Short.MAX_VALUE);
88         case "ui.screen": return getSub("ui.screen");
89         case "ui.screen.width": return N(Platform.getScreenWidth());
90         case "ui.screen.height": return N(Platform.getScreenHeight());
91         case "undocumented": return getSub("undocumented");
92         case "undocumented.initialOrigin": return Main.origin;
93         case "undocumented.initialTemplate": return Main.initialTemplate;
94         case "thread": return getSub("thread");
95         case "thread.yield": return METHOD;
96         case "thread.sleep": return METHOD;
97         case "stream": return getSub("stream");
98         case "stream.homedir": return url2res("file:" + System.getProperty("user.home"));
99         case "stream.tempdir": return url2res("file:" + System.getProperty("java.io.tempdir"));
100         case "stream.watch": return METHOD;
101         case "stream.unzip": return METHOD;
102         case "stream.uncab": return METHOD;
103         case "stream.cache": return METHOD;
104         case "stream.url": return METHOD;
105         case "stream.parse.html": return METHOD;
106         case "stream.parse.xml": return METHOD;
107         case "stream.parse.utf8": return METHOD;
108         case "net": return getSub("net");
109         case "net.rpc": return getSub("net.rpc");
110         case "net.rpc.xml": return METHOD;
111         case "net.rpc.soap": return METHOD;
112         case "log": return getSub("log");
113         case "log.debug": return METHOD;
114         case "log.info": return METHOD;
115         case "log.warn": return METHOD;
116         case "log.error": return METHOD;
117         case "crypto": return getSub("crypto");
118         case "crypto.rsa": return METHOD;
119         case "crypto.md5": return METHOD;
120         case "crypto.sha1": return METHOD;
121         case "crypto.rc4": return METHOD;
122         //#end
123         return super.get(name);
124     }
125
126     public void put(Object name, final Object value) throws JSExn {
127         //#switch(name)
128         case "thread": Scheduler.add((Scheduler.Task)value); return;
129         case "ui.clipboard": Platform.setClipBoard((String)value); return;
130         case "ui.frame": Platform.createSurface((Box)value, true, true); return;
131         case "ui.window": Platform.createSurface((Box)value, false, true); return;
132         case "undocumented.proxyAuthorization":
133             HTTP.Proxy.Authorization.authorization = value.toString();
134             HTTP.Proxy.Authorization.waitingForUser.release();
135             return;
136         //#end
137         throw new JSExn("attempted to put unknown property: ibex."+name);
138     }
139
140     public Object callMethod(Object name, Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
141         try {
142             //#switch(name)
143             case "date": return new JSDate(a, b, c, rest, nargs);
144             case "net.rpc.soap": return new SOAP((String)a, "", (String)b, (String)c);
145                 // FIXME support object dumping
146             case "log.debug":    JS.debug(a== null ? "**null**" : a.toString()); return null;
147             case "log.info":     JS.info(a== null ? "**null**" : a.toString()); return null;
148             case "log.warn":     JS.warn(a== null ? "**null**" : a.toString()); return null;
149             case "log.error":    JS.error(a== null ? "**null**" : a.toString()); return null;
150             //#end
151  
152             switch (nargs) {
153                 case 0:
154                     //#switch(name)
155                     case "thread.yield": sleep(0); return null;
156                     //#end
157                     break;
158                 case 1:
159                     //#switch(name)
160                     case "clone":
161                         if (!(a instanceof JS.Cloneable)) throw new JSExn("cannot clone a " + a.getClass().getName());
162                         return ((JS.Cloneable)a).jsclone();
163                     case "bless": return bless((JS)a);
164                     case "ui.browser": Platform.newBrowserWindow((String)a); return null;
165                     case "stream.unzip": return new Stream.Zip((Stream)a);
166                     case "stream.uncab": return new Stream.Cab((Stream)a);
167                     case "stream.cache":
168                         try { return new Stream.CachedStream((Stream)a, "resources", true); }
169                         catch (Stream.NotCacheableException e) { throw new JSExn("this resource cannot be cached"); }
170                     case "stream.url": {
171                         String url = (String)a;
172                         if (url.startsWith("http://")) return new Stream.HTTP(url);
173                         else if (url.startsWith("https://")) return new Stream.HTTP(url);
174                         else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
175                         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
176                         else if (url.startsWith("file:")) {
177                             // FIXME
178                             Platform.fileDialog(url.substring(5), false);
179                         }
180                         throw new JSExn("invalid resource specifier " + url);
181                     }
182                     case "thread.sleep": sleep(JS.toInt(a)); return null;
183                     case "regexp": return new JSRegexp(a, null);
184                     case "net.rpc.xml": return new XMLRPC((String)a, "");
185                     case "crypto.rsa": /* FEATURE */ return null;
186                     case "crypto.md5": /* FEATURE */ return null;
187                     case "crypto.sha1": /* FEATURE */ return null;
188                     case "crypto.rc4": /* FEATURE */ return null;
189                     case "stream.parse.html": throw new JSExn("not implemented yet"); //return null;
190                     case "stream.parse.xml": new XMLHelper((JS)b).doParse((JS)a); return null;
191                         // FIXME backgrounding
192                     case "stream.parse.utf8": try { return new String(InputStreamToByteArray.convert(Stream.getInputStream(a))); }
193                                               catch (Exception e) { Log.warn(this, e); }
194                     //#end
195                     break;
196                 case 2:
197                     //#switch(name)
198                     case "stream.watch": return new Stream.ProgressWatcher((Stream)a, (JS)b);
199                     case "regexp": return new JSRegexp(a, b);
200                     //#end
201                 case 3:
202                     //#switch(name)
203                     case "ui.font.height": return N(Font.getFont((Stream)a, JS.toInt(b)).textheight((String)c));
204                     case "ui.font.wait": throw new Error("FIXME: ibex.ui.font.wait not implemented");
205                     case "ui.font.width": return N(Font.getFont((Stream)a, JS.toInt(b)).textwidth((String)c));
206                     //#end
207                     break;
208             }
209         } catch (RuntimeException e) {
210             // FIXME: maybe JSExn should take a second argument, Exception
211             Log.warn(this, "ibex."+name+"() threw: " + e);
212             throw new JSExn("invalid argument for ibex object method "+name+"()");
213         }
214
215         throw new JSExn("invalid number of arguments ("+nargs+") for ibex object method "+name+"()");
216     }
217
218     public Stream url2res(String url) throws JSExn {
219         if (url.startsWith("http://")) return new Stream.HTTP(url);
220         else if (url.startsWith("https://")) return new Stream.HTTP(url);
221         else if (url.startsWith("data:")) return new Stream.ByteArray(Base64.decode(url.substring(5)), null);
222         else if (url.startsWith("utf8:")) return new Stream.ByteArray(url.substring(5).getBytes(), null);
223         else throw new JSExn("invalid resource specifier " + url);
224         // FIXME support file:// via dialog boxes
225     }
226
227     public static void sleep(final int i) throws JSExn {
228         try {
229             final JS.UnpauseCallback callback = JS.pause();
230             // FEATURE use a single sleeper thread
231             new Thread() { public void run() {
232                 try { Thread.sleep(i); } catch (InterruptedException e) { }
233                 Scheduler.add(callback);
234             } }.start();
235         } catch (JS.NotPauseableException npe) {
236             throw new JSExn("you cannot sleep or yield in the foreground thread");
237         }
238     }
239     
240     public static final JSMath ibexMath = new JSMath() {
241             private JS gs = new JSScope.Global();
242             public Object get(Object key) throws JSExn {
243                 //#switch(key)
244                 case "isNaN": return gs.get("isNaN");
245                 case "isFinite": return gs.get("isFinite");
246                 case "NaN": return gs.get("NaN");
247                 case "Infinity": return gs.get("Infinity");
248                 //#end
249                 return super.get(key);
250             }
251         };
252
253     public static final JS ibexString = new JS() {
254             private JS gs = new JSScope.Global();
255             public void put(Object key, Object val) { }
256             public Object get(Object key) throws JSExn {
257                 //#switch(key)
258                 case "parseInt": return gs.get("parseInt");
259                 case "parseFloat": return gs.get("parseFloat");
260                 case "decodeURI": return gs.get("decodeURI");
261                 case "decodeURIComponent": return gs.get("decodeURIComponent");
262                 case "encodeURI": return gs.get("encodeURI");
263                 case "encodeURIComponent": return gs.get("encodeURIComponent");
264                 case "escape": return gs.get("escape");
265                 case "unescape": return gs.get("unescape");
266                 case "fromCharCode": return gs.get("stringFromCharCode");
267                 //#end
268                 return null;
269             }
270         };
271
272     private class XMLHelper extends XML {
273         private class Wrapper extends XML.Exn { public JSExn wrapee; public Wrapper(JSExn jse) { super(""); wrapee = jse; } }
274         private JS characters, whitespace, endElement, startElement;
275         public XMLHelper(JS b) throws JSExn {
276             super(BUFFER_SIZE);
277             startElement = (JS)b.getAndTriggerTraps("startElement");
278             endElement   = (JS)b.getAndTriggerTraps("endElement");
279             characters   = (JS)b.getAndTriggerTraps("characters");
280             whitespace   = (JS)b.getAndTriggerTraps("whitespace");
281         }
282
283         public void startElement(XML.Element c) throws XML.Exn { try {
284                 JS attrs = new JS();
285                 // FIXME attribute URIs? add an additional hash?
286                 for(int i=0; i<c.getAttrLen(); i++) attrs.put(c.getAttrKey(i), c.getAttrVal(i));
287                 startElement.call(c.getLocalName(), attrs, c.getUri(), null, 3);
288         } catch (JSExn jse) { throw new Wrapper(jse); } }
289
290         public void endElement(XML.Element c) throws XML.Exn { try {
291                 endElement.call(c.getLocalName(), c.getUri(), null, null, 2);
292         } catch (JSExn jse) { throw new Wrapper(jse); } }
293
294         public void characters(char[] ch, int start, int length) throws XML.Exn { try {
295                 characters.call(new String(ch, start, length), null, null, null, 1);
296         } catch (JSExn jse) { throw new Wrapper(jse); } }
297
298         public void whitespace(char[] ch, int start, int length) throws XML.Exn { try {
299                 whitespace.call(new String(ch, start, length), null, null, null, 1);
300         } catch (JSExn jse) { throw new Wrapper(jse); } }
301
302         public void doParse(JS s) throws JSExn {
303             try { 
304                 parse(new BufferedReader(new InputStreamReader(Stream.getInputStream(s))));
305             } catch (Wrapper e) {
306                 throw e.wrapee;
307             } catch (XML.Exn e) {
308                 throw new JSExn("error parsing XML: " + e.toString());
309             } catch (IOException e) {
310                 if (Log.on) Log.info(this, "IO Exception while reading from file");
311                 if (Log.on) Log.info(this, e);
312                 throw new JSExn("error reading from Resource");
313             }
314         }
315     }
316
317     // FEATURE: move this into builtin.xwar
318     public Blessing bless(JS b) { return new Ibex.Blessing((JS.Cloneable)b, this, null, null); }
319     public static class Blessing extends JS.Clone {
320         private Ibex ibex;
321         private Template t = null;
322         public Object parentkey = null;
323         public Blessing parent = null;
324         private Hash cache = new Hash();
325         public Blessing(JS.Cloneable clonee, Ibex ibex, Blessing parent, Object parentkey) {
326             super(clonee); this.ibex = ibex; this.parentkey = parentkey; this.parent = parent; }
327         public Object get(Object key) throws JSExn {
328             if (key.equals("")) return ((Object)getStatic());
329             if (cache.get(key) != null) return cache.get(key);
330             Object ret = new Blessing((JS.Cloneable)clonee.get(key), ibex, this, key);
331             cache.put(key, ret);
332             return ret;
333         }
334         public static Blessing getBlessing(Object o) {
335             if (!(o instanceof JS)) return null;
336             JS js = (JS)o;
337             while (js instanceof JS.Clone && !(js instanceof Blessing)) js = ((JS.Clone)js).getClonee();
338             if (!(js instanceof Blessing)) return null;
339             return (Blessing)js;
340         }
341         public InputStream getImage() throws JSExn {
342             try {
343                 InputStream in = Stream.getInputStream(this);
344                 if (in != null) return in;
345             } catch (IOException e) { /* DELIBERATE */ }
346             String[] exts = new String[] { ".png", ".jpeg", ".gif" };
347             for (int i=0; i < exts.length; i++)
348                 try {
349                     InputStream in = Stream.getInputStream(parent.get(parentkey + exts[i]));
350                     if (in != null) return in;
351                 } catch (IOException f) { /* DELIBERATE */ }
352             return null;
353         }
354         public JSScope getStatic() {
355             try {
356                 if (t == null) t = Template.buildTemplate(parentkey + ".t", parent.get(parentkey + ".t"), ibex);
357                 return t.staticScope;
358             } catch (Exception e) {
359                 Log.error(this, e);
360                 return null;
361             }
362         }
363         public Object call(Object a, Object b, Object c, Object[] rest, int nargs) throws JSExn {
364             // GROSS hack
365             if (nargs != 1 && nargs != 9999) throw new JSExn("FIXME can only call with one arg");
366             getStatic();
367             if (t == null) throw new JSExn("No such template " + parentkey);
368             if (nargs == 9999) return t;
369             t.apply((Box)a);
370             return a;
371         }
372     }
373
374 }