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