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