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