1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
5 import java.util.zip.*;
12 * Encapsulates a template node (the <template/> element of a
13 * .xwt file, or any child element thereof).
15 * Note that the Template instance corresponding to the
16 * <template/> node carries all the header information -- hence
17 * some of the instance members are not meaningful on non-root
18 * Template instances. We refer to these non-root instances as
19 * <i>anonymous templates</i>.
21 * See the XWT reference for information on the order in which
22 * templates are applied, attributes are put, and scripts are run.
26 public class Template {
28 // Instance Members ///////////////////////////////////////////////////////
30 /** the id of this box */
33 /** the id of the redirect target; only meaningful on a root node */
34 String redirect = null;
36 /** templates that should be preapplied (in the order of application); only meaningful on a root node */
37 private Template[] preapply;
39 /** templates that should be postapplied (in the order of application); only meaningful on a root node */
40 private Template[] postapply;
42 /** keys to be "put" to instances of this template; elements correspond to those of vals */
43 private String[] keys;
45 /** values to be "put" to instances of this template; elements correspond to those of keys */
46 private Object[] vals;
48 /** child template objects */
49 private Template[] children;
51 /** see numUnits(); -1 means that this value has not yet been computed */
52 private int numunits = -1;
54 /** the scope in which the static block is executed */
55 private JS.Scope staticScope = null;
57 /** the script on the static node of this template, null if it has already been executed */
58 private JS.CompiledFunction staticscript = null;
60 /** the script on this node */
61 private JS.CompiledFunction script = null;
63 /** the filename this node came from; used only for debugging */
64 private String fileName = "unknown";
67 // Only used during parsing /////////////////////////////////////////////////////////////////
69 /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
70 private Vec childvect = new Vec();
72 /** during XML parsing, this holds partially-read character data; null otherwise */
73 private StringBuffer content = null;
75 /** line number of the first line of <tt>content</tt> */
76 private int content_start = 0;
78 /** number of lines in <tt>content</tt> */
79 private int content_lines = 0;
81 /** the line number that this element starts on */
82 private int startLine = -1;
85 // Static data/methods ///////////////////////////////////////////////////////////////////
87 private Template(String fileName) { this.fileName = fileName; }
89 public static Template getTemplate(Res r) {
91 if (r.t != null) return r.t;
92 r.t = new Template(r.getDescriptiveName());
93 new TemplateHelper().parseit(r.getInputStream(), r.t);
95 } catch (XML.SchemaException e) {
96 if (Log.on) Log.log(Template.class, "error parsing template " + r.t.fileName);
97 if (Log.on) Log.log(Template.class, e.getMessage());
99 } catch (XML.XMLException e) {
100 if (Log.on) Log.log(Template.class, "error parsing template at " + r.t.fileName + ":" + e.getLine() + "," + e.getCol());
101 if (Log.on) Log.log(Template.class, e.getMessage());
103 } catch (IOException e) {
104 if (Log.on) Log.log(Template.class, "IOException while parsing template " + r.t.fileName + " -- this should never happen");
105 if (Log.on) Log.log(Template.class, e);
111 // Methods to apply templates ////////////////////////////////////////////////////////
113 /** calculates, caches, and returns an integer approximation of how long it will take to apply this template,
114 * including pre/post and children */
116 if (numunits != -1) return numunits;
118 for(int i=0; preapply != null && i<preapply.length; i++) numunits += preapply[i].numUnits();
119 for(int i=0; postapply != null && i<postapply.length; i++) numunits += postapply[i].numUnits();
120 if (script != null) numunits += 10;
121 numunits += keys == null ? 0 : keys.length;
122 for(int i=0; children != null && i<children.length; i++) numunits += children[i].numUnits();
126 /** called before this template is applied or its static object can be externally referenced */
127 JS.Scope getStatic() {
128 if (staticScope == null) staticScope = new JS.Scope(null);
129 if (staticscript == null) return staticScope;
130 JS.CompiledFunction temp = staticscript;
132 temp.call(new JS.Array(), staticScope);
136 /** Applies the template to Box b
137 * @param pboxes a vector of all box parents on which to put $-references
138 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
140 // FIXME: $-vars not dealt with
141 void apply(Box b, JS.Callable callback, int numerator, int denominator, Res resourceRoot) {
144 int original_numerator = numerator;
146 for(int i=0; preapply != null && i<preapply.length; i++) {
147 preapply[i].apply(b, callback, numerator, denominator, resourceRoot);
148 numerator += preapply[i].numUnits();
151 for (int i=0; children != null && i<children.length; i++) {
153 children[i].apply(kid, callback, numerator, denominator, resourceRoot);
154 numerator += children[i].numUnits();
155 b.put(b.numChildren(), kid);
158 // whom to redirect to; doesn't take effect until after script runs
159 Box redir = (redirect != null && !"self".equals(redirect)) ? (Box)b.get("$" + redirect) : null;
161 if (script != null) script.call(new JS.Array(), new PerInstantiationScope(b, resourceRoot));
163 for(int i=0; keys != null && i<keys.length; i++) b.put(keys[i], vals[i]);
165 if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
167 for(int i=0; postapply != null && i<postapply.length; i++) {
168 postapply[i].apply(b, callback, numerator, denominator, resourceRoot);
169 numerator += postapply[i].numUnits();
172 numerator = original_numerator + numUnits();
174 if (callback != null) try {
175 JS.Array args = new JS.Array();
176 args.addElement(new Double(numerator));
177 args.addElement(new Double(denominator));
179 } catch (JS.Exn e) { if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e); }
181 if (Thread.currentThread() instanceof ThreadMessage) XWT.sleep(0);
186 // XML Parsing /////////////////////////////////////////////////////////////////
188 /** handles XML parsing; builds a Template tree as it goes */
189 static final class TemplateHelper extends XML {
193 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
194 void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
195 rootNodeHasBeenEncountered = false;
196 templateNodeHasBeenEncountered = false;
197 staticNodeHasBeenEncountered = false;
198 templateNodeHasBeenFinished = false;
199 nameOfHeaderNodeBeingProcessed = null;
201 nodeStack.setSize(0);
203 postapply.setSize(0);
206 parse(new InputStreamReader(is));
209 /** parsing state: true iff we have already encountered the <xwt> open-tag */
210 boolean rootNodeHasBeenEncountered = false;
212 /** parsing state: true iff we have already encountered the <template> open-tag */
213 boolean templateNodeHasBeenEncountered = false;
215 /** parsing state: true iff we have already encountered the <static> open-tag */
216 boolean staticNodeHasBeenEncountered = false;
218 /** parsing state: true iff we have already encountered the <template> close-tag */
219 boolean templateNodeHasBeenFinished = false;
221 /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
222 * that tag; otherwise, it is null. */
223 String nameOfHeaderNodeBeingProcessed = null;
225 /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
226 Vec nodeStack = new Vec();
228 /** builds up the list of preapplies */
229 Vec preapply = new Vec();
231 /** builds up the list of postapplies */
232 Vec postapply = new Vec();
234 /** the template we're currently working on */
237 public void startElement(XML.Element c) throws XML.SchemaException {
238 if (templateNodeHasBeenFinished) {
239 throw new XML.SchemaException("no elements may appear after the <template> node");
241 } else if (!rootNodeHasBeenEncountered) {
242 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
243 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
244 rootNodeHasBeenEncountered = true;
247 } else if (!templateNodeHasBeenEncountered) {
248 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
249 nameOfHeaderNodeBeingProcessed = c.localName;
251 if (c.localName.equals("import")) {
252 if (c.len != 1 || !c.keys[0].equals("name"))
253 throw new XML.SchemaException("<import> node must have exactly one attribute, which must be called 'name'");
254 String importpackage = c.vals[0].toString();
255 if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
258 } else if (c.localName.equals("redirect")) {
259 if (c.len != 1 || !c.keys[0].equals("target"))
260 throw new XML.SchemaException("<redirect> node must have exactly one attribute, which must be called 'target'");
261 if (t.redirect != null)
262 throw new XML.SchemaException("the <redirect> header element may not appear more than once");
263 t.redirect = c.vals[0].toString();
264 if(t.redirect.equals("null")) t.redirect = null;
267 } else if (c.localName.equals("preapply")) {
268 if (c.len != 1 || !c.keys[0].equals("name"))
269 throw new XML.SchemaException("<preapply> node must have exactly one attribute, which must be called 'name'");
270 preapply.addElement(c.vals[0]);
273 } else if (c.localName.equals("postapply")) {
274 if (c.len != 1 || !c.keys[0].equals("name"))
275 throw new XML.SchemaException("<postapply> node must have exactly one attribute, which must be called 'name'");
276 postapply.addElement(c.vals[0]);
279 } else if (c.localName.equals("static")) {
280 if (staticNodeHasBeenEncountered)
281 throw new XML.SchemaException("the <static> header node may not appear more than once");
283 throw new XML.SchemaException("the <static> node may not have attributes");
284 staticNodeHasBeenEncountered = true;
287 } else if (c.localName.equals("template")) {
288 // finalize importlist/preapply/postapply, since they can't change from here on
289 t.startLine = getLine();
290 if (preapply.size() > 0) preapply.copyInto(t.preapply = new Template[preapply.size()]);
291 if (postapply.size() > 0) postapply.copyInto(t.postapply = new Template[postapply.size()]);
292 templateNodeHasBeenEncountered = true;
295 throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
301 // push the last node we were in onto the stack
302 nodeStack.addElement(t);
304 // instantiate a new node, and set its fileName/importlist/preapply
305 Template t2 = new Template(t.fileName);
306 t2.startLine = getLine();
307 if (!c.localName.equals("box")) t2.preapply = new Template[] { /*c.localName FIXME */ };
309 // make the new node the current node
314 t.keys = new String[c.len];
315 t.vals = new Object[c.len];
316 Hash h = new Hash(c.len * 2, 3);
317 for(int i=0; i<c.len; i++) h.put(c.keys[i], c.vals[i]);
318 Vec v = new Vec(c.len, c.keys);
319 v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
320 for(int i=0; i<c.len; i++) {
321 // FIXME: height must come after image
322 // FIXME: thisbox must come first
323 t.keys[i] = (String)v.elementAt(i);
324 t.vals[i] = h.get(t.keys[i]);
327 for(int i=0; i<t.keys.length; i++) {
328 if (t.keys[i].equals("id")) {
329 t.id = t.vals[i].toString().intern();
334 t.keys[i] = t.keys[i].intern();
336 String valString = t.vals[i].toString();
338 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
339 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
340 else if (valString.equals("null")) t.vals[i] = null;
342 boolean hasNonNumeral = false;
343 boolean periodUsed = false;
344 for(int j=0; j<valString.length(); j++)
345 if (j == 0 && valString.charAt(j) == '-') {
346 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
348 } else if (!Character.isDigit(valString.charAt(j))) {
349 hasNonNumeral = true;
352 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
353 else t.vals[i] = valString.intern();
356 // bump thisbox to the front of the pack
357 if (t.keys[i].equals("thisbox")) {
358 t.keys[i] = t.keys[0];
359 t.keys[0] = "thisbox";
360 Object o = t.vals[0];
361 t.vals[0] = t.vals[i];
367 private JS.CompiledFunction genscript(boolean isstatic) {
368 JS.CompiledFunction thisscript = null;
370 thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
371 } catch (IOException ioe) {
372 if (Log.on) Log.log(this, " ERROR: " + ioe.getMessage());
382 public void endElement(XML.Element c) throws XML.SchemaException {
383 if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
384 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
385 nameOfHeaderNodeBeingProcessed = null;
387 } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
388 // turn our childvect into a Template[]
389 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
391 if (t.content != null) t.script = genscript(false);
393 if (nodeStack.size() == 0) {
395 templateNodeHasBeenFinished = true;
398 // add this template as a child of its parent
400 t = (Template)nodeStack.lastElement();
401 nodeStack.setSize(nodeStack.size() - 1);
402 t.childvect.addElement(oldt);
407 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
408 // invoke the no-tab crusade
409 for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
410 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
412 if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
413 if (t.content == null) {
414 t.content_start = getLine();
416 t.content = new StringBuffer();
419 t.content.append(ch, start, length);
422 } else if (nameOfHeaderNodeBeingProcessed != null) {
423 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
427 public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
431 private static class PerInstantiationScope extends JS.Scope {
432 Res resourceRoot = null;
433 public PerInstantiationScope(Scope parentScope, Res resourceRoot) {
435 this.resourceRoot = resourceRoot;
437 public boolean isTransparent() { return true; }
438 public boolean has(Object key) { return false; }
439 public void declare(String s) { super.declare(s); }
440 public Object get(Object key) {
441 // FIXME: access statics here
442 if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
444 Object ret = resourceRoot.get(key);
445 if (ret != null) return ret;
446 throw new JS.Exn("must declare " + key + " before using it!");
448 return super.get(key);
450 public void put(Object key, Object val) {
451 // FIXME: access statics here
452 if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
454 throw new JS.Exn("must declare " + key + " before using it!");