2003/08/10 06:03:02
[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.xwt.js.*;
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 JS.CompiledFunction staticscript = null;
77
78     /** the script on this node */
79     private JS.CompiledFunction 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         return buildTemplate(is, nodeName, new TemplateHelper());
119     }
120
121     public static Template buildTemplate(InputStream is, String nodeName, TemplateHelper t) {
122         try {
123             return new Template(is, nodeName, t);
124         } catch (XML.SchemaException e) {
125             if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
126             if (Log.on) Log.log(Template.class, e.getMessage());
127             return null;
128         } catch (XML.XMLException e) {
129             if (Log.on) Log.log(Template.class, "error parsing template at " + nodeName + ":" + e.getLine() + "," + e.getCol());
130             if (Log.on) Log.log(Template.class, e.getMessage());
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, TemplateHelper th) throws XML.XMLException, IOException {
147         this(nodeName);
148         th.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, JS.Callable 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.put("$" + id, b);
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             Box newkid = new Box();
201             children[i].apply(newkid, pboxes, ptemplates, callback, numerator, denominator);
202             b.put(Integer.MAX_VALUE, newkid);
203             numerator += children[i].numUnits();
204         }
205
206         // whom to redirect to; doesn't take effect until after script runs
207         Box redir = null;
208         if (redirect != null && !"self".equals(redirect)) redir = (Box)b.get("$" + redirect);
209
210         if (script != null) try {
211             script.call(new JS.Array(), b);
212         } catch (JS.Exn e) {
213             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
214         }
215
216         for(int i=0; keys != null && i<keys.length; i++) {
217             try {
218                 if (keys[i] == null) { }
219                 else if (keys[i].equals("border") || keys[i].equals("image") &&
220                         !vals[i].toString().startsWith("http://") && !vals[i].toString().startsWith("https://")) {
221                     String s = Resources.resolve(vals[i].toString() + ".png", importlist);
222                     if (s != null) b.put(keys[i], s.substring(0, s.length() - 4));
223                     else if (Log.on) Log.log(this, "unable to resolve image " + vals[i].toString() + " referenced in attributes of " + nodeName); 
224                 }
225                 else b.put(keys[i], vals[i]);
226             } catch(JS.Exn e) {
227                 if(Log.on) Log.log(this,"WARNING: uncaught ecmascript exception while putting attr \"" + keys[i] + 
228                     "\" of " + nodeName + " : " + e.getMessage());
229             }
230         }
231
232         if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
233
234         for(int i=0; _postapply != null && i<_postapply.length; i++)
235             if (_postapply[i] != null) {
236                 _postapply[i].apply(b, null, null, callback, numerator, denominator);
237                 numerator += _postapply[i].numUnits();
238             }
239
240         pboxes.setSize(numids);
241         ptemplates.setSize(numids);
242
243         numerator = original_numerator + numUnits();
244
245         if (callback != null)
246             try {
247                 JS.Array args = new JS.Array();
248                 args.addElement(new Double(numerator));
249                 args.addElement(new Double(denominator));
250                 callback.call(args);
251             } catch (JS.Exn e) {
252                 if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
253             }
254
255         if (Thread.currentThread() instanceof ThreadMessage) try {
256             XWT.sleep(0);
257         } catch (JS.Exn e) {
258             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
259         }
260     }
261
262
263     // Theming Logic ////////////////////////////////////////////////////////////
264
265     /** helper method to recursively gather up the list of keys to be preserved */
266     private void gatherPreserves(Vec v) {
267         for(int i=0; preserve != null && i<preserve.length; i++) v.addElement(preserve[i]);
268         for(int i=0; _preapply != null && i<_preapply.length; i++) if (_preapply[i] != null) _preapply[i].gatherPreserves(v);
269         for(int i=0; _postapply != null && i<_postapply.length; i++) if (_postapply[i] != null) _postapply[i].gatherPreserves(v);
270     }
271
272     /** adds a theme mapping, retemplatizing as needed */
273     public static void retheme(JS.Callable callback) {
274         /*
275         XWF.flushXWFs();
276
277         // clear changed marker and relink
278         Template[] t = new Template[cache.size()];
279         Enumeration e = cache.elements();
280         for(int i=0; e.hasMoreElements(); i++) t[i] = (Template)e.nextElement();
281         for(int i=0; i<t.length; i++) {
282             t[i].changed = false;
283             t[i].numunits = -1;
284             t[i].link(true);
285         }
286
287         for(int i=0; i<Surface.allSurfaces.size(); i++) {
288             Box b = ((Surface)Surface.allSurfaces.elementAt(i)).root;
289             if (b != null) reapply(b);
290         }
291
292         if (callback != null)
293             try {
294                 JS.Array args = new JS.Array();
295                 args.addElement(new Double(1.0));
296                 args.addElement(new Double(1.0));
297                 callback.call(args);
298             } catch (JS.Exn ex) {
299                 if (Log.on) Log.log(Template.class, "WARNING: uncaught ecmascript exception: " + ex.getMessage());
300             }
301         */
302     }
303
304     /** template reapplication procedure */
305     private static void reapply(Box b) {
306
307         Log.log(Template.class, "Template.reapply() not implemented");
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
365     /** runs statics, resolves string references to other templates into actual Template instance references, and sets <tt>change</tt> as needed */
366     void link() { link(false); }
367
368     /** same as link(), except that with a true value, it will force a re-link */
369     private void link(boolean force) {
370
371         if (staticscript != null) try { 
372             JS.Scope s = Static.createStatic(nodeName, false);
373             if (staticscript != null) {
374                 JS.CompiledFunction temp = staticscript;
375                 staticscript = null;
376
377                 // we layer a transparent scope over the Static so that we can catch requests for the xwt object
378                 // yet not screw up paths that include a package called xwt (ie xwt.static.org.xwt.foo)
379                 JS.Scope varScope = new JS.Scope(s) {
380                         public boolean isTransparent() { return true; }
381                         public Object get(Object key) {
382                             if ("xwt".equals(key)) return XWT.singleton; else return super.get(key);
383                         } };
384
385                 temp.call(new JS.Array(), varScope);
386             }
387         } catch (JS.Exn e) {
388             if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
389         }
390
391         if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
392         
393         if (preapply != null) {
394             if (_preapply == null) _preapply = new Template[preapply.length];
395             for(int i=0; i<_preapply.length; i++) {
396                 Template t = getTemplate(preapply[i], importlist);
397                 if (t != _preapply[i]) changed = true;
398                 _preapply[i] = t;
399             }
400         }
401         if (postapply != null) {
402             if (_postapply == null) _postapply = new Template[postapply.length];
403             for(int i=0; i<_postapply.length; i++) {
404                 Template t = getTemplate(postapply[i], importlist);
405                 if (t != _postapply[i]) changed = true;
406                 _postapply[i] = t;
407             }
408         }
409
410         for(int i=0; children != null && i<children.length; i++) children[i].link(force);
411     }
412
413
414     // XML Parsing /////////////////////////////////////////////////////////////////
415
416     /** handles XML parsing; builds a Template tree as it goes */
417     static final class TemplateHelper extends XML {
418
419         TemplateHelper() { }
420
421         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
422         void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
423             rootNodeHasBeenEncountered = false;
424             templateNodeHasBeenEncountered = false;
425             staticNodeHasBeenEncountered = false;
426             templateNodeHasBeenFinished = false;
427             nameOfHeaderNodeBeingProcessed = null;
428
429             nodeStack.setSize(0);
430             importlist.setSize(0);
431             preapply.setSize(0);
432             postapply.setSize(0);
433
434             importlist.fromArray(defaultImportList);
435
436             t = root;
437             parse(new InputStreamReader(is)); 
438         }
439
440         /** parsing state: true iff we have already encountered the <xwt> open-tag */
441         boolean rootNodeHasBeenEncountered = false;
442
443         /** parsing state: true iff we have already encountered the <template> open-tag */
444         boolean templateNodeHasBeenEncountered = false;
445
446         /** parsing state: true iff we have already encountered the <static> open-tag */
447         boolean staticNodeHasBeenEncountered = false;
448
449         /** parsing state: true iff we have already encountered the <template> close-tag */
450         boolean templateNodeHasBeenFinished = false;
451
452         /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
453          *  that tag; otherwise, it is null. */
454         String nameOfHeaderNodeBeingProcessed = null;
455
456         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
457         Vec nodeStack = new Vec();
458
459         /** builds up the list of imports */
460         Vec importlist = new Vec();
461
462         /** builds up the list of preapplies */
463         Vec preapply = new Vec();
464
465         /** builds up the list of postapplies */
466         Vec postapply = new Vec();
467
468         /** the template we're currently working on */
469         Template t = null;
470
471         public void startElement(XML.Element c) throws XML.SchemaException {
472             if (templateNodeHasBeenFinished) {
473                 throw new XML.SchemaException("no elements may appear after the <template> node");
474
475             } else if (!rootNodeHasBeenEncountered) {
476                 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
477                 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
478                 rootNodeHasBeenEncountered = true;
479                 return;
480         
481             } else if (!templateNodeHasBeenEncountered) {
482                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
483                 nameOfHeaderNodeBeingProcessed = c.localName;
484
485                 if (c.localName.equals("import")) {
486                     if (c.len != 1 || !c.keys[0].equals("name"))
487                         throw new XML.SchemaException("<import> node must have exactly one attribute, which must be called 'name'");
488                     String importpackage = c.vals[0].toString();
489                     if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
490                     importlist.addElement(importpackage);
491                     return;
492
493                 } else if (c.localName.equals("redirect")) {
494                     if (c.len != 1 || !c.keys[0].equals("target"))
495                         throw new XML.SchemaException("<redirect> node must have exactly one attribute, which must be called 'target'");
496                     if (t.redirect != null)
497                         throw new XML.SchemaException("the <redirect> header element may not appear more than once");
498                     t.redirect = c.vals[0].toString();
499                     if(t.redirect.equals("null")) t.redirect = null;
500                     return;
501
502                 } else if (c.localName.equals("preapply")) {
503                     if (c.len != 1 || !c.keys[0].equals("name"))
504                         throw new XML.SchemaException("<preapply> node must have exactly one attribute, which must be called 'name'");
505                     preapply.addElement(c.vals[0]);
506                     return;
507
508                 } else if (c.localName.equals("postapply")) {
509                     if (c.len != 1 || !c.keys[0].equals("name"))
510                         throw new XML.SchemaException("<postapply> node must have exactly one attribute, which must be called 'name'");
511                     postapply.addElement(c.vals[0]);
512                     return;
513
514                 } else if (c.localName.equals("static")) {
515                     if (staticNodeHasBeenEncountered)
516                         throw new XML.SchemaException("the <static> header node may not appear more than once");
517                     if (c.len > 0)
518                         throw new XML.SchemaException("the <static> node may not have attributes");
519                     staticNodeHasBeenEncountered = true;
520                     return;
521
522                 } else if (c.localName.equals("preserve")) {
523                     if (c.len != 1 || !c.keys[0].equals("attributes"))
524                         throw new XML.SchemaException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
525                     if (t.preserve != null)
526                         throw new XML.SchemaException("<preserve> header element may not appear more than once");
527
528                     StringTokenizer tok = new StringTokenizer(c.vals[0].toString(), ",", false);
529                     t.preserve = new String[tok.countTokens()];
530                     for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
531                     return;
532
533                 } else if (c.localName.equals("template")) {
534                     // finalize importlist/preapply/postapply, since they can't change from here on
535                     t.startLine = getLine();
536                     importlist.toArray(t.importlist = new String[importlist.size()]);
537                     if (preapply.size() > 0) preapply.copyInto(t.preapply = new String[preapply.size()]);
538                     if (postapply.size() > 0) postapply.copyInto(t.postapply = new String[postapply.size()]);
539                     importlist.setSize(0); preapply.setSize(0); postapply.setSize(0);
540                     templateNodeHasBeenEncountered = true;
541
542                 } else {
543                     throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
544
545                 }
546
547             } else {
548
549                 // push the last node we were in onto the stack
550                 nodeStack.addElement(t);
551
552                 // instantiate a new node, and set its nodeName/importlist/preapply
553                 Template t2 = new Template(t.nodeName + "." + t.childvect.size());
554                 t2.importlist = t.importlist;
555                 t2.startLine = getLine();
556                 if (!c.localName.equals("box")) t2.preapply = new String[] { c.localName };
557
558                 // make the new node the current node
559                 t = t2;
560
561             }
562
563             // TODO: Sort contents straight from one array to another
564             t.keys = new String[c.len];
565             t.vals = new Object[c.len];
566             System.arraycopy(c.keys, 0, t.keys, 0, c.len);
567             System.arraycopy(c.vals, 0, t.vals, 0, c.len);
568             quickSortAttributes(0, t.keys.length - 1);
569
570             for(int i=0; i<t.keys.length; i++) {
571                 if (t.keys[i].equals("id")) {
572                     t.id = t.vals[i].toString().intern();
573                     t.keys[i] = null;
574                     continue;
575                 }
576
577                 t.keys[i] = t.keys[i].intern();
578
579                 String valString = t.vals[i].toString();
580                 
581                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
582                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
583                 else if (valString.equals("null")) t.vals[i] = null;
584                 else {
585                     boolean hasNonNumeral = false;
586                     boolean periodUsed = false;
587                     for(int j=0; j<valString.length(); j++)
588                         if (j == 0 && valString.charAt(j) == '-') {
589                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
590                             periodUsed = true;
591                         } else if (!Character.isDigit(valString.charAt(j))) {
592                             hasNonNumeral = true;
593                             break;
594                         }
595                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
596                     else t.vals[i] = valString.intern();
597                 }
598
599                 // bump thisbox to the front of the pack
600                 if (t.keys[i].equals("thisbox")) {
601                     t.keys[i] = t.keys[0];
602                     t.keys[0] = "thisbox";
603                     Object o = t.vals[0];
604                     t.vals[0] = t.vals[i];
605                     t.vals[i] = o;
606                 }
607             }
608         }
609
610         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
611         private int partitionAttributes(int left, int right) {
612             int i, j, middle;
613             middle = (left + right) / 2;
614             String s = t.keys[right]; t.keys[right] = t.keys[middle]; t.keys[middle] = s;
615             Object o = t.vals[right]; t.vals[right] = t.vals[middle]; t.vals[middle] = o;
616             for (i = left - 1, j = right; ; ) {
617                 while (t.keys[++i].compareTo(t.keys[right]) < 0);
618                 while (j > left && t.keys[--j].compareTo(t.keys[right]) > 0);
619                 if (i >= j) break;
620                 s = t.keys[i]; t.keys[i] = t.keys[j]; t.keys[j] = s;
621                 o = t.vals[i]; t.vals[i] = t.vals[j]; t.vals[j] = o;
622             }
623             s = t.keys[right]; t.keys[right] = t.keys[i]; t.keys[i] = s;
624             o = t.vals[right]; t.vals[right] = t.vals[i]; t.vals[i] = o;
625             return i;
626         }
627
628         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
629         private void quickSortAttributes(int left, int right) {
630             if (left >= right) return;
631             int p = partitionAttributes(left, right);
632             quickSortAttributes(left, p - 1);
633             quickSortAttributes(p + 1, right);
634         }
635
636         public void endElement(XML.Element c) throws XML.SchemaException {
637             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
638                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
639                 nameOfHeaderNodeBeingProcessed = null;
640
641             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
642                 // turn our childvect into a Template[]
643                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
644                 t.childvect = null;
645                 if (t.content != null) t.script = genscript(false);
646                 
647                 if (nodeStack.size() == 0) {
648                     // </template>
649                     templateNodeHasBeenFinished = true;
650
651                 } else {
652                     // add this template as a child of its parent
653                     Template oldt = t;
654                     t = (Template)nodeStack.lastElement();
655                     nodeStack.setSize(nodeStack.size() - 1);
656                     t.childvect.addElement(oldt);
657                 }
658
659             }
660         }
661
662         private JS.CompiledFunction genscript(boolean isstatic) {
663             JS.CompiledFunction thisscript = null;
664             try {
665                 thisscript = JS.parse(t.nodeName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
666             } catch (JS.Exn ee) {
667                 if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
668                 thisscript = null;
669             } catch (IOException ioe) {
670                 if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
671                 thisscript = null;
672             }
673
674             t.content = null;
675             t.content_start = 0;
676             t.content_lines = 0;
677             return thisscript;
678         }
679
680         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
681             // invoke the no-tab crusade
682             for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
683                 t.nodeName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
684
685             if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
686                 if (t.content == null) {
687                     t.content_start = getLine();
688                     t.content_lines = 0;
689                     t.content = new StringBuffer();
690                 }
691
692                 t.content.append(ch, start, length);
693                 t.content_lines++;
694
695             } else if (nameOfHeaderNodeBeingProcessed != null) {
696                 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
697             }
698         }
699
700         public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
701         }
702     }
703
704 }
705
706