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