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