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