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