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