2003/11/16 08:28:10
[org.ibex.core.git] / src / org / xwt / Res.java
index bf7b6f8..e9a9465 100644 (file)
 package org.xwt;
 
 import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+import org.xwt.js.*;
+import org.xwt.util.*;
+import org.bouncycastle.util.encoders.Base64;
 
-/** base class for XWT resources */
-public abstract class Res {
 
-    public abstract InputStream getInputStream();
-    public Res getSubResource(String key) { return Null.singleton; }
+/** Base class for XWT resources */
+public abstract class Res extends JS {
 
-    public static Res stringToRes(String url) {
-        if (url.indexOf('!') == -1)
-            return new Zip(stringToRes(url.substring(0, url.lastIndexOf('!'))),
-                           url.substring(url.lastIndexOf('!') + 1));
-        if (url.startsWith("http://")) return new HTTP(url);
-        if (url.startsWith("https://")) return new HTTP(url);
-        throw new JS.Exn("invalid resource specifier");
+    // Base Class //////////////////////////////////////////////////////////////////////
+
+    public String typeName() { return "resource"; }
+
+    /** so that we get the same subresource each time */
+    private Hash refCache = null;
+
+    /** FIXME: needed? good idea? */
+    public Template t = null;
+
+    public final InputStream getInputStream() throws IOException { return getInputStream(""); }
+    public abstract InputStream getInputStream(String path) throws IOException;
+
+    public Res addExtension(String extension) { return new Ref(this, extension); }
+
+    public Object get(Object key) {
+        if ("".equals(key)) {
+            Template t = Template.getTemplate(addExtension(".xwt"));
+            return t == null ? null : t.getStatic();
+        }
+        Object ret = refCache == null ? null : refCache.get(key);
+        if (ret != null) return ret;
+        ret = new Ref(this, key);
+        if (refCache == null) refCache = new Hash();
+        refCache.put(key, ret);
+        return ret;
     }
 
-    /** the invalid resource; only causes an error if you actually try to use it */
-    public static class Null extends Res {
-        Null() { }
-        private static singleton = new Null();
-        public InputStream getInputStream() throws JS.Exn { throw new JS.Exn("invalid resource"); }
+
+
+    // Caching //////////////////////////////////////////////////////////////////////
+
+    public static class NotCacheableException extends Exception { }
+    public static NotCacheableException notCacheable = new NotCacheableException();
+
+    /** if it makes sense to cache a resource, the resource must return a unique key */
+    public String getCacheKey() throws NotCacheableException { throw notCacheable; }
+
+    // FIXME: general cleanup
+    /** subclass from this if you want a CachedInputStream for each path */
+    public static class CachedRes extends Res {
+        private Res parent;
+        private boolean disk = false;
+        private String key;
+        public String getCacheKey() throws NotCacheableException { return key; }
+        private Hash cachedInputStreams = new Hash();
+        public CachedRes(Res p, String s, boolean d) throws NotCacheableException {
+            this.parent = p; this.disk = d; this.key = p.getCacheKey();
+        }
+        public InputStream getInputStream(String path) throws IOException {
+            CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
+            if (cis == null) {
+                java.io.File f = null;
+                if (disk) {
+                    f = new java.io.File(System.getProperty("user.home") +
+                                         java.io.File.separatorChar + ".xwt" +
+                                         java.io.File.separatorChar + "caches" +
+                                         java.io.File.separatorChar +
+                                         new String(Base64.encode(key.getBytes())));
+                    Log.log(this, "caching resource in " + f);
+                    new java.io.File(f.getParent()).mkdirs();
+                    if (f.exists()) return new FileInputStream(f);
+                }
+                cis = new CachedInputStream(parent.getInputStream(path), f);
+                cachedInputStreams.put(path, cis);
+            }
+            return cis.getInputStream();
+        }
     }
 
+
+    // Useful Subclasses //////////////////////////////////////////////////////////////////////
+
     /** HTTP or HTTPS resource */
     public static class HTTP extends Res {
         private String url;
-        HTTP(String url) { this.url = url; }
-        public InputStream getInputStream() { return new HTTP(url).GET(); }
-        public Res getSubResource(String key) { return new HTTP(url + "/" + key); }
+        HTTP(String url) { while (url.endsWith("/")) url = url.substring(0, url.length() - 1); this.url = url; }
+        public String getCacheKey() throws NotCacheableException { return url; }
+        public InputStream getInputStream(String path) throws IOException { return new org.xwt.HTTP(url + path).GET(); }
+    }
+
+    /** byte arrays */
+    public static class ByteArray extends Res {
+        private byte[] bytes;
+        private String cacheKey = null;
+        ByteArray(byte[] bytes, String cacheKey) { this.bytes = bytes; this.cacheKey = cacheKey; }
+        public String getCacheKey() throws NotCacheableException { return cacheKey; }
+        public InputStream getInputStream(String path) throws IOException {
+            if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
+            return new ByteArrayInputStream(bytes);
+        }
     }
 
-    /** wrap a Res around a preexisting InputStream */
-    public static class IS extends Res {
-        InputStream parent;
-        IS(InputStream parent) { this.parent = parent; }
-        public InputStream getInputStream() { return parent; }
+    /** a file */
+    public static class File extends Res {
+        private String path;
+        File(String path) {
+            while (path.endsWith(java.io.File.separatorChar + "")) path = path.substring(0, path.length() - 1);
+            this.path = path;
+        }
+        public String getCacheKey() throws NotCacheableException { throw notCacheable; }  // already on the disk!
+        public InputStream getInputStream(String rest) throws IOException {
+            return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
     }
 
     /** "unwrap" a Zip archive */
     public static class Zip extends Res {
         private Res parent;
-        private String path = "";
-        Zip(Res parent, String path) { this.parent = parent; this.path = path; }
-        public InputStream getInputStream() {
-            ZipInputStream zis = new ZipInputStream(parent.getInputStream());
+        Zip(Res parent) { this.parent = parent; }
+        public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!zip:"; }
+        public InputStream getInputStream(String path) throws IOException {
+            if (path.startsWith("/")) path = path.substring(1);
+            InputStream pis = parent.getInputStream();
+            ZipInputStream zis = new ZipInputStream(pis);
             ZipEntry ze = zis.getNextEntry();
             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
-            if (ze == null) throw new JS.Exn("zip file not found in archive");
-            return zis;
+            if (ze == null) throw new JS.Exn("requested file (" + path + ") not found in archive");
+            return new KnownLength.KnownLengthInputStream(zis, (int)ze.getSize());
         }
-        public Res getSubResource(String key) { return new Zip(parent, path + '/' + key); }
     }
 
+    /** "unwrap" a Cab archive */
+    public static class Cab extends Res {
+        private Res parent;
+        Cab(Res parent) { this.parent = parent; }
+        public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!cab:"; }
+        public InputStream getInputStream(String path) throws IOException {
+            if (path.startsWith("/")) path = path.substring(1);
+            return new org.xwt.translators.MSPack(parent.getInputStream()).getInputStream(path);
+        }
+    }
+
+    /** the Builtin resource */
+    public static class Builtin extends Res {
+       public Builtin() { };
+       public String getCacheKey() throws NotCacheableException { throw notCacheable; }    // not cacheable
+       public InputStream getInputStream(String path) throws IOException {
+           if (!path.equals("")) throw new IOException("the builtin resource has no subresources");
+           return Platform.getBuiltinInputStream();
+       }
+    }
+
+    /** what you get when you reference a subresource */
+    public static class Ref extends Res {
+        Res parent;
+        Object key;
+        public String toString() { return parent.toString() + "/" + key; }
+        Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
+        public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "/" + key; }
+        public Res addExtension(String extension) {
+            return ((String)key).endsWith(extension) ? this : new Ref(parent, key + extension); }
+        public InputStream getInputStream(String path) throws IOException { return parent.getInputStream("/" + key + path); }
+    }
+
+    /** shadow resource which replaces the graft */
+    public static class ProgressWatcher extends Res {
+        final Res watchee;
+        JSFunction callback;
+        ProgressWatcher(Res watchee, JSFunction callback) { this.watchee = watchee; this.callback = callback; }
+        public String getCacheKey() throws NotCacheableException { return watchee.getCacheKey(); }
+        public InputStream getInputStream(String s) throws IOException {
+            final InputStream is = watchee.getInputStream(s);
+            return new FilterInputStream(is) {
+                    int bytesDownloaded = 0;
+                    public int read() throws IOException {
+                        int ret = super.read();
+                        if (ret != -1) bytesDownloaded++;
+                        return ret;
+                    }
+                    public int read(byte[] b, int off, int len) throws IOException {
+                        int ret = super.read(b, off, len);
+                        if (ret != 1) bytesDownloaded += ret;
+                        Scheduler.add(new Scheduler.Task() { public void perform() {
+                            JSArray args = new JSArray();
+                            args.addElement(new Integer(bytesDownloaded));
+                            args.addElement(new Integer(is instanceof KnownLength ? ((KnownLength)is).getLength() : 0));
+                            callback.call(args);
+                        } });
+                        return ret;
+                    }
+                };
+        }
+    }
 }