2004/01/07 20:37:32
[org.ibex.core.git] / src / org / xwt / Template.java
index 363886c..f85f3a7 100644 (file)
@@ -6,6 +6,7 @@ import java.util.zip.*;
 import java.util.*;
 import java.lang.*;
 import org.xwt.js.*;
+import org.xwt.translators.*;
 import org.xwt.util.*;
 
 /**
@@ -21,115 +22,86 @@ 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 ///////////////////////////////////////////////////////
 
-    /** 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 Template[] preapply;
-
-    /** templates that should be postapplied (in the order of application); only meaningful on a root node */
-    private Template[] postapply;
-
-    /** 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;
+    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 Vec children = new Vec();     ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
+    private int numunits = -1;            ///< see numUnits(); -1 means that this value has not yet been computed
 
-    /** child template objects */
-    private Template[] children;
+    private JSFunction script = null;       ///< the script on this node
+    private String fileName = "unknown";  ///< the filename this node came from; used only for debugging
+    private Vec preapply = new Vec();     ///< templates that should be preapplied (in the order of application)
 
-    /** see numUnits(); -1 means that this value has not yet been computed */
-    private int numunits = -1;
 
-    /** the scope in which the static block is executed */
-    private JS.Scope staticScope = null;
+    // Instance Members that are only meaningful on root Template //////////////////////////////////////
 
-    /** 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;
-
-    /** the filename this node came from; used only for debugging */
-    private String fileName = "unknown";
+    private JSScope staticScope = null;   ///< the scope in which the static block is executed
+    private JSFunction staticscript = null;  ///< the script on the static node of this template, null already performed
 
 
     // Only used during parsing /////////////////////////////////////////////////////////////////
 
-    /** 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;
+    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 final Stream r;                   ///< the resource we came from
 
 
     // Static data/methods ///////////////////////////////////////////////////////////////////
 
-    private Template(String fileName) { this.fileName = fileName; }
-
-    public static Template getTemplate(Res r) {
+    // FIXME need to provide the XWT object too
+    public static Template getTemplate(Stream r) throws JSExn {
         try {
+            r = r.addExtension(".xwt");
             if (r.t != null) return r.t;
-            r.t = new Template(r.getDescriptiveName());
+            r.t = new Template(r);
             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.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 " + r.t.fileName + " -- this should never happen");
-            if (Log.on) Log.log(Template.class, e);
-            return null;
+        } catch (Exception e) {
+            throw new JSExn("Error reading template stream: " + r + "\n" + e.toString());
+        }
+    }
+
+    public static Stream resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
+        // URL
+        if (str.indexOf("://") != -1) {
+            if (permitAbsolute) return (Stream)xwt.url2res(str);
+            throw new JSExn("absolute URL " + str + " not permitted here");
+        }
+
+        // root-relative
+        Stream ret = xwt.rr;
+        while(str.indexOf('.') != -1) {
+            String path = str.substring(0, str.indexOf('.'));
+            str = str.substring(str.indexOf('.') + 1);
+            ret = (Stream)ret.get(path);
         }
+        ret = (Stream)ret.get(str);
+        return ret;
     }
 
 
     // Methods to apply templates ////////////////////////////////////////////////////////
 
-    /** calculates, caches, and returns an integer approximation of how long it will take to apply this template,
-     *  including pre/post and children */
-    int numUnits() {
-        if (numunits != -1) return numunits;
-        numunits = 1;
-        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;
+    private Template(Stream r) {
+        this.r = r;
+        String f = r.toString();
+        if (f != null && !f.equals(""))
+            fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
     }
 
     /** 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);
+    JSScope getStatic(XWT xwt) throws JSExn {
+        if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
         if (staticscript == null) return staticScope;
-        JS.CompiledFunction temp = staticscript;
+        JSFunction temp = staticscript;
         staticscript = null;
-        temp.call(new JS.Array(), staticScope);
+        temp.cloneWithNewParentScope(staticScope).call(null, null, null, null, 0);
         return staticScope;
     }
     
@@ -137,46 +109,68 @@ public class Template {
      *  @param pboxes a vector of all box parents on which to put $-references
      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
      */
-    // FIXME: $-vars not dealt with
-    void apply(Box b, JS.Callable callback, int numerator, int denominator, Res resourceRoot) {
+    void apply(Box b, XWT xwt) throws JSExn {
+        try {
+            apply(b, xwt, null);
+        } catch (JSExn e) {
+            b.clear(b.VISIBLE);
+            b.mark_for_repack();
+            throw e;
+        }
+    }
 
-        getStatic();
-        int original_numerator = numerator;
 
-        for(int i=0; preapply != null && i<preapply.length; i++) {
-            preapply[i].apply(b, callback, numerator, denominator, resourceRoot);
-            numerator += preapply[i].numUnits();
-        }
+    private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
+        getStatic(xwt);
 
-        for (int i=0; children != null && i<children.length; i++) {
-            children[i].apply(new Box(), callback, numerator, denominator, resourceRoot);
-            numerator += children[i].numUnits();
+        if (id != null) parentPis.putDollar(id, b);
+        for(int i=0; i<preapply.size(); i++) {
+            Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt, false));
+            if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
+            t.apply(b, xwt);
         }
 
-        // whom to redirect to; doesn't take effect until after script runs
-        Box redir = (redirect != null && !"self".equals(redirect)) ? (Box)b.get("$" + redirect) : null;
+        PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
 
-        if (script != null) script.call(new JS.Array(), new PerInstantiationScope(b, resourceRoot));
+        for (int i=0; children != null && i<children.size(); i++) {
+            Box kid = new Box();
+            ((Template)children.elementAt(i)).apply(kid, xwt, pis);
+            b.putAndTriggerTraps(b.get("numchildren"), kid);
+        }
 
-        for(int i=0; keys != null && i<keys.length; i++) b.put(keys[i], vals[i]);
+        if (script != null) script.cloneWithNewParentScope(pis).call(null, null, null, null, 0);
 
-        if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
+        Object key, val;
+        for(int i=0; keys != null && i < keys.length; i++) {
+            if (keys[i] == null) continue;
+            key = keys[i];
+            val = vals[i];
 
-        for(int i=0; postapply != null && i<postapply.length; i++) {
-            postapply[i].apply(b, callback, numerator, denominator, resourceRoot);
-            numerator += postapply[i].numUnits();
-        }
+            if ("null".equals(val)) val = null;
 
-        numerator = original_numerator + numUnits();
+            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 = resolveStringToResource(((String)val).substring(1), xwt, true);
+                }
+            }
 
