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