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