2003/12/25 08:09:21
[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.Exn, 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.Exn {
191             switch(state) {
192             case STATE_INITIAL:
193                 if (!"xwt".equals(c.getLocalName()))
194                     throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
195                 if (c.getAttrLen() != 0)
196                     throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
197                 state = STATE_IN_XWT_NODE;
198                 return;
199
200             case STATE_IN_XWT_NODE:
201                 if (nameOfHeaderNodeBeingProcessed != null)
202                     throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
203                 nameOfHeaderNodeBeingProcessed = c.getLocalName();
204                 //#switch(c.getLocalName())
205                 case "doc":
206                     // FEATURE
207                     return;
208                 case "static":
209                     if (t.staticscript != null)
210                         throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
211                     if (c.getAttrLen() > 0)
212                         throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
213                     return;
214                 case "template":
215                     t.startLine = getLine();
216                     state = STATE_IN_TEMPLATE_NODE;
217                     processBodyElement(c);
218                     return;
219                 //#end
220                 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
221
222             case STATE_IN_TEMPLATE_NODE:
223                 // push the last node we were in onto the stack
224                 nodeStack.addElement(t);
225                 // instantiate a new node, and set its fileName/importlist/preapply
226                 Template t2 = new Template(t.r);
227                 t2.startLine = getLine();
228                 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
229                     t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
230                 // make the new node the current node
231                 t = t2;
232                 processBodyElement(c);
233                 return;
234
235             case STATE_FINISHED_TEMPLATE_NODE:
236                 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
237             }
238         }        
239
240         private void processBodyElement(XML.Element c) {
241             Vec keys = new Vec(c.getAttrLen());
242             Vec vals = new Vec(c.getAttrLen());
243
244             // process attributes into Vecs, dealing with any XML Namespaces in the process
245             ATTR: for (int i=0; i < c.getAttrLen(); i++) {
246                 //#switch(c.getAttrKey(i))
247                 case "font":
248                     keys.addElement(c.getAttrKey(i));
249                     if (c.getAttrUri(i) != null) vals.addElement(c.getAttrUri(i) + "." + c.getAttrVal(i));
250                     else vals.addElement(c.getAttrVal(i));
251                     continue ATTR;
252
253                 case "fill":
254                     keys.addElement(c.getAttrKey(i));
255                     if (c.getAttrUri(i) != null && !c.getAttrVal(i).startsWith("#") && SVG.colors.get(c.getAttrVal(i)) == null)
256                         vals.addElement(c.getAttrUri(i) + "." + c.getAttrVal(i));
257                     else vals.addElement(c.getAttrVal(i));
258                     continue ATTR;
259
260                 // process and do not add to box attributes
261
262                 case "preapply":
263                     String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
264                     StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
265                     while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
266                     continue ATTR;
267
268                 case "id":
269                     t.id = c.getAttrVal(i).toString().intern();
270                     continue ATTR;
271                 //#end
272
273                 keys.addElement(c.getAttrKey(i));
274                 vals.addElement(c.getAttrVal(i));
275             }
276
277             if (keys.size() == 0) return;
278
279             // sort the attributes lexicographically
280             Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
281                 return ((String)a).compareTo((String)b);
282             } });
283
284
285             // merge attributes into template
286             t.keys = new String[keys.size()];
287             t.vals = new Object[vals.size()];
288             keys.copyInto(t.keys);
289             vals.copyInto(t.vals);
290
291             // convert attributes to appropriate types and intern strings
292             for(int i=0; i<t.keys.length; i++) {
293                 t.keys[i] = t.keys[i].intern();
294
295                 String valString = t.vals[i].toString();
296                 
297                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
298                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
299                 else if (valString.equals("null")) t.vals[i] = null;
300                 else {
301                     boolean hasNonNumeral = false;
302                     boolean periodUsed = false;
303                     for(int j=0; j<valString.length(); j++)
304                         if (j == 0 && valString.charAt(j) == '-') {
305                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
306                             periodUsed = true;
307                         } else if (!Character.isDigit(valString.charAt(j))) {
308                             hasNonNumeral = true;
309                             break;
310                         }
311                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
312                     else t.vals[i] = valString.intern();
313                 }
314             }
315         }
316
317         private JSFunction parseScript(boolean isstatic) throws IOException {
318             JSFunction thisscript = null;
319             String contentString = t.content.toString();
320             if (contentString.trim().length() > 0)
321                 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
322                                                    t.content_start,
323                                                    new StringReader(contentString));
324             t.content = null;
325             t.content_start = 0;
326             return thisscript;
327         }
328
329         public void endElement(XML.Element c) throws XML.Exn, IOException {
330             if (state == STATE_IN_XWT_NODE) {
331                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
332                 nameOfHeaderNodeBeingProcessed = null;
333                 
334             } else if (state == STATE_IN_TEMPLATE_NODE) {
335                 if (t.content != null) t.script = parseScript(false);
336                 if (nodeStack.size() == 0) {
337                     // </template>
338                     state = STATE_FINISHED_TEMPLATE_NODE;
339                     
340                 } else {
341                     // add this template as a child of its parent
342                     Template oldt = t;
343                     t = (Template)nodeStack.lastElement();
344                     nodeStack.setSize(nodeStack.size() - 1);
345                     t.children.addElement(oldt);
346
347                     int oldt_lines = getLine() - oldt.startLine;
348                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
349                 }
350             }
351          }
352
353         public void characters(char[] ch, int start, int length) throws XML.Exn {
354             // invoke the no-tab crusade
355             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
356                 throw new XML.Exn("tabs are not allowed in XWT files", XML.Exn.SCHEMA, getLine(), getCol());
357
358             if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
359                 if (t.content == null) {
360                     t.content_start = getLine();
361                     t.content = new StringBuffer();
362                 }
363
364                 t.content.append(ch, start, length);
365
366             } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
367                 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
368             }
369         }
370
371         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
372     }
373
374     private static class PerInstantiationJSScope extends JSScope {
375         XWT xwt = null;
376         PerInstantiationJSScope parentBoxPis = null;
377         JSScope myStatic = null;
378         void putDollar(String key, Box target) throws JSExn {
379             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
380             declare("$" + key);
381             put("$" + key, target);
382         }
383         public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
384             super(parentScope);
385             this.parentBoxPis = parentBoxPis;
386             this.xwt = xwt;
387             this.myStatic = myStatic;
388         }
389         public Object get(Object key) throws JSExn {
390             if (super.has(key)) return super.get(key);
391             if (key.equals("xwt")) return xwt;
392             if (key.equals("")) return xwt.rr;
393             if (key.equals("static")) return myStatic;
394             return super.get(key);
395         }
396         public void put(Object key, Object val) throws JSExn {
397             if (super.has(key)) super.put(key, val);
398             else super.put(key, val);
399         }
400     }
401
402 }
403
404