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