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