2002/08/18 10:55:12
[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 if (name.equals("prefs")) return prefs;
69         else if (name.equals("encodeURI")) return JSObject.defaultObjects.get("encodeURI", null);
70         else if (name.equals("encodeURIComponent")) return JSObject.defaultObjects.get("encodeURIComponent", null);
71         else if (name.equals("decodeURI")) return JSObject.defaultObjects.get("decodeURI", null);
72         else if (name.equals("decodeURIComponent")) return JSObject.defaultObjects.get("decodeURIComponent", null);
73         else return super.get(name, start);
74     }
75
76     public void put(String name, Scriptable start, Object value) {
77         if (name == null) return;
78         else if (name.equals("thread") && value != null && value instanceof Function) ThreadMessage.newthread((Function)value);
79         else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
80
81         // FIXME: undocumented, possibly insecure
82         else if (name.equals("proxyAuthorization")) {
83             Proxy.Authorization.authorization = value.toString();
84             Proxy.Authorization.waitingForUser.release();
85         }
86
87         else super.put(name, start, value);
88     }
89
90
91     // Prefs Object //////////////////////////////////////////////////////////////////////////
92
93     static Scriptable prefsRPC = new XMLRPC("http://megacz:mypassword@localhost/RPC2", "prefs");
94
95     private static final JSObject prefs = new JSObject(false, true) {
96             public Object get(String name, Scriptable start) {
97                 if (name.equals("get")) return prefsGet;
98                 else if (name.equals("list")) return prefsList;
99                 else if (name.equals("put")) return prefsPut;
100                 else return null;
101             }
102         };
103
104     private static final JSObject.JSFunction prefsGet = new JSObject.JSFunction() {
105             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
106                 if (args.length != 1 || args[0] == null) return null;
107                 try {
108                     return ((Function)prefsRPC.get("get", null)).call(cx, null, null, new Object[] { args[0] });
109                 } catch (JavaScriptException jse) {
110                     Object val = jse.getValue();
111                     if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
112                         return null;
113                     throw jse;
114                 } catch (Exception e) {
115                     // FIXME
116                     throw new JavaScriptException(e.toString());
117                 }
118             }
119         };
120
121     private static final JSObject.JSFunction prefsPut = new JSObject.JSFunction() {
122             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
123                 if (args.length < 2 || args[0] == null) return null;
124                 try {
125                     return ((Function)prefsRPC.get("put", null)).call(cx, null, null, new Object[] { args[0].toString(), args[1] });
126                 } catch (JavaScriptException jse) {
127                     Object val = jse.getValue();
128                     if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
129                         return null;
130                     throw jse;
131                 } catch (Exception e) {
132                     // FIXME
133                     throw new JavaScriptException(e.toString());
134                 }
135             }
136         };
137
138     private static final JSObject.JSFunction prefsList = new JSObject.JSFunction() {
139             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
140                 if (args.length < 2 || args[0] == null) return null;
141                 try {
142                     return ((Function)prefsRPC.get("list", null)).call(cx, null, null, new Object[] { args[0].toString(), args[1] });
143                 } catch (JavaScriptException jse) {
144                     Object val = jse.getValue();
145                     if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
146                         return null;
147                     throw jse;
148                 } catch (Exception e) {
149                     // FIXME
150                     throw new JavaScriptException(e.toString());
151                 }
152             }
153         };
154
155     private static final JSObject.JSFunction prefsInvoke = new JSObject.JSFunction() {
156             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
157                 if (args.length < 2 || args[0] == null) return null;
158                 try {
159                     return ((Function)prefs.get("invoke")).call(cx, null, null, new Object[] { args[0].toString(), args[1], "megacz", "mypassword" });
160                 } catch (JavaScriptException jse) {
161                     Object val = jse.getValue();
162                     if (val instanceof JSObject && new Integer(1).equals(((JSObject)val).get("faultCode")))
163                         return null;
164                     throw jse;
165                 } catch (Exception e) {
166                     // FIXME
167                     throw new JavaScriptException(e.toString());
168                 }
169             }
170         };
171
172
173
174     // JSFunction Instances ///////////////////////////////////////////////////////////////////
175
176     private static final JSObject.JSFunction newBrowserWindow = new JSObject.JSFunction() {
177             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
178                 if (args.length != 1 || args[0] == null) return null;
179                 Platform.newBrowserWindow(args[0].toString());
180                 return null;
181             }
182         };
183
184     public static final JSObject.JSFunction yield = new JSObject.JSFunction() {
185             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
186                 sleep.call(cx, null, null, null);
187                 return null;
188             }
189         };
190
191     private static final JSObject.JSFunction println = new JSObject.JSFunction() {
192             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
193                 if (args.length == 1)
194                     if (Log.on) {
195                         String source = cx.interpreterSourceFile;
196                         if (source.endsWith("._")) source = source.substring(0, source.length() - 2);
197                         Log.log(source, args[0] == null ? "null" : args[0].toString());
198                     }
199                 return null;
200             }
201         };
202
203     private static final JSObject.JSFunction date = new JSObject.JSFunction() {
204             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
205                 try { return Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date", args);
206                 } catch (Exception e) {
207                     if (Log.on) Log.log(this, "Exception in Context.newObject() -- this should never happen");
208                     if (Log.on) Log.log(this, e);
209                     return null;
210                 }
211             }
212         };
213
214     private static final JSObject.JSFunction regexp = new JSObject.JSFunction() {
215             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
216                 try { return Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "RegExp", args);
217                 } catch (Exception e) {
218                     if (Log.on) Log.log(this, "Exception in Context.newObject() -- this should never happen");
219                     if (Log.on) Log.log(this, e);
220                     return null;
221                 }
222             }
223         };
224
225     private static final JSObject.JSFunction listfonts = new JSObject.JSFunction() {
226             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
227                 return Context.enter().newArray(org.xwt.util.JSObject.defaultObjects,  Platform.listFonts());
228             }
229         };
230
231     private static final JSObject.JSFunction theme = new JSObject.JSFunction() {
232             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
233                 if (args.length != 2) return null;
234                 if (args[0] == null || args[1] == null) return null;
235                 Template.retheme(args[0].toString(), args[1].toString());
236                 return null;
237             }
238         };
239
240     private static final JSObject.JSFunction xmlrpc = new JSObject.JSFunction() {
241             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
242                 if (args.length != 1 || args[0] == null) return null;
243                 return new XMLRPC(args[0].toString(), "");
244             }
245         };
246
247     private static final JSObject.JSFunction soap = new JSObject.JSFunction() {
248             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
249                 if (args.length == 1 && args[0] != null) return new SOAP(args[0].toString(), "", null, null);
250                 else if (args.length == 2 && args[0] != null && args[1] != null)
251                     return new SOAP(args[0].toString(), "", args[1].toString(), null);
252                 else if (args.length == 3 && args[0] != null && args[1] != null && args[2] != null)
253                     return new SOAP(args[0].toString(), "", args[1].toString(), args[2].toString());
254                 else return null;
255             }
256         };
257
258     private static final JSObject.JSFunction textwidth = new JSObject.JSFunction() {
259             public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException {
260                 if (args.length < 1 || args.length > 2) return null;
261                 if (args[0] == null || (args.length == 2 && args[1] == null)) return null;
262                 String font = args.length == 1 ? Platform.getDefaultFont() : args[0].toString();
263                 String text = args.length == 1 ? args[0].toString() : args[1].toString();
264                 XWF xwf = XWF.getXWF(font);
265                 if (xwf == null) return new Integer(Platform.stringWidth(font, text));
266                 else return new Integer(xwf.stringWidth(text));
267             }
268         };
269
270
271     private static final JSObject.JSFunction textheight = new JSObject.JSFunction() {
272             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
273                 if (args.length > 1) return null;
274                 if (args.length == 1 && args[0] == null) return null;
275                 String font = args.length == 0 || args[0] == null ? Platform.getDefaultFont() : args[0].toString();
276                 XWF xwf = XWF.getXWF(font);
277                 if (xwf == null) return new Integer(Platform.getMaxAscent(font) + Platform.getMaxDescent(font));
278                 else return new Integer(xwf.getMaxAscent() + xwf.getMaxDescent());
279             }
280         };
281
282     private static final JSObject.JSFunction newBox = new JSObject.JSFunction() {
283             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
284
285                 if (args.length > 0)
286                     if (Log.on) Log.log(XWT.class, "DEPRECATED: xwt.newBox() with multiple arguments is deprecated; use xwt.newBox().apply() " +
287                                         Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
288
289                 Function callback = null;
290                 for(int i=1; i<args.length; i++)
291                     if (args[i] instanceof Function && callback == null)
292                         callback = (Function)args[i];
293
294                 Box ret = new Box(args.length == 0 || args[0] == null ? "box" : args[0].toString(), Template.defaultImportList, callback);
295
296                 for(int i=1; i<args.length; i++)
297                     if (args[i] instanceof Box)
298                         ret.put(ret.numChildren(), null, (Box)args[i]);
299                 for(int i=1; i<args.length; i++)
300                     if (args[i] instanceof Scriptable && !(args[i] instanceof Box) && !(args[i] instanceof Function)) {
301                         Scriptable s = (Scriptable)args[i];
302                         Object[] keys = s.getIds();
303
304                         // FIXME: need to ensure that this is putGlobally(), but still run traps...
305                         for(int j=0; j<keys.length; j++) ret.put(keys[j].toString(), null, s.get(keys[j].toString(), s));
306                     }
307                 return ret;
308             }
309         };
310
311     private static final JSObject.JSFunction sleep = new JSObject.JSFunction() {
312             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
313                 if (args != null && (args.length != 1 || args[0] == null)) return null;
314                 int i = args == null ? 0 : SpecialBoxProperty.stoi(args[0].toString());
315
316                 Thread thread = Thread.currentThread();
317                 if (!(thread instanceof ThreadMessage)) {
318                     if (Log.on) Log.log(this, "cannot sleep() or yield() in the foreground thread");
319                     return null;
320                 }
321                 ThreadMessage mythread = (ThreadMessage)thread;
322                 mythread.done.release();
323
324                 if (i > 0) try { Thread.sleep(i); } catch (Exception e) { }
325                 
326                 MessageQueue.add(mythread);
327                 mythread.go.block();
328                 return null;
329             }
330         };
331
332     private static final JSObject.JSFunction openFile = new JSObject.JSFunction() {
333             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
334                 if (args.length != 1) return null;
335                 String file = Platform.fileDialog(args[0].toString(), false);
336                 return file == null ? null : new ByteStream(file);
337             }
338         };
339
340     private static final JSObject.JSFunction saveFile = new JSObject.JSFunction() {
341             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
342                 if (args.length != 2) return null;
343                 if (!(args[1] instanceof ByteStream)) return null;
344                 String file = args[0].toString();
345                 if (safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
346                     file = Platform.fileDialog(file, true);
347                     if (file == null) return null;
348                     safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
349                 }
350                 try {
351                     ((ByteStream)args[1]).writeTo(new FileOutputStream(file));
352                     return null;
353                 } catch (IOException e) {
354                     if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
355                     if (Log.on) Log.log(ByteStream.class, e);
356                     throw new JavaScriptException("error while writing a ByteStream to a file");
357                 }
358             }
359         };
360
361     private static final JSObject.JSFunction saveFileAs = new JSObject.JSFunction() {
362             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
363                 if (args.length != 2) return null;
364                 if (!(args[1] instanceof ByteStream)) return null;
365                 String file = args[0].toString();
366                 file = Platform.fileDialog(file, true);
367                 if (file == null) return null;
368                 safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
369                 try {
370                     ((ByteStream)args[1]).writeTo(new FileOutputStream(file));
371                     return null;
372                 } catch (IOException e) {
373                     if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
374                     if (Log.on) Log.log(ByteStream.class, e);
375                     throw new JavaScriptException("error while writing a ByteStream to a file");
376                 }
377             }
378         };
379
380     private static final JSObject.JSFunction utfEncode = new JSObject.JSFunction() {
381             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
382                 if (args == null || args.length != 1) return null;
383                 return new ByteStream(args[0].toString().getBytes());
384             }
385         };
386
387     
388     private static final JSObject.JSFunction parseHTML = new JSObject.JSFunction() {
389             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
390                 if (args == null || args.length != 1 || args[0] == null) return null;
391                 try {
392                     if (args[0] instanceof ByteStream) {
393                         return HTML.parseReader(new InputStreamReader(((ByteStream)args[0]).getInputStream()));
394                     } else {
395                         return HTML.parseReader(new StringReader(args[0].toString()));
396                     }
397                 } catch (IOException e) {
398                     if (Log.on) Log.log(HTML.class, "IO Exception while parsing HTML");
399                     if (Log.on) Log.log(HTML.class, e);
400                     throw new JavaScriptException("error while parsing HTML");
401                 }
402             }
403         };
404     
405     private static void recurse(String indent, String name, Object o, Context cx) {
406         if (!name.equals("")) name += " : ";
407
408         if (o == null) {
409             Log.log(cx.interpreterSourceFile, indent + name + "<null>");
410
411         } else if (o instanceof NativeArray) {
412             Log.log(cx.interpreterSourceFile, indent + name + "<array>");
413             NativeArray na = (NativeArray)o;
414             for(int i=0; i<na.jsGet_length(); i++)
415                 recurse(indent + "  ", i + "", na.get(i, null), cx);
416
417         } else if (!(o instanceof NativeDate) && (o instanceof JSObject || o instanceof ScriptableObject)) {
418             Log.log(cx.interpreterSourceFile, indent + name + "<object>");
419             Scriptable s = (Scriptable)o;
420             Object[] keys = s.getIds();
421             for(int i=0; i<keys.length; i++)
422                 recurse(indent + "  ", keys[i].toString(),
423                         keys[i] instanceof Integer ? s.get(((Integer)keys[i]).intValue(), null) : s.get(keys[i].toString(), null), cx);
424
425         } else {
426             Log.log(cx.interpreterSourceFile, indent + name + o);
427
428         }
429     }
430
431     private static final JSObject.JSFunction recursivePrintObject = new JSObject.JSFunction() {
432             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
433                 if (args == null || args.length != 1) return null;
434                 recurse("", "", args[0], cx);
435                 return null;
436             }
437         };
438
439     private static final JSObject.JSFunction loadArchive = new JSObject.JSFunction() {
440             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
441                 if (!ThreadMessage.suspendThread()) return null;
442
443                 try {
444                     if (args == null || args.length < 1 || args[0] == null) return null;
445                     URL u = new URL(args[0].toString());
446                     
447                     Function callback = null;
448                     if (args.length == 2 && args[1] != null && args[1] instanceof Function) callback = (Function)args[1];
449                     
450                     if (!u.getFile().endsWith(".xwar")) {
451                         if (Log.on) Log.log(this, "Error: archive names must end with .xwar: " + u.getFile());
452                         throw new JavaScriptException("Error: archive names must end with .xwar: " + u.getFile());
453                     }
454                     
455                     if (u.getProtocol().equals("http")) {
456                         HTTP http = new HTTP(u.toString());
457                         if (Main.originAddr == null) {
458                             try {
459                                 Main.originAddr = InetAddress.getByName(u.getHost());
460                             } catch (UnknownHostException e) {
461                                 if (Log.on) Log.log(this, "couldn't resolve " + u.getHost() + "; proceeding without permissions");
462                                 Main.originAddr = InetAddress.getByName("0.0.0.0");
463                             }
464                         } else {
465                             Main.originAddr = InetAddress.getByName("0.0.0.0");
466                         }
467                         HTTP.HTTPInputStream in = http.GET();
468                         Resources.loadArchive(in, in.getContentLength(), callback);
469
470                     } else if (u.getProtocol().equals("file")) {
471                         if (Main.originAddr != null) {
472                             if (Log.on) Log.log(this, "scripts downloaded from the network may not load xwars from the local filesystem");
473                             throw new JavaScriptException("scripts downloaded from the network may not load xwars from the local filesystem");
474                         }
475                         Resources.loadArchive(new FileInputStream(u.getFile()), (int)new File(u.getFile()).length(), callback);
476                         
477                     } else {
478                         if (Log.on) Log.log(this, "unknown protocol \"" + u.getProtocol() + "\"");
479                         throw new JavaScriptException("unknown protocol \"" + u.getProtocol() + "\"");
480                     }
481                     
482                 } catch (MalformedURLException me) {
483                     if (Log.on) Log.log(this, "Malformed URL: " + args[0]);
484                     if (Log.on) Log.log(this, me);
485                     throw new JavaScriptException(me.toString());
486                     
487                 } catch (IOException ioe) {
488                     if (Log.on) Log.log(this, "IOException while loading archive:");
489                     if (Log.on) Log.log(this, ioe);
490                     throw new JavaScriptException(ioe.toString());
491
492                 } finally {
493                     ThreadMessage.resumeThread();
494
495                 }
496                 return null;
497             }
498         };
499
500     private static final JSObject.JSFunction prefetchImage = new JSObject.JSFunction() {
501             public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
502                 if (args == null || args.length < 1 || args[0] == null) return null;
503                 Box.getImage(args[0].toString(), args.length > 1 && args[1] instanceof Function ? (Function)args[1] : null);
504                 return null;
505             }
506         };
507
508 }
509
510
511
512
513