a3d0e4eb3df2b1ec626535d67cf1bf348c1f23e9
[org.ibex.core.git] / src / org / ibex / core / Template.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.core;
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 JS[] keys;              ///< keys to be "put" to instances of this template; elements correspond to those of vals
29     private JS[] 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     JS staticObject = null;
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     public 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, staticObject);
85         for(int i=0; i<urikeys.length; i++) {
86             if (urikeys[i] == null) continue;
87             // FEATURE: Cache urikeys and resolved resources
88             //pis.declare(JS.S(urikeys[i]));
89             // JS:FIXME: ugly
90             pis.sput(JS.S(urikeys[i]), ibex.resolveString(urivals[i], true));
91         }
92
93         // FIXME needs to obey the new application-ordering rules
94         for (int i=0; children != null && i<children.size(); i++) {
95             Box kid = new Box();
96             ((Template)children.elementAt(i)).apply(kid, pis);
97             b.putAndTriggerTraps(b.get(JS.S("numchildren")), kid);
98         }
99
100         if (script != null) JS.cloneWithNewGlobalScope(script, pis).call(null, null, null, null, 0);
101
102         for(int i=0; keys != null && i < keys.length; i++) {
103             if (keys[i] == null) continue;
104             JS key = keys[i];
105             JS val = vals[i];
106
107             if ("null".equals(val)) val = null;
108
109             if (JS.isString(val) && (JS.toString(val).length() > 0)) {
110                 switch (JS.toString(val).charAt(0)) {
111                     case '$':
112                         val = pis.get(val);
113                         if (val == null) throw new JSExn("unknown box id '"+JS.toString(vals[i])+"' referenced in XML attribute");
114                         break;
115                     case '.':
116                         val = ibex.resolveString(JS.toString(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             b.putAndTriggerTraps(key, val);
122         }
123     }
124
125
126
127     // XML Parsing /////////////////////////////////////////////////////////////////
128
129     public static Template buildTemplate(String sourceName, JS 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, JS s, Ibex ibex) throws XML.Exn, IOException, JSExn {
158             this.sourceName = sourceName;
159             this.ibex = ibex;
160             InputStream is = s.getInputStream();
161             Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
162             while(b != null) {
163                 if(b.parentkey != null) initial_uri = JS.toString(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.staticObject = new JS.O();
170             JS staticScope = new PerInstantiationScope(null, ibex, null, t.staticObject);
171             if (staticScript != null) JS.cloneWithNewGlobalScope(staticScript, staticScope).call(null, null, null, null, 0);
172         }
173
174         private JS parseScript(StringBuffer content, int content_start) throws IOException {
175             if (content == null) return null;
176             String contentString = content.toString();
177             if (contentString.trim().length() > 0) return JS.fromReader(sourceName, content_start, new StringReader(contentString));
178             return null;
179         }
180
181         public void startElement(XML.Element c) throws XML.Exn {
182             switch(state) {
183                 case STATE_IN_META_NODE: { meta++; return; }
184                 case STATE_INITIAL:
185                     if (!"ibex".equals(c.getLocalName()))
186                         throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
187                     if (c.getAttrLen() != 0)
188                         throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
189                     if (c.getUri("ui") == null || "".equals(c.getUri("ui"))) c.addUri("ui", "ibex://ui");
190                     if (c.getUri("meta") == null || "".equals(c.getUri("meta"))) c.addUri("meta", "ibex://meta");
191                     if (c.getUri("") == null || "".equals(c.getUri(""))) c.addUri("", initial_uri);
192                     state = STATE_IN_ROOT_NODE;
193                     return;
194                 case STATE_IN_ROOT_NODE:
195                     if ("ibex://meta".equals(c.getUri())) { state = STATE_IN_META_NODE; meta = 0; return; }
196                     state = STATE_IN_TEMPLATE_NODE;
197                     t = (t == null) ? new Template(ibex) : new Template(t, getLine());
198                     break;
199                 case STATE_IN_TEMPLATE_NODE:
200                     nodeStack.addElement(t);
201                     t = new Template(ibex);
202                     break;
203             }
204
205             // FIXME: This is all wrong
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                     if(t.prev2 != null) throw new Error("FIXME: t.prev2 != null");
213                     t.prev2 = ((Ibex.Blessing)t.ibex.resolveString(tagname, false)).getTemplate();
214                     if(t.prev2 == null) throw new Exception("" + tagname + " not found");
215                 } catch (Exception e) {
216                     Log.error(Template.class, e);
217                 }
218             }
219                 
220             Hash urimap = c.getUriMap();
221             t.urikeys = new String[urimap.size()];
222             t.urivals = new String[urimap.size()];
223             Enumeration uriEnumeration = urimap.keys();
224             int ii = 0;
225             while(uriEnumeration.hasMoreElements()) {
226                 String key = (String)uriEnumeration.nextElement();
227                 String val = (String)urimap.get(key);
228                 if (val.equals("ibex://ui")) continue;
229                 if (val.equals("ibex://meta")) continue;
230                 t.urikeys[ii] = key;
231                 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
232                 t.urivals[ii] = val;
233                 ii++;
234             }
235             
236             Vec keys = new Vec(c.getAttrLen());
237             Vec vals = new Vec(c.getAttrLen());
238
239             // process attributes into Vecs, dealing with any XML Namespaces in the process
240             ATTR: for (int i=0; i < c.getAttrLen(); i++) {
241                 if (c.getAttrKey(i).equals("id")) {
242                     t.id = c.getAttrVal(i).toString().intern();
243                     continue ATTR;
244                 }
245
246                 // treat value starting with '.' as resource reference
247                 String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
248                 keys.addElement(c.getAttrKey(i));
249                 vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
250             }
251
252             if (keys.size() == 0) return;
253
254             // sort the attributes lexicographically
255             Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
256                 return ((String)a).compareTo((String)b);
257             } });
258
259             t.keys = new JS[keys.size()];
260             t.vals = new JS[vals.size()];
261             
262             // convert attributes to appropriate types and intern strings
263             for(int i=0; i<t.keys.length; i++) {
264                 // FEATURE: Intern
265                 t.keys[i] = JS.S((String)keys.elementAt(i));
266                 String valString = (String) vals.elementAt(i);
267                 
268                 if (valString.equals("true")) t.vals[i] = JS.T;
269                 else if (valString.equals("false")) t.vals[i] = JS.F;
270                 else if (valString.equals("null")) t.vals[i] = null;
271                 else {
272                     boolean hasNonNumeral = false;
273                     boolean periodUsed = false;
274                     for(int j=0; j<valString.length(); j++)
275                         if (j == 0 && valString.charAt(j) == '-') {
276                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
277                             periodUsed = true;
278                         } else if (!Character.isDigit(valString.charAt(j))) {
279                             hasNonNumeral = true;
280                             break;
281                         }
282                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JS.N(Double.parseDouble((valString)));
283                     else t.vals[i] = JS.S(valString.intern()); // FEATURE: JS.intern() ?
284                 }
285             }
286         }
287
288         public void endElement(XML.Element c) throws XML.Exn, IOException {
289             switch(state) {
290                 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
291                 case STATE_IN_ROOT_NODE: return;
292                 case STATE_IN_TEMPLATE_NODE: {
293                     if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
294                     if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
295                     Template oldt = t;
296                     t = (Template)nodeStack.lastElement();
297                     nodeStack.setSize(nodeStack.size() - 1);
298                     t.children.addElement(oldt);
299                     int oldt_lines = getLine() - oldt.startLine;
300                     if (t.content == null) t.content = new StringBuffer();
301                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
302                 }
303             }
304         }
305
306         public void characters(char[] ch, int start, int length) throws XML.Exn {
307             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
308                 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
309             switch(state) {
310                 case STATE_IN_TEMPLATE_NODE:
311                     if (t.content == null) {
312                         t.content_start = getLine();
313                         t.content = new StringBuffer();
314                     }
315                     t.content.append(ch, start, length);
316                     return;
317                 case STATE_IN_ROOT_NODE:
318                     if (static_content == null) {
319                         static_content_start = getLine();
320                         static_content = new StringBuffer();
321                     }
322                     static_content.append(ch, start, length);
323                     return;
324             }
325         }
326
327         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
328     }
329
330     private static class PerInstantiationScope extends JS.O {
331         Ibex ibex = null;
332         PerInstantiationScope parentBoxPis = null;
333         JS myStatic = null;
334         JS box;
335         void putDollar(String key, Box target) throws JSExn {
336             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
337             JS jskey = JS.S("$" + key);
338             //declare(jskey);
339             sput(jskey, target);
340         }
341         // JS:FIXME: ugly
342         void sput(JS key, JS val) throws JSExn { super.put(key,val); }
343         public PerInstantiationScope(JS box, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
344             this.parentBoxPis = parentBoxPis;
345             this.ibex = ibex;
346             this.myStatic = myStatic;
347             this.box = box;
348         }
349         public JS get(JS key) throws JSExn {
350             if(JS.isString(key)) {
351                 String s = JS.toString(key);
352                 // JS:FIXME This is a hack
353                 if (super.get(key) != null) return super.get(key);
354                 if (s.equals("ibex")) return ibex;
355                 if (s.equals("")) return ibex.get(key);
356                 if (s.equals("static")) return myStatic;
357             }
358             // JS:FIXME: This won't work with traps that do blocking operations
359             return box.getAndTriggerTraps(key);
360         }
361         // JS:FIXME: Everything below here should come from js.scope or something
362         public void put(JS key, JS val) throws JSExn { if(box != null) box.putAndTriggerTraps(key,val); else super.put(key,val); }
363         public void addTrap(JS key, JSFunction f) throws JSExn { box.addTrap(key,f); }
364         public void delTrap(JS key, JSFunction f) throws JSExn { box.delTrap(key,f); }
365     }
366
367 }
368
369