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