2004/01/03 04:21:15
[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 abstract class Platform {
21
22     public Platform() { platform = this; }
23
24     // Static Data /////////////////////////////////////////////////////////////////////////////////////
25
26     static boolean clipboardReadEnabled = false;       ///< true iff inside a C-v/A-v/Press3 trap handler
27     static Platform platform = null;                   ///< The appropriate Platform object for this JVM
28     static boolean alreadyDetectedProxy = false;       ///< true if proxy autodetection has already been run
29     static org.xwt.HTTP.Proxy cachedProxyInfo = null;  ///< the result of proxy autodetection
30     public static String build = "unknown";            ///< the current build
31
32     // VM Detection Logic /////////////////////////////////////////////////////////////////////
33
34     public static void forceLoad() { }                 ///< do-nothing method that forces &lt;clinit&gt; to run
35
36     // If you create a new subclass of Platform, you should add logic
37     // here to detect it. Do not reference your class directly -- use
38     // reflection.
39
40     static {
41         System.err.println("Detecting JVM...");
42         try {
43             String vendor = System.getProperty("java.vendor", "");
44             String version = System.getProperty("java.version", "");
45             String os_name = System.getProperty("os.name", "");
46             String os_version = System.getProperty("os.version", "");
47             String platform_class = null;
48             
49             if (os_name.startsWith("Darwin")) platform_class = "Darwin";
50             else if (vendor.startsWith("Free Software Foundation")) {
51                 if (os_name.startsWith("Window")) platform_class = "Win32";
52                 else platform_class = "X11";
53             } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
54             else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
55             else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java2";
56
57             // Disable 2d hardware acceleration on Jaguar (do we need this?)
58             // if (os_name.equals("Mac OS X") && os_version.startsWith("10.2")) System.setProperty("com.apple.hwaccel", "false");
59             //System.setProperty("com.apple.hwaccel", "false");
60
61             if (platform_class != null)
62                 Class.forName("org.xwt.plat." + platform_class).newInstance();
63
64             String term = Platform.getEnv("TERM");
65             Log.color = term != null && term.length() != 0 && !term.equals("cygwin");
66             
67             try {
68                 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
69             } catch (ClassNotFoundException cnfe) {
70             } catch (Exception e) {
71                 if (Log.on) Log.info(Platform.class, "exception while detecting build:");
72                 if (Log.on) Log.info(Platform.class, e);
73             }
74             if (Log.on) Log.diag(Platform.class, "XWT build: " + build);
75
76             if (Log.on) Log.diag(Platform.class, "XWT VM detection:   vendor = " + vendor);
77             if (Log.on) Log.diag(Platform.class, "                   version = " + version);
78             if (Log.on) Log.diag(Platform.class, "                        os = " + os_name + " [version " + os_version + "]");
79
80             if (platform_class == null) {
81                 if (Log.on) Log.info(Platform.class, "Unable to detect JVM");
82                 criticalAbort("Unable to detect JVM");
83             }
84
85             if (Log.on) Log.diag(Platform.class, "                  platform = " + platform.getDescriptiveName());
86             if (Log.on) Log.diag(Platform.class, "                     class = " + platform.getClass().getName());
87             platform.postInit();
88
89         } catch (Exception e) {
90             if (Log.on) Log.info(Platform.class, "Exception while trying to detect JVM");
91             if (Log.on) Log.info(Platform.class, e);
92             criticalAbort("Unable to detect JVM");
93         }
94
95     }
96
97
98     // Methods to be Overridden ///////////////////////////////////////////////////////////////////
99
100     /** a string describing the VM */
101     protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
102
103     /** invoked after initialization messages have been printed; useful for additional platform detection log messages */
104     protected void postInit() { }
105
106     protected Surface _createSurface(Box b, boolean framed) { return null; }
107     protected Picture _createPicture(Stream r) { return null; }
108     protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return null; }
109     protected Font.Glyph _createGlyph(org.xwt.Font f, char c) { return new DefaultGlyph(f, c); }
110
111     public static PixelBuffer createPixelBuffer(int w, int h, Surface s) { return platform._createPixelBuffer(w, h, s); }
112     public static Picture createPicture(Stream r) { return platform._createPicture(r); }
113     public static Font.Glyph createGlyph(org.xwt.Font f, char c) { return platform._createGlyph(f, c); }
114     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
115         Surface ret = platform._createSurface(b, framed);
116         ret.setInvisible(false);
117         ret.setLimits(b.minwidth, b.minheight, b.maxwidth, b.maxheight);
118         if (refreshable) {
119             Surface.allSurfaces.addElement(ret);
120             ret.dirty(0, 0, b.width, b.height);
121             ret.Refresh();
122         }
123         return ret;
124     }
125
126     /** the human-readable name of the key mapped to XWT's 'alt' key */
127     public static String altKeyName() { return platform._altKeyName(); }
128     protected String _altKeyName() { return "alt"; }
129
130     /** returns the contents of the clipboard */    
131     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
132     protected String _getClipBoard() { return null; }
133
134     /** sets the contents of the clipboard */
135     public static void setClipBoard(String s) { platform._setClipBoard(s); }
136     protected void _setClipBoard(String s) { }
137
138     /** returns the width of the screen, in pixels */
139     public static int getScreenWidth() { return platform._getScreenWidth(); }
140     protected int _getScreenWidth() { return 640; }
141
142     /** returns the height of the screen, in pixels */
143     public static int getScreenHeight() { return platform._getScreenHeight(); }
144     protected int _getScreenHeight() { return 480; }
145
146     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
147     protected void _criticalAbort(String message) { System.exit(-1); }
148
149     /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
150     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
151     protected boolean _needsAutoClick() { return false; }
152
153     /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
154     public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
155     protected boolean _needsAutoDoubleClick() { return false; }
156
157     /** returns true iff the platform has a case-sensitive filesystem */
158     public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
159     protected boolean _isCaseSensitive() { return true; }
160
161     /** returns an InputStream to the builtin xwar */
162     public static InputStream getBuiltinInputStream() { return platform._getBuiltinInputStream(); }
163     protected InputStream _getBuiltinInputStream() {
164         return this.getClass().getClassLoader().getResourceAsStream("org/xwt/builtin.jar");
165     }
166
167     /** returns the value of the environment variable key, or null if no such key exists */
168     public static String getEnv(String key) { return platform._getEnv(key); }
169     protected String _getEnv(String key) {
170         try {
171             String os = System.getProperty("os.name").toLowerCase();
172             Process p;
173             if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -1) {
174                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
175                 if (platform.getClass().getName().endsWith("Java12")) return null;
176                 p = Runtime.getRuntime().exec("command.com /c set");
177             } else if (os.indexOf("windows") > -1) {
178                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
179                 if (platform.getClass().getName().endsWith("Java12")) return null;
180                 p = Runtime.getRuntime().exec("cmd.exe /c set");
181             } else {  
182                 p = Runtime.getRuntime().exec("env");
183             }
184             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
185             String s;
186             while ((s = br.readLine()) != null)
187                 if (s.startsWith(key + "="))
188                     return s.substring(key.length() + 1);
189         } catch (Exception e) {
190             if (Log.on) Log.info(this, "Exception while reading from environment:");
191             if (Log.on) Log.info(this, e);
192         }
193         return null;
194     }
195
196     /** convert a JPEG into an Image */
197     public static synchronized void decodeJPEG(InputStream is, Picture p) { platform._decodeJPEG(is, p); }
198     protected abstract void _decodeJPEG(InputStream is, Picture p);
199
200     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
201     protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
202     public static String fileDialog(String suggestedFileName, boolean write) throws org.xwt.js.JSExn {
203         return platform._fileDialog(suggestedFileName, write);
204     }
205
206     /** default implementation is Eric Albert's BrowserLauncher.java */
207     protected void _newBrowserWindow(String url) {
208         try {
209             Class c = Class.forName("edu.stanford.ejalbert.BrowserLauncher");
210             Method m = c.getMethod("openURL", new Class[] { String.class });
211             m.invoke(null, new String[] { url });
212         } catch (Exception e) {
213             Log.info(this, e);
214         }
215     }
216
217     /** opens a new browser window */
218     public static void newBrowserWindow(String url) {
219         if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
220             if (Log.on) Log.info(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
221             return;
222         }
223
224         // check the URL for well-formedness, as a defense against buffer overflow attacks
225         try {
226             String u = url;
227             if (u.startsWith("https")) u = "http" + u.substring(5);
228             new URL(u);
229         } catch (MalformedURLException e) {
230             if (Log.on) Log.info(Platform.class, "URL " + url + " is not well-formed");
231             if (Log.on) Log.info(Platform.class, e);
232         }
233
234         if (Log.on) Log.info(Platform.class, "newBrowserWindow, url = " + url);
235         platform._newBrowserWindow(url);
236     }
237
238     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
239     public static void criticalAbort(String message) {
240         if (Log.on) Log.info(Platform.class, "Critical Abort:");
241         if (Log.on) Log.info(Platform.class, message);
242         platform._criticalAbort(message);
243     }
244
245     /** detects proxy settings */
246     protected synchronized org.xwt.HTTP.Proxy _detectProxy() { return null; }
247     public static synchronized org.xwt.HTTP.Proxy detectProxy() {
248
249         if (cachedProxyInfo != null) return cachedProxyInfo;
250         if (alreadyDetectedProxy) return null;
251         alreadyDetectedProxy = true;
252
253         if (Log.on) Log.info(Platform.class, "attempting environment-variable DNS proxy detection");
254         cachedProxyInfo = org.xwt.HTTP.Proxy.detectProxyViaManual();
255         if (cachedProxyInfo != null) return cachedProxyInfo;
256
257         if (Log.on) Log.info(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
258         cachedProxyInfo = platform._detectProxy();
259         if (cachedProxyInfo != null) return cachedProxyInfo;
260
261         return cachedProxyInfo;
262    } 
263
264     /** returns a Scheduler instance; used to implement platform-specific schedulers */
265     protected Scheduler _getScheduler() { return new Scheduler(); }
266     public static Scheduler getScheduler() { return platform._getScheduler(); }
267
268     // FEATURE: be more efficient for many of the subclasses
269     public static class DefaultGlyph extends Font.Glyph {
270         private Picture p = null;
271         public DefaultGlyph(org.xwt.Font f, char c) { super(f, c); }
272         public Picture getPicture() {
273             if (p == null && isLoaded) {
274                 p = createPicture(null);
275                 p.data = new int[data.length];
276                 for(int i=0; i<data.length; i++) p.data[i] = (data[i] & 0xff) << 24;
277                 data = null;
278                 p.width = this.width;
279                 p.height = this.height;
280             }
281             return p;
282         }
283     }
284
285
286 }
287
288