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