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