1 // Copyright 2004 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 JS 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 JS 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
55 // Static data/methods ///////////////////////////////////////////////////////////////////
57 public Template(InputStream is, XWT xwt) {
60 new TemplateHelper().parseit(is, this);
61 } catch (Exception e) {
62 throw new RuntimeException(e.toString());
66 public Template(XWT xwt) {
70 public static JS resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
73 if (str.indexOf("://") != -1) {
74 if (permitAbsolute) return (Stream)xwt.url2res(str);
75 throw new JSExn("absolute URL " + str + " not permitted here");
79 JS ret = (JS)xwt.getAndTriggerTraps("");
80 while(str.indexOf('.') != -1) {
81 String path = str.substring(0, str.indexOf('.'));
82 str = str.substring(str.indexOf('.') + 1);
83 ret = (JS)ret.get(path);
85 ret = (JS)ret.get(str);
90 // Methods to apply templates ////////////////////////////////////////////////////////
92 /** called before this template is applied or its static object can be externally referenced */
93 JSScope getStatic() throws JSExn {
94 if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
95 if (staticscript == null) return staticScope;
96 JS temp = staticscript;
98 JS.cloneWithNewParentScope(temp, staticScope).call(null, null, null, null, 0);
102 /** Applies the template to Box b
103 * @param pboxes a vector of all box parents on which to put $-references
104 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
106 void apply(Box b) throws JSExn {
109 } catch (IOException e) {
112 throw new JSExn(e.toString());
120 private void apply(Box b, PerInstantiationJSScope parentPis) throws JSExn, IOException {
123 if (id != null) parentPis.putDollar(id, b);
124 for(int i=0; i<preapply.size(); i++) {
125 Template t = new Template(Stream.getInputStream(resolveStringToResource((String)preapply.elementAt(i), xwt, false)), xwt);
126 if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
130 PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
132 for (int i=0; children != null && i<children.size(); i++) {
134 ((Template)children.elementAt(i)).apply(kid, pis);
135 b.putAndTriggerTraps(b.get("numchildren"), kid);
138 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
141 for(int i=0; keys != null && i < keys.length; i++) {
142 if (keys[i] == null) continue;
146 if ("null".equals(val)) val = null;
148 if (val != null && val instanceof String && ((String)val).length() > 0) {
149 switch (((String)val).charAt(0)) {
152 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
155 val = resolveStringToResource(((String)val).substring(1), xwt, true);
159 if (val != null && "redirect".equals(key)) {
160 val = pis.get("$"+val);
161 if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
165 b.putAndTriggerTraps(key, val);
167 e.addBacktrace(fileName + ":attr-" + key,0);
175 // XML Parsing /////////////////////////////////////////////////////////////////
177 /** handles XML parsing; builds a Template tree as it goes */
178 static final class TemplateHelper extends XML {
183 private static final int STATE_INITIAL = 0;
184 private static final int STATE_IN_XWT_NODE = 1;
185 private static final int STATE_IN_TEMPLATE_NODE = 2;
186 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
188 private String nameOfHeaderNodeBeingProcessed;
190 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
191 Template t = null; ///< the template we're currently working on
193 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
194 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
195 state = STATE_INITIAL;
196 nameOfHeaderNodeBeingProcessed = null;
197 nodeStack.setSize(0);
199 parse(new InputStreamReader(is));
202 public void startElement(XML.Element c) throws XML.Exn {
205 if (!"xwt".equals(c.getLocalName()))
206 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
207 if (c.getAttrLen() != 0)
208 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
209 state = STATE_IN_XWT_NODE;
212 case STATE_IN_XWT_NODE:
213 if (nameOfHeaderNodeBeingProcessed != null)
214 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
215 nameOfHeaderNodeBeingProcessed = c.getLocalName();
216 //#switch(c.getLocalName())
221 if (t.staticscript != null)
222 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
223 if (c.getAttrLen() > 0)
224 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
227 t.startLine = getLine();
228 state = STATE_IN_TEMPLATE_NODE;
229 processBodyElement(c);
232 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
234 case STATE_IN_TEMPLATE_NODE:
235 // push the last node we were in onto the stack
236 nodeStack.addElement(t);
237 // instantiate a new node, and set its fileName/importlist/preapply
238 Template t2 = new Template(t.xwt);
239 t2.startLine = getLine();
240 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
241 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
242 // make the new node the current node
244 processBodyElement(c);
247 case STATE_FINISHED_TEMPLATE_NODE:
248 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
252 private void processBodyElement(XML.Element c) {
253 Vec keys = new Vec(c.getAttrLen());
254 Vec vals = new Vec(c.getAttrLen());
256 // process attributes into Vecs, dealing with any XML Namespaces in the process
257 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
258 //#switch(c.getAttrKey(i))
260 String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
261 StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
262 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
266 t.id = c.getAttrVal(i).toString().intern();
270 // treat value starting with '.' as resource reference
271 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
272 keys.addElement(c.getAttrKey(i));
273 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
276 if (keys.size() == 0) return;
278 // sort the attributes lexicographically
279 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
280 return ((String)a).compareTo((String)b);
283 t.keys = new String[keys.size()];
284 t.vals = new Object[vals.size()];
285 keys.copyInto(t.keys);
286 vals.copyInto(t.vals);
288 // convert attributes to appropriate types and intern strings
289 for(int i=0; i<t.keys.length; i++) {
290 t.keys[i] = t.keys[i].intern();
292 String valString = t.vals[i].toString();
294 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
295 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
296 else if (valString.equals("null")) t.vals[i] = null;
298 boolean hasNonNumeral = false;
299 boolean periodUsed = false;
300 for(int j=0; j<valString.length(); j++)
301 if (j == 0 && valString.charAt(j) == '-') {
302 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
304 } else if (!Character.isDigit(valString.charAt(j))) {
305 hasNonNumeral = true;
308 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
309 else t.vals[i] = valString.intern();
314 private JS parseScript(boolean isstatic) throws IOException {
315 JS thisscript = null;
316 String contentString = t.content.toString();
317 if (contentString.trim().length() > 0)
318 thisscript = JS.fromReader(t.fileName + (isstatic ? "._" : ""),
320 new StringReader(contentString));
326 public void endElement(XML.Element c) throws XML.Exn, IOException {
327 if (state == STATE_IN_XWT_NODE) {
328 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
329 nameOfHeaderNodeBeingProcessed = null;
331 } else if (state == STATE_IN_TEMPLATE_NODE) {
332 if (t.content != null) t.script = parseScript(false);
333 if (nodeStack.size() == 0) {
335 state = STATE_FINISHED_TEMPLATE_NODE;
338 // add this template as a child of its parent
340 t = (Template)nodeStack.lastElement();
341 nodeStack.setSize(nodeStack.size() - 1);
342 t.children.addElement(oldt);
344 int oldt_lines = getLine() - oldt.startLine;
345 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
350 public void characters(char[] ch, int start, int length) throws XML.Exn {
351 // invoke the no-tab crusade
352 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
353 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
355 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
356 if (t.content == null) {
357 t.content_start = getLine();
358 t.content = new StringBuffer();
361 t.content.append(ch, start, length);
363 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
364 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
368 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
371 private static class PerInstantiationJSScope extends JSScope {
373 PerInstantiationJSScope parentBoxPis = null;
374 JSScope myStatic = null;
375 void putDollar(String key, Box target) throws JSExn {
376 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
378 put("$" + key, target);
380 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
382 this.parentBoxPis = parentBoxPis;
384 this.myStatic = myStatic;
386 public Object get(Object key) throws JSExn {
387 if (super.has(key)) return super.get(key);
388 if (key.equals("xwt")) return xwt;
389 if (key.equals("")) return xwt.get("");
390 if (key.equals("static")) return myStatic;
391 return super.get(key);
393 public void put(Object key, Object val) throws JSExn {
394 if (super.has(key)) super.put(key, val);
395 else super.put(key, val);