2003/11/19 02:40:17
[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         public String toString() { return key; }
61         private Hash cachedInputStreams = new Hash();
62         public CachedRes(Res p, String s, boolean d) throws NotCacheableException {
63             this.parent = p; this.disk = d; this.key = p.getCacheKey();
64         }
65         public InputStream getInputStream(String path) throws IOException {
66             CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
67             if (cis == null) {
68                 java.io.File f = null;
69                 if (disk) {
70                     f = new java.io.File(System.getProperty("user.home") +
71                                          java.io.File.separatorChar + ".xwt" +
72                                          java.io.File.separatorChar + "caches" +
73                                          java.io.File.separatorChar +
74                                          new String(Base64.encode(key.getBytes())));
75                     Log.log(this, "caching resource in " + f);
76                     new java.io.File(f.getParent()).mkdirs();
77                     if (f.exists()) return new FileInputStream(f);
78                 }
79                 cis = new CachedInputStream(parent.getInputStream(path), f);
80                 cachedInputStreams.put(path, cis);
81             }
82             return cis.getInputStream();
83         }
84     }
85
86
87     // Useful Subclasses //////////////////////////////////////////////////////////////////////
88
89     /** HTTP or HTTPS resource */
90     public static class HTTP extends Res {
91         private String url;
92         HTTP(String url) { while (url.endsWith("/")) url = url.substring(0, url.length() - 1); this.url = url; }
93         public String toString() { return url; }
94         public String getCacheKey() throws NotCacheableException { return url; }
95         public InputStream getInputStream(String path) throws IOException { return new org.xwt.HTTP(url + path).GET(); }
96     }
97
98     /** byte arrays */
99     public static class ByteArray extends Res {
100         private byte[] bytes;
101         private String cacheKey = null;
102         ByteArray(byte[] bytes, String cacheKey) { this.bytes = bytes; this.cacheKey = cacheKey; }
103         public String toString() { return "byte[]"; }
104         public String getCacheKey() throws NotCacheableException { return cacheKey; }
105         public InputStream getInputStream(String path) throws IOException {
106             if (!"".equals(path)) throw new JSExn("can't get subresources of a byte[] resource");
107             return new ByteArrayInputStream(bytes);
108         }
109     }
110
111     /** a file */
112     public static class File extends Res {
113         private String path;
114         File(String path) {
115             while (path.endsWith(java.io.File.separatorChar + "")) path = path.substring(0, path.length() - 1);
116             this.path = path;
117         }
118         public String toString() { return "file:" + path; }
119         public String getCacheKey() throws NotCacheableException { throw notCacheable; }  // already on the disk!
120         public InputStream getInputStream(String rest) throws IOException {
121             return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
122     }
123
124     /** "unwrap" a Zip archive */
125     public static class Zip extends Res {
126         private Res parent;
127         Zip(Res parent) { this.parent = parent; }
128         public String toString() { return parent.toString() + "!zip"; }
129         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!zip:"; }
130         public InputStream getInputStream(String path) throws IOException {
131             if (path.startsWith("/")) path = path.substring(1);
132             InputStream pis = parent.getInputStream();
133             ZipInputStream zis = new ZipInputStream(pis);
134             ZipEntry ze = zis.getNextEntry();
135             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
136             if (ze == null) throw new JSExn("requested file (" + path + ") not found in archive");
137             return new KnownLength.KnownLengthInputStream(zis, (int)ze.getSize());
138         }
139     }
140
141     /** "unwrap" a Cab archive */
142     public static class Cab extends Res {
143         private Res parent;
144         Cab(Res parent) { this.parent = parent; }
145         public String toString() { return parent.toString() + "!cab"; }
146         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "!cab:"; }
147         public InputStream getInputStream(String path) throws IOException {
148             if (path.startsWith("/")) path = path.substring(1);
149             return new org.xwt.translators.MSPack(parent.getInputStream()).getInputStream(path);
150         }
151     }
152
153     /** the Builtin resource */
154     public static class Builtin extends Res {
155         public Builtin() { };
156         public String getCacheKey() throws NotCacheableException { throw notCacheable; }    // not cacheable
157         public String toString() { return "builtin:"; }
158         public InputStream getInputStream(String path) throws IOException {
159             if (!path.equals("")) throw new IOException("the builtin resource has no subresources");
160             return Platform.getBuiltinInputStream();
161         }
162     }
163
164     /** what you get when you reference a subresource */
165     public static class Ref extends Res {
166         Res parent;
167         Object key;
168         public String toString() { return parent.toString() + "/" + key; }
169         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
170         public String getCacheKey() throws NotCacheableException { return parent.getCacheKey() + "/" + key; }
171         public Res addExtension(String extension) {
172             return ((String)key).endsWith(extension) ? this : new Ref(parent, key + extension); }
173         public InputStream getInputStream(String path) throws IOException { return parent.getInputStream("/" + key + path); }
174     }
175
176     /** shadow resource which replaces the graft */
177     public static class ProgressWatcher extends Res {
178         final Res watchee;
179         JSFunction callback;
180         ProgressWatcher(Res watchee, JSFunction callback) { this.watchee = watchee; this.callback = callback; }
181         public String toString() { return watchee.toString(); }
182         public String getCacheKey() throws NotCacheableException { return watchee.getCacheKey(); }
183         public InputStream getInputStream(String s) throws IOException {
184             final InputStream is = watchee.getInputStream(s);
185             return new FilterInputStream(is) {
186                     int bytesDownloaded = 0;
187                     public int read() throws IOException {
188                         int ret = super.read();
189                         if (ret != -1) bytesDownloaded++;
190                         return ret;
191                     }
192                     public int read(byte[] b, int off, int len) throws IOException {
193                         int ret = super.read(b, off, len);
194                         if (ret != 1) bytesDownloaded += ret;
195                         Scheduler.add(new Scheduler.Task() { public void perform() {
196                             callback.call(N(bytesDownloaded),
197                                           N(is instanceof KnownLength ? ((KnownLength)is).getLength() : 0), null, null, 2);
198                         } });
199                         return ret;
200                     }
201                 };
202         }
203     }
204 }