2003/09/25 10:10:52
authormegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:36:18 +0000 (07:36 +0000)
committermegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:36:18 +0000 (07:36 +0000)
darcs-hash:20040130073618-2ba56-05059dd0eba4c83891d8759afb45dd0863aa5851.gz

src/org/xwt/Box.java.pp
src/org/xwt/Picture.java
src/org/xwt/Res.java
src/org/xwt/Template.java
src/org/xwt/XWT.java

index f18182c..4a1c07a 100644 (file)
@@ -473,42 +473,6 @@ public final class Box extends JS.Scope {
                 return redirect.callMethod(method, args, checkOnly);
             }
             return new Integer(b.getIndexInParent());
-
-        } else if ("apply".equals(method)) {
-            if (checkOnly) return Boolean.TRUE;
-            if (args.elementAt(0) instanceof Res) {
-                Res res = (Res)args.elementAt(0);
-                //                res = res.addExtension(".xwt");
-                Template t = Template.getTemplate(res);
-                if (ThreadMessage.suspendThread()) try {
-                    JS.Callable callback = args.length() < 2 ? null : (Callable)args.elementAt(1);
-                    
-                    // FIXME!!! needs to be xwt.apply(template, box)
-                    t.apply(this, callback, 0, t.numUnits(), null);
-                } finally {
-                    ThreadMessage.resumeThread();
-                }
-            } else if (args.elementAt(0) instanceof String) {
-                String templatename = (String)args.elementAt(0);
-                // FIXME
-                Template t = Template.getTemplate(null);
-                if (t == null) {
-                    if (Log.on) Log.logJS(this, "template " + templatename + " not found");
-                } else {
-                    if (ThreadMessage.suspendThread()) try {
-                        JS.Callable callback = args.length() < 2 ? null : (Callable)args.elementAt(1);
-                        // FIXME!!! needs to be xwt.apply(template, box)
-                        t.apply(this, callback, 0, t.numUnits(), null);
-                    } finally {
-                        ThreadMessage.resumeThread();
-                    }
-                }
-            } else if (args.elementAt(0) instanceof JS && !(args.elementAt(0) instanceof Box)) {
-                JS s = (JS)args.elementAt(0);
-                Object[] keys = s.keys();
-                for(int j=0; j<keys.length; j++) put(keys[j].toString(), s.get(keys[j]));
-            }
-            return this;
         }
         return null;
     }
@@ -1132,8 +1096,8 @@ public final class Box extends JS.Scope {
                         } else {
                             // FIXME
                         }
-                        b.minwidth = b.image == null ? 0 : b.image.getWidth();
-                        b.minheight = b.image == null ? 0 : b.image.getHeight();
+                        b.minwidth = Math.min(b.maxwidth, Math.max(b.minwidth, b.image == null ? 0 : b.image.getWidth()));
+                        b.minheight = Math.min(b.maxheight, Math.max(b.minheight, b.image == null ? 0 : b.image.getHeight()));
                         MARK_FOR_REFLOW_b;
                         b.dirty();
                     }
