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.log(Template.class, "WARNING: exception (below) thrown during application of template;");
117 Log.log(Template.class, " setting visibility of target box to \"false\"");
123 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, staticJSScope);
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);
143 for(int i=0; keys != null && i<keys.length; i++)
144 if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') {
145 Object rbox = pis.get(vals[i]);
146 if (rbox == null) Log.log(this, "unknown box id '"+vals[i]+"' referenced in XML attribute");
147 else b.putAndTriggerTraps(keys[i], rbox);
149 else if ("fill".equals(keys[i]) && ((String)vals[i]).indexOf('.') >= 0) {
150 b.putAndTriggerTraps("fill", resolveStringToResource((String)vals[i], xwt, true));
152 else if ("redirect".equals(keys[i])) {
153 if (vals[i] == null || "null".equals(vals[i])) b.putAndTriggerTraps("redirect", null);
154 Object rbox = pis.get("$"+vals[i]);
155 if (rbox == null) Log.log(this, "redirect target '"+vals[i]+"' not found");
156 else b.putAndTriggerTraps("redirect", rbox);
158 else if (keys[i] != null) b.putAndTriggerTraps(keys[i], vals[i]);
163 // XML Parsing /////////////////////////////////////////////////////////////////
165 /** handles XML parsing; builds a Template tree as it goes */
166 static final class TemplateHelper extends XML {
171 private static final int STATE_INITIAL = 0;
172 private static final int STATE_IN_XWT_NODE = 1;
173 private static final int STATE_IN_TEMPLATE_NODE = 2;
174 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
176 private String nameOfHeaderNodeBeingProcessed;
178 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
179 Template t = null; ///< the template we're currently working on
181 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
182 void parseit(InputStream is, Template root) throws XML.Exn, IOException {
183 state = STATE_INITIAL;
184 nameOfHeaderNodeBeingProcessed = null;
185 nodeStack.setSize(0);
187 parse(new InputStreamReader(is));
190 public void startElement(XML.Element c) throws XML.Exn {
193 if (!"xwt".equals(c.getLocalName()))
194 throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
195 if (c.getAttrLen() != 0)
196 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
197 state = STATE_IN_XWT_NODE;
200 case STATE_IN_XWT_NODE:
201 if (nameOfHeaderNodeBeingProcessed != null)
202 throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
203 nameOfHeaderNodeBeingProcessed = c.getLocalName();
204 //#switch(c.getLocalName())
209 if (t.staticscript != null)
210 throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
211 if (c.getAttrLen() > 0)
212 throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
215 t.startLine = getLine();
216 state = STATE_IN_TEMPLATE_NODE;
217 processBodyElement(c);
220 throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
222 case STATE_IN_TEMPLATE_NODE:
223 // push the last node we were in onto the stack
224 nodeStack.addElement(t);
225 // instantiate a new node, and set its fileName/importlist/preapply
226 Template t2 = new Template(t.r);
227 t2.startLine = getLine();
228 if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
229 t2.preapply.addElement((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
230 // make the new node the current node
232 processBodyElement(c);
235 case STATE_FINISHED_TEMPLATE_NODE:
236 throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
240 private void processBodyElement(XML.Element c) {
241 Vec keys = new Vec(c.getAttrLen());
242 Vec vals = new Vec(c.getAttrLen());
244 // process attributes into Vecs, dealing with any XML Namespaces in the process
245 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
246 //#switch(c.getAttrKey(i))
248 keys.addElement(c.getAttrKey(i));
249 if (c.getAttrUri(i) != null) vals.addElement(c.getAttrUri(i) + "." + c.getAttrVal(i));
250 else vals.addElement(c.getAttrVal(i));
254 keys.addElement(c.getAttrKey(i));
255 if (c.getAttrUri(i) != null && !c.getAttrVal(i).startsWith("#") && SVG.colors.get(c.getAttrVal(i)) == null)
256 vals.addElement(c.getAttrUri(i) + "." + c.getAttrVal(i));
257 else vals.addElement(c.getAttrVal(i));
260 // process and do not add to box attributes
263 String uri = c.getAttrUri(i); if (!uri.equals("")) uri += ".";
264 StringTokenizer tok = new StringTokenizer(c.getAttrVal(i).toString(), " ");
265 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
269 t.id = c.getAttrVal(i).toString().intern();
273 keys.addElement(c.getAttrKey(i));
274 vals.addElement(c.getAttrVal(i));
277 if (keys.size() == 0) return;
279 // sort the attributes lexicographically
280 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
281 return ((String)a).compareTo((String)b);
285 // merge attributes into template
286 t.keys = new String[keys.size()];
287 t.vals = new Object[vals.size()];
288 keys.copyInto(t.keys);
289 vals.copyInto(t.vals);
291 // convert attributes to appropriate types and intern strings
292 for(int i=0; i<t.keys.length; i++) {
293 t.keys[i] = t.keys[i].intern();
295 String valString = t.vals[i].toString();
297 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
298 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
299 else if (valString.equals("null")) t.vals[i] = null;
301 boolean hasNonNumeral = false;
302 boolean periodUsed = false;
303 for(int j=0; j<valString.length(); j++)
304 if (j == 0 && valString.charAt(j) == '-') {
305 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
307 } else if (!Character.isDigit(valString.charAt(j))) {
308 hasNonNumeral = true;
311 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
312 else t.vals[i] = valString.intern();
317 private JSFunction parseScript(boolean isstatic) throws IOException {
318 JSFunction thisscript = null;
319 String contentString = t.content.toString();
320 if (contentString.trim().length() > 0)
321 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
323 new StringReader(contentString));
329 public void endElement(XML.Element c) throws XML.Exn, IOException {
330 if (state == STATE_IN_XWT_NODE) {
331 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
332 nameOfHeaderNodeBeingProcessed = null;
334 } else if (state == STATE_IN_TEMPLATE_NODE) {
335 if (t.content != null) t.script = parseScript(false);
336 if (nodeStack.size() == 0) {
338 state = STATE_FINISHED_TEMPLATE_NODE;
341 // add this template as a child of its parent
343 t = (Template)nodeStack.lastElement();
344 nodeStack.setSize(nodeStack.size() - 1);
345 t.children.addElement(oldt);
347 int oldt_lines = getLine() - oldt.startLine;
348 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
353 public void characters(char[] ch, int start, int length) throws XML.Exn {
354 // invoke the no-tab crusade
355 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
356 throw new XML.Exn("tabs are not allowed in XWT files", XML.Exn.SCHEMA, getLine(), getCol());
358 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
359 if (t.content == null) {
360 t.content_start = getLine();
361 t.content = new StringBuffer();
364 t.content.append(ch, start, length);
366 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
367 "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
371 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
374 private static class PerInstantiationJSScope extends JSScope {
376 PerInstantiationJSScope parentBoxPis = null;
377 JSScope myStatic = null;
378 void putDollar(String key, Box target) throws JSExn {
379 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
381 put("$" + key, target);
383 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
385 this.parentBoxPis = parentBoxPis;
387 this.myStatic = myStatic;
389 public Object get(Object key) throws JSExn {
390 if (super.has(key)) return super.get(key);
391 if (key.equals("xwt")) return xwt;
392 if (key.equals("")) return xwt.rr;
393 if (key.equals("static")) return myStatic;
394 return super.get(key);
396 public void put(Object key, Object val) throws JSExn {
397 if (super.has(key)) super.put(key, val);
398 else super.put(key, val);