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) {
113 throw new JSExn(e.toString());
122 private void apply(Box b, PerInstantiationJSScope parentPis) throws JSExn, IOException {
125 if (id != null) parentPis.putDollar(id, b);
126 for(int i=0; i<preapply.size(); i++) {
127 Template t = new Template(Stream.getInputStream(resolveStringToResource((String)preapply.elementAt(i), xwt, false)), xwt);
128 if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
132 PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticScope);
134 for (int i=0; children != null && i<children.size(); i++) {
136 ((Template)children.elementAt(i)).apply(kid, pis);
137 b.putAndTriggerTraps(b.get("numchildren"), kid);
140 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
143 for(int i=0; keys != null && i < keys.length; i++) {
144 if (keys[i] == null) continue;
148 if ("null".equals(val)) val = null;
150 if (val != null && val instanceof String && ((String)val).length() > 0) {
151 switch (((String)val).charAt(0)) {
154 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
157 val = resolveStringToResource(((String)val).substring(1), xwt, true);
161 if (val != null && "redirect".equals(key)) {
162 val = pis.get("$"+val);
163 if (val == null) throw new JSExn("redirect target '"+vals[i]+"' not found");
167 b.putAndTriggerTraps(key, val);
169 e.addBacktrace(fileName + ":attr-" + key,0);
177 // XML Parsing /////////////////////////////////////////////////////////////////
179 /** handles XML parsing; builds a Template tree as it goes */
180 static final class TemplateHelper extends XML {
185 private static final int STATE_INITIAL = 0;
186 private static final int STATE_IN_XWT_NODE = 1;
187 private static final int STATE_IN_TEMPLATE_NODE = 2;
188 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
190 private String nameOfHeaderNodeBeingProcessed;
192 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
193 Template t = null; ///< the template we're currently working on
195 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
196 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
197 state = STATE_INITIAL;
198 nameOfHeaderNodeBeingProcessed = null;
199 nodeStack.setSize(0);
201 parse(new InputStreamReader(is));
204 public void startElement(XML.Element c) throws XML.Exn {
207 if (!"xwt".equals(c.getLocalName()))
208 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
209 if (c.getAttrLen() != 0)
210 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
211 state = STATE_IN_XWT_NODE;
214 case STATE_IN_XWT_NODE:
215 if (nameOfHeaderNodeBeingProcessed != null)
216 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
217 nameOfHeaderNodeBeingProcessed = c.getLocalName();
218 //#switch(c.getLocalName())
223 if (t.staticscript != null)
224 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
225 if (c.getAttrLen() > 0)
226 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
229 t.startLine = getLine();
230 state = STATE_IN_TEMPLATE_NODE;
231 processBodyElement(c);
234 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
236 case STATE_IN_TEMPLATE_NODE:
237 // push the last node we were in onto the stack
238 nodeStack.addElement(t);
239 // instantiate a new node, and set its fileName/importlist/preapply
240 Template t2 = new Template(t.xwt);
241 t2.startLine = getLine();
242 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
243 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
244 // make the new node the current node
246 processBodyElement(c);
249 case STATE_FINISHED_TEMPLATE_NODE:
250 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
254 private void processBodyElement(XML.Element c) {
255 Vec keys = new Vec(c.getAttrLen());
256 Vec vals = new Vec(c.getAttrLen());
258 // process attributes into Vecs, dealing with any XML Namespaces in the process
259 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
260 //#switch(c.getAttrKey(i))
262 String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
263 StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
264 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
268 t.id = c.getAttrVal(i).toString().intern();
272 // treat value starting with '.' as resource reference
273 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
274 keys.addElement(c.getAttrKey(i));
275 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
278 if (keys.size() == 0) return;
280 // sort the attributes lexicographically
281 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
282 return ((String)a).compareTo((String)b);
285 t.keys = new String[keys.size()];
286 t.vals = new Object[vals.size()];
287 keys.copyInto(t.keys);
288 vals.copyInto(t.vals);
290 // convert attributes to appropriate types and intern strings
291 for(int i=0; i<t.keys.length; i++) {
292 t.keys[i] = t.keys[i].intern();
294 String valString = t.vals[i].toString();
296 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
297 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
298 else if (valString.equals("null")) t.vals[i] = null;
300 boolean hasNonNumeral = false;
301 boolean periodUsed = false;
302 for(int j=0; j<valString.length(); j++)
303 if (j == 0 && valString.charAt(j) == '-') {
304 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
306 } else if (!Character.isDigit(valString.charAt(j))) {
307 hasNonNumeral = true;
310 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
311 else t.vals[i] = valString.intern();
316 private JS parseScript(boolean isstatic) throws IOException {
317 JS thisscript = null;
318 String contentString = t.content.toString();
319 if (contentString.trim().length() > 0)
320 thisscript = JS.fromReader(t.fileName + (isstatic ? "._" : ""),
322 new StringReader(contentString));
328 public void endElement(XML.Element c) throws XML.Exn, IOException {
329 if (state == STATE_IN_XWT_NODE) {
330 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
331 nameOfHeaderNodeBeingProcessed = null;
333 } else if (state == STATE_IN_TEMPLATE_NODE) {
334 if (t.content != null) t.script = parseScript(false);
335 if (nodeStack.size() == 0) {
337 state = STATE_FINISHED_TEMPLATE_NODE;
340 // add this template as a child of its parent
342 t = (Template)nodeStack.lastElement();
343 nodeStack.setSize(nodeStack.size() - 1);
344 t.children.addElement(oldt);
346 int oldt_lines = getLine() - oldt.startLine;
347 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
352 public void characters(char[] ch, int start, int length) throws XML.Exn {
353 // invoke the no-tab crusade
354 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
355 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
357 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
358 if (t.content == null) {
359 t.content_start = getLine();
360 t.content = new StringBuffer();
363 t.content.append(ch, start, length);
365 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
366 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
370 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
373 private static class PerInstantiationJSScope extends JSScope {
375 PerInstantiationJSScope parentBoxPis = null;
376 JSScope myStatic = null;
377 void putDollar(String key, Box target) throws JSExn {
378 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
380 put("$" + key, target);
382 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
384 this.parentBoxPis = parentBoxPis;
386 this.myStatic = myStatic;
388 public Object get(Object key) throws JSExn {
389 if (super.has(key)) return super.get(key);
390 if (key.equals("xwt")) return xwt;
391 if (key.equals("")) return xwt.get("");
392 if (key.equals("static")) return myStatic;
393 return super.get(key);
395 public void put(Object key, Object val) throws JSExn {
396 if (super.has(key)) super.put(key, val);
397 else super.put(key, val);