@@ -1320,7 +1284,16 @@ public final class Box extends JS.Scope {
             //#end
 
             specialBoxProperties.put("redirect", new SpecialBoxProperty() {
-                    public void put(Box b, Object value) { }
+                    public void put(Box b, Object value) {
+                        if (b.redirect != b) Log.log(this, "cannot change the redirect of a box once it is set");
+                        else if (value == null) b.redirect = null;
+                        else {
+                            Box b2 = (Box)value;
+                            while(b2 != b && b2 != null) b2 = b2.parent;
+                            if (b2 == null) Log.log(this, "a box's redirect must be one of its descendants");
+                            b.redirect = (Box)value;
+                        }
+                    }
                     public Object get(Box b) {
                         if (b.redirect == null) return null;
                         if (b.redirect == b) return Boolean.TRUE;
index 88cf65b..29e3184 100644 (file)
@@ -22,6 +22,9 @@ public abstract class Picture {
 
     /** Pictures, cached by Res */
     private static Cache cache = new Cache();
+
+    private static GIF gif = new GIF();
+    private static PNG png = new PNG();
     
     /** turns a resource into a Picture.Source */
     public static Picture fromRes(Res r) {
@@ -32,10 +35,9 @@ public abstract class Picture {
                 PushbackInputStream pbis = new PushbackInputStream(r.getInputStream());
                 int c = pbis.read();
                 pbis.unread(c);
-                // FEATURE: cache GIF/PNG objects, reuse int[]'s?
-                if (c == 'G') ret = new GIF().fromInputStream(pbis, "FIXME");
-                else if (c == 137) ret = new PNG().fromInputStream(pbis, "FIXME");
-                else if (c == 0xff) ret = Platform.decodeJPEG(pbis, "FIXME");
+                if (c == 'G') ret = gif.fromInputStream(pbis, r.getDescriptiveName());
+                else if (c == 137) ret = png.fromInputStream(pbis, r.getDescriptiveName());
+                else if (c == 0xff) ret = Platform.decodeJPEG(pbis, r.getDescriptiveName());
                 else throw new JS.Exn("couldn't figure out image type from first byte");
                 cache.put(r, ret);
             } catch (IOException e) {
index 77b502b..bb63940 100644 (file)
@@ -10,14 +10,13 @@ import org.xwt.util.*;
 /** base class for XWT resources */
 public abstract class Res extends JS {
 
-    public String getDescriptiveName() { return "FIXME"; }
-
-    /** if this Res corresponds to a Template, it is cached here */
-    Template t = null;
+    public String getDescriptiveName() { return ""; }
 
     /** cache of subresources so that the equality operator works on them */
     private Hash refCache = null;
 
+    public Res getParent() { return null; }
+
     /** returns an InputStream containing the Resource's contents */
     public InputStream getInputStream() throws IOException { return getInputStream(""); }
     public abstract InputStream getInputStream(String path) throws IOException;
@@ -108,12 +107,17 @@ public abstract class Res extends JS {
         Res parent;
         Object key;
         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
+        public String getDescriptiveName() {
+            String pdn = parent.getDescriptiveName();
+            return pdn.equals("") ? key.toString() : (pdn + "." + key.toString());
+        }
         public Res addExtension(String extension) {
             return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
         }
         public InputStream getInputStream(String path) throws IOException {
             return parent.getInputStream("/" + key + path);
         }
+        public Res getParent() { return parent; }
         public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
     }
 
@@ -127,6 +131,8 @@ public abstract class Res extends JS {
         public int hashCode() { return graftee.hashCode(); }
         public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
+        public String getDescriptiveName() { return graftee.getDescriptiveName(); }
+        public Res getParent() { return graftee.getParent(); }
     }
 
     /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
index 95846c1..ef6a6f3 100644 (file)
@@ -21,107 +21,74 @@ 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;
+    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
 
-    /** values to be "put" to instances of this template; elements correspond to those of keys */
-    private Object[] vals;
+    private JS.CompiledFunction script = null;       ///< the script on this node
+    private String fileName = "unknown";             ///< the filename this node came from; used only for debugging
+    private Vec preapply;                            ///< templates that should be preapplied (in the order of application)
 
-    /** child template objects */
-    private Template[] children;
 
-    /** see numUnits(); -1 means that this value has not yet been computed */
-    private int numunits = -1;
+    // Instance Members that are only meaningful on root Template //////////////////////////////////////
 
-    /** 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 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 JS.Scope staticScope = null;             ///< the scope in which the static block is executed
+    private JS.CompiledFunction 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 content_lines = 0;       ///< number of lines in <tt>content</tt>
+    private int startLine = -1;          ///< the line number that this element starts on
+    final Res r;                         ///< the resource we came from
 
 
     // Static data/methods ///////////////////////////////////////////////////////////////////
 
-    private Template(String fileName) { this.fileName = fileName; }
-
     public static Template getTemplate(Res r) {
         try {
             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());
+        } catch (Exception e) {
+            if (Log.on) Log.log(r.t.fileName, e);
             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);
+        }
+    }
+
+    public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) {
+        // URL
+        if (str.indexOf("://") != -1) {
+            if (permitAbsolute) return str;
+            Log.log("absolute URL " + str + " not permitted here");
             return null;
         }
+
+        // root-relative
+        Res ret = xwt.rr;
+        while(str.indexOf('.') != -1) {
+            String path = str.substring(0, str.indexOf('.'));
+            str = str.substring(str.indexOf('.') + 1);
+            ret = (Res)ret.get(path);
+        }
+        ret = (Res)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() { this.r = r; }
 
     /** called before this template is applied or its static object can be externally referenced */
     JS.Scope getStatic() {
@@ -137,48 +104,30 @@ 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, JS.Callable c, XWT xwt) { apply(b, c, xwt, null); }
+    void apply(Box b, JS.Callable callback, XWT xwt, PerInstantiationScope parentPis) {
 
         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();
+        if (id != null) parentPis.putDollar(id, this);
+        for(int i=0; i<preapply.size(); i++) {
+            Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt));
+            if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
+            t.apply(b, callback, numerator, denominator, xwt);
         }
 
+        PerInstantiationScope pis = new PerInstantiationScope(b, xwt, parentPis);
         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();
+            getTemplate(resolveStringToResource((String)children.elementAt(i), xwt)).apply(kid, callback, xwt, pis);
             b.put(b.numChildren(), kid);
         }
 
-        // 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));
-
-        for(int i=0; keys != null && i<keys.length; i++) b.put(keys[i], vals[i]);
+        if (script != null) script.call(new JS.Array(), pis);
 
-        if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
-
-        for(int i=0; postapply != null && i<postapply.length; i++) {
-            postapply[i].apply(b, callback, numerator, denominator, resourceRoot);
-            numerator += postapply[i].numUnits();
-        }
-
-        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) XWT.sleep(0);
+        for(int i=0; keys != null && i<keys.length; i++)
+            if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') b.put(keys[i], pis.get(vals[i]));
+            else b.put(keys[i], vals[i]);
     }
 
 
@@ -190,138 +139,106 @@ 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;
+            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) {
+            switch(state) {
+            case STATE_INITIAL:
                 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;
+                state = STATE_IN_XWT_NODE
                 return;
-        
-            } else if (!templateNodeHasBeenEncountered) {
+
+            case STATE_IN_XWT_NODE:
                 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;
-                    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;
-
+                if (c.localName.equals("doc")) {
+                    // FIXME: ignore
                 } else if (c.localName.equals("static")) {
-                    if (staticNodeHasBeenEncountered)
+                    if (staticscript != null)
                         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
                     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;
-
+                    state = STATE_IN_TEMPLATE_NODE;
                 } else {
                     throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
-
                 }
+                return;
 
-            } else {
-
-                // 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);
-                t2.startLine = getLine();
-                if (!c.localName.equals("box")) t2.preapply = new Template[] { /*c.localName FIXME */ };
-
-                // make the new node the current node
-                t = t2;
+            case STATE_IN_TEMPLATE_NODE:
+                processBodyElement(c);
+                return;
 
+            case STATE_FINISHED_TEMPLATE_NODE:
+                throw new XML.SchemaException("no elements may appear after the <template> node");
             }
-
+        }        
+
+        private void processBodyElement(XML.Element c) {
+            // 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);
+            t2.startLine = getLine();
+            if (!c.localName.equals("box"))
+                t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
+            // make the new node the current node
+            t = t2;
+            
             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]);
+                if (c.keys[i].endsWith(":image")) {
+                    String uri = c.urimap.get(c.keys[i].substring(0, c.keys[i].indexOf(':')));
+                    c.keys[i] = c.keys[i].substring(c.keys[i].lastIndexOf(':') + 1);
+                    c.vals[i] = uri + "." + c.vals[i];
+                }                    
+                if ((c.keys[i].equals("preapply") || c.keys[i].endsWith(":preapply")) && c.localName.equals("template")) {
+                    String uri = "";
+                    if (c.keys[i].endsWith(":preapply")) {
+                        uri = "." + c.urimap.get(c.keys[i].substring(0, c.keys[i].indexOf(':')));
+                        c.keys[i] = c.keys[i].substring(c.keys[i].lastIndexOf(':') + 1);
+                    }
+                    StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
+                    while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
+                    continue;
+                }
+                h.put(c.keys[i], c.vals[i]);
+            }
+
+            Vec v = new Vec(h.size(), 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<h.size(); i++) {
+                if (t.keys[i].equals("thisbox")) {
+                    for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
+                    t.keys[0] = (String)v.elementAt(i);
+                    t.vals[0] = h.get(t.keys[i]);
+                } else {
+                    t.keys[i] = (String)v.elementAt(i);
+                    t.vals[i] = h.get(t.keys[i]);
+                }
             }
 
             for(int i=0; i<t.keys.length; i++) {
@@ -352,19 +269,10 @@ 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;
-                }
             }
         }
 
