1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
4 import java.lang.reflect.*;
11 * Abstracts away the small irregularities in JVM implementations.
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.
20 public class Platform {
22 // Static Data /////////////////////////////////////////////////////////////////////////////////////
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
28 static boolean clipboardReadEnabled = false;
30 /** The appropriate Platform object for this JVM */
31 static Platform platform = null;
33 /** true if proxy autodetection has already been run */
34 static boolean alreadyDetectedProxy = false;
36 /** the result of proxy autodetection */
37 static Proxy cachedProxyInfo = null;
39 /** the current build */
40 public static String build = "unknown";
42 // VM Detection Logic /////////////////////////////////////////////////////////////////////
44 /** do-nothing method that forces <clinit> to run */
45 public static void forceLoad() { }
47 // If you create a new subclass of Platform, you should add logic
48 // here to detect it. Do not reference your class directly -- use
52 System.out.println("Detecting JVM...");
54 String vendor = System.getProperty("java.vendor", "");
55 String version = System.getProperty("java.version", "");
56 String os_name = System.getProperty("os.name", "");
57 String os_version = System.getProperty("os.version", "");
58 String platform_class = null;
60 //if (os_name.startsWith("Mac OS X")) platform_class = "MacOSX";
61 if (vendor.startsWith("Free Software Foundation")) {
62 if (os_name.startsWith("Window")) platform_class = "Win32";
63 else platform_class = "POSIX";
64 } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
65 else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
66 else if (version.startsWith("1.4")) platform_class = "Java14";
67 else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java12";
69 // Disable 2d hardware acceleration on Jaguar
70 if (os_name.equals("Mac OS X") && os_version.equals("10.2"))
71 System.setProperty("com.apple.hwaccel", "false");
73 if (platform_class != null) {
74 platform = (Platform)Class.forName("org.xwt.plat." + platform_class).newInstance();
79 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
80 } catch (ClassNotFoundException cnfe) {
81 } catch (Exception e) {
82 if (Log.on) Log.log(Platform.class, "exception while detecting build:");
83 if (Log.on) Log.log(Platform.class, e);
85 if (Log.on) Log.log(Platform.class, "XWT build: " + build);
87 if (Log.on) Log.log(Platform.class, "XWT VM detection: vendor = " + vendor);
88 if (Log.on) Log.log(Platform.class, " version = " + version);
89 if (Log.on) Log.log(Platform.class, " os = " + os_name + " [version " + os_version + "]");
90 if (Log.on && Main.applet != null) Log.log(Platform.class, " browser = " + Main.applet.getParameter("browser"));
92 if (platform_class == null) {
93 if (Log.on) Log.log(Platform.class, "Unable to detect JVM");
94 new Platform().criticalAbort("Unable to detect JVM");
97 if (Log.on) Log.log(Platform.class, " platform = " + platform.getDescriptiveName());
98 if (Log.on) Log.log(Platform.class, " class = " + platform.getClass().getName());
101 } catch (Exception e) {
102 if (Log.on) Log.log(Platform.class, "Exception while trying to detect JVM");
103 if (Log.on) Log.log(Platform.class, e);
104 new Platform().criticalAbort("Unable to detect JVM");
110 // Methods to be Overridden ////////////////////////////////////////////////////////////////////
112 /** a string describing the VM */
113 protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
115 /** this initializes the platform; code in here can invoke methods on Platform since Platform.platform has already been set */
116 protected void init() { }
117 protected void postInit() { }
119 /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt>; we need to associate DoubleBuffers to surfaces
120 * due to AWT 1.1 requirements (definately for Navigator, possibly also for MSJVM).
122 protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return null; }
124 /** creates and returns a new surface */
125 protected Surface _createSurface(Box b, boolean framed) { return null; }
127 /** creates a socket object */
128 protected Socket _getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
129 Socket ret = ssl ? new TinySSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
130 ret.setTcpNoDelay(true);
134 /** creates and returns a picture */
135 protected Picture _createPicture(int[] b, int w, int h) { return null; }
137 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
138 protected boolean _supressDirtyOnResize() { return false; }
140 /** the human-readable name of the key mapped to XWT's 'alt' key */
141 protected String _altKeyName() { return "alt"; }
143 /** opens a connection to the resource identified by URL u, and returns an InputStream */
144 protected InputStream _urlToInputStream(URL u) throws IOException { return u.openStream(); }
146 /** returns the contents of the clipboard */
147 protected String _getClipBoard() { return null; }
149 /** sets the contents of the clipboard */
150 protected void _setClipBoard(String s) { }
152 /** returns the width of the screen, in pixels */
153 protected int _getScreenWidth() { return 640; }
155 /** returns the height of the screen, in pixels */
156 protected int _getScreenHeight() { return 480; }
158 /** returns the width of a string in a platform-specific font */
159 protected int _stringWidth(String font, String text) { return 10 * text.length(); }
161 /** returns the maximum ascent of all glyphs in a given platform-specific font */
162 protected int _getMaxAscent(String font) { return 10; }
164 /** returns the maximum descent of all glyphs in a given platform-specific font */
165 protected int _getMaxDescent(String font) { return 2; }
167 /** returns a list of all platform-specific fonts available */
168 protected String[] _listFonts() { return new String[] { }; }
170 /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
171 protected int _maxThreads() { return 25; }
173 /** creates a weak reference */
174 protected org.xwt.Weak _getWeak(final Object o) {
175 return new org.xwt.Weak() {
176 public Object get() { return o; }
181 protected void _exit() {
182 if (Main.applet == null) {
185 // just block ourselves forever
187 new Semaphore().block();
191 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
192 protected void _criticalAbort(String message) { _exit(); }
194 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
195 protected String _getDefaultFont() { return "sansserif10"; }
197 /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
198 protected boolean _needsAutoClick() { return false; }
200 /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
201 protected boolean _needsAutoDoubleClick() { return false; }
203 protected void _newBrowserWindow(String url) {
204 if (Log.on) Log.log(this, "Platform " + platform.getClass().getName() + " cannot open browser windows");
208 /** Returns null if XWT should always use direct connection; otherwise returns a ProxyInfo object with proxy settings */
209 protected synchronized Proxy _detectProxy() { return null; }
211 /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
212 protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
214 /** returns true iff the platform has a case-sensitive filesystem */
215 protected boolean _isCaseSensitive() { return true; }
217 /** returns the value of the environment variable key, or null if no such key exists */
218 protected String _getEnv(String key) {
220 String os = System.getProperty("os.name").toLowerCase();
222 if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -1) {
223 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
224 if (platform.getClass().getName().endsWith("Java12")) return null;
225 p = Runtime.getRuntime().exec("command.com /c set");
226 } else if (os.indexOf("windows") > -1) {
227 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
228 if (platform.getClass().getName().endsWith("Java12")) return null;
229 p = Runtime.getRuntime().exec("cmd.exe /c set");
231 p = Runtime.getRuntime().exec("env");
233 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
235 while ((s = br.readLine()) != null)
236 if (s.startsWith(key + "="))
237 return s.substring(key.length() + 1);
238 } catch (Exception e) {
239 if (Log.on) Log.log(this, "Exception while reading from environment:");
240 if (Log.on) Log.log(this, e);
245 // Static methods -- thunk to the instance /////////////////////////////////////////////////////////////////////////
247 /** if true, org.xwt.Surface should generate Click messages automatically when a Release happens after a Press and the mouse has not moved much */
248 public static boolean needsAutoClick() { return platform._needsAutoClick(); }
250 /** if true, org.xwt.Surface should generate DoubleClick messages automatically when needed */
251 public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
253 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
254 public static String getDefaultFont() { return platform._getDefaultFont(); }
256 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
257 public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
259 /** returns the width of a string in a platform-specific font */
260 public static int stringWidth(String font, String text) { return platform._stringWidth(font, text); }
262 /** returns the maximum ascent of all glyphs in a given platform-specific font */
263 public static int getMaxAscent(String font) { return platform._getMaxAscent(font); }
265 /** returns the maximum descent of all glyphs in a given platform-specific font. Three pixel minimum ensures space for underline. */
266 public static int getMaxDescent(String font) { return Math.max(3, platform._getMaxDescent(font)); }
268 /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
269 public static int maxThreads() { return platform._maxThreads(); }
271 /** returns a list of all platform-specific fonts available */
272 public static String[] listFonts() { return platform._listFonts(); }
274 /** creates a weak reference */
275 public static org.xwt.Weak getWeak(Object o) { return platform._getWeak(o); }
277 /** opens a connection to the resource identified by URL u, and returns an InputStream */
278 public static InputStream urlToInputStream(URL u) throws IOException { return platform._urlToInputStream(u); }
280 /** returns the contents of the clipboard */
281 public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
283 /** sets the contents of the clipboard */
284 public static void setClipBoard(String s) { platform._setClipBoard(s); }
286 /** creates a socket object, with or without ssl encryption */
287 public static Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
288 return platform._getSocket(host, port, ssl, negotiate);
291 /** returns the width of the screen, in pixels */
292 public static int getScreenWidth() { return platform._getScreenWidth(); }
294 /** returns the height of the screen, in pixels */
295 public static int getScreenHeight() { return platform._getScreenHeight(); }
297 /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt> */
298 public static DoubleBuffer createDoubleBuffer(int w, int h, Surface s) { return platform._createDoubleBuffer(w, h, s); }
300 /** creates and returns a picture */
301 public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
303 /** creates and returns a picture */
304 public static Picture createPicture(ImageDecoder i) { return platform._createPicture(i.getData(), i.getWidth(), i.getHeight()); }
306 /** returns true iff the platform has a case-sensitive filesystem */
307 public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
309 /** returns the value of the environment variable key, or null if no such key exists */
310 public static String getEnv(String key) { return platform._getEnv(key); }
312 /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
313 public static String fileDialog(String suggestedFileName, boolean write) {
314 if (!ThreadMessage.suspendThread()) return null;
316 return platform._fileDialog(suggestedFileName, write);
318 ThreadMessage.resumeThread();
322 /** opens a new browser window */
323 public static void newBrowserWindow(String url) {
324 if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
325 if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
329 // check the URL for well-formedness, as a defense against buffer overflow attacks
332 if (u.startsWith("https")) u = "http" + u.substring(5);
334 } catch (MalformedURLException e) {
335 if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
336 if (Log.on) Log.log(Platform.class, e);
339 if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
340 platform._newBrowserWindow(url);
344 public static void exit() {
345 Log.log(Platform.class, "exiting via Platform.exit()");
349 /** the human-readable name of the key mapped to XWT's 'alt' key */
350 public static String altKeyName() { return platform._altKeyName(); }
352 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
353 public static void criticalAbort(String message) {
354 if (Log.on) Log.log(Platform.class, "Critical Abort:");
355 if (Log.on) Log.log(Platform.class, message);
356 platform._criticalAbort(message);
359 /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
360 public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
361 Surface ret = platform._createSurface(b, framed);
362 ret.setInvisible(b.invisible);
363 b.set(Box.size, 0, b.size(0) < Surface.scarPicture.getWidth() ? Surface.scarPicture.getWidth() : b.size(0));
364 b.set(Box.size, 1, b.size(1) < Surface.scarPicture.getHeight() ? Surface.scarPicture.getHeight() : b.size(1));
366 Object titlebar = b.get("titlebar", null, true);
367 if (titlebar != null) ret.setTitleBarText(titlebar.toString());
369 Object icon = b.get("icon", null, true);
370 if (icon != null && !"".equals(icon)) {
371 Picture pic = Box.getPicture(icon.toString());
372 if (pic != null) ret.setIcon(pic);
373 else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
376 ret.setLimits(b.dmin(0), b.dmin(1), b.dmax(0), b.dmax(1));
379 Surface.refreshableSurfaceWasCreated = true;
380 Surface.allSurfaces.addElement(ret);
381 ret.dirty(0, 0, ret.width, ret.height);
387 /** detects proxy settings */
388 public static synchronized Proxy detectProxy() {
390 if (cachedProxyInfo != null) return cachedProxyInfo;
391 if (alreadyDetectedProxy) return null;
392 alreadyDetectedProxy = true;
394 if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
395 cachedProxyInfo = Proxy.detectProxyViaManual();
396 if (cachedProxyInfo != null) return cachedProxyInfo;
398 if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
399 cachedProxyInfo = platform._detectProxy();
400 if (cachedProxyInfo != null) return cachedProxyInfo;
402 return cachedProxyInfo;
405 // Helpful font parsing stuff //////////////////////////////////////////////////////
407 public static class ParsedFont {
408 public ParsedFont() { }
409 public ParsedFont(String s) { parse(s); }
410 public int size = 10;
411 public String name = "";
413 public boolean italic = false;
414 public boolean bold = false;
415 public boolean underline = false;
416 public boolean dotted_underline = false;
418 private static int stoi(Object o) {
419 if (o == null) return 0;
420 if (o instanceof Integer) return ((Integer)o).intValue();
422 String s = o.toString();
423 try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
424 catch (NumberFormatException e) { return 0; }
427 public void parse(String font) {
429 while(i < font.length() && !Character.isDigit(font.charAt(i)) && font.charAt(i) != '*') i++;
430 name = font.substring(0, i).toLowerCase().replace('_', ' ');
435 dotted_underline = false;
436 if (i != font.length()) {
437 if (font.charAt(i) == '*') {
442 while (j < font.length() && Character.isDigit(font.charAt(j))) j++;
443 if (i != j) size = stoi(font.substring(i, j));
446 while(i < font.length()) {
447 switch (font.charAt(i)) {
448 case 'b': bold = true; break;
449 case 'i': italic = true; break;
450 case 'd': dotted_underline = true; break;
451 case 'u': underline = true; break;