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