1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
5 import java.util.zip.*;
9 import org.xwt.translators.*;
10 import org.xwt.util.*;
13 * Encapsulates a template node (the <template/> element of a
14 * .xwt 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 XWT 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 String[] keys; ///< keys to be "put" to instances of this template; elements correspond to those of vals
32 private Object[] 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
38 JSScope staticScope = null; ///< the scope in which the static block is executed
41 // Only used during parsing /////////////////////////////////////////////////////////////////
43 private StringBuffer content = null; ///< during XML parsing, this holds partially-read character data; null otherwise
44 private int content_start = 0; ///< line number of the first line of <tt>content</tt>
45 private int startLine = -1; ///< the line number that this element starts on
49 // Static data/methods ///////////////////////////////////////////////////////////////////
52 private Template(Template t, int startLine) { prev = t; this.xwt = t.xwt; this.startLine = startLine; }
53 private Template(XWT xwt) { this.xwt = xwt; }
56 // Methods to apply templates ////////////////////////////////////////////////////////
59 /** Applies the template to Box b
60 * @param pboxes a vector of all box parents on which to put $-references
61 * @param ptemplates a vector of the fileNames to recieve private references on the pboxes
63 void apply(Box b) throws JSExn {
66 } catch (IOException e) {
70 throw new JSExn(e.toString());
79 private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
80 if (prev != null) prev.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, xwt, parentPis, staticScope);
86 for(int i=0; i<urikeys.length; i++) {
87 pis.declare(urikeys[i]);
88 pis.put(urikeys[i], xwt.resolveString(urivals[i], true));
91 // FIXME needs to obey the new application-ordering rules
92 for (int i=0; children != null && i<children.size(); i++) {
94 ((Template)children.elementAt(i)).apply(kid, pis);
95 b.putAndTriggerTraps(b.get("numchildren"), kid);
98 if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
101 for(int i=0; keys != null && i < keys.length; i++) {
102 if (keys[i] == null) continue;
106 if ("null".equals(val)) val = null;
108 if (val != null && val instanceof String && ((String)val).length() > 0) {
109 switch (((String)val).charAt(0)) {
112 if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
115 val = xwt.resolveString(((String)val).substring(1), false);
117 // 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(InputStream is, XWT xwt) {
131 return new TemplateHelper(is, xwt).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 {
141 private int state = STATE_INITIAL;
142 private static final int STATE_INITIAL = 0;
143 private static final int STATE_IN_XWT_NODE = 1;
144 private static final int STATE_IN_TEMPLATE_NODE = 2;
145 private static final int STATE_IN_META_NODE = 3;
147 StringBuffer static_content = null;
148 int static_content_start = 0;
149 Vec nodeStack = new Vec();
154 public TemplateHelper(InputStream is, XWT xwt) throws XML.Exn, IOException, JSExn {
156 parse(new InputStreamReader(is));
157 JS staticScript = parseScript(static_content, static_content_start);
158 t.staticScope = new PerInstantiationScope(null, xwt, null, null);
159 if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
162 private JS parseScript(StringBuffer content, int content_start) throws IOException {
163 if (content == null) return null;
164 String contentString = content.toString();
165 if (contentString.trim().length() > 0) return JS.fromReader("FIXME", content_start, new StringReader(contentString));
169 public void startElement(XML.Element c) throws XML.Exn {
171 case STATE_IN_META_NODE: { meta++; return; }
173 if (!"ibex".equals(c.getLocalName()))
174 throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
175 if (c.getAttrLen() != 0)
176 throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
177 state = STATE_IN_XWT_NODE;
179 case STATE_IN_XWT_NODE:
180 if ("meta".equals(c.getPrefix())) { state = STATE_IN_META_NODE; meta = 0; return; }
181 state = STATE_IN_TEMPLATE_NODE;
182 t = (t == null) ? new Template(xwt) : new Template(t, getLine());
184 case STATE_IN_TEMPLATE_NODE:
185 nodeStack.addElement(t);
186 t = new Template(xwt);
190 if (!("ui".equals(c.getPrefix()) && "box".equals(c.getLocalName()))) {
191 String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
194 t.prev = (Template)t.xwt.resolveString(tagname, false).call(null, null, null, null, 9999);
195 } catch (Exception e) {
196 Log.error(Template.class, e);
200 Hash urimap = c.getUriMap();
201 t.urikeys = new String[urimap.size()];
202 t.urivals = new String[urimap.size()];
203 Enumeration uriEnumeration = urimap.keys();
205 while(uriEnumeration.hasMoreElements()) {
206 String key = (String)uriEnumeration.nextElement();
207 String val = (String)urimap.get(key);
209 if (val.charAt(0) == '.') val = val.substring(1);
214 Vec keys = new Vec(c.getAttrLen());
215 Vec vals = new Vec(c.getAttrLen());
217 // process attributes into Vecs, dealing with any XML Namespaces in the process
218 ATTR: for (int i=0; i < c.getAttrLen(); i++) {
219 //#switch(c.getAttrKey(i))
221 t.id = c.getAttrVal(i).toString().intern();
225 // treat value starting with '.' as resource reference
226 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
227 keys.addElement(c.getAttrKey(i));
228 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
231 if (keys.size() == 0) return;
233 // sort the attributes lexicographically
234 Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
235 return ((String)a).compareTo((String)b);
238 t.keys = new String[keys.size()];
239 t.vals = new Object[vals.size()];
240 keys.copyInto(t.keys);
241 vals.copyInto(t.vals);
243 // convert attributes to appropriate types and intern strings
244 for(int i=0; i<t.keys.length; i++) {
245 t.keys[i] = t.keys[i].intern();
247 String valString = t.vals[i].toString();
249 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
250 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
251 else if (valString.equals("null")) t.vals[i] = null;
253 boolean hasNonNumeral = false;
254 boolean periodUsed = false;
255 for(int j=0; j<valString.length(); j++)
256 if (j == 0 && valString.charAt(j) == '-') {
257 } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
259 } else if (!Character.isDigit(valString.charAt(j))) {
260 hasNonNumeral = true;
263 if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
264 else t.vals[i] = valString.intern();
269 public void endElement(XML.Element c) throws XML.Exn, IOException {
271 case STATE_IN_META_NODE: if (meta-- < 0) state = STATE_IN_XWT_NODE; return;
272 case STATE_IN_XWT_NODE: return;
273 case STATE_IN_TEMPLATE_NODE: {
274 if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
275 if (nodeStack.size() == 0) { state = STATE_IN_XWT_NODE; return; }
277 t = (Template)nodeStack.lastElement();
278 nodeStack.setSize(nodeStack.size() - 1);
279 t.children.addElement(oldt);
280 int oldt_lines = getLine() - oldt.startLine;
281 for (int i=0; oldt_lines > i; i++) t.content.append('\n');
286 public void characters(char[] ch, int start, int length) throws XML.Exn {
287 for (int i=0; length >i; i++) if (ch[start+i] == '\t')
288 Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
290 case STATE_IN_TEMPLATE_NODE:
291 if (t.content == null) {
292 t.content_start = getLine();
293 t.content = new StringBuffer();
295 t.content.append(ch, start, length);
297 case STATE_IN_XWT_NODE:
298 if (static_content == null) {
299 static_content_start = getLine();
300 static_content = new StringBuffer();
302 static_content.append(ch, start, length);
307 public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
310 private static class PerInstantiationScope extends JSScope {
312 PerInstantiationScope parentBoxPis = null;
313 JSScope myStatic = null;
314 void putDollar(String key, Box target) throws JSExn {
315 if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
317 put("$" + key, target);
319 public PerInstantiationScope(JSScope parentScope, XWT xwt, PerInstantiationScope parentBoxPis, JSScope myStatic) {
321 this.parentBoxPis = parentBoxPis;
323 this.myStatic = myStatic;
325 public Object get(Object key) throws JSExn {
326 if (super.has(key)) return super.get(key);
327 if (key.equals("xwt")) return xwt;
328 if (key.equals("")) return xwt.get("");
329 if (key.equals("static")) return myStatic;
330 return super.get(key);