2003/09/24 07:33:32
[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
25 // FIXME imports
26 public class Template {
27
28     // Instance Members ///////////////////////////////////////////////////////
29
30     /** the id of this box */
31     String id = null;
32
33     /** the id of the redirect target; only meaningful on a root node */
34     String redirect = null;
35
36     /** templates that should be preapplied (in the order of application); only meaningful on a root node */
37     private Template[] preapply;
38
39     /** templates that should be postapplied (in the order of application); only meaningful on a root node */
40     private Template[] postapply;
41
42     /** keys to be "put" to instances of this template; elements correspond to those of vals */
43     private String[] keys;
44
45     /** values to be "put" to instances of this template; elements correspond to those of keys */
46     private Object[] vals;
47
48     /** child template objects */
49     private Template[] children;
50
51     /** see numUnits(); -1 means that this value has not yet been computed */
52     private int numunits = -1;
53
54     /** the scope in which the static block is executed */
55     private JS.Scope staticScope = null;
56
57     /** the script on the static node of this template, null if it has already been executed */
58     private JS.CompiledFunction staticscript = null;
59
60     /** the script on this node */
61     private JS.CompiledFunction script = null;
62
63     /** the filename this node came from; used only for debugging */
64     private String fileName = "unknown";
65
66
67     // Only used during parsing /////////////////////////////////////////////////////////////////
68
69     /** during XML parsing, this holds the list of currently-parsed children; null otherwise */
70     private Vec childvect = new Vec();
71
72     /** during XML parsing, this holds partially-read character data; null otherwise */
73     private StringBuffer content = null;
74
75     /** line number of the first line of <tt>content</tt> */
76     private int content_start = 0;
77
78     /** number of lines in <tt>content</tt> */
79     private int content_lines = 0;
80
81     /** the line number that this element starts on */
82     private int startLine = -1;
83
84
85     // Static data/methods ///////////////////////////////////////////////////////////////////
86
87     private Template(String fileName) { this.fileName = fileName; }
88
89     public static Template getTemplate(Res r) {
90         try {
91             if (r.t != null) return r.t;
92             r.t = new Template(r.getDescriptiveName());
93             new TemplateHelper().parseit(r.getInputStream(), r.t);
94             return r.t;
95         } catch (XML.SchemaException e) {
96             if (Log.on) Log.log(Template.class, "error parsing template " + r.t.fileName);
97             if (Log.on) Log.log(Template.class, e.getMessage());
98             return null;
99         } catch (XML.XMLException e) {
100             if (Log.on) Log.log(Template.class, "error parsing template at " + r.t.fileName + ":" + e.getLine() + "," + e.getCol());
101             if (Log.on) Log.log(Template.class, e.getMessage());
102             return null;
103         } catch (IOException e) {
104             if (Log.on) Log.log(Template.class, "IOException while parsing template " + r.t.fileName + " -- this should never happen");
105             if (Log.on) Log.log(Template.class, e);
106             return null;
107         }
108     }
109
110
111     // Methods to apply templates ////////////////////////////////////////////////////////
112
113     /** calculates, caches, and returns an integer approximation of how long it will take to apply this template,
114      *  including pre/post and children */
115     int numUnits() {
116         if (numunits != -1) return numunits;
117         numunits = 1;
118         for(int i=0; preapply != null && i<preapply.length; i++) numunits += preapply[i].numUnits();
119         for(int i=0; postapply != null && i<postapply.length; i++) numunits += postapply[i].numUnits();
120         if (script != null) numunits += 10;
121         numunits += keys == null ? 0 : keys.length;
122         for(int i=0; children != null && i<children.length; i++) numunits += children[i].numUnits();
123         return numunits;
124     }
125
126     /** called before this template is applied or its static object can be externally referenced */
127     JS.Scope getStatic() {
128         if (staticScope == null) staticScope = new JS.Scope(null);
129         if (staticscript == null) return staticScope;
130         JS.CompiledFunction temp = staticscript;
131         staticscript = null;
132         temp.call(new JS.Array(), staticScope);
133         return staticScope;
134     }
135     
136     /** Applies the template to Box b
137      *  @param pboxes a vector of all box parents on which to put $-references
138      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
139      */
140     // FIXME: $-vars not dealt with
141     void apply(Box b, JS.Callable callback, int numerator, int denominator, Res resourceRoot) {
142
143         getStatic();
144         int original_numerator = numerator;
145
146         for(int i=0; preapply != null && i<preapply.length; i++) {
147             preapply[i].apply(b, callback, numerator, denominator, resourceRoot);
148             numerator += preapply[i].numUnits();
149         }
150
151         for (int i=0; children != null && i<children.length; i++) {
152             Box kid = new Box();
153             children[i].apply(kid, callback, numerator, denominator, resourceRoot);
154             numerator += children[i].numUnits();
155             b.put(b.numChildren(), kid);
156         }
157
158         // whom to redirect to; doesn't take effect until after script runs
159         Box redir = (redirect != null && !"self".equals(redirect)) ? (Box)b.get("$" + redirect) : null;
160
161         if (script != null) script.call(new JS.Array(), new PerInstantiationScope(b, resourceRoot));
162
163         for(int i=0; keys != null && i<keys.length; i++) b.put(keys[i], vals[i]);
164
165         if (redirect != null && !"self".equals(redirect)) b.redirect = redir;
166
167         for(int i=0; postapply != null && i<postapply.length; i++) {
168             postapply[i].apply(b, callback, numerator, denominator, resourceRoot);
169             numerator += postapply[i].numUnits();
170         }
171
172         numerator = original_numerator + numUnits();
173
174         if (callback != null) try {
175             JS.Array args = new JS.Array();
176             args.addElement(new Double(numerator));
177             args.addElement(new Double(denominator));
178             callback.call(args);
179         } catch (JS.Exn e) { if (Log.on) Log.log(this, "WARNING: uncaught ecmascript exception: " + e); }
180
181         if (Thread.currentThread() instanceof ThreadMessage) XWT.sleep(0);
182     }
183
184
185
186     // XML Parsing /////////////////////////////////////////////////////////////////
187
188     /** handles XML parsing; builds a Template tree as it goes */
189     static final class TemplateHelper extends XML {
190
191         TemplateHelper() { }
192
193         /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
194         void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
195             rootNodeHasBeenEncountered = false;
196             templateNodeHasBeenEncountered = false;
197             staticNodeHasBeenEncountered = false;
198             templateNodeHasBeenFinished = false;
199             nameOfHeaderNodeBeingProcessed = null;
200
201             nodeStack.setSize(0);
202             preapply.setSize(0);
203             postapply.setSize(0);
204
205             t = root;
206             parse(new InputStreamReader(is)); 
207         }
208
209         /** parsing state: true iff we have already encountered the <xwt> open-tag */
210         boolean rootNodeHasBeenEncountered = false;
211
212         /** parsing state: true iff we have already encountered the <template> open-tag */
213         boolean templateNodeHasBeenEncountered = false;
214
215         /** parsing state: true iff we have already encountered the <static> open-tag */
216         boolean staticNodeHasBeenEncountered = false;
217
218         /** parsing state: true iff we have already encountered the <template> close-tag */
219         boolean templateNodeHasBeenFinished = false;
220
221         /** parsing state: If we have encountered the open tag of a header node, but not the close tag, this is the name of
222          *  that tag; otherwise, it is null. */
223         String nameOfHeaderNodeBeingProcessed = null;
224
225         /** stack of Templates whose XML elements we have seen open-tags for but not close-tags */
226         Vec nodeStack = new Vec();
227
228         /** builds up the list of preapplies */
229         Vec preapply = new Vec();
230
231         /** builds up the list of postapplies */
232         Vec postapply = new Vec();
233
234         /** the template we're currently working on */
235         Template t = null;
236
237         public void startElement(XML.Element c) throws XML.SchemaException {
238             if (templateNodeHasBeenFinished) {
239                 throw new XML.SchemaException("no elements may appear after the <template> node");
240
241             } else if (!rootNodeHasBeenEncountered) {
242                 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
243                 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
244                 rootNodeHasBeenEncountered = true;
245                 return;
246         
247             } else if (!templateNodeHasBeenEncountered) {
248                 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
249                 nameOfHeaderNodeBeingProcessed = c.localName;
250
251                 if (c.localName.equals("import")) {
252                     if (c.len != 1 || !c.keys[0].equals("name"))
253                         throw new XML.SchemaException("<import> node must have exactly one attribute, which must be called 'name'");
254                     String importpackage = c.vals[0].toString();
255                     if (importpackage.endsWith(".*")) importpackage = importpackage.substring(0, importpackage.length() - 2);
256                     return;
257
258                 } else if (c.localName.equals("redirect")) {
259                     if (c.len != 1 || !c.keys[0].equals("target"))
260                         throw new XML.SchemaException("<redirect> node must have exactly one attribute, which must be called 'target'");
261                     if (t.redirect != null)
262                         throw new XML.SchemaException("the <redirect> header element may not appear more than once");
263                     t.redirect = c.vals[0].toString();
264                     if(t.redirect.equals("null")) t.redirect = null;
265                     return;
266
267                 } else if (c.localName.equals("preapply")) {
268                     if (c.len != 1 || !c.keys[0].equals("name"))
269                         throw new XML.SchemaException("<preapply> node must have exactly one attribute, which must be called 'name'");
270                     preapply.addElement(c.vals[0]);
271                     return;
272
273                 } else if (c.localName.equals("postapply")) {
274                     if (c.len != 1 || !c.keys[0].equals("name"))
275                         throw new XML.SchemaException("<postapply> node must have exactly one attribute, which must be called 'name'");
276                     postapply.addElement(c.vals[0]);
277                     return;
278
279                 } else if (c.localName.equals("static")) {
280                     if (staticNodeHasBeenEncountered)
281                         throw new XML.SchemaException("the <static> header node may not appear more than once");
282                     if (c.len > 0)
283                         throw new XML.SchemaException("the <static> node may not have attributes");
284                     staticNodeHasBeenEncountered = true;
285                     return;
286
287                 } else if (c.localName.equals("template")) {
288                     // finalize importlist/preapply/postapply, since they can't change from here on
289                     t.startLine = getLine();
290                     if (preapply.size() > 0) preapply.copyInto(t.preapply = new Template[preapply.size()]);
291                     if (postapply.size() > 0) postapply.copyInto(t.postapply = new Template[postapply.size()]);
292                     templateNodeHasBeenEncountered = true;
293
294                 } else {
295                     throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
296
297                 }
298
299             } else {
300
301                 // push the last node we were in onto the stack
302                 nodeStack.addElement(t);
303
304                 // instantiate a new node, and set its fileName/importlist/preapply
305                 Template t2 = new Template(t.fileName);
306                 t2.startLine = getLine();
307                 if (!c.localName.equals("box")) t2.preapply = new Template[] { /*c.localName FIXME */ };
308
309                 // make the new node the current node
310                 t = t2;
311
312             }
313
314             t.keys = new String[c.len];
315             t.vals = new Object[c.len];
316             Hash h = new Hash(c.len * 2, 3);
317             for(int i=0; i<c.len; i++) h.put(c.keys[i], c.vals[i]);
318             Vec v = new Vec(c.len, c.keys);
319             v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
320             for(int i=0; i<c.len; i++) {
321                 // FIXME: height must come after image
322                 // FIXME: thisbox must come first
323                 t.keys[i] = (String)v.elementAt(i);
324                 t.vals[i] = h.get(t.keys[i]);
325             }
326
327             for(int i=0; i<t.keys.length; i++) {
328                 if (t.keys[i].equals("id")) {
329                     t.id = t.vals[i].toString().intern();
330                     t.keys[i] = null;
331                     continue;
332                 }
333
334                 t.keys[i] = t.keys[i].intern();
335
336                 String valString = t.vals[i].toString();
337                 
338                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
339                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
340                 else if (valString.equals("null")) t.vals[i] = null;
341                 else {
342                     boolean hasNonNumeral = false;
343                     boolean periodUsed = false;
344                     for(int j=0; j<valString.length(); j++)
345                         if (j == 0 && valString.charAt(j) == '-') {
346                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
347                             periodUsed = true;
348                         } else if (!Character.isDigit(valString.charAt(j))) {
349                             hasNonNumeral = true;
350                             break;
351                         }
352                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
353                     else t.vals[i] = valString.intern();
354                 }
355
356                 // bump thisbox to the front of the pack
357                 if (t.keys[i].equals("thisbox")) {
358                     t.keys[i] = t.keys[0];
359                     t.keys[0] = "thisbox";
360                     Object o = t.vals[0];
361                     t.vals[0] = t.vals[i];
362                     t.vals[i] = o;
363                 }
364             }
365         }
366
367         private JS.CompiledFunction genscript(boolean isstatic) {
368             JS.CompiledFunction thisscript = null;
369             try {
370                 thisscript = JS.parse(t.fileName + (isstatic ? "._" : ""), t.content_start, new StringReader(t.content.toString()));
371             } catch (IOException ioe) {
372                 if (Log.on) Log.log(this, "  ERROR: " + ioe.getMessage());
373                 thisscript = null;
374             }
375
376             t.content = null;
377             t.content_start = 0;
378             t.content_lines = 0;
379             return thisscript;
380         }
381
382         public void endElement(XML.Element c) throws XML.SchemaException {
383             if (rootNodeHasBeenEncountered && !templateNodeHasBeenEncountered) {
384                 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = genscript(true);
385                 nameOfHeaderNodeBeingProcessed = null;
386                 
387             } else if (templateNodeHasBeenEncountered && !templateNodeHasBeenFinished) {
388                 // turn our childvect into a Template[]
389                 t.childvect.copyInto(t.children = new Template[t.childvect.size()]);
390                 t.childvect = null;
391                 if (t.content != null) t.script = genscript(false);
392                 
393                 if (nodeStack.size() == 0) {
394                     // </template>
395                     templateNodeHasBeenFinished = true;
396                     
397                 } else {
398                     // add this template as a child of its parent
399                     Template oldt = t;
400                     t = (Template)nodeStack.lastElement();
401                     nodeStack.setSize(nodeStack.size() - 1);
402                     t.childvect.addElement(oldt);
403                 }
404             }
405          }
406
407         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
408             // invoke the no-tab crusade
409             for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
410                 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
411
412             if ("static".equals(nameOfHeaderNodeBeingProcessed) || templateNodeHasBeenEncountered) {
413                 if (t.content == null) {
414                     t.content_start = getLine();
415                     t.content_lines = 0;
416                     t.content = new StringBuffer();
417                 }
418
419                 t.content.append(ch, start, length);
420                 t.content_lines++;
421
422             } else if (nameOfHeaderNodeBeingProcessed != null) {
423                 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
424             }
425         }
426
427         public void whitespace(char[] ch, int start, int length) throws XML.SchemaException {
428         }
429     }
430
431     private static class PerInstantiationScope extends JS.Scope {
432         Res resourceRoot = null;
433         public PerInstantiationScope(Scope parentScope, Res resourceRoot) {
434             super(parentScope);
435             this.resourceRoot = resourceRoot;
436         }
437         public boolean isTransparent() { return true; }
438         public boolean has(Object key) { return false; }
439         public void declare(String s) { super.declare(s); }
440         public Object get(Object key) {
441             // FIXME: access statics here
442             if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
443                 !super.has(key)) {
444                 Object ret = resourceRoot.get(key);
445                 if (ret != null) return ret;
446                 throw new JS.Exn("must declare " + key + " before using it!");
447             }
448             return super.get(key);
449         }
450         public void put(Object key, Object val) {
451             // FIXME: access statics here
452             if (Box.SpecialBoxProperty.specialBoxProperties.get(key) == null &&
453                 !super.has(key)) {
454                 throw new JS.Exn("must declare " + key + " before using it!");
455             }
456             super.put(key, val);
457         }
458     }
459
460 }
461
462