changes made after tupshins reconstruction
[org.ibex.core.git] / src / org / xwt / Template.java
index 4ac78db..2cc6242 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
 package org.xwt;
 
 import java.io.*;
@@ -6,16 +6,12 @@ import java.util.zip.*;
 import java.util.*;
 import java.lang.*;
 import org.xwt.js.*;
+import org.xwt.translators.*;
 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
@@ -30,541 +26,222 @@ public class Template {
 
     // Instance Members ///////////////////////////////////////////////////////
 
-    /** this instance's nodeName */
-    String nodeName;
+    String id = null;                   ///< the id of this box
+    String redirect = null;             ///< the id of the redirect target; only meaningful on a root node
+    private String[] keys;              ///< keys to be "put" to instances of this template; elements correspond to those of vals
+    private Object[] vals;              ///< values to be "put" to instances of this template; elements correspond to those of keys
+    private String[] urikeys;
+    private String[] urivals;
+    private Vec children = new Vec();   ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
+    private JS script = null;           ///< the script on this node
+    Template prev;
+    JSScope staticScope = null;   ///< the scope in which the static block is executed
 
-    /** 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;
+    // Only used during parsing /////////////////////////////////////////////////////////////////
 
-    /** 'linked' form of preapply -- the String references have been resolved into instance references */
-    private Template[] _preapply = null;
+    private StringBuffer content = null;   ///< during XML parsing, this holds partially-read character data; null otherwise
+    private int content_start = 0;         ///< line number of the first line of <tt>content</tt>
+    private int startLine = -1;            ///< the line number that this element starts on
+    private XWT xwt;
 
-    /** 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;
-
-    /** keys to be "put" to instances of this template; elements correspond to those of vals */
-    private String[] keys;
-
-    /** 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 script on the static node of this template, null if it has already been executed */
-    private JS.CompiledFunction staticscript = null;
-
-    /** the script on this node */
-    private JS.CompiledFunction script = null;
-
-    /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
-    private Vec childvect = new Vec();
-
-    /** during XML parsing, this holds partially-read character data; null otherwise */
-    private StringBuffer content = null;
-
-    /** line number of the first line of <tt>content</tt> */
-    private int content_start = 0;
-
-    /** 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;
-
-        // 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));
-    }
-
-    public static Template buildTemplate(InputStream is, String nodeName) {
-        return buildTemplate(is, nodeName, new TemplateHelper());
-    }
-
-    public static Template buildTemplate(InputStream is, String nodeName, TemplateHelper t) {
-        try {
-            return new Template(is, nodeName, t);
-        } catch (XML.SchemaException e) {
-            if (Log.on) Log.log(Template.class, "error parsing template " + nodeName);
-            if (Log.on) Log.log(Template.class, e.getMessage());
-            return null;
-        } catch (XML.XMLException e) {
-            if (Log.on) Log.log(Template.class, "error parsing template at " + nodeName + ":" + 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, e);
-            return null;
-        }
-    }
-
+    // for non-root nodes
+    private Template(Template t, int startLine) { prev = t; this.xwt = t.xwt; this.startLine = startLine; }
+    private Template(XWT xwt) { this.xwt = xwt; }
+    
 
     // Methods to apply templates ////////////////////////////////////////////////////////
 
-    private Template(String nodeName) {
-        this.nodeName = nodeName;
-        cache.put(nodeName, this);
-    }
-    private Template(InputStream is, String nodeName, TemplateHelper th) throws XML.XMLException, IOException {
-        this(nodeName);
-        th.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 */
-    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();
-        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;
-    }
-    
+   
     /** 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, JS.Callable callback, int numerator, int denominator) {
-
-        int original_numerator = numerator;
-
-        if (pboxes == null) {
-            pboxes = new Vec();
-            ptemplates = new Vec();
-        }
-
-        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.put("$" + id, b);
-            }
-
-        if (script != null || (redirect != null && !"self".equals(redirect))) {
-            pboxes.addElement(b);
-            ptemplates.addElement(nodeName);
-        }
-
-        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, callback, numerator, denominator);
-                numerator += _preapply[i].numUnits();
-            }
-
-        for (int i=0; children != null && i<children.length; i++) {
-            b.put(Integer.MAX_VALUE, new Box(children[i], pboxes, ptemplates, callback, numerator, denominator));
-            numerator += children[i].numUnits();
-        }
-
-        // whom to redirect to; doesn't take effect until after script runs
-        Box redir = null;
-        if (redirect != null && !"self".equals(redirect)) redir = (Box)b.get("$" + redirect);
-
-        if (script != null) try {
-            script.call(new JS.Array(), b);
-        } catch (JS.Exn e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
-        }
-
-        for(int i=0; keys != null && i<keys.length; i++) {
-           // FIXME: make sure that if exceptions are thrown in here, the line number of the offending XML is logged
-            if (keys[i] == null) { }
-            else if (keys[i].equals("border") || keys[i].equals("image") &&
-                     !vals[i].toString().startsWith("http://") && !vals[i].toString().startsWith("https://")) {
-                String s = Resources.resolve(vals[i].toString() + ".png", importlist);
-                if (s != null) b.put(keys[i], 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], 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, callback, numerator, denominator);
-                numerator += _postapply[i].numUnits();
-            }
-
-        pboxes.setSize(numids);
-        ptemplates.setSize(numids);
-
-        numerator = original_numerator + numUnits();
-
-        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);
-            }
-
-        if (Thread.currentThread() instanceof ThreadMessage) try {
-           XWT.sleep(0);
-        } catch (JS.Exn e) {
-           if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e);
+    void apply(Box b) throws JSExn {
+        try {
+            apply(b, null);
+        } catch (IOException e) {
+            b.clear(b.VISIBLE);
+            b.mark_for_repack();
+            Log.warn(this, e);
+            throw new JSExn(e.toString());
+        } catch (JSExn e) {
+            b.clear(b.VISIBLE);
+            b.mark_for_repack();
+            Log.warn(this, e);
+            throw e;
         }
     }
 
+    private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
+        if (prev != null) prev.apply(b, null);
 
-    // Theming Logic ////////////////////////////////////////////////////////////
+        // FIXME this dollar stuff is all wrong
+        if (id != null) parentPis.putDollar(id, b);
 
-    /** 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);
-    }
-
-    /** adds a theme mapping, retemplatizing as needed */
-    public static void retheme(JS.Callable callback) {
-        XWF.flushXWFs();
-
-        // 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);
+        PerInstantiationScope pis = new PerInstantiationScope(b, xwt, parentPis, staticScope);
+        for(int i=0; i<urikeys.length; i++) {
+            pis.declare(urikeys[i]);
+            pis.put(urikeys[i], xwt.resolveString(urivals[i], true));
         }
 
-        for(int i=0; i<Surface.allSurfaces.size(); i++) {
-            Box b = ((Surface)Surface.allSurfaces.elementAt(i)).root;
-            if (b != null) reapply(b);
+        // FIXME needs to obey the new application-ordering rules
+        for (int i=0; children != null && i<children.size(); i++) {
+            Box kid = new Box();
+            ((Template)children.elementAt(i)).apply(kid, pis);
+            b.putAndTriggerTraps(b.get("numchildren"), kid);
         }
 
-        if (callback != null)
-            try {
-               JS.Array args = new JS.Array();
-               args.addElement(new Double(1.0));
-               args.addElement(new Double(1.0));
-                callback.call(args);
-            } catch (JS.Exn ex) {
-                if (Log.on) Log.log(Template.class, "WARNING: uncaught ecmascript exception: " + ex.getMessage());
-            }
-    }
-
-    /** template reapplication procedure */
-    private static void reapply(Box b) {
-
-       Log.log(Template.class, "Template.reapply() not implemented");
-       /*
-        // 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();
+        if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
+
+        Object key, val;
+        for(int i=0; keys != null && i < keys.length; i++) {
+            if (keys[i] == null) continue;
+            key = keys[i];
+            val = vals[i];
+
+            if ("null".equals(val)) val = null;
+
+            if (val != null && val instanceof String && ((String)val).length() > 0) {
+                switch (((String)val).charAt(0)) {
+                    case '$':
+                        val = pis.get(val);
+                        if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
+                        break;
+                    case '.':
+                        val = xwt.resolveString(((String)val).substring(1), false);
+                    // FIXME: url case
+                    // FIXME: should we be resolving all of these in the XML-parsing code?
                 }
             }
-            
-            // 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, null, 0, 1);
-            
-            // 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);
-       */
+            b.putAndTriggerTraps(key, val);
+        }
     }
 
