2002/09/15 23:38:37
[org.ibex.core.git] / src / org / xwt / Template.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.util.zip.*;
6 import java.util.*;
7 import java.lang.*;
8 import org.mozilla.javascript.*;
9 import org.xwt.util.*;
10
11 /**
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 "._"
18  *  as a path.
19  *
20  *  Note that the Template instance corresponding to the
21  *  &lt;template/&gt; 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>.
25  *
26  *  See the XWT reference for information on the order in which
27  *  templates are applied, attributes are put, and scripts are run.
28  */
29 public class Template {
30
31     // Instance Members ///////////////////////////////////////////////////////
32
33     /** this instance's nodeName */
34     String nodeName;
35
36     /** the id of the redirect target; only meaningful on a root node */
37     String redirect = null;
38
39     /** templates that should be preapplied (in the order of application); only meaningful on a root node */
40     private String[] preapply;
41
42     /** 'linked' form of preapply -- the String references have been resolved into instance references */
43     private Template[] _preapply = null;
44
45     /** templates that should be postapplied (in the order of application); only meaningful on a root node */
46     private String[] postapply;
47
48     /** 'linked' form of postapply -- the String references have been resolved into instance references */
49     private Template[] _postapply = null;
50
51     /** keys to be "put" to instances of this template; elements correspond to those of vals */
52     private String[] keys;
53
54     /** values to be "put" to instances of this template; elements correspond to those of keys */
55     private Object[] vals;
56
57     /** array of strings representing the importlist for this template */
58     private String[] importlist;
59
60     /** child template objects */
61     private Template[] children;
62
63     /** an array of the names of properties to be preserved when retheming; only meaningful on a root node */
64     private String[] preserve = null;
65     
66     /** the <tt>id</tt> attribute on this node */
67     private String id = "";
68
69     /** see numUnits(); -1 means that this value has not yet been computed */
70     private int numunits = -1;
71
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;
74
75     /** the script on the static node of this template, null if it has already been executed */
76     private Script staticscript = null;
77
78     /** the script on this node */
79     private Script script = null;
80
81     /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
82     private Vec childvect = new Vec();
83
84     /** during XML parsing, this holds partially-read character data; null otherwise */
85     private StringBuffer content = null;
86
87     /** line number of the first line of <tt>content</tt> */
88     private int content_start = 0;
89
90     /** number of lines in <tt>content</tt> */
91     private int content_lines = 0;
92
93     /** the line number that this element starts on */
94     private int startLine = -1;
95
96     // Static data/methods ///////////////////////////////////////////////////////////////////
97
98     /** a template cache so that only one Template object is created for each xwt */
99     private static Hashtable cache = new Hashtable(1000);
100
101     /** The default importlist; in future revisions this will contain "xwt.*" */
102     public static final String[] defaultImportList = new String[] { };
103
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;
110
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));
115     }
116
117     public static Template buildTemplate(InputStream is, String nodeName) {
118         try {
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);
123             return null;
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);
127             return null;
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);
131             return null;
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);
135             return null;
136         }
137     }
138
139
140     // Methods to apply templates ////////////////////////////////////////////////////////
141
142     private Template(String nodeName) {
143         this.nodeName = nodeName;
144         cache.put(nodeName, this);
145     }
146     private Template(InputStream is, String nodeName) throws XML.SAXException, IOException {
147         this(nodeName);
148         new TemplateHelper().parseit(is, this);
149     }
150
151     /** calculates, caches, and returns an integer approximation of how long it will take to apply this template, including pre/post and children */
152     int numUnits() {
153         link();
154         if (numunits != -1) return numunits;
155         numunits = 1;
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();
161         return numunits;
162     }
163     
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
167      */
168     void apply(Box b, Vec pboxes, Vec ptemplates, Function callback, int numerator, int denominator) {
169
170         int original_numerator = numerator;
171
172         if (pboxes == null) {
173             pboxes = new Vec();
174             ptemplates = new Vec();
175         }
176
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);
182             }
183
184         if (script != null || (redirect != null && !"self".equals(redirect))) {
185             pboxes.addElement(b);
186             ptemplates.addElement(nodeName);
187         }
188
189         int numids = pboxes.size();
190         
191         link();
192
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();
197             }
198
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();
202         }
203
204         // whom to redirect to; doesn't take effect until after script runs
205         Box redir = null;
206         if (redirect != null && !"self".equals(redirect))
207             redir = (Box)b.getPrivately("$" + redirect, nodeName);
208
209         if (script != null) try {
210             Context cx = Context.enter();
211             script.exec(cx, b);
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);
218         }
219
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); 
229             }
230             else b.put(keys[i], null, vals[i]);
231         }
232
233         if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
234
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();
239             }
240
241         pboxes.setSize(numids);
242         ptemplates.setSize(numids);
243
244         numerator = original_numerator + numUnits();
245
246         if (callback != null)
247             try {
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);
255             }
256
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);
262         }
263     }
264
265
266     // Theming Logic ////////////////////////////////////////////////////////////
267
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);
273     }
274
275     /** adds a theme mapping, retemplatizing as needed */
276     public static void retheme(Function callback) {
277         XWF.flushXWFs();
278
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;
285             t[i].numunits = -1;
286             t[i].link(true);
287         }
288
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);
292         }
293
294         if (callback != null)
295             try {
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);
303             }
304     }
305
306     /** template reapplication procedure */
307     private static void reapply(Box b) {
308
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;
314             b.template = t;
315         }
316         if (b.template != null && b.template.changed) retemplatize = true;
317
318         if (retemplatize) {
319
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);
326             
327             // Ref 7.5.3: "Remove and save all children of the box, or its redirect target, if it has one"
328             Box[] kids = null;
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);
333                     kids[i].remove();
334                 }
335             }
336             
337             // Ref 7.5.4: "Set the box's redirect target to self"
338             b.redirect = b;
339             
340             // Ref 7.5.5: "Remove all of the box's immediate children"
341             for(Box cur = b.getChild(b.numChildren() - 1); cur != null;) {
342                 Box oldcur = cur;
343                 cur = cur.prevSibling();
344                 oldcur.remove();
345             }
346             
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);
349             
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);
352             
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]);
355             
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]);
358         }        
359
360         // Recurse
361         for(Box j = b.getChild(0); j != null; j = j.nextSibling()) reapply(j);
362     }
363
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); }
366
367     /** same as link(), except that with a true value, it will force a re-link */
368     private void link(boolean force) {
369
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")
375                 staticscript = null;
376                 temp.exec(Context.enter(), s);
377             }
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);
385         }
386
387         if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
388         
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;
394                 _preapply[i] = t;
395             }
396         }
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;
402                 _postapply[i] = t;
403             }
404         }
405
406         for(int i=0; children != null && i<children.length; i++) children[i].link(force);
407     }
408
409
410     // XML Parsing /////////////////////////////////////////////////////////////////
411
412     /** handles XML parsing; builds a Template tree as it goes */
413     private static class TemplateHelper extends XML {
414
415         TemplateHelper() {
416             for(int i=0; i<defaultImportList.length; i++) importlist.addElement(defaultImportList[i]);
417         }
418
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 {
421             t = root;
422             parse(new TabAndMaxColumnEnforcingReader(new InputStreamReader(is), root.nodeName)); 
423         }
424
425         /** parsing state: true iff we have already encountered the <xwt> open-tag */
426         boolean rootNodeHasBeenEncountered = false;
427
428         /** parsing state: true iff we have already encountered the <template> open-tag */
429         boolean templateNodeHasBeenEncountered = false;
430
431         /** parsing state: true iff we have already encountered the <static> open-tag */
432         boolean staticNodeHasBeenEncountered = false;
433
434         /** parsing state: true iff we have already encountered the <template> close-tag */
435         boolean templateNodeHasBeenFinished = false;
436
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;
440
441         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
442         Vec nodeStack = new Vec();
443
444         /** builds up the list of imports */
445         Vec importlist = new Vec();
446
447         /** builds up the list of preapplies */
448         Vec preapply = new Vec();
449
450         /** builds up the list of postapplies */
451         Vec postapply = new Vec();
452
453         /** the template we're currently working on */
454         Template t = null;
455
456         public void startElement(String name, String[] keys, Object[] vals, int line, int col) throws XML.SAXException {
457
458             if (templateNodeHasBeenFinished) {
459                 throw new XML.SAXException("no elements may appear after the <template> node");
460
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;
465                 return;
466         
467             } else if (!templateNodeHasBeenEncountered) {
468                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SAXException("can't nest header nodes");
469                 nameOfHeaderNodeBeingProcessed = name;
470
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);
477                     return;
478
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();
485                     return;
486
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]);
491                     return;
492
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]);
497                     return;
498
499                 } else if (name.equals("static")) {
500                     if (staticNodeHasBeenEncountered)
501                         throw new XML.SAXException("the <static> header node may not appear more than once");
502                     if (keys.length > 0)
503                         throw new XML.SAXException("the <static> node may not have attributes");
504                     staticNodeHasBeenEncountered = true;
505                     return;
506
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");
512
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();
516                     return;
517
518                 } else if (name.equals("template")) {
519                     // finalize importlist/preapply/postapply, since they can't change from here on
520                     t.startLine = line;
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;
526
527                 } else {
528                     throw new XML.SAXException("unrecognized header node \"" + name + "\"");
529
530                 }
531
532             } else {
533
534                 // push the last node we were in onto the stack
535                 nodeStack.addElement(t);
536
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;
540                 t2.startLine = line;
541                 if (!name.equals("box")) t2.preapply = new String[] { name };
542
543                 // make the new node the current node
544                 t = t2;
545
546             }
547
548             t.keys = keys;
549             t.vals = vals;
550
551             quickSortAttributes(0, t.keys.length - 1);
552
553             for(int i=0; i<t.keys.length; i++) {
554                 if (t.keys[i].equals("id")) {
555                     t.id = vals[i].toString().intern();
556                     t.keys[i] = null;
557                     continue;
558                 }
559
560                 t.keys[i] = t.keys[i].intern();
561
562                 String valString = vals[i].toString();
563                 
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;
567                 else {
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) {
573                             periodUsed = true;
574                         } else if (!Character.isDigit(valString.charAt(j))) {
575                             hasNonNumeral = true;
576                             break;
577                         }
578                     if (valString.length() > 0 && !hasNonNumeral) vals[i] = new Double(valString);
579                     else vals[i] = valString.intern();
580                 }
581
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];
588                     t.vals[i] = o;
589                 }
590             }
591         }
592
593         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
594         private int partitionAttributes(int left, int right) {
595             int i, j, middle;
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);
602                 if (i >= j) break;
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;
605             }
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;
608             return i;
609         }
610         
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);
617         }
618         
619         public void endElement(String name, int line, int col) throws XML.SAXException {
620
621             boolean hasNonWhitespace = false;
622
623             int len = t == null || t.content == null ? 0 : t.content.length();
624             for(int i=0; t.content != null && i<len; i++)
625                 
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++;
629                     i--;
630
631                 // ignore /* .. */ comment blocks
632                 } else if (i<len - 1 && t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '*') {
633                     i += 2;
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;
636                     i--;
637
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') {
642                     int j = i + 8;
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() { ... }\"");
647
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;
656
657                 // generic check for nonwhitespace
658                 } else if (!Character.isWhitespace(t.content.charAt(i))) {
659                     hasNonWhitespace = true;
660
661                 }
662             
663             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
664                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && hasNonWhitespace) t.staticscript = genscript(true);
665                 nameOfHeaderNodeBeingProcessed = null;
666
667             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
668
669                 // turn our childvect into a Template[]
670                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
671                 t.childvect = null;
672                 if (hasNonWhitespace) t.script = genscript(false);
673                 
674                 if (nodeStack.size() == 0) {
675                     // </template>
676                     templateNodeHasBeenFinished = true;
677
678                 } else {
679                     // add this template as a child of its parent
680                     Template oldt = t;
681                     t = (Template)nodeStack.lastElement();
682                     nodeStack.setSize(nodeStack.size() - 1);
683                     t.childvect.addElement(oldt);
684                 }
685
686             }
687         }
688
689         private Script genscript(boolean isstatic) {
690             Script thisscript = null;
691             Context cx = Context.enter();
692             cx.setOptimizationLevel(-1);
693
694             try {
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());
698                 thisscript = null;
699             } catch (EvaluatorException ee) {
700                 if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
701                 thisscript = null;
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);
705                 thisscript = null;
706             }
707
708             t.content = null;
709             t.content_start = 0;
710             t.content_lines = 0;
711             return thisscript;
712         }
713
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;
719
720                 if (t.content == null) {
721                     t.content_start = line;
722                     t.content_lines = 0;
723                     t.content = new StringBuffer();
724                 }
725
726                 for(int i=t.content_start + t.content_lines; i<line; i++) {
727                     t.content.append('\n');
728                     t.content_lines++;
729                 }
730
731                 t.content.append(ch, start, length);
732                 t.content_lines += contentlines;
733
734             } else if (nameOfHeaderNodeBeingProcessed != null) {
735                 throw new XML.SAXException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
736
737             }
738
739         }
740
741     }
742
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; }
751         public int read() {
752             if (Log.on) Log.log(this, this.getClass().getName() + ".read() not supported, this should never happen");
753             return -1;
754         }
755         public long skip(long numskip) {
756             if (Log.on) Log.log(this, this.getClass().getName() + ".skip() not supported; this should never happen");
757             return numskip;
758         }
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') {
765                     column = 0;
766                     line++;
767                     lastCharWasCR = true;
768                 } else if (buf[i] == '\n') {
769                     column = 0;
770                     if (!lastCharWasCR) line++;
771                 } else if (++column > MAX_COLUMN) {
772                     throw new TemplateException(filename + ":" + line + ": lines longer than " + MAX_COLUMN + " characters not allowed");
773                 } else {
774                     lastCharWasCR = false;
775                 }
776             return ret;
777         }
778     }
779
780     private static class TemplateException extends IOException {
781         TemplateException(String s) { super(s); }
782     }
783
784 }
785
786