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