1    // Copyright 2004 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.js.*;
9    import org.xwt.util.*;
10   
11   /** 
12    *  Abstracts away the small irregularities in JVM implementations.
13    *
14    *  The default Platform class supports a vanilla JDK 1.1
15    *  JVM. Subclasses are provided for other VMs. Methods whose names
16    *  start with an underscore are meant to be overridden by
17    *  subclasses. If you create a subclass of Platform, you should put
18    *  it in the org.xwt.plat package, and add code to this file's static
19    *  block to detect the new platform.
20    */
21   public abstract class Platform {
22   
23       public Platform() { platform = this; }
24   
25       // Static Data /////////////////////////////////////////////////////////////////////////////////////
26   
27       static boolean clipboardReadEnabled = false;       ///< true iff inside a C-v/A-v/Press3 trap handler
28       static Platform platform = null;                   ///< The appropriate Platform object for this JVM
29       static boolean alreadyDetectedProxy = false;       ///< true if proxy autodetection has already been run
30       static org.xwt.HTTP.Proxy cachedProxyInfo = null;  ///< the result of proxy autodetection
31       public static String build = "unknown";            ///< the current build
32   
33       // VM Detection Logic /////////////////////////////////////////////////////////////////////
34   
35       // If you create a new subclass of Platform, you should add logic
36       // here to detect it. Do not reference your class directly -- use
37       // reflection.
38   
39       public static void forceLoad() {
40           System.err.print("Detecting JVM...");
41           try {
42               String vendor = System.getProperty("java.vendor", "");
43               String version = System.getProperty("java.version", "");
44               String os_name = System.getProperty("os.name", "");
45               String os_version = System.getProperty("os.version", "");
46               String platform_class = null;
47               
48               if (vendor.startsWith("Free Software Foundation")) {
49                   if (os_name.startsWith("Window")) platform_class = "Win32";
50                   else if (os_name.startsWith("Linux")) platform_class = "Linux";
51                   else if (os_name.startsWith("SunOS")) platform_class = "Solaris";
52                   else if (os_name.startsWith("Solaris")) platform_class = "Solaris";
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.xwt.plat." + platform_class);
63               try {
64                   if (platform_class != null) Class.forName("org.xwt.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.xwt.Build").getField("build").get(null);
74                   Log.diag(Platform.class, "XWT build: " + build);
75               } catch (ClassNotFoundException cnfe) {
76                   Log.warn(Platform.class, "XWT 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, "XWT 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.xwt.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.xwt.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 XWT'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.xwt.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.xwt.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/xwt/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.xwt.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, "xwt.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          try {
233              String u = url;
234              if (u.startsWith("https")) u = "http" + u.substring(5);
235              new URL(u);
236          } catch (MalformedURLException e) {
237              Log.info(Platform.class, "URL " + url + " is not well-formed");
238              Log.info(Platform.class, e);
239          }
240          Log.info(Platform.class, "newBrowserWindow, url = " + url);
241          platform._newBrowserWindow(url);
242      }
243  
244      /** detects proxy settings */
245      protected synchronized org.xwt.HTTP.Proxy _detectProxy() { return null; }
246      public static synchronized org.xwt.HTTP.Proxy detectProxy() {
247  
248          if (cachedProxyInfo != null) return cachedProxyInfo;
249          if (alreadyDetectedProxy) return null;
250          alreadyDetectedProxy = true;
251  
252          Log.info(Platform.class, "attempting environment-variable DNS proxy detection");
253          cachedProxyInfo = org.xwt.HTTP.Proxy.detectProxyViaManual();
254          if (cachedProxyInfo != null) return cachedProxyInfo;
255  
256          Log.info(Platform.class, "attempting " + platform.getClass().getName() + " proxy detection");
257          cachedProxyInfo = platform._detectProxy();
258          if (cachedProxyInfo != null) return cachedProxyInfo;
259  
260          return cachedProxyInfo;
261     } 
262  
263      /** returns a Scheduler instance; used to implement platform-specific schedulers */
264      protected Scheduler _getScheduler() { return new Scheduler(); }
265      public static Scheduler getScheduler() { return platform._getScheduler(); }
266  
267      // FEATURE: be more efficient for many of the subclasses
268      public static class DefaultGlyph extends Font.Glyph {
269          private Picture p = null;
270          public DefaultGlyph(org.xwt.Font f, char c) { super(f, c); }
271          public Picture getPicture() {
272              if (p == null && isLoaded) {
273                  Picture p = createPicture(null);
274                  p.data = new int[data.length];
275                  for(int i=0; i<data.length; i++) p.data[i] = (data[i] & 0xff) << 24;
276                  this.data = null;
277                  p.width = this.width;
278                  p.height = this.height;
279                  p.isLoaded = true;
280                  this.p = p;
281              }
282              return p;
283          }
284      }
285  }
286  
287  
288