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