javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 31 Mar 2013 13:26:27 +0200
branchmodel
changeset 911 fdf840690861
parent 909 e51a474fcf79
child 914 81dcd71877d5
permissions -rw-r--r--
Allow enums as model properties
     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("import org.apidesign.bck2brwsr.core.JavaScriptOnly;\n");
   132                 w.append("final class ").append(className).append(" {\n");
   133                 w.append("  private Object json;\n");
   134                 w.append("  private boolean locked;\n");
   135                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   136                 w.append(body.toString());
   137                 w.append("  private static Class<" + e.getSimpleName() + "> modelFor() { return null; }\n");
   138                 w.append("  public ").append(className).append("() {\n");
   139                 w.append("    ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(this, ");
   140                 writeStringArray(propsGetSet, w);
   141                 w.append(", ");
   142                 writeStringArray(Collections.<String>emptyList(), w);
   143                 w.append("    );\n");
   144                 w.append("  };\n");
   145                 w.append("}\n");
   146             } finally {
   147                 w.close();
   148             }
   149         } catch (IOException ex) {
   150             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   151             return false;
   152         }
   153         return ok;
   154     }
   155     
   156     private boolean processPage(Element e) {
   157         boolean ok = true;
   158         Page p = e.getAnnotation(Page.class);
   159         if (p == null) {
   160             return true;
   161         }
   162         String pkg = findPkgName(e);
   163 
   164         ProcessPage pp;
   165         try (InputStream is = openStream(pkg, p.xhtml())) {
   166             pp = ProcessPage.readPage(is);
   167             is.close();
   168         } catch (IOException iOException) {
   169             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
   170             ok = false;
   171             pp = null;
   172         }
   173         Writer w;
   174         String className = p.className();
   175         if (className.isEmpty()) {
   176             int indx = p.xhtml().indexOf('.');
   177             className = p.xhtml().substring(0, indx);
   178         }
   179         try {
   180             StringWriter body = new StringWriter();
   181             List<String> propsGetSet = new ArrayList<>();
   182             List<String> functions = new ArrayList<>();
   183             Map<String, Collection<String>> propsDeps = new HashMap<>();
   184             if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   185                 ok = false;
   186             }
   187             if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
   188                 ok = false;
   189             }
   190             if (!generateFunctions(e, body, className, e.getEnclosedElements(), functions)) {
   191                 ok = false;
   192             }
   193             
   194             FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
   195             w = new OutputStreamWriter(java.openOutputStream());
   196             try {
   197                 w.append("package " + pkg + ";\n");
   198                 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   199                 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   200                 w.append("final class ").append(className).append(" {\n");
   201                 w.append("  private boolean locked;\n");
   202                 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   203                     ok = false;
   204                 } else {
   205                     for (String id : pp.ids()) {
   206                         String tag = pp.tagNameForId(id);
   207                         String type = type(tag);
   208                         w.append("  ").append("public final ").
   209                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   210                             append(type).append("(\"").append(id).append("\");\n");
   211                     }
   212                 }
   213                 w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   214                 w.append(body.toString());
   215                 if (!propsGetSet.isEmpty()) {
   216                     w.write("public " + className + " applyBindings() {\n");
   217                     w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   218                     w.write(className + ".class, this, ");
   219                     writeStringArray(propsGetSet, w);
   220                     w.append(", ");
   221                     writeStringArray(functions, w);
   222                     w.write(");\n  return this;\n}\n");
   223 
   224                     w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   225                     w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   226                     w.write("}\n");
   227                 }
   228                 w.append("}\n");
   229             } finally {
   230                 w.close();
   231             }
   232         } catch (IOException ex) {
   233             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   234             return false;
   235         }
   236         return ok;
   237     }
   238 
   239     private static String type(String tag) {
   240         if (tag.equals("title")) {
   241             return "Title";
   242         }
   243         if (tag.equals("button")) {
   244             return "Button";
   245         }
   246         if (tag.equals("input")) {
   247             return "Input";
   248         }
   249         if (tag.equals("canvas")) {
   250             return "Canvas";
   251         }
   252         if (tag.equals("img")) {
   253             return "Image";
   254         }
   255         return "Element";
   256     }
   257 
   258     private static String cnstnt(String id) {
   259         return id.replace('.', '_').replace('-', '_');
   260     }
   261 
   262     private boolean initializeOnClick(
   263         String className, TypeElement type, Writer w, ProcessPage pp
   264     ) throws IOException {
   265         boolean ok = true;
   266         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   267         { //for (Element clazz : pe.getEnclosedElements()) {
   268           //  if (clazz.getKind() != ElementKind.CLASS) {
   269             //    continue;
   270            // }
   271             w.append("  public ").append(className).append("() {\n");
   272             StringBuilder dispatch = new StringBuilder();
   273             int dispatchCnt = 0;
   274             for (Element method : type.getEnclosedElements()) {
   275                 On oc = method.getAnnotation(On.class);
   276                 if (oc != null) {
   277                     for (String id : oc.id()) {
   278                         if (pp == null) {
   279                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
   280                             ok = false;
   281                             continue;
   282                         }
   283                         if (pp.tagNameForId(id) == null) {
   284                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   285                             ok = false;
   286                             continue;
   287                         }
   288                         ExecutableElement ee = (ExecutableElement)method;
   289                         CharSequence params = wrapParams(ee, id, className, "ev", null);
   290                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   291                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   292                             ok = false;
   293                             continue;
   294                         }
   295                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   296                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   297                             ok = false;
   298                             continue;
   299                         }
   300                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   301                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   302 
   303                         dispatch.
   304                             append("      case ").append(dispatchCnt).append(": ").
   305                             append(type.getSimpleName().toString()).
   306                             append('.').append(ee.getSimpleName()).append("(").
   307                             append(params).
   308                             append("); break;\n");
   309                         
   310                         dispatchCnt++;
   311                     }
   312                 }
   313             }
   314             w.append("  }\n");
   315             if (dispatchCnt > 0) {
   316                 w.append("class OnDispatch implements OnHandler {\n");
   317                 w.append("  private final int dispatch;\n");
   318                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   319                 w.append("  public void onEvent(Object ev) {\n");
   320                 w.append("    switch (dispatch) {\n");
   321                 w.append(dispatch);
   322                 w.append("    }\n");
   323                 w.append("  }\n");
   324                 w.append("}\n");
   325             }
   326             
   327 
   328         }
   329         return ok;
   330     }
   331 
   332     @Override
   333     public Iterable<? extends Completion> getCompletions(
   334         Element element, AnnotationMirror annotation, 
   335         ExecutableElement member, String userText
   336     ) {
   337         if (!userText.startsWith("\"")) {
   338             return Collections.emptyList();
   339         }
   340         
   341         Element cls = findClass(element);
   342         Page p = cls.getAnnotation(Page.class);
   343         String pkg = findPkgName(cls);
   344         ProcessPage pp;
   345         try {
   346             InputStream is = openStream(pkg, p.xhtml());
   347             pp = ProcessPage.readPage(is);
   348             is.close();
   349         } catch (IOException iOException) {
   350             return Collections.emptyList();
   351         }
   352         
   353         List<Completion> cc = new ArrayList<>();
   354         userText = userText.substring(1);
   355         for (String id : pp.ids()) {
   356             if (id.startsWith(userText)) {
   357                 cc.add(Completions.of("\"" + id + "\"", id));
   358             }
   359         }
   360         return cc;
   361     }
   362     
   363     private static Element findClass(Element e) {
   364         if (e == null) {
   365             return null;
   366         }
   367         Page p = e.getAnnotation(Page.class);
   368         if (p != null) {
   369             return e;
   370         }
   371         return e.getEnclosingElement();
   372     }
   373 
   374     private boolean generateProperties(
   375         Element where,
   376         Writer w, Property[] properties,
   377         Collection<String> props, Map<String,Collection<String>> deps
   378     ) throws IOException {
   379         boolean ok = true;
   380         for (Property p : properties) {
   381             final String tn;
   382             tn = typeName(where, p);
   383             String[] gs = toGetSet(p.name(), tn, p.array());
   384 
   385             if (p.array()) {
   386                 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
   387                     + p.name() + "\"");
   388                 final Collection<String> dependants = deps.get(p.name());
   389                 if (dependants != null) {
   390                     for (String depProp : dependants) {
   391                         w.write(", ");
   392                         w.write('\"');
   393                         w.write(depProp);
   394                         w.write('\"');
   395                     }
   396                 }
   397                 w.write(");\n");
   398                 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   399                 w.write("  if (locked) throw new IllegalStateException();\n");
   400                 w.write("  prop_" + p.name() + ".assign(ko);\n");
   401                 w.write("  return prop_" + p.name() + ";\n");
   402                 w.write("}\n");
   403             } else {
   404                 w.write("private " + tn + " prop_" + p.name() + ";\n");
   405                 w.write("public " + tn + " " + gs[0] + "() {\n");
   406                 w.write("  if (locked) throw new IllegalStateException();\n");
   407                 w.write("  return prop_" + p.name() + ";\n");
   408                 w.write("}\n");
   409                 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   410                 w.write("  if (locked) throw new IllegalStateException();\n");
   411                 w.write("  prop_" + p.name() + " = v;\n");
   412                 w.write("  if (ko != null) {\n");
   413                 w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   414                 final Collection<String> dependants = deps.get(p.name());
   415                 if (dependants != null) {
   416                     for (String depProp : dependants) {
   417                         w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   418                     }
   419                 }
   420                 w.write("  }\n");
   421                 w.write("}\n");
   422             }
   423             
   424             props.add(p.name());
   425             props.add(gs[2]);
   426             props.add(gs[3]);
   427             props.add(gs[0]);
   428         }
   429         return ok;
   430     }
   431 
   432     private boolean generateComputedProperties(
   433         Writer w, Property[] fixedProps,
   434         Collection<? extends Element> arr, Collection<String> props,
   435         Map<String,Collection<String>> deps
   436     ) throws IOException {
   437         boolean ok = true;
   438         for (Element e : arr) {
   439             if (e.getKind() != ElementKind.METHOD) {
   440                 continue;
   441             }
   442             if (e.getAnnotation(ComputedProperty.class) == null) {
   443                 continue;
   444             }
   445             ExecutableElement ee = (ExecutableElement)e;
   446             final TypeMirror rt = ee.getReturnType();
   447             final Types tu = processingEnv.getTypeUtils();
   448             TypeMirror ert = tu.erasure(rt);
   449             String tn = ert.toString();
   450             boolean array = false;
   451             if (tn.equals("java.util.List")) {
   452                 array = true;
   453             }
   454             
   455             final String sn = ee.getSimpleName().toString();
   456             String[] gs = toGetSet(sn, tn, array);
   457             
   458             w.write("public " + tn + " " + gs[0] + "() {\n");
   459             w.write("  if (locked) throw new IllegalStateException();\n");
   460             int arg = 0;
   461             for (VariableElement pe : ee.getParameters()) {
   462                 final String dn = pe.getSimpleName().toString();
   463                 
   464                 if (!verifyPropName(pe, dn, fixedProps)) {
   465                     ok = false;
   466                 }
   467                 
   468                 final String dt = pe.asType().toString();
   469                 String[] call = toGetSet(dn, dt, false);
   470                 w.write("  " + dt + " arg" + (++arg) + " = ");
   471                 w.write(call[0] + "();\n");
   472                 
   473                 Collection<String> depends = deps.get(dn);
   474                 if (depends == null) {
   475                     depends = new LinkedHashSet<>();
   476                     deps.put(dn, depends);
   477                 }
   478                 depends.add(sn);
   479             }
   480             w.write("  try {\n");
   481             w.write("    locked = true;\n");
   482             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   483             String sep = "";
   484             for (int i = 1; i <= arg; i++) {
   485                 w.write(sep);
   486                 w.write("arg" + i);
   487                 sep = ", ";
   488             }
   489             w.write(");\n");
   490             w.write("  } finally {\n");
   491             w.write("    locked = false;\n");
   492             w.write("  }\n");
   493             w.write("}\n");
   494 
   495             props.add(e.getSimpleName().toString());
   496             props.add(gs[2]);
   497             props.add(null);
   498             props.add(gs[0]);
   499         }
   500         
   501         return ok;
   502     }
   503 
   504     private static String[] toGetSet(String name, String type, boolean array) {
   505         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   506         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   507         if ("int".equals(type)) {
   508             bck2brwsrType = "I";
   509         }
   510         if ("double".equals(type)) {
   511             bck2brwsrType = "D";
   512         }
   513         String pref = "get";
   514         if ("boolean".equals(type)) {
   515             pref = "is";
   516             bck2brwsrType = "Z";
   517         }
   518         final String nu = n.replace('.', '_');
   519         if (array) {
   520             return new String[] { 
   521                 "get" + n,
   522                 null,
   523                 "get" + nu + "__Ljava_util_List_2",
   524                 null
   525             };
   526         }
   527         return new String[]{
   528             pref + n, 
   529             "set" + n, 
   530             pref + nu + "__" + bck2brwsrType,
   531             "set" + nu + "__V" + bck2brwsrType
   532         };
   533     }
   534 
   535     private String typeName(Element where, Property p) {
   536         String ret;
   537         boolean isModel = false;
   538         boolean isEnum = false;
   539         try {
   540             ret = p.type().getName();
   541         } catch (MirroredTypeException ex) {
   542             TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
   543             final Element e = processingEnv.getTypeUtils().asElement(tm);
   544             final Model m = e == null ? null : e.getAnnotation(Model.class);
   545             if (m != null) {
   546                 ret = findPkgName(e) + '.' + m.className();
   547                 isModel = true;
   548                 models.put(e, m.className());
   549             } else {
   550                 ret = tm.toString();
   551             }
   552             TypeMirror enm = processingEnv.getElementUtils().getTypeElement("java.lang.Enum").asType();
   553             enm = processingEnv.getTypeUtils().erasure(enm);
   554             isEnum = processingEnv.getTypeUtils().isSubtype(tm, enm);
   555         }
   556         if (p.array()) {
   557             String bt = findBoxedType(ret);
   558             if (bt != null) {
   559                 return bt;
   560             }
   561         }
   562         if (!isModel && !"java.lang.String".equals(ret) && !isEnum) {
   563             String bt = findBoxedType(ret);
   564             if (bt == null) {
   565                 processingEnv.getMessager().printMessage(
   566                     Diagnostic.Kind.ERROR, 
   567                     "Only primitive types supported in the mapping. Not " + ret,
   568                     where
   569                 );
   570             }
   571         }
   572         return ret;
   573     }
   574     
   575     private static String findBoxedType(String ret) {
   576         if (ret.equals("boolean")) {
   577             return Boolean.class.getName();
   578         }
   579         if (ret.equals("byte")) {
   580             return Byte.class.getName();
   581         }
   582         if (ret.equals("short")) {
   583             return Short.class.getName();
   584         }
   585         if (ret.equals("char")) {
   586             return Character.class.getName();
   587         }
   588         if (ret.equals("int")) {
   589             return Integer.class.getName();
   590         }
   591         if (ret.equals("long")) {
   592             return Long.class.getName();
   593         }
   594         if (ret.equals("float")) {
   595             return Float.class.getName();
   596         }
   597         if (ret.equals("double")) {
   598             return Double.class.getName();
   599         }
   600         return null;
   601     }
   602 
   603     private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
   604         StringBuilder sb = new StringBuilder();
   605         String sep = "";
   606         for (Property property : existingProps) {
   607             if (property.name().equals(propName)) {
   608                 return true;
   609             }
   610             sb.append(sep);
   611             sb.append('"');
   612             sb.append(property.name());
   613             sb.append('"');
   614             sep = ", ";
   615         }
   616         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
   617             propName + " is not one of known properties: " + sb
   618             , e
   619         );
   620         return false;
   621     }
   622 
   623     private static String findPkgName(Element e) {
   624         for (;;) {
   625             if (e.getKind() == ElementKind.PACKAGE) {
   626                 return ((PackageElement)e).getQualifiedName().toString();
   627             }
   628             e = e.getEnclosingElement();
   629         }
   630     }
   631 
   632     private boolean generateFunctions(
   633         Element clazz, StringWriter body, String className, 
   634         List<? extends Element> enclosedElements, List<String> functions
   635     ) {
   636         for (Element m : enclosedElements) {
   637             if (m.getKind() != ElementKind.METHOD) {
   638                 continue;
   639             }
   640             ExecutableElement e = (ExecutableElement)m;
   641             OnFunction onF = e.getAnnotation(OnFunction.class);
   642             if (onF == null) {
   643                 continue;
   644             }
   645             if (!e.getModifiers().contains(Modifier.STATIC)) {
   646                 processingEnv.getMessager().printMessage(
   647                     Diagnostic.Kind.ERROR, "@OnFunction method needs to be static", e
   648                 );
   649                 return false;
   650             }
   651             if (e.getModifiers().contains(Modifier.PRIVATE)) {
   652                 processingEnv.getMessager().printMessage(
   653                     Diagnostic.Kind.ERROR, "@OnFunction method cannot be private", e
   654                 );
   655                 return false;
   656             }
   657             if (e.getReturnType().getKind() != TypeKind.VOID) {
   658                 processingEnv.getMessager().printMessage(
   659                     Diagnostic.Kind.ERROR, "@OnFunction method should return void", e
   660                 );
   661                 return false;
   662             }
   663             String n = e.getSimpleName().toString();
   664             body.append("void ").append(n).append("(Object data, Object ev) {\n");
   665             body.append("  ").append(clazz.getSimpleName()).append(".").append(n).append("(");
   666             body.append(wrapParams(e, null, className, "ev", "data"));
   667             body.append(");\n");
   668             body.append("}\n");
   669             
   670             functions.add(n);
   671             functions.add(n + "__VLjava_lang_Object_2Ljava_lang_Object_2");
   672         }
   673         return true;
   674     }
   675 
   676     private CharSequence wrapParams(
   677         ExecutableElement ee, String id, String className, String evName, String dataName
   678     ) {
   679         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   680         StringBuilder params = new StringBuilder();
   681         boolean first = true;
   682         for (VariableElement ve : ee.getParameters()) {
   683             if (!first) {
   684                 params.append(", ");
   685             }
   686             first = false;
   687             String toCall = null;
   688             if (ve.asType() == stringType) {
   689                 if (ve.getSimpleName().contentEquals("id")) {
   690                     params.append('"').append(id).append('"');
   691                     continue;
   692                 }
   693                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(";
   694             }
   695             if (ve.asType().getKind() == TypeKind.DOUBLE) {
   696                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(";
   697             }
   698             if (ve.asType().getKind() == TypeKind.INT) {
   699                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toInt(";
   700             }
   701             if (dataName != null && ve.getSimpleName().contentEquals(dataName) && isModel(ve.asType())) {
   702                 toCall = "org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toModel(" + ve.asType() + ".class, ";
   703             }
   704 
   705             if (toCall != null) {
   706                 params.append(toCall);
   707                 if (dataName != null && ve.getSimpleName().contentEquals(dataName)) {
   708                     params.append(dataName);
   709                     params.append(", null");
   710                 } else {
   711                     params.append(evName);
   712                     params.append(", \"");
   713                     params.append(ve.getSimpleName().toString());
   714                     params.append("\"");
   715                 }
   716                 params.append(")");
   717                 continue;
   718             }
   719             String rn = ve.asType().toString();
   720             int last = rn.lastIndexOf('.');
   721             if (last >= 0) {
   722                 rn = rn.substring(last + 1);
   723             }
   724             if (rn.equals(className)) {
   725                 params.append(className).append(".this");
   726                 continue;
   727             }
   728             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   729                 "@On method can only accept String named 'id' or " + className + " arguments",
   730                 ee
   731             );
   732         }
   733         return params;
   734     }
   735     
   736     private boolean isModel(TypeMirror tm) {
   737         final Element e = processingEnv.getTypeUtils().asElement(tm);
   738         if (e == null) {
   739             return false;
   740         }
   741         for (Element ch : e.getEnclosedElements()) {
   742             if (ch.getKind() == ElementKind.METHOD) {
   743                 ExecutableElement ee = (ExecutableElement)ch;
   744                 if (ee.getParameters().isEmpty() && ee.getSimpleName().contentEquals("modelFor")) {
   745                     return true;
   746                 }
   747             }
   748         }
   749         return models.values().contains(e.getSimpleName().toString());
   750     }
   751 
   752     private void writeStringArray(List<String> strings, Writer w) throws IOException {
   753         w.write("new String[] {\n");
   754         String sep = "";
   755         for (String n : strings) {
   756             w.write(sep);
   757             if (n == null) {
   758                 w.write("    null");
   759             } else {
   760                 w.write("    \"" + n + "\"");
   761             }
   762             sep = ",\n";
   763         }
   764         w.write("\n  }");
   765     }
   766 }