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 void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
81 if (prev != null) prev.apply(b, null);
82 if (prev2 != null) prev2.apply(b, null);
84 // FIXME this dollar stuff is all wrong
85 if (id != null) parentPis.putDollar(id, b);
87 PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticObject);
88 for(int i=0; i<urikeys.length; i++) {
89 if (urikeys[i] == null) continue;
90 // FEATURE: Cache urikeys and resolved resources
91 //pis.declare(JSU.S(urikeys[i]));
93 pis.sput(JSU.S(urikeys[i]), ibex.resolveString(urivals[i], true));
96 // FIXME needs to obey the new application-ordering rules
97 for (int i=0; children != null && i<children.size(); i++) {
99 ((Template)children.elementAt(i)).apply(kid, pis);
100 b.putAndTriggerTraps(b.get(JSU.S("numchildren")), kid);
103 if (script != null) JS.cloneWithNewGlobalScope(script, pis).call(null, null, null, null, 0);
105 for(int i=0; keys != null && i < keys.length; i++) {
106 if (keys[i] == null) continue;
110 if ("null".equals(val)) val = null;
112 if (JS.isString(val) && (JS.toString(val).length() > 0)) {
113 switch (JS.toString(val).charAt(0)) {
116 if (val == null) throw new JSExn("unknown box id '"+JS.toString(vals[i])+"' referenced in XML attribute");
119 val = ibex.resolveString(JS.toString(val).substring(1), false);
121 // FIXME: should we be resolving all of these in the XML-parsing code?
124 b.putAndTriggerTraps(key, val);
130 // XML Parsing /////////////////////////////////////////////////////////////////
132 public static Template buildTemplate(String sourceName, JS s, Ibex ibex) {
134 return new TemplateHelper(sourceName, s, ibex).t;
135 } catch (Exception e) {
136 Log.error(Template.class, e);
141 /** handles XML parsing; builds a Template tree as it goes */
142 static final class TemplateHelper extends XML {
145 private int state = STATE_INITIAL;
146 private static final int STATE_INITIAL = 0;
147 private static final int STATE_IN_ROOT_NODE = 1;
148 private static final int STATE_IN_TEMPLATE_NODE = 2;
149 private static final int STATE_IN_META_NODE = 3;
151 StringBuffer static_content = null;
152 int static_content_start = 0;
153 Vec nodeStack = new Vec();
158 String initial_uri = "";
160 public TemplateHelper(String sourceName, JS s, Ibex ibex) throws XML.Exn, IOException, JSExn {
161 this.sourceName = sourceName;
163 InputStream is = s.getInputStream();
164 Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
166 if(b.parentkey != null) initial_uri = JS.toString(b.parentkey) + (initial_uri.equals("") ? "" : "." + initial_uri);
170 parse(new InputStreamReader(is));
171 JS staticScript = parseScript(static_content, static_content_start);
172 t.staticObject = new JS.O();
173 JS staticScope = new PerInstantiationScope(null, ibex, null, t.staticObject);
174 if (staticScript != null) JS.cloneWithNewGlobalScope(staticScript, staticScope).call(null, null, null, null, 0);
177 private JS parseScript(StringBuffer content, int content_start) throws IOException {
178 if (content == null) return null;
179 String contentString = content.toString();
180 if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
184 public void startElement(XML.Element c) throws XML.Exn {
186 case STATE_IN_META_NODE: { meta++; return; }
188 if (!"ibex".equals(c.getLocalName()))
189 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
190 if (c.getAttrLen() != 0)
191 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
192 if (c.getUri("ui") == null || "".equals(c.getUri("ui"))) c.addUri("ui", "ibex://ui");
193 if (c.getUri("meta") == null || "".equals(c.getUri("meta"))) c.addUri("meta", "ibex://meta");
194 if (c.getUri("") == null || "".equals(c.getUri(""))) c.addUri("", initial_uri);
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().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
214 // t.prev2 = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
215 if(t.prev2 != null) throw new Error("FIXME: t.prev2 != null");
216 t.prev2 = ((Ibex.Blessing)t.ibex.resolveString(tagname, false)).getTemplate();
217 if(t.prev2 == null) throw new Exception("" + tagname + " not found");
218 } catch (Exception e) {
219 Log.error(Template.class, e);
223 Hash urimap = c.getUriMap();
224 t.urikeys = new String[urimap.size()];
225 t.urivals = new String[urimap.size()];
226 Enumeration uriEnumeration = urimap.keys();
228 while(uriEnumeration.hasMoreElements()) {
229 String key = (String)uriEnumeration.nextElement();
230 String val = (String)urimap.get(key);
231 if (val.equals("ibex://ui")) continue;
232 if (val.equals("ibex://meta")) continue;
234 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
239 Vec keys = new Vec(c.getAttrLen());
240 Vec vals = new Vec(c.getAttrLen());
242 // process attributes into Vecs, dealing with any XML Namespaces in the process
243 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
244 if (c.getAttrKey(i).equals("id")) {
245 t.id = c.getAttrVal(i).toString().intern();
249 // treat value starting with '.' as resource reference
250 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
251 keys.addElement(c.getAttrKey(i));
252 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
255 if (keys.size() == 0) return;
257 // sort the attributes lexicographically
258 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
259 return ((String)a).compareTo((String)b);
262 t.keys = new JS[keys.size()];
263 t.vals = new JS[vals.size()];
265 // convert attributes to appropriate types and intern strings
266 for(int i=0; i<t.keys.length; i++) {
268 t.keys[i] = JSU.S((String)keys.elementAt(i));
269 String valString = (String) vals.elementAt(i);
271 if (valString.equals("true")) t.vals[i] = JSU.T;
272 else if (valString.equals("false")) t.vals[i] = JSU.F;
273 else if (valString.equals("null")) t.vals[i] = null;
275 boolean hasNonNumeral = false;
276 boolean periodUsed = false;
277 for(int j=0; j<valString.length(); j++)
278 if (j == 0 && valString.charAt(j) == '-') {
279 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
281 } else if (!Character.isDigit(valString.charAt(j))) {
282 hasNonNumeral = true;
285 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JSU.N(Double.parseDouble((valString)));
286 else t.vals[i] = JSU.S(valString.intern()); // FEATURE: JS.intern() ?
291 public void endElement(XML.Element c) throws XML.Exn, IOException {
293 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
294 case STATE_IN_ROOT_NODE: return;
295 case STATE_IN_TEMPLATE_NODE: {
296 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
297 if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
299 t = (Template)nodeStack.lastElement();
300 nodeStack.setSize(nodeStack.size() - 1);
301 t.children.addElement(oldt);
302 int oldt_lines = getLine() - oldt.startLine;
303 if (t.content == null) t.content = new StringBuffer();
304 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
309 public void characters(char[] ch, int start, int length) throws XML.Exn {
310 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
311 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
313 case STATE_IN_TEMPLATE_NODE:
314 if (t.content == null) {
315 t.content_start = getLine();
316 t.content = new StringBuffer();
318 t.content.append(ch, start, length);
320 case STATE_IN_ROOT_NODE:
321 if (static_content == null) {
322 static_content_start = getLine();
323 static_content = new StringBuffer();
325 static_content.append(ch, start, length);
330 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
333 private static class PerInstantiationScope extends JS.O {
335 PerInstantiationScope parentBoxPis = null;
338 void putDollar(String key, Box target) throws JSExn {
339 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
340 JS jskey = JSU.S("$" + key);
345 void sput(JS key, JS val) throws JSExn { super.put(key,val); }
346 public PerInstantiationScope(JS box, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
347 this.parentBoxPis = parentBoxPis;
349 this.myStatic = myStatic;
352 public JS get(JS key) throws JSExn {
353 if(JS.isString(key)) {
354 String s = JS.toString(key);
355 // JS:FIXME This is a hack
356 if (super.get(key) != null) return super.get(key);
357 if (s.equals("ibex")) return ibex;
358 if (s.equals("")) return ibex.get(key);
359 if (s.equals("static")) return myStatic;
361 // JS:FIXME: This won't work with traps that do blocking operations
362 return box.getAndTriggerTraps(key);
364 // JS:FIXME: Everything below here should come from js.scope or something
365 public void put(JS key, JS val) throws JSExn { if(box != null) box.putAndTriggerTraps(key,val); else super.put(key,val); }
366 public void addTrap(JS key, JSFunction f) throws JSExn { box.addTrap(key,f); }
367 public void delTrap(JS key, JSFunction f) throws JSExn { box.delTrap(key,f); }