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