javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 20 Feb 2013 18:14:59 +0100
branchmodel
changeset 769 0c0fe97fe0c7
parent 768 e320d8156140
child 770 26513bd377b9
permissions -rw-r--r--
Processor allows only primitive types and String as its values
     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.Writer;
    24 import java.util.ArrayList;
    25 import java.util.Collection;
    26 import java.util.Collections;
    27 import java.util.HashMap;
    28 import java.util.LinkedHashSet;
    29 import java.util.List;
    30 import java.util.Locale;
    31 import java.util.Map;
    32 import java.util.Set;
    33 import javax.annotation.processing.AbstractProcessor;
    34 import javax.annotation.processing.Completion;
    35 import javax.annotation.processing.Completions;
    36 import javax.annotation.processing.Processor;
    37 import javax.annotation.processing.RoundEnvironment;
    38 import javax.annotation.processing.SupportedAnnotationTypes;
    39 import javax.lang.model.element.AnnotationMirror;
    40 import javax.lang.model.element.Element;
    41 import javax.lang.model.element.ElementKind;
    42 import javax.lang.model.element.ExecutableElement;
    43 import javax.lang.model.element.Modifier;
    44 import javax.lang.model.element.PackageElement;
    45 import javax.lang.model.element.TypeElement;
    46 import javax.lang.model.element.VariableElement;
    47 import javax.lang.model.type.MirroredTypeException;
    48 import javax.lang.model.type.TypeMirror;
    49 import javax.lang.model.util.Types;
    50 import javax.tools.Diagnostic;
    51 import javax.tools.FileObject;
    52 import javax.tools.StandardLocation;
    53 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    54 import org.apidesign.bck2brwsr.htmlpage.api.On;
    55 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    56 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    57 import org.openide.util.lookup.ServiceProvider;
    58 
    59 /** Annotation processor to process an XHTML page and generate appropriate 
    60  * "id" file.
    61  *
    62  * @author Jaroslav Tulach <jtulach@netbeans.org>
    63  */
    64 @ServiceProvider(service=Processor.class)
    65 @SupportedAnnotationTypes({
    66     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    67     "org.apidesign.bck2brwsr.htmlpage.api.On"
    68 })
    69 public final class PageProcessor extends AbstractProcessor {
    70     @Override
    71     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    72         boolean ok = true;
    73         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    74             Page p = e.getAnnotation(Page.class);
    75             if (p == null) {
    76                 continue;
    77             }
    78             PackageElement pe = (PackageElement)e.getEnclosingElement();
    79             String pkg = pe.getQualifiedName().toString();
    80             
    81             ProcessPage pp;
    82             try {
    83                 InputStream is = openStream(pkg, p.xhtml());
    84                 pp = ProcessPage.readPage(is);
    85                 is.close();
    86             } catch (IOException iOException) {
    87                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    88                 ok = false;
    89                 pp = null;
    90             }
    91             Writer w;
    92             String className = p.className();
    93             if (className.isEmpty()) {
    94                 int indx = p.xhtml().indexOf('.');
    95                 className = p.xhtml().substring(0, indx);
    96             }
    97             try {
    98                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    99                 w = new OutputStreamWriter(java.openOutputStream());
   100                 try {
   101                     w.append("package " + pkg + ";\n");
   102                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   103                     w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
   104                     w.append("final class ").append(className).append(" {\n");
   105                     w.append("  private boolean locked;\n");
   106                     if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   107                         ok = false;
   108                     } else {
   109                         for (String id : pp.ids()) {
   110                             String tag = pp.tagNameForId(id);
   111                             String type = type(tag);
   112                             w.append("  ").append("public final ").
   113                                 append(type).append(' ').append(cnstnt(id)).append(" = new ").
   114                                 append(type).append("(\"").append(id).append("\");\n");
   115                         }
   116                     }
   117                     List<String> propsGetSet = new ArrayList<String>();
   118                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   119                     if (!generateComputedProperties(w, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
   120                         ok = false;
   121                     }
   122                     generateProperties(w, p.properties(), propsGetSet, propsDeps);
   123                     w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   124                     if (!propsGetSet.isEmpty()) {
   125                         w.write("public " + className + " applyBindings() {\n");
   126                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   127                         w.write(className + ".class, this, ");
   128                         w.write("new String[] {\n");
   129                         String sep = "";
   130                         for (String n : propsGetSet) {
   131                             w.write(sep);
   132                             if (n == null) {
   133                                 w.write("    null");
   134                             } else {
   135                                 w.write("    \"" + n + "\"");
   136                             }
   137                             sep = ",\n";
   138                         }
   139                         w.write("\n  });\n  return this;\n}\n");
   140                         
   141                         w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   142                         w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   143                         w.write("}\n");
   144                     }
   145                     w.append("}\n");
   146                 } finally {
   147                     w.close();
   148                 }
   149             } catch (IOException ex) {
   150                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   151                 return false;
   152             }
   153         }
   154         return ok;
   155     }
   156 
   157     private InputStream openStream(String pkg, String name) throws IOException {
   158         try {
   159             FileObject fo = processingEnv.getFiler().getResource(
   160                 StandardLocation.SOURCE_PATH, pkg, name);
   161             return fo.openInputStream();
   162         } catch (IOException ex) {
   163             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   164         }
   165     }
   166 
   167     private static String type(String tag) {
   168         if (tag.equals("title")) {
   169             return "Title";
   170         }
   171         if (tag.equals("button")) {
   172             return "Button";
   173         }
   174         if (tag.equals("input")) {
   175             return "Input";
   176         }
   177         if (tag.equals("canvas")) {
   178             return "Canvas";
   179         }
   180         if (tag.equals("img")) {
   181             return "Image";
   182         }
   183         return "Element";
   184     }
   185 
   186     private static String cnstnt(String id) {
   187         return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
   188     }
   189 
   190     private boolean initializeOnClick(
   191         String className, TypeElement type, Writer w, ProcessPage pp
   192     ) throws IOException {
   193         boolean ok = true;
   194         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   195         { //for (Element clazz : pe.getEnclosedElements()) {
   196           //  if (clazz.getKind() != ElementKind.CLASS) {
   197             //    continue;
   198            // }
   199             w.append("  public ").append(className).append("() {\n");
   200             StringBuilder dispatch = new StringBuilder();
   201             int dispatchCnt = 0;
   202             for (Element method : type.getEnclosedElements()) {
   203                 On oc = method.getAnnotation(On.class);
   204                 if (oc != null) {
   205                     for (String id : oc.id()) {
   206                         if (pp == null) {
   207                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
   208                             ok = false;
   209                             continue;
   210                         }
   211                         if (pp.tagNameForId(id) == null) {
   212                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   213                             ok = false;
   214                             continue;
   215                         }
   216                         ExecutableElement ee = (ExecutableElement)method;
   217                         StringBuilder params = new StringBuilder();
   218                         {
   219                             boolean first = true;
   220                             for (VariableElement ve : ee.getParameters()) {
   221                                 if (!first) {
   222                                     params.append(", ");
   223                                 }
   224                                 first = false;
   225                                 if (ve.asType() == stringType) {
   226                                     params.append('"').append(id).append('"');
   227                                     continue;
   228                                 }
   229                                 String rn = ve.asType().toString();
   230                                 int last = rn.lastIndexOf('.');
   231                                 if (last >= 0) {
   232                                     rn = rn.substring(last + 1);
   233                                 }
   234                                 if (rn.equals(className)) {
   235                                     params.append(className).append(".this");
   236                                     continue;
   237                                 }
   238                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   239                                     "@On method can only accept String or " + className + " arguments",
   240                                     ee
   241                                 );
   242                                 return false;
   243                             }
   244                         }
   245                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   246                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   247                             ok = false;
   248                             continue;
   249                         }
   250                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   251                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   252                             ok = false;
   253                             continue;
   254                         }
   255                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   256                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   257 
   258                         dispatch.
   259                             append("      case ").append(dispatchCnt).append(": ").
   260                             append(type.getSimpleName().toString()).
   261                             append('.').append(ee.getSimpleName()).append("(").
   262                             append(params).
   263                             append("); break;\n");
   264                         
   265                         dispatchCnt++;
   266                     }
   267                 }
   268             }
   269             w.append("  }\n");
   270             if (dispatchCnt > 0) {
   271                 w.append("class OnDispatch implements Runnable {\n");
   272                 w.append("  private final int dispatch;\n");
   273                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   274                 w.append("  public void run() {\n");
   275                 w.append("    switch (dispatch) {\n");
   276                 w.append(dispatch);
   277                 w.append("    }\n");
   278                 w.append("  }\n");
   279                 w.append("}\n");
   280             }
   281             
   282 
   283         }
   284         return ok;
   285     }
   286 
   287     @Override
   288     public Iterable<? extends Completion> getCompletions(
   289         Element element, AnnotationMirror annotation, 
   290         ExecutableElement member, String userText
   291     ) {
   292         if (!userText.startsWith("\"")) {
   293             return Collections.emptyList();
   294         }
   295         
   296         Element cls = findClass(element);
   297         Page p = cls.getAnnotation(Page.class);
   298         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   299         String pkg = pe.getQualifiedName().toString();
   300         ProcessPage pp;
   301         try {
   302             InputStream is = openStream(pkg, p.xhtml());
   303             pp = ProcessPage.readPage(is);
   304             is.close();
   305         } catch (IOException iOException) {
   306             return Collections.emptyList();
   307         }
   308         
   309         List<Completion> cc = new ArrayList<Completion>();
   310         userText = userText.substring(1);
   311         for (String id : pp.ids()) {
   312             if (id.startsWith(userText)) {
   313                 cc.add(Completions.of("\"" + id + "\"", id));
   314             }
   315         }
   316         return cc;
   317     }
   318     
   319     private static Element findClass(Element e) {
   320         if (e == null) {
   321             return null;
   322         }
   323         Page p = e.getAnnotation(Page.class);
   324         if (p != null) {
   325             return e;
   326         }
   327         return e.getEnclosingElement();
   328     }
   329 
   330     private void generateProperties(
   331         Writer w, Property[] properties, Collection<String> props,
   332         Map<String,Collection<String>> deps
   333     ) throws IOException {
   334         for (Property p : properties) {
   335             final String tn = typeName(p);
   336             String[] gs = toGetSet(p.name(), tn, p.array());
   337 
   338             if (p.array()) {
   339                 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
   340                     + p.name() + "\"");
   341                 final Collection<String> dependants = deps.get(p.name());
   342                 if (dependants != null) {
   343                     for (String depProp : dependants) {
   344                         w.write(", ");
   345                         w.write('\"');
   346                         w.write(depProp);
   347                         w.write('\"');
   348                     }
   349                 }
   350                 w.write(");\n");
   351                 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
   352                 w.write("  if (locked) throw new IllegalStateException();\n");
   353                 w.write("  prop_" + p.name() + ".assign(ko);\n");
   354                 w.write("  return prop_" + p.name() + ";\n");
   355                 w.write("}\n");
   356                 w.write("private Object[] " + gs[0] + "ToArray() {\n");
   357                 w.write("  return " + gs[0] + "().toArray(new Object[0]);\n");
   358                 w.write("}\n");
   359             } else {
   360                 w.write("private " + tn + " prop_" + p.name() + ";\n");
   361                 w.write("public " + tn + " " + gs[0] + "() {\n");
   362                 w.write("  if (locked) throw new IllegalStateException();\n");
   363                 w.write("  return prop_" + p.name() + ";\n");
   364                 w.write("}\n");
   365                 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   366                 w.write("  if (locked) throw new IllegalStateException();\n");
   367                 w.write("  prop_" + p.name() + " = v;\n");
   368                 w.write("  if (ko != null) {\n");
   369                 w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   370                 final Collection<String> dependants = deps.get(p.name());
   371                 if (dependants != null) {
   372                     for (String depProp : dependants) {
   373                         w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   374                     }
   375                 }
   376                 w.write("  }\n");
   377                 w.write("}\n");
   378             }
   379             
   380             props.add(p.name());
   381             props.add(gs[2]);
   382             props.add(gs[3]);
   383             props.add(gs[0]);
   384         }
   385     }
   386 
   387     private boolean generateComputedProperties(
   388         Writer w, Property[] fixedProps,
   389         Collection<? extends Element> arr, Collection<String> props,
   390         Map<String,Collection<String>> deps
   391     ) throws IOException {
   392         boolean ok = true;
   393         for (Element e : arr) {
   394             if (e.getKind() != ElementKind.METHOD) {
   395                 continue;
   396             }
   397             if (e.getAnnotation(ComputedProperty.class) == null) {
   398                 continue;
   399             }
   400             ExecutableElement ee = (ExecutableElement)e;
   401             final TypeMirror rt = ee.getReturnType();
   402             final Types tu = processingEnv.getTypeUtils();
   403             TypeMirror ert = tu.erasure(rt);
   404             String tn = ert.toString();
   405             boolean array = false;
   406             if (tn.equals("java.util.List")) {
   407                 array = true;
   408             }
   409             
   410             final String sn = ee.getSimpleName().toString();
   411             String[] gs = toGetSet(sn, tn, array);
   412             
   413             w.write("public " + tn + " " + gs[0] + "() {\n");
   414             w.write("  if (locked) throw new IllegalStateException();\n");
   415             int arg = 0;
   416             for (VariableElement pe : ee.getParameters()) {
   417                 final String dn = pe.getSimpleName().toString();
   418                 
   419                 if (!verifyPropName(pe, dn, fixedProps)) {
   420                     ok = false;
   421                 }
   422                 
   423                 final String dt = pe.asType().toString();
   424                 String[] call = toGetSet(dn, dt, false);
   425                 w.write("  " + dt + " arg" + (++arg) + " = ");
   426                 w.write(call[0] + "();\n");
   427                 
   428                 Collection<String> depends = deps.get(dn);
   429                 if (depends == null) {
   430                     depends = new LinkedHashSet<String>();
   431                     deps.put(dn, depends);
   432                 }
   433                 depends.add(sn);
   434             }
   435             w.write("  try {\n");
   436             w.write("    locked = true;\n");
   437             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   438             String sep = "";
   439             for (int i = 1; i <= arg; i++) {
   440                 w.write(sep);
   441                 w.write("arg" + i);
   442                 sep = ", ";
   443             }
   444             w.write(");\n");
   445             w.write("  } finally {\n");
   446             w.write("    locked = false;\n");
   447             w.write("  }\n");
   448             w.write("}\n");
   449 
   450             if (array) {
   451                 w.write("private Object[] " + gs[0] + "ToArray() {\n");
   452                 w.write("  return " + gs[0] + "().toArray(new Object[0]);\n");
   453                 w.write("}\n");
   454             }
   455             props.add(e.getSimpleName().toString());
   456             props.add(gs[2]);
   457             props.add(null);
   458             props.add(gs[0]);
   459         }
   460         
   461         return ok;
   462     }
   463 
   464     private static String[] toGetSet(String name, String type, boolean array) {
   465         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   466         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   467         if ("int".equals(type)) {
   468             bck2brwsrType = "I";
   469         }
   470         if ("double".equals(type)) {
   471             bck2brwsrType = "D";
   472         }
   473         String pref = "get";
   474         if ("boolean".equals(type)) {
   475             pref = "is";
   476             bck2brwsrType = "Z";
   477         }
   478         final String nu = n.replace('.', '_');
   479         if (array) {
   480             return new String[] { 
   481                 "get" + n,
   482                 null,
   483                 "get" + nu + "ToArray___3Ljava_lang_Object_2",
   484                 null
   485             };
   486         }
   487         return new String[]{
   488             pref + n, 
   489             "set" + n, 
   490             pref + nu + "__" + bck2brwsrType,
   491             "set" + nu + "__V" + bck2brwsrType
   492         };
   493     }
   494 
   495     private String typeName(Property p) {
   496         String ret;
   497         try {
   498             ret = p.type().getName();
   499         } catch (MirroredTypeException ex) {
   500             TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
   501             ret = tm.toString();
   502         }
   503         if (p.array()) {
   504             String bt = findBoxedType(ret);
   505             if (bt != null) {
   506                 return bt;
   507             }
   508         }
   509         if ("java.lang.String".equals(ret)) {
   510             return ret;
   511         }
   512         String bt = findBoxedType(ret);
   513         if (bt != null) {
   514             return ret;
   515         }
   516         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Only primitive types supported in the mapping. Not " + ret);
   517         return ret;
   518     }
   519     
   520     private static String findBoxedType(String ret) {
   521         if (ret.equals("byte")) {
   522             return Byte.class.getName();
   523         }
   524         if (ret.equals("short")) {
   525             return Short.class.getName();
   526         }
   527         if (ret.equals("char")) {
   528             return Character.class.getName();
   529         }
   530         if (ret.equals("int")) {
   531             return Integer.class.getName();
   532         }
   533         if (ret.equals("long")) {
   534             return Long.class.getName();
   535         }
   536         if (ret.equals("float")) {
   537             return Float.class.getName();
   538         }
   539         if (ret.equals("double")) {
   540             return Double.class.getName();
   541         }
   542         return null;
   543     }
   544 
   545     private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
   546         StringBuilder sb = new StringBuilder();
   547         String sep = "";
   548         for (Property property : existingProps) {
   549             if (property.name().equals(propName)) {
   550                 return true;
   551             }
   552             sb.append(sep);
   553             sb.append('"');
   554             sb.append(property.name());
   555             sb.append('"');
   556             sep = ", ";
   557         }
   558         processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
   559             propName + " is not one of known properties: " + sb
   560             , e
   561         );
   562         return false;
   563     }
   564 }