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 staticJSScope = 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 Res r; ///< the resource we came from
55 // Static data/methods ///////////////////////////////////////////////////////////////////
57 public static Template getTemplate(Res r) throws JSExn {
59 r = r.addExtension(".xwt");
60 if (r.t != null) return r.t;
61 r.t = new Template(r);
62 new TemplateHelper().parseit(r.getInputStream(), r.t);
64 } catch (Exception e) { throw new JSExn(e.toString());
68 public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
70 if (str.indexOf("://") != -1) {
71 if (permitAbsolute) return (Res)xwt.url2res(str);
72 throw new JSExn("absolute URL " + str + " not permitted here");
77 while(str.indexOf('.') != -1) {
78 String path = str.substring(0, str.indexOf('.'));
79 str = str.substring(str.indexOf('.') + 1);
80 ret = (Res)ret.get(path);
82 ret = (Res)ret.get(str);
87 // Methods to apply templates ////////////////////////////////////////////////////////
89 private Template(Res r) {
91 String f = r.toString();
92 if (f != null && !f.equals(""))
93 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
96 /** called before this template is applied or its static object can be externally referenced */
97 JSScope getStatic() throws JSExn {
98 if (staticJSScope == null) staticJSScope = new JSScope(null);
99 if (staticscript == null) return staticJSScope;
100 JSFunction temp = staticscript;
102 temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
103 return staticJSScope;
106 /** Applies the template to Box b
107 * @param pboxes a vector of all box parents on which to put $-references
108 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
110 void apply(Box b, XWT xwt) {
116 Log.info(Template.class, "WARNING: exception (below) thrown during application of template;");
117 Log.info(Template.class, " setting visibility of target box to \"false\"");
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, staticJSScope);
134 for (int i=0; children != null && i<children.size(); i++) {
136 ((Template)children.elementAt(i)).apply(kid, xwt, pis);
137 b.putAndTriggerTraps(JS.N(b.treeSize()), kid);
140 if (script != null) script.cloneWithNewParentScope(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");
166 b.putAndTriggerTraps(key, val);
172 // XML Parsing /////////////////////////////////////////////////////////////////
174 /** handles XML parsing; builds a Template tree as it goes */
175 static final class TemplateHelper extends XML {
180 private static final int STATE_INITIAL = 0;
181 private static final int STATE_IN_XWT_NODE = 1;
182 private static final int STATE_IN_TEMPLATE_NODE = 2;
183 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
185 private String nameOfHeaderNodeBeingProcessed;
187 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
188 Template t = null; ///< the template we're currently working on
190 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
191 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
192 state = STATE_INITIAL;
193 nameOfHeaderNodeBeingProcessed = null;
194 nodeStack.setSize(0);
196 parse(new InputStreamReader(is));
199 public void startElement(XML.Element c) throws XML.Exn {
202 if (!"xwt".equals(c.getLocalName()))
203 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
204 if (c.getAttrLen() != 0)
205 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
206 state = STATE_IN_XWT_NODE;
209 case STATE_IN_XWT_NODE:
210 if (nameOfHeaderNodeBeingProcessed != null)
211 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
212 nameOfHeaderNodeBeingProcessed = c.getLocalName();
213 //#switch(c.getLocalName())
218 if (t.staticscript != null)
219 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
220 if (c.getAttrLen() > 0)
221 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
224 t.startLine = getLine();
225 state = STATE_IN_TEMPLATE_NODE;
226 processBodyElement(c);
229 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
231 case STATE_IN_TEMPLATE_NODE:
232 // push the last node we were in onto the stack
233 nodeStack.addElement(t);
234 // instantiate a new node, and set its fileName/importlist/preapply
235 Template t2 = new Template(t.r);
236 t2.startLine = getLine();
237 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
238 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
239 // make the new node the current node
241 processBodyElement(c);
244 case STATE_FINISHED_TEMPLATE_NODE:
245 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
249 private void processBodyElement(XML.Element c) {
250 Vec keys = new Vec(c.getAttrLen());
251 Vec vals = new Vec(c.getAttrLen());
253 // process attributes into Vecs, dealing with any XML Namespaces in the process
254 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
255 //#switch(c.getAttrKey(i))
257 String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
258 StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
259 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
263 t.id = c.getAttrVal(i).toString().intern();
267 // treat value starting with '.' as resource reference
268 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
269 keys.addElement(c.getAttrKey(i));
270 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
273 if (keys.size() == 0) return;
275 // sort the attributes lexicographically
276 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
277 return ((String)a).compareTo((String)b);
280 t.keys = new String[keys.size()];
281 t.vals = new Object[vals.size()];
282 keys.copyInto(t.keys);
283 vals.copyInto(t.vals);
285 // convert attributes to appropriate types and intern strings
286 for(int i=0; i<t.keys.length; i++) {
287 t.keys[i] = t.keys[i].intern();
289 String valString = t.vals[i].toString();
291 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
292 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
293 else if (valString.equals("null")) t.vals[i] = null;
295 boolean hasNonNumeral = false;
296 boolean periodUsed = false;
297 for(int j=0; j<valString.length(); j++)
298 if (j == 0 && valString.charAt(j) == '-') {
299 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
301 } else if (!Character.isDigit(valString.charAt(j))) {
302 hasNonNumeral = true;
305 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
306 else t.vals[i] = valString.intern();
311 private JSFunction parseScript(boolean isstatic) throws IOException {
312 JSFunction thisscript = null;
313 String contentString = t.content.toString();
314 if (contentString.trim().length() > 0)
315 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
317 new StringReader(contentString));
323 public void endElement(XML.Element c) throws XML.Exn, IOException {
324 if (state == STATE_IN_XWT_NODE) {
325 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
326 nameOfHeaderNodeBeingProcessed = null;
328 } else if (state == STATE_IN_TEMPLATE_NODE) {
329 if (t.content != null) t.script = parseScript(false);
330 if (nodeStack.size() == 0) {
332 state = STATE_FINISHED_TEMPLATE_NODE;
335 // add this template as a child of its parent
337 t = (Template)nodeStack.lastElement();
338 nodeStack.setSize(nodeStack.size() - 1);
339 t.children.addElement(oldt);
341 int oldt_lines = getLine() - oldt.startLine;
342 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
347 public void characters(char[] ch, int start, int length) throws XML.Exn {
348 // invoke the no-tab crusade
349 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
350 throw new XML.Exn("tabs are not allowed in XWT files", XML.Exn.SCHEMA, getLine(), getCol());
352 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
353 if (t.content == null) {
354 t.content_start = getLine();
355 t.content = new StringBuffer();
358 t.content.append(ch, start, length);
360 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
361 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
365 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
368 private static class PerInstantiationJSScope extends JSScope {
370 PerInstantiationJSScope parentBoxPis = null;
371 JSScope myStatic = null;
372 void putDollar(String key, Box target) throws JSExn {
373 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
375 put("$" + key, target);
377 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
379 this.parentBoxPis = parentBoxPis;
381 this.myStatic = myStatic;
383 public Object get(Object key) throws JSExn {
384 if (super.has(key)) return super.get(key);
385 if (key.equals("xwt")) return xwt;
386 if (key.equals("")) return xwt.rr;
387 if (key.equals("static")) return myStatic;
388 return super.get(key);
390 public void put(Object key, Object val) throws JSExn {
391 if (super.has(key)) super.put(key, val);
392 else super.put(key, val);