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.XMLException, 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.SchemaException {
193 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
194 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
195 state = STATE_IN_XWT_NODE;
198 case STATE_IN_XWT_NODE:
199 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
200 nameOfHeaderNodeBeingProcessed = c.localName;
201 if (c.localName.equals("doc")) {
203 } else if (c.localName.equals("static")) {
204 if (t.staticscript != null)
205 throw new XML.SchemaException("the <static> header node may not appear more than once");
207 throw new XML.SchemaException("the <static> node may not have attributes");
208 } else if (c.localName.equals("template")) {
209 t.startLine = getLine();
210 state = STATE_IN_TEMPLATE_NODE;
211 processBodyElement(c);
213 throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
217 case STATE_IN_TEMPLATE_NODE:
218 // push the last node we were in onto the stack
219 nodeStack.addElement(t);
220 // instantiate a new node, and set its fileName/importlist/preapply
221 Template t2 = new Template(t.r);
222 t2.startLine = getLine();
223 if (!c.localName.equals("box") && !c.localName.equals("template"))
224 t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
225 // make the new node the current node
227 processBodyElement(c);
230 case STATE_FINISHED_TEMPLATE_NODE:
231 throw new XML.SchemaException("no elements may appear after the <template> node");
235 private void processBodyElement(XML.Element c) {
236 Hash h = new Hash(c.len * 2, 3);
238 // WARNING: c.keys.length != c.len; USE c.len
239 for(int i=0; i<c.len; i++) {
240 if (c.keys[i] == null) throw new RuntimeException("XML parser returned a null key position="+i);
241 else if (c.keys[i].equals("font") && c.uris[i] != null) c.vals[i] = c.uris[i] + "." + c.vals[i];
242 else if (c.keys[i].equals("fill") && c.uris[i] != null && !c.vals[i].startsWith("#")
243 && SVG.colors.get(c.vals[i]) == null) c.vals[i] = c.uris[i] + "." + c.vals[i];
244 else if (c.keys[i].equals("preapply")) {
245 // process preapply and 'remove' from array
246 String uri = c.uris[i] == null ? "" : c.uris[i] + '.';
247 StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
248 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
250 if (i < c.len - 1) { // not the last attribute
251 c.keys[i] = c.keys[c.len - 1];
252 c.vals[i] = c.vals[c.len - 1];
253 c.uris[i] = c.uris[c.len - 1];
258 h.put(c.keys[i], c.vals[i]);
260 t.keys = new String[h.size()];
261 t.vals = new Object[h.size()];
263 Vec v = new Vec(h.size(), c.keys);
264 v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
265 for(int i=0; i<h.size(); i++) {
266 if (c.keys[i].equals("thisbox")) {
267 for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
268 t.keys[0] = (String)v.elementAt(i);
269 t.vals[0] = h.get(t.keys[0]);
271 t.keys[i] = (String)v.elementAt(i);
272 t.vals[i] = h.get(t.keys[i]);
276 for(int i=0; i<t.keys.length; i++) {
277 if (t.keys[i].equals("id")) {
278 t.id = t.vals[i].toString().intern();
283 t.keys[i] = t.keys[i].intern();
285 String valString = t.vals[i].toString();
287 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
288 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
289 else if (valString.equals("null")) t.vals[i] = null;
291 boolean hasNonNumeral = false;
292 boolean periodUsed = false;
293 for(int j=0; j<valString.length(); j++)
294 if (j == 0 && valString.charAt(j) == '-') {
295 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
297 } else if (!Character.isDigit(valString.charAt(j))) {
298 hasNonNumeral = true;
301 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
302 else t.vals[i] = valString.intern();
307 private JSFunction parseScript(boolean isstatic) throws IOException {
308 JSFunction thisscript = null;
309 String contentString = t.content.toString();
310 if (contentString.trim().length() > 0)
311 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
313 new StringReader(contentString));
319 public void endElement(XML.Element c) throws XML.SchemaException, IOException {
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("")) return xwt.rr;
383 if (key.equals("static")) return myStatic;
384 return super.get(key);
386 public void put(Object key, Object val) throws JSExn {
387 if (super.has(key)) super.put(key, val);
388 else super.put(key, val);