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 pis.declare(urikeys[i]);
85 pis.put(urikeys[i], ibex.resolveString(urivals[i], true));
88 // FIXME needs to obey the new application-ordering rules
89 for (int i=0; children != null && i<children.size(); i++) {
91 ((Template)children.elementAt(i)).apply(kid, pis);
92 b.putAndTriggerTraps(b.get("numchildren"), kid);
95 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
98 for(int i=0; keys != null && i < keys.length; i++) {
99 if (keys[i] == null) continue;
103 if ("null".equals(val)) val = null;
105 if (val != null && val instanceof String && ((String)val).length() > 0) {
106 switch (((String)val).charAt(0)) {
109 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
112 val = ibex.resolveString(((String)val).substring(1), false);
114 // FIXME: should we be resolving all of these in the XML-parsing code?
118 b.putAndTriggerTraps(key, val);
124 // XML Parsing /////////////////////////////////////////////////////////////////
126 public static Template buildTemplate(String sourceName, InputStream is, Ibex ibex) {
128 return new TemplateHelper(sourceName, is, ibex).t;
129 } catch (Exception e) {
130 Log.error(Template.class, e);
135 /** handles XML parsing; builds a Template tree as it goes */
136 static final class TemplateHelper extends XML {
139 private int state = STATE_INITIAL;
140 private static final int STATE_INITIAL = 0;
141 private static final int STATE_IN_ROOT_NODE = 1;
142 private static final int STATE_IN_TEMPLATE_NODE = 2;
143 private static final int STATE_IN_META_NODE = 3;
145 StringBuffer static_content = null;
146 int static_content_start = 0;
147 Vec nodeStack = new Vec();
152 public TemplateHelper(String sourceName, InputStream is, Ibex ibex) throws XML.Exn, IOException, JSExn {
153 this.sourceName = sourceName;
155 parse(new InputStreamReader(is));
156 JS staticScript = parseScript(static_content, static_content_start);
157 t.staticScope = new PerInstantiationScope(null, ibex, null, null);
158 if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
161 private JS parseScript(StringBuffer content, int content_start) throws IOException {
162 if (content == null) return null;
163 String contentString = content.toString();
164 if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
168 public void startElement(XML.Element c) throws XML.Exn {
170 case STATE_IN_META_NODE: { meta++; return; }
172 if (!"ibex".equals(c.getLocalName()))
173 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
174 if (c.getAttrLen() != 0)
175 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
176 state = STATE_IN_ROOT_NODE;
178 case STATE_IN_ROOT_NODE:
179 if ("meta".equals(c.getPrefix())) { state = STATE_IN_META_NODE; meta = 0; return; }
180 state = STATE_IN_TEMPLATE_NODE;
181 t = (t == null) ? new Template(ibex) : new Template(t, getLine());
183 case STATE_IN_TEMPLATE_NODE:
184 nodeStack.addElement(t);
185 t = new Template(ibex);
189 if (!(/* "ui".equals(c.getPrefix()) && */ "box".equals(c.getLocalName()))) {
190 String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
193 t.prev = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
194 } catch (Exception e) {
195 Log.error(Template.class, e);
199 Hash urimap = c.getUriMap();
200 t.urikeys = new String[urimap.size()];
201 t.urivals = new String[urimap.size()];
202 Enumeration uriEnumeration = urimap.keys();
204 while(uriEnumeration.hasMoreElements()) {
205 String key = (String)uriEnumeration.nextElement();
206 String val = (String)urimap.get(key);
208 if (val.charAt(0) == '.') val = val.substring(1);
213 Vec keys = new Vec(c.getAttrLen());
214 Vec vals = new Vec(c.getAttrLen());
216 // process attributes into Vecs, dealing with any XML Namespaces in the process
217 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
218 //#switch(c.getAttrKey(i))
220 t.id = c.getAttrVal(i).toString().intern();
224 // treat value starting with '.' as resource reference
225 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
226 keys.addElement(c.getAttrKey(i));
227 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
230 if (keys.size() == 0) return;
232 // sort the attributes lexicographically
233 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
234 return ((String)a).compareTo((String)b);
237 t.keys = new String[keys.size()];
238 t.vals = new Object[vals.size()];
239 keys.copyInto(t.keys);
240 vals.copyInto(t.vals);
242 // convert attributes to appropriate types and intern strings
243 for(int i=0; i<t.keys.length; i++) {
244 t.keys[i] = t.keys[i].intern();
246 String valString = t.vals[i].toString();
248 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
249 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
250 else if (valString.equals("null")) t.vals[i] = null;
252 boolean hasNonNumeral = false;
253 boolean periodUsed = false;
254 for(int j=0; j<valString.length(); j++)
255 if (j == 0 && valString.charAt(j) == '-') {
256 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
258 } else if (!Character.isDigit(valString.charAt(j))) {
259 hasNonNumeral = true;
262 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
263 else t.vals[i] = valString.intern();
268 public void endElement(XML.Element c) throws XML.Exn, IOException {
270 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
271 case STATE_IN_ROOT_NODE: return;
272 case STATE_IN_TEMPLATE_NODE: {
273 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
274 if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
276 t = (Template)nodeStack.lastElement();
277 nodeStack.setSize(nodeStack.size() - 1);
278 t.children.addElement(oldt);
279 int oldt_lines = getLine() - oldt.startLine;
280 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
285 public void characters(char[] ch, int start, int length) throws XML.Exn {
286 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
287 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
289 case STATE_IN_TEMPLATE_NODE:
290 if (t.content == null) {
291 t.content_start = getLine();
292 t.content = new StringBuffer();
294 t.content.append(ch, start, length);
296 case STATE_IN_ROOT_NODE:
297 if (static_content == null) {
298 static_content_start = getLine();
299 static_content = new StringBuffer();
301 static_content.append(ch, start, length);
306 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
309 private static class PerInstantiationScope extends JSScope {
311 PerInstantiationScope parentBoxPis = null;
312 JSScope myStatic = null;
313 void putDollar(String key, Box target) throws JSExn {
314 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
316 put("$" + key, target);
318 public PerInstantiationScope(JSScope parentScope, Ibex ibex, PerInstantiationScope parentBoxPis, JSScope myStatic) {
320 this.parentBoxPis = parentBoxPis;
322 this.myStatic = myStatic;
324 public Object get(Object key) throws JSExn {
325 if (super.has(key)) return super.get(key);
326 if (key.equals("ibex")) return ibex;
327 if (key.equals("")) return ibex.get("");
328 if (key.equals("static")) return myStatic;
329 return super.get(key);