move LocalStorage from core to plat
[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.crypto.*;
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     /** Implements cooperative multitasking */
298     public static class Scheduler {
299
300     // Public API Exposed to org.ibex /////////////////////////////////////////////////
301
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(); }
305
306     private static Callable current = null;
307
308     private static volatile boolean rendering = false;
309     private static volatile boolean again = false;
310
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) {
315             try {
316                 rendering = true;
317                 do {
318                     // FEATURE: this could be cleaner
319                     again = false;
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);
323                     }
324                 } while(again);
325             } finally {
326                 rendering = false;
327             }
328         }
329     }
330
331     
332
333         // API which must be supported by subclasses /////////////////////////////////////
334
335         /**
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.
340          */
341         public void run() { defaultRun(); }
342         public Scheduler() { }
343
344
345         // Default Implementation //////////////////////////////////////////////////////
346
347         protected static Queue runnable = new Queue(50);
348         public void defaultRun() {
349             while(true) {
350                 current = (Callable)runnable.remove(true);
351                 try {
352                     // FIXME hideous
353                     synchronized(this) {
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;
359                             } else {
360                                 s._mousex = s.mousex;
361                                 s._mousey = s.mousey;
362                             }
363                         }
364                         Log.debug(Scheduler.class, "performing " + current);
365                         current.run(null);
366                     }
367                     renderAll();
368                 } catch (JSExn e) {
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) {
375                     t.printStackTrace();
376                 }
377                 // if an Error is thrown it will cause the engine to quit
378             }
379         }
380     }
381
382     /** Manages access to ~/.ibex */
383     public static class LocalStorage {
384
385         static String ibexDirName = System.getProperty("user.home") + java.io.File.separatorChar + ".ibex";
386
387         static java.io.File ibexDir = null;
388         static java.io.File cacheDir = null;
389
390         static {
391             try {
392                 ibexDir = new java.io.File(ibexDirName);
393                 if (!ibexDir.mkdirs()) ibexDir = null;
394                 try {
395                     cacheDir = new java.io.File(ibexDirName + java.io.File.separatorChar + "cache");
396                     if (!cacheDir.mkdirs()) cacheDir = null;
397                 } catch (Exception e) {
398                     Log.warn(LocalStorage.class, "unable to create cache directory " +
399                              ibexDirName + java.io.File.separatorChar + "cache");
400                 }
401             } catch (Exception e) {
402                 Log.warn(LocalStorage.class, "unable to create ibex directory " + ibexDirName);
403             }
404         }
405
406         // FEATURE: we ought to be able to do stuff like sha1-checking and date checking on cached resources    
407         public static class Cache {
408
409             private static void delTree(java.io.File f) throws IOException {
410                 if (f.isDirectory()) {
411                     String[] s = f.list();
412                     for(int i=0; i<s.length; i++)
413                         delTree(new java.io.File(f.getPath() + java.io.File.separatorChar + s[i]));
414                 }
415                 f.delete();
416             }
417
418             public static void flush() throws IOException {
419                 delTree(cacheDir);
420                 cacheDir.mkdirs();
421             }
422
423             public static java.io.File getCacheFileForKey(String key) {
424                 // FEATURE: be smarter here
425                 return new java.io.File(cacheDir.getPath() + File.separatorChar + new String(Encode.toBase64(key.getBytes())));
426             }
427
428         }
429     }
430
431 }
432
433