2002/05/16 04:21:02
[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 jazz.*;
8 import java.lang.*;
9 import java.applet.*;
10 import org.mozilla.javascript.*;
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     /** The number of bytes read from the initial-xwar stream; used to display a progress bar on the splash screen */
29     public static int bytesDownloaded = 0;
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 false;
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 == '_' ||
43                   (c >= '0' && c <= '9') ||
44                   (c == '.' && i == name.length() - 4))) return false;
45         }
46         return true;
47     }
48
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
56             if (subfiles[i].equals("CVS")) {
57                 if (Log.on) Log.log(Resources.class, "ignoring CVS/ directory");
58                 continue;
59             }
60             if (!validResourceName(subfiles[i])) {
61                 if (subfiles[i].charAt(subfiles[i].length() - 1) != '~')
62                     if (Log.on) Log.log(Resources.class, "WARNING: ignoring file entry with invalid name: " + subfiles[i]);
63                 continue;
64             }
65
66             String name = prefix + subfiles[i];
67             File file = new File(dir.getPath() + File.separatorChar + subfiles[i]);
68             if (file.isDirectory()) loadDirectory(file, name + File.separatorChar);
69             else {
70                 bytes.put(name.replace(File.separatorChar, '.'), file);
71                 bytesDownloaded += file.length();
72                 Main.updateSplashScreen();
73             }
74         }
75     }
76
77     /** Load an archive from an inputstream. */
78     public static synchronized void loadArchive(InputStream is) throws IOException {
79         ZipInputStream zis = new ZipInputStream(new FilterInputStream(is) {
80                 public int read() throws IOException {
81                     bytesDownloaded++;
82                     return super.read();
83                 }
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                     Main.updateSplashScreen();
88                     return ret;
89                 }
90             });
91         for(ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
92             String name = ze.getName();
93             if (!validResourceName(name.substring(name.lastIndexOf('/') + 1))) {
94                 if (Log.on) Log.log(Resources.class, "WARNING: ignoring xwar entry with invalid name: " + name);
95                 continue;
96             }
97             if (ze.isDirectory()) {
98                 new Static(name.replace('/', '.'));
99                 continue;
100             }
101             if (name.endsWith(".xwt")) {
102                 if (Log.verbose) Log.log(Resources.class, "building template " + name);
103                 Template.buildTemplate(zis, name.substring(0, name.length() - 4).replace('/', '.'));
104                 if (Log.verbose) Log.log(Resources.class, "   done building template " + name);
105                 bytes.put(name.replace('/', '.'), new byte[] { });                          // placeholder so resolveResource() works properly
106             } else {
107                 bytes.put(name.replace('/', '.'), isToByteArray(zis));
108             }
109         }
110         if (Log.verbose) Log.log(Resources.class, "done loading archive");
111     }
112
113     /** holds the current theme mappings */
114     static Vector mapFrom = new Vector();
115
116     /** holds the current theme mappings */
117     static Vector mapTo = new Vector();
118
119     /**
120      *  Resolves the partial resource name <tt>name</tt> to a fully
121      *  resolved resource name, using <tt>importlist</tt> as a search
122      *  list, or null if no resource was found.
123      *
124      *  Both the arguments and return values from this function SHOULD
125      *  include extensions (".xwt", ".xwf", etc) and SHOULD use dots
126      *  (".") instead of slashes ("/").
127      */
128     public static String resolve(String name, String[] importlist) {
129         final int imax = importlist == null ? 0 : importlist.length;
130         for(int i=-1; i < imax; i++) {
131             String resolved = i == -1 ? name : (importlist[i] + '.' + name);
132             for(int j=mapFrom.size() - 1; j>=0; j--) {
133                 String from = mapFrom.elementAt(j).toString();
134                 if (resolved.startsWith(from) && (resolved.endsWith(".xwt") || resolved.endsWith(".xwf"))) {
135                     String tryme = mapTo.elementAt(j) + resolved.substring(from.length());
136                     if (bytes.get(tryme) != null) return tryme;
137                 }
138             }
139             if (bytes.get(resolved) != null) return resolved;
140         }
141         return null;
142     }
143
144     /** Returns the named resource as a byte[].
145      *  @param name A fully resolved resource name, using slashes
146      *              instead of periods. If it is null, this function
147      *              will return null.
148      */
149     public static byte[] getResource(String name) {
150         if (name == null) return null;
151         synchronized(bytes) {
152             Object o = bytes.get(name);
153             if (o == null) return null;
154             if (o instanceof byte[]) return ((byte[])o);
155             if (o instanceof File) {
156                 try {
157                     FileInputStream fi = new FileInputStream((File)o);
158                     byte[] b = isToByteArray(fi);
159                     bytes.put(name, b);
160                     return b;
161                 } catch (Exception e) {
162                     if (Log.on) Log.log(Resources.class, "Exception while reading from file " + o);
163                     if (Log.on) Log.log(Resources.class, e);
164                     return null;
165                 }
166             }
167             return null;
168         }
169     }
170     
171     /** scratch space for isToByteArray() */
172     private static byte[] workspace = new byte[16 * 1024];
173
174     /** Trivial method to completely read an InputStream */
175     public static synchronized byte[] isToByteArray(InputStream is) throws IOException {
176         int pos = 0;
177         while (true) {
178             int numread = is.read(workspace, pos, workspace.length - pos);
179             if (numread == -1) break;
180             else if (pos + numread < workspace.length) pos += numread;
181             else {
182                 pos += numread;
183                 byte[] temp = new byte[workspace.length * 2];
184                 System.arraycopy(workspace, 0, temp, 0, workspace.length);
185                 workspace = temp;
186             }
187         }
188         byte[] ret = new byte[pos];
189         System.arraycopy(workspace, 0, ret, 0, pos);
190         return ret;
191     }
192 }
193
194
195