d35be0975b8d7649d1bb894fdfbeaa0001a812f3
[org.ibex.core.git] / src / org / xwt / Res.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.util.*;
6 import java.util.zip.*;
7 import org.xwt.js.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11
12 /** Base class for XWT resources */
13 public abstract class Res extends JS {
14
15     // Base Class //////////////////////////////////////////////////////////////////////
16
17     public String typeName() { return "resource"; }
18
19     /** so that we get the same subresource each time */
20     private Hash refCache = null;
21
22     /** FIXME: needed? good idea? */
23     public Template t = null;
24
25     public final InputStream getInputStream() throws IOException { return getInputStream(""); }
26     public abstract InputStream getInputStream(String path) throws IOException;
27
28     public Res addExtension(String extension) { return new Ref(this, extension); }
29
30     public Object get(Object key) {
31         if ("".equals(key)) {
32             Template t = Template.getTemplate(addExtension(".xwt"));
33             return t == null ? null : t.getStatic();
34         }
35         Object ret = refCache == null ? null : refCache.get(key);
36         if (ret != null) return ret;
37         ret = new Ref(this, key);
38         if (refCache == null) refCache = new Hash();
39         refCache.put(key, ret);
40         return ret;
41     }
42
43
44
45     // Caching //////////////////////////////////////////////////////////////////////
46
47     public static class NotCacheableException extends Exception { }
48     public static NotCacheableException notCacheable = new NotCacheableException();
49
50     /** if it makes sense to cache a resource, the resource must return a unique key */
51     public String getCacheKey() throws NotCacheableException { throw notCacheable; }
52
53     // FIXME: general cleanup
54     /** subclass from this if you want a CachedInputStream for each path */
55     public static class CachedRes extends Res {
56         private Res parent;
57         private boolean disk = false;
58         private String key;
59         public String getCacheKey() throws NotCacheableException { return key; }
60         private Hash cachedInputStreams = new Hash();
61         public CachedRes(Res p, String s, boolean d) throws NotCacheableException {
62             this.parent = p; this.disk = d; this.key = p.getCacheKey();
63         }
64         public InputStream getInputStream(String path) throws IOException {
65             CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
66             if (cis == null) {
67                 java.io.File f = null;
68                 if (disk) {
69                     f = new java.io.File(System.getProperty("user.home") +
70                                          java.io.File.separatorChar + ".xwt" +
71                                          java.io.File.separatorChar + "caches" +
72                                          java.io.File.separatorChar +
73                                          new String(Base64.encode(key.getBytes())));
74                     Log.log(this, "caching resource in " + f);
75                     new java.io.File(f.getParent()).mkdirs();
76                     if (f.exists()) return new FileInputStream(f);
77                 }
78                 cis = new CachedInputStream(parent.getInputStream(path), f);
79                 cachedInputStreams.put(path, cis);
80             }
81             return cis.getInputStream();
82         }
83     }
84
85
86     // Useful Subclasses //////////////////////////////////////////////////////////////////////
87
88     /** HTTP or HTTPS resource */
89     public static class HTTP extends Res {
90         private String url;
91         HTTP(String url) { while (url.endsWith("/")) url = url.substring(0, url.length() - 1); this.url = url; }
92         public String getCacheKey() throws NotCacheableException { return url; }
93         public InputStream getInputStream(String path) throws IOException { return new org.xwt.HTTP(url + path).GET(); }
94     }
95
96     /** byte arrays */
97     public static class ByteArray extends Res {
98         private byte[] bytes;
99         private String cacheKey = null;
100         ByteArray(byte[] bytes, String cacheKey) { this.bytes = bytes; this.cacheKey = cacheKey; }
101         public String getCacheKey() throws NotCacheableException { return cacheKey; }
102         public InputStream getInputStream(String path) throws IOException {
103             if (!"".equals(path)) throw new JSExn("can't get subresources of a byte[] resource");
104             return new ByteArrayInputStream(bytes);
105         }
106     }
107
108     /** a file */
109     public static class File extends Res {
110         private String path;
111         File(String path) {
112             while (path.endsWith(java.io.File.separatorChar + "")) path = path.substring(0, path.length() - 1);
113             this.path = path;
114         }
115         public String getCacheKey() throws NotCacheableException { throw notCacheable; }  // already on the disk!
116         public InputStream getInputStream(String rest) throws IOException {
117             return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
118     }
119
120     /** "unwrap" a Zip archive */
121     public static class Zip extends Res {
122         private Res parent;
123         Zip(Res parent) { this.parent = parent; }
124         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!zip:"; }
125         public InputStream getInputStream(String path) throws IOException {
126             if (path.startsWith("/")) path = path.substring(1);
127             InputStream pis = parent.getInputStream();
128             ZipInputStream zis = new ZipInputStream(pis);
129             ZipEntry ze = zis.getNextEntry();
130             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
131             if (ze == null) throw new JSExn("requested file (" + path + ") not found in archive");
132             return new KnownLength.KnownLengthInputStream(zis, (int)ze.getSize());
133         }
134     }
135
136     /** "unwrap" a Cab archive */
137     public static class Cab extends Res {
138         private Res parent;
139         Cab(Res parent) { this.parent = parent; }
140         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!cab:"; }
141         public InputStream getInputStream(String path) throws IOException {
142             if (path.startsWith("/")) path = path.substring(1);
143             return new org.xwt.translators.MSPack(parent.getInputStream()).getInputStream(path);
144         }
145     }
146
147     /** the Builtin resource */
148     public static class Builtin extends Res {
149         public Builtin() { };
150         public String getCacheKey() throws NotCacheableException { throw notCacheable; }    // not cacheable
151         public InputStream getInputStream(String path) throws IOException {
152             if (!path.equals("")) throw new IOException("the builtin resource has no subresources");
153             return Platform.getBuiltinInputStream();
154         }
155     }
156
157     /** what you get when you reference a subresource */
158     public static class Ref extends Res {
159         Res parent;
160         Object key;
161         public String toString() { return parent.toString() + "/" + key; }
162         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
163         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "/" + key; }
164         public Res addExtension(String extension) {
165             return ((String)key).endsWith(extension) ? this : new Ref(parent, key + extension); }
166         public InputStream getInputStream(String path) throws IOException { return parent.getInputStream("/" + key + path); }
167     }
168
169     /** shadow resource which replaces the graft */
170     public static class ProgressWatcher extends Res {
171         final Res watchee;
172         JSFunction callback;
173         ProgressWatcher(Res watchee, JSFunction callback) { this.watchee = watchee; this.callback = callback; }
174         public String getCacheKey() throws NotCacheableException { return watchee.getCacheKey(); }
175         public InputStream getInputStream(String s) throws IOException {
176             final InputStream is = watchee.getInputStream(s);
177             return new FilterInputStream(is) {
178                     int bytesDownloaded = 0;
179                     public int read() throws IOException {
180                         int ret = super.read();
181                         if (ret != -1) bytesDownloaded++;
182                         return ret;
183                     }
184                     public int read(byte[] b, int off, int len) throws IOException {
185                         int ret = super.read(b, off, len);
186                         if (ret != 1) bytesDownloaded += ret;
187                         Scheduler.add(new Scheduler.Task() { public void perform() {
188                             callback.call(N(bytesDownloaded),
189                                           N(is instanceof KnownLength ? ((KnownLength)is).getLength() : 0), null, null, 2);
190                         } });
191                         return ret;
192                     }
193                 };
194         }
195     }
196 }