1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
10 import org.ibex.util.*;
13 * Encapsulates a template node (the <template/> element of a
14 * .ibex 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 Ibex 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 JS[] keys; ///< keys to be "put" to instances of this template; elements correspond to those of vals
32 private JS[] vals; ///< values to be "put" to instances of this template; elements correspond to those of keys
33 private String[] urikeys;
34 private String[] urivals;
35 private Vec children = new Vec(); ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
36 private JS script = null; ///< the script on this node
39 JS staticObject = null;
42 // Only used during parsing /////////////////////////////////////////////////////////////////
44 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
45 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
46 private int startLine = -1; ///< the line number that this element starts on
50 // Static data/methods ///////////////////////////////////////////////////////////////////
53 private Template(Template t, int startLine) { prev = t; this.ibex = t.ibex; this.startLine = startLine; }
54 private Template(Ibex ibex) { this.ibex = ibex; }
57 // Methods to apply templates ////////////////////////////////////////////////////////
60 /** Applies the template to Box b
61 * @param pboxes a vector of all box parents on which to put $-references
62 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
64 public void apply(Box b) throws JSExn {
67 } catch (IOException e) {
71 throw new JSExn(e.toString());
80 private static final JS[] callempty = new JS[0];
81 private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
82 if (prev != null) prev.apply(b, null);
83 if (prev2 != null) prev2.apply(b, null);
85 // FIXME this dollar stuff is all wrong
86 if (id != null) parentPis.putDollar(id, b);
88 PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticObject);
89 for(int i=0; i<urikeys.length; i++) {
90 if (urikeys[i] == null) continue;
91 // FEATURE: Cache urikeys and resolved resources
92 //pis.declare(JSU.S(urikeys[i]));
94 pis.sput(JSU.S(urikeys[i]), ibex.resolveString(urivals[i], true));
97 // FIXME needs to obey the new application-ordering rules
98 for (int i=0; children != null && i<children.size(); i++) {
100 ((Template)children.elementAt(i)).apply(kid, pis);
101 b.putAndTriggerTraps(b.get(JSU.S("numchildren")), kid);
104 if (script != null) JSU.cloneWithNewGlobalScope(script, pis).call(null, callempty);
106 for(int i=0; keys != null && i < keys.length; i++) {
107 if (keys[i] == null) continue;
111 if ("null".equals(val)) val = null;
113 if (JSU.isString(val) && (JSU.toString(val).length() > 0)) {
114 switch (JSU.toString(val).charAt(0)) {
117 if (val == null) throw new JSExn("unknown box id '"+JSU.str(vals[i])+"' referenced in XML attribute");
120 val = ibex.resolveString(JSU.toString(val).substring(1), false);
122 // FIXME: should we be resolving all of these in the XML-parsing code?
125 b.putAndTriggerTraps(key, val);
131 // XML Parsing /////////////////////////////////////////////////////////////////
133 public static Template buildTemplate(String sourceName, JS s, Ibex ibex) {
135 return new TemplateHelper(sourceName, s, ibex).t;
136 } catch (Exception e) {
137 Log.error(Template.class, e);
142 /** handles XML parsing; builds a Template tree as it goes */
143 static final class TemplateHelper extends XML {
146 private int state = STATE_INITIAL;
147 private static final int STATE_INITIAL = 0;
148 private static final int STATE_IN_ROOT_NODE = 1;
149 private static final int STATE_IN_TEMPLATE_NODE = 2;
150 private static final int STATE_IN_META_NODE = 3;
151 private static final JS[] callempty = new JS[0];
153 StringBuffer static_content = null;
154 int static_content_start = 0;
155 Vec nodeStack = new Vec();
160 String initial_uri = "";
162 public TemplateHelper(String sourceName, JS s, Ibex ibex) throws XML.Exn, IOException, JSExn {
163 this.sourceName = sourceName;
165 InputStream is = JSU.getInputStream(s);
166 Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
168 if(b.parentkey != null) initial_uri = JSU.toString(b.parentkey) + (initial_uri.equals("") ? "" : "." + initial_uri);
172 parse(new InputStreamReader(is));
173 JS staticScript = parseScript(static_content, static_content_start);
174 t.staticObject = new JS.Obj();
175 JS staticScope = new PerInstantiationScope(null, ibex, null, t.staticObject);
176 if (staticScript != null) JSU.cloneWithNewGlobalScope(staticScript, staticScope).call(null, callempty);
179 private JS parseScript(StringBuffer content, int content_start) throws IOException {
180 if (content == null) return null;
181 String contentString = content.toString();
182 if (contentString.trim().length() > 0) return JSU.fromReader(sourceName, content_start, new StringReader(contentString));
186 public void startElement(Tree.Element c) throws XML.Exn {
187 Tree.Attributes a = c.getAttributes();
189 case STATE_IN_META_NODE: { meta++; return; }
191 if (!"ibex".equals(c.getLocalName()))
192 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
193 if (a.attrSize() != 0)
194 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
195 state = STATE_IN_ROOT_NODE;
197 case STATE_IN_ROOT_NODE:
198 if ("ibex://meta".equals(c.getUri())) { state = STATE_IN_META_NODE; meta = 0; return; }
199 state = STATE_IN_TEMPLATE_NODE;
200 t = (t == null) ? new Template(ibex) : new Template(t, getLine());
202 case STATE_IN_TEMPLATE_NODE:
203 nodeStack.addElement(t);
204 t = new Template(ibex);
208 // FIXME: This is all wrong
209 if (!("ibex://ui".equals(c.getUri()) && "box".equals(c.getLocalName()))) {
210 String tagname = (c.getUri() == null || "".equals(c.getUri()) ? "" :
211 (c.getUri() + ".")) + c.getLocalName();
215 // t.prev2 = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
216 if(t.prev2 != null) throw new Error("FIXME: t.prev2 != null");
217 t.prev2 = ((Ibex.Blessing)t.ibex.resolveString(tagname, false)).getTemplate();
218 if(t.prev2 == null) throw new Exception("" + tagname + " not found");
219 } catch (Exception e) {
220 Log.error(Template.class, e);
224 Tree.Prefixes prefixes = c.getPrefixes();
225 t.urikeys = new String[prefixes.pfxSize()];
226 t.urivals = new String[prefixes.pfxSize()];
229 for (int i=0; i < prefixes.pfxSize(); i++) {
230 String key = prefixes.getPrefixKey(i);
231 String val = prefixes.getPrefixVal(i);
232 if (val.equals("ibex://ui")) continue;
233 if (val.equals("ibex://meta")) continue;
235 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
240 // FIXME: 2-value Array
241 Basket.Array keys = new Basket.Array(a.attrSize());
242 Basket.Array vals = new Basket.Array(a.attrSize());
244 // process attributes into Vecs, dealing with any XML Namespaces in the process
245 ATTR: for (int i=0; i < a.attrSize(); i++) {
246 if (a.getKey(i).equals("id")) {
247 t.id = a.getVal(i).toString().intern();
251 // treat value starting with '.' as resource reference
252 String uri = a.getUri(i); if (uri != null && !uri.equals("")) uri = '.' + uri;
253 keys.add(a.getKey(i));
254 vals.add((a.getVal(i).startsWith(".") ? uri : "") + a.getVal(i));
257 if (keys.size() == 0) return;
259 // sort the attributes lexicographically
260 Basket.Array.sort(keys, vals, new Basket.CompareFunc() {
261 public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); }
262 }, 0, keys.size() - 1);
264 t.keys = new JS[keys.size()];
265 t.vals = new JS[vals.size()];
267 // convert attributes to appropriate types and intern strings
268 for(int i=0; i<t.keys.length; i++) {
270 t.keys[i] = JSU.S((String)keys.get(i));
271 String valString = (String) vals.get(i);
273 if (valString.equals("true")) t.vals[i] = JSU.T;
274 else if (valString.equals("false")) t.vals[i] = JSU.F;
275 else if (valString.equals("null")) t.vals[i] = null;
277 boolean hasNonNumeral = false;
278 boolean periodUsed = false;
279 for(int j=0; j<valString.length(); j++)
280 if (j == 0 && valString.charAt(j) == '-') {
281 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
283 } else if (!Character.isDigit(valString.charAt(j))) {
284 hasNonNumeral = true;
287 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JSU.N(Double.parseDouble((valString)));
288 else t.vals[i] = JSU.S(valString.intern()); // FEATURE: JS.intern() ?
293 public void endElement(Tree.Element c) throws XML.Exn, IOException {
295 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
296 case STATE_IN_ROOT_NODE: return;
297 case STATE_IN_TEMPLATE_NODE: {
298 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
299 if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
301 t = (Template)nodeStack.lastElement();
302 nodeStack.setSize(nodeStack.size() - 1);
303 t.children.addElement(oldt);
304 int oldt_lines = getLine() - oldt.startLine;
305 if (t.content == null) t.content = new StringBuffer();
306 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
311 public void characters(char[] ch, int start, int length) throws XML.Exn {
312 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
313 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
315 case STATE_IN_TEMPLATE_NODE:
316 if (t.content == null) {
317 t.content_start = getLine();
318 t.content = new StringBuffer();
320 t.content.append(ch, start, length);
322 case STATE_IN_ROOT_NODE:
323 if (static_content == null) {
324 static_content_start = getLine();
325 static_content = new StringBuffer();
327 static_content.append(ch, start, length);
332 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
335 // FIXME: david, get to work
336 private static class PerInstantiationScope extends JS.Obj {
338 PerInstantiationScope parentBoxPis = null;
341 void putDollar(String key, Box target) throws JSExn {
342 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
343 JS jskey = JSU.S("$" + key);
348 void sput(JS key, JS val) throws JSExn { super.put(key,val); }
349 public PerInstantiationScope(JS box, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
350 this.parentBoxPis = parentBoxPis;
352 this.myStatic = myStatic;
355 public JS get(JS key) throws JSExn {
356 if(JSU.isString(key)) {
357 String s = JSU.toString(key);
358 // JS:FIXME This is a hack
359 if (super.get(key) != null) return super.get(key);
360 if (s.equals("ibex")) return ibex;
361 if (s.equals("")) return ibex.get(key);
362 if (s.equals("static")) return myStatic;
364 // JS:FIXME: This won't work with traps that do blocking operations
365 return box.getAndTriggerTraps(key);
367 // JS:FIXME: Everything below here should come from js.scope or something
368 public void put(JS key, JS val) throws JSExn { if(box != null) box.putAndTriggerTraps(key,val); else super.put(key,val); }
369 public void addTrap(JS key, JS f) throws JSExn { box.addTrap(key,f); }
370 public void delTrap(JS key, JS f) throws JSExn { box.delTrap(key,f); }