2003/04/28 08:24:18
[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         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, 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     static final class TemplateHelper extends XML {
414
415         TemplateHelper() { }
416
417         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
418         void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
419             rootNodeHasBeenEncountered = false;
420             templateNodeHasBeenEncountered = false;
421             staticNodeHasBeenEncountered = false;
422             templateNodeHasBeenFinished = false;
423             nameOfHeaderNodeBeingProcessed = null;
424
425             nodeStack.setSize(0);
426             importlist.setSize(0);
427             preapply.setSize(0);
428             postapply.setSize(0);
429
430             importlist.fromArray(defaultImportList);
431
432             t = root;
433             parse(new InputStreamReader(is)); 
434         }
435
436         /** parsing state: true iff we have already encountered the <xwt> open-tag */
437         boolean rootNodeHasBeenEncountered = false;
438
439         /** parsing state: true iff we have already encountered the <template> open-tag */
440         boolean templateNodeHasBeenEncountered = false;
441
442         /** parsing state: true iff we have already encountered the <static> open-tag */
443         boolean staticNodeHasBeenEncountered = false;
444
445         /** parsing state: true iff we have already encountered the <template> close-tag */
446         boolean templateNodeHasBeenFinished = false;
447
448         /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
449          *  that tag; otherwise, it is null. */
450         String nameOfHeaderNodeBeingProcessed = null;
451
452         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
453         Vec nodeStack = new Vec();
454
455         /** builds up the list of imports */
456         Vec importlist = new Vec();
457
458         /** builds up the list of preapplies */
459         Vec preapply = new Vec();
460
461         /** builds up the list of postapplies */
462         Vec postapply = new Vec();
463
464         /** the template we're currently working on */
465         Template t = null;
466
467         public void startElement(XML.Element c) throws XML.SchemaException {
468             if (templateNodeHasBeenFinished) {
469                 throw new XML.SchemaException("no elements may appear after the <template> node");
470
471             } else if (!rootNodeHasBeenEncountered) {
472                 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
473                 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
474                 rootNodeHasBeenEncountered = true;
475                 return;
476         
477             } else if (!templateNodeHasBeenEncountered) {
478                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
479                 nameOfHeaderNodeBeingProcessed = c.localName;
480
481                 if (c.localName.equals("import")) {
482                     if (c.len != 1 || !c.keys[0].equals("name"))
483                         throw new XML.SchemaException("<import> node must have exactly one attribute, which must be called 'name'");
484                     String importpackage = c.vals[0].toString();
485                     if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
486                     importlist.addElement(importpackage);
487                     return;
488
489                 } else if (c.localName.equals("redirect")) {
490                     if (c.len != 1 || !c.keys[0].equals("target"))
491                         throw new XML.SchemaException("<redirect> node must have exactly one attribute, which must be called 'target'");
492                     if (t.redirect != null)
493                         throw new XML.SchemaException("the <redirect> header element may not appear more than once");
494                     t.redirect = c.vals[0].toString();
495                     return;
496
497                 } else if (c.localName.equals("preapply")) {
498                     if (c.len != 1 || !c.keys[0].equals("name"))
499                         throw new XML.SchemaException("<preapply> node must have exactly one attribute, which must be called 'name'");
500                     preapply.addElement(c.vals[0]);
501                     return;
502
503                 } else if (c.localName.equals("postapply")) {
504                     if (c.len != 1 || !c.keys[0].equals("name"))
505                         throw new XML.SchemaException("<postapply> node must have exactly one attribute, which must be called 'name'");
506                     postapply.addElement(c.vals[0]);
507                     return;
508
509                 } else if (c.localName.equals("static")) {
510                     if (staticNodeHasBeenEncountered)
511                         throw new XML.SchemaException("the <static> header node may not appear more than once");
512                     if (c.len > 0)
513                         throw new XML.SchemaException("the <static> node may not have attributes");
514                     staticNodeHasBeenEncountered = true;
515                     return;
516
517                 } else if (c.localName.equals("preserve")) {
518                     if (c.len != 1 || !c.keys[0].equals("attributes"))
519                         throw new XML.SchemaException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
520                     if (t.preserve != null)
521                         throw new XML.SchemaException("<preserve> header element may not appear more than once");
522
523                     StringTokenizer tok = new StringTokenizer(c.vals[0].toString(), ",", false);
524                     t.preserve = new String[tok.countTokens()];
525                     for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
526                     return;
527
528                 } else if (c.localName.equals("template")) {
529                     // finalize importlist/preapply/postapply, since they can't change from here on
530                     t.startLine = getLine();
531                     importlist.toArray(t.importlist = new String[importlist.size()]);
532                     if (preapply.size() > 0) preapply.copyInto(t.preapply = new String[preapply.size()]);
533                     if (postapply.size() > 0) postapply.copyInto(t.postapply = new String[postapply.size()]);
534                     importlist.setSize(0); preapply.setSize(0); postapply.setSize(0);
535                     templateNodeHasBeenEncountered = true;
536
537                 } else {
538                     throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
539
540                 }
541
542             } else {
543
544                 // push the last node we were in onto the stack
545                 nodeStack.addElement(t);
546
547                 // instantiate a new node, and set its nodeName/importlist/preapply
548                 Template t2 = new Template(t.nodeName + "." + t.childvect.size());
549                 t2.importlist = t.importlist;
550                 t2.startLine = getLine();
551                 if (!c.localName.equals("box")) t2.preapply = new String[] { c.localName };
552
553                 // make the new node the current node
554                 t = t2;
555
556             }
557
558             // TODO: Sort contents straight from one array to another
559             t.keys = new String[c.len];
560             t.vals = new Object[c.len];
561             System.arraycopy(c.keys, 0, t.keys, 0, c.len);
562             System.arraycopy(c.vals, 0, t.vals, 0, c.len);
563             quickSortAttributes(0, t.keys.length - 1);
564
565             for(int i=0; i<t.keys.length; i++) {
566                 if (t.keys[i].equals("id")) {
567                     t.id = t.vals[i].toString().intern();
568                     t.keys[i] = null;
569                     continue;
570                 }
571
572                 t.keys[i] = t.keys[i].intern();
573
574                 String valString = t.vals[i].toString();
575                 
576                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
577                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
578                 else if (valString.equals("null")) t.vals[i] = null;
579                 else {
580                     boolean hasNonNumeral = false;
581                     boolean periodUsed = false;
582                     for(int j=0; j<valString.length(); j++)
583                         if (j == 0 && valString.charAt(j) == '-') {
584                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
585                             periodUsed = true;
586                         } else if (!Character.isDigit(valString.charAt(j))) {
587                             hasNonNumeral = true;
588                             break;
589                         }
590                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
591                     else t.vals[i] = valString.intern();
592                 }
593
594                 // bump thisbox to the front of the pack
595                 if (t.keys[i].equals("thisbox")) {
596                     t.keys[i] = t.keys[0];
597                     t.keys[0] = "thisbox";
598                     Object o = t.vals[0];
599                     t.vals[0] = t.vals[i];
600                     t.vals[i] = o;
601                 }
602             }
603         }
604
605         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
606         private int partitionAttributes(int left, int right) {
607             int i, j, middle;
608             middle = (left + right) / 2;
609             String s = t.keys[right]; t.keys[right] = t.keys[middle]; t.keys[middle] = s;
610             Object o = t.vals[right]; t.vals[right] = t.vals[middle]; t.vals[middle] = o;
611             for (i = left - 1, j = right; ; ) {
612                 while (t.keys[++i].compareTo(t.keys[right]) < 0);
613                 while (j > left && t.keys[--j].compareTo(t.keys[right]) > 0);
614                 if (i >= j) break;
615                 s = t.keys[i]; t.keys[i] = t.keys[j]; t.keys[j] = s;
616                 o = t.vals[i]; t.vals[i] = t.vals[j]; t.vals[j] = o;
617             }
618             s = t.keys[right]; t.keys[right] = t.keys[i]; t.keys[i] = s;
619             o = t.vals[right]; t.vals[right] = t.vals[i]; t.vals[i] = o;
620             return i;
621         }
622
623         /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
624         private void quickSortAttributes(int left, int right) {
625             if (left >= right) return;
626             int p = partitionAttributes(left, right);
627             quickSortAttributes(left, p - 1);
628             quickSortAttributes(p + 1, right);
629         }
630
631         public void endElement(XML.Element c) throws XML.SchemaException {
632             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
633                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
634                 nameOfHeaderNodeBeingProcessed = null;
635
636             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
637                 // turn our childvect into a Template[]
638                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
639                 t.childvect = null;
640                 if (t.content != null) t.script = genscript(false);
641                 
642                 if (nodeStack.size() == 0) {
643                     // </template>
644                     templateNodeHasBeenFinished = true;
645
646                 } else {
647                     // add this template as a child of its parent
648                     Template oldt = t;
649                     t = (Template)nodeStack.lastElement();
650                     nodeStack.setSize(nodeStack.size() - 1);
651                     t.childvect.addElement(oldt);
652                 }
653
654             }
655         }
656
657         private Script genscript(boolean isstatic) {
658             Script thisscript = null;
659             Context cx = Context.enter();
660             cx.setOptimizationLevel(-1);
661
662             try {
663                 thisscript = cx.compileReader(null, new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start, null);
664             } catch (EcmaError ee) {
665                 if (Log.on) Log.log(this, ee.getMessage() + " at " + ee.getSourceName() + ":" + ee.getLineNumber());
666                 thisscript = null;
667             } catch (EvaluatorException ee) {
668                 if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
669                 thisscript = null;
670             } catch (IOException ioe) {
671                 if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
672                 thisscript = null;
673             }
674
675             t.content = null;
676             t.content_start = 0;
677             t.content_lines = 0;
678             return thisscript;
679         }
680
681         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
682             // invoke the no-tab crusade
683             for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
684                 t.nodeName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
685
686             if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
687                 if (t.content == null) {
688                     t.content_start = getLine();
689                     t.content_lines = 0;
690                     t.content = new StringBuffer();
691                 }
692
693                 t.content.append(ch, start, length);
694                 t.content_lines++;
695
696             } else if (nameOfHeaderNodeBeingProcessed != null) {
697                 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
698             }
699         }
700
701         public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
702         }
703     }
704
705 }
706
707