2003/07/07 04:41:01
[org.ibex.core.git] / src / org / xwt / XWT.java
1 // Copyright 2002 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.bouncycastle.util.encoders.Base64;
11
12 /** Singleton class that provides all functionality in the xwt.* namespace */
13 public final class XWT extends JS.Obj {
14
15     public static final XWT singleton = new XWT();
16     private final JS xwtMath = new XWTMath();
17     private final JS xwtString = new XWTString();
18
19     /** each key is a string representing a filename which the user has already given XWT permission to write to */
20     private static Hashtable safeFiles = new Hashtable();
21
22     public Object get(Object name) {
23         if (name.equals("alt")) return Surface.alt ? Boolean.TRUE : Boolean.FALSE;
24         else if (name.equals("control")) return Surface.control ? Boolean.TRUE : Boolean.FALSE;
25         else if (name.equals("shift")) return Surface.shift ? Boolean.TRUE : Boolean.FALSE;
26         else if (name.equals("clipboard")) return Platform.getClipBoard();
27         else if (name.equals("static")) return Static.getStatic("");
28         else if (name.equals("button")) {
29             if (Surface.button1 && !Surface.button2 && !Surface.button3) return new Integer(1);
30             else if (!Surface.button1 && Surface.button2 && !Surface.button3) return new Integer(1);
31             else if (!Surface.button1 && !Surface.button2 && Surface.button3) return new Integer(1);
32             else return new Integer(0);
33         }
34         else if (name.equals("encodeURI")) throw new Error("not implemented");
35         else if (name.equals("encodeURIComponent")) throw new Error("not implemented");
36         else if (name.equals("decodeURI")) throw new Error("not implemented");
37         else if (name.equals("decodeURIComponent")) throw new Error("not implemented");
38         else return super.get(name);
39     }
40
41     public void put(Object name, Object value) {
42         if (name.equals("thread") && value != null && value instanceof JS.Callable) ThreadMessage.newthread((JS.Callable)value);
43         else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
44         else if (name.equals("proxyAuthorization")) {
45             // FIXME: undocumented, possibly insecure
46             Proxy.Authorization.authorization = value.toString();
47             Proxy.Authorization.waitingForUser.release();
48         } else super.put(name, value);
49     }
50
51     private XWT() {
52         super.put("maxdim", new Integer(Short.MAX_VALUE));
53         super.put("origin", Main.origin);
54         super.put("altKeyName", Platform.altKeyName());
55         super.put("screenWidth", new Integer(Platform.getScreenWidth()));
56         super.put("screenHeight", new Integer(Platform.getScreenHeight()));
57         super.put("fileSeparator", File.separator);
58         super.put("homeDir", System.getProperty("user.home"));
59         super.put("tempDir", System.getProperty("java.io.tempdir"));
60         super.put("math", xwtMath);
61         super.put("string", xwtString);
62
63         super.put("newBrowserWindow", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
64             if (args.length() != 1 || args.elementAt(0) == null) return null;
65             Platform.newBrowserWindow(args.elementAt(0).toString());
66             return null;
67         }});
68
69         super.put("parseFloat", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
70             if (args.length() != 1 || args.elementAt(0) == null) return null;
71             return new Float(args.elementAt(0).toString());
72         }});
73
74         super.put("parseInt", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
75             if (args.length() != 1 || args.elementAt(0) == null) return null;
76             return new Float(args.elementAt(0).toString());
77         }});
78
79         super.put("yield", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
80             sleep(0);
81             return null;
82         }});
83
84         super.put("theme", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
85                 if (args.length() != 2) return null;
86                 if (args.elementAt(0) == null || args.elementAt(1) == null) return null;
87                 for(int i=1; i<args.length(); i++) {
88                     if (args.elementAt(i) instanceof String) {
89                         String from = (String)args.elementAt(0);
90                         String to = (String)args.elementAt(i);
91                         if (Log.on) Log.log(this, "retheming from " + from + " to " + to);
92                         Resources.mapFrom.addElement(from);
93                         Resources.mapTo.addElement(to);
94                     }
95                 }
96                 JS.Callable callback = args.elementAt(args.length() - 1) instanceof JS.Callable ?
97                     (JS.Callable)args.elementAt(args.length() - 1) : null;
98                 Template.retheme(callback);
99                 return null;
100         }});
101             
102         super.put("println", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
103             if (args.length() != 1) return null;
104             if (Log.on) Log.logJS(this, (args.elementAt(0) == null ? "**null**" : args.elementAt(0).toString()));
105             return null;
106         }});
107
108         super.put("date", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
109             Log.log(XWT.class, "date not implemented");
110             //throw new Error("not implemented");
111             return null;
112         }});
113
114         super.put("regexp", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
115             return new Regexp(args);
116         }});
117
118         super.put("listfonts", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
119             Object[] fonts = Platform.listFonts();
120             JS.Array ret = new JS.Array();
121             for(int i=0; i<fonts.length; i++) ret.addElement(fonts[i]);
122             return ret;
123         }});
124
125         super.put("xmlrpc", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
126             if (args.length() != 1 || args.elementAt(0) == null) return null;
127             return new XMLRPC(args.elementAt(0).toString(), "");
128         }});
129
130         super.put("soap", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
131             if (args.length() == 1 && args.elementAt(0) != null) return new SOAP(args.elementAt(0).toString(), "", null, null);
132             else if (args.length() == 2 && args.elementAt(0) != null && args.elementAt(1) != null)
133                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), null);
134             else if (args.length() == 3 && args.elementAt(0) != null && args.elementAt(1) != null && args.elementAt(2) != null)
135                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), args.elementAt(2).toString());
136             else return null;
137         }});
138
139         super.put("textwidth", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
140             if (args.length() < 1 || args.length() > 2) return null;
141             if (args.elementAt(0) == null || (args.length() == 2 && args.elementAt(1) == null)) return null;
142             String font = args.length() == 1 ? Platform.getDefaultFont() : args.elementAt(0).toString();
143             String text = args.length() == 1 ? args.elementAt(0).toString() : args.elementAt(1).toString();
144             XWF xwf = XWF.getXWF(font);
145             if (xwf == null) return new Integer(Platform.stringWidth(font, text));
146             else return new Integer(xwf.stringWidth(text));
147         }});
148
149         super.put("textheight", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
150             if (args.length() > 1) return null;
151             if (args.length() == 1 && args.elementAt(0) == null) return null;
152             String font = args.length() == 0 || args.elementAt(0) == null ? Platform.getDefaultFont() : args.elementAt(0).toString();
153             XWF xwf = XWF.getXWF(font);
154             if (xwf == null) return new Integer(Platform.getMaxAscent(font) + Platform.getMaxDescent(font));
155             else return new Integer(xwf.getMaxAscent() + xwf.getMaxDescent());
156         }});
157         
158         super.put("newBox", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
159             if (args.length() > 0) Log.log(XWT.class, "DEPRECATED: xwt.newBox() with multiple arguments is deprecated; use xwt.newBox().apply()");
160             JS.Callable callback = null;
161             for(int i=1; i<args.length(); i++)
162                 if (args.elementAt(i) instanceof JS.Callable && callback == null)
163                     callback = (JS.Callable)args.elementAt(i);
164             Box ret = new Box(args.length() == 0 || args.elementAt(0) == null ? "box" : args.elementAt(0).toString(),
165                               Template.defaultImportList, callback);
166             for(int i=1; i<args.length(); i++)
167                 if (args.elementAt(i) instanceof Box)
168                     ret.put(ret.numChildren(), (Box)args.elementAt(i));
169             for(int i=1; i<args.length(); i++)
170                 if (args.elementAt(i) instanceof JS && !(args.elementAt(i) instanceof Box) && !(args.elementAt(i) instanceof JS.Callable)) {
171                     JS s = (JS)args.elementAt(i);
172                     Object[] keys = s.keys();
173                     for(int j=0; j<keys.length; j++) ret.put(keys[j].toString(), s.get(keys[j].toString()));
174                 }
175             return ret;
176         }});
177
178         super.put("sleep", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
179             if (args != null && (args.length() != 1 || args.elementAt(0) == null)) return null;
180             int i = args == null ? 0 : SpecialBoxProperty.stoi(args.elementAt(0).toString());
181             sleep(i);
182             return null;
183         }});
184
185         super.put("openFile", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
186             if (args.length() != 1) return null;
187             String file = Platform.fileDialog(args.elementAt(0).toString(), false);
188             return file == null ? null : new ByteStream(file);
189         }});
190
191         super.put("saveFile", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
192             if (args.length() != 2) return null;
193             if (!(args.elementAt(1) instanceof ByteStream)) return null;
194             String file = args.elementAt(0).toString();
195             if (safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
196                 file = Platform.fileDialog(file, true);
197                 if (file == null) return null;
198                 safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
199             }
200             try {
201                 ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
202                 return null;
203             } catch (IOException e) {
204                 if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
205                 if (Log.on) Log.log(ByteStream.class, e);
206                 throw new JS.Exn("error while writing a ByteStream to a file");
207             }
208         }});
209
210         super.put("saveFileAs", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
211             if (args.length() != 2) return null;
212             if (!(args.elementAt(1) instanceof ByteStream)) return null;
213             String file = args.elementAt(0).toString();
214             file = Platform.fileDialog(file, true);
215             if (file == null) return null;
216             safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
217             try {
218                 ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
219                 return null;
220             } catch (IOException e) {
221                 if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
222                 if (Log.on) Log.log(ByteStream.class, e);
223                 throw new JS.Exn("error while writing a ByteStream to a file");
224             }
225         }});
226
227         super.put("utfEncode", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
228             if (args == null || args.length() != 1) return null;
229             return new ByteStream(args.elementAt(0).toString().getBytes());
230         }});
231
232         super.put("parseHTML", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
233                 if (args == null || args.length() != 1 || args.elementAt(0) == null) return null;
234                 try {
235                     if (args.elementAt(0) instanceof ByteStream) {
236                         return HTML.parseReader(new InputStreamReader(((ByteStream)args.elementAt(0)).getInputStream()));
237                     } else {
238                         return HTML.parseReader(new StringReader(args.elementAt(0).toString()));
239                     }
240                 } catch (IOException e) {
241                     if (Log.on) Log.log(HTML.class, "IO Exception while parsing HTML");
242                     if (Log.on) Log.log(HTML.class, e);
243                     throw new JS.Exn("error while parsing HTML");
244                 }
245             }
246         });
247     
248     super.put("recursivePrintObject", new JS.Callable() { public Object call(JS.Array args) {
249         if (args.length() != 1) return null;
250         recurse("", "", args.elementAt(0));
251         return null;
252     }});
253
254     super.put("loadArchive", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
255         if (!ThreadMessage.suspendThread()) return null;
256         try {
257             if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
258             URL u = new URL(args.elementAt(0).toString());
259             
260             JS.Callable callback = null;
261             if (args.length() == 2 && args.elementAt(1) != null && args.elementAt(1) instanceof JS.Callable)
262                 callback = (JS.Callable)args.elementAt(1);
263             
264             if (!u.getFile().endsWith(".xwar")) {
265                 if (Log.on) Log.log(this, "Error: archive names must end with .xwar: " + u.getFile());
266                 throw new JS.Exn("Error: archive names must end with .xwar: " + u.getFile());
267             }
268             
269             if (u.getProtocol().equals("http")) {
270                 HTTP http = new HTTP(u.toString());
271                 if (Main.originAddr == null) {
272                     try {
273                         Main.originAddr = InetAddress.getByName(u.getHost());
274                     } catch (UnknownHostException e) {
275                         if (Log.on) Log.log(this, "couldn't resolve " + u.getHost() + "; proceeding without permissions");
276                         Main.originAddr = InetAddress.getByName("0.0.0.0");
277                     }
278                 } else {
279                     Main.originAddr = InetAddress.getByName("0.0.0.0");
280                 }
281                 HTTP.HTTPInputStream in = http.GET();
282                 Resources.loadArchive(in, in.getContentLength(), callback);
283                 
284             } else if (u.getProtocol().equals("file")) {
285                 if (Main.originAddr != null) {
286                     if (Log.on) Log.log(this, "scripts downloaded from the network may not load xwars from the local filesystem");
287                     throw new JS.Exn("scripts downloaded from the network may not load xwars from the local filesystem");
288                 }
289                 Resources.loadArchive(new FileInputStream(u.getFile()), (int)new File(u.getFile()).length(), callback);
290                 
291             } else {
292                 if (Log.on) Log.log(this, "unknown protocol \"" + u.getProtocol() + "\"");
293                 throw new JS.Exn("unknown protocol \"" + u.getProtocol() + "\"");
294             }
295             
296         } catch (MalformedURLException me) {
297             if (Log.on) Log.log(this, "Malformed URL: " + args.elementAt(0));
298             if (Log.on) Log.log(this, me);
299             throw new JS.Exn(me.toString());
300             
301         } catch (IOException ioe) {
302             if (Log.on) Log.log(this, "IOException while loading archive:");
303             if (Log.on) Log.log(this, ioe);
304             throw new JS.Exn(ioe.toString());
305             
306         } finally {
307             ThreadMessage.resumeThread();
308             
309         }
310         return null;
311     }});
312
313     super.put("prefetchImage", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
314         if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
315         Box.getImage(args.elementAt(0).toString(),
316                      args.length() > 1 && args.elementAt(1) instanceof JS.Callable ? (JS.Callable)args.elementAt(1) : null);
317         return null;
318     }});
319     }
320
321     private static void recurse(String indent, String name, Object o) {
322         if (!name.equals("")) name += " : ";
323
324         if (o == null) {
325             Log.logJS(indent + name + "<null>");
326
327         } else if (o instanceof JS.Array) {
328             Log.logJS(indent + name + "<array>");
329             JS.Array na = (JS.Array)o;
330             for(int i=0; i<na.length(); i++)
331                 recurse(indent + "  ", i + "", na.elementAt(i));
332
333         } else if (o instanceof JS) {
334             Log.logJS(indent + name + "<object>");
335             JS s = (JS)o;
336             Object[] keys = s.keys();
337             for(int i=0; i<keys.length; i++)
338                 recurse(indent + "  ", keys[i].toString(),
339                         (keys[i] instanceof Integer) ?
340                         s.get(((Integer)keys[i])) : s.get(keys[i].toString()));
341
342         } else {
343             Log.logJS(indent + name + o);
344
345         }
346     }
347
348
349     public static void sleep(int i) {
350         java.lang.Thread thread = java.lang.Thread.currentThread();
351         if (!(thread instanceof ThreadMessage)) {
352             if (Log.on) Log.log(XWT.class, "cannot sleep() or yield() in the foreground thread");
353         } else {
354             ThreadMessage mythread = (ThreadMessage)thread;
355             mythread.done.release();
356             if (i > 0) try { java.lang.Thread.sleep(i); } catch (Exception e) { }
357             MessageQueue.add(mythread);
358             mythread.go.block();
359         }
360     }
361     
362     private static class XWTMath extends JS.Obj {
363         public XWTMath() {
364             JS gs = new JS.GlobalScope();
365             put("isNaN",gs.get("isNaN"));
366             put("isFinite",gs.get("isFinite"));
367             put("NaN",gs.get("NaN"));
368             put("Infinity",gs.get("Infinity"));
369             setSeal(true);
370         }
371         public Object get(Object key) {
372             Object ret = super.get(key);
373             if(ret == null) ret = JS.Math.get(key);
374             return ret;
375         }
376     }
377     private static class XWTString extends JS.Obj {
378         public XWTString() {
379             JS gs = new JS.GlobalScope();
380             put("parseInt",gs.get("parseInt"));
381             put("parseFloat",gs.get("parseFloat"));
382             put("decodeURI",gs.get("decodeURI"));
383             put("decodeURIComponent",gs.get("decodeURIComponent"));
384             put("encodeURI",gs.get("encodeURI"));
385             put("encodeURIComponent",gs.get("encodeURIComponent"));
386             setSeal(true);
387         }
388     }
389 }