2003/11/03 00:08:26
[org.ibex.core.git] / src / org / xwt / XWT.java
1 // Copyright 2003 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.Obj {
15
16     public final Res rr;
17     public XWT(Res rr) { this.rr = rr; }
18
19     private final JS xwtMath = new XWTMath();
20     private final JS xwtString = new XWTString();
21
22     /** each key is a string representing a filename which the user has already given XWT permission to write to */
23     private static Hashtable safeFiles = new Hashtable();
24
25     public Object get(Object name) {
26         if (name.equals("alt")) return Surface.alt ? Boolean.TRUE : Boolean.FALSE;
27         else if (name.equals("rr")) return rr;
28         else if (name.equals("box")) return new Box();
29         else if (name.equals("control")) return Surface.control ? Boolean.TRUE : Boolean.FALSE;
30         else if (name.equals("shift")) return Surface.shift ? Boolean.TRUE : Boolean.FALSE;
31         else if (name.equals("clipboard")) return Platform.getClipBoard();
32         else if (name.equals("origin")) return Main.origin;
33         else if (name.equals("maxdim")) return new Integer(Short.MAX_VALUE);
34         else if (name.equals("altKeyName")) return Platform.altKeyName();
35         else if (name.equals("screenWidth")) return new Integer(Platform.getScreenWidth());
36         else if (name.equals("screenHeight")) return new Integer(Platform.getScreenHeight());
37         else if (name.equals("fileSeparator")) return File.separator;
38         else if (name.equals("homeDir")) return System.getProperty("user.home");
39         else if (name.equals("tempDir")) return System.getProperty("java.io.tempdir");
40         else if (name.equals("math")) return xwtMath;
41         else if (name.equals("string")) return xwtString;
42         else if (name.equals("parseInt")) return xwtString.get("parseInt");
43         else if (name.equals("parseFloat")) return xwtString.get("parseFloat");
44         else if (name.equals("button")) {
45             if (Surface.button1 && !Surface.button2 && !Surface.button3) return new Integer(1);
46             else if (!Surface.button1 && Surface.button2 && !Surface.button3) return new Integer(1);
47             else if (!Surface.button1 && !Surface.button2 && Surface.button3) return new Integer(1);
48             else return new Integer(0);
49         }
50         else return rr.get(name);
51     }
52
53     public void put(Object name, final Object value) {
54         if (name.equals("thread") && value != null && (value instanceof JS.Callable || value instanceof JS.CompiledFunction)) {
55             Scheduler.add(new Scheduler.Task() { public void perform() {
56                 new JS.Thread((CompiledFunction)value).resume();
57             } });
58         } else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
59         else if (name.equals("frame")) Platform.createSurface((Box)value, true, true);
60         else if (name.equals("window")) Platform.createSurface((Box)value, false, true);
61         else if (name.equals("proxyAuthorization")) {
62             HTTP.Proxy.Authorization.authorization = value.toString();
63             HTTP.Proxy.Authorization.waitingForUser.release();
64         } else super.put(name, value);
65     }
66
67     public Object callMethod(Object method, JS.Array args, boolean checkOnly) {
68
69         if (method.equals("newBrowserWindow")) {
70             if (checkOnly) return Boolean.TRUE;
71             if (args.length() != 1 || args.elementAt(0) == null) return null;
72             Platform.newBrowserWindow(args.elementAt(0).toString());
73             return null;
74
75         } else if (method.equals("clone")) {
76             if (checkOnly) return Boolean.TRUE;
77             return new XWT((Res)args.elementAt(0));
78
79         } else if (method.equals("graft")) {
80             if (checkOnly) return Boolean.TRUE;
81             if (args.elementAt(0) instanceof Box) throw new JS.Exn("can't graft onto Boxes (yet)");
82             if (args.elementAt(0) instanceof Number) throw new JS.Exn("can't graft onto Numbers (yet)");
83             if (args.elementAt(0) instanceof String) throw new JS.Exn("can't graft onto Strings (yet)");
84             if (args.elementAt(0) instanceof Res)
85                 return new Res.Graft((Res)args.elementAt(0), args.elementAt(1), args.elementAt(2));
86             return new JS.Graft((JS)args.elementAt(0), args.elementAt(1), args.elementAt(2));
87
88         } else if (method.equals("unzip")) {
89             if (checkOnly) return Boolean.TRUE;
90             return new Res.Zip((Res)args.elementAt(0));
91
92         } else if (method.equals("watchProgress")) {
93             if (checkOnly) return Boolean.TRUE;
94             return new Res.ProgressWatcher((Res)args.elementAt(0), (JS.CompiledFunction)args.elementAt(1));
95
96         } else if (method.equals("yield")) {
97             if (checkOnly) return Boolean.TRUE;
98             sleep(0);
99             return null;
100
101         } else if (method.equals("load")) {
102             if (checkOnly) return Boolean.TRUE;
103             return Res.stringToRes(args.elementAt(0).toString());
104
105         } else if (method.equals("println")) {
106             if (checkOnly) return Boolean.TRUE;
107             if (args.length() != 1) return null;
108             if (Log.on) Log.logJS(this, (args.elementAt(0) == null ? "**null**" : args.elementAt(0).toString()));
109             return null;
110
111         } else if (method.equals("date")) {
112             if (checkOnly) return Boolean.TRUE;
113             Log.log(XWT.class, "date not implemented");
114             return null;
115
116         } else if (method.equals("regexp")) {
117             if (checkOnly) return Boolean.TRUE;
118             return new Regexp(args);
119
120         } else if (method.equals("apply")) {
121             if (checkOnly) return Boolean.TRUE;
122             Box b = (Box)args.elementAt(0);
123             Template.getTemplate((Res)args.elementAt(1)).apply(b, null, this);
124             return b;
125
126         } else if (method.equals("xmlrpc")) {
127             if (checkOnly) return Boolean.TRUE;
128             if (args.length() != 1 || args.elementAt(0) == null) return null;
129             return new XMLRPC(args.elementAt(0).toString(), "");
130
131         } else if (method.equals("soap")) {
132             if (checkOnly) return Boolean.TRUE;
133             if (args.length() == 1 && args.elementAt(0) != null) return new SOAP(args.elementAt(0).toString(), "", null, null);
134             else if (args.length() == 2 && args.elementAt(0) != null && args.elementAt(1) != null)
135                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), null);
136             else if (args.length() == 3 && args.elementAt(0) != null && args.elementAt(1) != null && args.elementAt(2) != null)
137                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), args.elementAt(2).toString());
138             else return null;
139
140         } else if (method.equals("sleep")) {
141             if (checkOnly) return Boolean.TRUE;
142             if (args != null && (args.length() != 1 || args.elementAt(0) == null)) return null;
143             int i = args == null ? 0 : Box.stoi(args.elementAt(0).toString());
144             sleep(i);
145             return null;
146
147         } else if (method.equals("openFile")) {
148             if (checkOnly) return Boolean.TRUE;
149             if (args.length() != 1) return null;
150             String file = Platform.fileDialog(args.elementAt(0).toString(), false);
151             return file == null ? null : new Res.File(file);
152
153         } else if (method.equals("saveFile") || method.equals("saveFileAs")) {
154             if (checkOnly) return Boolean.TRUE;
155             if (args.length() != 2) return null;
156             if (!(args.elementAt(1) instanceof Res)) return null;
157             String file = args.elementAt(0).toString();
158             if (method.equals("saveFileAs") ||
159                 safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
160                 file = Platform.fileDialog(file, true);
161                 // FIXME: throw exception here
162                 if (file == null) return null;
163                 safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
164             }
165             try {
166                 InputStream is = ((Res)args.elementAt(1)).getInputStream();
167                 FileOutputStream out = new FileOutputStream(file);
168                 byte[] buffer = new byte[1024 * 16];
169                 while(true) {
170                     int numread = is.read(buffer, 0, buffer.length);
171                     if (numread == -1) break;
172                     out.write(buffer, 0, numread);
173                 }
174                 is.close();
175                 out.close();
176                 return null;
177             } catch (IOException e) {
178                 if (Log.on) Log.log(XWT.class, "IO Exception while writing a ByteStream to a file");
179                 if (Log.on) Log.log(XWT.class, e);
180                 throw new JS.Exn("error while writing a Resource to a file");
181             }
182
183         } else if (method.equals("parseHTML")) {
184             if (checkOnly) return Boolean.TRUE;
185                 if (args == null || args.length() != 1 || args.elementAt(0) == null) return null;
186                 try {
187                     if (args.elementAt(0) instanceof Res) {
188                         return HTML.parseReader(new InputStreamReader(((Res)args.elementAt(0)).getInputStream()));
189                     } else {
190                         return HTML.parseReader(new StringReader(args.elementAt(0).toString()));
191                     }
192                 } catch (IOException e) {
193                     if (Log.on) Log.log(HTML.class, "IO Exception while parsing HTML");
194                     if (Log.on) Log.log(HTML.class, e);
195                     throw new JS.Exn("error while parsing HTML");
196                 }
197
198         } else if (method.equals("recursivePrintObject")) {
199             if (checkOnly) return Boolean.TRUE;
200             if (args.length() != 1) return null;
201             recurse("", "", args.elementAt(0));
202             return null;
203         }
204             
205         if (checkOnly) return Boolean.FALSE;
206         return null;
207     }
208
209     private static void recurse(String indent, String name, Object o) {
210         if (!name.equals("")) name += " : ";
211
212         if (o == null) {
213             Log.logJS(indent + name + "<null>");
214
215         } else if (o instanceof JS.Array) {
216             Log.logJS(indent + name + "<array>");
217             JS.Array na = (JS.Array)o;
218             for(int i=0; i<na.length(); i++)
219                 recurse(indent + "  ", i + "", na.elementAt(i));
220
221         } else if (o instanceof JS) {
222             Log.logJS(indent + name + "<object>");
223             JS s = (JS)o;
224             Object[] keys = s.keys();
225             for(int i=0; i<keys.length; i++)
226                 if (keys[i] != null)
227                     recurse(indent + "  ", keys[i].toString(),
228                             (keys[i] instanceof Integer) ?
229                             s.get(((Integer)keys[i])) : s.get(keys[i].toString()));
230
231         } else {
232             Log.logJS(indent + name + o);
233
234         }
235     }
236
237     public static void sleep(final int i) {
238         final JS.Thread jsthread = JS.Thread.current();
239         final long currentTime = System.currentTimeMillis();
240         final Scheduler.Task task = new Scheduler.Task() { public void perform() {
241             if (System.currentTimeMillis() - currentTime < i) Scheduler.add(this);
242             else jsthread.resume();
243         } };
244         jsthread.pause();
245         Scheduler.add(task);
246     }
247     
248     private static class XWTMath extends org.xwt.js.Math {
249         public XWTMath() {
250             JS gs = new JS.GlobalScope();
251             put("isNaN",gs.get("isNaN"));
252             put("isFinite",gs.get("isFinite"));
253             put("NaN",gs.get("NaN"));
254             put("Infinity",gs.get("Infinity"));
255             setSeal(true);
256         }
257         public Object get(Object key) {
258             Object ret = super.get(key);
259             if(ret == null) ret = JS.Math.get(key);
260             return ret;
261         }
262     }
263     private static class XWTString extends JS.Obj {
264         public XWTString() {
265             JS gs = new JS.GlobalScope();
266             put("parseInt",gs.get("parseInt"));
267             put("parseFloat",gs.get("parseFloat"));
268             put("decodeURI",gs.get("decodeURI"));
269             put("decodeURIComponent",gs.get("decodeURIComponent"));
270             put("encodeURI",gs.get("encodeURI"));
271             put("encodeURIComponent",gs.get("encodeURIComponent"));
272             put("escape",gs.get("escape"));
273             put("unescape",gs.get("unescape"));
274             put("fromCharCode",gs.get("stringFromCharCode"));
275             setSeal(true);
276         }
277     }
278 }