2003/11/17 10:18: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.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 content_lines = 0;         ///< number of lines in <tt>content</tt>
51     private int startLine = -1;            ///< the line number that this element starts on
52     private final Res r;                   ///< the resource we came from
53
54
55     // Static data/methods ///////////////////////////////////////////////////////////////////
56
57     public static Template getTemplate(Res r) {
58         try {
59             r = r.addExtension(".xwt");
60             if (r.t != null) return r.t;
61             r.t = new Template(r);
62             new TemplateHelper().parseit(r.getInputStream(), r.t);
63             return r.t;
64         } catch (Exception e) {
65             if (Log.on) Log.log(r.t == null ? "null" : r.t.fileName, e);
66             return null;
67         }
68     }
69
70     public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) {
71         // URL
72         if (str.indexOf("://") != -1) {
73             // FIXME
74             //if (permitAbsolute) return Res.fromString(str);
75             Log.log(Template.class, "absolute URL " + str + " not permitted here");
76             return null;
77         }
78
79         // root-relative
80         Res ret = xwt.rr;
81         while(str.indexOf('.') != -1) {
82             String path = str.substring(0, str.indexOf('.'));
83             str = str.substring(str.indexOf('.') + 1);
84             ret = (Res)ret.get(path);
85         }
86         ret = (Res)ret.get(str);
87         return ret;
88     }
89
90
91     // Methods to apply templates ////////////////////////////////////////////////////////
92
93     private Template(Res r) { this.r = r; }
94
95     /** called before this template is applied or its static object can be externally referenced */
96     JSScope getStatic() {
97         if (staticJSScope == null) staticJSScope = new JSScope(null);
98         if (staticscript == null) return staticJSScope;
99         JSFunction temp = staticscript;
100         staticscript = null;
101         temp.cloneWithNewParentJSScope(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) { apply(b, xwt, null); }
110     void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) {
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.putAndTriggerJSTraps(JS.N(b.numchildren), kid);
126         }
127
128         if (script != null) script.cloneWithNewParentJSScope(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) == '$') b.putAndTriggerJSTraps(keys[i], pis.get(vals[i]));
132             else if ("image".equals(keys[i])) b.putAndTriggerJSTraps("image", resolveStringToResource((String)vals[i], xwt, true));
133             else if (keys[i] != null) b.putAndTriggerJSTraps(keys[i], vals[i]);
134     }
135
136
137
138     // XML Parsing /////////////////////////////////////////////////////////////////
139
140     /** handles XML parsing; builds a Template tree as it goes */
141     static final class TemplateHelper extends XML {
142
143         TemplateHelper() { }
144
145         private int state;
146         private static final int STATE_INITIAL = 0;
147         private static final int STATE_IN_XWT_NODE = 1;
148         private static final int STATE_IN_TEMPLATE_NODE = 2;
149         private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
150
151         private String nameOfHeaderNodeBeingProcessed;
152
153         Vec nodeStack = new Vec();  ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
154         Template t = null;          ///< the template we're currently working on
155
156         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
157         void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
158             state = STATE_INITIAL;
159             nameOfHeaderNodeBeingProcessed = null;
160             nodeStack.setSize(0);
161             t = root;
162             parse(new InputStreamReader(is)); 
163         }
164
165         public void startElement(XML.Element c) throws XML.SchemaException {
166             switch(state) {
167             case STATE_INITIAL:
168                 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
169                 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
170                 state = STATE_IN_XWT_NODE;
171                 return;
172
173             case STATE_IN_XWT_NODE:
174                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
175                 nameOfHeaderNodeBeingProcessed = c.localName;
176                 if (c.localName.equals("doc")) {
177                     // FEATURE
178                 } else if (c.localName.equals("static")) {
179                     if (t.staticscript != null)
180                         throw new XML.SchemaException("the <static> header node may not appear more than once");
181                     if (c.len > 0)
182                         throw new XML.SchemaException("the <static> node may not have attributes");
183                 } else if (c.localName.equals("template")) {
184                     t.startLine = getLine();
185                     state = STATE_IN_TEMPLATE_NODE;
186                     processBodyElement(c);
187                 } else {
188                     throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
189                 }
190                 return;
191
192             case STATE_IN_TEMPLATE_NODE:
193                 // push the last node we were in onto the stack
194                 nodeStack.addElement(t);
195                 // instantiate a new node, and set its fileName/importlist/preapply
196                 Template t2 = new Template(t.r);
197                 t2.startLine = getLine();
198                 if (!c.localName.equals("box") && !c.localName.equals("template"))
199                     t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
200                 // make the new node the current node
201                 t = t2;
202                 processBodyElement(c);
203                 return;
204
205             case STATE_FINISHED_TEMPLATE_NODE:
206                 throw new XML.SchemaException("no elements may appear after the <template> node");
207             }
208         }        
209
210         private void processBodyElement(XML.Element c) {
211             Hash h = new Hash(c.len * 2, 3);
212             for(int i=0; i<c.len; i++) {
213                 if (c.keys[i] == null) continue;
214                 if (c.keys[i].endsWith(":image")) {
215                     String uri = (String)c.urimap.get(c.keys[i].substring(0, c.keys[i].indexOf(':')));
216                     c.keys[i] = c.keys[i].substring(c.keys[i].lastIndexOf(':') + 1);
217                     c.vals[i] = uri + "." + c.vals[i];
218                 }                    
219                 if ((c.keys[i].equals("preapply") || c.keys[i].endsWith(":preapply")) && c.localName.equals("template")) {
220                     String uri = "";
221                     if (c.keys[i].endsWith(":preapply")) {
222                         uri = "." + c.urimap.get(c.keys[i].substring(0, c.keys[i].indexOf(':')));
223                         c.keys[i] = c.keys[i].substring(c.keys[i].lastIndexOf(':') + 1);
224                     }
225                     StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
226                     while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
227                     c.keys[i] = c.keys[c.keys.length - 1];
228                     c.vals[i] = c.vals[c.vals.length - 1];
229                     i--;
230                     continue;
231                 }
232                 h.put(c.keys[i], c.vals[i]);
233             }
234             t.keys = new String[h.size()];
235             t.vals = new Object[h.size()];
236
237             Vec v = new Vec(h.size(), c.keys);
238             v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
239             for(int i=0; i<h.size(); i++) {
240                 if (c.keys[i].equals("thisbox")) {
241                     for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
242                     t.keys[0] = (String)v.elementAt(i);
243                     t.vals[0] = h.get(t.keys[0]);
244                 } else {
245                     t.keys[i] = (String)v.elementAt(i);
246                     t.vals[i] = h.get(t.keys[i]);
247                 }
248             }
249
250             for(int i=0; i<t.keys.length; i++) {
251                 if (t.keys[i].equals("id")) {
252                     t.id = t.vals[i].toString().intern();
253                     t.keys[i] = null;
254                     continue;
255                 }
256
257                 t.keys[i] = t.keys[i].intern();
258
259                 String valString = t.vals[i].toString();
260                 
261                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
262                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
263                 else if (valString.equals("null")) t.vals[i] = null;
264                 else {
265                     boolean hasNonNumeral = false;
266                     boolean periodUsed = false;
267                     for(int j=0; j<valString.length(); j++)
268                         if (j == 0 && valString.charAt(j) == '-') {
269                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
270                             periodUsed = true;
271                         } else if (!Character.isDigit(valString.charAt(j))) {
272                             hasNonNumeral = true;
273                             break;
274                         }
275                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
276                     else t.vals[i] = valString.intern();
277                 }
278             }
279         }
280
281         private JSFunction parseScript(boolean isstatic) {
282             JSFunction thisscript = null;
283             try {
284                 String contentString = t.content.toString();
285                 if (contentString.trim().length() > 0)
286                     thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(contentString));
287             } catch (IOException ioe) {
288                 if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
289                 thisscript = null;
290             }
291             t.content = null;
292             t.content_start = 0;
293             t.content_lines = 0;
294             return thisscript;
295         }
296
297         public void endElement(XML.Element c) throws XML.SchemaException {
298             if (state == STATE_IN_XWT_NODE) {
299                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
300                 nameOfHeaderNodeBeingProcessed = null;
301                 
302             } else if (state == STATE_IN_TEMPLATE_NODE) {
303                 if (t.content != null) t.script = parseScript(false);
304                 if (nodeStack.size() == 0) {
305                     // </template>
306                     state = STATE_FINISHED_TEMPLATE_NODE;
307                     
308                 } else {
309                     // add this template as a child of its parent
310                     Template oldt = t;
311                     t = (Template)nodeStack.lastElement();
312                     nodeStack.setSize(nodeStack.size() - 1);
313                     t.children.addElement(oldt);
314                 }
315             }
316          }
317
318         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
319             // invoke the no-tab crusade
320             for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
321                 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
322
323             if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
324                 if (t.content == null) {
325                     t.content_start = getLine();
326                     t.content_lines = 0;
327                     t.content = new StringBuffer();
328                 }
329
330                 t.content.append(ch, start, length);
331                 t.content_lines++;
332
333             } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
334                 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
335             }
336         }
337
338         public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
339     }
340
341     private static class PerInstantiationJSScope extends JSScope {
342         XWT xwt = null;
343         PerInstantiationJSScope parentBoxPis = null;
344         JSScope myStatic = null;
345         void putDollar(String key, Box target) {
346             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
347             declare("$" + key);
348             put("$" + key, target);
349         }
350         public PerInstantiationJSScope(JSScope parentJSScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
351             super(parentJSScope);
352             this.parentBoxPis = parentBoxPis;
353             this.xwt = xwt;
354             this.myStatic = myStatic;
355         }
356         public Object get(Object key) {
357             if (super.has(key)) return super.get(key);
358             if (key.equals("xwt")) return xwt;
359             if (key.equals("static")) return myStatic;
360             return super.get(key);
361         }
362         public void put(Object key, Object val) {
363             if (super.has(key)) super.put(key, val);
364             else super.put(key, val);
365         }
366     }
367
368 }
369
370