00b00d2c8ea07bbc1bacbabd8cf9cca0e5e58d9e
[org.ibex.core.git] / src / org / xwt / Platform.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.lang.reflect.*;
5 import java.net.*;
6 import java.io.*;
7 import java.util.*;
8 import org.xwt.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.xwt.plat package, and add code to this file's static
18  *  block to detect the new platform.
19  */
20 public class Platform {
21
22     // Static Data /////////////////////////////////////////////////////////////////////////////////////
23
24     /**
25      *  set to true during the delivery of a KeyPressed:C-v/A-v or Press3; it is safe to use a
26      *  'global' here, since message delivery is single-threaded and non-preemptable
27      */
28     static boolean clipboardReadEnabled = false;
29
30     /** The appropriate Platform object for this JVM */
31     static Platform platform = null;
32
33     /** true if proxy autodetection has already been run */
34     static boolean alreadyDetectedProxy = false;
35
36     /** the result of proxy autodetection */
37     static org.xwt.HTTP.Proxy cachedProxyInfo = null;
38
39     /** the current build */
40     public static String build = "unknown";
41
42     // VM Detection Logic /////////////////////////////////////////////////////////////////////
43
44     /** do-nothing method that forces <clinit> to run */
45     public static void forceLoad() { }
46
47     // If you create a new subclass of Platform, you should add logic
48     // here to detect it. Do not reference your class directly -- use
49     // reflection.
50
51     static {
52         System.err.println("Detecting JVM...");
53         try {
54             String vendor = System.getProperty("java.vendor", "");
55             String version = System.getProperty("java.version", "");
56             String os_name = System.getProperty("os.name", "");
57             String os_version = System.getProperty("os.version", "");
58             String platform_class = null;
59             
60             if (os_name.startsWith("Darwin")) platform_class = "Darwin";
61             else if (vendor.startsWith("Free Software Foundation")) {
62                 if (os_name.startsWith("Window")) platform_class = "Win32";
63                 else platform_class = "X11";
64             } else if (version.startsWith("1.1") && vendor.startsWith("Netscape")) platform_class = "Netscape";
65             else if (version.startsWith("1.1") && vendor.startsWith("Microsoft")) platform_class = "Microsoft";
66             else if (!version.startsWith("1.0") && !version.startsWith("1.1")) platform_class = "Java2";
67
68             /*
69             // Disable 2d hardware acceleration on Jaguar
70             if (os_name.equals("Mac OS X") && os_version.startsWith("10.2")) System.setProperty("com.apple.hwaccel", "false");
71             */
72
73             if (platform_class != null) {
74                 platform = (Platform)Class.forName("org.xwt.plat." + platform_class).newInstance();
75                 platform.init();
76             }
77
78             try {
79                 build = (String)Class.forName("org.xwt.Build").getField("build").get(null);
80             } catch (ClassNotFoundException cnfe) {
81             } catch (Exception e) {
82                 if (Log.on) Log.log(Platform.class, "exception while detecting build:");
83                 if (Log.on) Log.log(Platform.class, e);
84             }
85             if (Log.on) Log.log(Platform.class, "XWT build: " + build);
86
87             if (Log.on) Log.log(Platform.class, "XWT VM detection:   vendor = " + vendor);
88             if (Log.on) Log.log(Platform.class, "                   version = " + version);
89             if (Log.on) Log.log(Platform.class, "                        os = " + os_name + " [version " + os_version + "]");
90
91             if (platform_class == null) {
92                 if (Log.on) Log.log(Platform.class, "Unable to detect JVM");
93                 new Platform().criticalAbort("Unable to detect JVM");
94             }
95
96             if (Log.on) Log.log(Platform.class, "                  platform = " + platform.getDescriptiveName());
97             if (Log.on) Log.log(Platform.class, "                     class = " + platform.getClass().getName());
98             platform.postInit();
99
100         } catch (Exception e) {
101             if (Log.on) Log.log(Platform.class, "Exception while trying to detect JVM");
102             if (Log.on) Log.log(Platform.class, e);
103             new Platform().criticalAbort("Unable to detect JVM");
104         }
105
106     }
107
108
109     // Methods to be Overridden ////////////////////////////////////////////////////////////////////
110
111     /** a string describing the VM */
112     protected String getDescriptiveName() { return "Generic Java 1.1 VM"; }
113
114     /** this initializes the platform; code in here can invoke methods on Platform since Platform.platform has already been set */
115     protected void init() { }
116     protected void postInit() { }
117
118     /** creates and returns a doublebuffer 'belonging' to <tt>owner</tt>; we need to associate PixelBuffers to surfaces
119      *  due to AWT 1.1 requirements (definately for Navigator, possibly also for MSJVM).
120      */
121     public static PixelBuffer createPixelBuffer(int w, int h, Surface s) { return platform._createPixelBuffer(w, h, s); }
122     protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return null; }
123     
124     /** creates and returns a picture */
125     public static Picture createPicture(int[] data, int w, int h) { return platform._createPicture(data, w, h); }
126     public static Picture createAlphaOnlyPicture(byte[] data, int w, int h) { return platform._createAlphaOnlyPicture(data, w, h); }
127     
128     protected Picture _createPicture(int[] b, int w, int h) { return null; }
129     protected Picture _createAlphaOnlyPicture(byte[] b, int w, int h) {
130         int[] b2 = new int[b.length];
131         for(int i=0;i<b.length;i++) b2[i] = (b[i]&0xff) << 24;
132         return _createPicture(b2,w,h);
133     }
134
135     /** should return true if it is safe to supress full-surface dirties immediately after a window resize */
136     public static boolean supressDirtyOnResize() { return platform._supressDirtyOnResize(); }
137     protected boolean _supressDirtyOnResize() { return false; }
138
139     /** the human-readable name of the key mapped to XWT's 'alt' key */
140     public static String altKeyName() { return platform._altKeyName(); }
141     protected String _altKeyName() { return "alt"; }
142
143     /** returns the contents of the clipboard */    
144     public static Object getClipBoard() { return clipboardReadEnabled ? platform._getClipBoard() : null; }
145     protected String _getClipBoard() { return null; }
146
147     /** sets the contents of the clipboard */
148     public static void setClipBoard(String s) { platform._setClipBoard(s); }
149     protected void _setClipBoard(String s) { }
150
151     /** returns the width of the screen, in pixels */
152     public static int getScreenWidth() { return platform._getScreenWidth(); }
153     protected int _getScreenWidth() { return 640; }
154
155     /** returns the height of the screen, in pixels */
156     public static int getScreenHeight() { return platform._getScreenHeight(); }
157     protected int _getScreenHeight() { return 480; }
158
159     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
160     protected void _criticalAbort(String message) { System.exit(-1); }
161
162     /** if true, org.xwt.Surface will generate a Click automatically after a press and a release */
163     public static boolean needsAutoClick() { return platform._needsAutoClick(); }
164     protected boolean _needsAutoClick() { return false; }
165
166     /** if true, org.xwt.Surface will generate a DoubleClick automatically after recieving two clicks in a short period of time */
167     public static boolean needsAutoDoubleClick() { return platform._needsAutoDoubleClick(); }
168     protected boolean _needsAutoDoubleClick() { return false; }
169
170     /** returns true iff the platform has a case-sensitive filesystem */
171     public static boolean isCaseSensitive() { return platform._isCaseSensitive(); }
172     protected boolean _isCaseSensitive() { return true; }
173
174     /** returns an InputStream to the builtin xwar */
175     public static InputStream getBuiltinInputStream() { return platform._getBuiltinInputStream(); }
176     protected InputStream _getBuiltinInputStream() {
177         return this.getClass().getClassLoader().getResourceAsStream("org/xwt/builtin.jar");
178     }
179
180     /** returns the value of the environment variable key, or null if no such key exists */
181     public static String getEnv(String key) { return platform._getEnv(key); }
182     protected String _getEnv(String key) {
183         try {
184             String os = System.getProperty("os.name").toLowerCase();
185             Process p;
186             if (os.indexOf("windows 9") != -1 || os.indexOf("windows me") != -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("command.com /c set");
190             } else if (os.indexOf("windows") > -1) {
191                 // hack -- jdk1.2/1.3 on Win32 pop open an ugly DOS box; 1.4 does not
192                 if (platform.getClass().getName().endsWith("Java12")) return null;
193                 p = Runtime.getRuntime().exec("cmd.exe /c set");
194             } else {  
195                 p = Runtime.getRuntime().exec("env");
196             }
197             BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
198             String s;
199             while ((s = br.readLine()) != null)
200                 if (s.startsWith(key + "="))
201                     return s.substring(key.length() + 1);
202         } catch (Exception e) {
203             if (Log.on) Log.log(this, "Exception while reading from environment:");
204             if (Log.on) Log.log(this, e);
205         }
206         return null;
207     }
208
209     /** convert a JPEG into an Image */
210     public static synchronized Picture decodeJPEG(InputStream is, String name) { return platform._decodeJPEG(is, name); }
211     protected Picture _decodeJPEG(InputStream is, String name) { return null; }
212
213     /** displays a platform-specific "open file" dialog and returns the chosen filename, or null if the user hit cancel */
214     protected String _fileDialog(String suggestedFileName, boolean write) { return null; }
215     public static String fileDialog(String suggestedFileName, boolean write) throws org.xwt.js.JS.Exn {
216         return platform._fileDialog(suggestedFileName, write);
217     }
218
219     /** default implementation is Eric Albert's BrowserLauncher.java */
220     protected void _newBrowserWindow(String url) {
221         try {
222             Class c = Class.forName("edu.stanford.ejalbert.BrowserLauncher");
223             Method m = c.getMethod("openURL", new Class[] { String.class });
224             m.invoke(null, new String[] { url });
225         } catch (Exception e) {
226             Log.log(this, e);
227         }
228     }
229
230     /** opens a new browser window */
231     public static void newBrowserWindow(String url) {
232         if (!(url.startsWith("https://") || url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("mailto:"))) {
233             if (Log.on) Log.log(Platform.class, "xwt.newBrowserWindow() only supports http and https urls");
234             return;
235         }
236
237         // check the URL for well-formedness, as a defense against buffer overflow attacks
238         try {
239             String u = url;
240             if (u.startsWith("https")) u = "http" + u.substring(5);
241             new URL(u);
242         } catch (MalformedURLException e) {
243             if (Log.on) Log.log(Platform.class, "URL " + url + " is not well-formed");
244             if (Log.on) Log.log(Platform.class, e);
245         }
246
247         if (Log.on) Log.log(Platform.class, "newBrowserWindow, url = " + url);
248         platform._newBrowserWindow(url);
249     }
250
251     /** used to notify the user of very serious failures; usually used when logging is not working or unavailable */
252     public static void criticalAbort(String message) {
253         if (Log.on) Log.log(Platform.class, "Critical Abort:");
254         if (Log.on) Log.log(Platform.class, message);
255         platform._criticalAbort(message);
256     }
257
258     /** this method invokes the platform _createSurface() method and then enforces a few post-call invariants */
259     protected Surface _createSurface(Box b, boolean framed) { return null; }
260     public static Surface createSurface(Box b, boolean framed, boolean refreshable) {
261         Surface ret = platform._createSurface(b, framed);
262         ret.setInvisible(false);
263
264         ret.setLimits(b.minwidth, b.minheight, b.maxwidth, b.maxheight);
265
266         if (refreshable) {
267             Surface.allSurfaces.addElement(ret);
268             ret.dirty(0, 0, b.width, b.height);
269             ret.Refresh();
270         }
271         return ret;
272     }
273
274     /** detects proxy settings */
275     protected synchronized org.xwt.HTTP.Proxy _detectProxy() { return null; }
276     public static synchronized org.xwt.HTTP.Proxy detectProxy() {
277
278         if (cachedProxyInfo != null) return cachedProxyInfo;
279         if (alreadyDetectedProxy) return null;
280         alreadyDetectedProxy = true;
281
282         if (Log.on) Log.log(Platform.class, "attempting environment-variable DNS proxy detection");
283         cachedProxyInfo = org.xwt.HTTP.Proxy.detectProxyViaManual();
284         if (cachedProxyInfo != null) return cachedProxyInfo;
285
286         if (Log.on) Log.log(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
287         cachedProxyInfo = platform._detectProxy();
288         if (cachedProxyInfo != null) return cachedProxyInfo;
289
290         return cachedProxyInfo;
291     }
292
293     /** returns a Scheduler instance; used to implement platform-specific schedulers */
294     protected Scheduler _getScheduler() { return new Scheduler(); }
295     public static Scheduler getScheduler() { return platform._getScheduler(); }
296     
297     public static void running() { platform._running(); }
298     public void _running() { new Semaphore().block(); }
299 }
300
301