0d02cd0e3dc469c05d70bfdba27c80ca2f84e666
[org.ibex.core.git] / src / org / xwt / Platform.java
1 // Copyright 2004 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.js.*;
9 import org.xwt.util.*;
10
11 /** 
12  *  Abstracts away the small irregularities in JVM implementations.
13  *
14  *  The default Platform class supports a vanilla JDK 1.1
15  *  JVM. Subclasses are provided for other VMs. Methods whose names
16  *  start with an underscore are meant to be overridden by
17  *  subclasses. If you create a subclass of Platform, you should put
18  *  it in the org.xwt.plat package, and add code to this file's static
19  *  block to detect the new platform.
20  */
21 public abstract class Platform {
22
23     public Platform() { platform = this; }
24
25     // Static Data /////////////////////////////////////////////////////////////////////////////////////
26
27     static boolean clipboardReadEnabled = false;       ///< true iff inside a C-v/A-v/Press3 trap handler
28     static Platform platform = null;                   ///< The appropriate Platform object for this JVM
29     static boolean alreadyDetectedProxy = false;       ///< true if proxy autodetection has already been run
30     static org.xwt.HTTP.Proxy cachedProxyInfo = null;  ///< the result of proxy autodetection
31     public static String build = "unknown";            ///< the current build
32
33     // VM Detection Logic /////////////////////////////////////////////////////////////////////
34
35     public static void forceLoad() { }                 ///< do-nothing method that forces &lt;clinit&gt; to run
36
37     // If you create a new subclass of Platform, you should add logic
38     // here to detect it. Do not reference your class directly -- use
39     // reflection.
40
41     static {
42         System.err.println("Detecting JVM...");
43         try {
44             String vendor = System.getProperty("java.vendor", "");
45             String version = System.getProperty("java.version", "");
46             String os_name = System.getProperty("os.name", "");
47             String os_version = System.getProperty("os.version", "");
48             String platform_class = null;
49             
50             if (os_name.startsWith("Darwin")) platform_class = "Darwin";
51             else if (vendor.startsWith("Free Software Foundation")) {
52                 if (os_name.startsWith("Window")) platform_class = "Win32";
53                 else platform_class = "X11";
54             } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
55             else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
56             else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java2";
57
58             // Disable 2d hardware acceleration on Jaguar (do we need this?)
59             // if (os_name.equals("Mac OS X") && os_version.startsWith("10.2")) System.setProperty("com.apple.hwaccel", "false");
60             //System.setProperty("com.apple.hwaccel", "false");
61
62             if (platform_class != null)
63                 Class.forName("org.xwt.plat." + platform_class).newInstance();
64
65             String term = Platform.getEnv("TERM");
66             Log.color = term != null && term.length() != 0 && !term.equals("cygwin");
67             
68             try {
69                 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
70             } catch (ClassNotFoundException cnfe) {
71             } catch (Exception e) {
72                 if (Log.on) Log.info(Platform.class, "exception while detecting build:");
73                 if (Log.on) Log.info(Platform.class, e);
74             }
75             if (Log.on) Log.diag(Platform.class, "XWT build: " + build);
76
77             if (Log.on) Log.diag(Platform.class, "XWT VM detection:   vendor = " + vendor);
78             if (Log.on) Log.diag(Platform.class, "                   version = " + version);
79             if (Log.on) Log.diag(Platform.class, "                        os = " + os_name + " [version " + os_version + "]");
80
81             if (platform_class == null) {
82                 if (Log.on) Log.info(Platform.class, "Unable to detect JVM");
83                 criticalAbort("Unable to detect JVM");
84             }
85
86             if (Log.on) Log.diag(Platform.class, "                  platform = " + platform.getDescriptiveName());
87             if (Log.on) Log.diag(Platform.class, "                     class = " + platform.getClass().getName());
88             platform.postInit();
89
90         } catch (Exception e) {
91             if (Log.on) Log.info(Platform.class, "Exception while trying to detect JVM");
92             if (Log.on) Log.info(Platform.class, e);
93             criticalAbort("Unable to detect JVM");
94         }
95
96     }
97
98
99     // Methods to be Overridden ///////////////////////////////////////////////////////////////////
100
101     /** a string describing the VM */
102     protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
103
104     /** invoked after initialization messages have been printed; useful for additional platform detection log messages */
105     protected void postInit() { }
106
107     protected Surface _createSurface(Box b, boolean framed) { return null; }
108     protected Picture _createPicture(JS r) { return null; }
109     protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return null; }
110     protected Font.Glyph _createGlyph(org.xwt.Font f, char c) { return new DefaultGlyph(f, c); }
111
112     public static PixelBuffer createPixelBuffer(int w, int h, Surface s) { return platform._createPixelBuffer(w, h, s); }
113     public static Picture createPicture(JS r) { return platform._createPicture(r); }
114     public static Font.Glyph createGlyph(org.xwt.Font f, char c) { return platform._createGlyph(f, c); }
115     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
116         Surface ret = platform._createSurface(b, framed);
117         ret.setInvisible(false);
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                 Picture 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                 this.data = null;
278                 p.width = this.width;
279                 p.height = this.height;
280                 p.isLoaded = true;
281                 this.p = p;
282             }
283             return p;
284         }
285     }
286
287
288 }
289
290