53f449a0c306604ed31dd58fa4545b54d6477471
[org.ibex.core.git] / src / org / xwt / Template.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.util.zip.*;
6 import java.util.*;
7 import java.lang.*;
8 import org.xwt.js.*;
9 import org.xwt.translators.*;
10 import org.xwt.util.*;
11
12 /**
13  *  Encapsulates a template node (the <template/> element of a
14  *  .xwt file, or any child element thereof).
15  *
16  *  Note that the Template instance corresponding to the
17  *  <template/> node carries all the header information -- hence
18  *  some of the instance members are not meaningful on non-root
19  *  Template instances. We refer to these non-root instances as
20  *  <i>anonymous templates</i>.
21  *
22  *  See the XWT reference for information on the order in which
23  *  templates are applied, attributes are put, and scripts are run.
24  */
25 public class Template {
26
27     // Instance Members ///////////////////////////////////////////////////////
28
29     String id = null;                     ///< the id of this box
30     String redirect = null;               ///< the id of the redirect target; only meaningful on a root node
31     private String[] keys;                ///< keys to be "put" to instances of this template; elements correspond to those of vals
32     private Object[] vals;                ///< values to be "put" to instances of this template; elements correspond to those of keys
33     private Vec children = new Vec();     ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
34     private int numunits = -1;            ///< see numUnits(); -1 means that this value has not yet been computed
35
36     private JS script = null;       ///< the script on this node
37     private String fileName = "unknown";  ///< the filename this node came from; used only for debugging
38     private Vec preapply = new Vec();     ///< templates that should be preapplied (in the order of application)
39
40
41     // Instance Members that are only meaningful on root Template //////////////////////////////////////
42
43     private JSScope staticScope = null;   ///< the scope in which the static block is executed
44     private JS staticscript = null;  ///< the script on the static node of this template, null already performed
45
46
47     // Only used during parsing /////////////////////////////////////////////////////////////////
48
49     private StringBuffer content = null;   ///< during XML parsing, this holds partially-read character data; null otherwise
50     private int content_start = 0;         ///< line number of the first line of <tt>content</tt>
51     private int startLine = -1;            ///< the line number that this element starts on
52     private XWT xwt;
53
54
55     // Static data/methods ///////////////////////////////////////////////////////////////////
56
57     public Template(InputStream is, XWT xwt) {
58         this.xwt = xwt;
59         try {
60             new TemplateHelper().parseit(is, this);
61         } catch (Exception e) {
62             throw new RuntimeException(e.toString());
63         }
64     }
65
66     public Template(XWT xwt) {
67         this.xwt = xwt;
68     }
69
70     public static JS resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
71         if (str.indexOf("://") != -1) {
72             if (permitAbsolute) return (Stream)xwt.url2res(str);
73             throw new JSExn("absolute URL " + str + " not permitted here");
74         }
75         // root-relative
76         JS ret = (JS)xwt.getAndTriggerTraps("");
77         while(str.indexOf('.') != -1) {
78             String path = str.substring(0, str.indexOf('.'));
79             str = str.substring(str.indexOf('.') + 1);
80             ret = (JS)ret.get(path);
81         }
82         ret = (JS)ret.get(str);
83         return ret;
84     }
85
86
87     // Methods to apply templates ////////////////////////////////////////////////////////
88
89     /** called before this template is applied or its static object can be externally referenced */
90     JSScope getStatic() throws JSExn {
91         if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
92         if (staticscript == null) return staticScope;
93         JS temp = staticscript;
94         staticscript = null;
95         JS.cloneWithNewParentScope(temp, staticScope).call(null, null, null, null, 0);
96         return staticScope;
97     }
98     
99     /** Applies the template to Box b
100      *  @param pboxes a vector of all box parents on which to put $-references
101      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
102      */
103     void apply(Box b) throws JSExn {
104         try {
105             apply(b, null);
106         } catch (IOException e) {
107             b.clear(b.VISIBLE);
108             b.mark_for_repack();
109             Log.warn(this, e);
110             throw new JSExn(e.toString());
111         } catch (JSExn e) {
112             b.clear(b.VISIBLE);
113             b.mark_for_repack();
114             Log.warn(this, e);
115             throw e;
116         }
117     }
118
119     private void apply(Box b, PerInstantiationJSScope parentPis) throws JSExn, IOException {
120         getStatic();
121
122         if (id != null) parentPis.putDollar(id, b);
123         for(int i=0; i<preapply.size(); i++) {
124             JS templateFunc = resolveStringToResource((String)preapply.elementAt(i), xwt, false);
125             templateFunc.call(b, null, null, null, 1);
126         }
127
128         PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
129
130         for (int i=0; children != null && i<children.size(); i++) {
131             Box kid = new Box();
132             ((Template)children.elementAt(i)).apply(kid, pis);
133             b.putAndTriggerTraps(b.get("numchildren"), kid);
134         }
135
136         if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
137
138         Object key, val;
139         for(int i=0; keys != null && i < keys.length; i++) {
140             if (keys[i] == null) continue;
141             key = keys[i];
142             val = vals[i];
143
144             if ("null".equals(val)) val = null;
145
146             if (val != null && val instanceof String && ((String)val).length() > 0) {
147                 switch (((String)val).charAt(0)) {
148                     case '$':
149                         val = pis.get(val);
150                         if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
151                         break;
152                     case '.':
153                         val = resolveStringToResource(((String)val).substring(1), xwt, true);
154                 }
155             }
156
157             if (val != null && "redirect".equals(key)) {
158                 val = pis.get("$"+val);
159                 if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
160             }
161
162             try {
163                 b.putAndTriggerTraps(key, val);
164             } catch(JSExn e) {
165                 e.addBacktrace(fileName + ":attr-" + key,0);
166                 throw e;
167             }
168         }
169     }
170
171
172
173     // XML Parsing /////////////////////////////////////////////////////////////////
174
175     /** handles XML parsing; builds a Template tree as it goes */
176     static final class TemplateHelper extends XML {
177
178         TemplateHelper() { }
179
180         private int state;
181         private static final int STATE_INITIAL = 0;
182         private static final int STATE_IN_XWT_NODE = 1;
183         private static final int STATE_IN_TEMPLATE_NODE = 2;
184         private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
185
186         private String nameOfHeaderNodeBeingProcessed;
187
188         Vec nodeStack = new Vec();  ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
189         Template t = null;          ///< the template we're currently working on
190
191         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
192         void parseit(InputStream is, Template root) throws XML.Exn, IOException {
193             state = STATE_INITIAL;
194             nameOfHeaderNodeBeingProcessed = null;
195             nodeStack.setSize(0);
196             t = root;
197             parse(new InputStreamReader(is)); 
198         }
199
200         public void startElement(XML.Element c) throws XML.Exn {
201             switch(state) {
202             case STATE_INITIAL:
203                 if (!"xwt".equals(c.getLocalName()))
204                     throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
205                 if (c.getAttrLen() != 0)
206                     throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
207                 state = STATE_IN_XWT_NODE;
208                 return;
209
210             case STATE_IN_XWT_NODE:
211                 if (nameOfHeaderNodeBeingProcessed != null)
212                     throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
213                 nameOfHeaderNodeBeingProcessed = c.getLocalName();
214                 //#switch(c.getLocalName())
215                 case "doc":
216                     // FEATURE
217                     return;
218                 case "static":
219                     if (t.staticscript != null)
220                         throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
221                     if (c.getAttrLen() > 0)
222                         throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
223                     return;
224                 case "template":
225                     t.startLine = getLine();
226                     state = STATE_IN_TEMPLATE_NODE;
227                     processBodyElement(c);
228                     return;
229                 //#end
230                 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
231
232             case STATE_IN_TEMPLATE_NODE:
233                 // push the last node we were in onto the stack
234                 nodeStack.addElement(t);
235                 // instantiate a new node, and set its fileName/importlist/preapply
236                 Template t2 = new Template(t.xwt);
237                 t2.startLine = getLine();
238                 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
239                     t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
240                 // make the new node the current node
241                 t = t2;
242                 processBodyElement(c);
243                 return;
244
245             case STATE_FINISHED_TEMPLATE_NODE:
246                 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
247             }
248         }        
249
250         private void processBodyElement(XML.Element c) {
251             Vec keys = new Vec(c.getAttrLen());
252             Vec vals = new Vec(c.getAttrLen());
253
254             // process attributes into Vecs, dealing with any XML Namespaces in the process
255             ATTR: for (int i=0; i < c.getAttrLen(); i++) {
256                 //#switch(c.getAttrKey(i))
257                 case "preapply":
258                     String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
259                     StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
260                     while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
261                     continue ATTR;
262
263                 case "id":
264                     t.id = c.getAttrVal(i).toString().intern();
265                     continue ATTR;
266                 //#end
267
268                 // treat value starting with '.' as resource reference
269                 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
270                 keys.addElement(c.getAttrKey(i));
271                 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
272             }
273
274             if (keys.size() == 0) return;
275
276             // sort the attributes lexicographically
277             Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
278                 return ((String)a).compareTo((String)b);
279             } });
280
281             t.keys = new String[keys.size()];
282             t.vals = new Object[vals.size()];
283             keys.copyInto(t.keys);
284             vals.copyInto(t.vals);
285
286             // convert attributes to appropriate types and intern strings
287             for(int i=0; i<t.keys.length; i++) {
288                 t.keys[i] = t.keys[i].intern();
289
290                 String valString = t.vals[i].toString();
291                 
292                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
293                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
294                 else if (valString.equals("null")) t.vals[i] = null;
295                 else {
296                     boolean hasNonNumeral = false;
297                     boolean periodUsed = false;
298                     for(int j=0; j<valString.length(); j++)
299                         if (j == 0 && valString.charAt(j) == '-') {
300                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
301                             periodUsed = true;
302                         } else if (!Character.isDigit(valString.charAt(j))) {
303                             hasNonNumeral = true;
304                             break;
305                         }
306                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
307                     else t.vals[i] = valString.intern();
308                 }
309             }
310         }
311
312         private JS parseScript(boolean isstatic) throws IOException {
313             JS thisscript = null;
314             String contentString = t.content.toString();
315             if (contentString.trim().length() > 0)
316                 thisscript = JS.fromReader(t.fileName + (isstatic ? "._" : ""),
317                                                    t.content_start,
318                                                    new StringReader(contentString));
319             t.content = null;
320             t.content_start = 0;
321             return thisscript;
322         }
323
324         public void endElement(XML.Element c) throws XML.Exn, IOException {
325             if (state == STATE_IN_XWT_NODE) {
326                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
327                 nameOfHeaderNodeBeingProcessed = null;
328                 
329             } else if (state == STATE_IN_TEMPLATE_NODE) {
330                 if (t.content != null) t.script = parseScript(false);
331                 if (nodeStack.size() == 0) {
332                     // </template>
333                     state = STATE_FINISHED_TEMPLATE_NODE;
334                     
335                 } else {
336                     // add this template as a child of its parent
337                     Template oldt = t;
338                     t = (Template)nodeStack.lastElement();
339                     nodeStack.setSize(nodeStack.size() - 1);
340                     t.children.addElement(oldt);
341
342                     int oldt_lines = getLine() - oldt.startLine;
343                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
344                 }
345             }
346          }
347
348         public void characters(char[] ch, int start, int length) throws XML.Exn {
349             // invoke the no-tab crusade
350             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
351                 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
352
353             if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
354                 if (t.content == null) {
355                     t.content_start = getLine();
356                     t.content = new StringBuffer();
357                 }
358
359                 t.content.append(ch, start, length);
360
361             } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
362                 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
363             }
364         }
365
366         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
367     }
368
369     private static class PerInstantiationJSScope extends JSScope {
370         XWT xwt = null;
371         PerInstantiationJSScope parentBoxPis = null;
372         JSScope myStatic = null;
373         void putDollar(String key, Box target) throws JSExn {
374             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
375             declare("$" + key);
376             put("$" + key, target);
377         }
378         public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
379             super(parentScope);
380             this.parentBoxPis = parentBoxPis;
381             this.xwt = xwt;
382             this.myStatic = myStatic;
383         }
384         public Object get(Object key) throws JSExn {
385             if (super.has(key)) return super.get(key);
386             if (key.equals("xwt")) return xwt;
387             if (key.equals("")) return xwt.get("");
388             if (key.equals("static")) return myStatic;
389             return super.get(key);
390         }
391         public void put(Object key, Object val) throws JSExn {
392             if (super.has(key)) super.put(key, val);
393             else super.put(key, val);
394         }
395     }
396
397 }
398
399