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