javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 22 Mar 2013 00:05:41 +0100
changeset 871 6168fb585ab4
parent 866 9b4751828ceb
child 878 ecbd252fd3a7
permissions -rw-r--r--
Alas, need to merge into default branch, but without any changes from the accidental commit on default branch
     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.TypeKind;
    49 import javax.lang.model.type.TypeMirror;
    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         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    73             Page p = e.getAnnotation(Page.class);
    74             if (p == null) {
    75                 continue;
    76             }
    77             PackageElement pe = (PackageElement)e.getEnclosingElement();
    78             String pkg = pe.getQualifiedName().toString();
    79             
    80             ProcessPage pp;
    81             try {
    82                 InputStream is = openStream(pkg, p.xhtml());
    83                 pp = ProcessPage.readPage(is);
    84                 is.close();
    85             } catch (IOException iOException) {
    86                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    87                 return false;
    88             }
    89             Writer w;
    90             String className = p.className();
    91             if (className.isEmpty()) {
    92                 int indx = p.xhtml().indexOf('.');
    93                 className = p.xhtml().substring(0, indx);
    94             }
    95             try {
    96                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    97                 w = new OutputStreamWriter(java.openOutputStream());
    98                 try {
    99                     w.append("package " + pkg + ";\n");
   100                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
   101                     w.append("final class ").append(className).append(" {\n");
   102                     w.append("  private boolean locked;\n");
   103                     if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   104                         return false;
   105                     }
   106                     for (String id : pp.ids()) {
   107                         String tag = pp.tagNameForId(id);
   108                         String type = type(tag);
   109                         w.append("  ").append("public final ").
   110                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   111                             append(type).append("(\"").append(id).append("\");\n");
   112                     }
   113                     List<String> propsGetSet = new ArrayList<String>();
   114                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   115                     generateComputedProperties(w, e.getEnclosedElements(), propsGetSet, propsDeps);
   116                     generateProperties(w, p.properties(), propsGetSet, propsDeps);
   117                     w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   118                     if (!propsGetSet.isEmpty()) {
   119                         w.write("public " + className + " applyBindings() {\n");
   120                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   121                         w.write(className + ".class, this, ");
   122                         w.write("new String[] {\n");
   123                         String sep = "";
   124                         for (String n : propsGetSet) {
   125                             w.write(sep);
   126                             if (n == null) {
   127                                 w.write("    null");
   128                             } else {
   129                                 w.write("    \"" + n + "\"");
   130                             }
   131                             sep = ",\n";
   132                         }
   133                         w.write("\n  });\n  return this;\n}\n");
   134                         
   135                         w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   136                         w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   137                         w.write("}\n");
   138                     }
   139                     w.append("}\n");
   140                 } finally {
   141                     w.close();
   142                 }
   143             } catch (IOException ex) {
   144                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   145                 return false;
   146             }
   147         }
   148         return true;
   149     }
   150 
   151     private InputStream openStream(String pkg, String name) throws IOException {
   152         try {
   153             FileObject fo = processingEnv.getFiler().getResource(
   154                 StandardLocation.SOURCE_PATH, pkg, name);
   155             return fo.openInputStream();
   156         } catch (IOException ex) {
   157             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   158         }
   159     }
   160 
   161     private static String type(String tag) {
   162         if (tag.equals("title")) {
   163             return "Title";
   164         }
   165         if (tag.equals("button")) {
   166             return "Button";
   167         }
   168         if (tag.equals("input")) {
   169             return "Input";
   170         }
   171         if (tag.equals("canvas")) {
   172             return "Canvas";
   173         }
   174         if (tag.equals("img")) {
   175             return "Image";
   176         }
   177         return "Element";
   178     }
   179 
   180     private static String cnstnt(String id) {
   181         return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
   182     }
   183 
   184     private boolean initializeOnClick(
   185         String className, TypeElement type, Writer w, ProcessPage pp
   186     ) throws IOException {
   187         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   188         { //for (Element clazz : pe.getEnclosedElements()) {
   189           //  if (clazz.getKind() != ElementKind.CLASS) {
   190             //    continue;
   191            // }
   192             w.append("  public ").append(className).append("() {\n");
   193             StringBuilder dispatch = new StringBuilder();
   194             int dispatchCnt = 0;
   195             for (Element method : type.getEnclosedElements()) {
   196                 On oc = method.getAnnotation(On.class);
   197                 if (oc != null) {
   198                     for (String id : oc.id()) {
   199                         if (pp.tagNameForId(id) == null) {
   200                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   201                             return false;
   202                         }
   203                         ExecutableElement ee = (ExecutableElement)method;
   204                         StringBuilder params = new StringBuilder();
   205                         {
   206                             boolean first = true;
   207                             for (VariableElement ve : ee.getParameters()) {
   208                                 if (!first) {
   209                                     params.append(", ");
   210                                 }
   211                                 first = false;
   212                                 if (ve.asType() == stringType) {
   213                                     if (ve.getSimpleName().contentEquals("id")) {
   214                                         params.append('"').append(id).append('"');
   215                                         continue;
   216                                     }
   217                                     params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(ev, \"");
   218                                     params.append(ve.getSimpleName().toString());
   219                                     params.append("\")");
   220                                     continue;
   221                                 }
   222                                 if (processingEnv.getTypeUtils().getPrimitiveType(TypeKind.DOUBLE) == ve.asType()) {
   223                                     params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(ev, \"");
   224                                     params.append(ve.getSimpleName().toString());
   225                                     params.append("\")");
   226                                     continue;
   227                                 }
   228                                 String rn = ve.asType().toString();
   229                                 int last = rn.lastIndexOf('.');
   230                                 if (last >= 0) {
   231                                     rn = rn.substring(last + 1);
   232                                 }
   233                                 if (rn.equals(className)) {
   234                                     params.append(className).append(".this");
   235                                     continue;
   236                                 }
   237                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   238                                     "@On method can only accept String named 'id' or " + className + " arguments",
   239                                     ee
   240                                 );
   241                                 return false;
   242                             }
   243                         }
   244                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   245                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   246                             return false;
   247                         }
   248                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   249                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   250                             return false;
   251                         }
   252                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   253                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   254 
   255                         dispatch.
   256                             append("      case ").append(dispatchCnt).append(": ").
   257                             append(type.getSimpleName().toString()).
   258                             append('.').append(ee.getSimpleName()).append("(").
   259                             append(params).
   260                             append("); break;\n");
   261                         
   262                         dispatchCnt++;
   263                     }
   264                 }
   265             }
   266             w.append("  }\n");
   267             if (dispatchCnt > 0) {
   268                 w.append("class OnDispatch implements OnHandler {\n");
   269                 w.append("  private final int dispatch;\n");
   270                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   271                 w.append("  public void onEvent(Object ev) {\n");
   272                 w.append("    switch (dispatch) {\n");
   273                 w.append(dispatch);
   274                 w.append("    }\n");
   275                 w.append("  }\n");
   276                 w.append("}\n");
   277             }
   278             
   279 
   280         }
   281         return true;
   282     }
   283 
   284     @Override
   285     public Iterable<? extends Completion> getCompletions(
   286         Element element, AnnotationMirror annotation, 
   287         ExecutableElement member, String userText
   288     ) {
   289         if (!userText.startsWith("\"")) {
   290             return Collections.emptyList();
   291         }
   292         
   293         Element cls = findClass(element);
   294         Page p = cls.getAnnotation(Page.class);
   295         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   296         String pkg = pe.getQualifiedName().toString();
   297         ProcessPage pp;
   298         try {
   299             InputStream is = openStream(pkg, p.xhtml());
   300             pp = ProcessPage.readPage(is);
   301             is.close();
   302         } catch (IOException iOException) {
   303             return Collections.emptyList();
   304         }
   305         
   306         List<Completion> cc = new ArrayList<Completion>();
   307         userText = userText.substring(1);
   308         for (String id : pp.ids()) {
   309             if (id.startsWith(userText)) {
   310                 cc.add(Completions.of("\"" + id + "\"", id));
   311             }
   312         }
   313         return cc;
   314     }
   315     
   316     private static Element findClass(Element e) {
   317         if (e == null) {
   318             return null;
   319         }
   320         Page p = e.getAnnotation(Page.class);
   321         if (p != null) {
   322             return e;
   323         }
   324         return e.getEnclosingElement();
   325     }
   326 
   327     private static void generateProperties(
   328         Writer w, Property[] properties, Collection<String> props,
   329         Map<String,Collection<String>> deps
   330     ) throws IOException {
   331         for (Property p : properties) {
   332             final String tn = typeName(p);
   333             String[] gs = toGetSet(p.name(), tn);
   334 
   335             w.write("private " + tn + " prop_" + p.name() + ";\n");
   336             w.write("public " + tn + " " + gs[0] + "() {\n");
   337             w.write("  if (locked) throw new IllegalStateException();\n");
   338             w.write("  return prop_" + p.name() + ";\n");
   339             w.write("}\n");
   340             w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   341             w.write("  if (locked) throw new IllegalStateException();\n");
   342             w.write("  prop_" + p.name() + " = v;\n");
   343             w.write("  if (ko != null) {\n");
   344             w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   345             final Collection<String> dependants = deps.get(p.name());
   346             if (dependants != null) {
   347                 for (String depProp : dependants) {
   348                     w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   349                 }
   350             }
   351             w.write("  }\n");
   352             w.write("}\n");
   353             
   354             props.add(p.name());
   355             props.add(gs[2]);
   356             props.add(gs[3]);
   357             props.add(gs[0]);
   358         }
   359     }
   360 
   361     private boolean generateComputedProperties(
   362         Writer w, Collection<? extends Element> arr, Collection<String> props,
   363         Map<String,Collection<String>> deps
   364     ) throws IOException {
   365         for (Element e : arr) {
   366             if (e.getKind() != ElementKind.METHOD) {
   367                 continue;
   368             }
   369             if (e.getAnnotation(ComputedProperty.class) == null) {
   370                 continue;
   371             }
   372             ExecutableElement ee = (ExecutableElement)e;
   373             final String tn = ee.getReturnType().toString();
   374             final String sn = ee.getSimpleName().toString();
   375             String[] gs = toGetSet(sn, tn);
   376             
   377             w.write("public " + tn + " " + gs[0] + "() {\n");
   378             w.write("  if (locked) throw new IllegalStateException();\n");
   379             int arg = 0;
   380             for (VariableElement pe : ee.getParameters()) {
   381                 final String dn = pe.getSimpleName().toString();
   382                 final String dt = pe.asType().toString();
   383                 String[] call = toGetSet(dn, dt);
   384                 w.write("  " + dt + " arg" + (++arg) + " = ");
   385                 w.write(call[0] + "();\n");
   386                 
   387                 Collection<String> depends = deps.get(dn);
   388                 if (depends == null) {
   389                     depends = new LinkedHashSet<String>();
   390                     deps.put(dn, depends);
   391                 }
   392                 depends.add(sn);
   393             }
   394             w.write("  try {\n");
   395             w.write("    locked = true;\n");
   396             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   397             String sep = "";
   398             for (int i = 1; i <= arg; i++) {
   399                 w.write(sep);
   400                 w.write("arg" + i);
   401                 sep = ", ";
   402             }
   403             w.write(");\n");
   404             w.write("  } finally {\n");
   405             w.write("    locked = false;\n");
   406             w.write("  }\n");
   407             w.write("}\n");
   408             
   409             props.add(e.getSimpleName().toString());
   410             props.add(gs[2]);
   411             props.add(null);
   412             props.add(gs[0]);
   413         }
   414         
   415         return true;
   416     }
   417 
   418     private static String[] toGetSet(String name, String type) {
   419         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   420         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   421         if ("int".equals(type)) {
   422             bck2brwsrType = "I";
   423         }
   424         if ("double".equals(type)) {
   425             bck2brwsrType = "D";
   426         }
   427         String pref = "get";
   428         if ("boolean".equals(type)) {
   429             pref = "is";
   430             bck2brwsrType = "Z";
   431         }
   432         final String nu = n.replace('.', '_');
   433         return new String[]{
   434             pref + n, 
   435             "set" + n, 
   436             pref + nu + "__" + bck2brwsrType,
   437             "set" + nu + "__V" + bck2brwsrType
   438         };
   439     }
   440 
   441     private static String typeName(Property p) {
   442         try {
   443             return p.type().getName();
   444         } catch (MirroredTypeException ex) {
   445             return ex.getTypeMirror().toString();
   446         }
   447     }
   448 }