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