1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
5 import java.util.zip.*;
8 import org.mozilla.javascript.*;
12 * Encapsulates a template node (the <template/> element of a
13 * .xwt file, or any child element thereof). Each instance of
14 * Template has a <tt>nodeName</tt> -- this is the resource name of
15 * the file that the template node occurs in, concatenated with the
16 * path from the root element to this node, each step of which is in
17 * the form .n for some integer n. Static nodes use the string "._"
20 * Note that the Template instance corresponding to the
21 * <template/> node carries all the header information -- hence
22 * some of the instance members are not meaningful on non-root
23 * Template instances. We refer to these non-root instances as
24 * <i>anonymous templates</i>.
26 * See the XWT reference for information on the order in which
27 * templates are applied, attributes are put, and scripts are run.
29 public class Template {
31 // Instance Members ///////////////////////////////////////////////////////
33 /** this instance's nodeName */
36 /** the id of the redirect target; only meaningful on a root node */
37 String redirect = null;
39 /** templates that should be preapplied (in the order of application); only meaningful on a root node */
40 private String[] preapply;
42 /** 'linked' form of preapply -- the String references have been resolved into instance references */
43 private Template[] _preapply = null;
45 /** templates that should be postapplied (in the order of application); only meaningful on a root node */
46 private String[] postapply;
48 /** 'linked' form of postapply -- the String references have been resolved into instance references */
49 private Template[] _postapply = null;
51 /** keys to be "put" to instances of this template; elements correspond to those of vals */
52 private String[] keys;
54 /** values to be "put" to instances of this template; elements correspond to those of keys */
55 private Object[] vals;
57 /** array of strings representing the importlist for this template */
58 private String[] importlist;
60 /** child template objects */
61 private Template[] children;
63 /** an array of the names of properties to be preserved when retheming; only meaningful on a root node */
64 private String[] preserve = null;
66 /** the <tt>id</tt> attribute on this node */
67 private String id = "";
69 /** see numUnits(); -1 means that this value has not yet been computed */
70 private int numunits = -1;
72 /** true iff the resolution of this template's preapply/postapply sets changed as a result of the most recent call to retheme() */
73 private boolean changed = false;
75 /** the script on the static node of this template, null if it has already been executed */
76 private Script staticscript = null;
78 /** the script on this node */
79 private Script script = null;
81 /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
82 private Vec childvect = new Vec();
84 /** during XML parsing, this holds partially-read character data; null otherwise */
85 private StringBuffer content = null;
87 /** line number of the first line of <tt>content</tt> */
88 private int content_start = 0;
90 /** number of lines in <tt>content</tt> */
91 private int content_lines = 0;
93 /** the line number that this element starts on */
94 private int startLine = -1;
96 // Static data/methods ///////////////////////////////////////////////////////////////////
98 /** a template cache so that only one Template object is created for each xwt */
99 private static Hashtable cache = new Hashtable(1000);
101 /** The default importlist; in future revisions this will contain "xwt.*" */
102 public static final String[] defaultImportList = new String[] { };
104 /** returns the appropriate template, resolving and theming as needed */
105 public static Template getTemplate(String name, String[] importlist) {
106 String resolved = Resources.resolve(name + ".xwt", importlist);
107 Template t = resolved == null ? null : (Template)cache.get(resolved.substring(0, resolved.length() - 4));
108 if (t != null) return t;
109 if (resolved == null) return null;
111 // note that Templates in xwar's are instantiated as read in via loadStream() --
112 // the following code only runs when XWT is reading templates from a filesystem.
113 ByteArrayInputStream bais = new ByteArrayInputStream(Resources.getResource(resolved));
114 return buildTemplate(bais, resolved.substring(0, resolved.length() - 4));
117 public static Template buildTemplate(InputStream is, String nodeName) {
119 return new Template(is, nodeName);
120 } catch (XML.SAXParseException e) {
121 if (Log.on) Log.log(Template.class, "error parsing template at " + nodeName + ":" + e.getLineNumber() + "," + e.getColumnNumber());
122 if (Log.on) Log.log(Template.class, e);
124 } catch (XML.SAXException e) {
125 if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
126 if (Log.on) Log.log(Template.class, e);
128 } catch (TemplateException te) {
129 if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
130 if (Log.on) Log.log(Template.class, te);
132 } catch (IOException e) {
133 if (Log.on) Log.log(Template.class, "IOException while parsing template " + nodeName + " -- this should never happen");
134 if (Log.on) Log.log(Template.class, e);
140 // Methods to apply templates ////////////////////////////////////////////////////////
142 private Template(String nodeName) {
143 this.nodeName = nodeName;
144 cache.put(nodeName, this);
146 private Template(InputStream is, String nodeName) throws XML.SAXException, IOException {
148 new TemplateHelper().parseit(is, this);
151 /** calculates, caches, and returns an integer approximation of how long it will take to apply this template, including pre/post and children */
154 if (numunits != -1) return numunits;
156 for(int i=0; _preapply != null && i<_preapply.length; i++) if (_preapply[i] != null) numunits += _preapply[i].numUnits();
157 for(int i=0; _postapply != null && i<_postapply.length; i++) if (_postapply[i] != null) numunits += _postapply[i].numUnits();
158 if (script != null) numunits += 10;
159 numunits += keys == null ? 0 : keys.length;
160 for(int i=0; children != null && i<children.length; i++) numunits += children[i].numUnits();
164 /** Applies the template to Box b
165 * @param pboxes a vector of all box parents on which to put $-references
166 * @param ptemplates a vector of the nodeNames to recieve private references on the pboxes
168 void apply(Box b, Vec pboxes, Vec ptemplates, Function callback, int numerator, int denominator) {
170 int original_numerator = numerator;
172 if (pboxes == null) {
174 ptemplates = new Vec();
177 if (id != null && !id.equals(""))
178 for(int i=0; i<pboxes.size(); i++) {
179 Box parent = (Box)pboxes.elementAt(i);
180 String parentNodeName = (String)ptemplates.elementAt(i);
181 parent.putPrivately("$" + id, b, parentNodeName);
184 if (script != null || (redirect != null && !"self".equals(redirect))) {
185 pboxes.addElement(b);
186 ptemplates.addElement(nodeName);
189 int numids = pboxes.size();
193 for(int i=0; _preapply != null && i<_preapply.length; i++)
194 if (_preapply[i] != null) {
195 _preapply[i].apply(b, null, null, callback, numerator, denominator);
196 numerator += _preapply[i].numUnits();
199 for (int i=0; children != null && i<children.length; i++) {
200 b.put(Integer.MAX_VALUE, null, new Box(children[i], pboxes, ptemplates, callback, numerator, denominator));
201 numerator += children[i].numUnits();
204 // whom to redirect to; doesn't take effect until after script runs
206 if (redirect != null && !"self".equals(redirect))
207 redir = (Box)b.getPrivately("$" + redirect, nodeName);
209 if (script != null) try {
210 Context cx = Context.enter();
212 } catch (EcmaError e) {
213 if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
214 if (Log.on) Log.log(this, " thrown while instantiating " + nodeName + " at " + e.getSourceName() + ":" + e.getLineNumber());
215 } catch (JavaScriptException e) {
216 if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
217 if (Log.on) Log.log(this, " thrown while instantiating " + nodeName + " at " + e.sourceFile + ":" + e.line);
220 for(int i=0; keys != null && i<keys.length; i++) {
221 Context.enter().interpreterSourceFile = nodeName;
222 Context.enter().interpreterLine = startLine;
223 if (keys[i] == null) { }
224 else if (keys[i].equals("border") || keys[i].equals("image") &&
225 !vals[i].toString().startsWith("http://") && !vals[i].toString().startsWith("https://")) {
226 String s = Resources.resolve(vals[i].toString() + ".png", importlist);
227 if (s != null) b.put(keys[i], null, s.substring(0, s.length() - 4));
228 else if (Log.on) Log.log(this, "unable to resolve image " + vals[i].toString() + " referenced in attributes of " + nodeName);
230 else b.put(keys[i], null, vals[i]);
233 if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
235 for(int i=0; _postapply != null && i<_postapply.length; i++)
236 if (_postapply[i] != null) {
237 _postapply[i].apply(b, null, null, callback, numerator, denominator);
238 numerator += _postapply[i].numUnits();
241 pboxes.setSize(numids);
242 ptemplates.setSize(numids);
244 numerator = original_numerator + numUnits();
246 if (callback != null)
248 callback.call(Context.enter(), null, null, new Object[] { new Double(numerator), new Double(denominator) });
249 } catch (EcmaError e) {
250 if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
251 if (Log.on) Log.log(this, " thrown from within progress callback at " + e.getSourceName() + ":" + e.getLineNumber());
252 } catch (JavaScriptException e) {
253 if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
254 if (Log.on) Log.log(this, " thrown from within progress callback at " + e.sourceFile + ":" + e.line);
257 if (Thread.currentThread() instanceof ThreadMessage) try {
258 XWT.yield.call(Context.enter(), null, null, null);
259 } catch (JavaScriptException e) {
260 if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
261 if (Log.on) Log.log(this, " thrown from within yield at " + e.sourceFile + ":" + e.line);
266 // Theming Logic ////////////////////////////////////////////////////////////
268 /** helper method to recursively gather up the list of keys to be preserved */
269 private void gatherPreserves(Vec v) {
270 for(int i=0; preserve != null && i<preserve.length; i++) v.addElement(preserve[i]);
271 for(int i=0; _preapply != null && i<_preapply.length; i++) if (_preapply[i] != null) _preapply[i].gatherPreserves(v);
272 for(int i=0; _postapply != null && i<_postapply.length; i++) if (_postapply[i] != null) _postapply[i].gatherPreserves(v);
275 /** adds a theme mapping, retemplatizing as needed */
276 public static void retheme(Function callback) {
279 // clear changed marker and relink
280 Template[] t = new Template[cache.size()];
281 Enumeration e = cache.elements();
282 for(int i=0; e.hasMoreElements(); i++) t[i] = (Template)e.nextElement();
283 for(int i=0; i<t.length; i++) {
284 t[i].changed = false;
289 for(int i=0; i<Surface.allSurfaces.size(); i++) {
290 Box b = ((Surface)Surface.allSurfaces.elementAt(i)).root;
291 if (b != null) reapply(b);
294 if (callback != null)
296 callback.call(Context.enter(), null, null, new Object[] { new Double(1.0), new Double(1.0) });
297 } catch (EcmaError ex) {
298 if (Log.on) Log.log(Template.class, "WARNING: uncaught interpreter exception: " + ex.getMessage());
299 if (Log.on) Log.log(Template.class, " thrown from within progress callback at " + ex.getSourceName() + ":" + ex.getLineNumber());
300 } catch (JavaScriptException ex) {
301 if (Log.on) Log.log(Template.class, "WARNING: uncaught ecmascript exception: " + ex.getMessage());
302 if (Log.on) Log.log(Template.class, " thrown from within progress callback at " + ex.sourceFile + ":" + ex.line);
306 /** template reapplication procedure */
307 private static void reapply(Box b) {
309 // Ref 7.5.1: check if we need to retemplatize
310 boolean retemplatize = false;
311 if (b.templatename != null) {
312 Template t = getTemplate(b.templatename, b.importlist);
313 if (t != b.template) retemplatize = true;
316 if (b.template != null && b.template.changed) retemplatize = true;
320 // Ref 7.5.2: "Preserve all properties on the box mentioned in the <preserve> elements of any
321 // of the templates which would be applied in step 7."
322 Vec keys = new Vec();
323 b.template.gatherPreserves(keys);
324 Object[] vals = new Object[keys.size()];
325 for(int i=0; i<keys.size(); i++) vals[i] = b.get(((String)keys.elementAt(i)), null);
327 // Ref 7.5.3: "Remove and save all children of the box, or its redirect target, if it has one"
329 if (b.redirect != null) {
330 kids = new Box[b.redirect.numChildren()];
331 for(int i=b.redirect.numChildren() - 1; i >= 0; i--) {
332 kids[i] = b.redirect.getChild(i);
337 // Ref 7.5.4: "Set the box's redirect target to self"
340 // Ref 7.5.5: "Remove all of the box's immediate children"
341 for(Box cur = b.getChild(b.numChildren() - 1); cur != null;) {
343 cur = cur.prevSibling();
347 // Ref 7.5.6: "Remove all traps set by scripts run during the application of any template to this box"
348 Trap.removeAllTrapsByBox(b);
350 // Ref 7.5.7: "Apply the template to the box according to the usual application procedure"
351 b.template.apply(b, null, null, null, 0, 1);
353 // Ref 7.5.8: "Re-add the saved children which were removed in step 3"
354 for(int i=0; kids != null && i<kids.length; i++) b.put(Integer.MAX_VALUE, null, kids[i]);
356 // Ref 7.5.9: "Re-put any property values which were preserved in step 2"
357 for(int i=0; i<keys.size(); i++) b.put((String)keys.elementAt(i), null, vals[i]);
361 for(Box j = b.getChild(0); j != null; j = j.nextSibling()) reapply(j);
364 /** runs statics, resolves string references to other templates into actual Template instance references, and sets <tt>change</tt> as needed */
365 void link() { link(false); }
367 /** same as link(), except that with a true value, it will force a re-link */
368 private void link(boolean force) {
370 if (staticscript != null) try {
371 Scriptable s = Static.createStatic(nodeName, false);
372 if (staticscript != null) {
373 Script temp = staticscript;
374 ((InterpretedScript)temp).setParentScope(s); // so we know how to handle Static.get("xwt")
376 temp.exec(Context.enter(), s);
378 } catch (EcmaError e) {
379 if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
380 if (Log.on) Log.log(this, " thrown while executing <static/> block for " + nodeName +
381 " at " + e.getSourceName() + ":" + e.getLineNumber());
382 } catch (JavaScriptException e) {
383 if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
384 if (Log.on) Log.log(this, " thrown while executing <static/> block for " + nodeName + " at " + e.sourceFile + ":" + e.line);
387 if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
389 if (preapply != null) {
390 if (_preapply == null) _preapply = new Template[preapply.length];
391 for(int i=0; i<_preapply.length; i++) {
392 Template t = getTemplate(preapply[i], importlist);
393 if (t != _preapply[i]) changed = true;
397 if (postapply != null) {
398 if (_postapply == null) _postapply = new Template[postapply.length];
399 for(int i=0; i<_postapply.length; i++) {
400 Template t = getTemplate(postapply[i], importlist);
401 if (t != _postapply[i]) changed = true;
406 for(int i=0; children != null && i<children.length; i++) children[i].link(force);
410 // XML Parsing /////////////////////////////////////////////////////////////////
412 /** handles XML parsing; builds a Template tree as it goes */
413 private static class TemplateHelper extends XML {
416 for(int i=0; i<defaultImportList.length; i++) importlist.addElement(defaultImportList[i]);
419 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
420 void parseit(InputStream is, Template root) throws XML.SAXException, IOException {
422 parse(new TabAndMaxColumnEnforcingReader(new InputStreamReader(is), root.nodeName));
425 /** parsing state: true iff we have already encountered the <xwt> open-tag */
426 boolean rootNodeHasBeenEncountered = false;
428 /** parsing state: true iff we have already encountered the <template> open-tag */
429 boolean templateNodeHasBeenEncountered = false;
431 /** parsing state: true iff we have already encountered the <static> open-tag */
432 boolean staticNodeHasBeenEncountered = false;
434 /** parsing state: true iff we have already encountered the <template> close-tag */
435 boolean templateNodeHasBeenFinished = false;
437 /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
438 * that tag; otherwise, it is null. */
439 String nameOfHeaderNodeBeingProcessed = null;
441 /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
442 Vec nodeStack = new Vec();
444 /** builds up the list of imports */
445 Vec importlist = new Vec();
447 /** builds up the list of preapplies */
448 Vec preapply = new Vec();
450 /** builds up the list of postapplies */
451 Vec postapply = new Vec();
453 /** the template we're currently working on */
456 public void startElement(String name, String[] keys, Object[] vals, int line, int col) throws XML.SAXException {
458 if (templateNodeHasBeenFinished) {
459 throw new XML.SAXException("no elements may appear after the <template> node");
461 } else if (!rootNodeHasBeenEncountered) {
462 if (!"xwt".equals(name)) throw new XML.SAXException("root element was not <xwt>");
463 if (keys.length != 0) throw new XML.SAXException("root element must not have attributes");
464 rootNodeHasBeenEncountered = true;
467 } else if (!templateNodeHasBeenEncountered) {
468 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SAXException("can't nest header nodes");
469 nameOfHeaderNodeBeingProcessed = name;
471 if (name.equals("import")) {
472 if (keys.length != 1 || !keys[0].equals("name"))
473 throw new XML.SAXException("<import> node must have exactly one attribute, which must be called 'name'");
474 String importpackage = vals[0].toString();
475 if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
476 importlist.addElement(importpackage);
479 } else if (name.equals("redirect")) {
480 if (keys.length != 1 || !keys[0].equals("target"))
481 throw new XML.SAXException("<redirect> node must have exactly one attribute, which must be called 'target'");
482 if (t.redirect != null)
483 throw new XML.SAXException("the <redirect> header element may not appear more than once");
484 t.redirect = vals[0].toString();
487 } else if (name.equals("preapply")) {
488 if (keys.length != 1 || !keys[0].equals("name"))
489 throw new XML.SAXException("<preapply> node must have exactly one attribute, which must be called 'name'");
490 preapply.addElement(vals[0]);
493 } else if (name.equals("postapply")) {
494 if (keys.length != 1 || !keys[0].equals("name"))
495 throw new XML.SAXException("<postapply> node must have exactly one attribute, which must be called 'name'");
496 postapply.addElement(vals[0]);
499 } else if (name.equals("static")) {
500 if (staticNodeHasBeenEncountered)
501 throw new XML.SAXException("the <static> header node may not appear more than once");
503 throw new XML.SAXException("the <static> node may not have attributes");
504 staticNodeHasBeenEncountered = true;
507 } else if (name.equals("preserve")) {
508 if (keys.length != 1 || !keys[0].equals("attributes"))
509 throw new XML.SAXException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
510 if (t.preserve != null)
511 throw new XML.SAXException("<preserve> header element may not appear more than once");
513 StringTokenizer tok = new StringTokenizer(vals[0].toString(), ",", false);
514 t.preserve = new String[tok.countTokens()];
515 for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
518 } else if (name.equals("template")) {
519 // finalize importlist/preapply/postapply, since they can't change from here on
521 importlist.toArray(t.importlist = new String[importlist.size()]);
522 if (preapply.size() > 0) preapply.copyInto(t.preapply = new String[preapply.size()]);
523 if (postapply.size() > 0) postapply.copyInto(t.postapply = new String[postapply.size()]);
524 importlist = preapply = postapply = null;
525 templateNodeHasBeenEncountered = true;
528 throw new XML.SAXException("unrecognized header node \"" + name + "\"");
534 // push the last node we were in onto the stack
535 nodeStack.addElement(t);
537 // instantiate a new node, and set its nodeName/importlist/preapply
538 Template t2 = new Template(t.nodeName + "." + t.childvect.size());
539 t2.importlist = t.importlist;
541 if (!name.equals("box")) t2.preapply = new String[] { name };
543 // make the new node the current node
551 quickSortAttributes(0, t.keys.length - 1);
553 for(int i=0; i<t.keys.length; i++) {
554 if (t.keys[i].equals("id")) {
555 t.id = vals[i].toString().intern();
560 t.keys[i] = t.keys[i].intern();
562 String valString = vals[i].toString();
564 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
565 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
566 else if (valString.equals("null")) t.vals[i] = null;
568 boolean hasNonNumeral = false;
569 boolean periodUsed = false;
570 for(int j=0; j<valString.length(); j++)
571 if (j == 0 && valString.charAt(j) == '-') {
572 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
574 } else if (!Character.isDigit(valString.charAt(j))) {
575 hasNonNumeral = true;
578 if (valString.length() > 0 && !hasNonNumeral) vals[i] = new Double(valString);
579 else vals[i] = valString.intern();
582 // bump thisbox to the front of the pack
583 if (t.keys[i].equals("thisbox")) {
584 t.keys[i] = t.keys[0];
585 t.keys[0] = "thisbox";
586 Object o = t.vals[0];
587 t.vals[0] = t.vals[i];
593 /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
594 private int partitionAttributes(int left, int right) {
596 middle = (left + right) / 2;
597 String s = t.keys[right]; t.keys[right] = t.keys[middle]; t.keys[middle] = s;
598 Object o = t.vals[right]; t.vals[right] = t.vals[middle]; t.vals[middle] = o;
599 for (i = left - 1, j = right; ; ) {
600 while (t.keys[++i].compareTo(t.keys[right]) < 0);
601 while (j > left && t.keys[--j].compareTo(t.keys[right]) > 0);
603 s = t.keys[i]; t.keys[i] = t.keys[j]; t.keys[j] = s;
604 o = t.vals[i]; t.vals[i] = t.vals[j]; t.vals[j] = o;
606 s = t.keys[right]; t.keys[right] = t.keys[i]; t.keys[i] = s;
607 o = t.vals[right]; t.vals[right] = t.vals[i]; t.vals[i] = o;
611 /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
612 private void quickSortAttributes(int left, int right) {
613 if (left >= right) return;
614 int p = partitionAttributes(left, right);
615 quickSortAttributes(left, p - 1);
616 quickSortAttributes(p + 1, right);
619 public void endElement(String name, int line, int col) throws XML.SAXException {
621 boolean hasNonWhitespace = false;
623 int len = t == null || t.content == null ? 0 : t.content.length();
624 for(int i=0; t.content != null && i<len; i++)
626 // ignore double-slash comment blocks
627 if (t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '/') {
628 while(t.content.charAt(i) != '\n' && i<len) i++;
631 // ignore /* .. */ comment blocks
632 } else if (i<len - 1 && t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '*') {
634 while(i<len - 1 && !(t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/')) i++;
635 if (i<len - 1 && t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/') i += 2;
638 // check for named functions
639 } else if (i + 8 <= len && t.content.charAt(i) == 'f' && t.content.charAt(i+1) == 'u' &&
640 t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'c' && t.content.charAt(i+4) == 't' &&
641 t.content.charAt(i+5) == 'i' && t.content.charAt(i+6) == 'o' && t.content.charAt(i+7) == 'n') {
643 while(j<len && Character.isWhitespace(t.content.charAt(j))) j++;
644 if (j<len && t.content.charAt(j) != '(')
645 throw new XML.SAXException("named functions are not permitted in XWT -- instead of \"function foo() { ... }\"," +
646 " use \"foo = function() { ... }\"");
648 // replace " and " with " && "
649 } else if (i + 5 < len && Character.isWhitespace(t.content.charAt(i)) &&
650 t.content.charAt(i+1) == 'a' && t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'd' &&
651 Character.isWhitespace(t.content.charAt(i + 4))) {
652 t.content.setCharAt(i+1, '&');
653 t.content.setCharAt(i+2, '&');
654 t.content.setCharAt(i+3, ' ');
655 hasNonWhitespace = true;
657 // generic check for nonwhitespace
658 } else if (!Character.isWhitespace(t.content.charAt(i))) {
659 hasNonWhitespace = true;
663 if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
664 if ("static".equals(nameOfHeaderNodeBeingProcessed) && hasNonWhitespace) t.staticscript = genscript(true);
665 nameOfHeaderNodeBeingProcessed = null;
667 } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
669 // turn our childvect into a Template[]
670 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
672 if (hasNonWhitespace) t.script = genscript(false);
674 if (nodeStack.size() == 0) {
676 templateNodeHasBeenFinished = true;
679 // add this template as a child of its parent
681 t = (Template)nodeStack.lastElement();
682 nodeStack.setSize(nodeStack.size() - 1);
683 t.childvect.addElement(oldt);
689 private Script genscript(boolean isstatic) {
690 Script thisscript = null;
691 Context cx = Context.enter();
692 cx.setOptimizationLevel(-1);
695 thisscript = cx.compileReader(null, new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start, null);
696 } catch (EcmaError ee) {
697 if (Log.on) Log.log(this, ee.getMessage() + " at " + ee.getSourceName() + ":" + ee.getLineNumber());
699 } catch (EvaluatorException ee) {
700 if (Log.on) Log.log(this, " ERROR: " + ee.getMessage());
702 } catch (IOException ioe) {
703 if (Log.on) Log.log(this, "IOException while compiling script; this should never happen");
704 if (Log.on) Log.log(this, ioe);
714 public void content(char[] ch, int start, int length, int line, int col) throws XML.SAXException {
715 if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
716 int contentlines = 0;
717 for(int i=start; i<start + length; i++) if (ch[i] == '\n') contentlines++;
718 line -= contentlines;
720 if (t.content == null) {
721 t.content_start = line;
723 t.content = new StringBuffer();
726 for(int i=t.content_start + t.content_lines; i<line; i++) {
727 t.content.append('\n');
731 t.content.append(ch, start, length);
732 t.content_lines += contentlines;
734 } else if (nameOfHeaderNodeBeingProcessed != null) {
735 throw new XML.SAXException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
743 /** a filtering reader that watches for tabs and long lines */
744 private static class TabAndMaxColumnEnforcingReader extends FilterReader {
745 private int MAX_COLUMN = 150;
746 private int column = 0;
747 private int line = 1;
748 private boolean lastCharWasCR = false;
749 private String filename;
750 public TabAndMaxColumnEnforcingReader(Reader r, String filename) { super(r); this.filename = filename; }
752 if (Log.on) Log.log(this, this.getClass().getName() + ".read() not supported, this should never happen");
755 public long skip(long numskip) {
756 if (Log.on) Log.log(this, this.getClass().getName() + ".skip() not supported; this should never happen");
759 public int read(char[] buf, int off, int len) throws IOException {
760 int ret = super.read(buf, off, len);
761 for(int i=off; i<off + ret; i++)
762 if (buf[i] == '\t') {
763 throw new TemplateException(filename + ":" + line + "," + column + ": tabs are not allowed in XWT files");
764 } else if (buf[i] == '\r') {
767 lastCharWasCR = true;
768 } else if (buf[i] == '\n') {
770 if (!lastCharWasCR) line++;
771 } else if (++column > MAX_COLUMN) {
772 throw new TemplateException(filename + ":" + line + ": lines longer than " + MAX_COLUMN + " characters not allowed");
774 lastCharWasCR = false;
780 private static class TemplateException extends IOException {
781 TemplateException(String s) { super(s); }