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 new TemplateHelper().parseit(r.getInputStream(), r.t);
63 } catch (Exception e) {
64 if (Log.on) Log.log(r.t == null ? "null" : r.t.fileName, e);
69 public static Res resolveStringToResource(String str, XWT xwt, boolean permitAbsolute) {
71 if (str.indexOf("://") != -1) {
73 //if (permitAbsolute) return Res.fromString(str);
74 Log.log(Template.class, "absolute URL " + str + " not permitted here");
80 while(str.indexOf('.') != -1) {
81 String path = str.substring(0, str.indexOf('.'));
82 str = str.substring(str.indexOf('.') + 1);
83 ret = (Res)ret.get(path);
85 ret = (Res)ret.get(str);
90 // Methods to apply templates ////////////////////////////////////////////////////////
92 private Template(Res r) {
94 String f = r.toString();
95 if (f != null && !f.equals(""))
96 fileName = f.substring(f.lastIndexOf('/')+1, f.endsWith(".xwt") ? f.length() - 4 : f.length());
99 /** called before this template is applied or its static object can be externally referenced */
100 JSScope getStatic() {
101 if (staticJSScope == null) staticJSScope = new JSScope(null);
102 if (staticscript == null) return staticJSScope;
103 JSFunction temp = staticscript;
105 temp.cloneWithNewParentScope(staticJSScope).call(null, null, null, null, 0);
106 return staticJSScope;
109 /** Applies the template to Box b
110 * @param pboxes a vector of all box parents on which to put $-references
111 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
113 void apply(Box b, XWT xwt) { apply(b, xwt, null); }
114 void apply(Box b, XWT xwt, PerInstantiationJSScope parentPis) {
118 if (id != null) parentPis.putDollar(id, b);
119 for(int i=0; i<preapply.size(); i++) {
120 Template t = getTemplate(resolveStringToResource((String)preapply.elementAt(i), xwt, false));
121 if (t == null) throw new RuntimeException("unable to resolve resource " + preapply.elementAt(i));
125 PerInstantiationJSScope pis = new PerInstantiationJSScope(b, xwt, parentPis, staticJSScope);
126 for (int i=0; children != null && i<children.size(); i++) {
128 ((Template)children.elementAt(i)).apply(kid, xwt, pis);
129 b.putAndTriggerTraps(JS.N(b.numchildren), kid);
132 if (script != null) script.cloneWithNewParentScope(pis).call(null, null, null, null, 0);
134 for(int i=0; keys != null && i<keys.length; i++)
135 if (vals[i] instanceof String && ((String)vals[i]).charAt(0) == '$') b.putAndTriggerTraps(keys[i], pis.get(vals[i]));
136 else if ("image".equals(keys[i])) b.putAndTriggerTraps("image", resolveStringToResource((String)vals[i], xwt, true));
137 else if (keys[i] != null) b.putAndTriggerTraps(keys[i], vals[i]);
142 // XML Parsing /////////////////////////////////////////////////////////////////
144 /** handles XML parsing; builds a Template tree as it goes */
145 static final class TemplateHelper extends XML {
150 private static final int STATE_INITIAL = 0;
151 private static final int STATE_IN_XWT_NODE = 1;
152 private static final int STATE_IN_TEMPLATE_NODE = 2;
153 private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
155 private String nameOfHeaderNodeBeingProcessed;
157 Vec nodeStack = new Vec(); ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
158 Template t = null; ///< the template we're currently working on
160 /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
161 void parseit(InputStream is, Template root) throws XML.XMLException, IOException {
162 state = STATE_INITIAL;
163 nameOfHeaderNodeBeingProcessed = null;
164 nodeStack.setSize(0);
166 parse(new InputStreamReader(is));
169 public void startElement(XML.Element c) throws XML.SchemaException {
172 if (!"xwt".equals(c.localName)) throw new XML.SchemaException("root element was not <xwt>");
173 if (c.len != 0) throw new XML.SchemaException("root element must not have attributes");
174 state = STATE_IN_XWT_NODE;
177 case STATE_IN_XWT_NODE:
178 if (nameOfHeaderNodeBeingProcessed != null) throw new XML.SchemaException("can't nest header nodes");
179 nameOfHeaderNodeBeingProcessed = c.localName;
180 if (c.localName.equals("doc")) {
182 } else if (c.localName.equals("static")) {
183 if (t.staticscript != null)
184 throw new XML.SchemaException("the <static> header node may not appear more than once");
186 throw new XML.SchemaException("the <static> node may not have attributes");
187 } else if (c.localName.equals("template")) {
188 t.startLine = getLine();
189 state = STATE_IN_TEMPLATE_NODE;
190 processBodyElement(c);
192 throw new XML.SchemaException("unrecognized header node \"" + c.localName + "\"");
196 case STATE_IN_TEMPLATE_NODE:
197 // push the last node we were in onto the stack
198 nodeStack.addElement(t);
199 // instantiate a new node, and set its fileName/importlist/preapply
200 Template t2 = new Template(t.r);
201 t2.startLine = getLine();
202 if (!c.localName.equals("box") && !c.localName.equals("template"))
203 t2.preapply.addElement((c.uri == null ? "" : (c.uri + ".")) + c.localName);
204 // make the new node the current node
206 processBodyElement(c);
209 case STATE_FINISHED_TEMPLATE_NODE:
210 throw new XML.SchemaException("no elements may appear after the <template> node");
214 private void processBodyElement(XML.Element c) {
215 Hash h = new Hash(c.len * 2, 3);
216 for(int i=0; i<c.len; i++) {
217 if (c.keys[i] == null) continue;
218 if (c.keys[i].equals("font")) c.vals[i] = c.uris[i] + "." + c.vals[i];
219 if (c.keys[i].equals("preapply")) {
220 String uri = c.uris[i];
221 StringTokenizer tok = new StringTokenizer(c.vals[i].toString(), " ");
222 while(tok.hasMoreTokens()) t.preapply.addElement(uri + tok.nextToken());
223 c.keys[i] = c.keys[c.keys.length - 1];
224 c.vals[i] = c.vals[c.vals.length - 1];
228 h.put(c.keys[i], c.vals[i]);
230 t.keys = new String[h.size()];
231 t.vals = new Object[h.size()];
233 Vec v = new Vec(h.size(), c.keys);
234 v.sort(new Vec.CompareFunc() { public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); } });
235 for(int i=0; i<h.size(); i++) {
236 if (c.keys[i].equals("thisbox")) {
237 for(int j=i; j>0; j--) { t.keys[j] = t.keys[j - 1]; t.vals[j] = t.vals[j - 1]; }
238 t.keys[0] = (String)v.elementAt(i);
239 t.vals[0] = h.get(t.keys[0]);
241 t.keys[i] = (String)v.elementAt(i);
242 t.vals[i] = h.get(t.keys[i]);
246 for(int i=0; i<t.keys.length; i++) {
247 if (t.keys[i].equals("id")) {
248 t.id = t.vals[i].toString().intern();
253 t.keys[i] = t.keys[i].intern();
255 String valString = t.vals[i].toString();
257 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
258 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
259 else if (valString.equals("null")) t.vals[i] = null;
261 boolean hasNonNumeral = false;
262 boolean periodUsed = false;
263 for(int j=0; j<valString.length(); j++)
264 if (j == 0 && valString.charAt(j) == '-') {
265 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
267 } else if (!Character.isDigit(valString.charAt(j))) {
268 hasNonNumeral = true;
271 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
272 else t.vals[i] = valString.intern();
277 private JSFunction parseScript(boolean isstatic) {
278 JSFunction thisscript = null;
280 String contentString = t.content.toString();
281 if (contentString.trim().length() > 0)
282 thisscript = JSFunction.fromReader(t.fileName + (isstatic ? "._" : ""),
284 new StringReader(contentString));
285 } catch (IOException ioe) {
286 if (Log.on) Log.log(this, " ERROR: " + ioe.getMessage());
294 public void endElement(XML.Element c) throws XML.SchemaException {
295 if (state == STATE_IN_XWT_NODE) {
296 if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
297 nameOfHeaderNodeBeingProcessed = null;
299 } else if (state == STATE_IN_TEMPLATE_NODE) {
300 if (t.content != null) t.script = parseScript(false);
301 if (nodeStack.size() == 0) {
303 state = STATE_FINISHED_TEMPLATE_NODE;
306 // add this template as a child of its parent
308 t = (Template)nodeStack.lastElement();
309 nodeStack.setSize(nodeStack.size() - 1);
310 t.children.addElement(oldt);
312 int oldt_lines = getLine() - oldt.startLine;
313 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
318 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
319 // invoke the no-tab crusade
320 for (int i=0; length >i; i++) if (ch[start+i] == '\t') throw new XML.SchemaException(
321 t.fileName+ ":" + getLine() + "," + getCol() + ": tabs are not allowed in XWT files");
323 if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
324 if (t.content == null) {
325 t.content_start = getLine();
326 t.content = new StringBuffer();
329 t.content.append(ch, start, length);
331 } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) {
332 throw new XML.SchemaException("header node <" + nameOfHeaderNodeBeingProcessed + "> cannot have text content");
336 public void whitespace(char[] ch, int start, int length) throws XML.SchemaException { }
339 private static class PerInstantiationJSScope extends JSScope {
341 PerInstantiationJSScope parentBoxPis = null;
342 JSScope myStatic = null;
343 void putDollar(String key, Box target) {
344 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
346 put("$" + key, target);
348 public PerInstantiationJSScope(JSScope parentScope, XWT xwt, PerInstantiationJSScope parentBoxPis, JSScope myStatic) {
350 this.parentBoxPis = parentBoxPis;
352 this.myStatic = myStatic;
354 public Object get(Object key) {
355 if (super.has(key)) return super.get(key);
356 if (key.equals("xwt")) return xwt;
357 if (key.equals("static")) return myStatic;
358 return super.get(key);
360 public void put(Object key, Object val) {
361 if (super.has(key)) super.put(key, val);
362 else super.put(key, val);