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