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