c9b8611628bd817896347fc1834a3d54d75131b3
[org.ibex.xt-crawshaw.git] / src / java / org / ibex / xt / Template.java
1 package org.ibex.xt;
2
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.InputStreamReader;
6 import java.io.Reader;
7 import java.io.StringReader;
8 import java.io.StringWriter;
9 import java.io.Writer;
10 import java.io.IOException;
11
12 import java.util.*;
13 import org.ibex.util.*;
14 import org.ibex.js.*;
15
16 public class Template extends JSElement {
17     public static Template parse(String path, Template.Scope s) throws IOException {
18         Reader xmlreader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
19         XML.Document doc = new XML.Document();
20         doc.parse(xmlreader);
21         return new Template(doc.getRoot(), s);
22     }
23
24     public static XML.Element wrap(XML.Element e, Template.Scope s) throws IOException {
25         final String uri = e.getUri();
26
27         if (uri.equals("http://xt.ibex.org/")) {
28             //#switch(e.getLocalName())
29             case "js":          e = new Template.JSTag(e); break;
30             case "foreach":     e = new Template.ForEach(e); break;
31             case "children":    e = new Template.Children(e); break;
32             case "transaction": e = new Template.Transaction(e, s); break;
33             //#end
34
35         } else if (uri.startsWith("http://xt.ibex.org/")) {
36             //#switch(uri.substring(19))
37             case "io": System.out.println("ibex.xt.io not yet implemented"); // TODO
38             //#end
39             //throw new RuntimeException("Unknown XT library: "+uri);
40
41         } else if (uri.startsWith("local:")) {
42             Template t = parse(s.getLocalPath() + uri.substring(6), s);
43
44             List c = e.getChildren();
45             if (c.size() > 0) {
46                 // move all children from e to placeholder
47                 XML.Element placeholder = findPlaceholder(t);
48                 if (placeholder == null) throw new RuntimeException(
49                     "<"+e.getQName()+"> attempted to include children into a " +
50                     "template which does not contain an <xt:children /> tag.");
51
52                 placeholder.getChildren().addAll(e.getChildren());
53                 e.getChildren().clear();
54             }
55
56             // merge original attributes with replacement template
57             e = new JSElement.Merge(t, e);
58         }
59
60         XML.Attributes a = e.getAttributes();
61         for (int i=0; i < a.attrSize(); i++) {
62             if ("if".equals(a.getKey(i)) &&
63                 "http://xt.ibex.org/".equals(a.getUri(i))) {
64                 e = new Template.IfWrap(e);
65             }
66         }
67
68         // wrap children
69         List c = e.getChildren();
70         for (int i=0; i < c.size(); i++)
71             if (c.get(i) instanceof XML.Element) wrap((XML.Element)c.get(i), s);
72
73         return e;
74     }
75
76     /** Returns the first Template.Children child found. */
77     private static Template.Children findPlaceholder(XML.Element e) {
78         if (e instanceof Template.Children) return (Template.Children)e;
79         List c = e.getChildren();
80         for (int i=0; i < c.size(); i++) {
81             if (!(c.get(i) instanceof XML.Element)) continue;
82             Template.Children ret = findPlaceholder((XML.Element)c.get(i));
83             if (ret != null) return ret;
84         }
85         return null;
86     }
87
88     private Template.Scope tscope;
89
90     public Template(XML.Element w, Template.Scope t) { super(w); tscope = t; }
91
92     public JSScope getParentScope() { return tscope; }
93
94     public static final class IfWrap extends JSElement {
95         public IfWrap(XML.Element e) { super(e); }
96
97         public void out(Writer w) throws IOException {
98             loadAttr();
99
100             try {
101                 Object varIf = get("if"); if (varIf != null) undeclare("if");
102                 if (varIf != null && !Boolean.getBoolean((String)varIf)) return;
103             } catch (JSExn e) { throw new RuntimeException(e); }
104
105             wrapped.out(w);
106         }
107     }
108
109     public static final class JSTag extends JSElement {
110         public JSTag(XML.Element e) {
111             super(e);
112             List c = getChildren();
113             for (int i=0; i < c.size(); i++)
114                 if (c.get(i) instanceof XML.Element) throw new RuntimeException(
115                     "<"+getPrefix()+":js> tags may not have child elements");
116         }
117
118         public void out(Writer w) throws IOException {
119             loadAttr();
120
121             List c = getChildren();
122             StringWriter s = new StringWriter();
123             for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(s);
124             exec(s.toString());
125         }
126     }
127
128     public static final class ForEach extends JSElement {
129         public ForEach(XML.Element e) { super(e); }
130
131         public void out(Writer w) throws IOException {
132             loadAttr();
133
134             try {
135                 Object varIn = get("in"); if (varIn != null) undeclare("in");
136                 Object varPut = get("put"); if (varPut != null) undeclare("put");
137
138                 varIn = exec("return (" + varIn + ");");
139                 if (varIn == null || (varIn instanceof JSArray)) throw new RuntimeException(
140                     "<"+getPrefix()+":foreach> requires attribute 'in' to specify " +
141                     "the name of a valid js array in the current scope, not in='"+varIn+"'.");
142
143                 if (varPut == null) varPut = "x";
144                 else if (!(varPut instanceof String) || get(varPut) != null)
145                     throw new RuntimeException(
146                     "<"+getPrefix()+":foreach> 'put' attribute requires the name of "+
147                     "an undeclared variable, not put='"+varPut+"'.");
148                 if (get(varPut) != null) throw new RuntimeException(
149                     "<"+getPrefix()+":foreach> has no 'put' attribute defined and the "+
150                     "default variable 'x' already exists in the current scope.");
151
152                 List c = getChildren();
153
154                 declare((String)varPut);
155                 Iterator it = ((JSArray)varIn).toList().iterator(); while (it.hasNext()) {
156                     put(varPut, it.next());
157                     for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(w);
158                 }
159             } catch (JSExn e) { throw new RuntimeException(e); }
160         }
161     }
162
163     public static final class Children extends JSElement {
164         public Children(XML.Element e) { super(e); }
165     }
166
167     // TODO: finish
168     public static final class Transaction extends JSElement {
169         private final Template.Scope scope; // FIXME: HACK. unstatisise all tags, or do this to all
170         public Transaction(XML.Element e, Template.Scope s) { super(e); scope = s;} // TODO: check kids
171
172         public void out(Writer w) throws IOException {
173             loadAttr();
174
175             // TODO: <xt:use />
176             List c = getChildren();
177             StringWriter sw = new StringWriter();
178             for (int i=0; i < c.size(); i++) ((Tree.Leaf)c.get(i)).out(sw);
179             JS t = JS.fromReader("input", 0, new StringReader(sw.toString()));
180             t = JS.cloneWithNewParentScope(t, new JSScope(null));
181             scope.transaction(t);
182         }
183     }
184
185     public static final class Java extends JSElement {
186         // TODO what exactly?
187         public Java(XML.Element w) { super(w); }
188     }
189
190     public abstract static class Scope extends JSScope {
191         public Scope(JSScope j) { super(j); }
192
193         /** Returns the template path for local:/ namespace. */
194         public abstract String getLocalPath();
195
196         /** Registers a new Prevayler transaction. */
197         public abstract void transaction(JS t);
198     }
199
200 }