-        private JS.CompiledFunction genscript(boolean isstatic) {
+        private JS.CompiledFunction parseScript(boolean isstatic) {
             JS.CompiledFunction thisscript = null;
             try {
                 thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
@@ -372,7 +280,6 @@ public class Template {
                 if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
                 thisscript = null;
             }
-
             t.content = null;
             t.content_start = 0;
             t.content_lines = 0;
@@ -380,26 +287,22 @@ public class Template {
         }
 
         public void endElement(XML.Element c) throws XML.SchemaException {
-            if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
-                if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
+            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);
                 }
             }
          }
@@ -409,7 +312,7 @@ public class Template {
             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");
 
-            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;
@@ -424,36 +327,37 @@ public class Template {
             }
         }
 
-        public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
-        }
+        public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
     }
 
     private static class PerInstantiationScope extends JS.Scope {
-        Res resourceRoot = null;
-        public PerInstantiationScope(Scope parentScope, Res resourceRoot) {
+        XWT xwt = null;
+        PerInstantiationScope parentBoxPis = null;
+        void putDollar(String key, Box target) {
+            if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
+            declare("$" + key);
+            put("$" + key, target);
+        }
+        public PerInstantiationScope(Scope parentScope, XWT xwt, PerInstantiationScope parentBoxPis) {
             super(parentScope);
-            this.resourceRoot = resourceRoot;
+            this.parentBoxPis = parentBoxPis;
+            this.xwt = xwt;
         }
         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);
+            if (key.equals("xwt")) return xwt;
+            if (Box.SpecialBoxProperty.specialBoxProperties.get(key) != null) return parentScope.get(key);
+            if (super.has(key)) return super.get(key);
+            Object ret = xwt.rr.get(key);
+            if (ret != null) return ret;
+            throw new JS.Exn("must declare " + key + " before using it!");
         }
         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);
