2003/05/08 13:38:40
[org.ibex.core.git] / src / org / xwt / Platform.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.lang.reflect.*;
5 import java.net.*;
6 import java.io.*;
7 import java.util.*;
8 import org.xwt.util.*;
9
10 /** 
11  *  Abstracts away the small irregularities in JVM implementations.
12  *
13  *  The default Platform class supports a vanilla JDK 1.1
14  *  JVM. Subclasses are provided for other VMs. Methods whose names
15  *  start with an underscore are meant to be overridden by
16  *  subclasses. If you create a subclass of Platform, you should put
17  *  it in the org.xwt.plat package, and add code to this file's static
18  *  block to detect the new platform.
19  */
20 public class Platform {
21
22     // Static Data /////////////////////////////////////////////////////////////////////////////////////
23
24     /**
25      *  set to true during the delivery of a KeyPressed:C-v/A-v or Press3; it is safe to use a
26      *  'global' here, since message delivery is single-threaded and non-preemptable
27      */
28     static boolean clipboardReadEnabled = false;
29
30     /** The appropriate Platform object for this JVM */
31     static Platform platform = null;
32
33     /** true if proxy autodetection has already been run */
34     static boolean alreadyDetectedProxy = false;
35
36     /** the result of proxy autodetection */
37     static Proxy cachedProxyInfo = null;
38
39     /** the current build */
40     public static String build = "unknown";
41
42     // VM Detection Logic /////////////////////////////////////////////////////////////////////
43
44     /** do-nothing method that forces <clinit> to run */
45     public static void forceLoad() { }
46
47     // If you create a new subclass of Platform, you should add logic
48     // here to detect it. Do not reference your class directly -- use
49     // reflection.
50
51     static {
52         System.err.println("Detecting JVM...");
53         try {
54             String vendor = System.getProperty("java.vendor", "");
55             String version = System.getProperty("java.version", "");
56             String os_name = System.getProperty("os.name", "");
57             String os_version = System.getProperty("os.version", "");
58             String platform_class = null;
59             
60             if (os_name.startsWith("Darwin")) platform_class = "Carbon";
61             else if (vendor.startsWith("Free Software Foundation")) {
62                 if (os_name.startsWith("Window")) platform_class = "Win32";
63                 else platform_class = "X11";
64             } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
65             else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
66             else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java2";
67
68         // Disable 2d hardware acceleration on Jaguar
69         if (os_name.equals("Mac OS X") && os_version.equals("10.2"))
70         System.setProperty("com.apple.hwaccel", "false");
71
72             if (platform_class != null) {
73                 platform = (Platform)Class.forName("org.xwt.plat." + platform_class).newInstance();
74                 platform.init();
75             }
76
77             try {
78                 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
79             } catch (ClassNotFoundException cnfe) {
80             } catch (Exception e) {
81                 if (Log.on) Log.log(Platform.class, "exception while detecting build:");
82                 if (Log.on) Log.log(Platform.class, e);
83             }
84             if (Log.on) Log.log(Platform.class, "XWT build: " + build);
85
86             if (Log.on) Log.log(Platform.class, "XWT VM detection:   vendor = " + vendor);
87             if (Log.on) Log.log(Platform.class, "                   version = " + version);
88             if (Log.on) Log.log(Platform.class, "                        os = " + os_name + " [version " + os_version + "]");
89             if (Log.on && Main.applet != null) Log.log(Platform.class, "                   browser = " + Main.applet.getParameter("browser"));
90
91             if (platform_class == null) {
92                 if (Log.on) Log.log(Platform.class, "Unable to detect JVM");
93                 new Platform().criticalAbort("Unable to detect JVM");
94             }
95
96             if (Log.on) Log.log(Platform.class, "                  platform = " + platform.getDescriptiveName());
97             if (Log.on) Log.log(Platform.class, "                     class = " + platform.getClass().getName());
98             platform.postInit();
99
100         } catch (Exception e) {
101             if (Log.on) Log.log(Platform.class, "Exception while trying to detect JVM");
102             if (Log.on) Log.log(Platform.class, e);
103             new Platform().criticalAbort("Unable to detect JVM");
104         }
105
106     }
107
108
109     // Methods to be Overridden ////////////////////////////////////////////////////////////////////
110
111     /** a string describing the VM */
112     protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
113
114     /** this initializes the platform; code in here can invoke methods on Platform since Platform.platform has already been set */
115     protected void init() { }
116     protected void postInit() { }
117
118     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt>; we need to associate DoubleBuffers to surfaces
119      *  due to AWT 1.1 requirements (definately for Navigator, possibly also for MSJVM).
120      */
121     protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return null; }
122     
123     /** creates and returns a new surface */
124     protected Surface _createSurface(Box b, boolean framed) { return null; }
125
126     /** creates a socket object */
127     protected Socket _getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
128         Socket ret = ssl ? new TinySSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
129         ret.setTcpNoDelay(true);
130         return ret;
131     }
132
133     /** creates and returns a picture */
134     protected Picture _createPicture(int[] b, int w, int h) { return null; }
135     
136     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
137     protected boolean _supressDirtyOnResize() { return false; }
138
139     /** the human-readable name of the key mapped to XWT's 'alt' key */
140     protected String _altKeyName() { return "alt"; }
141
142     /** opens a connection to the resource identified by URL u, and returns an InputStream */
143     protected InputStream _urlToInputStream(URL u) throws IOException { return u.openStream(); }
144
145     /** returns the contents of the clipboard */    
146     protected String _getClipBoard() { return null; }
147
148     /** sets the contents of the clipboard */
149     protected void _setClipBoard(String s) { }
150
151     /** returns the width of the screen, in pixels */
152     protected int _getScreenWidth() { return 640; }
153
154     /** returns the height of the screen, in pixels */
155     protected int _getScreenHeight() { return 480; }
156
157     /** returns the width of a string in a platform-specific font */
158     protected int _stringWidth(String font, String text) { return 10 * text.length(); }
159
160     /** returns the maximum ascent of all glyphs in a given platform-specific font */
161     protected int _getMaxAscent(String font) { return 10; }
162
163     /** returns the maximum descent of all glyphs in a given platform-specific font */
164     protected int _getMaxDescent(String font) { return 2; }
165
166     /** returns a list of all platform-specific fonts available */
167     protected String[] _listFonts() { return new String[] { }; }
168
169     /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
170     protected int _maxThreads() { return 25; }
171
172     /** creates a weak reference */
173     protected org.xwt.Weak _getWeak(final Object o) {
174         return new org.xwt.Weak() {
175                 public Object get() { return o; }
176             };
177     }
178
179         /** Called once XWT is initialized and the application is running. */
180         protected void _running() {}
181     
182     /** quits XWT */
183     protected void _exit() {
184         if (Main.applet == null) {
185             System.exit(0);
186         } else {
187             // just block ourselves forever
188             // FIXME
189             new Semaphore().block();
190         }
191     }
192
193     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
194     protected void _criticalAbort(String message) { _exit(); }
195
196     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
197     protected String _getDefaultFont() { return "sansserif10"; }
198
199     /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
200     protected boolean _needsAutoClick() { return false; }
201
202     /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
203     protected boolean _needsAutoDoubleClick() { return false; }
204
205     protected void _newBrowserWindow(String url) {
206         if (Log.on) Log.log(this, "Platform " + platform.getClass().getName() + " cannot open browser windows");
207         return;
208     }
209
210     /** Returns null if XWT should always use direct connection; otherwise returns a ProxyInfo object with proxy settings */
211     protected synchronized Proxy _detectProxy() { return null; }
212
213     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
214     protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
215
216     /** returns true iff the platform has a case-sensitive filesystem */
217     protected boolean _isCaseSensitive() { return true; }
218
219     /** returns an InputStream to the builtin xwar */
220     protected InputStream _getBuiltinInputStream() {
221         return Platform.class.getClassLoader().getResourceAsStream("org/xwt/builtin.xwar");
222     }
223
224     /** returns the value of the environment variable key, or null if no such key exists */
225     protected String _getEnv(String key) {
226         try {
227             String os = System.getProperty("os.name").toLowerCase();
228             Process p;
229             if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -1) {
230                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
231                 if (platform.getClass().getName().endsWith("Java12")) return null;
232                 p = Runtime.getRuntime().exec("command.com /c set");
233             } else if (os.indexOf("windows") > -1) {
234                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
235                 if (platform.getClass().getName().endsWith("Java12")) return null;
236                 p = Runtime.getRuntime().exec("cmd.exe /c set");
237             } else {  
238                 p = Runtime.getRuntime().exec("env");
239             }
240             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
241             String s;
242             while ((s = br.readLine()) != null)
243                 if (s.startsWith(key + "="))
244                     return s.substring(key.length() + 1);
245         } catch (Exception e) {
246             if (Log.on) Log.log(this, "Exception while reading from environment:");
247             if (Log.on) Log.log(this, e);
248         }
249         return null;
250     }
251
252     /** convert a JPEG into an Image */
253     protected ImageDecoder _decodeJPEG(InputStream is, String name) { return null; }
254
255
256     // Static methods -- thunk to the instance /////////////////////////////////////////////////////////////////////////
257
258     /** if true, org.xwt.Surface should generate Click messages automatically when a Release happens after a Press and the mouse has not moved much */
259     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
260
261     /** if true, org.xwt.Surface should generate DoubleClick messages automatically when needed */
262     public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
263
264     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
265     public static String getDefaultFont() { return platform._getDefaultFont(); }
266
267     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
268     public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
269
270     /** returns the width of a string in a platform-specific font */
271     public static int stringWidth(String font, String text) { return platform._stringWidth(font, text); }
272
273     /** returns the maximum ascent of all glyphs in a given platform-specific font */
274     public static int getMaxAscent(String font) { return platform._getMaxAscent(font); }
275
276     /** returns the maximum descent of all glyphs in a given platform-specific font. Three pixel minimum ensures space for underline. */
277     public static int getMaxDescent(String font) { return Math.max(3, platform._getMaxDescent(font)); }
278
279     /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
280     public static int maxThreads() { return platform._maxThreads(); }
281
282     /** returns a list of all platform-specific fonts available */
283     public static String[] listFonts() { return platform._listFonts(); }
284
285     /** creates a weak reference */
286     public static org.xwt.Weak getWeak(Object o) { return platform._getWeak(o); }
287
288     /** opens a connection to the resource identified by URL u, and returns an InputStream */
289     public static InputStream urlToInputStream(URL u) throws IOException { return platform._urlToInputStream(u); }
290
291     /** returns the contents of the clipboard */    
292     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
293
294     /** sets the contents of the clipboard */
295     public static void setClipBoard(String s) { platform._setClipBoard(s); }
296
297     /** creates a socket object, with or without ssl encryption */
298     public static Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
299         return platform._getSocket(host, port, ssl, negotiate);
300     }
301
302     /** returns the width of the screen, in pixels */
303     public static int getScreenWidth() { return platform._getScreenWidth(); }
304
305     /** returns the height of the screen, in pixels */
306     public static int getScreenHeight() { return platform._getScreenHeight(); }
307
308     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt> */
309     public static DoubleBuffer createDoubleBuffer(int w, int h, Surface s) { return platform._createDoubleBuffer(w, h, s); }
310
311     /** creates and returns a picture */
312     public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
313
314     /** returns an InputStream to the builtin xwar */
315     public static InputStream getBuiltinInputStream() { return platform._getBuiltinInputStream(); }
316         
317     /** creates and returns a picture */
318     public static Picture createPicture(ImageDecoder i) { return platform._createPicture(i.getData(), i.getWidth(), i.getHeight()); }
319
320     /** returns true iff the platform has a case-sensitive filesystem */
321     public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
322
323     /** returns the value of the environment variable key, or null if no such key exists */
324     public static String getEnv(String key) { return platform._getEnv(key); }
325
326     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
327     public static String fileDialog(String suggestedFileName, boolean write) {
328         if (!ThreadMessage.suspendThread()) return null;
329         try {
330             return platform._fileDialog(suggestedFileName, write);
331         } finally {
332             ThreadMessage.resumeThread();
333         }
334     }
335
336     /** opens a new browser window */
337     public static void newBrowserWindow(String url) {
338         if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
339             if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
340             return;
341         }
342
343         // check the URL for well-formedness, as a defense against buffer overflow attacks
344         try {
345             String u = url;
346             if (u.startsWith("https")) u = "http" + u.substring(5);
347             new URL(u);
348         } catch (MalformedURLException e) {
349             if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
350             if (Log.on) Log.log(Platform.class, e);
351         }
352
353         if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
354         platform._newBrowserWindow(url);
355     }
356
357         /** Called once XWT is initialized and the application is running. */
358         public static void running() {
359                 Log.log(Platform.class, "XWT is running");
360                 platform._running();
361         }
362         
363     /** quits XWT */
364     public static void exit() {
365         Log.log(Platform.class, "exiting via Platform.exit()");
366         platform._exit();
367     }
368
369     /** the human-readable name of the key mapped to XWT's 'alt' key */
370     public static String altKeyName() { return platform._altKeyName(); }
371
372     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
373     public static void criticalAbort(String message) {
374         if (Log.on) Log.log(Platform.class, "Critical Abort:");
375         if (Log.on) Log.log(Platform.class, message);
376         platform._criticalAbort(message);
377     }
378
379     /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
380     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
381         Surface ret = platform._createSurface(b, framed);
382         ret.setInvisible(b.invisible);
383         b.set(Box.size, 0, b.size(0) < Surface.scarPicture.getWidth() ? Surface.scarPicture.getWidth() : b.size(0));
384         b.set(Box.size, 1, b.size(1) < Surface.scarPicture.getHeight() ? Surface.scarPicture.getHeight() : b.size(1));
385
386         Object titlebar = b.get("titlebar", null, true);
387         if (titlebar != null) ret.setTitleBarText(titlebar.toString());
388
389         Object icon = b.get("icon", null, true);
390         if (icon != null && !"".equals(icon)) {
391             Picture pic = Box.getPicture(icon.toString());
392             if (pic != null) ret.setIcon(pic);
393             else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
394         }
395
396         ret.setLimits(b.dmin(0), b.dmin(1), b.dmax(0), b.dmax(1));
397
398         if (refreshable) {
399             Surface.refreshableSurfaceWasCreated = true;
400             Surface.allSurfaces.addElement(ret);
401             ret.dirty(0, 0, ret.width, ret.height);
402             ret.Refresh();
403         }
404         return ret;
405     }
406
407     /** detects proxy settings */
408     public static synchronized Proxy detectProxy() {
409
410         if (cachedProxyInfo != null) return cachedProxyInfo;
411         if (alreadyDetectedProxy) return null;
412         alreadyDetectedProxy = true;
413
414         if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
415         cachedProxyInfo = Proxy.detectProxyViaManual();
416         if (cachedProxyInfo != null) return cachedProxyInfo;
417
418         if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
419         cachedProxyInfo = platform._detectProxy();
420         if (cachedProxyInfo != null) return cachedProxyInfo;
421
422         return cachedProxyInfo;
423     }
424
425     public static synchronized ImageDecoder decodeJPEG(InputStream is, String name) {
426         return platform._decodeJPEG(is, name);
427     }
428
429     // Helpful font parsing stuff //////////////////////////////////////////////////////
430
431     public static class ParsedFont {
432         public ParsedFont() { }
433         public ParsedFont(String s) { parse(s); }
434         public int size = 10;
435         public String name = "";
436
437         public boolean italic = false;
438         public boolean bold = false;
439         public boolean underline = false;
440         public boolean dotted_underline = false;
441
442         private static int stoi(Object o) {
443             if (o == null) return 0;
444             if (o instanceof Integer) return ((Integer)o).intValue();
445             
446             String s = o.toString(); 
447             try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
448             catch (NumberFormatException e) { return 0; }
449         }
450
451         public void parse(String font) {
452             int i = 0;
453             while(i < font.length() && !Character.isDigit(font.charAt(i)) && font.charAt(i) != '*') i++;
454             name = font.substring(0, i).toLowerCase().replace('_', ' ');
455             size = 10;
456             italic = false;
457             bold = false;
458             underline = false;
459             dotted_underline = false;
460             if (i != font.length()) {
461                 if (font.charAt(i) == '*') {
462                     size = 0;
463                     i++;
464                 } else {
465                     int j = i;
466                     while (j < font.length() && Character.isDigit(font.charAt(j))) j++;
467                     if (i != j) size = stoi(font.substring(i, j));
468                     i = j;
469                 }
470                 while(i < font.length()) {
471                     switch (font.charAt(i)) {
472                     case 'b': bold = true; break;
473                     case 'i': italic = true; break;
474                     case 'd': dotted_underline = true; break;
475                     case 'u': underline = true; break;
476                     }
477                     i++;
478                 }
479             }
480         }
481
482     }
483
484 }
485
486