javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 04 Apr 2013 13:08:26 +0200
branchmodel
changeset 930 e8916518b38d
parent 929 b43aaf398748
child 934 19b4ddc302a6
permissions -rw-r--r--
clone() on model classes
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.OutputStreamWriter;
    23 import java.io.StringWriter;
    24 import java.io.Writer;
    25 import java.util.ArrayList;
    26 import java.util.Collection;
    27 import java.util.Collections;
    28 import java.util.HashMap;
    29 import java.util.LinkedHashSet;
    30 import java.util.List;
    31 import java.util.Map;
    32 import java.util.Set;
    33 import java.util.WeakHashMap;
    34 import javax.annotation.processing.AbstractProcessor;
    35 import javax.annotation.processing.Completion;
    36 import javax.annotation.processing.Completions;
    37 import javax.annotation.processing.Processor;
    38 import javax.annotation.processing.RoundEnvironment;
    39 import javax.annotation.processing.SupportedAnnotationTypes;
    40 import javax.lang.model.element.AnnotationMirror;
    41 import javax.lang.model.element.Element;
    42 import javax.lang.model.element.ElementKind;
    43 import javax.lang.model.element.ExecutableElement;
    44 import javax.lang.model.element.Modifier;
    45 import javax.lang.model.element.PackageElement;
    46 import javax.lang.model.element.TypeElement;
    47 import javax.lang.model.element.VariableElement;
    48 import javax.lang.model.type.MirroredTypeException;
    49 import javax.lang.model.type.TypeKind;
    50 import javax.lang.model.type.TypeMirror;
    51 import javax.lang.model.util.Elements;
    52 import javax.lang.model.util.Types;
    53 import javax.tools.Diagnostic;
    54 import javax.tools.FileObject;
    55 import javax.tools.StandardLocation;
    56 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    57 import org.apidesign.bck2brwsr.htmlpage.api.Model;
    58 import org.apidesign.bck2brwsr.htmlpage.api.On;
    59 import org.apidesign.bck2brwsr.htmlpage.api.OnFunction;
    60 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    61 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    62 import org.openide.util.lookup.ServiceProvider;
    63 
    64 /** Annotation processor to process an XHTML page and generate appropriate 
    65  * "id" file.
    66  *
    67  * @author Jaroslav Tulach <jtulach@netbeans.org>
    68  */
    69 @ServiceProvider(service=Processor.class)
    70 @SupportedAnnotationTypes({
    71     "org.apidesign.bck2brwsr.htmlpage.api.Model",
    72     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    73     "org.apidesign.bck2brwsr.htmlpage.api.OnFunction",
    74     "org.apidesign.bck2brwsr.htmlpage.api.On"
    75 })
    76 public final class PageProcessor extends AbstractProcessor {
    77     private final Map<Element,String> models = new WeakHashMap<>();
    78     @Override
    79     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    80         boolean ok = true;
    81         for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
    82             if (!processModel(e)) {
    83                 ok = false;
    84             }
    85         }
    86         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    87             if (!processPage(e)) {
    88                 ok = false;
    89             }
    90         }
    91         if (roundEnv.processingOver()) {
    92             models.clear();
    93         }
    94         return ok;
    95     }
    96 
    97     private InputStream openStream(String pkg, String name) throws IOException {
    98         try {
    99             FileObject fo = processingEnv.getFiler().getResource(
   100                 StandardLocation.SOURCE_PATH, pkg, name);
   101             return fo.openInputStream();
   102         } catch (IOException ex) {
   103             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   104         }
   105     }
   106     
   107     private boolean processModel(Element e) {
   108         boolean ok = true;
   109         Model m = e.getAnnotation(Model.class);
   110         if (m == null) {
   111             return true;
   112         }
   113         String pkg = findPkgName(e);
   114         Writer w;
   115         String className = m.className();
   116         try {
   117             StringWriter body = new StringWriter();
   118             List<String> propsGetSet = new ArrayList<>();
   119             List<String> functions = new ArrayList<>();
   120             Map<String, Collection<String>> propsDeps = new HashMap<>();
   121             if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   122                 ok = false;
   123             }
   124             if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
   125                 ok = false;
   126             }
   127             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   128                 ok = false;
   129             }
   130             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   131             w = new OutputStreamWriter(java.openOutputStream());
   132             try {
   133                 w.append("package " + pkg + ";\n");
   134                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   135                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   136                 w.append("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
   137                 w.append("final class ").append(className).append(" implements Cloneable {\n");
   138                 w.append("  private Object json;\n");
   139                 w.append("  private boolean locked;\n");
   140                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   141                 w.append(body.toString());
   142                 w.append("  private static Class<" + inPckName(e) + "> modelFor() { return null; }\n");
   143                 w.append("  public ").append(className).append("() {\n");
   144                 w.append("    ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
   145                 writeStringArray(propsGetSet, w);
   146                 w.append(", ");
   147                 writeStringArray(functions, w);
   148                 w.append("    );\n");
   149                 w.append("  };\n");
   150                 writeToString(m.properties(), w);
   151                 writeClone(className, m.properties(), w);
   152                 w.append("}\n");
   153             } finally {
   154                 w.close();
   155             }
   156         } catch (IOException ex) {
   157             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   158             return false;
   159         }
   160         return ok;
   161     }
   162     
   163     private boolean processPage(Element e) {
   164         boolean ok = true;
   165         Page p = e.getAnnotation(Page.class);
   166         if (p == null) {
   167             return true;
   168         }
   169         String pkg = findPkgName(e);
   170 
   171         ProcessPage pp;
   172         try (InputStream is = openStream(pkg, p.xhtml())) {
   173             pp = ProcessPage.readPage(is);
   174             is.close();
   175         } catch (IOException iOException) {
   176             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml() + " as " + iOException.getMessage(), e);
   177             ok = false;
   178             pp = null;
   179         }
   180         Writer w;
   181         String className = p.className();
   182         if (className.isEmpty()) {
   183             int indx = p.xhtml().indexOf('.');
   184             className = p.xhtml().substring(0, indx);
   185         }
   186         try {
   187             StringWriter body = new StringWriter();
   188             List<String> propsGetSet = new ArrayList<>();
   189             List<String> functions = new ArrayList<>();
   190             Map<String, Collection<String>> propsDeps = new HashMap<>();
   191             if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   192                 ok = false;
   193             }
   194             if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
   195                 ok = false;
   196             }
   197             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   198                 ok = false;
   199             }
   200             
   201             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   202             w = new OutputStreamWriter(java.openOutputStream());
   203             try {
   204                 w.append("package " + pkg + ";\n");
   205                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   206                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   207                 w.append("final class ").append(className).append(" {\n");
   208                 w.append("  private boolean locked;\n");
   209                 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   210                     ok = false;
   211                 } else {
   212                     if (pp != null) for (String id : pp.ids()) {
   213                         String tag = pp.tagNameForId(id);
   214                         String type = type(tag);
   215                         w.append("  ").append("public final ").
   216                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   217                             append(type).append("(\"").append(id).append("\");\n");
   218                     }
   219                 }
   220                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   221                 w.append(body.toString());
   222                 if (!propsGetSet.isEmpty()) {
   223                     w.write("public " + className + " applyBindings() {\n");
   224                     w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   225                     w.write(className + ".class, this, ");
   226                     writeStringArray(propsGetSet, w);
   227                     w.append(", ");
   228                     writeStringArray(functions, w);
   229                     w.write(");\n  return this;\n}\n");
   230 
   231                     w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   232                     w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   233                     w.write("}\n");
   234                 }
   235                 w.append("}\n");
   236             } finally {
   237                 w.close();
   238             }
   239         } catch (IOException ex) {
   240             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   241             return false;
   242         }
   243         return ok;
   244     }
   245 
   246     private static String type(String tag) {
   247         if (tag.equals("title")) {
   248             return "Title";
   249         }
   250         if (tag.equals("button")) {
   251             return "Button";
   252         }
   253         if (tag.equals("input")) {
   254             return "Input";
   255         }
   256         if (tag.equals("canvas")) {
   257             return "Canvas";
   258         }
   259         if (tag.equals("img")) {
   260             return "Image";
   261         }
   262         return "Element";
   263     }
   264 
   265     private static String cnstnt(String id) {
   266         return id.replace('.', '_').replace('-', '_');
   267     }
   268 
   269     private boolean initializeOnClick(
   270         String className, TypeElement type, Writer w, ProcessPage pp
   271     ) throws IOException {
   272         boolean ok = true;
   273         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   274         { //for (Element clazz : pe.getEnclosedElements()) {
   275           //  if (clazz.getKind() != ElementKind.CLASS) {
   276             //    continue;
   277            // }
   278             w.append("  public ").append(className).append("() {\n");
   279             StringBuilder dispatch = new StringBuilder();
   280             int dispatchCnt = 0;
   281             for (Element method : type.getEnclosedElements()) {
   282                 On oc = method.getAnnotation(On.class);
   283                 if (oc != null) {
   284                     for (String id : oc.id()) {
   285                         if (pp == null) {
   286                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
   287                             ok = false;
   288                             continue;
   289                         }
   290                         if (pp.tagNameForId(id) == null) {
   291                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   292                             ok = false;
   293                             continue;
   294                         }
   295                         ExecutableElement ee = (ExecutableElement)method;
   296                         CharSequence params = wrapParams(ee, id, className, "ev", null);
   297                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   298                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   299                             ok = false;
   300                             continue;
   301                         }
   302                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   303                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   304                             ok = false;
   305                             continue;
   306                         }
   307                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   308                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   309 
   310                         dispatch.
   311                             append("      case ").append(dispatchCnt).append(": ").
   312                             append(type.getSimpleName().toString()).
   313                             append('.').append(ee.getSimpleName()).append("(").
   314                             append(params).
   315                             append("); break;\n");
   316                         
   317                         dispatchCnt++;
   318                     }
   319                 }
   320             }
   321             w.append("  }\n");
   322             if (dispatchCnt > 0) {
   323                 w.append("class OnDispatch implements OnHandler {\n");
   324                 w.append("  private final int dispatch;\n");
   325                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   326                 w.append("  public void onEvent(Object ev) {\n");
   327                 w.append("    switch (dispatch) {\n");
   328                 w.append(dispatch);
   329                 w.append("    }\n");
   330                 w.append("  }\n");
   331                 w.append("}\n");
   332             }
   333             
   334 
   335         }
   336         return ok;
   337     }
   338 
   339     @Override
   340     public Iterable<? extends Completion> getCompletions(
   341         Element element, AnnotationMirror annotation, 
   342         ExecutableElement member, String userText
   343     ) {
   344         if (!userText.startsWith("\"")) {
   345             return Collections.emptyList();
   346         }
   347         
   348         Element cls = findClass(element);
   349         Page p = cls.getAnnotation(Page.class);
   350         String pkg = findPkgName(cls);
   351         ProcessPage pp;
   352         try {
   353             InputStream is = openStream(pkg, p.xhtml());
   354             pp = ProcessPage.readPage(is);
   355             is.close();
   356         } catch (IOException iOException) {
   357             return Collections.emptyList();
   358         }
   359         
   360         List<Completion> cc = new ArrayList<>();
   361         userText = userText.substring(1);
   362         for (String id : pp.ids()) {
   363             if (id.startsWith(userText)) {
   364                 cc.add(Completions.of("\"" + id + "\"", id));
   365             }
   366         }
   367         return cc;
   368     }
   369     
   370     private static Element findClass(Element e) {
   371         if (e == null) {
   372             return null;
   373         }
   374         Page p = e.getAnnotation(Page.class);
   375         if (p != null) {
   376             return e;
   377         }
   378         return e.getEnclosingElement();
   379     }
   380 
   381     private boolean generateProperties(
   382         Element where,
   383         Writer w, Property[] properties,
   384         Collection<String> props, Map<String,Collection<String>> deps
   385     ) throws IOException {
   386         boolean ok = true;
   387         for (Property p : properties) {
   388             final String tn;
   389             tn = typeName(where, p);
   390             String[] gs = toGetSet(p.name(), tn, p.array());
   391 
   392             if (p.array()) {
   393                 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
   394                     + p.name() + "\"");
   395                 final Collection<String> dependants = deps.get(p.name());
   396                 if (dependants != null) {
   397                     for (String depProp : dependants) {
   398                         w.write(", ");
   399                         w.write('\"');
   400                         w.write(depProp);
   401                         w.write('\"');
   402                     }
   403                 }
   404                 w.write(");\n");
   405                 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   406                 w.write("  if (locked) throw new IllegalStateException();\n");
   407                 w.write("  prop_" + p.name() + ".assign(ko);\n");
   408                 w.write("  return prop_" + p.name() + ";\n");
   409                 w.write("}\n");
   410             } else {
   411                 w.write("private " + tn + " prop_" + p.name() + ";\n");
   412                 w.write("public " + tn + " " + gs[0] + "() {\n");
   413                 w.write("  if (locked) throw new IllegalStateException();\n");
   414                 w.write("  return prop_" + p.name() + ";\n");
   415                 w.write("}\n");
   416                 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   417                 w.write("  if (locked) throw new IllegalStateException();\n");
   418                 w.write("  prop_" + p.name() + " = v;\n");
   419                 w.write("  if (ko != null) {\n");
   420                 w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   421                 final Collection<String> dependants = deps.get(p.name());
   422                 if (dependants != null) {
   423                     for (String depProp : dependants) {
   424                         w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   425                     }
   426                 }
   427                 w.write("  }\n");
   428                 w.write("}\n");
   429             }
   430             
   431             props.add(p.name());
   432             props.add(gs[2]);
   433             props.add(gs[3]);
   434             props.add(gs[0]);
   435         }
   436         return ok;
   437     }
   438 
   439     private boolean generateComputedProperties(
   440         Writer w, Property[] fixedProps,
   441         Collection<? extends Element> arr, Collection<String> props,
   442         Map<String,Collection<String>> deps
   443     ) throws IOException {
   444         boolean ok = true;
   445         for (Element e : arr) {
   446             if (e.getKind() != ElementKind.METHOD) {
   447                 continue;
   448             }
   449             if (e.getAnnotation(ComputedProperty.class) == null) {
   450                 continue;
   451             }
   452             ExecutableElement ee = (ExecutableElement)e;
   453             final TypeMirror rt = ee.getReturnType();
   454             final Types tu = processingEnv.getTypeUtils();
   455             TypeMirror ert = tu.erasure(rt);
   456             String tn = fqn(ert, ee);
   457             boolean array = false;
   458             if (tn.equals("java.util.List")) {
   459                 array = true;
   460             }
   461             
   462             final String sn = ee.getSimpleName().toString();
   463             String[] gs = toGetSet(sn, tn, array);
   464             
   465             w.write("public " + tn + " " + gs[0] + "() {\n");
   466             w.write("  if (locked) throw new IllegalStateException();\n");
   467             int arg = 0;
   468             for (VariableElement pe : ee.getParameters()) {
   469                 final String dn = pe.getSimpleName().toString();
   470                 
   471                 if (!verifyPropName(pe, dn, fixedProps)) {
   472                     ok = false;
   473                 }
   474                 
   475                 final String dt = fqn(pe.asType(), ee);
   476                 String[] call = toGetSet(dn, dt, false);
   477                 w.write("  " + dt + " arg" + (++arg) + " = ");
   478                 w.write(call[0] + "();\n");
   479                 
   480                 Collection<String> depends = deps.get(dn);
   481                 if (depends == null) {
   482                     depends = new LinkedHashSet<>();
   483                     deps.put(dn, depends);
   484                 }
   485                 depends.add(sn);
   486             }
   487             w.write("  try {\n");
   488             w.write("    locked = true;\n");
   489             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   490             String sep = "";
   491             for (int i = 1; i <= arg; i++) {
   492                 w.write(sep);
   493                 w.write("arg" + i);
   494                 sep = ", ";
   495             }
   496             w.write(");\n");
   497             w.write("  } finally {\n");
   498             w.write("    locked = false;\n");
   499             w.write("  }\n");
   500             w.write("}\n");
   501 
   502             props.add(e.getSimpleName().toString());
   503             props.add(gs[2]);
   504             props.add(null);
   505             props.add(gs[0]);
   506         }
   507         
   508         return ok;
   509     }
   510 
   511     private static String[] toGetSet(String name, String type, boolean array) {
   512         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   513         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   514         if ("int".equals(type)) {
   515             bck2brwsrType = "I";
   516         }
   517         if ("double".equals(type)) {
   518             bck2brwsrType = "D";
   519         }
   520         String pref = "get";
   521         if ("boolean".equals(type)) {
   522             pref = "is";
   523             bck2brwsrType = "Z";
   524         }
   525         final String nu = n.replace('.', '_');
   526         if (array) {
   527             return new String[] { 
   528                 "get" + n,
   529                 null,
   530                 "get" + nu + "__Ljava_util_List_2",
   531                 null
   532             };
   533         }
   534         return new String[]{
   535             pref + n, 
   536             "set" + n, 
   537             pref + nu + "__" + bck2brwsrType,
   538             "set" + nu + "__V" + bck2brwsrType
   539         };
   540     }
   541 
   542     private String typeName(Element where, Property p) {
   543         String ret;
   544         boolean[] isModel = { false };
   545         boolean[] isEnum = { false };
   546         ret = checkType(p, isModel, isEnum);
   547         if (p.array()) {
   548             String bt = findBoxedType(ret);
   549             if (bt != null) {
   550                 return bt;
   551             }
   552         }
   553         if (!isModel[0] && !"java.lang.String".equals(ret) && !isEnum[0]) {
   554             String bt = findBoxedType(ret);
   555             if (bt == null) {
   556                 processingEnv.getMessager().printMessage(
   557                     Diagnostic.Kind.ERROR, 
   558                     "Only primitive types supported in the mapping. Not " + ret,
   559                     where
   560                 );
   561             }
   562         }
   563         return ret;
   564     }
   565     
   566     private static String findBoxedType(String ret) {
   567         if (ret.equals("boolean")) {
   568             return Boolean.class.getName();
   569         }
   570         if (ret.equals("byte")) {
   571             return Byte.class.getName();
   572         }
   573         if (ret.equals("short")) {
   574             return Short.class.getName();
   575         }
   576         if (ret.equals("char")) {
   577             return Character.class.getName();
   578         }
   579         if (ret.equals("int")) {
   580             return Integer.class.getName();
   581         }
   582         if (ret.equals("long")) {
   583             return Long.class.getName();
   584         }
   585         if (ret.equals("float")) {
   586             return Float.class.getName();
   587         }
   588         if (ret.equals("double")) {
   589             return Double.class.getName();
   590         }
   591         return null;
   592     }
   593 
   594     private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
   595         StringBuilder sb = new StringBuilder();
   596         String sep = "";
   597         for (Property property : existingProps) {
   598             if (property.name().equals(propName)) {
   599                 return true;
   600             }
   601             sb.append(sep);
   602             sb.append('"');
   603             sb.append(property.name());
   604             sb.append('"');
   605             sep = ", ";
   606         }
   607         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
   608             propName + " is not one of known properties: " + sb
   609             , e
   610         );
   611         return false;
   612     }
   613 
   614     private static String findPkgName(Element e) {
   615         for (;;) {
   616             if (e.getKind() == ElementKind.PACKAGE) {
   617                 return ((PackageElement)e).getQualifiedName().toString();
   618             }
   619             e = e.getEnclosingElement();
   620         }
   621     }
   622 
   623     private boolean generateFunctions(
   624         Element clazz, StringWriter body, String className, 
   625         List<? extends Element> enclosedElements, List<String> functions
   626     ) {
   627         for (Element m : enclosedElements) {
   628             if (m.getKind() != ElementKind.METHOD) {
   629                 continue;
   630             }
   631             ExecutableElement e = (ExecutableElement)m;
   632             OnFunction onF = e.getAnnotation(OnFunction.class);
   633             if (onF == null) {
   634                 continue;
   635             }
   636             if (!e.getModifiers().contains(Modifier.STATIC)) {
   637                 processingEnv.getMessager().printMessage(
   638                     Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
   639                 );
   640                 return false;
   641             }
   642             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   643                 processingEnv.getMessager().printMessage(
   644                     Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
   645                 );
   646                 return false;
   647             }
   648             if (e.getReturnType().getKind() != TypeKind.VOID) {
   649                 processingEnv.getMessager().printMessage(
   650                     Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
   651                 );
   652                 return false;
   653             }
   654             String n = e.getSimpleName().toString();
   655             body.append("private void ").append(n).append("(Object data, Object ev) {\n");
   656             body.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
   657             body.append(wrapParams(e, null, className, "ev", "data"));
   658             body.append(");\n");
   659             body.append("}\n");
   660             
   661             functions.add(n);
   662             functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
   663         }
   664         return true;
   665     }
   666 
   667     private CharSequence wrapParams(
   668         ExecutableElement ee, String id, String className, String evName, String dataName
   669     ) {
   670         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   671         StringBuilder params = new StringBuilder();
   672         boolean first = true;
   673         for (VariableElement ve : ee.getParameters()) {
   674             if (!first) {
   675                 params.append(", ");
   676             }
   677             first = false;
   678             String toCall = null;
   679             if (ve.asType() == stringType) {
   680                 if (ve.getSimpleName().contentEquals("id")) {
   681                     params.append('"').append(id).append('"');
   682                     continue;
   683                 }
   684                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
   685             }
   686             if (ve.asType().getKind() == TypeKind.DOUBLE) {
   687                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
   688             }
   689             if (ve.asType().getKind() == TypeKind.INT) {
   690                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
   691             }
   692             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
   693                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
   694             }
   695 
   696             if (toCall != null) {
   697                 params.append(toCall);
   698                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
   699                     params.append(dataName);
   700                     params.append(", null");
   701                 } else {
   702                     params.append(evName);
   703                     params.append(", \"");
   704                     params.append(ve.getSimpleName().toString());
   705                     params.append("\"");
   706                 }
   707                 params.append(")");
   708                 continue;
   709             }
   710             String rn = fqn(ve.asType(), ee);
   711             int last = rn.lastIndexOf('.');
   712             if (last >= 0) {
   713                 rn = rn.substring(last + 1);
   714             }
   715             if (rn.equals(className)) {
   716                 params.append(className).append(".this");
   717                 continue;
   718             }
   719             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   720                 "@On method can only accept String named 'id' or " + className + " arguments",
   721                 ee
   722             );
   723         }
   724         return params;
   725     }
   726     
   727     private boolean isModel(TypeMirror tm) {
   728         final Element e = processingEnv.getTypeUtils().asElement(tm);
   729         if (e == null) {
   730             return false;
   731         }
   732         for (Element ch : e.getEnclosedElements()) {
   733             if (ch.getKind() == ElementKind.METHOD) {
   734                 ExecutableElement ee = (ExecutableElement)ch;
   735                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
   736                     return true;
   737                 }
   738             }
   739         }
   740         return models.values().contains(e.getSimpleName().toString());
   741     }
   742 
   743     private void writeStringArray(List<String> strings, Writer w) throws IOException {
   744         w.write("new String[] {\n");
   745         String sep = "";
   746         for (String n : strings) {
   747             w.write(sep);
   748             if (n == null) {
   749                 w.write("    null");
   750             } else {
   751                 w.write("    \"" + n + "\"");
   752             }
   753             sep = ",\n";
   754         }
   755         w.write("\n  }");
   756     }
   757     
   758     private void writeToString(Property[] props, Writer w) throws IOException {
   759         w.write("  public String toString() {\n");
   760         w.write("    StringBuilder sb = new StringBuilder();\n");
   761         w.write("    sb.append('{');\n");
   762         String sep = "";
   763         for (Property p : props) {
   764             w.write(sep);
   765             w.append("    sb.append(\"" + p.name() + ": \");\n");
   766             w.append("    sb.append(org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toJSON(prop_");
   767             w.append(p.name()).append("));\n");
   768             sep =    "    sb.append(',');\n";
   769         }
   770         w.write("    sb.append('}');\n");
   771         w.write("    return sb.toString();\n");
   772         w.write("  }\n");
   773     }
   774     private void writeClone(String className, Property[] props, Writer w) throws IOException {
   775         w.write("  public " + className + " clone() {\n");
   776         w.write("    " + className + " ret = new " + className + "();\n");
   777         for (Property p : props) {
   778             if (!p.array()) {
   779                 boolean isModel[] = { false };
   780                 boolean isEnum[] = { false };
   781                 checkType(p, isModel, isEnum);
   782                 if (!isModel[0]) {
   783                     w.write("    ret.prop_" + p.name() + " = prop_" + p.name() + ";\n");
   784                     continue;
   785                 }
   786             }
   787             w.write("    ret.prop_" + p.name() + " = prop_" + p.name() + ".clone();\n");
   788         }
   789         
   790         w.write("    return ret;\n");
   791         w.write("  }\n");
   792     }
   793 
   794     private String inPckName(Element e) {
   795         StringBuilder sb = new StringBuilder();
   796         while (e.getKind() != ElementKind.PACKAGE) {
   797             if (sb.length() == 0) {
   798                 sb.append(e.getSimpleName());
   799             } else {
   800                 sb.insert(0, '.');
   801                 sb.insert(0, e.getSimpleName());
   802             }
   803             e = e.getEnclosingElement();
   804         }
   805         return sb.toString();
   806     }
   807 
   808     private String fqn(TypeMirror pt, Element relative) {
   809         if (pt.getKind() == TypeKind.ERROR) {
   810             final Elements eu = processingEnv.getElementUtils();
   811             PackageElement pckg = eu.getPackageOf(relative);
   812             return pckg.getQualifiedName() + "." + pt.toString();
   813         }
   814         return pt.toString();
   815     }
   816 
   817     private String checkType(Property p, boolean[] isModel, boolean[] isEnum) {
   818         String ret;
   819         try {
   820             ret = p.type().getName();
   821         } catch (MirroredTypeException ex) {
   822             TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
   823             final Element e = processingEnv.getTypeUtils().asElement(tm);
   824             final Model m = e == null ? null : e.getAnnotation(Model.class);
   825             if (m != null) {
   826                 ret = findPkgName(e) + '.' + m.className();
   827                 isModel[0] = true;
   828                 models.put(e, m.className());
   829             } else {
   830                 ret = tm.toString();
   831             }
   832             TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
   833             enm = processingEnv.getTypeUtils().erasure(enm);
   834             isEnum[0] = processingEnv.getTypeUtils().isSubtype(tm, enm);
   835         }
   836         return ret;
   837     }
   838 }