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