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) { throw new JSExn(e.toString());
69 public static Stream resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
71 if (str.indexOf("://") != -1) {
72 if (permitAbsolute) return (Stream)xwt.url2res(str);
73 throw new JSExn("absolute URL " + str + " not permitted here");
78 while(str.indexOf('.') != -1) {
79 String path = str.substring(0, str.indexOf('.'));
80 str = str.substring(str.indexOf('.') + 1);
81 ret = (Stream)ret.get(path);
83 ret = (Stream)ret.get(str);
88 // Methods to apply templates ////////////////////////////////////////////////////////
90 private Template(Stream r) {
92 String f = r.toString();
93 if (f != null && !f.equals(""))
94 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
97 /** called before this template is applied or its static object can be externally referenced */
98 JSScope getStatic(XWT xwt) throws JSExn {
99 if (staticScope == null) staticScope = new PerInstantiationJSScope(null, xwt, null, null);
100 if (staticscript == null) return staticScope;
101 JSFunction temp = staticscript;
103 temp.cloneWithNewParentScope(staticScope).call(null, null, null, null, 0);
107 /** Applies the template to Box b
108 * @param pboxes a vector of all box parents on which to put $-references
109 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
111 void apply(Box b, XWT xwt) {
117 Log.info(Template.class, "WARNING: exception (below) thrown during application of template;");
118 Log.info(Template.class, " setting visibility of target box to \"false\"");
124 private void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
127 if (id != null) parentPis.putDollar(id, b);
128 for(int i=0; i<preapply.size(); i++) {
129 Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt, false));
130 if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
134 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(JS.N(b.treeSize()), 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");
167 b.putAndTriggerTraps(key, val);
173 // XML Parsing /////////////////////////////////////////////////////////////////
175 /** handles XML parsing; builds a Template tree as it goes */
176 static final class TemplateHelper extends XML {
181 private static final int STATE_INITIAL = 0;
182 private static final int STATE_IN_XWT_NODE = 1;
183 private static final int STATE_IN_TEMPLATE_NODE = 2;
184 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
186 private String nameOfHeaderNodeBeingProcessed;
188 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
189 Template t = null; ///< the template we're currently working on
191 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
192 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
193 state = STATE_INITIAL;
194 nameOfHeaderNodeBeingProcessed = null;
195 nodeStack.setSize(0);
197 parse(new InputStreamReader(is));
200 public void startElement(XML.Element c) throws XML.Exn {
203 if (!"xwt".equals(c.getLocalName()))
204 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
205 if (c.getAttrLen() != 0)
206 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
207 state = STATE_IN_XWT_NODE;
210 case STATE_IN_XWT_NODE:
211 if (nameOfHeaderNodeBeingProcessed != null)
212 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
213 nameOfHeaderNodeBeingProcessed = c.getLocalName();
214 //#switch(c.getLocalName())
219 if (t.staticscript != null)
220 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
221 if (c.getAttrLen() > 0)
222 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
225 t.startLine = getLine();
226 state = STATE_IN_TEMPLATE_NODE;
227 processBodyElement(c);
230 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
232 case STATE_IN_TEMPLATE_NODE:
233 // push the last node we were in onto the stack
234 nodeStack.addElement(t);
235 // instantiate a new node, and set its fileName/importlist/preapply
236 Template t2 = new Template(t.r);
237 t2.startLine = getLine();
238 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
239 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
240 // make the new node the current node
242 processBodyElement(c);
245 case STATE_FINISHED_TEMPLATE_NODE:
246 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
250 private void processBodyElement(XML.Element c) {
251 Vec keys = new Vec(c.getAttrLen());
252 Vec vals = new Vec(c.getAttrLen());
254 // process attributes into Vecs, dealing with any XML Namespaces in the process
255 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
256 //#switch(c.getAttrKey(i))
258 String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
259 StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
260 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
264 t.id = c.getAttrVal(i).toString().intern();
268 // treat value starting with '.' as resource reference
269 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
270 keys.addElement(c.getAttrKey(i));
271 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
274 if (keys.size() == 0) return;
276 // sort the attributes lexicographically
277 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
278 return ((String)a).compareTo((String)b);
281 t.keys = new String[keys.size()];
282 t.vals = new Object[vals.size()];
283 keys.copyInto(t.keys);
284 vals.copyInto(t.vals);
286 // convert attributes to appropriate types and intern strings
287 for(int i=0; i<t.keys.length; i++) {
288 t.keys[i] = t.keys[i].intern();
290 String valString = t.vals[i].toString();
292 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
293 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
294 else if (valString.equals("null")) t.vals[i] = null;
296 boolean hasNonNumeral = false;
297 boolean periodUsed = false;
298 for(int j=0; j<valString.length(); j++)
299 if (j == 0 && valString.charAt(j) == '-') {
300 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
302 } else if (!Character.isDigit(valString.charAt(j))) {
303 hasNonNumeral = true;
306 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
307 else t.vals[i] = valString.intern();
312 private JSFunction parseScript(boolean isstatic) throws IOException {
313 JSFunction thisscript = null;
314 String contentString = t.content.toString();
315 if (contentString.trim().length() > 0)
316 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
318 new StringReader(contentString));
324 public void endElement(XML.Element c) throws XML.Exn, IOException {
325 if (state == STATE_IN_XWT_NODE) {
326 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
327 nameOfHeaderNodeBeingProcessed = null;
329 } else if (state == STATE_IN_TEMPLATE_NODE) {
330 if (t.content != null) t.script = parseScript(false);
331 if (nodeStack.size() == 0) {
333 state = STATE_FINISHED_TEMPLATE_NODE;
336 // add this template as a child of its parent
338 t = (Template)nodeStack.lastElement();
339 nodeStack.setSize(nodeStack.size() - 1);
340 t.children.addElement(oldt);
342 int oldt_lines = getLine() - oldt.startLine;
343 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
348 public void characters(char[] ch, int start, int length) throws XML.Exn {
349 // invoke the no-tab crusade
350 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
351 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
353 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
354 if (t.content == null) {
355 t.content_start = getLine();
356 t.content = new StringBuffer();
359 t.content.append(ch, start, length);
361 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
362 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
366 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
369 private static class PerInstantiationJSScope extends JSScope {
371 PerInstantiationJSScope parentBoxPis = null;
372 JSScope myStatic = null;
373 void putDollar(String key, Box target) throws JSExn {
374 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
376 put("$" + key, target);
378 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
380 this.parentBoxPis = parentBoxPis;
382 this.myStatic = myStatic;
384 public Object get(Object key) throws JSExn {
385 if (super.has(key)) return super.get(key);
386 if (key.equals("xwt")) return xwt;
387 if (key.equals("")) return xwt.rr;
388 if (key.equals("static")) return myStatic;
389 return super.get(key);
391 public void put(Object key, Object val) throws JSExn {
392 if (super.has(key)) super.put(key, val);
393 else super.put(key, val);