20858e60107cdfeb56f34f5b2cb750122a3b9c2a
[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
10 /** base class for XWT resources */
11 public abstract class Res extends JS {
12
13     public String getDescriptiveName() { return "FIXME"; }
14
15     /** if this Res corresponds to a Template, it is cached here */
16     Template t = null;
17
18     /** cache of subresources so that the equality operator works on them */
19     private Hash refCache = null;
20
21     /** returns an InputStream containing the Resource's contents */
22     public InputStream getInputStream() throws IOException { return getInputStream(""); }
23     public abstract InputStream getInputStream(String path) throws IOException;
24
25     /** graft newResource in place of this resource on its parent */
26     public Res graft(Object newResource) { throw new JS.Exn("cannot graft onto this resource"); }
27
28     /** if the path of this resource does not end with extension, return a new one wit it appended */
29     public Res addExtension(String extension) { return new Ref(this, extension); }
30
31     public Object[] keys() { throw new JS.Exn("cannot enumerate a resource"); } 
32     public void put(Object key, Object val) { throw new JS.Exn("cannot put to a resource"); } 
33     public Object get(Object key) {
34         if ("".equals(key)) {
35             Template t = Template.getTemplate(addExtension(".xwt"));
36             return t == null ? null : t.getStatic();
37         }
38         Object ret = refCache == null ? null : refCache.get(key);
39         if (ret != null) return ret;
40         ret = new Ref(this, key);
41         if (refCache == null) refCache = new Hash();
42         refCache.put(key, ret);
43         return ret;
44     }
45
46     public static Res stringToRes(String url) {
47         if (url.indexOf('!') != -1)
48             return (Res)(new Zip(stringToRes(url.substring(0, url.lastIndexOf('!')))).get(url.substring(url.lastIndexOf('!') + 1)));
49         if (url.startsWith("http://")) return new HTTP(url);
50         if (url.startsWith("https://")) return new HTTP(url);
51         if (url.startsWith("file:")) return new File(url.substring(5));
52         if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
53         throw new JS.Exn("invalid resource specifier");
54     }
55
56     /** HTTP or HTTPS resource */
57     public static class HTTP extends Res {
58         private String url;
59         HTTP(String url) { this.url = url; }
60         public InputStream getInputStream(String path) throws IOException { return new org.xwt.HTTP(url + path).GET(); }
61     }
62
63     /** byte arrays */
64     public static class ByteArray extends Res {
65         private byte[] bytes;
66         ByteArray(byte[] bytes) { this.bytes = bytes; }
67         public InputStream getInputStream(String path) throws IOException {
68             if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
69             return new ByteArrayInputStream(bytes);
70         }
71     }
72
73     // FIXME: dangerous
74     /** a file */
75     public static class File extends Res {
76         private String path;
77         File(String path) { this.path = path; }
78         public InputStream getInputStream(String rest) throws IOException {
79             return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
80     }
81
82     /** wrap a Res around a preexisting InputStream */
83     public static class IS extends Res {
84         InputStream parent;
85         IS(InputStream parent) { this.parent = parent; }
86         public InputStream getInputStream(String path) {
87             if (!"".equals(path)) throw new JS.Exn("can't access subresources of IS");
88             return parent;
89         }
90     }
91
92     /** "unwrap" a Zip archive */
93     public static class Zip extends Res {
94         private Res parent;
95         Zip(Res parent) { this.parent = parent; }
96         public InputStream getInputStream(String path) throws IOException {
97             if (path.startsWith("/")) path = path.substring(1);
98             ZipInputStream zis = new ZipInputStream(parent.getInputStream());
99             ZipEntry ze = zis.getNextEntry();
100             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
101             if (ze == null) throw new JS.Exn("requested file not found in archive");
102             return zis;
103         }
104     }
105
106     /** what you get when you reference a subresource */
107     public static class Ref extends Res {
108         Res parent;
109         Object key;
110         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
111         public Res addExtension(String extension) {
112             return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
113         }
114         public InputStream getInputStream(String path) throws IOException {
115             return parent.getInputStream("/" + key + path);
116         }
117         public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
118     }
119
120     /** shadow resource which replaces the graft */
121     public static class Graft extends Res {
122         Res graftee;
123         Object replaced_key;
124         Object replaced_val;
125         Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
126         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
127         public int hashCode() { return graftee.hashCode(); }
128         public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
129         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
130     }
131
132     /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
133     public static class CAB extends Res {
134         private Res parent;
135         CAB(Res parent) { this.parent = parent; }
136         private int swap_endian(int i) {
137             return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
138         }
139         public InputStream getInputStream(String path) throws IOException {
140             InputStream is = parent.getInputStream();
141             byte[] scan = new byte[4];
142             int ofs = 0;
143             for(int i=0; i<2; i++)  {
144                 // wierdly, .exe files have three MSCF's
145                 while(scan[0] != 'M' || scan[1] != 'S' || scan[2] != 'C' || scan[3] != 'F') {
146                     System.arraycopy(scan, 1, scan, 0, 3);
147                     int read = is.read();
148                     if (read == -1) throw new JS.Exn("MSCF header tag not found in file");
149                     scan[3] = (byte)read;
150                     ofs++;
151                 }
152                 scan[0] = 0;
153             }
154             Log.log(this, "found MSCF header at offset " + ofs);
155             return org.xwt.util.CAB.getFileInputStream(is, path, true);
156         }
157     }
158
159     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
160         if (method.equals("getUTF")) {
161             if (checkOnly) return Boolean.TRUE;
162             if (args.length() != 0) return null;
163             try {
164                 CharArrayWriter caw = new CharArrayWriter();
165                 InputStream is = getInputStream();
166                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
167                 char[] buf = new char[1024];
168                 while(true) {
169                     int numread = r.read(buf, 0, 1024);
170                     if (numread == -1) break;
171                     caw.write(buf, 0, numread);
172                 }
173                 return caw.toString();
174             } catch (IOException e) {
175                 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
176                 if (Log.on) Log.log(Res.class, e);
177                 throw new JS.Exn("error while reading from Resource");
178             }
179         } else if (method.equals("getDOM")) {
180             if (checkOnly) return Boolean.TRUE;
181             if (args.length() != 0) return null;
182             return new XMLHelper().doParse();
183         }
184         if (checkOnly) return Boolean.FALSE;
185         return null;
186     }
187
188     private class XMLHelper extends XML {
189         Vector obStack = new Vector();
190         public XMLHelper() { super(BUFFER_SIZE); }
191         public void startElement(XML.Element c) throws XML.SchemaException {
192             JS o = new JS.Obj();
193             o.put("$name", c.localName);
194             for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
195             o.put("$numchildren", new Integer(0));
196             obStack.addElement(o);
197         }
198         public void endElement(XML.Element c) throws XML.SchemaException {
199             if (obStack.size() == 1) return;
200             JS me = (JS)obStack.lastElement();
201             obStack.setSize(obStack.size() - 1);
202             JS parent = (JS)obStack.lastElement();
203             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
204             parent.put("$numchildren", new Integer(numchildren + 1));
205             parent.put(new Integer(numchildren), me);
206         }
207         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
208             String s = new String(ch, start, length);
209             JS parent = (JS)obStack.lastElement();
210             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
211             Object lastChild = parent.get(new Integer(numchildren - 1));
212             if (lastChild instanceof String) {
213                 parent.put(new Integer(numchildren - 1), lastChild + s);
214             } else {
215                 parent.put("$numchildren", new Integer(numchildren + 1));
216                 parent.put(new Integer(numchildren), s);
217             }
218         }
219         public void whitespace(char[] ch, int start, int length) {}
220         public JS doParse() throws JS.Exn {
221             try { 
222                 InputStream is = getInputStream();
223                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
224                 parse(r);
225             } catch (XML.XMLException e) {
226                 throw new JS.Exn("error parsing XML: " + e.toString());
227             } catch (IOException e) {
228                 if (Log.on) Log.log(this, "IO Exception while reading from file");
229                 if (Log.on) Log.log(this, e);
230                 throw new JS.Exn("error reading from Resource");
231             }
232             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
233         }
234     }
235
236     public void writeTo(OutputStream os) throws IOException {
237         InputStream is = getInputStream();
238         byte[] buf = new byte[1024];
239         while(true) {
240             int numread = is.read(buf, 0, 1024);
241             if (numread == -1) break;
242             if (Log.on) Log.log(this, "wrote " + numread + " bytes");
243             os.write(buf, 0, numread);
244         }
245         os.flush();
246
247         // we have to close this because flush() doesn't work on Win32-GCJ
248         os.close();
249     }
250 }