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