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