b73a1fb0d32ef93d01ca0b54b1f1dfbef8055205
[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             return new Regexp(args);
113         }});
114
115         super.put("listfonts", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
116             Object[] fonts = Platform.listFonts();
117             JS.Array ret = new JS.Array();
118             for(int i=0; i<fonts.length; i++) ret.addElement(fonts[i]);
119             return ret;
120         }});
121
122         super.put("xmlrpc", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
123             if (args.length() != 1 || args.elementAt(0) == null) return null;
124             return new XMLRPC(args.elementAt(0).toString(), "");
125         }});
126
127         super.put("soap", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
128             if (args.length() == 1 && args.elementAt(0) != null) return new SOAP(args.elementAt(0).toString(), "", null, null);
129             else if (args.length() == 2 && args.elementAt(0) != null && args.elementAt(1) != null)
130                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), null);
131             else if (args.length() == 3 && args.elementAt(0) != null && args.elementAt(1) != null && args.elementAt(2) != null)
132                 return new SOAP(args.elementAt(0).toString(), "", args.elementAt(1).toString(), args.elementAt(2).toString());
133             else return null;
134         }});
135
136         super.put("textwidth", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
137             if (args.length() < 1 || args.length() > 2) return null;
138             if (args.elementAt(0) == null || (args.length() == 2 && args.elementAt(1) == null)) return null;
139             String font = args.length() == 1 ? Platform.getDefaultFont() : args.elementAt(0).toString();
140             String text = args.length() == 1 ? args.elementAt(0).toString() : args.elementAt(1).toString();
141             XWF xwf = XWF.getXWF(font);
142             if (xwf == null) return new Integer(Platform.stringWidth(font, text));
143             else return new Integer(xwf.stringWidth(text));
144         }});
145
146         super.put("textheight", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
147             if (args.length() > 1) return null;
148             if (args.length() == 1 && args.elementAt(0) == null) return null;
149             String font = args.length() == 0 || args.elementAt(0) == null ? Platform.getDefaultFont() : args.elementAt(0).toString();
150             XWF xwf = XWF.getXWF(font);
151             if (xwf == null) return new Integer(Platform.getMaxAscent(font) + Platform.getMaxDescent(font));
152             else return new Integer(xwf.getMaxAscent() + xwf.getMaxDescent());
153         }});
154         
155         super.put("newBox", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
156             if (args.length() > 0) Log.log(XWT.class, "DEPRECATED: xwt.newBox() with multiple arguments is deprecated; use xwt.newBox().apply()");
157             JS.Callable callback = null;
158             for(int i=1; i<args.length(); i++)
159                 if (args.elementAt(i) instanceof JS.Callable && callback == null)
160                     callback = (JS.Callable)args.elementAt(i);
161             Box ret = new Box(args.length() == 0 || args.elementAt(0) == null ? "box" : args.elementAt(0).toString(),
162                               Template.defaultImportList, callback);
163             for(int i=1; i<args.length(); i++)
164                 if (args.elementAt(i) instanceof Box)
165                     ret.put(ret.numChildren(), (Box)args.elementAt(i));
166             for(int i=1; i<args.length(); i++)
167                 if (args.elementAt(i) instanceof JS && !(args.elementAt(i) instanceof Box) && !(args.elementAt(i) instanceof JS.Callable)) {
168                     JS s = (JS)args.elementAt(i);
169                     Object[] keys = s.keys();
170                     for(int j=0; j<keys.length; j++) ret.put(keys[j].toString(), s.get(keys[j].toString()));
171                 }
172             return ret;
173         }});
174
175         super.put("sleep", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
176             if (args != null && (args.length() != 1 || args.elementAt(0) == null)) return null;
177             int i = args == null ? 0 : SpecialBoxProperty.stoi(args.elementAt(0).toString());
178             sleep(i);
179             return null;
180         }});
181
182         super.put("openFile", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
183             if (args.length() != 1) return null;
184             String file = Platform.fileDialog(args.elementAt(0).toString(), false);
185             return file == null ? null : new ByteStream(file);
186         }});
187
188         super.put("saveFile", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
189             if (args.length() != 2) return null;
190             if (!(args.elementAt(1) instanceof ByteStream)) return null;
191             String file = args.elementAt(0).toString();
192             if (safeFiles.get(Platform.isCaseSensitive() ? file : file.toLowerCase()) == null) {
193                 file = Platform.fileDialog(file, true);
194                 if (file == null) return null;
195                 safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
196             }
197             try {
198                 ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
199                 return null;
200             } catch (IOException e) {
201                 if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
202                 if (Log.on) Log.log(ByteStream.class, e);
203                 throw new JS.Exn("error while writing a ByteStream to a file");
204             }
205         }});
206
207         super.put("saveFileAs", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
208             if (args.length() != 2) return null;
209             if (!(args.elementAt(1) instanceof ByteStream)) return null;
210             String file = args.elementAt(0).toString();
211             file = Platform.fileDialog(file, true);
212             if (file == null) return null;
213             safeFiles.put(Platform.isCaseSensitive() ? file : file.toLowerCase(), new Object());
214             try {
215                 ((ByteStream)args.elementAt(1)).writeTo(new FileOutputStream(file));
216                 return null;
217             } catch (IOException e) {
218                 if (Log.on) Log.log(ByteStream.class, "IO Exception while writing a ByteStream to a file");
219                 if (Log.on) Log.log(ByteStream.class, e);
220                 throw new JS.Exn("error while writing a ByteStream to a file");
221             }
222         }});
223
224         super.put("utfEncode", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
225             if (args == null || args.length() != 1) return null;
226             return new ByteStream(args.elementAt(0).toString().getBytes());
227         }});
228
229         super.put("parseHTML", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
230                 if (args == null || args.length() != 1 || args.elementAt(0) == null) return null;
231                 try {
232                     if (args.elementAt(0) instanceof ByteStream) {
233                         return HTML.parseReader(new InputStreamReader(((ByteStream)args.elementAt(0)).getInputStream()));
234                     } else {
235                         return HTML.parseReader(new StringReader(args.elementAt(0).toString()));
236                     }
237                 } catch (IOException e) {
238                     if (Log.on) Log.log(HTML.class, "IO Exception while parsing HTML");
239                     if (Log.on) Log.log(HTML.class, e);
240                     throw new JS.Exn("error while parsing HTML");
241                 }
242             }
243         });
244     
245     super.put("recursivePrintObject", new JS.Callable() { public Object call(JS.Array args) {
246         if (args.length() != 1) return null;
247         recurse("", "", args.elementAt(0));
248         return null;
249     }});
250
251     super.put("loadArchive", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
252         if (!ThreadMessage.suspendThread()) return null;
253         try {
254             if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
255             URL u = new URL(args.elementAt(0).toString());
256             
257             JS.Callable callback = null;
258             if (args.length() == 2 && args.elementAt(1) != null && args.elementAt(1) instanceof JS.Callable)
259                 callback = (JS.Callable)args.elementAt(1);
260             
261             if (!u.getFile().endsWith(".xwar")) {
262                 if (Log.on) Log.log(this, "Error: archive names must end with .xwar: " + u.getFile());
263                 throw new JS.Exn("Error: archive names must end with .xwar: " + u.getFile());
264             }
265             
266             if (u.getProtocol().equals("http")) {
267                 HTTP http = new HTTP(u.toString());
268                 if (Main.originAddr == null) {
269                     try {
270                         Main.originAddr = InetAddress.getByName(u.getHost());
271                     } catch (UnknownHostException e) {
272                         if (Log.on) Log.log(this, "couldn't resolve " + u.getHost() + "; proceeding without permissions");
273                         Main.originAddr = InetAddress.getByName("0.0.0.0");
274                     }
275                 } else {
276                     Main.originAddr = InetAddress.getByName("0.0.0.0");
277                 }
278                 HTTP.HTTPInputStream in = http.GET();
279                 Resources.loadArchive(in, in.getContentLength(), callback);
280                 
281             } else if (u.getProtocol().equals("file")) {
282                 if (Main.originAddr != null) {
283                     if (Log.on) Log.log(this, "scripts downloaded from the network may not load xwars from the local filesystem");
284                     throw new JS.Exn("scripts downloaded from the network may not load xwars from the local filesystem");
285                 }
286                 Resources.loadArchive(new FileInputStream(u.getFile()), (int)new File(u.getFile()).length(), callback);
287                 
288             } else {
289                 if (Log.on) Log.log(this, "unknown protocol \"" + u.getProtocol() + "\"");
290                 throw new JS.Exn("unknown protocol \"" + u.getProtocol() + "\"");
291             }
292             
293         } catch (MalformedURLException me) {
294             if (Log.on) Log.log(this, "Malformed URL: " + args.elementAt(0));
295             if (Log.on) Log.log(this, me);
296             throw new JS.Exn(me.toString());
297             
298         } catch (IOException ioe) {
299             if (Log.on) Log.log(this, "IOException while loading archive:");
300             if (Log.on) Log.log(this, ioe);
301             throw new JS.Exn(ioe.toString());
302             
303         } finally {
304             ThreadMessage.resumeThread();
305             
306         }
307         return null;
308     }});
309
310     super.put("prefetchImage", new JS.Callable() { public Object call(JS.Array args) throws JS.Exn {
311         if (args == null || args.length() < 1 || args.elementAt(0) == null) return null;
312         Box.getImage(args.elementAt(0).toString(),
313                      args.length() > 1 && args.elementAt(1) instanceof JS.Callable ? (JS.Callable)args.elementAt(1) : null);
314         return null;
315     }});
316     }
317
318     private static void recurse(String indent, String name, Object o) {
319         if (!name.equals("")) name += " : ";
320
321         if (o == null) {
322             Log.logJS(indent + name + "<null>");
323
324         } else if (o instanceof JS.Array) {
325             Log.logJS(indent + name + "<array>");
326             JS.Array na = (JS.Array)o;
327             for(int i=0; i<na.length(); i++)
328                 recurse(indent + "  ", i + "", na.elementAt(i));
329
330         } else if (o instanceof JS) {
331             Log.logJS(indent + name + "<object>");
332             JS s = (JS)o;
333             Object[] keys = s.keys();
334             for(int i=0; i<keys.length; i++)
335                 recurse(indent + "  ", keys[i].toString(),
336                         (keys[i] instanceof Integer) ?
337                         s.get(((Integer)keys[i])) : s.get(keys[i].toString()));
338
339         } else {
340             Log.logJS(indent + name + o);
341
342         }
343     }
344
345
346     public static void sleep(int i) {
347         java.lang.Thread thread = java.lang.Thread.currentThread();
348         if (!(thread instanceof ThreadMessage)) {
349             if (Log.on) Log.log(XWT.class, "cannot sleep() or yield() in the foreground thread");
350         } else {
351             ThreadMessage mythread = (ThreadMessage)thread;
352             mythread.done.release();
353             if (i > 0) try { java.lang.Thread.sleep(i); } catch (Exception e) { }
354             MessageQueue.add(mythread);
355             mythread.go.block();
356         }
357     }
358 }
359
360
361
362
363
364
365
366