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