c0240ca7d5e8c3ca710bbd9ceddc9e371416228a
[org.ibex.core.git] / src / org / xwt / Resources.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.net.*;
6 import java.util.*;
7 import java.util.zip.*;
8 import java.lang.*;
9 import java.applet.*;
10 import org.xwt.js.*;
11 import org.xwt.util.*;
12
13 /**
14  *  A singleton class that acts as a repository for files obtained
15  *  from xwar archives or the local filesystem.
16  *
17  *  All names are converted to resource names (dots instead of
18  *  slashes) when they are loaded into this repository; however,
19  *  filename extensions are left on, so queries (resolveResource(),
20  *  getResource()) should include the extension when querying for
21  *  resources.
22  */
23 public class Resources {
24
25     /** Holds resources added at runtime. Initialized to hold 2000 to work around a NetscapeJVM bug. */
26     private static Hash bytes = new Hash(2000, 3);
27
28     /** keeps track of which archive loaded templates into which package */
29     private static Hash usedPackages = new Hash();
30
31     /** Returns true iff <tt>name</tt> is a valid resource name */
32     private static boolean validResourceName(String name) {
33         if (name == null || name.equals("")) return true;
34         if (name.endsWith("/box.xwt") || name.endsWith("/svg.xwt")) return false;
35         if (name.equals("box.xwt") || name.equals("svg.xwt")) return false;
36         if (!((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') ||
37               (name.charAt(0) >= 'a' && name.charAt(0) <= 'z'))) return false;
38         for(int i=1; i<name.length(); i++) {
39             char c = name.charAt(i);
40             if (!((c >= 'A' && c <= 'Z') ||
41                   (c >= 'a' && c <= 'z') ||
42                   c == '_' || c == '.' || 
43                   (c >= '0' && c <= '9'))) return false;
44         }
45         return true;
46     }
47
48     /** Load a directory as if it were an archive */
49     public static synchronized void loadDirectory(File dir) throws IOException { loadDirectory(dir, ""); }
50     private static synchronized void loadDirectory(File dir, String prefix) throws IOException {
51         new Static(prefix.replace(File.separatorChar, '.'));
52         String[] subfiles = dir.list();
53         for(int i=0; i<subfiles.length; i++) {
54             if (subfiles[i].equals("CVS") || !validResourceName(subfiles[i])) continue;
55             String name = prefix + subfiles[i];
56             File file = new File(dir.getPath() + File.separatorChar + subfiles[i]);
57             if (file.isDirectory()) {
58                 loadDirectory(file, name + File.separatorChar);
59             } else {
60                 if (name.endsWith(".xwt")) {
61                     String name2 = name.substring(0, name.length() - 4);
62                     Static.createStatic(name2.replace(File.separatorChar, '.'), false);
63                 }
64                 bytes.put(name.replace(File.separatorChar, '.'), file);
65             }
66         }
67     }
68
69     /** Load an archive from an inputstream. */
70     public static synchronized void loadArchive(InputStream is) throws IOException { loadArchive(is, 0, null); }
71     public static synchronized void loadArchive(InputStream is, final int length, final JS.Function callback) throws IOException {
72
73         // random placeholder
74         Object thisArchive = new Object();
75
76         ZipInputStream zis = new ZipInputStream(new FilterInputStream(is) {
77                 int bytesDownloaded = 0;
78                 boolean clear = true;
79                 public int read() throws IOException {
80                     bytesDownloaded++;
81                     return super.read();
82                 }
83                 public int read(byte[] b, int off, int len) throws IOException {
84                     int ret = super.read(b, off, len);
85                     if (clear && callback != null) {
86                         clear = false;
87                         ThreadMessage.newthread(new JS.Function() {
88                                 public Object _call(JS.Array args_) throws JS.Exn {
89                                     try {
90                                         JS.Array args = new JS.Array();
91                                         args.addElement(new Double(bytesDownloaded));
92                                         args.addElement(new Double(length));
93                                         callback.call(args);
94                                     } finally {
95                                         clear = true;
96                                     }
97                                     return null;
98                                 }                            
99                             });
100                     }
101                     bytesDownloaded += ret;
102                     return ret;
103                 }
104             });
105
106         Template.TemplateHelper t = new Template.TemplateHelper();
107
108         for(ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
109             String name = ze.getName();
110             if (!validResourceName(name.substring(name.lastIndexOf('/') + 1))) {
111                 if (Log.on) Log.log(Resources.class, "WARNING: ignoring xwar entry with invalid name: " + name);
112                 continue;
113             }
114
115             if (name.endsWith(".xwt")) {
116                 // placeholder so resolveResource() works properly
117                 bytes.put(name.replace('/', '.'), new byte[] { });
118                 name = name.substring(0, name.length() - 4);
119                 Static.createStatic(name.replace('/', '.'), false);
120                 Template.buildTemplate(zis, name.replace('/', '.'), t);
121
122             } else {
123                 bytes.put(name.replace('/', '.'), isToByteArray(zis));
124             }
125         }
126         if (Log.verbose) Log.log(Resources.class, "done loading archive");
127     }
128
129     /** holds the current theme mappings */
130     static Vector mapFrom = new Vector();
131
132     /** holds the current theme mappings */
133     static Vector mapTo = new Vector();
134
135     /**
136      *  Resolves the partial resource name <tt>name</tt> to a fully
137      *  resolved resource name, using <tt>importlist</tt> as a search
138      *  list, or null if no resource was found.
139      *
140      *  Both the arguments and return values from this function SHOULD
141      *  include extensions (".xwt", ".xwf", etc) and SHOULD use dots
142      *  (".") instead of slashes ("/").
143      */
144     public static String resolve(String name, String[] importlist) {
145         final int imax = importlist == null ? 0 : importlist.length;
146         for(int i=-1; i < imax; i++) {
147             String resolved = i == -1 ? name : (importlist[i] + '.' + name);
148             for(int j=mapFrom.size() - 1; j>=0; j--) {
149                 String from = mapFrom.elementAt(j).toString();
150                 if (resolved.startsWith(from) && (resolved.endsWith(".xwt") || resolved.endsWith(".xwf"))) {
151                     String tryme = mapTo.elementAt(j) + resolved.substring(from.length());
152                     if (bytes.get(tryme) != null) return tryme;
153                 }
154             }
155             if (bytes.get(resolved) != null) return resolved;
156         }
157         return null;
158     }
159
160     /** Returns the named resource as a byte[].
161      *  @param name A fully resolved resource name, using slashes
162      *              instead of periods. If it is null, this function
163      *              will return null.
164      */
165     public static byte[] getResource(String name) {
166         if (name == null) return null;
167         synchronized(bytes) {
168             Object o = bytes.get(name);
169             if (o == null) return null;
170             if (o instanceof byte[]) return ((byte[])o);
171             if (o instanceof File) {
172                 try {
173                     FileInputStream fi = new FileInputStream((File)o);
174                     byte[] b = isToByteArray(fi);
175                     bytes.put(name, b);
176                     return b;
177                 } catch (Exception e) {
178                     if (Log.on) Log.log(Resources.class, "Exception while reading from file " + o);
179                     if (Log.on) Log.log(Resources.class, e);
180                     return null;
181                 }
182             }
183             return null;
184         }
185     }
186     
187     /** scratch space for isToByteArray() */
188     private static byte[] workspace = new byte[16 * 1024];
189
190     /** Trivial method to completely read an InputStream */
191     public static synchronized byte[] isToByteArray(InputStream is) throws IOException {
192         int pos = 0;
193         while (true) {
194             int numread = is.read(workspace, pos, workspace.length - pos);
195             if (numread == -1) break;
196             else if (pos + numread < workspace.length) pos += numread;
197             else {
198                 pos += numread;
199                 byte[] temp = new byte[workspace.length * 2];
200                 System.arraycopy(workspace, 0, temp, 0, workspace.length);
201                 workspace = temp;
202             }
203         }
204         byte[] ret = new byte[pos];
205         System.arraycopy(workspace, 0, ret, 0, pos);
206         return ret;
207     }
208 }
209
210
211