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