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