2003/12/29 03:27:43
[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.translators.*;
10 import org.xwt.util.*;
11
12 /**
13  *  Encapsulates a template node (the <template/> element of a
14  *  .xwt file, or any child element thereof).
15  *
16  *  Note that the Template instance corresponding to the
17  *  <template/> node carries all the header information -- hence
18  *  some of the instance members are not meaningful on non-root
19  *  Template instances. We refer to these non-root instances as
20  *  <i>anonymous templates</i>.
21  *
22  *  See the XWT reference for information on the order in which
23  *  templates are applied, attributes are put, and scripts are run.
24  */
25 public class Template {
26
27     // Instance Members ///////////////////////////////////////////////////////
28
29     String id = null;                     ///< the id of this box
30     String redirect = null;               ///< the id of the redirect target; only meaningful on a root node
31     private String[] keys;                ///< keys to be "put" to instances of this template; elements correspond to those of vals
32     private Object[] vals;                ///< values to be "put" to instances of this template; elements correspond to those of keys
33     private Vec children = new Vec();     ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
34     private int numunits = -1;            ///< see numUnits(); -1 means that this value has not yet been computed
35
36     private JSFunction script = null;       ///< the script on this node
37     private String fileName = "unknown";  ///< the filename this node came from; used only for debugging
38     private Vec preapply = new Vec();     ///< templates that should be preapplied (in the order of application)
39
40
41     // Instance Members that are only meaningful on root Template //////////////////////////////////////
42
43     private JSScope staticJSScope = null;   ///< the scope in which the static block is executed
44     private JSFunction staticscript = null;  ///< the script on the static node of this template, null already performed
45
46
47     // Only used during parsing /////////////////////////////////////////////////////////////////
48
49     private StringBuffer content = null;   ///< during XML parsing, this holds partially-read character data; null otherwise
50     private int content_start = 0;         ///< line number of the first line of <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) throws JSExn {
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) { throw new JSExn(e.toString());
65         }
66     }
67
68     public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
69         // URL
70         if (str.indexOf("://") != -1) {
71             if (permitAbsolute) return (Res)xwt.url2res(str);
72             throw new JSExn("absolute URL " + str + " not permitted here");
73         }
74
75         // root-relative
76         Res ret = xwt.rr;
77         while(str.indexOf('.') != -1) {
78             String path = str.substring(0, str.indexOf('.'));
79             str = str.substring(str.indexOf('.') + 1);
80             ret = (Res)ret.get(path);
81         }
82         ret = (Res)ret.get(str);
83         return ret;
84     }
85
86
87     // Methods to apply templates ////////////////////////////////////////////////////////
88
89     private Template(Res r) {
90         this.r = r;
91         String f = r.toString();
92         if (f != null && !f.equals(""))
93             fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
94     }
95
96     /** called before this template is applied or its static object can be externally referenced */
97     JSScope getStatic() throws JSExn {
98         if (staticJSScope == null) staticJSScope = new JSScope(null);
99         if (staticscript == null) return staticJSScope;
100         JSFunction temp = staticscript;
101         staticscript = null;
102         temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
103         return staticJSScope;
104     }
105     
106     /** Applies the template to Box b
107      *  @param pboxes a vector of all box parents on which to put $-references
108      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
109      */
110     void apply(Box b, XWT xwt) {
111         try {
112             apply(b, xwt, null);
113         } catch (JSExn e) {
114             b.clear(b.VISIBLE);
115             b.mark_for_repack();
116             Log.info(Template.class, "WARNING: exception (below) thrown during application of template;");
117             Log.info(Template.class, "         setting visibility of target box to \"false\"");
118             JS.log(e);
119         }
120     }
121
122
123     private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
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         Object key, val;
143         for(int i=0; keys != null && i < keys.length; i++) {
144             if (keys[i] == null) continue;
145             key = keys[i];
146             val = vals[i];
147
148             if ("null".equals(val)) val = null;
149
150             if (val != null && val instanceof String && ((String)val).length() > 0) {
151                 switch (((String)val).charAt(0)) {
152                     case '$':
153                         val = pis.get(val);
154                         if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
155                         break;
156                     case '.':
157                         val = resolveStringToResource(((String)val).substring(1), xwt, true);
158                 }
159             }
160
161             if (val != null && "redirect".equals(key)) {
162                 val = pis.get("$"+val);
163                 if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
164             }
165
166             b.putAndTriggerTraps(key, val);
167         }
168     }
169
170
171
172     // XML Parsing /////////////////////////////////////////////////////////////////
173
174     /** handles XML parsing; builds a Template tree as it goes */
175     static final class TemplateHelper extends XML {
176
177         TemplateHelper() { }
178
179         private int state;
180         private static final int STATE_INITIAL = 0;
181         private static final int STATE_IN_XWT_NODE = 1;
182         private static final int STATE_IN_TEMPLATE_NODE = 2;
183         private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
184
185         private String nameOfHeaderNodeBeingProcessed;
186
187         Vec nodeStack = new Vec();  ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
188         Template t = null;          ///< the template we're currently working on
189
190         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
191         void parseit(InputStream is, Template root) throws XML.Exn, IOException {
192             state = STATE_INITIAL;
193             nameOfHeaderNodeBeingProcessed = null;
194             nodeStack.setSize(0);
195             t = root;
196             parse(new InputStreamReader(is)); 
197         }
198
199         public void startElement(XML.Element c) throws XML.Exn {
200             switch(state) {
201             case STATE_INITIAL:
202                 if (!"xwt".equals(c.getLocalName()))
203                     throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
204                 if (c.getAttrLen() != 0)
205                     throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
206                 state = STATE_IN_XWT_NODE;
207                 return;
208
209             case STATE_IN_XWT_NODE:
210                 if (nameOfHeaderNodeBeingProcessed != null)
211                     throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
212                 nameOfHeaderNodeBeingProcessed = c.getLocalName();
213                 //#switch(c.getLocalName())
214                 case "doc":
215                     // FEATURE
216                     return;
217                 case "static":
218                     if (t.staticscript != null)
219                         throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
220                     if (c.getAttrLen() > 0)
221                         throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
222                     return;
223                 case "template":
224                     t.startLine = getLine();
225                     state = STATE_IN_TEMPLATE_NODE;
226                     processBodyElement(c);
227                     return;
228                 //#end
229                 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
230
231             case STATE_IN_TEMPLATE_NODE:
232                 // push the last node we were in onto the stack
233                 nodeStack.addElement(t);
234                 // instantiate a new node, and set its fileName/importlist/preapply
235                 Template t2 = new Template(t.r);
236                 t2.startLine = getLine();
237                 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
238                     t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
239                 // make the new node the current node
240                 t = t2;
241                 processBodyElement(c);
242                 return;
243
244             case STATE_FINISHED_TEMPLATE_NODE:
245                 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
246             }
247         }        
248
249         private void processBodyElement(XML.Element c) {
250             Vec keys = new Vec(c.getAttrLen());
251             Vec vals = new Vec(c.getAttrLen());
252
253             // process attributes into Vecs, dealing with any XML Namespaces in the process
254             ATTR: for (int i=0; i < c.getAttrLen(); i++) {
255                 //#switch(c.getAttrKey(i))
256                 case "preapply":
257                     String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
258                     StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
259                     while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
260                     continue ATTR;
261
262                 case "id":
263                     t.id = c.getAttrVal(i).toString().intern();
264                     continue ATTR;
265                 //#end
266
267                 // treat value starting with '.' as resource reference
268                 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
269                 keys.addElement(c.getAttrKey(i));
270                 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
271             }
272
273             if (keys.size() == 0) return;
274
275             // sort the attributes lexicographically
276             Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
277                 return ((String)a).compareTo((String)b);
278             } });
279
280             t.keys = new String[keys.size()];
281             t.vals = new Object[vals.size()];
282             keys.copyInto(t.keys);
283             vals.copyInto(t.vals);
284
285             // convert attributes to appropriate types and intern strings
286             for(int i=0; i<t.keys.length; i++) {
287                 t.keys[i] = t.keys[i].intern();
288
289                 String valString = t.vals[i].toString();
290                 
291                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
292                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
293                 else if (valString.equals("null")) t.vals[i] = null;
294                 else {
295                     boolean hasNonNumeral = false;
296                     boolean periodUsed = false;
297                     for(int j=0; j<valString.length(); j++)
298                         if (j == 0 && valString.charAt(j) == '-') {
299                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
300                             periodUsed = true;
301                         } else if (!Character.isDigit(valString.charAt(j))) {
302                             hasNonNumeral = true;
303                             break;
304                         }
305                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
306                     else t.vals[i] = valString.intern();
307                 }
308             }
309         }
310
311         private JSFunction parseScript(boolean isstatic) throws IOException {
312             JSFunction thisscript = null;
313             String contentString = t.content.toString();
314             if (contentString.trim().length() > 0)
315                 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
316                                                    t.content_start,
317                                                    new StringReader(contentString));
318             t.content = null;
319             t.content_start = 0;
320             return thisscript;
321         }
322
323         public void endElement(XML.Element c) throws XML.Exn, IOException {
324             if (state == STATE_IN_XWT_NODE) {
325                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
326                 nameOfHeaderNodeBeingProcessed = null;
327                 
328             } else if (state == STATE_IN_TEMPLATE_NODE) {
329                 if (t.content != null) t.script = parseScript(false);
330                 if (nodeStack.size() == 0) {
331                     // </template>
332                     state = STATE_FINISHED_TEMPLATE_NODE;
333                     
334                 } else {
335                     // add this template as a child of its parent
336                     Template oldt = t;
337                     t = (Template)nodeStack.lastElement();
338                     nodeStack.setSize(nodeStack.size() - 1);
339                     t.children.addElement(oldt);
340
341                     int oldt_lines = getLine() - oldt.startLine;
342                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
343                 }
344             }
345          }
346
347         public void characters(char[] ch, int start, int length) throws XML.Exn {
348             // invoke the no-tab crusade
349             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
350                 throw new XML.Exn("tabs are not allowed in XWT files", XML.Exn.SCHEMA, getLine(), getCol());
351
352             if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
353                 if (t.content == null) {
354                     t.content_start = getLine();
355                     t.content = new StringBuffer();
356                 }
357
358                 t.content.append(ch, start, length);
359
360             } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
361                 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
362             }
363         }
364
365         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
366     }
367
368     private static class PerInstantiationJSScope extends JSScope {
369         XWT xwt = null;
370         PerInstantiationJSScope parentBoxPis = null;
371         JSScope myStatic = null;
372         void putDollar(String key, Box target) throws JSExn {
373             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
374             declare("$" + key);
375             put("$" + key, target);
376         }
377         public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
378             super(parentScope);
379             this.parentBoxPis = parentBoxPis;
380             this.xwt = xwt;
381             this.myStatic = myStatic;
382         }
383         public Object get(Object key) throws JSExn {
384             if (super.has(key)) return super.get(key);
385             if (key.equals("xwt")) return xwt;
386             if (key.equals("")) return xwt.rr;
387             if (key.equals("static")) return myStatic;
388             return super.get(key);
389         }
390         public void put(Object key, Object val) throws JSExn {
391             if (super.has(key)) super.put(key, val);
392             else super.put(key, val);
393         }
394     }
395
396 }
397
398