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 JS script = null; ///< the script on this node
35 private String tagname = null; ///< template to preapply (if any)
38 // Instance Members that are only meaningful on root Template //////////////////////////////////////
40 private JSScope staticScope = null; ///< the scope in which the static block is executed
41 private JS staticscript = null; ///< the script on the static node of this template, null already performed
44 // Only used during parsing /////////////////////////////////////////////////////////////////
46 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
47 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
48 private int startLine = -1; ///< the line number that this element starts on
52 // Static data/methods ///////////////////////////////////////////////////////////////////
55 private Template(XWT xwt) { this.xwt = xwt; }
56 public Template(InputStream is, XWT xwt) throws IOException, JSExn, XML.Exn {
57 this.xwt = xwt; new TemplateHelper().parseit(is, this);
61 // Methods to apply templates ////////////////////////////////////////////////////////
63 /** called before this template is applied or its static object can be externally referenced */
64 JSScope getStatic() throws JSExn {
65 if (staticScope == null) staticScope = new PerInstantiationScope(null, xwt, null, null);
66 if (staticscript == null) return staticScope;
67 JS temp = staticscript;
69 JS.cloneWithNewParentScope(temp, staticScope).call(null, null, null, null, 0);
73 /** Applies the template to Box b
74 * @param pboxes a vector of all box parents on which to put $-references
75 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
77 void apply(Box b) throws JSExn {
80 } catch (IOException e) {
84 throw new JSExn(e.toString());
93 private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
96 // FIXME this dollar stuff is all wrong
97 if (id != null) parentPis.putDollar(id, b);
98 if (tagname != null) xwt.resolveString(tagname, false).call(b, null, null, null, 1);
100 PerInstantiationScope pis = new PerInstantiationScope(b, xwt, parentPis, staticScope);
102 // FIXME needs to obey the new application-ordering rules
103 for (int i=0; children != null && i<children.size(); i++) {
105 ((Template)children.elementAt(i)).apply(kid, pis);
106 b.putAndTriggerTraps(b.get("numchildren"), kid);
109 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
112 for(int i=0; keys != null && i < keys.length; i++) {
113 if (keys[i] == null) continue;
117 if ("null".equals(val)) val = null;
119 if (val != null && val instanceof String && ((String)val).length() > 0) {
120 switch (((String)val).charAt(0)) {
123 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
126 val = xwt.resolveString(((String)val).substring(1), false);
128 // FIXME: should we be resolving all of these in the XML-parsing code?
132 b.putAndTriggerTraps(key, val);
138 // XML Parsing /////////////////////////////////////////////////////////////////
140 /** handles XML parsing; builds a Template tree as it goes */
141 static final class TemplateHelper extends XML {
146 private static final int STATE_INITIAL = 0;
147 private static final int STATE_IN_XWT_NODE = 1;
148 private static final int STATE_IN_TEMPLATE_NODE = 2;
149 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
151 private String nameOfHeaderNodeBeingProcessed;
153 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
154 Template t = null; ///< the template we're currently working on
156 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
157 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
158 state = STATE_INITIAL;
159 nameOfHeaderNodeBeingProcessed = null;
160 nodeStack.setSize(0);
162 parse(new InputStreamReader(is));
165 public void startElement(XML.Element c) throws XML.Exn {
168 if (!"xwt".equals(c.getLocalName()))
169 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
170 if (c.getAttrLen() != 0)
171 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
172 state = STATE_IN_XWT_NODE;
175 case STATE_IN_XWT_NODE:
176 if (nameOfHeaderNodeBeingProcessed != null)
177 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
178 nameOfHeaderNodeBeingProcessed = c.getLocalName();
179 //#switch(c.getLocalName())
184 if (t.staticscript != null)
185 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
186 if (c.getAttrLen() > 0)
187 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
190 t.startLine = getLine();
191 state = STATE_IN_TEMPLATE_NODE;
192 processBodyElement(c);
195 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
197 case STATE_IN_TEMPLATE_NODE:
198 // push the last node we were in onto the stack
199 nodeStack.addElement(t);
200 // instantiate a new node, and set its fileName/importlist/preapply
201 Template t2 = new Template(t.xwt);
202 t2.startLine = getLine();
203 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
204 t2.tagname = ((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
205 // make the new node the current node
207 processBodyElement(c);
210 case STATE_FINISHED_TEMPLATE_NODE:
211 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
215 private void processBodyElement(XML.Element c) {
216 Vec keys = new Vec(c.getAttrLen());
217 Vec vals = new Vec(c.getAttrLen());
219 // process attributes into Vecs, dealing with any XML Namespaces in the process
220 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
221 //#switch(c.getAttrKey(i))
223 t.id = c.getAttrVal(i).toString().intern();
227 // treat value starting with '.' as resource reference
228 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
229 keys.addElement(c.getAttrKey(i));
230 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
233 if (keys.size() == 0) return;
235 // sort the attributes lexicographically
236 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
237 return ((String)a).compareTo((String)b);
240 t.keys = new String[keys.size()];
241 t.vals = new Object[vals.size()];
242 keys.copyInto(t.keys);
243 vals.copyInto(t.vals);
245 // convert attributes to appropriate types and intern strings
246 for(int i=0; i<t.keys.length; i++) {
247 t.keys[i] = t.keys[i].intern();
249 String valString = t.vals[i].toString();
251 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
252 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
253 else if (valString.equals("null")) t.vals[i] = null;
255 boolean hasNonNumeral = false;
256 boolean periodUsed = false;
257 for(int j=0; j<valString.length(); j++)
258 if (j == 0 && valString.charAt(j) == '-') {
259 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
261 } else if (!Character.isDigit(valString.charAt(j))) {
262 hasNonNumeral = true;
265 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
266 else t.vals[i] = valString.intern();
271 private JS parseScript(boolean isstatic) throws IOException {
272 JS thisscript = null;
273 String contentString = t.content.toString();
274 if (contentString.trim().length() > 0)
275 thisscript = JS.fromReader("FIXME", t.content_start, new StringReader(contentString));
281 public void endElement(XML.Element c) throws XML.Exn, IOException {
282 if (state == STATE_IN_XWT_NODE) {
283 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
284 nameOfHeaderNodeBeingProcessed = null;
286 } else if (state == STATE_IN_TEMPLATE_NODE) {
287 if (t.content != null) t.script = parseScript(false);
288 if (nodeStack.size() == 0) {
290 state = STATE_FINISHED_TEMPLATE_NODE;
293 // add this template as a child of its parent
295 t = (Template)nodeStack.lastElement();
296 nodeStack.setSize(nodeStack.size() - 1);
297 t.children.addElement(oldt);
299 int oldt_lines = getLine() - oldt.startLine;
300 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
305 public void characters(char[] ch, int start, int length) throws XML.Exn {
306 // invoke the no-tab crusade
307 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
308 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
310 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
311 if (t.content == null) {
312 t.content_start = getLine();
313 t.content = new StringBuffer();
316 t.content.append(ch, start, length);
318 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
319 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
323 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
326 private static class PerInstantiationScope extends JSScope {
328 PerInstantiationScope parentBoxPis = null;
329 JSScope myStatic = null;
330 void putDollar(String key, Box target) throws JSExn {
331 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
333 put("$" + key, target);
335 public PerInstantiationScope(JSScope parentScope, XWT xwt, PerInstantiationScope parentBoxPis, JSScope myStatic) {
337 this.parentBoxPis = parentBoxPis;
339 this.myStatic = myStatic;
341 public Object get(Object key) throws JSExn {
342 if (super.has(key)) return super.get(key);
343 if (key.equals("xwt")) return xwt;
344 if (key.equals("")) return xwt.get("");
345 if (key.equals("static")) return myStatic;
346 return super.get(key);
348 public void put(Object key, Object val) throws JSExn {
349 if (super.has(key)) super.put(key, val);
350 else super.put(key, val);