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