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