2003/12/16 23:01:41
[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) {
110         try {
111             apply(b, xwt, null);
112         } catch (JSExn e) {
113             b.clear(b.VISIBLE);
114             b.mark_for_repack();
115             Log.log(Template.class, "WARNING: exception (below) thrown during application of template;");
116             Log.log(Template.class, "         setting visibility of target box to \"false\"");
117             Log.logJS(e);
118         }
119     }
120
121
122     private 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 in XML attribute");
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) throws IOException {
303             JSFunction thisscript = null;
304             String contentString = t.content.toString();
305             if (contentString.trim().length() > 0)
306                 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
307                                                    t.content_start,
308                                                    new StringReader(contentString));
309             t.content = null;
310             t.content_start = 0;
311             return thisscript;
312         }
313
314         public void endElement(XML.Element c) throws XML.SchemaException, IOException {
315             if (state == STATE_IN_XWT_NODE) {
316                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
317                 nameOfHeaderNodeBeingProcessed = null;
318                 
319             } else if (state == STATE_IN_TEMPLATE_NODE) {
320                 if (t.content != null) t.script = parseScript(false);
321                 if (nodeStack.size() == 0) {
322                     // </template>
323                     state = STATE_FINISHED_TEMPLATE_NODE;
324                     
325                 } else {
326                     // add this template as a child of its parent
327                     Template oldt = t;
328                     t = (Template)nodeStack.lastElement();
329                     nodeStack.setSize(nodeStack.size() - 1);
330                     t.children.addElement(oldt);
331
332                     int oldt_lines = getLine() - oldt.startLine;
333                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
334                 }
335             }
336          }
337
338         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
339             // invoke the no-tab crusade
340             for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
341                 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
342
343             if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
344                 if (t.content == null) {
345                     t.content_start = getLine();
346                     t.content = new StringBuffer();
347                 }
348
349                 t.content.append(ch, start, length);
350
351             } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
352                 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
353             }
354         }
355
356         public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
357     }
358
359     private static class PerInstantiationJSScope extends JSScope {
360         XWT xwt = null;
361         PerInstantiationJSScope parentBoxPis = null;
362         JSScope myStatic = null;
363         void putDollar(String key, Box target) throws JSExn {
364             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
365             declare("$" + key);
366             put("$" + key, target);
367         }
368         public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
369             super(parentScope);
370             this.parentBoxPis = parentBoxPis;
371             this.xwt = xwt;
372             this.myStatic = myStatic;
373         }
374         public Object get(Object key) throws JSExn {
375             if (super.has(key)) return super.get(key);
376             if (key.equals("xwt")) return xwt;
377             if (key.equals("")) return xwt.rr;
378             if (key.equals("static")) return myStatic;
379             return super.get(key);
380         }
381         public void put(Object key, Object val) throws JSExn {
382             if (super.has(key)) super.put(key, val);
383             else super.put(key, val);
384         }
385     }
386
387 }
388
389