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