-        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 (val != null && "redirect".equals(key)) {
+                val = pis.get("$"+val);
+                if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
+            }
 
-        if (Thread.currentThread() instanceof ThreadMessage) XWT.sleep(0);
+            try {
+                b.putAndTriggerTraps(key, val);
+            } catch(JSExn e) {
+                e.addBacktrace(fileName + ":attr-" + key,0);
+                throw e;
+            }
+        }
     }
 
 
@@ -188,143 +182,114 @@ public class Template {
 
         TemplateHelper() { }
 
+        private int state;
+        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_FINISHED_TEMPLATE_NODE = 3;
+
+        private String nameOfHeaderNodeBeingProcessed;
+
+        Vec nodeStack = new Vec();  ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
+        Template t = null;          ///< the template we're currently working on
+
         /** 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;
+        void parseit(InputStream is, Template root) throws XML.Exn, IOException {
+            state = STATE_INITIAL;
             nameOfHeaderNodeBeingProcessed = null;
-
             nodeStack.setSize(0);
-            preapply.setSize(0);
-            postapply.setSize(0);
-
             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 */
-        Vec nodeStack = 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;
-
-        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;
+        public void startElement(XML.Element c) throws XML.Exn {
+            switch(state) {
+            case STATE_INITIAL:
+                if (!"xwt".equals(c.getLocalName()))
+                    throw new XML.Exn("root element was not <xwt>", 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;
-        
-            } 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);
-                    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();
-                    if(t.redirect.equals("null")) t.redirect = null;
+            case STATE_IN_XWT_NODE:
+                if (nameOfHeaderNodeBeingProcessed != null)
+                    throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
+                nameOfHeaderNodeBeingProcessed = c.getLocalName();
+                //#switch(c.getLocalName())
+                case "doc":
+                    // FEATURE
                     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]);
