2004/01/07 20:37:32
[org.ibex.core.git] / src / org / xwt / Template.java
index a95ec38..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.*;
 
 /**
@@ -39,7 +40,7 @@ public class Template {
 
     // Instance Members that are only meaningful on root Template //////////////////////////////////////
 
-    private JSScope staticJSScope = null;   ///< the scope in which the static block is executed
+    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
 
 
@@ -48,44 +49,46 @@ public class Template {
     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 Res r;                   ///< the resource we came from
+    private final Stream r;                   ///< the resource we came from
 
 
     // Static data/methods ///////////////////////////////////////////////////////////////////
 
-    public static Template getTemplate(Res r) throws JSExn {
+    // 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);
             new TemplateHelper().parseit(r.getInputStream(), r.t);
             return r.t;
-        } catch (Exception e) { throw new JSExn(e.toString());
+        } catch (Exception e) {
+            throw new JSExn("Error reading template stream: " + r + "\n" + e.toString());
         }
     }
 
-    public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
+    public static Stream resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
         // URL
         if (str.indexOf("://") != -1) {
-            if (permitAbsolute) return (Res)xwt.url2res(str);
+            if (permitAbsolute) return (Stream)xwt.url2res(str);
             throw new JSExn("absolute URL " + str + " not permitted here");
         }
 
         // root-relative
-        Res ret = xwt.rr;
+        Stream 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 = (Stream)ret.get(path);
         }
-        ret = (Res)ret.get(str);
+        ret = (Stream)ret.get(str);
         return ret;
     }
 
 
     // Methods to apply templates ////////////////////////////////////////////////////////
 
-    private Template(Res r) {
+    private Template(Stream r) {
         this.r = r;
         String f = r.toString();
         if (f != null && !f.equals(""))
@@ -93,23 +96,32 @@ public class Template {
     }
 
     /** called before this template is applied or its static object can be externally referenced */
-    JSScope getStatic() throws JSExn {
-        if (staticJSScope == null) staticJSScope = new JSScope(null);
-        if (staticscript == null) return staticJSScope;
+    JSScope getStatic(XWT xwt) throws JSExn {
+        if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
+        if (staticscript == null) return staticScope;
         JSFunction temp = staticscript;
         staticscript = null;
-        temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
-        return staticJSScope;
+        temp.cloneWithNewParentScope(staticScope).call(null, null, null, null, 0);
+        return staticScope;
     }
     
     /** Applies the template to Box b
      *  @param pboxes a vector of all box parents on which to put $-references
      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
      */
-    void apply(Box b, XWT xwt) throws JSExn { apply(b, xwt, null); }
-    void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
+    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();
+
+    private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
+        getStatic(xwt);
 
         if (id != null) parentPis.putDollar(id, b);
         for(int i=0; i<preapply.size(); i++) {
@@ -118,29 +130,47 @@ public class Template {
             t.apply(b, xwt);
         }
 
-        PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticJSScope);
+        PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
+
         for (int i=0; children != null && i<children.size(); i++) {
             Box kid = new Box();
             ((Template)children.elementAt(i)).apply(kid, xwt, pis);
-            b.putAndTriggerTraps(JS.N(b.treeSize()), kid);
+            b.putAndTriggerTraps(b.get("numchildren"), kid);
         }
 
         if (script != null) script.cloneWithNewParentScope(pis).call(null, null, null, null, 0);
 
-        for(int i=0; keys != null && i<keys.length; i++)
-            if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') {
-                Object rbox = pis.get(vals[i]);
-                if (rbox == null) Log.log(this, "unknown box id '"+vals[i]+"' referenced in XML attribute");
-                else b.putAndTriggerTraps(keys[i], rbox);
+        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 = resolveStringToResource(((String)val).substring(1), xwt, true);
+                }
+            }
+
+            if (val != null && "redirect".equals(key)) {
+                val = pis.get("$"+val);
+                if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
             }
