2002/03/21 01:19:33
[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     // Static methods -- thunk to the instance /////////////////////////////////////////////////////////////////////////
160
161     /** if true, org.xwt.Surface should generate Click messages automatically when a Release happens after a Press and the mouse has not moved much */
162     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
163
164     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
165     public static String getDefaultFont() { return platform._getDefaultFont(); }
166
167     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
168     public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
169
170     /** returns the width of a string in a platform-specific font */
171     public static int stringWidth(String font, String text) { return platform._stringWidth(font, text); }
172
173     /** returns the maximum ascent of all glyphs in a given platform-specific font */
174     public static int getMaxAscent(String font) { return platform._getMaxAscent(font); }
175
176     /** returns the maximum descent of all glyphs in a given platform-specific font */
177     public static int getMaxDescent(String font) { return platform._getMaxDescent(font); }
178
179     /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
180     public static int maxThreads() { return platform._maxThreads(); }
181
182     /** returns a list of all platform-specific fonts available */
183     public static String[] listFonts() { return platform._listFonts(); }
184
185     /** creates a weak reference */
186     public static org.xwt.Weak getWeak(Object o) { return platform._getWeak(o); }
187
188     /** opens a connection to the resource identified by URL u, and returns an InputStream */
189     public static InputStream urlToInputStream(URL u) throws IOException { return platform._urlToInputStream(u); }
190
191     /** returns the contents of the clipboard */    
192     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
193
194     /** sets the contents of the clipboard */
195     public static void setClipBoard(String s) { platform._setClipBoard(s); }
196
197     /** creates a socket object, with or without ssl encryption */
198     public static Socket getSocket(String host, int port, boolean ssl) throws IOException { return platform._getSocket(host, port, ssl); }
199
200     /** returns the width of the screen, in pixels */
201     public static int getScreenWidth() { return platform._getScreenWidth(); }
202
203     /** returns the height of the screen, in pixels */
204     public static int getScreenHeight() { return platform._getScreenHeight(); }
205
206     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt> */
207     public static DoubleBuffer createDoubleBuffer(int w, int h, Surface s) { return platform._createDoubleBuffer(w, h, s); }
208
209     /** creates and returns a picture */
210     public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
211
212     /** creates and returns a picture */
213     public static Picture createPicture(ImageDecoder i) { return platform._createPicture(i.getData(), i.getWidth(), i.getHeight()); }
214
215     /** quits XWT */
216     public static void exit() {
217         Log.log(Platform.class, "exiting via Platform.exit()");
218         platform._exit();
219     }
220
221     /** the human-readable name of the key mapped to XWT's 'alt' key */
222     public static String altKeyName() { return platform._altKeyName(); }
223
224     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
225     public static void criticalAbort(String message) {
226         if (Log.on) Log.log(Platform.class, "Critical Abort:");
227         if (Log.on) Log.log(Platform.class, message);
228         platform._criticalAbort(message);
229     }
230
231     /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
232     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
233         Surface ret = platform._createSurface(b, framed);
234         ret.setInvisible(b.invisible);
235         b.set(Box.size, 0, ret.width);
236         b.set(Box.size, 1, ret.height);
237
238         Object titlebar = b.get("titlebar", null, true);
239         if (titlebar != null) ret.setTitleBarText(titlebar.toString());
240
241         Object icon = b.get("icon", null, true);
242         if (icon != null && !"".equals(icon)) {
243             Picture pic = Box.getPicture(icon.toString());
244             if (pic != null) ret.setIcon(pic);
245             else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
246         }
247
248         if (refreshable) {
249             Surface.refreshableSurfaceWasCreated = true;
250             Surface.allSurfaces.addElement(ret);
251             ret.dirty(0, 0, ret.width, ret.height);
252             ret.Refresh();
253         }
254         return ret;
255     }
256
257     // Helpful font parsing stuff //////////////////////////////////////////////////////
258
259     public static class ParsedFont {
260         public ParsedFont() { }
261         public ParsedFont(String s) { parse(s); }
262         public int size = 10;
263         public String name = "";
264
265         public boolean italic = false;
266         public boolean bold = false;
267         public boolean underline = false;
268         public boolean dotted_underline = false;
269
270         private static int stoi(Object o) {
271             if (o == null) return 0;
272             if (o instanceof Integer) return ((Integer)o).intValue();
273             
274             String s = o.toString(); 
275             try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
276             catch (NumberFormatException e) { return 0; }
277         }
278
279         public void parse(String font) {
280             int i = 0;
281             while(i < font.length() && !Character.isDigit(font.charAt(i))) i++;
282             name = font.substring(0, i).toLowerCase().replace('_', ' ');
283             size = 10;
284             italic = false;
285             bold = false;
286             underline = false;
287             dotted_underline = false;
288             if (i != font.length()) {
289                 int j = i;
290                 while (j < font.length() && Character.isDigit(font.charAt(j))) j++;
291                 if (i != j) size = stoi(font.substring(i, j));
292                 i = j;
293                 while(i < font.length()) {
294                     switch (font.charAt(i)) {
295                     case 'b': bold = true;
296                     case 'i': italic = true;
297                     case 'd': dotted_underline = true;
298                     case 'u': underline = true;
299                     }
300                     i++;
301                 }
302             }
303         }
304
305     }
306
307 }
308