2003/10/16 05:39:20
[org.ibex.core.git] / src / org / xwt / Platform.java
1 // Copyright 2003 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     /**
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
27      */
28     static boolean clipboardReadEnabled = false;
29
30     /** The appropriate Platform object for this JVM */
31     static Platform platform = null;
32
33     /** true if proxy autodetection has already been run */
34     static boolean alreadyDetectedProxy = false;
35
36     /** the result of proxy autodetection */
37     static HTTP.Proxy cachedProxyInfo = null;
38
39     /** the current build */
40     public static String build = "unknown";
41
42     // VM Detection Logic /////////////////////////////////////////////////////////////////////
43
44     /** do-nothing method that forces <clinit> to run */
45     public static void forceLoad() { }
46
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
49     // reflection.
50
51     static {
52         System.err.println("Detecting JVM...");
53         try {
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;
59             
60             if (os_name.startsWith("Darwin")) platform_class = "Darwin";
61             else if (vendor.startsWith("Free Software Foundation")) {
62                 if (os_name.startsWith("Window")) platform_class = "Win32";
63                 else platform_class = "X11";
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.0") && !version.startsWith("1.1")) platform_class = "Java2";
67
68             /*
69         // Disable 2d hardware acceleration on Jaguar
70         if (os_name.equals("Mac OS X") && os_version.equals("10.2"))
71             */
72         System.setProperty("com.apple.hwaccel", "false");
73
74             if (platform_class != null) {
75                 platform = (Platform)Class.forName("org.xwt.plat." + platform_class).newInstance();
76                 platform.init();
77             }
78
79             try {
80                 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
81             } catch (ClassNotFoundException cnfe) {
82             } catch (Exception e) {
83                 if (Log.on) Log.log(Platform.class, "exception while detecting build:");
84                 if (Log.on) Log.log(Platform.class, e);
85             }
86             if (Log.on) Log.log(Platform.class, "XWT build: " + build);
87
88             if (Log.on) Log.log(Platform.class, "XWT VM detection:   vendor = " + vendor);
89             if (Log.on) Log.log(Platform.class, "                   version = " + version);
90             if (Log.on) Log.log(Platform.class, "                        os = " + os_name + " [version " + os_version + "]");
91
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");
95             }
96
97             if (Log.on) Log.log(Platform.class, "                  platform = " + platform.getDescriptiveName());
98             if (Log.on) Log.log(Platform.class, "                     class = " + platform.getClass().getName());
99             platform.postInit();
100
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");
105         }
106
107     }
108
109
110     // Methods to be Overridden ////////////////////////////////////////////////////////////////////
111
112     /** a string describing the VM */
113     protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
114
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() { }
118
119     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt>; we need to associate PixelBuffers to surfaces
120      *  due to AWT 1.1 requirements (definately for Navigator, possibly also for MSJVM).
121      */
122     public static PixelBuffer createPixelBuffer(int w, int h, Surface s) { return platform._createPixelBuffer(w, h, s); }
123     protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return null; }
124     
125     /** creates and returns a picture */
126     public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
127     public static Picture createAlphaOnlyPicture(byte[] data, int w, int h) { return platform._createAlphaOnlyPicture(data, w, h); }
128     
129     protected Picture _createPicture(int[] b, int w, int h) { return null; }
130     protected Picture _createAlphaOnlyPicture(byte[] b, int w, int h) {
131         int[] b2 = new int[b.length];
132         for(int i=0;i<b.length;i++) b2[i] = (b[i]&0xff) << 24;
133         return _createPicture(b2,w,h);
134     }
135
136     /** creates a socket object */
137     public static Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
138         return platform._getSocket(host, port, ssl, negotiate);
139     }
140     protected Socket _getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
141         Socket ret = ssl ? new TinySSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
142         ret.setTcpNoDelay(true);
143         return ret;
144     }
145     
146     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
147     public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
148     protected boolean _supressDirtyOnResize() { return false; }
149
150     /** the human-readable name of the key mapped to XWT's 'alt' key */
151     public static String altKeyName() { return platform._altKeyName(); }
152     protected String _altKeyName() { return "alt"; }
153
154     /** returns the contents of the clipboard */    
155     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
156     protected String _getClipBoard() { return null; }
157
158     /** sets the contents of the clipboard */
159     public static void setClipBoard(String s) { platform._setClipBoard(s); }
160     protected void _setClipBoard(String s) { }
161
162     /** returns the width of the screen, in pixels */
163     public static int getScreenWidth() { return platform._getScreenWidth(); }
164     protected int _getScreenWidth() { return 640; }
165
166     /** returns the height of the screen, in pixels */
167     public static int getScreenHeight() { return platform._getScreenHeight(); }
168     protected int _getScreenHeight() { return 480; }
169
170     /** returns the maximum number of threads that the XWT engine can create without adversely affecting the host OS */
171     public static int maxThreads() { return platform._maxThreads(); }
172     protected int _maxThreads() { return 25; }
173
174     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
175     protected void _criticalAbort(String message) { System.exit(-1); }
176
177     /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
178     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
179     protected boolean _needsAutoClick() { return false; }
180
181     /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
182     public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
183     protected boolean _needsAutoDoubleClick() { return false; }
184
185     /** returns true iff the platform has a case-sensitive filesystem */
186     public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
187     protected boolean _isCaseSensitive() { return true; }
188
189     /** returns an InputStream to the builtin xwar */
190     public static InputStream getBuiltinInputStream() { return platform._getBuiltinInputStream(); }
191     protected InputStream _getBuiltinInputStream() {
192         return this.getClass().getClassLoader().getResourceAsStream("org/xwt/builtin.jar");
193     }
194
195     /** returns the value of the environment variable key, or null if no such key exists */
196     public static String getEnv(String key) { return platform._getEnv(key); }
197     protected String _getEnv(String key) {
198         try {
199             String os = System.getProperty("os.name").toLowerCase();
200             Process p;
201             if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -1) {
202                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
203                 if (platform.getClass().getName().endsWith("Java12")) return null;
204                 p = Runtime.getRuntime().exec("command.com /c set");
205             } else if (os.indexOf("windows") > -1) {
206                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
207                 if (platform.getClass().getName().endsWith("Java12")) return null;
208                 p = Runtime.getRuntime().exec("cmd.exe /c set");
209             } else {  
210                 p = Runtime.getRuntime().exec("env");
211             }
212             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
213             String s;
214             while ((s = br.readLine()) != null)
215                 if (s.startsWith(key + "="))
216                     return s.substring(key.length() + 1);
217         } catch (Exception e) {
218             if (Log.on) Log.log(this, "Exception while reading from environment:");
219             if (Log.on) Log.log(this, e);
220         }
221         return null;
222     }
223
224     /** convert a JPEG into an Image */
225     public static synchronized Picture decodeJPEG(InputStream is, String name) { return platform._decodeJPEG(is, name); }
226     protected Picture _decodeJPEG(InputStream is, String name) { return null; }
227
228     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
229     protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
230     public static String fileDialog(String suggestedFileName, boolean write) {
231         if (!ThreadMessage.suspendThread()) return null;
232         try {
233             return platform._fileDialog(suggestedFileName, write);
234         } finally {
235             ThreadMessage.resumeThread();
236         }
237     }
238
239     /** default implementation is Eric Albert's BrowserLauncher.java */
240     protected void _newBrowserWindow(String url) {
241         try {
242             Class c = Class.forName("edu.stanford.ejalbert.BrowserLauncher");
243             Method m = c.getMethod("openURL", new Class[] { String.class });
244             m.invoke(null, new String[] { url });
245         } catch (Exception e) {
246             Log.log(this, e);
247         }
248     }
249
250     /** opens a new browser window */
251     public static void newBrowserWindow(String url) {
252         if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
253             if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
254             return;
255         }
256
257         // check the URL for well-formedness, as a defense against buffer overflow attacks
258         try {
259             String u = url;
260             if (u.startsWith("https")) u = "http" + u.substring(5);
261             new URL(u);
262         } catch (MalformedURLException e) {
263             if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
264             if (Log.on) Log.log(Platform.class, e);
265         }
266
267         if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
268         platform._newBrowserWindow(url);
269     }
270
271     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
272     public static void criticalAbort(String message) {
273         if (Log.on) Log.log(Platform.class, "Critical Abort:");
274         if (Log.on) Log.log(Platform.class, message);
275         platform._criticalAbort(message);
276     }
277
278     /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
279     protected Surface _createSurface(Box b, boolean framed) { return null; }
280     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
281         Surface ret = platform._createSurface(b, framed);
282         ret.setInvisible(false);
283
284         Object titlebar = b.get("titlebar", true);
285         if (titlebar != null) ret.setTitleBarText(titlebar.toString());
286
287         Object icon = b.get("icon", true);
288         if (icon != null && icon instanceof Res) {
289             Picture pic = Picture.fromRes((Res)icon);
290             if (pic != null) ret.setIcon(pic);
291             else if (Log.on) Log.log(Platform.class, "unable to load icon " + icon);
292         }
293
294         ret.setLimits(b.minwidth, b.minheight, b.maxwidth, b.maxheight);
295
296         if (refreshable) {
297             Surface.allSurfaces.addElement(ret);
298             ret.dirty(0, 0, b.width, b.height);
299             ret.Refresh();
300         }
301         return ret;
302     }
303
304     /** detects proxy settings */
305     protected synchronized HTTP.Proxy _detectProxy() { return null; }
306     public static synchronized HTTP.Proxy detectProxy() {
307
308         if (cachedProxyInfo != null) return cachedProxyInfo;
309         if (alreadyDetectedProxy) return null;
310         alreadyDetectedProxy = true;
311
312         if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
313         cachedProxyInfo = HTTP.Proxy.detectProxyViaManual();
314         if (cachedProxyInfo != null) return cachedProxyInfo;
315
316         if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
317         cachedProxyInfo = platform._detectProxy();
318         if (cachedProxyInfo != null) return cachedProxyInfo;
319
320         return cachedProxyInfo;
321     }
322     
323     public static void running() { platform._running(); }
324     public void _running() { new Semaphore().block(); }
325 }
326
327