1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
5 import java.util.zip.*;
9 import org.xwt.translators.*;
10 import org.xwt.util.*;
13 * Encapsulates a template node (the <template/> element of a
14 * .xwt file, or any child element thereof).
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>.
22 * See the XWT reference for information on the order in which
23 * templates are applied, attributes are put, and scripts are run.
25 public class Template {
27 // Instance Members ///////////////////////////////////////////////////////
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
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)
41 // Instance Members that are only meaningful on root Template //////////////////////////////////////
43 private JSScope staticScope = 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
47 // Only used during parsing /////////////////////////////////////////////////////////////////
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 Stream r; ///< the resource we came from
55 // Static data/methods ///////////////////////////////////////////////////////////////////
57 // FIXME need to provide the XWT object too
58 public static Template getTemplate(Stream r) throws JSExn {
60 r = r.addExtension(".xwt");
61 if (r.t != null) return r.t;
62 r.t = new Template(r);
63 new TemplateHelper().parseit(r.getInputStream(), r.t);
65 } catch (Exception e) {
66 throw new JSExn("Error reading template stream: " + r + "\n" + e.toString());
70 public static Stream resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
72 if (str.indexOf("://") != -1) {
73 if (permitAbsolute) return (Stream)xwt.url2res(str);
74 throw new JSExn("absolute URL " + str + " not permitted here");
79 while(str.indexOf('.') != -1) {
80 String path = str.substring(0, str.indexOf('.'));
81 str = str.substring(str.indexOf('.') + 1);
82 ret = (Stream)ret.get(path);
84 ret = (Stream)ret.get(str);
89 // Methods to apply templates ////////////////////////////////////////////////////////
91 private Template(Stream r) {
93 String f = r.toString();
94 if (f != null && !f.equals(""))
95 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
98 /** called before this template is applied or its static object can be externally referenced */
99 JSScope getStatic(XWT xwt) throws JSExn {
100 if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
101 if (staticscript == null) return staticScope;
102 JSFunction temp = staticscript;
104 temp.cloneWithNewParentScope(staticScope).call(null, null, null, null, 0);
108 /** Applies the template to Box b
109 * @param pboxes a vector of all box parents on which to put $-references
110 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
112 void apply(Box b, XWT xwt) throws JSExn {
123 private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
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));
133 PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
135 for (int i=0; children != null && i<children.size(); i++) {
137 ((Template)children.elementAt(i)).apply(kid, xwt, pis);
138 b.putAndTriggerTraps(b.get("numchildren"), kid);
141 if (script != null) script.cloneWithNewParentScope(pis).call(null, null, null, null, 0);
144 for(int i=0; keys != null && i < keys.length; i++) {
145 if (keys[i] == null) continue;
149 if ("null".equals(val)) val = null;
151 if (val != null && val instanceof String && ((String)val).length() > 0) {
152 switch (((String)val).charAt(0)) {
155 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
158 val = resolveStringToResource(((String)val).substring(1), xwt, true);
162 if (val != null && "redirect".equals(key)) {
163 val = pis.get("$"+val);
164 if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
168 b.putAndTriggerTraps(key, val);
170 e.addBacktrace(fileName + ":attr-" + key,0);
178 // XML Parsing /////////////////////////////////////////////////////////////////
180 /** handles XML parsing; builds a Template tree as it goes */
181 static final class TemplateHelper extends XML {
186 private static final int STATE_INITIAL = 0;
187 private static final int STATE_IN_XWT_NODE = 1;
188 private static final int STATE_IN_TEMPLATE_NODE = 2;
189 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
191 private String nameOfHeaderNodeBeingProcessed;
193 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
194 Template t = null; ///< the template we're currently working on
196 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
197 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
198 state = STATE_INITIAL;
199 nameOfHeaderNodeBeingProcessed = null;
200 nodeStack.setSize(0);
202 parse(new InputStreamReader(is));
205 public void startElement(XML.Element c) throws XML.Exn {
208 if (!"xwt".equals(c.getLocalName()))
209 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
210 if (c.getAttrLen() != 0)
211 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
212 state = STATE_IN_XWT_NODE;
215 case STATE_IN_XWT_NODE:
216 if (nameOfHeaderNodeBeingProcessed != null)
217 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
218 nameOfHeaderNodeBeingProcessed = c.getLocalName();
219 //#switch(c.getLocalName())
224 if (t.staticscript != null)
225 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
226 if (c.getAttrLen() > 0)
227 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
230 t.startLine = getLine();
231 state = STATE_IN_TEMPLATE_NODE;
232 processBodyElement(c);
235 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
237 case STATE_IN_TEMPLATE_NODE:
238 // push the last node we were in onto the stack
239 nodeStack.addElement(t);
240 // instantiate a new node, and set its fileName/importlist/preapply
241 Template t2 = new Template(t.r);
242 t2.startLine = getLine();
243 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
244 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
245 // make the new node the current node
247 processBodyElement(c);
250 case STATE_FINISHED_TEMPLATE_NODE:
251 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
255 private void processBodyElement(XML.Element c) {
256 Vec keys = new Vec(c.getAttrLen());
257 Vec vals = new Vec(c.getAttrLen());
259 // process attributes into Vecs, dealing with any XML Namespaces in the process
260 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
261 //#switch(c.getAttrKey(i))
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());
269 t.id = c.getAttrVal(i).toString().intern();
273 // treat value starting with '.' as resource reference
274 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
275 keys.addElement(c.getAttrKey(i));
276 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
279 if (keys.size() == 0) return;
281 // sort the attributes lexicographically
282 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
283 return ((String)a).compareTo((String)b);
286 t.keys = new String[keys.size()];
287 t.vals = new Object[vals.size()];
288 keys.copyInto(t.keys);
289 vals.copyInto(t.vals);
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();
295 String valString = t.vals[i].toString();
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;
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) {
307 } else if (!Character.isDigit(valString.charAt(j))) {
308 hasNonNumeral = true;
311 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
312 else t.vals[i] = valString.intern();
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 ? "._" : ""),
323 new StringReader(contentString));
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;
334 } else if (state == STATE_IN_TEMPLATE_NODE) {
335 if (t.content != null) t.script = parseScript(false);
336 if (nodeStack.size() == 0) {
338 state = STATE_FINISHED_TEMPLATE_NODE;
341 // add this template as a child of its parent
343 t = (Template)nodeStack.lastElement();
344 nodeStack.setSize(nodeStack.size() - 1);
345 t.children.addElement(oldt);
347 int oldt_lines = getLine() - oldt.startLine;
348 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
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 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
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();
364 t.content.append(ch, start, length);
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());
371 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
374 private static class PerInstantiationJSScope extends JSScope {
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);
381 put("$" + key, target);
383 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
385 this.parentBoxPis = parentBoxPis;
387 this.myStatic = myStatic;
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);
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);