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