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