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