+                case "static":
+                    if (t.staticscript != null)
+                        throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
+                    if (c.getAttrLen() > 0)
+                        throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
                     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("template")) {
-                    // finalize importlist/preapply/postapply, since they can't change from here on
+                case "template":
                     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.SchemaException("unrecognized header node \"" + c.localName + "\"");
-
-                }
-
-            } else {
+                    state = STATE_IN_TEMPLATE_NODE;
+                    processBodyElement(c);
+                    return;
+                //#end
+                throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
 
+            case STATE_IN_TEMPLATE_NODE:
                 // push the last node we were in onto the stack
                 nodeStack.addElement(t);
-
                 // instantiate a new node, and set its fileName/importlist/preapply
-                Template t2 = new Template(t.fileName);
+                Template t2 = new Template(t.r);
                 t2.startLine = getLine();
-                if (!c.localName.equals("box")) t2.preapply = new Template[] { /*c.localName FIXME */ };
-
+                if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
+                    t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
                 // make the new node the current node
                 t = t2;
+                processBodyElement(c);
+                return;
 
+            case STATE_FINISHED_TEMPLATE_NODE:
+                throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
+            }
+        }        
+
+        private void processBodyElement(XML.Element c) {
+            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 "preapply":
+                    String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
+                    StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
+                    while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
+                    continue ATTR;
+
+                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));
             }
 
-            // TODO: Sort contents straight from one array to another
-            // FIXME: height must come after image
-            // FIXME: use Vec here
-            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);
+            if (keys.size() == 0) return;
 
-            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;
-                }
+            // sort the attributes lexicographically
+            Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
+                return ((String)a).compareTo((String)b);
+            } });
 
+            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++) {
                 t.keys[i] = t.keys[i].intern();
 
                 String valString = t.vals[i].toString();
@@ -346,135 +311,91 @@ 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);
+        private JSFunction parseScript(boolean isstatic) throws IOException {
+            JSFunction thisscript = null;
+            String contentString = t.content.toString();
+            if (contentString.trim().length() > 0)
+                thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
+                                                   t.content_start,
+                                                   new StringReader(contentString));
+            t.content = null;
+            t.content_start = 0;
+            return thisscript;
         }
 
-        public void endElement(XML.Element c) throws XML.SchemaException {
-            if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
-                if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
+        public void endElement(XML.Element c) throws XML.Exn, IOException {
+            if (state == STATE_IN_XWT_NODE) {
+                if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(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);
                 
+            } else if (state == STATE_IN_TEMPLATE_NODE) {
+                if (t.content != null) t.script = parseScript(false);
                 if (nodeStack.size() == 0) {
                     // </template>
-                    templateNodeHasBeenFinished = true;
-
+                    state = STATE_FINISHED_TEMPLATE_NODE;
+                    
                 } else {
                     // add this template as a child of its parent
                     Template oldt = t;
                     t = (Template)nodeStack.lastElement();
                     nodeStack.setSize(nodeStack.size() - 1);
-                    t.childvect.addElement(oldt);
-                }
-
-            }
-        }
+                    t.children.addElement(oldt);
 
-        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;
+                    int oldt_lines = getLine() - oldt.startLine;
+                    for (int i=0; oldt_lines > i; i++) t.content.append('\n');
+                }
             }
+         }
 
-            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 {
+        public void characters(char[] ch, int start, int length) throws XML.Exn {
             // 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");
+            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()+")");
 
-            if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
+            if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
                 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++;
 
-            } else if (nameOfHeaderNodeBeingProcessed != null) {
-                throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
+            } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
+                "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
             }
         }
 
-        public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
-        }
+        public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
     }
 
-    private static class PerInstantiationScope extends JS.Scope {
-        Res resourceRoot = null;
-        public PerInstantiationScope(Scope parentScope, Res resourceRoot) {
+    private static class PerInstantiationJSScope extends JSScope {
+        XWT xwt = null;
+        PerInstantiationJSScope 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 PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
             super(parentScope);
-            this.resourceRoot = resourceRoot;
+            this.parentBoxPis = parentBoxPis;
+            this.xwt = xwt;
+            this.myStatic = myStatic;
         }
-        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!");
-            }
+        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.rr;
+            if (key.equals("static")) return myStatic;
             return super.get(key);
         }
-        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);
+        public void put(Object key, Object val) throws JSExn {
+            if (super.has(key)) super.put(key, val);
+            else super.put(key, val);
         }
     }