-    /** 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 { 
-            JS.Scope s = Static.createStatic(nodeName, false);
-            if (staticscript != null) {
-                JS.CompiledFunction temp = staticscript;
-                staticscript = null;
 
-               // we layer a transparent scope over the Static so that we can catch requests for the xwt object
-               // yet not screw up paths that include a package called xwt (ie xwt.static.org.xwt.foo)
-               JS.Scope varScope = new JS.Scope(s) {
-                       public boolean isTransparent() { return true; }
-                       public Object get(Object key) {
-                           if ("xwt".equals(key)) return XWT.singleton; else return super.get(key);
-                       } };
 
-               temp.call(new JS.Array(), varScope);
-            }
-        } catch (JS.Exn e) {
-            if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e.getMessage());
-        }
+    // XML Parsing /////////////////////////////////////////////////////////////////
 
-        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;
-            }
+    public static Template buildTemplate(InputStream is, XWT xwt) {
+        try {
+            return new TemplateHelper(is, xwt).t;
+        } catch (Exception e) {
+            Log.error(Template.class, e);
+            return null;
         }
-
-        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 */
     static final class TemplateHelper extends XML {
 
-        TemplateHelper() { }
-
-        /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
-        void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
-            rootNodeHasBeenEncountered = false;
-            templateNodeHasBeenEncountered = false;
-            staticNodeHasBeenEncountered = false;
-            templateNodeHasBeenFinished = false;
-            nameOfHeaderNodeBeingProcessed = null;
-
-            nodeStack.setSize(0);
-            importlist.setSize(0);
-            preapply.setSize(0);
-            postapply.setSize(0);
-
-            importlist.fromArray(defaultImportList);
+        private int state = STATE_INITIAL;
+        private static final int STATE_INITIAL = 0;
+        private static final int STATE_IN_XWT_NODE = 1;
+        private static final int STATE_IN_TEMPLATE_NODE = 2; 
+        private static final int STATE_IN_META_NODE = 3;
 
-            t = root;
-            parse(new InputStreamReader(is)); 
-        }
-
-        /** parsing state: true iff we have already encountered the <xwt> open-tag */
-        boolean rootNodeHasBeenEncountered = false;
-
-        /** parsing state: true iff we have already encountered the <template> open-tag */
-        boolean templateNodeHasBeenEncountered = false;
-
-        /** parsing state: true iff we have already encountered the <static> open-tag */
-        boolean staticNodeHasBeenEncountered = false;
-
-        /** parsing state: true iff we have already encountered the <template> close-tag */
-        boolean templateNodeHasBeenFinished = false;
-
-        /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
-         *  that tag; otherwise, it is null. */
-        String nameOfHeaderNodeBeingProcessed = null;
-
-        /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
+        StringBuffer static_content = null;
+        int static_content_start = 0;
         Vec nodeStack = new Vec();
