2003/09/24 07:33:32
[org.ibex.core.git] / src / org / xwt / Template.java
index e2eb037..95846c1 100644 (file)
@@ -1,21 +1,16 @@
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+// Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
 package org.xwt;
 
 import java.io.*;
 import java.util.zip.*;
 import java.util.*;
 import java.lang.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
 import org.xwt.util.*;
 
 /**
  *  Encapsulates a template node (the <template/> element of a
- *  .xwt file, or any child element thereof). Each instance of
- *  Template has a <tt>nodeName</tt> -- this is the resource name of
- *  the file that the template node occurs in, concatenated with the
- *  path from the root element to this node, each step of which is in
- *  the form .n for some integer n. Static nodes use the string "._"
- *  as a path.
+ *  .xwt file, or any child element thereof).
  *
  *  Note that the Template instance corresponding to the
  *  &lt;template/&gt; node carries all the header information -- hence
@@ -26,27 +21,23 @@ import org.xwt.util.*;
  *  See the XWT reference for information on the order in which
  *  templates are applied, attributes are put, and scripts are run.
  */
+
+// FIXME imports
 public class Template {
 
     // Instance Members ///////////////////////////////////////////////////////
 
-    /** this instance's nodeName */
-    String nodeName;
+    /** the id of this box */
+    String id = null;
 
     /** the id of the redirect target; only meaningful on a root node */
     String redirect = null;
 
     /** templates that should be preapplied (in the order of application); only meaningful on a root node */
-    private String[] preapply;
-
-    /** 'linked' form of preapply -- the String references have been resolved into instance references */
-    private Template[] _preapply = null;
+    private Template[] preapply;
 
     /** templates that should be postapplied (in the order of application); only meaningful on a root node */
-    private String[] postapply;
-
-    /** 'linked' form of postapply -- the String references have been resolved into instance references */
-    private Template[] _postapply = null;
+    private Template[] postapply;
 
     /** keys to be "put" to instances of this template; elements correspond to those of vals */
     private String[] keys;
@@ -54,29 +45,26 @@ public class Template {
     /** values to be "put" to instances of this template; elements correspond to those of keys */
     private Object[] vals;
 
-    /** array of strings representing the importlist for this template */
-    private String[] importlist;
-
     /** child template objects */
     private Template[] children;
 
-    /** an array of the names of properties to be preserved when retheming; only meaningful on a root node */
-    private String[] preserve = null;
-    
-    /** the <tt>id</tt> attribute on this node */
-    private String id = "";
-
     /** see numUnits(); -1 means that this value has not yet been computed */
     private int numunits = -1;
 
-    /** true iff the resolution of this template's preapply/postapply sets changed as a result of the most recent call to retheme() */
-    private boolean changed = false;
+    /** the scope in which the static block is executed */
+    private JS.Scope staticScope = null;
 
     /** the script on the static node of this template, null if it has already been executed */
-    private Script staticscript = null;
+    private JS.CompiledFunction staticscript = null;
 
     /** the script on this node */
-    private Script script = null;
+    private JS.CompiledFunction script = null;
+
+    /** the filename this node came from; used only for debugging */
+    private String fileName = "unknown";
+
+
+    // Only used during parsing /////////////////////////////////////////////////////////////////
 
     /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
     private Vec childvect = new Vec();
@@ -90,45 +78,30 @@ public class Template {
     /** number of lines in <tt>content</tt> */
     private int content_lines = 0;
 
+    /** the line number that this element starts on */
+    private int startLine = -1;
 
-    // Static data/methods ///////////////////////////////////////////////////////////////////
-
-    /** a template cache so that only one Template object is created for each xwt */
-    private static Hashtable cache = new Hashtable(1000);
-
-    /** The default importlist; in future revisions this will contain "xwt.*" */
-    public static final String[] defaultImportList = new String[] { };
 
-    /** returns the appropriate template, resolving and theming as needed */
-    public static Template getTemplate(String name, String[] importlist) {
-        String resolved = Resources.resolve(name + ".xwt", importlist);
-        Template t = resolved == null ? null : (Template)cache.get(resolved.substring(0, resolved.length() - 4));
-        if (t != null) return t;
-        if (resolved == null) return null;
+    // Static data/methods ///////////////////////////////////////////////////////////////////
 
-        // note that Templates in xwar's are instantiated as read in via loadStream() --
-        // the following code only runs when XWT is reading templates from a filesystem.
-        ByteArrayInputStream bais = new ByteArrayInputStream(Resources.getResource(resolved));
-        return buildTemplate(bais, resolved.substring(0, resolved.length() - 4));
-    }
+    private Template(String fileName) { this.fileName = fileName; }
 
-    public static Template buildTemplate(InputStream is, String nodeName) {
+    public static Template getTemplate(Res r) {
         try {
-            return new Template(is, nodeName);
-        } catch (XML.SAXParseException e) {
-            if (Log.on) Log.log(Template.class, "error parsing template at " + nodeName + ":" + e.getLineNumber() + "," + e.getColumnNumber());
-            if (Log.on) Log.log(Template.class, e);
+            if (r.t != null) return r.t;
+            r.t = new Template(r.getDescriptiveName());
+            new TemplateHelper().parseit(r.getInputStream(), r.t);
+            return r.t;
+        } catch (XML.SchemaException e) {
+            if (Log.on) Log.log(Template.class, "error parsing template " + r.t.fileName);
+            if (Log.on) Log.log(Template.class, e.getMessage());
             return null;
-        } catch (XML.SAXException e) {
-            if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
-            if (Log.on) Log.log(Template.class, e);
-            return null;
-        } catch (TemplateException te) {
-            if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
-            if (Log.on) Log.log(Template.class, te);
+        } catch (XML.XMLException e) {
+            if (Log.on) Log.log(Template.class, "error parsing template at " + r.t.fileName + ":" + e.getLine() + "," + e.getCol());
+            if (Log.on) Log.log(Template.class, e.getMessage());
             return null;
         } catch (IOException e) {
-            if (Log.on) Log.log(Template.class, "IOException while parsing template " + nodeName + " -- this should never happen");
+            if (Log.on) Log.log(Template.class, "IOException while parsing template " + r.t.fileName + " -- this should never happen");
             if (Log.on) Log.log(Template.class, e);
             return null;
         }
@@ -137,251 +110,100 @@ public class Template {
 
     // Methods to apply templates ////////////////////////////////////////////////////////
 
-    private Template() { } 
-    private Template(InputStream is, String nodeName) throws XML.SAXException, IOException {
-        this.nodeName = nodeName;
-        cache.put(nodeName, this);
-        new TemplateHelper().parseit(is, this);
-    }
-
-    /** calculates, caches, and returns an integer approximation of how long it will take to apply this template, including pre/post and children */
+    /** calculates, caches, and returns an integer approximation of how long it will take to apply this template,
+     *  including pre/post and children */
     int numUnits() {
-        link();
         if (numunits != -1) return numunits;
         numunits = 1;
-        for(int i=0; _preapply != null && i<_preapply.length; i++) if (_preapply[i] != null) numunits += _preapply[i].numUnits();
-        for(int i=0; _postapply != null && i<_postapply.length; i++) if (_postapply[i] != null) numunits += _postapply[i].numUnits();
+        for(int i=0; preapply != null && i<preapply.length; i++) numunits += preapply[i].numUnits();
+        for(int i=0; postapply != null && i<postapply.length; i++) numunits += postapply[i].numUnits();
         if (script != null) numunits += 10;
         numunits += keys == null ? 0 : keys.length;
         for(int i=0; children != null && i<children.length; i++) numunits += children[i].numUnits();
         return numunits;
     }
+
+    /** called before this template is applied or its static object can be externally referenced */
+    JS.Scope getStatic() {
+        if (staticScope == null) staticScope = new JS.Scope(null);
+        if (staticscript == null) return staticScope;
+        JS.CompiledFunction temp = staticscript;
+        staticscript = null;
+        temp.call(new JS.Array(), staticScope);
+        return staticScope;
+    }
     
     /** Applies the template to Box b
      *  @param pboxes a vector of all box parents on which to put $-references
-     *  @param ptemplates a vector of the nodeNames to recieve private references on the pboxes
+     *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
      */
-    void apply(Box b, Vec pboxes, Vec ptemplates) {
-
-        if (pboxes == null) {
-            pboxes = new Vec();
-            ptemplates = new Vec();
-        }
+    // FIXME: $-vars not dealt with
+    void apply(Box b, JS.Callable callback, int numerator, int denominator, Res resourceRoot) {
 
-        if (id != null && !id.equals(""))
-            for(int i=0; i<pboxes.size(); i++) {
-                Box parent = (Box)pboxes.elementAt(i);
-                String parentNodeName = (String)ptemplates.elementAt(i);
-                parent.putPrivately("$" + id, b, parentNodeName);
-            }
+        getStatic();
+        int original_numerator = numerator;
 
-        if (script != null || (redirect != null && !"self".equals(redirect))) {
-            pboxes.addElement(b);
-            ptemplates.addElement(nodeName);
+        for(int i=0; preapply != null && i<preapply.length; i++) {
+            preapply[i].apply(b, callback, numerator, denominator, resourceRoot);
+            numerator += preapply[i].numUnits();
         }
 
-        int numids = pboxes.size();
-        
-        link();
-
-        for(int i=0; _preapply != null && i<_preapply.length; i++)
-            if (_preapply[i] != null) _preapply[i].apply(b, null, null);
-
-        for (int i=0; children != null && i<children.length; i++)
-            b.put(Integer.MAX_VALUE, null, new Box(children[i], pboxes, ptemplates));
-
-        // whom to redirect to; doesn't take effect until after script runs
-        Box redir = null;
-        if (redirect != null && !"self".equals(redirect))
-            redir = (Box)b.getPrivately("$" + redirect, nodeName);
-
-        if (script != null) try {
-            Context cx = Context.enter();
-            script.exec(cx, b);
-        } catch (EcmaError e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
-            if (Log.on) Log.log(this, "         thrown while instantiating " + nodeName + " at " + e.getSourceName() + ":" + e.getLineNumber());
-        } catch (JavaScriptException e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
-            if (Log.on) Log.log(this, "         thrown while instantiating " + nodeName + " at " + e.sourceFile + ":" + e.line);
+        for (int i=0; children != null && i<children.length; i++) {
+            Box kid = new Box();
+            children[i].apply(kid, callback, numerator, denominator, resourceRoot);
+            numerator += children[i].numUnits();
+            b.put(b.numChildren(), kid);
         }
 
-        for(int i=0; keys != null && i<keys.length; i++)
-            if (keys[i] == null) { }
-            else if (keys[i].equals("border") || keys[i].equals("image")) {
-                if (vals[i].startsWith("http://") || vals[i].startsWith("https://")) {
-                    b.put(keys[i], null, s.substring(0, s.length() - 4));
-                } else {
-                    String s = Resources.resolve(vals[i].toString() + ".png", importlist);
-                    if (s != null) b.put(keys[i], null, s.substring(0, s.length() - 4));
-                    else if (Log.on) Log.log(this, "unable to resolve image " + vals[i].toString() + " referenced in attributes of " + nodeName); 
-                }
-            }
-            else b.put(keys[i], null, vals[i]);
-
-        if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
-
-        for(int i=0; _postapply != null && i<_postapply.length; i++)
-            if (_postapply[i] != null) _postapply[i].apply(b, null, null);
-
-        pboxes.setSize(numids);
-        ptemplates.setSize(numids);
-
-        Main.instantiatedUnits += 1 + (script == null ? 0 : 10) + (keys == null ? 0 : keys.length);
-        Main.updateSplashScreen();
-    }
+        // whom to redirect to; doesn't take effect until after script runs
+        Box redir = (redirect != null && !"self".equals(redirect)) ? (Box)b.get("$" + redirect) : null;
 
+        if (script != null) script.call(new JS.Array(), new PerInstantiationScope(b, resourceRoot));
 
-    // Theming Logic ////////////////////////////////////////////////////////////
+        for(int i=0; keys != null && i<keys.length; i++) b.put(keys[i], vals[i]);
 
-    /** helper method to recursively gather up the list of keys to be preserved */
-    private void gatherPreserves(Vec v) {
-        for(int i=0; preserve != null && i<preserve.length; i++) v.addElement(preserve[i]);
-        for(int i=0; _preapply != null && i<_preapply.length; i++) if (_preapply[i] != null) _preapply[i].gatherPreserves(v);
-        for(int i=0; _postapply != null && i<_postapply.length; i++) if (_postapply[i] != null) _postapply[i].gatherPreserves(v);
-    }
+        if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
 
-    /** adds a theme mapping, retemplatizing as needed */
-    public static void retheme(String from, String to) {
-        if (Log.on) Log.log(Template.class, "retheming from " + from + " to " + to);
-        XWF.flushXWFs();
-        Resources.mapFrom.addElement(from);
-        Resources.mapTo.addElement(to);
-
-        // clear changed marker and relink
-        Template[] t = new Template[cache.size()];
-        Enumeration e = cache.elements();
-        for(int i=0; e.hasMoreElements(); i++) t[i] = (Template)e.nextElement();
-        for(int i=0; i<t.length; i++) {
-            t[i].changed = false;
-            t[i].numunits = -1;
-            t[i].link(true);
+        for(int i=0; postapply != null && i<postapply.length; i++) {
+            postapply[i].apply(b, callback, numerator, denominator, resourceRoot);
+            numerator += postapply[i].numUnits();
         }
 
-        for(int i=0; i<Surface.allSurfaces.size(); i++) {
-            Box b = ((Surface)Surface.allSurfaces.elementAt(i)).root;
-            if (b != null) reapply(b);
-        }
-    }
+        numerator = original_numerator + numUnits();
 
-    /** template reapplication procedure */
-    private static void reapply(Box b) {
+        if (callback != null) try {
+            JS.Array args = new JS.Array();
+            args.addElement(new Double(numerator));
+            args.addElement(new Double(denominator));
+            callback.call(args);
+        } catch (JS.Exn e) { if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e); }
 
-        // Ref 7.5.1: check if we need to retemplatize
-        boolean retemplatize = false;
-        if (b.templatename != null) {
-            Template t = getTemplate(b.templatename, b.importlist);
-            if (t != b.template) retemplatize = true;
-            b.template = t;
-        }
-        if (b.template != null && b.template.changed)
-            retemplatize = true;
-
-        if (retemplatize) {
-
-            // Ref 7.5.2: "Preserve all properties on the box mentioned in the <preserve> elements of any
-            //             of the templates which would be applied in step 7."
-            Vec keys = new Vec();
-            b.template.gatherPreserves(keys);
-            Object[] vals = new Object[keys.size()];
-            for(int i=0; i<keys.size(); i++) vals[i] = b.get(((String)keys.elementAt(i)), null);
-            
-            // Ref 7.5.3: "Remove and save all children of the box, or its redirect target, if it has one"
-            Box[] kids = null;
-            if (b.redirect != null) {
-                kids = new Box[b.redirect.numChildren()];
-                for(int i=b.redirect.numChildren() - 1; i >= 0; i--) {
-                    kids[i] = b.redirect.getChild(i);
-                    kids[i].remove();
-                }
-            }
-            
-            // Ref 7.5.4: "Set the box's redirect target to self"
-            b.redirect = b;
-            
-            // Ref 7.5.5: "Remove all of the box's immediate children"
-            for(Box cur = b.getChild(b.numChildren() - 1); cur != null;) {
-                Box oldcur = cur;
-                cur = cur.prevSibling();
-                oldcur.remove();
-            }
-            
-            // Ref 7.5.6: "Remove all traps set by scripts run during the application of any template to this box"
-            Trap.removeAllTrapsByBox(b);
-            
-            // Ref 7.5.7: "Apply the template to the box according to the usual application procedure"
-            b.template.apply(b, null, null);
-            
-            // Ref 7.5.8: "Re-add the saved children which were removed in step 3"
-            for(int i=0; kids != null && i<kids.length; i++) b.put(Integer.MAX_VALUE, null, kids[i]);
-            
-            // Ref 7.5.9: "Re-put any property values which were preserved in step 2"
-            for(int i=0; i<keys.size(); i++) b.put((String)keys.elementAt(i), null, vals[i]);
-        }        
-
-        // Recurse
-        for(Box j = b.getChild(0); j != null; j = j.nextSibling()) reapply(j);
+        if (Thread.currentThread() instanceof ThreadMessage) XWT.sleep(0);
     }
 
-    /** runs statics, resolves string references to other templates into actual Template instance references, and sets <tt>change</tt> as needed */
-    void link() { link(false); }
-
-    /** same as link(), except that with a true value, it will force a re-link */
-    private void link(boolean force) {
-
-        if (staticscript != null) try { 
-            Scriptable s = Static.getStatic(nodeName);
-            if (staticscript != null) {
-                Script temp = staticscript;
-                ((InterpretedScript)temp).setParentScope(s);     // so we know how to handle Static.get("xwt")
-                staticscript = null;
-                temp.exec(Context.enter(), s);
-            }
-        } catch (EcmaError e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught interpreter exception: " + e.getMessage());
-            if (Log.on) Log.log(this, "         thrown while executing <static/> block for " + nodeName +
-                                      " at " + e.getSourceName() + ":" + e.getLineNumber());
-        } catch (JavaScriptException e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
-            if (Log.on) Log.log(this, "         thrown while executing <static/> block for " + nodeName + " at " + e.sourceFile + ":" + e.line);
-        }
-
-        if (!(force || (preapply != null && _preapply == null) || (postapply != null && _postapply == null))) return;
-        
-        if (preapply != null) {
-            if (_preapply == null) _preapply = new Template[preapply.length];
-            for(int i=0; i<_preapply.length; i++) {
-                Template t = getTemplate(preapply[i], importlist);
-                if (t != _preapply[i]) changed = true;
-                _preapply[i] = t;
-            }
-        }
-        if (postapply != null) {
-            if (_postapply == null) _postapply = new Template[postapply.length];
-            for(int i=0; i<_postapply.length; i++) {
-                Template t = getTemplate(postapply[i], importlist);
-                if (t != _postapply[i]) changed = true;
-                _postapply[i] = t;
-            }
-        }
-
-        for(int i=0; children != null && i<children.length; i++) children[i].link(force);
-    }
 
 
     // XML Parsing /////////////////////////////////////////////////////////////////
 
     /** handles XML parsing; builds a Template tree as it goes */
-    private static class TemplateHelper extends XML {
+    static final class TemplateHelper extends XML {
 
-        TemplateHelper() {
-            for(int i=0; i<defaultImportList.length; i++) importlist.addElement(defaultImportList[i]);
-        }
+        TemplateHelper() { }
 
         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
-        void parseit(InputStream is, Template root) throws XML.SAXException, IOException {
+        void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
+            rootNodeHasBeenEncountered = false;
+            templateNodeHasBeenEncountered = false;
+            staticNodeHasBeenEncountered = false;
+            templateNodeHasBeenFinished = false;
+            nameOfHeaderNodeBeingProcessed = null;
+
+            nodeStack.setSize(0);
+            preapply.setSize(0);
+            postapply.setSize(0);
+
             t = root;
-            parse(new TabAndMaxColumnEnforcingReader(new InputStreamReader(is), root.nodeName)); 
+            parse(new InputStreamReader(is)); 
         }
 
         /** parsing state: true iff we have already encountered the <xwt> open-tag */
@@ -403,9 +225,6 @@ public class Template {
         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
         Vec nodeStack = new Vec();
 
-        /** builds up the list of imports */
-        Vec importlist = new Vec();
-
         /** builds up the list of preapplies */
         Vec preapply = new Vec();
 
@@ -415,78 +234,65 @@ public class Template {
         /** the template we're currently working on */
         Template t = null;
 
-        public void startElement(String name, String[] keys, Object[] vals, int line, int col) throws XML.SAXException {
-
+        public void startElement(XML.Element c) throws XML.SchemaException {
             if (templateNodeHasBeenFinished) {
-                throw new XML.SAXException("no elements may appear after the <template> node");
+                throw new XML.SchemaException("no elements may appear after the <template> node");
 
             } else if (!rootNodeHasBeenEncountered) {
-                if (!"xwt".equals(name)) throw new XML.SAXException("root element was not <xwt>");
-                if (keys.length != 0) throw new XML.SAXException("root element must not have attributes");
+                if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
+                if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
                 rootNodeHasBeenEncountered = true;
                 return;
         
             } else if (!templateNodeHasBeenEncountered) {
-                if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SAXException("can't nest header nodes");
-                nameOfHeaderNodeBeingProcessed = name;
+                if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
+                nameOfHeaderNodeBeingProcessed = c.localName;
 
-                if (name.equals("import")) {
-                    if (keys.length != 1 || !keys[0].equals("name"))
-                        throw new XML.SAXException("<import> node must have exactly one attribute, which must be called 'name'");
-                    String importpackage = vals[0].toString();
+                if (c.localName.equals("import")) {
+                    if (c.len != 1 || !c.keys[0].equals("name"))
+                        throw new XML.SchemaException("<import> node must have exactly one attribute, which must be called 'name'");
+                    String importpackage = c.vals[0].toString();
                     if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
-                    importlist.addElement(importpackage);
                     return;
 
-                } else if (name.equals("redirect")) {
-                    if (keys.length != 1 || !keys[0].equals("target"))
-                        throw new XML.SAXException("<redirect> node must have exactly one attribute, which must be called 'target'");
+                } else if (c.localName.equals("redirect")) {
+                    if (c.len != 1 || !c.keys[0].equals("target"))
+                        throw new XML.SchemaException("<redirect> node must have exactly one attribute, which must be called 'target'");
                     if (t.redirect != null)
-                        throw new XML.SAXException("the <redirect> header element may not appear more than once");
-                    t.redirect = vals[0].toString();
+                        throw new XML.SchemaException("the <redirect> header element may not appear more than once");
+                    t.redirect = c.vals[0].toString();
+                    if(t.redirect.equals("null")) t.redirect = null;
                     return;
 
-                } else if (name.equals("preapply")) {
-                    if (keys.length != 1 || !keys[0].equals("name"))
-                        throw new XML.SAXException("<preapply> node must have exactly one attribute, which must be called 'name'");
-                    preapply.addElement(vals[0]);
+                } else if (c.localName.equals("preapply")) {
+                    if (c.len != 1 || !c.keys[0].equals("name"))
+                        throw new XML.SchemaException("<preapply> node must have exactly one attribute, which must be called 'name'");
+                    preapply.addElement(c.vals[0]);
                     return;
 
-                } else if (name.equals("postapply")) {
-                    if (keys.length != 1 || !keys[0].equals("name"))
-                        throw new XML.SAXException("<postapply> node must have exactly one attribute, which must be called 'name'");
-                    postapply.addElement(vals[0]);
+                } else if (c.localName.equals("postapply")) {
+                    if (c.len != 1 || !c.keys[0].equals("name"))
+                        throw new XML.SchemaException("<postapply> node must have exactly one attribute, which must be called 'name'");
+                    postapply.addElement(c.vals[0]);
                     return;
 
-                } else if (name.equals("static")) {
+                } else if (c.localName.equals("static")) {
                     if (staticNodeHasBeenEncountered)
-                        throw new XML.SAXException("the <static> header node may not appear more than once");
-                    if (keys.length > 0)
-                        throw new XML.SAXException("the <static> node may not have attributes");
+                        throw new XML.SchemaException("the <static> header node may not appear more than once");
+                    if (c.len > 0)
+                        throw new XML.SchemaException("the <static> node may not have attributes");
                     staticNodeHasBeenEncountered = true;
                     return;
 
-                } else if (name.equals("preserve")) {
-                    if (keys.length != 1 || !keys[0].equals("attributes"))
-                        throw new XML.SAXException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
-                    if (t.preserve != null)
-                        throw new XML.SAXException("<preserve> header element may not appear more than once");
-
-                    StringTokenizer tok = new StringTokenizer(vals[0].toString(), ",", false);
-                    t.preserve = new String[tok.countTokens()];
-                    for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
-                    return;
-
-                } else if (name.equals("template")) {
+                } else if (c.localName.equals("template")) {
                     // finalize importlist/preapply/postapply, since they can't change from here on
-                    importlist.toArray(t.importlist = new String[importlist.size()]);
-                    if (preapply.size() > 0) preapply.copyInto(t.preapply = new String[preapply.size()]);
-                    if (postapply.size() > 0) postapply.copyInto(t.postapply = new String[postapply.size()]);
-                    importlist = preapply = postapply = null;
+                    t.startLine = getLine();
+                    if (preapply.size() > 0) preapply.copyInto(t.preapply = new Template[preapply.size()]);
+                    if (postapply.size() > 0) postapply.copyInto(t.postapply = new Template[postapply.size()]);
                     templateNodeHasBeenEncountered = true;
 
                 } else {
-                    throw new XML.SAXException("unrecognized header node \"" + name + "\"");
+                    throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
 
                 }
 
@@ -495,32 +301,39 @@ public class Template {
                 // push the last node we were in onto the stack
                 nodeStack.addElement(t);
 
-                // instantiate a new node, and set its nodeName/importlist/preapply
-                Template t2 = new Template();
-                t2.nodeName = t.nodeName + "." + t.childvect.size();
-                t2.importlist = t.importlist;
-                if (!name.equals("box")) t2.preapply = new String[] { name };
+                // instantiate a new node, and set its fileName/importlist/preapply
+                Template t2 = new Template(t.fileName);
+                t2.startLine = getLine();
+                if (!c.localName.equals("box")) t2.preapply = new Template[] { /*c.localName FIXME */ };
 
                 // make the new node the current node
                 t = t2;
 
             }
 
-            t.keys = keys;
-            t.vals = vals;
-
-            quickSortAttributes(0, t.keys.length - 1);
+            t.keys = new String[c.len];
+            t.vals = new Object[c.len];
+            Hash h = new Hash(c.len * 2, 3);
+            for(int i=0; i<c.len; i++) h.put(c.keys[i], c.vals[i]);
+            Vec v = new Vec(c.len, c.keys);
+            v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
+            for(int i=0; i<c.len; i++) {
+                // FIXME: height must come after image
+                // FIXME: thisbox must come first
+                t.keys[i] = (String)v.elementAt(i);
+                t.vals[i] = h.get(t.keys[i]);
+            }
 
             for(int i=0; i<t.keys.length; i++) {
                 if (t.keys[i].equals("id")) {
-                    t.id = vals[i].toString().intern();
+                    t.id = t.vals[i].toString().intern();
                     t.keys[i] = null;
                     continue;
                 }
 
                 t.keys[i] = t.keys[i].intern();
 
-                String valString = vals[i].toString();
+                String valString = t.vals[i].toString();
                 
                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
@@ -536,8 +349,8 @@ public class Template {
                             hasNonNumeral = true;
                             break;
                         }
-                    if (valString.length() > 0 && !hasNonNumeral) vals[i] = new Double(valString);
-                    else vals[i] = valString.intern();
+                    if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
+                    else t.vals[i] = valString.intern();
                 }
 
                 // bump thisbox to the front of the pack
@@ -551,91 +364,36 @@ public class Template {
             }
         }
 
-        /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
-        private int partitionAttributes(int left, int right) {
-            int i, j, middle;
-            middle = (left + right) / 2;
-            String s = t.keys[right]; t.keys[right] = t.keys[middle]; t.keys[middle] = s;
-            Object o = t.vals[right]; t.vals[right] = t.vals[middle]; t.vals[middle] = o;
-            for (i = left - 1, j = right; ; ) {
-                while (t.keys[++i].compareTo(t.keys[right]) < 0);
-                while (j > left && t.keys[--j].compareTo(t.keys[right]) > 0);
-                if (i >= j) break;
-                s = t.keys[i]; t.keys[i] = t.keys[j]; t.keys[j] = s;
-                o = t.vals[i]; t.vals[i] = t.vals[j]; t.vals[j] = o;
+        private JS.CompiledFunction genscript(boolean isstatic) {
+            JS.CompiledFunction thisscript = null;
+            try {
+                thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
+            } catch (IOException ioe) {
+                if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
+                thisscript = null;
             }
-            s = t.keys[right]; t.keys[right] = t.keys[i]; t.keys[i] = s;
-            o = t.vals[right]; t.vals[right] = t.vals[i]; t.vals[i] = o;
-            return i;
-        }
-        
-        /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
-        private void quickSortAttributes(int left, int right) {
-            if (left >= right) return;
-            int p = partitionAttributes(left, right);
-            quickSortAttributes(left, p - 1);
-            quickSortAttributes(p + 1, right);
-        }
-        
-        public void endElement(String name, int line, int col) throws XML.SAXException {
-
-            boolean hasNonWhitespace = false;
 
-            int len = t == null || t.content == null ? 0 : t.content.length();
-            for(int i=0; t.content != null && i<len; i++)
-                
-                // ignore double-slash comment blocks
-                if (t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '/') {
-                    while(t.content.charAt(i) != '\n' && i<len) i++;
-                    i--;
-
-                // ignore /* .. */ comment blocks
-                } else if (i<len - 1 && t.content.charAt(i) == '/' && t.content.charAt(i + 1) == '*') {
-                    i += 2;
-                    while(i<len - 1 && !(t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/')) i++;
-                    if (i<len - 1 && t.content.charAt(i) == '*' && t.content.charAt(i + 1) == '/') i += 2;
-                    i--;
-
-                // check for named functions
-                } else if (i + 8 <= len && t.content.charAt(i) == 'f' && t.content.charAt(i+1) == 'u' &&
-                           t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'c' && t.content.charAt(i+4) == 't' &&
-                           t.content.charAt(i+5) == 'i' && t.content.charAt(i+6) == 'o' && t.content.charAt(i+7) == 'n') {
-                    int j = i + 8;
-                    while(j<len && Character.isWhitespace(t.content.charAt(j))) j++;
-                    if (j<len && t.content.charAt(j) != '(')
-                        throw new XML.SAXException("named functions are not permitted in XWT -- instead of \"function foo() { ... }\"," +
-                                        " use \"foo = function() { ... }\"");
-
-                // replace " and " with " && "
-                } else if (i + 5 < len && Character.isWhitespace(t.content.charAt(i)) &&
-                           t.content.charAt(i+1) == 'a' && t.content.charAt(i+2) == 'n' && t.content.charAt(i+3) == 'd' &&
-                           Character.isWhitespace(t.content.charAt(i + 4))) {
-                    t.content.setCharAt(i+1, '&');
-                    t.content.setCharAt(i+2, '&');
-                    t.content.setCharAt(i+3, ' ');
-                    hasNonWhitespace = true;
-
-                // generic check for nonwhitespace
-                } else if (!Character.isWhitespace(t.content.charAt(i))) {
-                    hasNonWhitespace = true;
+            t.content = null;
+            t.content_start = 0;
+            t.content_lines = 0;
+            return thisscript;
+        }
 
-                }
-            
+        public void endElement(XML.Element c) throws XML.SchemaException {
             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
-                if ("static".equals(nameOfHeaderNodeBeingProcessed) && hasNonWhitespace) t.staticscript = genscript(true);
+                if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
                 nameOfHeaderNodeBeingProcessed = null;
-
+                
             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
-
                 // turn our childvect into a Template[]
                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
                 t.childvect = null;
-                if (hasNonWhitespace) t.script = genscript(false);
+                if (t.content != null) t.script = genscript(false);
                 
                 if (nodeStack.size() == 0) {
                     // </template>
                     templateNodeHasBeenFinished = true;
-
+                    
                 } else {
                     // add this template as a child of its parent
                     Template oldt = t;
@@ -643,105 +401,62 @@ public class Template {
                     nodeStack.setSize(nodeStack.size() - 1);
                     t.childvect.addElement(oldt);
                 }
-
-            }
-        }
-
-        private Script genscript(boolean isstatic) {
-            Script thisscript = null;
-            Context cx = Context.enter();
-            cx.setOptimizationLevel(-1);
-
-            try {
-                thisscript = cx.compileReader(null, new StringReader(t.content.toString()), t.nodeName + (isstatic ? "._" : ""), t.content_start, null);
-            } catch (EcmaError ee) {
-                if (Log.on) Log.log(this, ee.getMessage() + " at " + ee.getSourceName() + ":" + ee.getLineNumber());
-                thisscript = null;
-            } catch (EvaluatorException ee) {
-                if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
-                thisscript = null;
-            } catch (IOException ioe) {
-                if (Log.on) Log.log(this, "IOException while compiling script; this should never happen");
-                if (Log.on) Log.log(this, ioe);
-                thisscript = null;
             }
+         }
 
-            t.content = null;
-            t.content_start = 0;
-            t.content_lines = 0;
-            return thisscript;
-        }
+        public void characters(char[] ch, int start, int length) throws XML.SchemaException {
+            // invoke the no-tab crusade
+            for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
+                t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
 
-        public void content(char[] ch, int start, int length, int line, int col) throws XML.SAXException {
             if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
-                int contentlines = 0;
-                for(int i=start; i<start + length; i++) if (ch[i] == '\n') contentlines++;
-                line -= contentlines;
-
                 if (t.content == null) {
-                    t.content_start = line;
+                    t.content_start = getLine();
                     t.content_lines = 0;
                     t.content = new StringBuffer();
                 }
 
-                for(int i=t.content_start + t.content_lines; i<line; i++) {
-                    t.content.append('\n');
-                    t.content_lines++;
-                }
-
                 t.content.append(ch, start, length);
-                t.content_lines += contentlines;
+                t.content_lines++;
 
             } else if (nameOfHeaderNodeBeingProcessed != null) {
-                throw new XML.SAXException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
-
+                throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
             }
-
         }
 
+        public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
+        }
     }
 
-    /** a filtering reader that watches for tabs and long lines */
-    private static class TabAndMaxColumnEnforcingReader extends FilterReader {
-        private int MAX_COLUMN = 150;
-        private int column = 0;
-        private int line = 1;
-        private boolean lastCharWasCR = false;
-        private String filename;
-        public TabAndMaxColumnEnforcingReader(Reader r, String filename) { super(r); this.filename = filename; }
-        public int read() {
-            if (Log.on) Log.log(this, this.getClass().getName() + ".read() not supported, this should never happen");
-            return -1;
+    private static class PerInstantiationScope extends JS.Scope {
+        Res resourceRoot = null;
+        public PerInstantiationScope(Scope parentScope, Res resourceRoot) {
+            super(parentScope);
+            this.resourceRoot = resourceRoot;
         }
-        public long skip(long numskip) {
-            if (Log.on) Log.log(this, this.getClass().getName() + ".skip() not supported; this should never happen");
-            return numskip;
+        public boolean isTransparent() { return true; }
+        public boolean has(Object key) { return false; }
+        public void declare(String s) { super.declare(s); }
+        public Object get(Object key) {
+            // FIXME: access statics here
+            if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
+                !super.has(key)) {
+                Object ret = resourceRoot.get(key);
+                if (ret != null) return ret;
+                throw new JS.Exn("must declare " + key + " before using it!");
+            }
+            return super.get(key);
         }
-        public int read(char[] buf, int off, int len) throws IOException {
-            int ret = super.read(buf, off, len);
-            for(int i=off; i<off + ret; i++)
-                if (buf[i] == '\t') {
-                    throw new TemplateException(filename + ":" + line + "," + column + ": tabs are not allowed in XWT files");
-                } else if (buf[i] == '\r') {
-                    column = 0;
-                    line++;
-                    lastCharWasCR = true;
-                } else if (buf[i] == '\n') {
-                    column = 0;
-                    if (!lastCharWasCR) line++;
-                } else if (++column > MAX_COLUMN) {
-                    throw new TemplateException(filename + ":" + line + ": lines longer than " + MAX_COLUMN + " characters not allowed");
-                } else {
-                    lastCharWasCR = false;
-                }
-            return ret;
+        public void put(Object key, Object val) {
+            // FIXME: access statics here
+            if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
+                !super.has(key)) {
+                throw new JS.Exn("must declare " + key + " before using it!");
+            }
+            super.put(key, val);
         }
     }
 
-    private static class TemplateException extends IOException {
-        TemplateException(String s) { super(s); }
-    }
-
 }