0461dbc5dcac30d70f5808ec764525f8f3a11c20
[org.ibex.core.git] / src / org / ibex / Template.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3
4 import java.io.*;
5 import java.util.*;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8
9 /**
10  *  Encapsulates a template node (the <template/> element of a
11  *  .ibex file, or any child element thereof).
12  *
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>.
18  *
19  *  See the Ibex reference for information on the order in which
20  *  templates are applied, attributes are put, and scripts are run.
21  */
22 public class Template {
23
24     // Instance Members ///////////////////////////////////////////////////////
25
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
34     Template prev;
35     Template prev2;
36     JSScope staticScope = null;         ///< the scope in which the static block is executed
37
38
39     // Only used during parsing /////////////////////////////////////////////////////////////////
40
41     private StringBuffer content = null;   ///< during XML parsing, this holds partially-read character data; null otherwise
42     private int content_start = 0;         ///< line number of the first line of <tt>content</tt>
43     private int startLine = -1;            ///< the line number that this element starts on
44     private Ibex ibex;
45
46
47     // Static data/methods ///////////////////////////////////////////////////////////////////
48
49     // for non-root nodes
50     private Template(Template t, int startLine) { prev = t; this.ibex = t.ibex; this.startLine = startLine; }
51     private Template(Ibex ibex) { this.ibex = ibex; }
52     
53
54     // Methods to apply templates ////////////////////////////////////////////////////////
55
56    
57     /** Applies the template to Box b
58      *  @param pboxes a vector of all box parents on which to put $-references
59      *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
60      */
61     void apply(Box b) throws JSExn {
62         try {
63             apply(b, null);
64         } catch (IOException e) {
65             b.clear(Box.VISIBLE);
66             b.mark_for_repack();
67             Log.warn(this, e);
68             throw new JSExn(e.toString());
69         } catch (JSExn e) {
70             b.clear(Box.VISIBLE);
71             b.mark_for_repack();
72             Log.warn(this, e);
73             throw e;
74         }
75     }
76
77     private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
78         if (prev != null) prev.apply(b, null);
79         if (prev2 != null) prev2.apply(b, null);
80
81         // FIXME this dollar stuff is all wrong
82         if (id != null) parentPis.putDollar(id, b);
83
84         PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticScope);
85         for(int i=0; i<urikeys.length; i++) {
86             if (urikeys[i] == null) continue;
87             pis.declare(urikeys[i]);
88             pis.put(urikeys[i], ibex.resolveString(urivals[i], true));
89         }
90
91         // FIXME needs to obey the new application-ordering rules
92         for (int i=0; children != null && i<children.size(); i++) {
93             Box kid = new Box();
94             ((Template)children.elementAt(i)).apply(kid, pis);
95             b.putAndTriggerTraps(b.get("numchildren"), kid);
96         }
97
98         if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
99
100         Object key, val;
101         for(int i=0; keys != null && i < keys.length; i++) {
102             if (keys[i] == null) continue;
103             key = keys[i];
104             val = vals[i];
105
106             if ("null".equals(val)) val = null;
107
108             if (val != null && val instanceof String && ((String)val).length() > 0) {
109                 switch (((String)val).charAt(0)) {
110                     case '$':
111                         val = pis.get(val);
112                         if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
113                         break;
114                     case '.':
115                         val = ibex.resolveString(((String)val).substring(1), false);
116                     // FIXME: url case
117                     // FIXME: should we be resolving all of these in the XML-parsing code?
118                 }
119             }
120
121             b.putAndTriggerTraps(key, val);
122         }
123     }
124
125
126
127     // XML Parsing /////////////////////////////////////////////////////////////////
128
129     public static Template buildTemplate(String sourceName, Object s, Ibex ibex) {
130         try {
131             return new TemplateHelper(sourceName, s, ibex).t;
132         } catch (Exception e) {
133             Log.error(Template.class, e);
134             return null;
135         }
136     }
137
138     /** handles XML parsing; builds a Template tree as it goes */
139     static final class TemplateHelper extends XML {
140
141         String sourceName;
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;
147
148         StringBuffer static_content = null;
149         int static_content_start = 0;
150         Vec nodeStack = new Vec();
151         Template t = null;
152         int meta = 0;
153         Ibex ibex;
154
155         String initial_uri = "";
156
157         public TemplateHelper(String sourceName, Object s, Ibex ibex) throws XML.Exn, IOException, JSExn {
158             this.sourceName = sourceName;
159             this.ibex = ibex;
160             InputStream is = Stream.getInputStream(s);
161             Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
162             while(b != null) {
163                 if(b.parentkey != null) initial_uri = b.parentkey + (initial_uri.equals("") ? "" : "." + initial_uri);
164                 b = b.parent;
165             }
166             initial_uri = "";
167             parse(new InputStreamReader(is));
168             JS staticScript = parseScript(static_content, static_content_start);
169             t.staticScope = new PerInstantiationScope(null, ibex, null, null);
170             if (staticScript != null) JS.cloneWithNewParentScope(staticScript, t.staticScope).call(null, null, null, null, 0);
171         }
172
173         private JS parseScript(StringBuffer content, int content_start) throws IOException {
174             if (content == null) return null;
175             String contentString = content.toString();
176             if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
177             return null;
178         }
179
180         public void startElement(XML.Element c) throws XML.Exn {
181             switch(state) {
182                 case STATE_IN_META_NODE: { meta++; return; }
183                 case STATE_INITIAL:
184                     if (!"ibex".equals(c.getLocalName()))
185                         throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
186                     if (c.getAttrLen() != 0)
187                         throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
188                     if (c.getUri("ui") == null || "".equals(c.getUri("ui"))) c.addUri("ui", "ibex://ui");
189                     if (c.getUri("meta") == null || "".equals(c.getUri("meta"))) c.addUri("meta", "ibex://meta");
190                     if (c.getUri("") == null || "".equals(c.getUri(""))) c.addUri("", initial_uri);
191                     state = STATE_IN_ROOT_NODE;
192                     return;
193                 case STATE_IN_ROOT_NODE:
194                     if ("ibex://meta".equals(c.getUri())) { state = STATE_IN_META_NODE; meta = 0; return; }
195                     state = STATE_IN_TEMPLATE_NODE;
196                     t = (t == null) ? new Template(ibex) : new Template(t, getLine());
197                     break;
198                 case STATE_IN_TEMPLATE_NODE:
199                     nodeStack.addElement(t);
200                     t = new Template(ibex);
201                     break;
202             }
203
204             if (!("ibex://ui".equals(c.getUri()) && "box".equals(c.getLocalName()))) {
205                 String tagname = (c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName();
206                 // GROSS hack
207                 try {
208                     // GROSSER hack
209                     t.prev2 = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
210                 } catch (Exception e) {
211                     Log.error(Template.class, e);
212                 }
213             }
214                 
215             Hash urimap = c.getUriMap();
216             t.urikeys = new String[urimap.size()];
217             t.urivals = new String[urimap.size()];
218             Enumeration uriEnumeration = urimap.keys();
219             int ii = 0;
220             while(uriEnumeration.hasMoreElements()) {
221                 String key = (String)uriEnumeration.nextElement();
222                 String val = (String)urimap.get(key);
223                 if (val.equals("ibex://ui")) continue;
224                 if (val.equals("ibex://meta")) continue;
225                 t.urikeys[ii] = key;
226                 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
227                 t.urivals[ii] = val;
228                 ii++;
229             }
230             
231             Vec keys = new Vec(c.getAttrLen());
232             Vec vals = new Vec(c.getAttrLen());
233
234             // process attributes into Vecs, dealing with any XML Namespaces in the process
235             ATTR: for (int i=0; i < c.getAttrLen(); i++) {
236                 if (c.getAttrKey(i).equals("id")) {
237                     t.id = c.getAttrVal(i).toString().intern();
238                     continue ATTR;
239                 }
240
241                 // treat value starting with '.' as resource reference
242                 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
243                 keys.addElement(c.getAttrKey(i));
244                 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
245             }
246
247             if (keys.size() == 0) return;
248
249             // sort the attributes lexicographically
250             Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
251                 return ((String)a).compareTo((String)b);
252             } });
253
254             t.keys = new String[keys.size()];
255             t.vals = new Object[vals.size()];
256             keys.copyInto(t.keys);
257             vals.copyInto(t.vals);
258
259             // convert attributes to appropriate types and intern strings
260             for(int i=0; i<t.keys.length; i++) {
261                 t.keys[i] = t.keys[i].intern();
262
263                 String valString = t.vals[i].toString();
264                 
265                 if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
266                 else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
267                 else if (valString.equals("null")) t.vals[i] = null;
268                 else {
269                     boolean hasNonNumeral = false;
270                     boolean periodUsed = false;
271                     for(int j=0; j<valString.length(); j++)
272                         if (j == 0 && valString.charAt(j) == '-') {
273                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
274                             periodUsed = true;
275                         } else if (!Character.isDigit(valString.charAt(j))) {
276                             hasNonNumeral = true;
277                             break;
278                         }
279                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
280                     else t.vals[i] = valString.intern();
281                 }
282             }
283         }
284
285         public void endElement(XML.Element c) throws XML.Exn, IOException {
286             switch(state) {
287                 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
288                 case STATE_IN_ROOT_NODE: return;
289                 case STATE_IN_TEMPLATE_NODE: {
290                     if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
291                     if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
292                     Template oldt = t;
293                     t = (Template)nodeStack.lastElement();
294                     nodeStack.setSize(nodeStack.size() - 1);
295                     t.children.addElement(oldt);
296                     int oldt_lines = getLine() - oldt.startLine;
297                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
298                 }
299             }
300         }
301
302         public void characters(char[] ch, int start, int length) throws XML.Exn {
303             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
304                 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
305             switch(state) {
306                 case STATE_IN_TEMPLATE_NODE:
307                     if (t.content == null) {
308                         t.content_start = getLine();
309                         t.content = new StringBuffer();
310                     }
311                     t.content.append(ch, start, length);
312                     return;
313                 case STATE_IN_ROOT_NODE:
314                     if (static_content == null) {
315                         static_content_start = getLine();
316                         static_content = new StringBuffer();
317                     }
318                     static_content.append(ch, start, length);
319                     return;
320             }
321         }
322
323         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
324     }
325
326     private static class PerInstantiationScope extends JSScope {
327         Ibex ibex = null;
328         PerInstantiationScope parentBoxPis = null;
329         JSScope myStatic = null;
330         void putDollar(String key, Box target) throws JSExn {
331             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
332             declare("$" + key);
333             put("$" + key, target);
334         }
335         public PerInstantiationScope(JSScope parentScope, Ibex ibex, PerInstantiationScope parentBoxPis, JSScope myStatic) {
336             super(parentScope);
337             this.parentBoxPis = parentBoxPis;
338             this.ibex = ibex;
339             this.myStatic = myStatic;
340         }
341         public Object get(Object key) throws JSExn {
342             if (super.has(key)) return super.get(key);
343             if (key.equals("ibex")) return ibex;
344             if (key.equals("")) return ibex.get("");
345             if (key.equals("static")) return myStatic;
346             return super.get(key);
347         }
348     }
349
350 }
351
352