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