pass correct range to sort()
[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() == null || "".equals(c.getUri()) ? "" :
211                                  (c.getUri() + ".")) + c.getLocalName();
212                 // GROSS hack
213                 try {
214                     // GROSSER hack
215                     // t.prev2 = (Template)t.ibex.resolveString(tagname, false).call(null, null, null, null, 9999);
216                     if(t.prev2 != null) throw new Error("FIXME: t.prev2 != null");
217                     t.prev2 = ((Ibex.Blessing)t.ibex.resolveString(tagname, false)).getTemplate();
218                     if(t.prev2 == null) throw new Exception("" + tagname + " not found");
219                 } catch (Exception e) {
220                     Log.error(Template.class, e);
221                 }
222             }
223
224             Tree.Prefixes prefixes = c.getPrefixes();
225             t.urikeys = new String[prefixes.pfxSize()];
226             t.urivals = new String[prefixes.pfxSize()];
227
228             int ii = 0;
229             for (int i=0; i < prefixes.pfxSize(); i++) {
230                 String key = prefixes.getPrefixKey(i);
231                 String val = prefixes.getPrefixVal(i);
232                 if (val.equals("ibex://ui")) continue;
233                 if (val.equals("ibex://meta")) continue;
234                 t.urikeys[ii] = key;
235                 if (val.length() > 0 && val.charAt(0) == '.') val = val.substring(1);
236                 t.urivals[ii] = val;
237                 ii++;
238             }
239
240             // FIXME: 2-value Array
241             Basket.Array keys = new Basket.Array(a.attrSize());
242             Basket.Array vals = new Basket.Array(a.attrSize());
243
244             // process attributes into Vecs, dealing with any XML Namespaces in the process
245             ATTR: for (int i=0; i < a.attrSize(); i++) {
246                 if (a.getKey(i).equals("id")) {
247                     t.id = a.getVal(i).toString().intern();
248                     continue ATTR;
249                 }
250
251                 // treat value starting with '.' as resource reference
252                 String uri = a.getUri(i); if (uri != null && !uri.equals("")) uri = '.' + uri;
253                 keys.add(a.getKey(i));
254                 vals.add((a.getVal(i).startsWith(".") ? uri : "") + a.getVal(i));
255             }
256
257             if (keys.size() == 0) return;
258
259             // sort the attributes lexicographically
260             Basket.Array.sort(keys, vals, new Basket.CompareFunc() {
261                 public int compare(Object a, Object b) { return ((String)a).compareTo((String)b); }
262             }, 0, keys.size() - 1);
263
264             t.keys = new JS[keys.size()];
265             t.vals = new JS[vals.size()];
266             
267             // convert attributes to appropriate types and intern strings
268             for(int i=0; i<t.keys.length; i++) {
269                 // FEATURE: Intern
270                 t.keys[i] = JSU.S((String)keys.get(i));
271                 String valString = (String) vals.get(i);
272                 
273                 if (valString.equals("true")) t.vals[i] = JSU.T;
274                 else if (valString.equals("false")) t.vals[i] = JSU.F;
275                 else if (valString.equals("null")) t.vals[i] = null;
276                 else {
277                     boolean hasNonNumeral = false;
278                     boolean periodUsed = false;
279                     for(int j=0; j<valString.length(); j++)
280                         if (j == 0 && valString.charAt(j) == '-') {
281                         } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
282                             periodUsed = true;
283                         } else if (!Character.isDigit(valString.charAt(j))) {
284                             hasNonNumeral = true;
285                             break;
286                         }
287                     if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = JSU.N(Double.parseDouble((valString)));
288                     else t.vals[i] = JSU.S(valString.intern()); // FEATURE: JS.intern() ?
289                 }
290             }
291         }
292
293         public void endElement(Tree.Element c) throws XML.Exn, IOException {
294             switch(state) {
295                 case STATE_IN_META_NODE: if (--meta < 0) state = STATE_IN_ROOT_NODE; return;
296                 case STATE_IN_ROOT_NODE: return;
297                 case STATE_IN_TEMPLATE_NODE: {
298                     if (t.content != null) { t.script = parseScript(t.content, t.content_start); t.content = null; }
299                     if (nodeStack.size() == 0) { state = STATE_IN_ROOT_NODE; return; }
300                     Template oldt = t;
301                     t = (Template)nodeStack.lastElement();
302                     nodeStack.setSize(nodeStack.size() - 1);
303                     t.children.addElement(oldt);
304                     int oldt_lines = getLine() - oldt.startLine;
305                     if (t.content == null) t.content = new StringBuffer();
306                     for (int i=0; oldt_lines > i; i++) t.content.append('\n');
307                 }
308             }
309         }
310
311         public void characters(char[] ch, int start, int length) throws XML.Exn {
312             for (int i=0; length >i; i++) if (ch[start+i] == '\t')
313                 Log.error(Template.class, "tabs are not allowed in Ibex files ("+getLine()+":"+getCol()+")");
314             switch(state) {
315                 case STATE_IN_TEMPLATE_NODE:
316                     if (t.content == null) {
317                         t.content_start = getLine();
318                         t.content = new StringBuffer();
319                     }
320                     t.content.append(ch, start, length);
321                     return;
322                 case STATE_IN_ROOT_NODE:
323                     if (static_content == null) {
324                         static_content_start = getLine();
325                         static_content = new StringBuffer();
326                     }
327                     static_content.append(ch, start, length);
328                     return;
329             }
330         }
331
332         public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
333     }
334
335     // FIXME: david, get to work
336     private static class PerInstantiationScope extends JS.Obj {
337         Ibex ibex = null;
338         PerInstantiationScope parentBoxPis = null;
339         JS myStatic = null;
340         JS box;
341         void putDollar(String key, Box target) throws JSExn {
342             if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
343             JS jskey = JSU.S("$" + key);
344             //declare(jskey);
345             sput(jskey, target);
346         }
347         // JS:FIXME: ugly
348         void sput(JS key, JS val) throws JSExn { super.put(key,val); }
349         public PerInstantiationScope(JS box, Ibex ibex, PerInstantiationScope parentBoxPis, JS myStatic) {
350             this.parentBoxPis = parentBoxPis;
351             this.ibex = ibex;
352             this.myStatic = myStatic;
353             this.box = box;
354         }
355         public JS get(JS key) throws JSExn {
356             if(JSU.isString(key)) {
357                 String s = JSU.toString(key);
358                 // JS:FIXME This is a hack
359                 if (super.get(key) != null) return super.get(key);
360                 if (s.equals("ibex")) return ibex;
361                 if (s.equals("")) return ibex.get(key);
362                 if (s.equals("static")) return myStatic;
363             }
364             // JS:FIXME: This won't work with traps that do blocking operations
365             return box.getAndTriggerTraps(key);
366         }
367         // JS:FIXME: Everything below here should come from js.scope or something
368         public void put(JS key, JS val) throws JSExn { if(box != null) box.putAndTriggerTraps(key,val); else super.put(key,val); }
369         public void addTrap(JS key, JS f) throws JSExn { box.addTrap(key,f); }
370         public void delTrap(JS key, JS f) throws JSExn { box.delTrap(key,f); }
371     }
372
373 }
374
375