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 JS[] keys; ///< keys to be "put" to instances of this template; elements correspond to those of vals
29 private JS[] 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
36 JSScope staticScope = null; ///< the scope in which the static block is executed
37 JS staticObject = null;
40 // Only used during parsing /////////////////////////////////////////////////////////////////
42 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
43 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
44 private int startLine = -1; ///< the line number that this element starts on
48 // Static data/methods ///////////////////////////////////////////////////////////////////
51 private Template(Template t, int startLine) { prev = t; this.ibex = t.ibex; this.startLine = startLine; }
52 private Template(Ibex ibex) { this.ibex = ibex; }
55 // Methods to apply templates ////////////////////////////////////////////////////////
58 /** Applies the template to Box b
59 * @param pboxes a vector of all box parents on which to put $-references
60 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
62 public void apply(Box b) throws JSExn {
65 } catch (IOException e) {
69 throw new JSExn(e.toString());
78 private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
79 if (prev != null) prev.apply(b, null);
80 if (prev2 != null) prev2.apply(b, null);
82 // FIXME this dollar stuff is all wrong
83 if (id != null) parentPis.putDollar(id, b);
85 PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticObject);
86 for(int i=0; i<urikeys.length; i++) {
87 if (urikeys[i] == null) continue;
88 // FEATURE: Cache urikeys and resolved resources
89 pis.declare(JS.S(urikeys[i]));
90 pis.put(JS.S(urikeys[i]), ibex.resolveString(urivals[i], true));
93 // FIXME needs to obey the new application-ordering rules
94 for (int i=0; children != null && i<children.size(); i++) {
96 ((Template)children.elementAt(i)).apply(kid, pis);
97 b.putAndTriggerTraps(b.get(JS.S("numchildren")), kid);
100 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
102 for(int i=0; keys != null && i < keys.length; i++) {
103 if (keys[i] == null) continue;
107 if ("null".equals(val)) val = null;
109 if (JS.isString(val) && (JS.toString(val).length() > 0)) {
110 switch (JS.toString(val).charAt(0)) {
113 if (val == null) throw new JSExn("unknown box id '"+JS.toString(vals[i])+"' referenced in XML attribute");
116 val = ibex.resolveString(JS.toString(val).substring(1), false);
118 // FIXME: should we be resolving all of these in the XML-parsing code?
121 b.putAndTriggerTraps(key, val);
127 // XML Parsing /////////////////////////////////////////////////////////////////
129 public static Template buildTemplate(String sourceName, JS s, Ibex ibex) {
131 return new TemplateHelper(sourceName, s, ibex).t;
132 } catch (Exception e) {
133 Log.error(Template.class, e);
138 /** handles XML parsing; builds a Template tree as it goes */
139 static final class TemplateHelper extends XML {
142 private int state = STATE_INITIAL;
143 private static final int STATE_INITIAL = 0;
144 private static final int STATE_IN_ROOT_NODE = 1;
145 private static final int STATE_IN_TEMPLATE_NODE = 2;
146 private static final int STATE_IN_META_NODE = 3;
148 StringBuffer static_content = null;
149 int static_content_start = 0;
150 Vec nodeStack = new Vec();
155 String initial_uri = "";
157 public TemplateHelper(String sourceName, JS s, Ibex ibex) throws XML.Exn, IOException, JSExn {
158 this.sourceName = sourceName;
160 InputStream is = s.getInputStream();
161 Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
163 if(b.parentkey != null) initial_uri = JS.toString(b.parentkey) + (initial_uri.equals("") ? "" : "." + initial_uri);
167 parse(new InputStreamReader(is));
168 JS staticScript = parseScript(static_content, static_content_start);
169 t.staticObject = new JS.O();
170 t.staticScope = new PerInstantiationScope(null, ibex, null, t.staticObject);
171 if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
174 private JS parseScript(StringBuffer content, int content_start) throws IOException {
175 if (content == null) return null;
176 String contentString = content.toString();
177 if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
181 public void startElement(XML.Element c) throws XML.Exn {
183 case STATE_IN_META_NODE: { meta++; return; }
185 if (!"ibex".equals(c.getLocalName()))
186 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
187 if (c.getAttrLen() != 0)
188 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
189 if (c.getUri("ui") == null || "".equals(c.getUri("ui"))) c.addUri("ui", "ibex://ui");
190 if (c.getUri("meta") == null || "".equals(c.getUri("meta"))) c.addUri("meta", "ibex://meta");
191 if (c.getUri("") == null || "".equals(c.getUri(""))) c.addUri("", initial_uri);
192 state = STATE_IN_ROOT_NODE;
194 case STATE_IN_ROOT_NODE:
195 if ("ibex://meta".equals(c.getUri())) { state = STATE_IN_META_NODE; meta = 0; return; }
196 state = STATE_IN_TEMPLATE_NODE;
197 t = (t == null) ? new Template(ibex) : new Template(t, getLine());
199 case STATE_IN_TEMPLATE_NODE:
200 nodeStack.addElement(t);
201 t = new Template(ibex);
205 // FIXME: This is all wrong
206 if (!("ibex://ui".equals(c.getUri()) && "box".equals(c.getLocalName()))) {
207 String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
211 // t.prev2 = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
212 if(t.prev2 != null) throw new Error("FIXME: t.prev2 != null");
213 t.prev2 = ((Ibex.Blessing)t.ibex.resolveString(tagname, false)).getTemplate();
214 } catch (Exception e) {
215 Log.error(Template.class, e);
219 Hash urimap = c.getUriMap();
220 t.urikeys = new String[urimap.size()];
221 t.urivals = new String[urimap.size()];
222 Enumeration uriEnumeration = urimap.keys();
224 while(uriEnumeration.hasMoreElements()) {
225 String key = (String)uriEnumeration.nextElement();
226 String val = (String)urimap.get(key);
227 if (val.equals("ibex://ui")) continue;
228 if (val.equals("ibex://meta")) continue;
230 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
235 Vec keys = new Vec(c.getAttrLen());
236 Vec vals = new Vec(c.getAttrLen());
238 // process attributes into Vecs, dealing with any XML Namespaces in the process
239 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
240 if (c.getAttrKey(i).equals("id")) {
241 t.id = c.getAttrVal(i).toString().intern();
245 // treat value starting with '.' as resource reference
246 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
247 keys.addElement(c.getAttrKey(i));
248 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
251 if (keys.size() == 0) return;
253 // sort the attributes lexicographically
254 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
255 return ((String)a).compareTo((String)b);
258 t.keys = new JS[keys.size()];
259 t.vals = new JS[vals.size()];
261 // convert attributes to appropriate types and intern strings
262 for(int i=0; i<t.keys.length; i++) {
264 t.keys[i] = JS.S((String)keys.elementAt(i));
265 String valString = (String) vals.elementAt(i);
267 if (valString.equals("true")) t.vals[i] = JS.T;
268 else if (valString.equals("false")) t.vals[i] = JS.F;
269 else if (valString.equals("null")) t.vals[i] = null;
271 boolean hasNonNumeral = false;
272 boolean periodUsed = false;
273 for(int j=0; j<valString.length(); j++)
274 if (j == 0 && valString.charAt(j) == '-') {
275 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
277 } else if (!Character.isDigit(valString.charAt(j))) {
278 hasNonNumeral = true;
281 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JS.N(Double.parseDouble((valString)));
282 else t.vals[i] = JS.S(valString.intern()); // FEATURE: JS.intern() ?
287 public void endElement(XML.Element c) throws XML.Exn, IOException {
289 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
290 case STATE_IN_ROOT_NODE: return;
291 case STATE_IN_TEMPLATE_NODE: {
292 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
293 if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
295 t = (Template)nodeStack.lastElement();
296 nodeStack.setSize(nodeStack.size() - 1);
297 t.children.addElement(oldt);
298 int oldt_lines = getLine() - oldt.startLine;
299 if (t.content == null) t.content = new StringBuffer();
300 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
305 public void characters(char[] ch, int start, int length) throws XML.Exn {
306 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
307 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
309 case STATE_IN_TEMPLATE_NODE:
310 if (t.content == null) {
311 t.content_start = getLine();
312 t.content = new StringBuffer();
314 t.content.append(ch, start, length);
316 case STATE_IN_ROOT_NODE:
317 if (static_content == null) {
318 static_content_start = getLine();
319 static_content = new StringBuffer();
321 static_content.append(ch, start, length);
326 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
329 private static class PerInstantiationScope extends JSScope {
331 PerInstantiationScope parentBoxPis = null;
333 void putDollar(String key, Box target) throws JSExn {
334 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
335 JS jskey = JS.S("$" + key);
339 public PerInstantiationScope(JSScope parentScope, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
341 this.parentBoxPis = parentBoxPis;
343 this.myStatic = myStatic;
345 public JS get(JS key) throws JSExn {
346 if (super.has(key)) return super.get(key);
347 if(JS.isString(key)) {
348 String s = JS.toString(key);
349 if (s.equals("ibex")) return ibex;
350 if (s.equals("")) return ibex.get(key);
351 if (s.equals("static")) return myStatic;
353 return super.get(key);