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