1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
10 import org.mozilla.javascript.*;
11 import org.xwt.util.*;
14 * A singleton class that acts as a repository for files obtained
15 * from xwar archives or the local filesystem.
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
23 public class Resources {
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);
28 /** keeps track of which archive loaded templates into which package */
29 private static Hash usedPackages = new Hash();
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') ||
43 (c >= '0' && c <= '9') ||
44 (c == '.' && i == name.length() - 4))) return false;
49 /** Load a directory as if it were an archive */
50 public static synchronized void loadDirectory(File dir) throws IOException { loadDirectory(dir, ""); }
51 private static synchronized void loadDirectory(File dir, String prefix) throws IOException {
52 new Static(prefix.replace(File.separatorChar, '.'));
53 String[] subfiles = dir.list();
54 for(int i=0; i<subfiles.length; i++) {
55 if (subfiles[i].equals("CVS") || !validResourceName(subfiles[i])) continue;
56 String name = prefix + subfiles[i];
57 File file = new File(dir.getPath() + File.separatorChar + subfiles[i]);
58 if (file.isDirectory()) {
59 loadDirectory(file, name + File.separatorChar);
61 if (name.endsWith(".xwt")) {
62 Static.createStatic(name.replace(File.separatorChar, '.'), false);
63 usedPackages.put(JSObject.nodeNameToPackageName(name.replace('/', '.')), new Object());
65 bytes.put(name.replace(File.separatorChar, '.'), file);
70 /** Load an archive from an inputstream. */
71 public static synchronized void loadArchive(InputStream is) throws IOException { loadArchive(is, 0, null); }
72 public static synchronized void loadArchive(InputStream is, final int length, final Function callback) throws IOException {
75 Object thisArchive = new Object();
77 ZipInputStream zis = new ZipInputStream(new FilterInputStream(is) {
78 int bytesDownloaded = 0;
80 public int read() throws IOException {
84 public int read(byte[] b, int off, int len) throws IOException {
85 int ret = super.read(b, off, len);
86 if (ret != -1) bytesDownloaded += ret;
87 if (clear && callback != null) {
89 ThreadMessage.newthread(new JSObject.JSFunction() {
90 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
92 callback.call(cx, null, null, new Object[] { new Double(bytesDownloaded), new Double(length) });
104 for(ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
105 String name = ze.getName();
106 if (!validResourceName(name.substring(name.lastIndexOf('/') + 1))) {
107 if (Log.on) Log.log(Resources.class, "WARNING: ignoring xwar entry with invalid name: " + name);
111 if (name.endsWith(".xwt")) {
112 // placeholder so resolveResource() works properly
113 bytes.put(name.replace('/', '.'), new byte[] { });
114 name = name.substring(0, name.length() - 4);
116 String packageName = JSObject.nodeNameToPackageName(name.replace('/', '.'));
117 Object user = usedPackages.get(packageName);
118 if (user != null && user != thisArchive) {
119 if (Log.on) Log.log(Resources.class, "templates have already been loaded into " + packageName + "; refusing to load " + name);
121 usedPackages.put(packageName, thisArchive);
122 Static.createStatic(name.replace('/', '.'), false);
123 Template.buildTemplate(zis, name.replace('/', '.'));
127 bytes.put(name.replace('/', '.'), isToByteArray(zis));
130 if (Log.verbose) Log.log(Resources.class, "done loading archive");
133 /** holds the current theme mappings */
134 static Vector mapFrom = new Vector();
136 /** holds the current theme mappings */
137 static Vector mapTo = new Vector();
140 * Resolves the partial resource name <tt>name</tt> to a fully
141 * resolved resource name, using <tt>importlist</tt> as a search
142 * list, or null if no resource was found.
144 * Both the arguments and return values from this function SHOULD
145 * include extensions (".xwt", ".xwf", etc) and SHOULD use dots
146 * (".") instead of slashes ("/").
148 public static String resolve(String name, String[] importlist) {
149 final int imax = importlist == null ? 0 : importlist.length;
150 for(int i=-1; i < imax; i++) {
151 String resolved = i == -1 ? name : (importlist[i] + '.' + name);
152 for(int j=mapFrom.size() - 1; j>=0; j--) {
153 String from = mapFrom.elementAt(j).toString();
154 if (resolved.startsWith(from) && (resolved.endsWith(".xwt") || resolved.endsWith(".xwf"))) {
155 String tryme = mapTo.elementAt(j) + resolved.substring(from.length());
156 if (bytes.get(tryme) != null) return tryme;
159 if (bytes.get(resolved) != null) return resolved;
164 /** Returns the named resource as a byte[].
165 * @param name A fully resolved resource name, using slashes
166 * instead of periods. If it is null, this function
169 public static byte[] getResource(String name) {
170 if (name == null) return null;
171 synchronized(bytes) {
172 Object o = bytes.get(name);
173 if (o == null) return null;
174 if (o instanceof byte[]) return ((byte[])o);
175 if (o instanceof File) {
177 FileInputStream fi = new FileInputStream((File)o);
178 byte[] b = isToByteArray(fi);
181 } catch (Exception e) {
182 if (Log.on) Log.log(Resources.class, "Exception while reading from file " + o);
183 if (Log.on) Log.log(Resources.class, e);
191 /** scratch space for isToByteArray() */
192 private static byte[] workspace = new byte[16 * 1024];
194 /** Trivial method to completely read an InputStream */
195 public static synchronized byte[] isToByteArray(InputStream is) throws IOException {
198 int numread = is.read(workspace, pos, workspace.length - pos);
199 if (numread == -1) break;
200 else if (pos + numread < workspace.length) pos += numread;
203 byte[] temp = new byte[workspace.length * 2];
204 System.arraycopy(workspace, 0, temp, 0, workspace.length);
208 byte[] ret = new byte[pos];
209 System.arraycopy(workspace, 0, ret, 0, pos);