1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.ibex.util.*;
10 * Encapsulates a template node (the <template/> element of a
11 * .ibex file, or any child element thereof).
13 * Note that the Template instance corresponding to the
14 * <template/> node carries all the header information -- hence
15 * some of the instance members are not meaningful on non-root
16 * Template instances. We refer to these non-root instances as
17 * <i>anonymous templates</i>.
19 * See the Ibex reference for information on the order in which
20 * templates are applied, attributes are put, and scripts are run.
22 public class Template {
24 // Instance Members ///////////////////////////////////////////////////////
26 String id = null; ///< the id of this box
27 String redirect = null; ///< the id of the redirect target; only meaningful on a root node
28 private String[] keys; ///< keys to be "put" to instances of this template; elements correspond to those of vals
29 private Object[] vals; ///< values to be "put" to instances of this template; elements correspond to those of keys
30 private String[] urikeys;
31 private String[] urivals;
32 private Vec children = new Vec(); ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
33 private JS script = null; ///< the script on this node
35 JSScope staticScope = null; ///< the scope in which the static block is executed
38 // Only used during parsing /////////////////////////////////////////////////////////////////
40 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
41 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
42 private int startLine = -1; ///< the line number that this element starts on
46 // Static data/methods ///////////////////////////////////////////////////////////////////
49 private Template(Template t, int startLine) { prev = t; this.ibex = t.ibex; this.startLine = startLine; }
50 private Template(Ibex ibex) { this.ibex = ibex; }
53 // Methods to apply templates ////////////////////////////////////////////////////////
56 /** Applies the template to Box b
57 * @param pboxes a vector of all box parents on which to put $-references
58 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
60 void apply(Box b) throws JSExn {
63 } catch (IOException e) {
67 throw new JSExn(e.toString());
76 private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
77 if (prev != null) prev.apply(b, null);
79 // FIXME this dollar stuff is all wrong
80 if (id != null) parentPis.putDollar(id, b);
82 PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticScope);
83 for(int i=0; i<urikeys.length; i++) {
84 if (urikeys[i] == null) continue;
85 pis.declare(urikeys[i]);
86 pis.put(urikeys[i], ibex.resolveString(urivals[i], true));
89 // FIXME needs to obey the new application-ordering rules
90 for (int i=0; children != null && i<children.size(); i++) {
92 ((Template)children.elementAt(i)).apply(kid, pis);
93 b.putAndTriggerTraps(b.get("numchildren"), kid);
96 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
99 for(int i=0; keys != null && i < keys.length; i++) {
100 if (keys[i] == null) continue;
104 if ("null".equals(val)) val = null;
106 if (val != null && val instanceof String && ((String)val).length() > 0) {
107 switch (((String)val).charAt(0)) {
110 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
113 val = ibex.resolveString(((String)val).substring(1), false);
115 // FIXME: should we be resolving all of these in the XML-parsing code?
119 b.putAndTriggerTraps(key, val);
125 // XML Parsing /////////////////////////////////////////////////////////////////
127 public static Template buildTemplate(String sourceName, Object s, Ibex ibex) {
129 return new TemplateHelper(sourceName, s, ibex).t;
130 } catch (Exception e) {
131 Log.error(Template.class, e);
136 /** handles XML parsing; builds a Template tree as it goes */
137 static final class TemplateHelper extends XML {
140 private int state = STATE_INITIAL;
141 private static final int STATE_INITIAL = 0;
142 private static final int STATE_IN_ROOT_NODE = 1;
143 private static final int STATE_IN_TEMPLATE_NODE = 2;
144 private static final int STATE_IN_META_NODE = 3;
146 StringBuffer static_content = null;
147 int static_content_start = 0;
148 Vec nodeStack = new Vec();
153 String initial_uri = "";
155 public TemplateHelper(String sourceName, Object s, Ibex ibex) throws XML.Exn, IOException, JSExn {
156 this.sourceName = sourceName;
158 InputStream is = Stream.getInputStream(s);
159 Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
161 initial_uri = (b.parentkey == null ? "" : (b.parentkey + ".")) + initial_uri;
164 parse(new InputStreamReader(is));
165 JS staticScript = parseScript(static_content, static_content_start);
166 t.staticScope = new PerInstantiationScope(null, ibex, null, null);
167 if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
170 private JS parseScript(StringBuffer content, int content_start) throws IOException {
171 if (content == null) return null;
172 String contentString = content.toString();
173 if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
177 public void startElement(XML.Element c) throws XML.Exn {
179 case STATE_IN_META_NODE: { meta++; return; }
181 if (!"ibex".equals(c.getLocalName()))
182 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
183 if (c.getAttrLen() != 0)
184 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
185 if (c.getUri("ui") == null || "".equals(c.getUri("ui"))) c.addUri("ui", "ibex://ui");
186 if (c.getUri("meta") == null || "".equals(c.getUri("meta"))) c.addUri("meta", "ibex://meta");
187 if (c.getUri("") == null || "".equals(c.getUri(""))) c.addUri("", initial_uri);
188 state = STATE_IN_ROOT_NODE;
190 case STATE_IN_ROOT_NODE:
191 if ("ibex://meta".equals(c.getUri())) {
192 state = STATE_IN_META_NODE; meta = 0; return;
194 state = STATE_IN_TEMPLATE_NODE;
195 t = (t == null) ? new Template(ibex) : new Template(t, getLine());
197 case STATE_IN_TEMPLATE_NODE:
198 nodeStack.addElement(t);
199 t = new Template(ibex);
203 if (!("ibex://ui".equals(c.getUri()) && "box".equals(c.getLocalName()))) {
204 String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
207 t.prev = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
208 } catch (Exception e) {
209 Log.error(Template.class, e);
213 Hash urimap = c.getUriMap();
214 t.urikeys = new String[urimap.size()];
215 t.urivals = new String[urimap.size()];
216 Enumeration uriEnumeration = urimap.keys();
218 while(uriEnumeration.hasMoreElements()) {
219 String key = (String)uriEnumeration.nextElement();
220 String val = (String)urimap.get(key);
221 if (val.equals("ibex://ui")) continue;
222 if (val.equals("ibex://meta")) continue;
224 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
229 Vec keys = new Vec(c.getAttrLen());
230 Vec vals = new Vec(c.getAttrLen());
232 // process attributes into Vecs, dealing with any XML Namespaces in the process
233 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
234 //#switch(c.getAttrKey(i))
236 t.id = c.getAttrVal(i).toString().intern();
240 // treat value starting with '.' as resource reference
241 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
242 keys.addElement(c.getAttrKey(i));
243 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
246 if (keys.size() == 0) return;
248 // sort the attributes lexicographically
249 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
250 return ((String)a).compareTo((String)b);
253 t.keys = new String[keys.size()];
254 t.vals = new Object[vals.size()];
255 keys.copyInto(t.keys);
256 vals.copyInto(t.vals);
258 // convert attributes to appropriate types and intern strings
259 for(int i=0; i<t.keys.length; i++) {
260 t.keys[i] = t.keys[i].intern();
262 String valString = t.vals[i].toString();
264 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
265 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
266 else if (valString.equals("null")) t.vals[i] = null;
268 boolean hasNonNumeral = false;
269 boolean periodUsed = false;
270 for(int j=0; j<valString.length(); j++)
271 if (j == 0 && valString.charAt(j) == '-') {
272 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
274 } else if (!Character.isDigit(valString.charAt(j))) {
275 hasNonNumeral = true;
278 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
279 else t.vals[i] = valString.intern();
284 public void endElement(XML.Element c) throws XML.Exn, IOException {
286 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
287 case STATE_IN_ROOT_NODE: return;
288 case STATE_IN_TEMPLATE_NODE: {
289 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
290 if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
292 t = (Template)nodeStack.lastElement();
293 nodeStack.setSize(nodeStack.size() - 1);
294 t.children.addElement(oldt);
295 int oldt_lines = getLine() - oldt.startLine;
296 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
301 public void characters(char[] ch, int start, int length) throws XML.Exn {
302 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
303 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
305 case STATE_IN_TEMPLATE_NODE:
306 if (t.content == null) {
307 t.content_start = getLine();
308 t.content = new StringBuffer();
310 t.content.append(ch, start, length);
312 case STATE_IN_ROOT_NODE:
313 if (static_content == null) {
314 static_content_start = getLine();
315 static_content = new StringBuffer();
317 static_content.append(ch, start, length);
322 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
325 private static class PerInstantiationScope extends JSScope {
327 PerInstantiationScope parentBoxPis = null;
328 JSScope myStatic = null;
329 void putDollar(String key, Box target) throws JSExn {
330 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
332 put("$" + key, target);
334 public PerInstantiationScope(JSScope parentScope, Ibex ibex, PerInstantiationScope parentBoxPis, JSScope myStatic) {
336 this.parentBoxPis = parentBoxPis;
338 this.myStatic = myStatic;
340 public Object get(Object key) throws JSExn {
341 if (super.has(key)) return super.get(key);
342 if (key.equals("ibex")) return ibex;
343 if (key.equals("")) return ibex.get("");
344 if (key.equals("static")) return myStatic;
345 return super.get(key);