-
-        /** builds up the list of imports */
-        Vec importlist = new Vec();
-
-        /** builds up the list of preapplies */
-        Vec preapply = new Vec();
-
-        /** builds up the list of postapplies */
-        Vec postapply = new Vec();
-
-        /** the template we're currently working on */
         Template t = null;
+        int meta = 0;
+        XWT xwt;
+
+        public TemplateHelper(InputStream is, XWT xwt) throws XML.Exn, IOException, JSExn {
+            this.xwt = xwt;
+            parse(new InputStreamReader(is));
+            JS staticScript = parseScript(static_content, static_content_start);
+            t.staticScope = new PerInstantiationScope(null, xwt, null, null);
+            if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
+        }
 
-        public void startElement(XML.Element c) throws XML.SchemaException {
-            if (templateNodeHasBeenFinished) {
-                throw new XML.SchemaException("no elements may appear after the <template> node");
-
-            } else if (!rootNodeHasBeenEncountered) {
-                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.SchemaException("can't nest header nodes");
-                nameOfHeaderNodeBeingProcessed = c.localName;
-
-                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 (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.SchemaException("the <redirect> header element may not appear more than once");
-                    t.redirect = c.vals[0].toString();
-                    return;
-
-                } 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 (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 (c.localName.equals("static")) {
-                    if (staticNodeHasBeenEncountered)
-                        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 (c.localName.equals("preserve")) {
-                    if (c.len != 1 || !c.keys[0].equals("attributes"))
-                        throw new XML.SchemaException("<preserve> node must have exactly one attribute, which must be called 'attributes'");
-                    if (t.preserve != null)
-                        throw new XML.SchemaException("<preserve> header element may not appear more than once");
+        private JS parseScript(StringBuffer content, int content_start) throws IOException {
+            if (content == null) return null;
+            String contentString = content.toString();
+            if (contentString.trim().length() > 0) return JS.fromReader("FIXME", content_start, new StringReader(contentString));
+            return null;
+        }
 
-                    StringTokenizer tok = new StringTokenizer(c.vals[0].toString(), ",", false);
-                    t.preserve = new String[tok.countTokens()];
-                    for(int i=0; i<t.preserve.length; i++) t.preserve[i] = tok.nextToken();
+        public void startElement(XML.Element c) throws XML.Exn {
+            switch(state) {
+                case STATE_IN_META_NODE: { meta++; return; }
+                case STATE_INITIAL:
+                    if (!"ibex".equals(c.getLocalName()))
+                        throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
+                    if (c.getAttrLen() != 0)
+                        throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
+                    state = STATE_IN_XWT_NODE;
                     return;
+                case STATE_IN_XWT_NODE:
+                    if ("meta".equals(c.getPrefix())) { state = STATE_IN_META_NODE; meta = 0; return; }
+                    state = STATE_IN_TEMPLATE_NODE;
+                    t = (t == null) ? new Template(xwt) : new Template(t, getLine());
+                    break;
+                case STATE_IN_TEMPLATE_NODE:
+                    nodeStack.addElement(t);
+                    t = new Template(xwt);
+                    break;
+            }
 
-                } else if (c.localName.equals("template")) {
-                    // finalize importlist/preapply/postapply, since they can't change from here on
-                    t.startLine = getLine();
-                    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.setSize(0); preapply.setSize(0); postapply.setSize(0);
-                    templateNodeHasBeenEncountered = true;
-
-                } else {
-                    throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
-
+            if (!("ui".equals(c.getPrefix()) && "box".equals(c.getLocalName()))) {
+                String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
+                // GROSS hack
+                try {
+                    t.prev = (Template)t.xwt.resolveString(tagname, false).call(null, null, null, null, 9999);
+                } catch (Exception e) {
+                    Log.error(Template.class, e);
                 }
+            }
+                
+            Hash urimap = c.getUriMap();
+            t.urikeys = new String[urimap.size()];
+            t.urivals = new String[urimap.size()];
+            Enumeration uriEnumeration = urimap.keys();
+            int ii = 0;
+            while(uriEnumeration.hasMoreElements()) {
+                String key = (String)uriEnumeration.nextElement();
+                String val = (String)urimap.get(key);
+                t.urikeys[ii] = key;
+                if (val.charAt(0) == '.') val = val.substring(1);
+                t.urivals[ii] = val;
+                ii++;
+            }
+            
+            Vec keys = new Vec(c.getAttrLen());
+            Vec vals = new Vec(c.getAttrLen());
+
+            // process attributes into Vecs, dealing with any XML Namespaces in the process
+            ATTR: for (int i=0; i < c.getAttrLen(); i++) {
+                //#switch(c.getAttrKey(i))
+                case "id":
+                    t.id = c.getAttrVal(i).toString().intern();
+                    continue ATTR;
+                //#end
+
+                // treat value starting with '.' as resource reference
+                String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
+                keys.addElement(c.getAttrKey(i));
+                vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
+            }
 
-            } else {
-
-                // 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(t.nodeName + "." + t.childvect.size());
-                t2.importlist = t.importlist;
-                t2.startLine = getLine();
-                if (!c.localName.equals("box")) t2.preapply = new String[] { c.localName };
-
-                // make the new node the current node
-                t = t2;
+            if (keys.size() == 0) return;
 
-            }
+            // sort the attributes lexicographically
+            Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
+                return ((String)a).compareTo((String)b);
+            } });
 
-            // TODO: Sort contents straight from one array to another
-            t.keys = new String[c.len];
-            t.vals = new Object[c.len];
-            System.arraycopy(c.keys, 0, t.keys, 0, c.len);
-            System.arraycopy(c.vals, 0, t.vals, 0, c.len);
-            quickSortAttributes(0, t.keys.length - 1);
+            t.keys = new String[keys.size()];
+            t.vals = new Object[vals.size()];
+            keys.copyInto(t.keys);
+            vals.copyInto(t.vals);
 
+            // convert attributes to appropriate types and intern strings
             for(int i=0; i<t.keys.length; i++) {
-                if (t.keys[i].equals("id")) {
-                    t.id = t.vals[i].toString().intern();
-                    t.keys[i] = null;
-                    continue;
-                }
-
                 t.keys[i] = t.keys[i].intern();
 
                 String valString = t.vals[i].toString();
@@ -586,109 +263,71 @@ public class Template {
                     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
-                if (t.keys[i].equals("thisbox")) {
-                    t.keys[i] = t.keys[0];
-                    t.keys[0] = "thisbox";
-                    Object o = t.vals[0];
-                    t.vals[0] = t.vals[i];
-                    t.vals[i] = o;
-                }
             }
         }
 
-        /** 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;
-            }
-            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(XML.Element c) throws XML.SchemaException {
-            if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
-                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 (t.content != null) t.script = genscript(false);
-                
-                if (nodeStack.size() == 0) {
-                    // </template>
-                    templateNodeHasBeenFinished = true;
-
-                } else {
-                    // add this template as a child of its parent
+        public void endElement(XML.Element c) throws XML.Exn, IOException {
+            switch(state) {
+                case STATE_IN_META_NODE: if (meta-- < 0) state = STATE_IN_XWT_NODE; return;
+                case STATE_IN_XWT_NODE: return;
+                case STATE_IN_TEMPLATE_NODE: {
+                    if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
+                    if (nodeStack.size() == 0) { state = STATE_IN_XWT_NODE; return; }
                     Template oldt = t;
                     t = (Template)nodeStack.lastElement();
                     nodeStack.setSize(nodeStack.size() - 1);
-                    t.childvect.addElement(oldt);
+                    t.children.addElement(oldt);
+                    int oldt_lines = getLine() - oldt.startLine;
+                    for (int i=0; oldt_lines > i; i++) t.content.append('\n');
                 }
-
             }
         }
 
-        private JS.CompiledFunction genscript(boolean isstatic) {
-            JS.CompiledFunction thisscript = null;
-            try {
-                thisscript = JS.parse(t.nodeName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
-            } catch (JS.Exn ee) {
-                if (Log.on) Log.log(this, "  ERROR: " + ee.getMessage());
-                thisscript = null;
-            } catch (IOException ioe) {
-                if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
-                thisscript = null;
+        public void characters(char[] ch, int start, int length) throws XML.Exn {
+            for (int i=0; length >i; i++) if (ch[start+i] == '\t')
+                Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
+            switch(state) {
+                case STATE_IN_TEMPLATE_NODE:
+                    if (t.content == null) {
+                        t.content_start = getLine();
+                        t.content = new StringBuffer();
+                    }
+                    t.content.append(ch, start, length);
+                    return;
+                case STATE_IN_XWT_NODE:
+                    if (static_content == null) {
+                        static_content_start = getLine();
+                        static_content = new StringBuffer();
+                    }
+                    static_content.append(ch, start, length);
+                    return;
             }
-
-            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.nodeName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
-
-            if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
-                if (t.content == null) {
-                    t.content_start = getLine();
-                    t.content_lines = 0;
-                    t.content = new StringBuffer();
-                }
-
-                t.content.append(ch, start, length);
-                t.content_lines++;
+        public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
+    }
 
-            } else if (nameOfHeaderNodeBeingProcessed != null) {
-                throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
-            }
+    private static class PerInstantiationScope extends JSScope {
+        XWT xwt = null;
+        PerInstantiationScope parentBoxPis = null;
+        JSScope myStatic = null;
+        void putDollar(String key, Box target) throws JSExn {
+            if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
+            declare("$" + key);
+            put("$" + key, target);
         }
-
-        public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
+        public PerInstantiationScope(JSScope parentScope, XWT xwt, PerInstantiationScope parentBoxPis, JSScope myStatic) {
+            super(parentScope);
+            this.parentBoxPis = parentBoxPis;
+            this.xwt = xwt;
+            this.myStatic = myStatic;
+        }
+        public Object get(Object key) throws JSExn {
+            if (super.has(key)) return super.get(key);
+            if (key.equals("xwt")) return xwt;
+            if (key.equals("")) return xwt.get("");
+            if (key.equals("static")) return myStatic;
+            return super.get(key);
         }
     }