make core compile with new js stuff and Task replacement class
[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 static final JS[] callempty = new JS[0];
81     private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
82         if (prev != null) prev.apply(b, null);
83         if (prev2 != null) prev2.apply(b, null);
84
85         // FIXME this dollar stuff is all wrong
86         if (id != null) parentPis.putDollar(id, b);
87
88         PerInstantiationScope pis = new PerInstantiationScope(b, ibex, parentPis, staticObject);
89         for(int i=0; i<urikeys.length; i++) {
90             if (urikeys[i] == null) continue;
91             // FEATURE: Cache urikeys and resolved resources
92             //pis.declare(JSU.S(urikeys[i]));
93             // JS:FIXME: ugly
94             pis.sput(JSU.S(urikeys[i]), ibex.resolveString(urivals[i], true));
95         }
96
97         // FIXME needs to obey the new application-ordering rules
98         for (int i=0; children != null && i<children.size(); i++) {
99             Box kid = new Box();
100             ((Template)children.elementAt(i)).apply(kid, pis);
101             b.putAndTriggerTraps(b.get(JSU.S("numchildren")), kid);
102         }
103
104         if (script != null) JSU.cloneWithNewGlobalScope(script, pis).call(callempty);
105
106         for(int i=0; keys != null && i < keys.length; i++) {
107             if (keys[i] == null) continue;
108             JS key = keys[i];
109             JS val = vals[i];
110
111             if ("null".equals(val)) val = null;
112
113             if (JSU.isString(val) && (JSU.toString(val).length() > 0)) {
114                 switch (JSU.toString(val).charAt(0)) {
115                     case '$':
116                         val = pis.get(val);
117                         if (val == null) throw new JSExn("unknown box id '"+JSU.str(vals[i])+"' referenced in XML attribute");
118                         break;
119                     case '.':
120                         val = ibex.resolveString(JSU.toString(val).substring(1), false);
121                     // FIXME: url case
122                     // FIXME: should we be resolving all of these in the XML-parsing code?
123                 }
124             }
125             b.putAndTriggerTraps(key, val);
126         }
127     }
128
129
130
131     // XML Parsing /////////////////////////////////////////////////////////////////
132
133     public static Template buildTemplate(String sourceName, JS s, Ibex ibex) {
134         try {
135             return new TemplateHelper(sourceName, s, ibex).t;
136         } catch (Exception e) {
137             Log.error(Template.class, e);
138             return null;
139         }
140     }
141
142     /** handles XML parsing; builds a Template tree as it goes */
143     static final class TemplateHelper extends XML {
144
145         String sourceName;
146         private int state = STATE_INITIAL;
147         private static final int STATE_INITIAL = 0;
148         private static final int STATE_IN_ROOT_NODE = 1;
149         private static final int STATE_IN_TEMPLATE_NODE = 2; 
150         private static final int STATE_IN_META_NODE = 3;
151         private static final JS[] callempty = new JS[0];
152
153         StringBuffer static_content = null;
154         int static_content_start = 0;
155         Vec nodeStack = new Vec();
156         Template t = null;
157         int meta = 0;
158         Ibex ibex;
159
160         String initial_uri = "";
161
162         public TemplateHelper(String sourceName, JS s, Ibex ibex) throws XML.Exn, IOException, JSExn {
163             this.sourceName = sourceName;
164             this.ibex = ibex;
165             InputStream is = s.getInputStream();
166             Ibex.Blessing b = Ibex.Blessing.getBlessing(s).parent;
167             while(b != null) {
168                 if(b.parentkey != null) initial_uri = JSU.toString(b.parentkey) + (initial_uri.equals("") ? "" : "." + initial_uri);
169                 b = b.parent;
170             }
171             initial_uri = "";
172             parse(new InputStreamReader(is));
173             JS staticScript = parseScript(static_content, static_content_start);
174             t.staticObject = new JS.Obj();
175             JS staticScope = new PerInstantiationScope(null, ibex, null, t.staticObject);
176             if (staticScript != null) JSU.cloneWithNewGlobalScope(staticScript, staticScope).call(callempty);
177         }
178
179         private JS parseScript(StringBuffer content, int content_start) throws IOException {
180             if (content == null) return null;
181             String contentString = content.toString();
182             if (contentString.trim().length() > 0) return JSU.fromReader(sourceName, content_start, new StringReader(contentString));
183             return null;
184         }
185
186         public void startElement(Tree.Element c) throws XML.Exn {
187             Tree.Attributes a = c.getAttributes();
188             switch(state) {
189                 case STATE_IN_META_NODE: { meta++; return; }
190                 case STATE_INITIAL:
191                     if (!"ibex".equals(c.getLocalName()))
192                         throw new XML.Exn("root element was not <ibex>", XML.Exn.SCHEMA, getLine(), getCol());
193                     if (a.attrSize() != 0)
194                         throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
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             Tree.Prefixes prefixes = c.getPrefixes();
224             t.urikeys = new String[prefixes.pfxSize()];
225             t.urivals = new String[prefixes.pfxSize()];
226
227             int ii = 0;
228             for (int i=0; i < prefixes.pfxSize(); i++) {
229                 String key = prefixes.getPrefixKey(i);
230                 String val = prefixes.getPrefixVal(i);
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             // FIXME: 2-value Array
240             Basket.Array keys = new Basket.Array(a.attrSize());
241             Basket.Array vals = new Basket.Array(a.attrSize());
242
243             // process attributes into Vecs, dealing with any XML Namespaces in the process
244             ATTR: for (int i=0; i < a.attrSize(); i++) {
245                 if (a.getKey(i).equals("id")) {
246                     t.id = a.getVal(i).toString().intern();
247                     continue ATTR;
248                 }
249
250                 // treat value starting with '.' as resource reference
251                 String uri = a.getUri(i); if (!uri.equals("")) uri = '.' + uri;
252                 keys.add(a.getKey(i));
253                 vals.add((a.getVal(i).startsWith(".") ? uri : "") + a.getVal(i));
254             }
255
256             if (keys.size() == 0) return;
257
258             // sort the attributes lexicographically
259             Basket.Array.sort(keys, vals, new Basket.CompareFunc() {
260                 public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); }
261             }, 0, keys.size());
262
263             t.keys = new JS[keys.size()];
264             t.vals = new JS[vals.size()];
265             
266             // convert attributes to appropriate types and intern strings
267             for(int i=0; i<t.keys.length; i++) {
268                 // FEATURE: Intern
269                 t.keys[i] = JSU.S((String)keys.get(i));
270                 String valString = (String) vals.get(i);
271                 
272                 if (valString.equals("true")) t.vals[i] = JSU.T;
273                 else if (valString.equals("false")) t.vals[i] = JSU.F;
274                 else if (valString.equals("null")) t.vals[i] = null;
275                 else {
276                     boolean hasNonNumeral = false;
277                     boolean periodUsed = false;
278                     for(int j=0; j<valString.length(); j++)
279                         if (j == 0 && valString.charAt(j) == '-') {
280                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
281                             periodUsed = true;
282                         } else if (!Character.isDigit(valString.charAt(j))) {
283                             hasNonNumeral = true;
284                             break;
285                         }
286                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JSU.N(Double.parseDouble((valString)));
287                     else t.vals[i] = JSU.S(valString.intern()); // FEATURE: JS.intern() ?
288                 }
289             }
290         }
291
292         public void endElement(Tree.Element c) throws XML.Exn, IOException {
293             switch(state) {
294                 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
295                 case STATE_IN_ROOT_NODE: return;
296                 case STATE_IN_TEMPLATE_NODE: {
297                     if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
298                     if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
299                     Template oldt = t;
300                     t = (Template)nodeStack.lastElement();
301                     nodeStack.setSize(nodeStack.size() - 1);
302                     t.children.addElement(oldt);
303                     int oldt_lines = getLine() - oldt.startLine;
304                     if (t.content == null) t.content = new StringBuffer();
305                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
306                 }
307             }
308         }
309
310         public void characters(char[] ch, int start, int length) throws XML.Exn {
311             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
312                 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
313             switch(state) {
314                 case STATE_IN_TEMPLATE_NODE:
315                     if (t.content == null) {
316                         t.content_start = getLine();
317                         t.content = new StringBuffer();
318                     }
319                     t.content.append(ch, start, length);
320                     return;
321                 case STATE_IN_ROOT_NODE:
322                     if (static_content == null) {
323                         static_content_start = getLine();
324                         static_content = new StringBuffer();
325                     }
326                     static_content.append(ch, start, length);
327                     return;
328             }
329         }
330
331         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
332     }
333
334     // FIXME: david, get to work
335     private static class PerInstantiationScope extends JS.Obj {
336         Ibex ibex = null;
337         PerInstantiationScope parentBoxPis = null;
338         JS myStatic = null;
339         JS box;
340         void putDollar(String key, Box target) throws JSExn {
341             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
342             JS jskey = JSU.S("$" + key);
343             //declare(jskey);
344             sput(jskey, target);
345         }
346         // JS:FIXME: ugly
347         void sput(JS key, JS val) throws JSExn { super.put(key,val); }
348         public PerInstantiationScope(JS box, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
349             this.parentBoxPis = parentBoxPis;
350             this.ibex = ibex;
351             this.myStatic = myStatic;
352             this.box = box;
353         }
354         public JS get(JS key) throws JSExn {
355             if(JSU.isString(key)) {
356                 String s = JSU.toString(key);
357                 // JS:FIXME This is a hack
358                 if (super.get(key) != null) return super.get(key);
359                 if (s.equals("ibex")) return ibex;
360                 if (s.equals("")) return ibex.get(key);
361                 if (s.equals("static")) return myStatic;
362             }
363             // JS:FIXME: This won't work with traps that do blocking operations
364             return box.getAndTriggerTraps(key);
365         }
366         // JS:FIXME: Everything below here should come from js.scope or something
367         public void put(JS key, JS val) throws JSExn { if(box != null) box.putAndTriggerTraps(key,val); else super.put(key,val); }
368         public void addTrap(JS key, JS f) throws JSExn { box.addTrap(key,f); }
369         public void delTrap(JS key, JS f) throws JSExn { box.delTrap(key,f); }
370     }
371
372 }
373
374