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