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