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 platform_class = null;
59 //if (os_name.startsWith("Mac OS X")) platform_class = "MacOSX";
60 if (vendor.startsWith("Free Software Foundation")) {
61 if (os_name.startsWith("Window")) platform_class = "Win32";
62 else platform_class = "POSIX";
63 } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
64 else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
65 else if (version.startsWith("1.4")) platform_class = "Java14";
66 else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java12";
68 if (platform_class != null) {
69 platform = (Platform)Class.forName("org.xwt.plat." + platform_class).newInstance();
74 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
75 } catch (ClassNotFoundException cnfe) {
76 } catch (Exception e) {
77 if (Log.on) Log.log(Platform.class, "exception while detecting build:");
78 if (Log.on) Log.log(Platform.class, e);
80 if (Log.on) Log.log(Platform.class, "XWT build: " + build);
82 if (Log.on) Log.log(Platform.class, "XWT VM detection: vendor = " + vendor);
83 if (Log.on) Log.log(Platform.class, " version = " + version);
84 if (Log.on) Log.log(Platform.class, " os = " + os_name);
85 if (Log.on && Main.applet != null) Log.log(Platform.class, " browser = " + Main.applet.getParameter("browser"));
87 if (platform_class == null) {
88 if (Log.on) Log.log(Platform.class, "Unable to detect JVM");
89 new Platform().criticalAbort("Unable to detect JVM");
92 if (Log.on) Log.log(Platform.class, " platform = " + platform.getDescriptiveName());
93 if (Log.on) Log.log(Platform.class, " class = " + platform.getClass().getName());
96 } catch (Exception e) {
97 if (Log.on) Log.log(Platform.class, "Exception while trying to detect JVM");
98 if (Log.on) Log.log(Platform.class, e);
99 new Platform().criticalAbort("Unable to detect JVM");
105 // Methods to be Overridden ////////////////////////////////////////////////////////////////////
107 /** a string describing the VM */
108 protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
110 /** this initializes the platform; code in here can invoke methods on Platform since Platform.platform has already been set */
111 protected void init() { }
112 protected void postInit() { }
114 /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt>; we need to associate DoubleBuffers to surfaces
115 * due to AWT 1.1 requirements (definately for Navigator, possibly also for MSJVM).
117 protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return null; }
119 /** creates and returns a new surface */
120 protected Surface _createSurface(Box b, boolean framed) { return null; }
122 /** creates a socket object */
123 protected Socket _getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
124 Socket ret = ssl ? new TinySSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
125 ret.setTcpNoDelay(true);
129 /** creates and returns a picture */
130 protected Picture _createPicture(int[] b, int w, int h) { return null; }
132 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
133 protected boolean _supressDirtyOnResize() { return false; }
135 /** the human-readable name of the key mapped to XWT's 'alt' key */
136 protected String _altKeyName() { return "alt"; }
138 /** opens a connection to the resource identified by URL u, and returns an InputStream */
139 protected InputStream _urlToInputStream(URL u) throws IOException { return u.openStream(); }
141 /** returns the contents of the clipboard */
142 protected String _getClipBoard() { return null; }
144 /** sets the contents of the clipboard */
145 protected void _setClipBoard(String s) { }
147 /** returns the width of the screen, in pixels */
148 protected int _getScreenWidth() { return 640; }
150 /** returns the height of the screen, in pixels */
151 protected int _getScreenHeight() { return 480; }
153 /** returns the width of a string in a platform-specific font */
154 protected int _stringWidth(String font, String text) { return 10 * text.length(); }
156 /** returns the maximum ascent of all glyphs in a given platform-specific font */
157 protected int _getMaxAscent(String font) { return 10; }
159 /** returns the maximum descent of all glyphs in a given platform-specific font */
160 protected int _getMaxDescent(String font) { return 2; }
162 /** returns a list of all platform-specific fonts available */
163 protected String[] _listFonts() { return new String[] { }; }
165 /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
166 protected int _maxThreads() { return 25; }
168 /** creates a weak reference */
169 protected org.xwt.Weak _getWeak(final Object o) {
170 return new org.xwt.Weak() {
171 public Object get() { return o; }
176 protected void _exit() {
177 if (Main.applet == null) {
180 // just block ourselves forever
182 new Semaphore().block();
186 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
187 protected void _criticalAbort(String message) { _exit(); }
189 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
190 protected String _getDefaultFont() { return "sansserif10"; }
192 /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
193 protected boolean _needsAutoClick() { return false; }
195 /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
196 protected boolean _needsAutoDoubleClick() { return false; }
198 protected void _newBrowserWindow(String url) {
199 if (Log.on) Log.log(this, "Platform " + platform.getClass().getName() + " cannot open browser windows");
203 /** Returns null if XWT should always use direct connection; otherwise returns a ProxyInfo object with proxy settings */
204 protected synchronized Proxy _detectProxy() { return null; }
206 /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
207 protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
209 /** returns true iff the platform has a case-sensitive filesystem */
210 protected boolean _isCaseSensitive() { return true; }
212 /** returns the value of the environment variable key, or null if no such key exists */
213 protected String _getEnv(String key) {
215 String os = System.getProperty("os.name").toLowerCase();
217 if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -1) {
218 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
219 if (platform.getClass().getName().endsWith("Java12")) return null;
220 p = Runtime.getRuntime().exec("command.com /c set");
221 } else if (os.indexOf("windows") > -1) {
222 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
223 if (platform.getClass().getName().endsWith("Java12")) return null;
224 p = Runtime.getRuntime().exec("cmd.exe /c set");
226 p = Runtime.getRuntime().exec("env");
228 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
230 while ((s = br.readLine()) != null)
231 if (s.startsWith(key + "="))
232 return s.substring(key.length() + 1);
233 } catch (Exception e) {
234 if (Log.on) Log.log(this, "Exception while reading from environment:");
235 if (Log.on) Log.log(this, e);
240 // Static methods -- thunk to the instance /////////////////////////////////////////////////////////////////////////
242 /** if true, org.xwt.Surface should generate Click messages automatically when a Release happens after a Press and the mouse has not moved much */
243 public static boolean needsAutoClick() { return platform._needsAutoClick(); }
245 /** if true, org.xwt.Surface should generate DoubleClick messages automatically when needed */
246 public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
248 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
249 public static String getDefaultFont() { return platform._getDefaultFont(); }
251 /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
252 public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
254 /** returns the width of a string in a platform-specific font */
255 public static int stringWidth(String font, String text) { return platform._stringWidth(font, text); }
257 /** returns the maximum ascent of all glyphs in a given platform-specific font */
258 public static int getMaxAscent(String font) { return platform._getMaxAscent(font); }
260 /** returns the maximum descent of all glyphs in a given platform-specific font. Three pixel minimum ensures space for underline. */
261 public static int getMaxDescent(String font) { return Math.max(3, platform._getMaxDescent(font)); }
263 /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
264 public static int maxThreads() { return platform._maxThreads(); }
266 /** returns a list of all platform-specific fonts available */
267 public static String[] listFonts() { return platform._listFonts(); }
269 /** creates a weak reference */
270 public static org.xwt.Weak getWeak(Object o) { return platform._getWeak(o); }
272 /** opens a connection to the resource identified by URL u, and returns an InputStream */
273 public static InputStream urlToInputStream(URL u) throws IOException { return platform._urlToInputStream(u); }
275 /** returns the contents of the clipboard */
276 public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
278 /** sets the contents of the clipboard */
279 public static void setClipBoard(String s) { platform._setClipBoard(s); }
281 /** creates a socket object, with or without ssl encryption */
282 public static Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
283 return platform._getSocket(host, port, ssl, negotiate);
286 /** returns the width of the screen, in pixels */
287 public static int getScreenWidth() { return platform._getScreenWidth(); }
289 /** returns the height of the screen, in pixels */
290 public static int getScreenHeight() { return platform._getScreenHeight(); }
292 /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt> */
293 public static DoubleBuffer createDoubleBuffer(int w, int h, Surface s) { return platform._createDoubleBuffer(w, h, s); }
295 /** creates and returns a picture */
296 public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
298 /** creates and returns a picture */
299 public static Picture createPicture(ImageDecoder i) { return platform._createPicture(i.getData(), i.getWidth(), i.getHeight()); }
301 /** returns true iff the platform has a case-sensitive filesystem */
302 public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
304 /** returns the value of the environment variable key, or null if no such key exists */
305 public static String getEnv(String key) { return platform._getEnv(key); }
307 /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
308 public static String fileDialog(String suggestedFileName, boolean write) {
309 if (!ThreadMessage.suspendThread()) return null;
311 return platform._fileDialog(suggestedFileName, write);
313 ThreadMessage.resumeThread();
317 /** opens a new browser window */
318 public static void newBrowserWindow(String url) {
319 if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
320 if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
324 // check the URL for well-formedness, as a defense against buffer overflow attacks
327 if (u.startsWith("https")) u = "http" + u.substring(5);
329 } catch (MalformedURLException e) {
330 if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
331 if (Log.on) Log.log(Platform.class, e);
334 if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
335 platform._newBrowserWindow(url);
339 public static void exit() {
340 Log.log(Platform.class, "exiting via Platform.exit()");
344 /** the human-readable name of the key mapped to XWT's 'alt' key */
345 public static String altKeyName() { return platform._altKeyName(); }
347 /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
348 public static void criticalAbort(String message) {
349 if (Log.on) Log.log(Platform.class, "Critical Abort:");
350 if (Log.on) Log.log(Platform.class, message);
351 platform._criticalAbort(message);
354 /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
355 public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
356 Surface ret = platform._createSurface(b, framed);
357 ret.setInvisible(b.invisible);
358 b.set(Box.size, 0, b.size(0) < Surface.scarPicture.getWidth() ? Surface.scarPicture.getWidth() : b.size(0));
359 b.set(Box.size, 1, b.size(1) < Surface.scarPicture.getHeight() ? Surface.scarPicture.getHeight() : b.size(1));
361 Object titlebar = b.get("titlebar", null, true);
362 if (titlebar != null) ret.setTitleBarText(titlebar.toString());
364 Object icon = b.get("icon", null, true);
365 if (icon != null && !"".equals(icon)) {
366 Picture pic = Box.getPicture(icon.toString());
367 if (pic != null) ret.setIcon(pic);
368 else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
371 ret.setLimits(b.dmin(0), b.dmin(1), b.dmax(0), b.dmax(1));
374 Surface.refreshableSurfaceWasCreated = true;
375 Surface.allSurfaces.addElement(ret);
376 ret.dirty(0, 0, ret.width, ret.height);
382 /** detects proxy settings */
383 public static synchronized Proxy detectProxy() {
385 if (cachedProxyInfo != null) return cachedProxyInfo;
386 if (alreadyDetectedProxy) return null;
387 alreadyDetectedProxy = true;
389 if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
390 cachedProxyInfo = Proxy.detectProxyViaManual();
391 if (cachedProxyInfo != null) return cachedProxyInfo;
393 if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
394 cachedProxyInfo = platform._detectProxy();
395 if (cachedProxyInfo != null) return cachedProxyInfo;
397 return cachedProxyInfo;
400 // Helpful font parsing stuff //////////////////////////////////////////////////////
402 public static class ParsedFont {
403 public ParsedFont() { }
404 public ParsedFont(String s) { parse(s); }
405 public int size = 10;
406 public String name = "";
408 public boolean italic = false;
409 public boolean bold = false;
410 public boolean underline = false;
411 public boolean dotted_underline = false;
413 private static int stoi(Object o) {
414 if (o == null) return 0;
415 if (o instanceof Integer) return ((Integer)o).intValue();
417 String s = o.toString();
418 try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
419 catch (NumberFormatException e) { return 0; }
422 public void parse(String font) {
424 while(i < font.length() && !Character.isDigit(font.charAt(i)) && font.charAt(i) != '*') i++;
425 name = font.substring(0, i).toLowerCase().replace('_', ' ');
430 dotted_underline = false;
431 if (i != font.length()) {
432 if (font.charAt(i) == '*') {
437 while (j < font.length() && Character.isDigit(font.charAt(j))) j++;
438 if (i != j) size = stoi(font.substring(i, j));
441 while(i < font.length()) {
442 switch (font.charAt(i)) {
443 case 'b': bold = true; break;
444 case 'i': italic = true; break;
445 case 'd': dotted_underline = true; break;
446 case 'u': underline = true; break;