2002/08/18 05:30:45
[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(String from, String to) {
277         if (Log.on) Log.log(Template.class, "retheming from " + from + " to " + to);
278         XWF.flushXWFs();
279         Resources.mapFrom.addElement(from);
280         Resources.mapTo.addElement(to);
281
282         // clear changed marker and relink
283         Template[] t = new Template[cache.size()];
284         Enumeration e = cache.elements();
285         for(int i=0; e.hasMoreElements(); i++) t[i] = (Template)e.nextElement();
286         for(int i=0; i<t.length; i++) {
287             t[i].changed = false;
288             t[i].numunits = -1;
289             t[i].link(true);
290         }
291
292         for(int i=0; i<Surface.allSurfaces.size(); i++) {
293             Box b = ((Surface)Surface.allSurfaces.elementAt(i)).root;
294             if (b != null) reapply(b);
295         }
296     }
297
298     /** template reapplication procedure */
299     private static void reapply(Box b) {
300
301         // Ref 7.5.1: check if we need to retemplatize
302         boolean retemplatize = false;
303         if (b.templatename != null) {
304             Template t = getTemplate(b.templatename, b.importlist);
305             if (t != b.template) retemplatize = true;
306             b.template = t;
307         }
308         if (b.template != null && b.template.changed) retemplatize = true;
309
310         if (retemplatize) {
311
312             // Ref 7.5.2: "Preserve all properties on the box mentioned in the <preserve> elements of any
313             //             of the templates which would be applied in step 7."
314             Vec keys = new Vec();
315             b.template.gatherPreserves(keys);
316             Object[] vals = new Object[keys.size()];
317             for(int i=0; i<keys.size(); i++) vals[i] = b.get(((String)keys.elementAt(i)), null);
318             
319             // Ref 7.5.3: "Remove and save all children of the box, or its redirect target, if it has one"
320             Box[] kids = null;
321             if (b.redirect != null) {
322                 kids = new Box[b.redirect.numChildren()];
323                 for(int i=b.redirect.numChildren() - 1; i >= 0; i--) {
324                     kids[i] = b.redirect.getChild(i);
325                     kids[i].remove();
326                 }
327             }
328             
329             // Ref 7.5.4: "Set the box's redirect target to self"
330             b.redirect = b;
331             
332             // Ref 7.5.5: "Remove all of the box's immediate children"
333             for(Box cur = b.getChild(b.numChildren() - 1); cur != null;) {
334                 Box oldcur = cur;
335                 cur = cur.prevSibling();
336                 oldcur.remove();
337             }
338             
339             // Ref 7.5.6: "Remove all traps set by scripts run during the application of any template to this box"
340             Trap.removeAllTrapsByBox(b);
341             
342             // Ref 7.5.7: "Apply the template to the box according to the usual application procedure"
343             b.template.apply(b, null, null, null, 0, 1);
344             
345             // Ref 7.5.8: "Re-add the saved children which were removed in step 3"
346             for(int i=0; kids != null && i<kids.length; i++) b.put(Integer.MAX_VALUE, null, kids[i]);
347             
348             // Ref 7.5.9: "Re-put any property values which were preserved in step 2"
349             for(int i=0; i<keys.size(); i++) b.put((String)keys.elementAt(i), null, vals[i]);
350         }        
351
352         // Recurse
353         for(Box j = b.getChild(0); j != null; j = j.nextSibling()) reapply(j);
354     }
355
356     /** runs statics, resolves string references to other templates into actual Template instance references, and sets <tt>change</tt> as needed */
357     void link() { link(false); }
358
359     /** same as link(), except that with a true value, it will force a re-link */
360     private void link(boolean force) {
361
362         if (staticscript != null) try { 
363             Scriptable s = Static.createStatic(nodeName, false);
364             if (staticscript != null) {
365                 Script temp = staticscript;
366                 ((InterpretedScript)temp).setParentScope(s);     // so we know how to handle Static.get("xwt")
367                 staticscript = null;
368                 temp.exec(Context.enter(), s);
369             }
370         } catch (EcmaError e) {
371             if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
372             if (Log.on) Log.log(this, "         thrown while executing <static/> block for " + nodeName +
373                                       " at " + e.getSourceName() + ":" + e.getLineNumber());
374         } catch (JavaScriptException e) {
375             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
376             if (Log.on) Log.log(this, "         thrown while executing <static/> block for " + nodeName + " at " + e.sourceFile + ":" + e.line);
377         }
378
379         if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
380         
381         if (preapply != null) {
382             if (_preapply == null) _preapply = new Template[preapply.length];
383             for(int i=0; i<_preapply.length; i++) {
384                 Template t = getTemplate(preapply[i], importlist);
385                 if (t != _preapply[i]) changed = true;
386                 _preapply[i] = t;
387             }
388         }
389         if (postapply != null) {
390             if (_postapply == null) _postapply = new Template[postapply.length];
391             for(int i=0; i<_postapply.length; i++) {
392                 Template t = getTemplate(postapply[i], importlist);
393                 if (t != _postapply[i]) changed = true;
394                 _postapply[i] = t;
395             }
396         }
397
398         for(int i=0; children != null && i<children.length; i++) children[i].link(force);
399     }
400
401
402     // XML Parsing /////////////////////////////////////////////////////////////////
403
404     /** handles XML parsing; builds a Template tree as it goes */
405     private static class TemplateHelper extends XML {
406
407         TemplateHelper() {
408             for(int i=0; i<defaultImportList.length; i++) importlist.addElement(defaultImportList[i]);
409         }
410
411         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
412         void parseit(InputStream is, Template root) throws XML.SAXException, IOException {
413             t = root;
414             parse(new TabAndMaxColumnEnforcingReader(new InputStreamReader(is), root.nodeName)); 
415         }
416
417         /** parsing state: true iff we have already encountered the <xwt> open-tag */
418         boolean rootNodeHasBeenEncountered = false;
419
420         /** parsing state: true iff we have already encountered the <template> open-tag */
421         boolean templateNodeHasBeenEncountered = false;
422
423         /** parsing state: true iff we have already encountered the <static> open-tag */
424         boolean staticNodeHasBeenEncountered = false;
425
426         /** parsing state: true iff we have already encountered the <template> close-tag */
427         boolean templateNodeHasBeenFinished = false;
428
429         /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
430          *  that tag; otherwise, it is null. */
431         String nameOfHeaderNodeBeingProcessed = null;
432
433         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
434         Vec nodeStack = new Vec();
435
436         /** builds up the list of imports */
437         Vec importlist = new Vec();
438
439         /** builds up the list of preapplies */
440         Vec preapply = new Vec();
441
442         /** builds up the list of postapplies */
443         Vec postapply = new Vec();
444
445         /** the template we're currently working on */
446         Template t = null;
447
448         public void startElement(String name, String[] keys, Object[] vals, int line, int col) throws XML.SAXException {
449
450             if (templateNodeHasBeenFinished) {
451                 throw new XML.SAXException("no elements may appear after the <template> node");
452
453             } else if (!rootNodeHasBeenEncountered) {
454                 if (!"xwt".equals(name)) throw new XML.SAXException("root element was not <xwt>");
455                 if (keys.length != 0) throw new XML.SAXException("root element must not have attributes");
456                 rootNodeHasBeenEncountered = true;
457                 return;
458         
459             } else if (!templateNodeHasBeenEncountered) {
460                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SAXException("can't nest header nodes");
461                 nameOfHeaderNodeBeingProcessed = name;
462
463                 if (name.equals("import")) {
464                     if (keys.length != 1 || !keys[0].equals("name"))
465                         throw new XML.SAXException("<import> node must have exactly one attribute, which must be called 'name'");
466                     String importpackage = vals[0].toString();
467                     if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
468                     importlist.addElement(importpackage);
469                     return;
470
471                 } else if (name.equals("redirect")) {
472                     if (keys.length != 1 || !keys[0].equals("target"))
473                         throw new XML.SAXException("<redirect> node must have exactly one attribute, which must be called 'target'");
474                     if (t.redirect != null)
475                         throw new XML.SAXException("the <redirect> header element may not appear more than once");
476                     t.redirect = vals[0].toString();
477                     return;
478
479                 } else if (name.equals("preapply")) {
480                     if (keys.length != 1 || !keys[0].equals("name"))
481                         throw new XML.SAXException("<preapply> node must have exactly one attribute, which must be called 'name'");
482                     preapply.addElement(vals[0]);
483                     return;
484
485                 } else if (name.equals("postapply")) {
486                     if (keys.length != 1 || !keys[0].equals("name"))
487                         throw new XML.SAXException("<postapply> node must have exactly one attribute, which must be called 'name'");
488                     postapply.addElement(vals[0]);
489                     return;
490
491                 } else if (name.equals("static")) {
492                     if (staticNodeHasBeenEncountered)
493                         throw new XML.SAXException("the <static> header node may not appear more than once");
494                     if (keys.length > 0)
495                         throw new XML.SAXException("the <static> node may not have attributes");
496                     staticNodeHasBeenEncountered = true;
497                     return;
498
499                 } else if (name.equals("preserve")) {
500                     if (keys.length != 1 || !keys[0].equals("attributes"))
501                         throw new XML.SAXException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
502                     if (t.preserve != null)
503                         throw new XML.SAXException("<preserve> header element may not appear more than once");
504
505                     StringTokenizer tok = new StringTokenizer(vals[0].toString(), ",", false);
506                     t.preserve = new String[tok.countTokens()];
507                     for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
508                     return;
509
510                 } else if (name.equals("template")) {
511                     // finalize importlist/preapply/postapply, since they can't change from here on
512                     t.startLine = line;
513                     importlist.toArray(t.importlist = new String[importlist.size()]);
514                     if (preapply.size() > 0) preapply.copyInto(t.preapply = new String[preapply.size()]);
515                     if (postapply.size() > 0) postapply.copyInto(t.postapply = new String[postapply.size()]);
516                     importlist = preapply = postapply = null;
517                     templateNodeHasBeenEncountered = true;
518
519                 } else {
520                     throw new XML.SAXException("unrecognized header node \"" + name + "\"");
521
522                 }
523
524             } else {
525
526                 // push the last node we were in onto the stack
527                 nodeStack.addElement(t);
528
529                 // instantiate a new node, and set its nodeName/importlist/preapply
530                 Template t2 = new Template(t.nodeName + "." + t.childvect.size());
531                 t2.importlist = t.importlist;
532                 t2.startLine = line;
533                 if (!name.equals("box")) t2.preapply = new String[] { name };
534
535                 // make the new node the current node
536                 t = t2;
537
538             }
539
540             t.keys = keys;
541             t.vals = vals;
542
543             quickSortAttributes(0, t.keys.length - 1);
544
545             for(int i=0; i<t.keys.length; i++) {
546                 if (t.keys[i].equals("id")) {
547                     t.id = vals[i].toString().intern();
548                     t.keys[i] = null;
549                     continue;
550                 }
551
552                 t.keys[i] = t.keys[i].intern();
553
554                 String valString = vals[i].toString();
555                 
556                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
557                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
558                 else if (valString.equals("null")) t.vals[i] = null;
559                 else {
560                     boolean hasNonNumeral = false;
561                     boolean periodUsed = false;
562                     for(int j=0; j<valString.length(); j++)
563                         if (j == 0 && valString.charAt(j) == '-') {
564                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
565                             periodUsed = true;
566                         } else if (!Character.isDigit(valString.charAt(j))) {
567                             hasNonNumeral = true;
568                             break;
569                         }
570                     if (valString.length() > 0 && !hasNonNumeral) vals[i] = new Double(valString);
571                     else vals[i] = valString.intern();
572                 }
573
574                 // bump thisbox to the front of the pack
575                 if (t.keys[i].equals("thisbox")) {
576                     t.keys[i] = t.keys[0];
577                     t.keys[0] = "thisbox";
578                     Object o = t.vals[0];
579                     t.vals[0] = t.vals[i];
580                     t.vals[i] = o;
581                 }
582             }
583         }
584
585         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
586         private int partitionAttributes(int left, int right) {
587             int i, j, middle;
588             middle = (left + right) / 2;
589             String s = t.keys[right]; t.keys[right] = t.keys[middle]; t.keys[middle] = s;
590             Object o = t.vals[right]; t.vals[right] = t.vals[middle]; t.vals[middle] = o;
591             for (i = left - 1, j = right; ; ) {
592                 while (t.keys[++i].compareTo(t.keys[right]) < 0);
593                 while (j > left && t.keys[--j].compareTo(t.keys[right]) > 0);
594                 if (i >= j) break;
595                 s = t.keys[i]; t.keys[i] = t.keys[j]; t.keys[j] = s;
596                 o = t.vals[i]; t.vals[i] = t.vals[j]; t.vals[j] = o;
597             }
598             s = t.keys[right]; t.keys[right] = t.keys[i]; t.keys[i] = s;
599             o = t.vals[right]; t.vals[right] = t.vals[i]; t.vals[i] = o;
600             return i;
601         }
602         
603         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
604         private void quickSortAttributes(int left, int right) {
605             if (left >= right) return;
606             int p = partitionAttributes(left, right);
607             quickSortAttributes(left, p - 1);
608             quickSortAttributes(p + 1, right);
609         }
610         
611         public void endElement(String name, int line, int col) throws XML.SAXException {
612
613             boolean hasNonWhitespace = false;
614
615             int len = t == null || t.content == null ? 0 : t.content.length();
616             for(int i=0; t.content != null && i<len; i++)
617                 
618                 // ignore double-slash comment blocks
619                 if (t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '/') {
620                     while(t.content.charAt(i) != '\n' && i<len) i++;
621                     i--;
622
623                 // ignore /* .. */ comment blocks
624                 } else if (i<len - 1 && t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '*') {
625                     i += 2;
626                     while(i<len - 1 && !(t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/')) i++;
627                     if (i<len - 1 && t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/') i += 2;
628                     i--;
629
630                 // check for named functions
631                 } else if (i + 8 <= len && t.content.charAt(i) == 'f' && t.content.charAt(i+1) == 'u' &&
632                            t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'c' && t.content.charAt(i+4) == 't' &&
633                            t.content.charAt(i+5) == 'i' && t.content.charAt(i+6) == 'o' && t.content.charAt(i+7) == 'n') {
634                     int j = i + 8;
635                     while(j<len && Character.isWhitespace(t.content.charAt(j))) j++;
636                     if (j<len && t.content.charAt(j) != '(')
637                         throw new XML.SAXException("named functions are not permitted in XWT -- instead of \"function foo() { ... }\"," +
638                                         " use \"foo = function() { ... }\"");
639
640                 // replace " and " with " && "
641                 } else if (i + 5 < len && Character.isWhitespace(t.content.charAt(i)) &&
642                            t.content.charAt(i+1) == 'a' && t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'd' &&
643                            Character.isWhitespace(t.content.charAt(i + 4))) {
644                     t.content.setCharAt(i+1, '&');
645                     t.content.setCharAt(i+2, '&');
646                     t.content.setCharAt(i+3, ' ');
647                     hasNonWhitespace = true;
648
649                 // generic check for nonwhitespace
650                 } else if (!Character.isWhitespace(t.content.charAt(i))) {
651                     hasNonWhitespace = true;
652
653                 }
654             
655             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
656                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && hasNonWhitespace) t.staticscript = genscript(true);
657                 nameOfHeaderNodeBeingProcessed = null;
658
659             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
660
661                 // turn our childvect into a Template[]
662                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
663                 t.childvect = null;
664                 if (hasNonWhitespace) t.script = genscript(false);
665                 
666                 if (nodeStack.size() == 0) {
667                     // </template>
668                     templateNodeHasBeenFinished = true;
669
670                 } else {
671                     // add this template as a child of its parent
672                     Template oldt = t;
673                     t = (Template)nodeStack.lastElement();
674                     nodeStack.setSize(nodeStack.size() - 1);
675                     t.childvect.addElement(oldt);
676                 }
677
678             }
679         }
680
681         private Script genscript(boolean isstatic) {
682             Script thisscript = null;
683             Context cx = Context.enter();
684             cx.setOptimizationLevel(-1);
685
686             try {
687                 thisscript = cx.compileReader(null, new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start, null);
688             } catch (EcmaError ee) {
689                 if (Log.on) Log.log(this, ee.getMessage() + " at " + ee.getSourceName() + ":" + ee.getLineNumber());
690                 thisscript = null;
691             } catch (EvaluatorException ee) {
692                 if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
693                 thisscript = null;
694             } catch (IOException ioe) {
695                 if (Log.on) Log.log(this, "IOException while compiling script; this should never happen");
696                 if (Log.on) Log.log(this, ioe);
697                 thisscript = null;
698             }
699
700             t.content = null;
701             t.content_start = 0;
702             t.content_lines = 0;
703             return thisscript;
704         }
705
706         public void content(char[] ch, int start, int length, int line, int col) throws XML.SAXException {
707             if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
708                 int contentlines = 0;
709                 for(int i=start; i<start + length; i++) if (ch[i] == '\n') contentlines++;
710                 line -= contentlines;
711
712                 if (t.content == null) {
713                     t.content_start = line;
714                     t.content_lines = 0;
715                     t.content = new StringBuffer();
716                 }
717
718                 for(int i=t.content_start + t.content_lines; i<line; i++) {
719                     t.content.append('\n');
720                     t.content_lines++;
721                 }
722
723                 t.content.append(ch, start, length);
724                 t.content_lines += contentlines;
725
726             } else if (nameOfHeaderNodeBeingProcessed != null) {
727                 throw new XML.SAXException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
728
729             }
730
731         }
732
733     }
734
735     /** a filtering reader that watches for tabs and long lines */
736     private static class TabAndMaxColumnEnforcingReader extends FilterReader {
737         private int MAX_COLUMN = 150;
738         private int column = 0;
739         private int line = 1;
740         private boolean lastCharWasCR = false;
741         private String filename;
742         public TabAndMaxColumnEnforcingReader(Reader r, String filename) { super(r); this.filename = filename; }
743         public int read() {
744             if (Log.on) Log.log(this, this.getClass().getName() + ".read() not supported, this should never happen");
745             return -1;
746         }
747         public long skip(long numskip) {
748             if (Log.on) Log.log(this, this.getClass().getName() + ".skip() not supported; this should never happen");
749             return numskip;
750         }
751         public int read(char[] buf, int off, int len) throws IOException {
752             int ret = super.read(buf, off, len);
753             for(int i=off; i<off + ret; i++)
754                 if (buf[i] == '\t') {
755                     throw new TemplateException(filename + ":" + line + "," + column + ": tabs are not allowed in XWT files");
756                 } else if (buf[i] == '\r') {
757                     column = 0;
758                     line++;
759                     lastCharWasCR = true;
760                 } else if (buf[i] == '\n') {
761                     column = 0;
762                     if (!lastCharWasCR) line++;
763                 } else if (++column > MAX_COLUMN) {
764                     throw new TemplateException(filename + ":" + line + ": lines longer than " + MAX_COLUMN + " characters not allowed");
765                 } else {
766                     lastCharWasCR = false;
767                 }
768             return ret;
769         }
770     }
771
772     private static class TemplateException extends IOException {
773         TemplateException(String s) { super(s); }
774     }
775
776 }
777
778