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