c6eee6ec4e6fa79d50488a9092c9448b94470d84
[org.ibex.xt-crawshaw.git] / src / java / org / ibex / xt / JSElement.java
1 package org.ibex.xt;
2
3 import java.io.StringReader;
4 import java.io.Writer;
5 import java.io.OutputStream;
6 import java.io.IOException;
7 import java.util.*;
8
9 import org.ibex.util.*;
10 import org.ibex.js.JS;
11 import org.ibex.js.JSScope;
12 import org.ibex.js.JSExn;
13
14 public class JSElement extends JSScope implements XML.Element {
15     protected XML.Element wrapped;
16
17     /** Creates an Element around <tt>wrapped</tt>, replacing
18      *  references to it in its parent and children with this object. */
19     public JSElement(XML.Element wrapped) {
20         super(findScope(wrapped));
21         this.wrapped = wrapped;
22
23         // remap parent and children
24         if (wrapped.getParent() != null) {
25             List c = wrapped.getParent().getChildren();
26             c.set(c.indexOf(wrapped), this);
27         }
28         List c = wrapped.getChildren();
29         for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).setParent(this);
30     }
31
32     public void out(OutputStream o) throws IOException { wrapped.out(o); }
33     public void out(Writer w) throws IOException { wrapped.out(w); }
34
35     /** Load the attributes into the js scope. */
36     protected void loadAttr() {
37         try {
38             XML.Attributes a = getAttributes();
39             // FIXME: questionable abuse of XML namespaces here
40             boolean xturi = "http://xt.ibex.org/".equals(getUri());
41             for(int i=0; i < a.attrSize(); i++) {
42                 if (!xturi && !"http://xt.ibex.org/".equals(a.getUri(i))) continue;
43                 declare(a.getKey(i));
44                 put(a.getKey(i), eval(a.getVal(i)));
45             }
46         } catch (JSExn e) { throw new Exn(e); }
47     }
48
49     private Object eval(String s) {
50         if (s == null) return null;
51         StringBuffer ret = new StringBuffer();
52         while (s.indexOf("${") != -1) {
53             ret.append(s.substring(0, s.indexOf("${")));
54             String s2 = s.substring(s.indexOf("${")+2);
55             Object app = exec("return (" + s2.substring(0, s2.indexOf('}')) + ");\n");
56             s = s.substring(s.indexOf('}') + 1);
57
58             if (!(app == null ||
59                   app instanceof String ||
60                   app instanceof Number ||
61                   app instanceof Boolean))
62                 throw new Exn("javascripts within ${...} can only return " +
63                               "strings, numbers, and booleans; not a " +
64                               app.getClass().getName());
65
66             ret.append(app == null ? "null" : app.toString());
67         }
68         ret.append(s);
69         return ret.toString();
70     }
71
72     public Object exec(String s) {
73         try {
74             return JS.eval(JS.cloneWithNewParentScope(
75                            JS.fromReader("input", 0, new StringReader(s)), this));
76         } catch (IOException e) {
77             e.printStackTrace();
78             throw new Exn("impossible IOException, reading from StringReader");
79         } catch (JSExn e) {
80             throw new Exn(e);
81         }
82     }
83
84     // Pass Through ///////////////////////////////////////////////////////////
85
86     public void setParent(Tree.Node p)    { wrapped.setParent(p); }
87     public Tree.Node getParent()          { return wrapped.getParent(); }
88     public XML.Attributes getAttributes() { return wrapped.getAttributes(); }
89     public XML.Prefixes getPrefixes()     { return wrapped.getPrefixes(); }
90     public List getChildren()             { return wrapped.getChildren(); }
91     public String getQName()              { return wrapped.getQName(); }
92     public String getLocalName()          { return wrapped.getLocalName(); }
93     public String getPrefix()             { return wrapped.getPrefix(); }
94     public String getUri()                { return wrapped.getUri(); }
95
96     /** Works up the Element object model until an instance of a JSScope is found. */
97     private static JSScope findScope(Tree.Node e) {
98         while (e != null && !(e instanceof JSScope)) e = e.getParent();
99         return (JSScope)e;
100     }
101
102     /** A JSElement with the element attributes merged with a second
103      *  element.
104      *
105      *  All functions of the XML.Element interface are mapped onto the
106      *  primary element, except <tt>getAttributes()</tt>. This function
107      *  returns a MergedAttr instance with the <b>secondary</b> element
108      *  acting as the primary attribute source.
109      */
110     public static class Merge extends JSElement {
111         private final XML.Attributes a;
112         public Merge(XML.Element wrapped, XML.Element merge) {
113             super(wrapped);
114             a = new MergeAttr(merge.getAttributes(), wrapped.getAttributes());
115         }
116         public XML.Attributes getAttributes() { return a; }
117     }
118
119     /** Creates a single view onto two sets of Attributes, first
120      *  checking the <tt>primary</tt> array for an entry, or
121      *  otherwise returning any matching entry in the
122      *  <tt>secondary</tt> Attributes object.
123      *
124      *  FIXME: toXML() produces invalid XML if qname in both a and b.
125      */
126     public static final class MergeAttr implements XML.Attributes {
127         private final XML.Attributes a, b;
128         public MergeAttr(XML.Attributes primary, XML.Attributes secondary) {
129             a = primary; b = secondary;
130         }
131         public int getIndex(String qname) {
132             int i = a.getIndex(qname); if (i >= 0) return i;
133                 i = b.getIndex(qname); if (i >= 0) return i + a.attrSize();
134             return -1;
135         }
136         public int getIndex(String uri, String key) {
137             int i = a.getIndex(uri, key); if (i >= 0) return i;
138                 i = b.getIndex(uri, key); if (i >= 0) return i + b.attrSize();
139             return -1;
140         }
141         public String getKey(int i) {
142             return i >= a.attrSize() ? b.getKey(i-a.attrSize()) : a.getKey(i); }
143         public String getVal(int i) {
144             return i >= a.attrSize() ? b.getVal(i-a.attrSize()) : a.getVal(i); }
145         public String getUri(int i) {
146             return i >= a.attrSize() ? b.getUri(i-a.attrSize()) : a.getUri(i); }
147         public String getPrefix(int i) {
148             return i >= a.attrSize() ? b.getUri(i-a.attrSize()) : a.getUri(i); }
149         public String getQName(int i) {
150             return i >= a.attrSize() ? b.getUri(i-a.attrSize()) : a.getUri(i); }
151         public int attrSize() { return a.attrSize() + b.attrSize(); }
152     }
153
154     public static class Exn extends RuntimeException {
155         public Exn(String cause) { super(cause); }
156         public Exn(JSExn e) { super(e); }
157         public String toString() { return "JSElement.Exn: "+getMessage(); }
158     }
159 }