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