-            else if ("image".equals(keys[i])) b.putAndTriggerTraps("image", resolveStringToResource((String)vals[i], xwt, true));
-            else if ("redirect".equals(keys[i])) {
-                if (vals[i] == null || "null".equals(vals[i])) b.putAndTriggerTraps("redirect", null);
-                Object rbox = pis.get("$"+vals[i]);
-                if (rbox == null) Log.log(this, "redirect target '"+vals[i]+"' not found");
-                else b.putAndTriggerTraps("redirect", rbox);
+
+            try {
+                b.putAndTriggerTraps(key, val);
+            } catch(JSExn e) {
+                e.addBacktrace(fileName + ":attr-" + key,0);
+                throw e;
             }
-            else if (keys[i] != null) b.putAndTriggerTraps(keys[i], vals[i]);
+        }
     }
 
 
@@ -164,7 +194,7 @@ public class Template {
         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 {
+        void parseit(InputStream is, Template root) throws XML.Exn, IOException {
             state = STATE_INITIAL;
             nameOfHeaderNodeBeingProcessed = null;
             nodeStack.setSize(0);
@@ -172,32 +202,37 @@ public class Template {
             parse(new InputStreamReader(is)); 
         }
 
-        public void startElement(XML.Element c) throws XML.SchemaException {
+        public void startElement(XML.Element c) throws XML.Exn {
             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");
+                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;
 
             case STATE_IN_XWT_NODE:
-                if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
-                nameOfHeaderNodeBeingProcessed = c.localName;
-                if (c.localName.equals("doc")) {
+                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
-                } else if (c.localName.equals("static")) {
+                    return;
+                case "static":
                     if (t.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");
-                } else if (c.localName.equals("template")) {
+                        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;
+                case "template":
                     t.startLine = getLine();
                     state = STATE_IN_TEMPLATE_NODE;
                     processBodyElement(c);
-                } else {
-                    throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
-                }
-                return;
+                    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
@@ -205,64 +240,56 @@ public class Template {
                 // instantiate a new node, and set its fileName/importlist/preapply
                 Template t2 = new Template(t.r);
                 t2.startLine = getLine();
-                if (!c.localName.equals("box") && !c.localName.equals("template"))
-                    t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
+                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.SchemaException("no elements may appear after the <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) {
-            Hash h = new Hash(c.len * 2, 3);
-
-            // WARNING: c.keys.length != c.len; USE c.len
-            for(int i=0; i<c.len; i++) {
-                if (c.keys[i] == null) throw new RuntimeException("XML parser returned a null key position="+i);
-                if (c.keys[i].equals("font") && c.uris[i] != null) c.vals[i] = c.uris[i] + "." + c.vals[i];
-                if (c.keys[i].equals("preapply")) {
-                    // process preapply and 'remove' from array
-                    String uri = c.uris[i] == null ? "" : c.uris[i] + '.';
-                    StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
+            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;
 
-                    if (i < c.len - 1) { // not the last attribute
-                        c.keys[i] = c.keys[c.len - 1];
-                        c.vals[i] = c.vals[c.len - 1];
-                        c.uris[i] = c.uris[c.len - 1];
-                    }
-                    c.len--; i--;
-                    continue;
-                }
-                h.put(c.keys[i], c.vals[i]);
-            }
-            t.keys = new String[h.size()];
-            t.vals = new Object[h.size()];
-
-            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 (c.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[0]);
-                } else {
-                    t.keys[i] = (String)v.elementAt(i);
-                    t.vals[i] = h.get(t.keys[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));
             }
 
-            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;
-                }
+            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);
+            } });
 
+            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();
@@ -299,7 +326,7 @@ public class Template {
             return thisscript;
         }
 
-        public void endElement(XML.Element c) throws XML.SchemaException, IOException {
+        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;
@@ -323,10 +350,10 @@ public class Template {
             }
          }
 
-        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) || state == STATE_IN_TEMPLATE_NODE) {
                 if (t.content == null) {
@@ -336,12 +363,12 @@ public class Template {
 
                 t.content.append(ch, start, length);
 
-            } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
-                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 PerInstantiationJSScope extends JSScope {
@@ -362,7 +389,7 @@ public class Template {
         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("")) return xwt.rr;
             if (key.equals("static")) return myStatic;
             return super.get(key);
         }