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