2002/07/19 04:46:04
[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 HTTP.ProxyInfo 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 HTTP.ProxyInfo _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) {
218                 p = Runtime.getRuntime().exec("command.com /c set");
219             } else if ( (os.indexOf("nt") > -1) || (os.indexOf("windows 2000") > -1) ) {
220                 p = Runtime.getRuntime().exec("cmd.exe /c set");
221             } else {  
222                 p = Runtime.getRuntime().exec("env");
223             }
224             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
225             String s;
226             while ((s = br.readLine()) != null)
227                 if (s.startsWith(key + "="))
228                     return s.substring(key.length() + 1);
229         } catch (Exception e) {
230             if (Log.on) Log.log(this, "Exception while reading from environment:");
231             if (Log.on) Log.log(this, e);
232         }
233         return null;
234     }
235
236     // Static methods -- thunk to the instance /////////////////////////////////////////////////////////////////////////
237
238     /** if true, org.xwt.Surface should generate Click messages automatically when a Release happens after a Press and the mouse has not moved much */
239     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
240
241     /** if true, org.xwt.Surface should generate DoubleClick messages automatically when needed */
242     public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
243
244     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
245     public static String getDefaultFont() { return platform._getDefaultFont(); }
246
247     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
248     public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
249
250     /** returns the width of a string in a platform-specific font */
251     public static int stringWidth(String font, String text) { return platform._stringWidth(font, text); }
252
253     /** returns the maximum ascent of all glyphs in a given platform-specific font */
254     public static int getMaxAscent(String font) { return platform._getMaxAscent(font); }
255
256     /** returns the maximum descent of all glyphs in a given platform-specific font. Three pixel minimum ensures space for underline. */
257     public static int getMaxDescent(String font) { return Math.max(3, platform._getMaxDescent(font)); }
258
259     /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
260     public static int maxThreads() { return platform._maxThreads(); }
261
262     /** returns a list of all platform-specific fonts available */
263     public static String[] listFonts() { return platform._listFonts(); }
264
265     /** creates a weak reference */
266     public static org.xwt.Weak getWeak(Object o) { return platform._getWeak(o); }
267
268     /** opens a connection to the resource identified by URL u, and returns an InputStream */
269     public static InputStream urlToInputStream(URL u) throws IOException { return platform._urlToInputStream(u); }
270
271     /** returns the contents of the clipboard */    
272     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
273
274     /** sets the contents of the clipboard */
275     public static void setClipBoard(String s) { platform._setClipBoard(s); }
276
277     /** creates a socket object, with or without ssl encryption */
278     public static Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
279         return platform._getSocket(host, port, ssl, negotiate);
280     }
281
282     /** returns the width of the screen, in pixels */
283     public static int getScreenWidth() { return platform._getScreenWidth(); }
284
285     /** returns the height of the screen, in pixels */
286     public static int getScreenHeight() { return platform._getScreenHeight(); }
287
288     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt> */
289     public static DoubleBuffer createDoubleBuffer(int w, int h, Surface s) { return platform._createDoubleBuffer(w, h, s); }
290
291     /** creates and returns a picture */
292     public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
293
294     /** creates and returns a picture */
295     public static Picture createPicture(ImageDecoder i) { return platform._createPicture(i.getData(), i.getWidth(), i.getHeight()); }
296
297     /** returns true iff the platform has a case-sensitive filesystem */
298     public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
299
300     /** returns the value of the environment variable key, or null if no such key exists */
301     public static String getEnv(String key) { return platform._getEnv(key); }
302
303     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
304     public static String fileDialog(String suggestedFileName, boolean write) {
305         if (!ThreadMessage.suspendThread()) return null;
306         try {
307             return platform._fileDialog(suggestedFileName, write);
308         } finally {
309             ThreadMessage.resumeThread();
310         }
311     }
312
313     /** opens a new browser window */
314     public static void newBrowserWindow(String url) {
315         if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
316             if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
317             return;
318         }
319
320         // check the URL for well-formedness, as a defense against buffer overflow attacks
321         try {
322             String u = url;
323             if (u.startsWith("https")) u = "http" + u.substring(5);
324             new URL(u);
325         } catch (MalformedURLException e) {
326             if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
327             if (Log.on) Log.log(Platform.class, e);
328         }
329
330         if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
331         platform._newBrowserWindow(url);
332     }
333
334     /** quits XWT */
335     public static void exit() {
336         Log.log(Platform.class, "exiting via Platform.exit()");
337         platform._exit();
338     }
339
340     /** the human-readable name of the key mapped to XWT's 'alt' key */
341     public static String altKeyName() { return platform._altKeyName(); }
342
343     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
344     public static void criticalAbort(String message) {
345         if (Log.on) Log.log(Platform.class, "Critical Abort:");
346         if (Log.on) Log.log(Platform.class, message);
347         platform._criticalAbort(message);
348     }
349
350     /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
351     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
352         Surface ret = platform._createSurface(b, framed);
353         ret.setInvisible(b.invisible);
354         b.set(Box.size, 0, b.size(0) < Surface.scarPicture.getWidth() ? Surface.scarPicture.getWidth() : b.size(0));
355         b.set(Box.size, 1, b.size(1) < Surface.scarPicture.getHeight() ? Surface.scarPicture.getHeight() : b.size(1));
356
357         Object titlebar = b.get("titlebar", null, true);
358         if (titlebar != null) ret.setTitleBarText(titlebar.toString());
359
360         Object icon = b.get("icon", null, true);
361         if (icon != null && !"".equals(icon)) {
362             Picture pic = Box.getPicture(icon.toString());
363             if (pic != null) ret.setIcon(pic);
364             else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
365         }
366
367         ret.setLimits(b.dmin(0), b.dmin(1), b.dmax(0), b.dmax(1));
368
369         if (refreshable) {
370             Surface.refreshableSurfaceWasCreated = true;
371             Surface.allSurfaces.addElement(ret);
372             ret.dirty(0, 0, ret.width, ret.height);
373             ret.Refresh();
374         }
375         return ret;
376     }
377
378     /** detects proxy settings */
379     public static synchronized HTTP.ProxyInfo detectProxy() {
380
381         if (cachedProxyInfo != null) return cachedProxyInfo;
382         if (alreadyDetectedProxy) return null;
383         alreadyDetectedProxy = true;
384
385         if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
386         cachedProxyInfo = HTTP.ProxyInfo.detectProxyViaManual();
387         if (cachedProxyInfo != null) return cachedProxyInfo;
388
389         if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
390         cachedProxyInfo = platform._detectProxy();
391         if (cachedProxyInfo != null) return cachedProxyInfo;
392
393         if (Log.on) Log.log(Platform.class, "attempting WPAD proxy detection");
394         cachedProxyInfo = HTTP.ProxyInfo.detectProxyViaWPAD();
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