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