87d5a63080198336b46b88741a75d42f2fe315c8
[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) { throw new JSExn(e.toString());
66         }
67     }
68
69     public static Stream resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
70         // URL
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
76         // root-relative
77         Stream ret = xwt.rr;
78         while(str.indexOf('.') != -1) {
79             String path = str.substring(0, str.indexOf('.'));
80             str = str.substring(str.indexOf('.') + 1);
81             ret = (Stream)ret.get(path);
82         }
83         ret = (Stream)ret.get(str);
84         return ret;
85     }
86
87
88     // Methods to apply templates ////////////////////////////////////////////////////////
89
90     private Template(Stream r) {
91         this.r = r;
92         String f = r.toString();
93         if (f != null && !f.equals(""))
94             fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
95     }
96
97     /** called before this template is applied or its static object can be externally referenced */
98     JSScope getStatic(XWT xwt) throws JSExn {
99         if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
100         if (staticscript == null) return staticScope;
101         JSFunction temp = staticscript;
102         staticscript = null;
103         temp.cloneWithNewParentScope(staticScope).call(null, null, null, null, 0);
104         return staticScope;
105     }
106     
107     /** Applies the template to Box b
108      *  @param pboxes a vector of all box parents on which to put $-references
109      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
110      */
111     void apply(Box b, XWT xwt) {
112         try {
113             apply(b, xwt, null);
114         } catch (JSExn e) {
115             b.clear(b.VISIBLE);
116             b.mark_for_repack();
117             Log.info(Template.class, "WARNING: exception (below) thrown during application of template;");
118             Log.info(Template.class, "         setting visibility of target box to \"false\"");
119             JS.log(e);
120         }
121     }
122
123
124     private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
125         getStatic(xwt);
126
127         if (id != null) parentPis.putDollar(id, b);
128         for(int i=0; i<preapply.size(); i++) {
129             Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt, false));
130             if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
131             t.apply(b, xwt);
132         }
133
134         PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
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(JS.N(b.treeSize()), 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             b.putAndTriggerTraps(key, val);
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.r);
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 JSFunction parseScript(boolean isstatic) throws IOException {
313             JSFunction thisscript = null;
314             String contentString = t.content.toString();
315             if (contentString.trim().length() > 0)
316                 thisscript = JSFunction.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.rr;
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