1    // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2    package org.xwt;
3    
4    import java.io.*;
5    import java.util.zip.*;
6    import java.util.*;
7    import java.lang.*;
8    import org.xwt.js.*;
9    import org.xwt.translators.*;
10   import org.xwt.util.*;
11   
12   /**
13    *  Encapsulates a template node (the <template/> element of a
14    *  .xwt file, or any child element thereof).
15    *
16    *  Note that the Template instance corresponding to the
17    *  <template/> node carries all the header information -- hence
18    *  some of the instance members are not meaningful on non-root
19    *  Template instances. We refer to these non-root instances as
20    *  <i>anonymous templates</i>.
21    *
22    *  See the XWT reference for information on the order in which
23    *  templates are applied, attributes are put, and scripts are run.
24    */
25   public class Template {
26   
27       // Instance Members ///////////////////////////////////////////////////////
28   
29       String id = null;                   ///< the id of this box
30       String redirect = null;             ///< the id of the redirect target; only meaningful on a root node
31       private String[] keys;              ///< keys to be "put" to instances of this template; elements correspond to those of vals
32       private Object[] vals;              ///< values to be "put" to instances of this template; elements correspond to those of keys
33       private Vec children = new Vec();   ///< during XML parsing, this holds the list of currently-parsed children; null otherwise
34       private JS script = null;           ///< the script on this node
35       private String tagname = null;      ///< template to preapply (if any)
36   
37   
38       // Instance Members that are only meaningful on root Template //////////////////////////////////////
39   
40       private JSScope staticScope = null;   ///< the scope in which the static block is executed
41       private JS staticscript = null;       ///< the script on the static node of this template, null already performed
42   
43   
44       // Only used during parsing /////////////////////////////////////////////////////////////////
45   
46       private StringBuffer content = null;   ///< during XML parsing, this holds partially-read character data; null otherwise
47       private int content_start = 0;         ///< line number of the first line of <tt>content</tt>
48       private int startLine = -1;            ///< the line number that this element starts on
49       private XWT xwt;
50   
51   
52       // Static data/methods ///////////////////////////////////////////////////////////////////
53   
54       // for non-root nodes
55       private Template(XWT xwt) { this.xwt = xwt; }
56       public Template(InputStream is, XWT xwt) throws IOException, JSExn, XML.Exn {
57           this.xwt = xwt; new TemplateHelper().parseit(is, this);
58       }
59       
60   
61       // Methods to apply templates ////////////////////////////////////////////////////////
62   
63       /** called before this template is applied or its static object can be externally referenced */
64       JSScope getStatic() throws JSExn {
65           if (staticScope == null) staticScope = new PerInstantiationScope(null, xwt, null, null);
66           if (staticscript == null) return staticScope;
67           JS temp = staticscript;
68           staticscript = null;
69           JS.cloneWithNewParentScope(temp, staticScope).call(null, null, null, null, 0);
70           return staticScope;
71       }
72       
73       /** Applies the template to Box b
74        *  @param pboxes a vector of all box parents on which to put $-references
75        *  @param ptemplates a vector of the fileNames to recieve private references on the pboxes
76        */
77       void apply(Box b) throws JSExn {
78           try {
79               apply(b, null);
80           } catch (IOException e) {
81               b.clear(b.VISIBLE);
82               b.mark_for_repack();
83               Log.warn(this, e);
84               throw new JSExn(e.toString());
85           } catch (JSExn e) {
86               b.clear(b.VISIBLE);
87               b.mark_for_repack();
88               Log.warn(this, e);
89               throw e;
90           }
91       }
92   
93       private void apply(Box b, PerInstantiationScope parentPis) throws JSExn, IOException {
94           getStatic();
95   
96           // FIXME this dollar stuff is all wrong
97           if (id != null) parentPis.putDollar(id, b);
98           if (tagname != null) xwt.resolveString(tagname, false).call(b, null, null, null, 1);
99   
100          PerInstantiationScope pis = new PerInstantiationScope(b, xwt, parentPis, staticScope);
101  
102          // FIXME needs to obey the new application-ordering rules
103          for (int i=0; children != null && i<children.size(); i++) {
104              Box kid = new Box();
105              ((Template)children.elementAt(i)).apply(kid, pis);
106              b.putAndTriggerTraps(b.get("numchildren"), kid);
107          }
108  
109          if (script != null) JS.cloneWithNewParentScope(script, pis).call(null, null, null, null, 0);
110  
111          Object key, val;
112          for(int i=0; keys != null && i < keys.length; i++) {
113              if (keys[i] == null) continue;
114              key = keys[i];
115              val = vals[i];
116  
117              if ("null".equals(val)) val = null;
118  
119              if (val != null && val instanceof String && ((String)val).length() > 0) {
120                  switch (((String)val).charAt(0)) {
121                      case '$':
122                          val = pis.get(val);
123                          if (val == null) throw new JSExn("unknown box id '"+vals[i]+"' referenced in XML attribute");
124                          break;
125                      case '.':
126                          val = xwt.resolveString(((String)val).substring(1), false);
127                      // FIXME: url case
128                      // FIXME: should we be resolving all of these in the XML-parsing code?
129                  }
130              }
131  
132              b.putAndTriggerTraps(key, val);
133          }
134      }
135  
136  
137  
138      // XML Parsing /////////////////////////////////////////////////////////////////
139  
140      /** handles XML parsing; builds a Template tree as it goes */
141      static final class TemplateHelper extends XML {
142  
143          TemplateHelper() { }
144  
145          private int state;
146          private static final int STATE_INITIAL = 0;
147          private static final int STATE_IN_XWT_NODE = 1;
148          private static final int STATE_IN_TEMPLATE_NODE = 2;
149          private static final int STATE_FINISHED_TEMPLATE_NODE = 3;
150  
151          private String nameOfHeaderNodeBeingProcessed;
152  
153          Vec nodeStack = new Vec();  ///< stack of Templates whose XML elements we have seen open-tags for but not close-tags
154          Template t = null;          ///< the template we're currently working on
155  
156          /** parse an XML input stream, building a Template tree off of <tt>root</tt> */
157          void parseit(InputStream is, Template root) throws XML.Exn, IOException {
158              state = STATE_INITIAL;
159              nameOfHeaderNodeBeingProcessed = null;
160              nodeStack.setSize(0);
161              t = root;
162              parse(new InputStreamReader(is)); 
163          }
164  
165          public void startElement(XML.Element c) throws XML.Exn {
166              switch(state) {
167              case STATE_INITIAL:
168                  if (!"xwt".equals(c.getLocalName()))
169                      throw new XML.Exn("root element was not <xwt>", XML.Exn.SCHEMA, getLine(), getCol());
170                  if (c.getAttrLen() != 0)
171                      throw new XML.Exn("root element must not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
172                  state = STATE_IN_XWT_NODE;
173                  return;
174  
175              case STATE_IN_XWT_NODE:
176                  if (nameOfHeaderNodeBeingProcessed != null)
177                      throw new XML.Exn("can't nest header nodes", XML.Exn.SCHEMA, getLine(), getCol());
178                  nameOfHeaderNodeBeingProcessed = c.getLocalName();
179                  //#switch(c.getLocalName())
180                  case "doc":
181                      // FEATURE
182                      return;
183                  case "static":
184                      if (t.staticscript != null)
185                          throw new XML.Exn("the <static> header node may only appear once", XML.Exn.SCHEMA, getLine(), getCol());
186                      if (c.getAttrLen() > 0)
187                          throw new XML.Exn("the <static> node may not have attributes", XML.Exn.SCHEMA, getLine(), getCol());
188                      return;
189                  case "template":
190                      t.startLine = getLine();
191                      state = STATE_IN_TEMPLATE_NODE;
192                      processBodyElement(c);
193                      return;
194                  //#end
195                  throw new XML.Exn("unrecognized header node \"" + c.getLocalName() + "\"", XML.Exn.SCHEMA, getLine(), getCol());
196  
197              case STATE_IN_TEMPLATE_NODE:
198                  // push the last node we were in onto the stack
199                  nodeStack.addElement(t);
200                  // instantiate a new node, and set its fileName/importlist/preapply
201                  Template t2 = new Template(t.xwt);
202                  t2.startLine = getLine();
203                  if (!c.getLocalName().equals("box") && !c.getLocalName().equals("template"))
204                      t2.tagname = ((c.getUri().equals("") ? "" : (c.getUri() + ".")) + c.getLocalName());
205                  // make the new node the current node
206                  t = t2;
207                  processBodyElement(c);
208                  return;
209  
210              case STATE_FINISHED_TEMPLATE_NODE:
211                  throw new XML.Exn("no elements may appear after the <template> node", XML.Exn.SCHEMA, getLine(), getCol());
212              }
213          }        
214  
215          private void processBodyElement(XML.Element c) {
216              Vec keys = new Vec(c.getAttrLen());
217              Vec vals = new Vec(c.getAttrLen());
218  
219              // process attributes into Vecs, dealing with any XML Namespaces in the process
220              ATTR: for (int i=0; i < c.getAttrLen(); i++) {
221                  //#switch(c.getAttrKey(i))
222                  case "id":
223                      t.id = c.getAttrVal(i).toString().intern();
224                      continue ATTR;
225                  //#end
226  
227                  // treat value starting with '.' as resource reference
228                  String uri = c.getAttrUri(i); if (!uri.equals("")) uri = '.' + uri;
229                  keys.addElement(c.getAttrKey(i));
230                  vals.addElement((c.getAttrVal(i).startsWith(".") ? uri : "") + c.getAttrVal(i));
231              }
232  
233              if (keys.size() == 0) return;
234  
235              // sort the attributes lexicographically
236              Vec.sort(keys, vals, new Vec.CompareFunc() { public int compare(Object a, Object b) {
237                  return ((String)a).compareTo((String)b);
238              } });
239  
240              t.keys = new String[keys.size()];
241              t.vals = new Object[vals.size()];
242              keys.copyInto(t.keys);
243              vals.copyInto(t.vals);
244  
245              // convert attributes to appropriate types and intern strings
246              for(int i=0; i<t.keys.length; i++) {
247                  t.keys[i] = t.keys[i].intern();
248  
249                  String valString = t.vals[i].toString();
250                  
251                  if (valString.equals("true")) t.vals[i] = Boolean.TRUE;
252                  else if (valString.equals("false")) t.vals[i] = Boolean.FALSE;
253                  else if (valString.equals("null")) t.vals[i] = null;
254                  else {
255                      boolean hasNonNumeral = false;
256                      boolean periodUsed = false;
257                      for(int j=0; j<valString.length(); j++)
258                          if (j == 0 && valString.charAt(j) == '-') {
259                          } else if (valString.charAt(j) == '.' && !periodUsed && j != valString.length() - 1) {
260                              periodUsed = true;
261                          } else if (!Character.isDigit(valString.charAt(j))) {
262                              hasNonNumeral = true;
263                              break;
264                          }
265                      if (valString.length() > 0 && !hasNonNumeral) t.vals[i] = new Double(valString);
266                      else t.vals[i] = valString.intern();
267                  }
268              }
269          }
270  
271          private JS parseScript(boolean isstatic) throws IOException {
272              JS thisscript = null;
273              String contentString = t.content.toString();
274              if (contentString.trim().length() > 0)
275                  thisscript = JS.fromReader("FIXME", t.content_start, new StringReader(contentString));
276              t.content = null;
277              t.content_start = 0;
278              return thisscript;
279          }
280  
281          public void endElement(XML.Element c) throws XML.Exn, IOException {
282              if (state == STATE_IN_XWT_NODE) {
283                  if ("static".equals(nameOfHeaderNodeBeingProcessed) && t.content != null) t.staticscript = parseScript(true);
284                  nameOfHeaderNodeBeingProcessed = null;
285                  
286              } else if (state == STATE_IN_TEMPLATE_NODE) {
287                  if (t.content != null) t.script = parseScript(false);
288                  if (nodeStack.size() == 0) {
289                      // </template>
290                      state = STATE_FINISHED_TEMPLATE_NODE;
291                      
292                  } else {
293                      // add this template as a child of its parent
294                      Template oldt = t;
295                      t = (Template)nodeStack.lastElement();
296                      nodeStack.setSize(nodeStack.size() - 1);
297                      t.children.addElement(oldt);
298  
299                      int oldt_lines = getLine() - oldt.startLine;
300                      for (int i=0; oldt_lines > i; i++) t.content.append('\n');
301                  }
302              }
303           }
304  
305          public void characters(char[] ch, int start, int length) throws XML.Exn {
306              // invoke the no-tab crusade
307              for (int i=0; length >i; i++) if (ch[start+i] == '\t')
308                  Log.error(Template.class, "tabs are not allowed in XWT files ("+getLine()+":"+getCol()+")");
309  
310              if ("static".equals(nameOfHeaderNodeBeingProcessed) || state == STATE_IN_TEMPLATE_NODE) {
311                  if (t.content == null) {
312                      t.content_start = getLine();
313                      t.content = new StringBuffer();
314                  }
315  
316                  t.content.append(ch, start, length);
317  
318              } else if (nameOfHeaderNodeBeingProcessed != null && state != STATE_FINISHED_TEMPLATE_NODE) { throw new XML.Exn(
319                  "header node <" +nameOfHeaderNodeBeingProcessed+ "> cannot have text content", XML.Exn.SCHEMA, getLine(), getCol());
320              }
321          }
322  
323          public void whitespace(char[] ch, int start, int length) throws XML.Exn { }
324      }
325  
326      private static class PerInstantiationScope extends JSScope {
327          XWT xwt = null;
328          PerInstantiationScope parentBoxPis = null;
329          JSScope myStatic = null;
330          void putDollar(String key, Box target) throws JSExn {
331              if (parentBoxPis != null) parentBoxPis.putDollar(key, target);
332              declare("$" + key);
333              put("$" + key, target);
334          }
335          public PerInstantiationScope(JSScope parentScope, XWT xwt, PerInstantiationScope parentBoxPis, JSScope myStatic) {
336              super(parentScope);
337              this.parentBoxPis = parentBoxPis;
338              this.xwt = xwt;
339              this.myStatic = myStatic;
340          }
341          public Object get(Object key) throws JSExn {
342              if (super.has(key)) return super.get(key);
343              if (key.equals("xwt")) return xwt;
344              if (key.equals("")) return xwt.get("");
345              if (key.equals("static")) return myStatic;
346              return super.get(key);
347          }
348          public void put(Object key, Object val) throws JSExn {
349              if (super.has(key)) super.put(key, val);
350              else super.put(key, val);
351          }
352      }
353  
354  }
355  
356  
357