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