javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 31 Mar 2013 05:43:38 +0200
branchmodel
changeset 907 5dc21ce7269d
parent 906 22358b42ec2a
child 908 3e023bea2da4
permissions -rw-r--r--
Guard against NPE
     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.Types;
    52 import javax.tools.Diagnostic;
    53 import javax.tools.FileObject;
    54 import javax.tools.StandardLocation;
    55 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    56 import org.apidesign.bck2brwsr.htmlpage.api.Model;
    57 import org.apidesign.bck2brwsr.htmlpage.api.On;
    58 import org.apidesign.bck2brwsr.htmlpage.api.OnFunction;
    59 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    60 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    61 import org.openide.util.lookup.ServiceProvider;
    62 
    63 /** Annotation processor to process an XHTML page and generate appropriate 
    64  * "id" file.
    65  *
    66  * @author Jaroslav Tulach <jtulach@netbeans.org>
    67  */
    68 @ServiceProvider(service=Processor.class)
    69 @SupportedAnnotationTypes({
    70     "org.apidesign.bck2brwsr.htmlpage.api.Model",
    71     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    72     "org.apidesign.bck2brwsr.htmlpage.api.OnFunction",
    73     "org.apidesign.bck2brwsr.htmlpage.api.On"
    74 })
    75 public final class PageProcessor extends AbstractProcessor {
    76     private final Map<Element,String> models = new WeakHashMap<>();
    77     @Override
    78     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    79         boolean ok = true;
    80         for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
    81             if (!processModel(e)) {
    82                 ok = false;
    83             }
    84         }
    85         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    86             if (!processPage(e)) {
    87                 ok = false;
    88             }
    89         }
    90         if (roundEnv.processingOver()) {
    91             models.clear();
    92         }
    93         return ok;
    94     }
    95 
    96     private InputStream openStream(String pkg, String name) throws IOException {
    97         try {
    98             FileObject fo = processingEnv.getFiler().getResource(
    99                 StandardLocation.SOURCE_PATH, pkg, name);
   100             return fo.openInputStream();
   101         } catch (IOException ex) {
   102             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   103         }
   104     }
   105     
   106     private boolean processModel(Element e) {
   107         boolean ok = true;
   108         Model m = e.getAnnotation(Model.class);
   109         if (m == null) {
   110             return true;
   111         }
   112         String pkg = findPkgName(e);
   113         Writer w;
   114         String className = m.className();
   115         try {
   116             StringWriter body = new StringWriter();
   117             List<String> propsGetSet = new ArrayList<>();
   118             Map<String, Collection<String>> propsDeps = new HashMap<>();
   119             if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   120                 ok = false;
   121             }
   122             if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
   123                 ok = false;
   124             }
   125             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   126             w = new OutputStreamWriter(java.openOutputStream());
   127             try {
   128                 w.append("package " + pkg + ";\n");
   129                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   130                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   131                 w.append("final class ").append(className).append(" {\n");
   132                 w.append("  private Object json;\n");
   133                 w.append("  private boolean locked;\n");
   134                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   135                 w.append(body.toString());
   136                 w.append("  private static Class<" + e.getSimpleName() + "> modelFor() { return null; }\n");
   137                 w.append("}\n");
   138             } finally {
   139                 w.close();
   140             }
   141         } catch (IOException ex) {
   142             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   143             return false;
   144         }
   145         return ok;
   146     }
   147     
   148     private boolean processPage(Element e) {
   149         boolean ok = true;
   150         Page p = e.getAnnotation(Page.class);
   151         if (p == null) {
   152             return true;
   153         }
   154         String pkg = findPkgName(e);
   155 
   156         ProcessPage pp;
   157         try (InputStream is = openStream(pkg, p.xhtml())) {
   158             pp = ProcessPage.readPage(is);
   159             is.close();
   160         } catch (IOException iOException) {
   161             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
   162             ok = false;
   163             pp = null;
   164         }
   165         Writer w;
   166         String className = p.className();
   167         if (className.isEmpty()) {
   168             int indx = p.xhtml().indexOf('.');
   169             className = p.xhtml().substring(0, indx);
   170         }
   171         try {
   172             StringWriter body = new StringWriter();
   173             List<String> propsGetSet = new ArrayList<>();
   174             List<String> functions = new ArrayList<>();
   175             Map<String, Collection<String>> propsDeps = new HashMap<>();
   176             if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   177                 ok = false;
   178             }
   179             if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
   180                 ok = false;
   181             }
   182             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   183                 ok = false;
   184             }
   185             
   186             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   187             w = new OutputStreamWriter(java.openOutputStream());
   188             try {
   189                 w.append("package " + pkg + ";\n");
   190                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   191                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   192                 w.append("final class ").append(className).append(" {\n");
   193                 w.append("  private boolean locked;\n");
   194                 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   195                     ok = false;
   196                 } else {
   197                     for (String id : pp.ids()) {
   198                         String tag = pp.tagNameForId(id);
   199                         String type = type(tag);
   200                         w.append("  ").append("public final ").
   201                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   202                             append(type).append("(\"").append(id).append("\");\n");
   203                     }
   204                 }
   205                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   206                 w.append(body.toString());
   207                 if (!propsGetSet.isEmpty()) {
   208                     w.write("public " + className + " applyBindings() {\n");
   209                     w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   210                     w.write(className + ".class, this, ");
   211                     w.write("new String[] {\n");
   212                     String sep = "";
   213                     for (String n : propsGetSet) {
   214                         w.write(sep);
   215                         if (n == null) {
   216                             w.write("    null");
   217                         } else {
   218                             w.write("    \"" + n + "\"");
   219                         }
   220                         sep = ",\n";
   221                     }
   222                     w.write("\n  }, new String[] {\n");
   223                     sep = "";
   224                     for (String n : functions) {
   225                         w.write(sep);
   226                         w.write(n);
   227                         sep = ",\n";
   228                     }
   229                     w.write("\n  });\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 = ert.toString();
   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 = pe.asType().toString();
   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         try {
   546             ret = p.type().getName();
   547         } catch (MirroredTypeException ex) {
   548             TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
   549             final Element e = processingEnv.getTypeUtils().asElement(tm);
   550             final Model m = e == null ? null : e.getAnnotation(Model.class);
   551             if (m != null) {
   552                 ret = findPkgName(e) + '.' + m.className();
   553                 isModel = true;
   554                 models.put(e, m.className());
   555             } else {
   556                 ret = tm.toString();
   557             }
   558         }
   559         if (p.array()) {
   560             String bt = findBoxedType(ret);
   561             if (bt != null) {
   562                 return bt;
   563             }
   564         }
   565         if (!isModel && !"java.lang.String".equals(ret)) {
   566             String bt = findBoxedType(ret);
   567             if (bt == null) {
   568                 processingEnv.getMessager().printMessage(
   569                     Diagnostic.Kind.ERROR, 
   570                     "Only primitive types supported in the mapping. Not " + ret,
   571                     where
   572                 );
   573             }
   574         }
   575         return ret;
   576     }
   577     
   578     private static String findBoxedType(String ret) {
   579         if (ret.equals("boolean")) {
   580             return Boolean.class.getName();
   581         }
   582         if (ret.equals("byte")) {
   583             return Byte.class.getName();
   584         }
   585         if (ret.equals("short")) {
   586             return Short.class.getName();
   587         }
   588         if (ret.equals("char")) {
   589             return Character.class.getName();
   590         }
   591         if (ret.equals("int")) {
   592             return Integer.class.getName();
   593         }
   594         if (ret.equals("long")) {
   595             return Long.class.getName();
   596         }
   597         if (ret.equals("float")) {
   598             return Float.class.getName();
   599         }
   600         if (ret.equals("double")) {
   601             return Double.class.getName();
   602         }
   603         return null;
   604     }
   605 
   606     private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
   607         StringBuilder sb = new StringBuilder();
   608         String sep = "";
   609         for (Property property : existingProps) {
   610             if (property.name().equals(propName)) {
   611                 return true;
   612             }
   613             sb.append(sep);
   614             sb.append('"');
   615             sb.append(property.name());
   616             sb.append('"');
   617             sep = ", ";
   618         }
   619         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
   620             propName + " is not one of known properties: " + sb
   621             , e
   622         );
   623         return false;
   624     }
   625 
   626     private static String findPkgName(Element e) {
   627         for (;;) {
   628             if (e.getKind() == ElementKind.PACKAGE) {
   629                 return ((PackageElement)e).getQualifiedName().toString();
   630             }
   631             e = e.getEnclosingElement();
   632         }
   633     }
   634 
   635     private boolean generateFunctions(
   636         Element clazz, StringWriter body, String className, 
   637         List<? extends Element> enclosedElements, List<String> functions
   638     ) {
   639         for (Element m : enclosedElements) {
   640             if (m.getKind() != ElementKind.METHOD) {
   641                 continue;
   642             }
   643             ExecutableElement e = (ExecutableElement)m;
   644             OnFunction onF = e.getAnnotation(OnFunction.class);
   645             if (onF == null) {
   646                 continue;
   647             }
   648             if (!e.getModifiers().contains(Modifier.STATIC)) {
   649                 processingEnv.getMessager().printMessage(
   650                     Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
   651                 );
   652                 return false;
   653             }
   654             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   655                 processingEnv.getMessager().printMessage(
   656                     Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
   657                 );
   658                 return false;
   659             }
   660             if (e.getReturnType().getKind() != TypeKind.VOID) {
   661                 processingEnv.getMessager().printMessage(
   662                     Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
   663                 );
   664                 return false;
   665             }
   666             String n = e.getSimpleName().toString();
   667             body.append("void ").append(n).append("(Object data, Object ev) {\n");
   668             body.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
   669             body.append(wrapParams(e, null, className, "ev", "data"));
   670             body.append(");\n");
   671             body.append("}\n");
   672             
   673             functions.add('\"' + n + '\"');
   674             functions.add('\"' + n + "__VLjava_lang_Object_2Ljava_lang_Object_2" + '\"');
   675         }
   676         return true;
   677     }
   678 
   679     private CharSequence wrapParams(
   680         ExecutableElement ee, String id, String className, String evName, String dataName
   681     ) {
   682         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   683         StringBuilder params = new StringBuilder();
   684         boolean first = true;
   685         for (VariableElement ve : ee.getParameters()) {
   686             if (!first) {
   687                 params.append(", ");
   688             }
   689             first = false;
   690             String toCall = null;
   691             if (ve.asType() == stringType) {
   692                 if (ve.getSimpleName().contentEquals("id")) {
   693                     params.append('"').append(id).append('"');
   694                     continue;
   695                 }
   696                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
   697             }
   698             if (ve.asType().getKind() == TypeKind.DOUBLE) {
   699                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
   700             }
   701             if (ve.asType().getKind() == TypeKind.INT) {
   702                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
   703             }
   704             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
   705                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
   706             }
   707 
   708             if (toCall != null) {
   709                 params.append(toCall);
   710                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
   711                     params.append(dataName);
   712                     params.append(", null");
   713                 } else {
   714                     params.append(evName);
   715                     params.append(", \"");
   716                     params.append(ve.getSimpleName().toString());
   717                     params.append("\"");
   718                 }
   719                 params.append(")");
   720                 continue;
   721             }
   722             String rn = ve.asType().toString();
   723             int last = rn.lastIndexOf('.');
   724             if (last >= 0) {
   725                 rn = rn.substring(last + 1);
   726             }
   727             if (rn.equals(className)) {
   728                 params.append(className).append(".this");
   729                 continue;
   730             }
   731             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   732                 "@On method can only accept String named 'id' or " + className + " arguments",
   733                 ee
   734             );
   735         }
   736         return params;
   737     }
   738     
   739     private boolean isModel(TypeMirror tm) {
   740         final Element e = processingEnv.getTypeUtils().asElement(tm);
   741         if (e == null) {
   742             return false;
   743         }
   744         for (Element ch : e.getEnclosedElements()) {
   745             if (ch.getKind() == ElementKind.METHOD) {
   746                 ExecutableElement ee = (ExecutableElement)ch;
   747                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
   748                     return true;
   749                 }
   750             }
   751         }
   752         return models.values().contains(e.getSimpleName().toString());
   753     }
   754 }