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