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