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