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) {
58 r = r.addExtension(".xwt");
59 if (r.t != null) return r.t;
60 r.t = new Template(r);
61 try { new TemplateHelper().parseit(r.getInputStream(), r.t); }
62 catch (FileNotFoundException e) { Log.log(Template.class, "template not found: "+r); }
64 } catch (Exception e) {
65 if (Log.on) Log.log(r.t == null ? "null" : r.t.fileName, e);
70 public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) {
72 if (str.indexOf("://") != -1) {
74 if (permitAbsolute) return (Res)xwt.callMethod("res.url", str, null, null, null, 1);
76 throw new Error("this should never happen");
78 Log.log(Template.class, "absolute URL " + str + " not permitted here");
84 while(str.indexOf('.') != -1) {
85 String path = str.substring(0, str.indexOf('.'));
86 str = str.substring(str.indexOf('.') + 1);
87 ret = (Res)ret.get(path);
89 ret = (Res)ret.get(str);
94 // Methods to apply templates ////////////////////////////////////////////////////////
96 private Template(Res r) {
98 String f = r.toString();
99 if (f != null && !f.equals(""))
100 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
103 /** called before this template is applied or its static object can be externally referenced */
104 JSScope getStatic() {
105 if (staticJSScope == null) staticJSScope = new JSScope(null);
106 if (staticscript == null) return staticJSScope;
107 JSFunction temp = staticscript;
110 temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
111 } catch (JSExn jse) {
112 throw new Error("this should never happen");
114 return staticJSScope;
117 /** Applies the template to Box b
118 * @param pboxes a vector of all box parents on which to put $-references
119 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
121 void apply(Box b, XWT xwt) throws JSExn { apply(b, xwt, null); }
122 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);
142 for(int i=0; keys != null && i<keys.length; i++)
143 if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') {
144 Object rbox = pis.get(vals[i]);
145 if (rbox == null) Log.log(this, "unknown box id '"+vals[i]+"' referenced");
146 else b.putAndTriggerTraps(keys[i], rbox);
148 else if ("image".equals(keys[i])) b.putAndTriggerTraps("image", resolveStringToResource((String)vals[i], xwt, true));
149 else if ("redirect".equals(keys[i])) {
150 if (vals[i] == null || "null".equals(vals[i])) b.putAndTriggerTraps("redirect", null);
151 Object rbox = pis.get("$"+vals[i]);
152 if (rbox == null) Log.log(this, "redirect target '"+vals[i]+"' not found");
153 else b.putAndTriggerTraps("redirect", rbox);
155 else if (keys[i] != null) b.putAndTriggerTraps(keys[i], vals[i]);
160 // XML Parsing /////////////////////////////////////////////////////////////////
162 /** handles XML parsing; builds a Template tree as it goes */
163 static final class TemplateHelper extends XML {
168 private static final int STATE_INITIAL = 0;
169 private static final int STATE_IN_XWT_NODE = 1;
170 private static final int STATE_IN_TEMPLATE_NODE = 2;
171 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
173 private String nameOfHeaderNodeBeingProcessed;
175 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
176 Template t = null; ///< the template we're currently working on
178 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
179 void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
180 state = STATE_INITIAL;
181 nameOfHeaderNodeBeingProcessed = null;
182 nodeStack.setSize(0);
184 parse(new InputStreamReader(is));
187 public void startElement(XML.Element c) throws XML.SchemaException {
190 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
191 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
192 state = STATE_IN_XWT_NODE;
195 case STATE_IN_XWT_NODE:
196 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
197 nameOfHeaderNodeBeingProcessed = c.localName;
198 if (c.localName.equals("doc")) {
200 } else if (c.localName.equals("static")) {
201 if (t.staticscript != null)
202 throw new XML.SchemaException("the <static> header node may not appear more than once");
204 throw new XML.SchemaException("the <static> node may not have attributes");
205 } else if (c.localName.equals("template")) {
206 t.startLine = getLine();
207 state = STATE_IN_TEMPLATE_NODE;
208 processBodyElement(c);
210 throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
214 case STATE_IN_TEMPLATE_NODE:
215 // push the last node we were in onto the stack
216 nodeStack.addElement(t);
217 // instantiate a new node, and set its fileName/importlist/preapply
218 Template t2 = new Template(t.r);
219 t2.startLine = getLine();
220 if (!c.localName.equals("box") && !c.localName.equals("template"))
221 t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
222 // make the new node the current node
224 processBodyElement(c);
227 case STATE_FINISHED_TEMPLATE_NODE:
228 throw new XML.SchemaException("no elements may appear after the <template> node");
232 private void processBodyElement(XML.Element c) {
233 Hash h = new Hash(c.len * 2, 3);
235 // WARNING: c.keys.length != c.len; USE c.len
236 for(int i=0; i<c.len; i++) {
237 if (c.keys[i] == null) throw new RuntimeException("XML parser returned a null key position="+i);
238 if (c.keys[i].equals("font") && c.uris[i] != null) c.vals[i] = c.uris[i] + "." + c.vals[i];
239 if (c.keys[i].equals("preapply")) {
240 // process preapply and 'remove' from array
241 String uri = c.uris[i] == null ? "" : c.uris[i] + '.';
242 StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
243 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
245 if (i < c.len - 1) { // not the last attribute
246 c.keys[i] = c.keys[c.len - 1];
247 c.vals[i] = c.vals[c.len - 1];
248 c.uris[i] = c.uris[c.len - 1];
253 h.put(c.keys[i], c.vals[i]);
255 t.keys = new String[h.size()];
256 t.vals = new Object[h.size()];
258 Vec v = new Vec(h.size(), c.keys);
259 v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
260 for(int i=0; i<h.size(); i++) {
261 if (c.keys[i].equals("thisbox")) {
262 for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
263 t.keys[0] = (String)v.elementAt(i);
264 t.vals[0] = h.get(t.keys[0]);
266 t.keys[i] = (String)v.elementAt(i);
267 t.vals[i] = h.get(t.keys[i]);
271 for(int i=0; i<t.keys.length; i++) {
272 if (t.keys[i].equals("id")) {
273 t.id = t.vals[i].toString().intern();
278 t.keys[i] = t.keys[i].intern();
280 String valString = t.vals[i].toString();
282 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
283 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
284 else if (valString.equals("null")) t.vals[i] = null;
286 boolean hasNonNumeral = false;
287 boolean periodUsed = false;
288 for(int j=0; j<valString.length(); j++)
289 if (j == 0 && valString.charAt(j) == '-') {
290 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
292 } else if (!Character.isDigit(valString.charAt(j))) {
293 hasNonNumeral = true;
296 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
297 else t.vals[i] = valString.intern();
302 private JSFunction parseScript(boolean isstatic) {
303 JSFunction thisscript = null;
305 String contentString = t.content.toString();
306 if (contentString.trim().length() > 0)
307 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
309 new StringReader(contentString));
310 } catch (IOException ioe) {
311 if (Log.on) Log.log(this, " ERROR: " + ioe.getMessage());
319 public void endElement(XML.Element c) throws XML.SchemaException {
320 if (state == STATE_IN_XWT_NODE) {
321 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
322 nameOfHeaderNodeBeingProcessed = null;
324 } else if (state == STATE_IN_TEMPLATE_NODE) {
325 if (t.content != null) t.script = parseScript(false);
326 if (nodeStack.size() == 0) {
328 state = STATE_FINISHED_TEMPLATE_NODE;
331 // add this template as a child of its parent
333 t = (Template)nodeStack.lastElement();
334 nodeStack.setSize(nodeStack.size() - 1);
335 t.children.addElement(oldt);
337 int oldt_lines = getLine() - oldt.startLine;
338 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
343 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
344 // invoke the no-tab crusade
345 for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
346 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
348 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
349 if (t.content == null) {
350 t.content_start = getLine();
351 t.content = new StringBuffer();
354 t.content.append(ch, start, length);
356 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
357 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
361 public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
364 private static class PerInstantiationJSScope extends JSScope {
366 PerInstantiationJSScope parentBoxPis = null;
367 JSScope myStatic = null;
368 void putDollar(String key, Box target) throws JSExn {
369 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
371 put("$" + key, target);
373 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
375 this.parentBoxPis = parentBoxPis;
377 this.myStatic = myStatic;
379 public Object get(Object key) throws JSExn {
380 if (super.has(key)) return super.get(key);
381 if (key.equals("xwt")) return xwt;
382 if (key.equals("static")) return myStatic;
383 return super.get(key);
385 public void put(Object key, Object val) throws JSExn {
386 if (super.has(key)) super.put(key, val);
387 else super.put(key, val);