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.
7 import java.lang.reflect.*;
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.*;
19 * Abstracts away the small irregularities in JVM implementations.
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.
28 public abstract class Platform {
30 public Platform() { platform = this; }
32 // Static Data /////////////////////////////////////////////////////////////////////////////////////
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
40 // VM Detection Logic /////////////////////////////////////////////////////////////////////
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
46 public static void forceLoad() {
47 System.err.print("Detecting JVM...");
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;
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";
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");
70 System.err.println(" " + os_name + " ==> org.ibex.plat." + platform_class);
72 if (platform_class != null) Class.forName("org.ibex.plat." + platform_class).newInstance();
73 } catch (InstantiationException e) {
77 String term = Platform.getEnv("TERM");
78 Log.color = term != null && term.length() != 0 && !term.equals("cygwin");
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);
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());
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");
106 // Methods to be Overridden ///////////////////////////////////////////////////////////////////
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); }
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);
120 Surface.allSurfaces.addElement(ret);
125 if (b.get(JSU.S("titlebar")) != null) ret.setTitleBarText(JSU.toString(b.get(JSU.S("titlebar"))));
127 Log.warn(Platform.class, e);
132 /** a string describing the VM */
133 protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
135 /** invoked after initialization messages have been printed; useful for additional platform detection log messages */
136 protected void postInit() { }
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"; }
142 /** returns the contents of the clipboard */
143 public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
144 protected String _getClipBoard() { return null; }
146 /** sets the contents of the clipboard */
147 public static void setClipBoard(String s) { platform._setClipBoard(s); }
148 protected void _setClipBoard(String s) { }
150 /** returns the width of the screen, in pixels */
151 public static int getScreenWidth() { return platform._getScreenWidth(); }
152 protected int _getScreenWidth() { return 640; }
154 /** returns the height of the screen, in pixels */
155 public static int getScreenHeight() { return platform._getScreenHeight(); }
156 protected int _getScreenHeight() { return 480; }
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);
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; }
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; }
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; }
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");}
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) {
186 String os = System.getProperty("os.name").toLowerCase();
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");
197 p = Runtime.getRuntime().exec("env");
199 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
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:");
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);
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);
221 /** default implementation is Eric Albert's BrowserLauncher.java */
222 protected void _newBrowserWindow(String url) {
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");
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");
239 // check the URL for well-formedness, as a defense against buffer overflow attacks
240 // FIXME check URL without using URL class
244 if (u.startsWith("https")) u = "http" + u.substring(5);
246 } catch (MalformedURLException e) {
247 Log.info(Platform.class, "URL " + url + " is not well-formed");
248 Log.info(Platform.class, e);
251 Log.info(Platform.class, "newBrowserWindow, url = " + url);
252 platform._newBrowserWindow(url);
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() {
259 if (cachedProxyInfo != null) return cachedProxyInfo;
260 if (alreadyDetectedProxy) return null;
261 alreadyDetectedProxy = true;
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;
267 Log.info(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
268 cachedProxyInfo = platform._detectProxy();
269 if (cachedProxyInfo != null) return cachedProxyInfo;
271 return cachedProxyInfo;
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(); }
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;
288 p.width = this.width;
289 p.height = this.height;
297 /** Implements cooperative multitasking */
298 public static class Scheduler {
300 // Public API Exposed to org.ibex /////////////////////////////////////////////////
302 private static Scheduler singleton;
303 public static void add(Callable t) { Log.debug(Scheduler.class, "scheduling " + t); Scheduler.runnable.append(t); }
304 public static void init() { if (singleton == null) (singleton = Platform.getScheduler()).run(); }
306 private static Callable current = null;
308 private static volatile boolean rendering = false;
309 private static volatile boolean again = false;
311 /** synchronizd so that we can safely call it from an event-delivery thread, in-context */
312 public static void renderAll() {
313 if (rendering) { again = true; return; }
314 synchronized(Scheduler.class) {
318 // FEATURE: this could be cleaner
320 for(int i=0; i<Surface.allSurfaces.size(); i++) {
321 Surface s = ((Surface)Surface.allSurfaces.elementAt(i));
322 do { s.render(); } while(s.abort);
333 // API which must be supported by subclasses /////////////////////////////////////
336 * SCHEDULER INVARIANT: all scheduler implementations MUST invoke
337 * Surface.renderAll() after performing a Callable if no tasks remain
338 * in the queue. A scheduler may choose to invoke
339 * Surface.renderAll() more often than that if it so chooses.
341 public void run() { defaultRun(); }
342 public Scheduler() { }
345 // Default Implementation //////////////////////////////////////////////////////
347 protected static Queue runnable = new Queue(50);
348 public void defaultRun() {
350 current = (Callable)runnable.remove(true);
354 for(int i=0; i<Surface.allSurfaces.size(); i++) {
355 Surface s = (Surface)Surface.allSurfaces.elementAt(i);
356 if (current instanceof JS) {
357 s._mousex = Integer.MAX_VALUE;
358 s._mousey = Integer.MAX_VALUE;
360 s._mousex = s.mousex;
361 s._mousey = s.mousey;
364 Log.debug(Scheduler.class, "performing " + current);
369 Log.info(Scheduler.class, "a JavaScript thread spawned with ibex.thread() threw an exception:");
370 Log.info(Scheduler.class,e);
371 } catch (Exception e) {
372 Log.info(Scheduler.class, "a Callable threw an exception which was caught by the scheduler:");
373 Log.info(Scheduler.class, e);
374 } catch (Throwable t) {
377 // if an Error is thrown it will cause the engine to quit