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