+            if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null) parentScope.put(key, val);
+            else if (super.has(key)) super.put(key, val); 
+            else throw new JS.Exn("must declare " + key + " before using it!");
         }
     }
 
index 22d20a9..19b2237 100644 (file)
@@ -13,9 +13,9 @@ import org.bouncycastle.util.encoders.Base64;
 /** Singleton class that provides all functionality in the xwt.* namespace */
 public final class XWT extends JS.Obj {
 
-    public Res resourceRoot = null;
+    public final Res rr;
+    public XWT(Res rr) { this.rr = rr; }
 
-    public static final XWT singleton = new XWT();
     private final JS xwtMath = new XWTMath();
     private final JS xwtString = new XWTString();
 
@@ -24,6 +24,7 @@ public final class XWT extends JS.Obj {
 
     public Object get(Object name) {
         if (name.equals("alt")) return Surface.alt ? Boolean.TRUE : Boolean.FALSE;
+        else if (name.equals("rr")) return rr;
         else if (name.equals("control")) return Surface.control ? Boolean.TRUE : Boolean.FALSE;
         else if (name.equals("shift")) return Surface.shift ? Boolean.TRUE : Boolean.FALSE;
         else if (name.equals("clipboard")) return Platform.getClipBoard();
@@ -52,7 +53,6 @@ public final class XWT extends JS.Obj {
         if (name.equals("thread") && value != null && value instanceof JS.Callable) ThreadMessage.newthread((JS.Callable)value);
         else if (name.equals("clipboard")) Platform.setClipBoard(value.toString());
         else if (name.equals("proxyAuthorization")) {
-            // FIXME: undocumented, possibly insecure
             HTTP.Proxy.Authorization.authorization = value.toString();
             HTTP.Proxy.Authorization.waitingForUser.release();
         } else super.put(name, value);
@@ -66,6 +66,9 @@ public final class XWT extends JS.Obj {
             Platform.newBrowserWindow(args.elementAt(0).toString());
             return null;
 
+        } else if (method.equals("clone")) {
+            return new XWT((Res)args.elementAt(0));
+
         } else if (method.equals("yield")) {
             if (checkOnly) return Boolean.TRUE;
             sleep(0);