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