1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
5 import java.util.zip.*;
12 * Encapsulates a template node (the <template/> element of a
13 * .xwt file, or any child element thereof).
15 * Note that the Template instance corresponding to the
16 * <template/> node carries all the header information -- hence
17 * some of the instance members are not meaningful on non-root
18 * Template instances. We refer to these non-root instances as
19 * <i>anonymous templates</i>.
21 * See the XWT reference for information on the order in which
22 * templates are applied, attributes are put, and scripts are run.
24 public class Template {
26 // Instance Members ///////////////////////////////////////////////////////
28 String id = null; ///< the id of this box
29 String redirect = null; ///< the id of the redirect target; only meaningful on a root node
30 private String[] keys; ///< keys to be "put" to instances of this template; elements correspond to those of vals
31 private Object[] vals; ///< values to be "put" to instances of this template; elements correspond to those of keys
32 private Vec children = new Vec(); ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
33 private int numunits = -1; ///< see numUnits(); -1 means that this value has not yet been computed
35 private JSFunction script = null; ///< the script on this node
36 private String fileName = "unknown"; ///< the filename this node came from; used only for debugging
37 private Vec preapply = new Vec(); ///< templates that should be preapplied (in the order of application)
40 // Instance Members that are only meaningful on root Template //////////////////////////////////////
42 private JSScope staticJSScope = null; ///< the scope in which the static block is executed
43 private JSFunction staticscript = null; ///< the script on the static node of this template, null already performed
46 // Only used during parsing /////////////////////////////////////////////////////////////////
48 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
49 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
50 private int startLine = -1; ///< the line number that this element starts on
51 private final Res r; ///< the resource we came from
54 // Static data/methods ///////////////////////////////////////////////////////////////////
56 public static Template getTemplate(Res r) throws JSExn {
58 r = r.addExtension(".xwt");
59 if (r.t != null) return r.t;
60 r.t = new Template(r);
61 new TemplateHelper().parseit(r.getInputStream(), r.t);
63 } catch (Exception e) { throw new JSExn(e.toString());
67 public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) throws JSExn {
69 if (str.indexOf("://") != -1) {
70 if (permitAbsolute) return (Res)xwt.url2res(str);
71 throw new JSExn("absolute URL " + str + " not permitted here");
76 while(str.indexOf('.') != -1) {
77 String path = str.substring(0, str.indexOf('.'));
78 str = str.substring(str.indexOf('.') + 1);
79 ret = (Res)ret.get(path);
81 ret = (Res)ret.get(str);
86 // Methods to apply templates ////////////////////////////////////////////////////////
88 private Template(Res r) {
90 String f = r.toString();
91 if (f != null && !f.equals(""))
92 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
95 /** called before this template is applied or its static object can be externally referenced */
96 JSScope getStatic() throws JSExn {
97 if (staticJSScope == null) staticJSScope = new JSScope(null);
98 if (staticscript == null) return staticJSScope;
99 JSFunction temp = staticscript;
101 temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
102 return staticJSScope;
105 /** Applies the template to Box b
106 * @param pboxes a vector of all box parents on which to put $-references
107 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
109 void apply(Box b, XWT xwt) throws JSExn { apply(b, xwt, null); }
110 void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) throws JSExn {
114 if (id != null) parentPis.putDollar(id, b);
115 for(int i=0; i<preapply.size(); i++) {
116 Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt, false));
117 if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
121 PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticJSScope);
122 for (int i=0; children != null && i<children.size(); i++) {
124 ((Template)children.elementAt(i)).apply(kid, xwt, pis);
125 b.putAndTriggerTraps(JS.N(b.treeSize()), kid);
128 if (script != null) script.cloneWithNewParentScope(pis).call(null, null, null, null, 0);
130 for(int i=0; keys != null && i<keys.length; i++)
131 if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') {
132 Object rbox = pis.get(vals[i]);
133 if (rbox == null) Log.log(this, "unknown box id '"+vals[i]+"' referenced in XML attribute");
134 else b.putAndTriggerTraps(keys[i], rbox);
136 else if ("image".equals(keys[i])) b.putAndTriggerTraps("image", resolveStringToResource((String)vals[i], xwt, true));
137 else if ("redirect".equals(keys[i])) {
138 if (vals[i] == null || "null".equals(vals[i])) b.putAndTriggerTraps("redirect", null);
139 Object rbox = pis.get("$"+vals[i]);
140 if (rbox == null) Log.log(this, "redirect target '"+vals[i]+"' not found");
141 else b.putAndTriggerTraps("redirect", rbox);
143 else if (keys[i] != null) b.putAndTriggerTraps(keys[i], vals[i]);
148 // XML Parsing /////////////////////////////////////////////////////////////////
150 /** handles XML parsing; builds a Template tree as it goes */
151 static final class TemplateHelper extends XML {
156 private static final int STATE_INITIAL = 0;
157 private static final int STATE_IN_XWT_NODE = 1;
158 private static final int STATE_IN_TEMPLATE_NODE = 2;
159 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
161 private String nameOfHeaderNodeBeingProcessed;
163 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
164 Template t = null; ///< the template we're currently working on
166 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
167 void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
168 state = STATE_INITIAL;
169 nameOfHeaderNodeBeingProcessed = null;
170 nodeStack.setSize(0);
172 parse(new InputStreamReader(is));
175 public void startElement(XML.Element c) throws XML.SchemaException {
178 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
179 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
180 state = STATE_IN_XWT_NODE;
183 case STATE_IN_XWT_NODE:
184 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
185 nameOfHeaderNodeBeingProcessed = c.localName;
186 if (c.localName.equals("doc")) {
188 } else if (c.localName.equals("static")) {
189 if (t.staticscript != null)
190 throw new XML.SchemaException("the <static> header node may not appear more than once");
192 throw new XML.SchemaException("the <static> node may not have attributes");
193 } else if (c.localName.equals("template")) {
194 t.startLine = getLine();
195 state = STATE_IN_TEMPLATE_NODE;
196 processBodyElement(c);
198 throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
202 case STATE_IN_TEMPLATE_NODE:
203 // push the last node we were in onto the stack
204 nodeStack.addElement(t);
205 // instantiate a new node, and set its fileName/importlist/preapply
206 Template t2 = new Template(t.r);
207 t2.startLine = getLine();
208 if (!c.localName.equals("box") && !c.localName.equals("template"))
209 t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
210 // make the new node the current node
212 processBodyElement(c);
215 case STATE_FINISHED_TEMPLATE_NODE:
216 throw new XML.SchemaException("no elements may appear after the <template> node");
220 private void processBodyElement(XML.Element c) {
221 Hash h = new Hash(c.len * 2, 3);
223 // WARNING: c.keys.length != c.len; USE c.len
224 for(int i=0; i<c.len; i++) {
225 if (c.keys[i] == null) throw new RuntimeException("XML parser returned a null key position="+i);
226 if (c.keys[i].equals("font") && c.uris[i] != null) c.vals[i] = c.uris[i] + "." + c.vals[i];
227 if (c.keys[i].equals("preapply")) {
228 // process preapply and 'remove' from array
229 String uri = c.uris[i] == null ? "" : c.uris[i] + '.';
230 StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
231 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
233 if (i < c.len - 1) { // not the last attribute
234 c.keys[i] = c.keys[c.len - 1];
235 c.vals[i] = c.vals[c.len - 1];
236 c.uris[i] = c.uris[c.len - 1];
241 h.put(c.keys[i], c.vals[i]);
243 t.keys = new String[h.size()];
244 t.vals = new Object[h.size()];
246 Vec v = new Vec(h.size(), c.keys);
247 v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
248 for(int i=0; i<h.size(); i++) {
249 if (c.keys[i].equals("thisbox")) {
250 for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
251 t.keys[0] = (String)v.elementAt(i);
252 t.vals[0] = h.get(t.keys[0]);
254 t.keys[i] = (String)v.elementAt(i);
255 t.vals[i] = h.get(t.keys[i]);
259 for(int i=0; i<t.keys.length; i++) {
260 if (t.keys[i].equals("id")) {
261 t.id = t.vals[i].toString().intern();
266 t.keys[i] = t.keys[i].intern();
268 String valString = t.vals[i].toString();
270 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
271 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
272 else if (valString.equals("null")) t.vals[i] = null;
274 boolean hasNonNumeral = false;
275 boolean periodUsed = false;
276 for(int j=0; j<valString.length(); j++)
277 if (j == 0 && valString.charAt(j) == '-') {
278 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
280 } else if (!Character.isDigit(valString.charAt(j))) {
281 hasNonNumeral = true;
284 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
285 else t.vals[i] = valString.intern();
290 private JSFunction parseScript(boolean isstatic) throws IOException {
291 JSFunction thisscript = null;
292 String contentString = t.content.toString();
293 if (contentString.trim().length() > 0)
294 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
296 new StringReader(contentString));
302 public void endElement(XML.Element c) throws XML.SchemaException, IOException {
303 if (state == STATE_IN_XWT_NODE) {
304 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
305 nameOfHeaderNodeBeingProcessed = null;
307 } else if (state == STATE_IN_TEMPLATE_NODE) {
308 if (t.content != null) t.script = parseScript(false);
309 if (nodeStack.size() == 0) {
311 state = STATE_FINISHED_TEMPLATE_NODE;
314 // add this template as a child of its parent
316 t = (Template)nodeStack.lastElement();
317 nodeStack.setSize(nodeStack.size() - 1);
318 t.children.addElement(oldt);
320 int oldt_lines = getLine() - oldt.startLine;
321 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
326 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
327 // invoke the no-tab crusade
328 for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
329 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
331 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
332 if (t.content == null) {
333 t.content_start = getLine();
334 t.content = new StringBuffer();
337 t.content.append(ch, start, length);
339 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
340 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
344 public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
347 private static class PerInstantiationJSScope extends JSScope {
349 PerInstantiationJSScope parentBoxPis = null;
350 JSScope myStatic = null;
351 void putDollar(String key, Box target) throws JSExn {
352 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
354 put("$" + key, target);
356 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
358 this.parentBoxPis = parentBoxPis;
360 this.myStatic = myStatic;
362 public Object get(Object key) throws JSExn {
363 if (super.has(key)) return super.get(key);
364 if (key.equals("xwt")) return xwt;
365 if (key.equals("")) return xwt.rr;
366 if (key.equals("static")) return myStatic;
367 return super.get(key);
369 public void put(Object key, Object val) throws JSExn {
370 if (super.has(key)) super.put(key, val);
371 else super.put(key, val);