javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 21 Jan 2013 11:55:27 +0100
branchmodel
changeset 500 f9e80d48e9b4
parent 498 607f062485cc
child 505 4198be34b516
permissions -rw-r--r--
@ComputedProperty methods can't access the 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("class ").append(className).append(" {\n");
    98                     w.append("  private static boolean locked;\n");
    99                     w.append("  private ").append(className).append("() {}\n");
   100                     for (String id : pp.ids()) {
   101                         String tag = pp.tagNameForId(id);
   102                         String type = type(tag);
   103                         w.append("  ").append("public static final ").
   104                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   105                             append(type).append("(\"").append(id).append("\");\n");
   106                     }
   107                     w.append("  static {\n");
   108                     if (!initializeOnClick((TypeElement) e, w, pp)) {
   109                         return false;
   110                     }
   111                     w.append("  }\n");
   112                     List<String> propsGetSet = new ArrayList<String>();
   113                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   114                     generateComputedProperties(w, e.getEnclosedElements(), propsGetSet, propsDeps);
   115                     generateProperties(w, p.properties(), propsGetSet, propsDeps);
   116                     w.append("  private static org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   117                     if (!propsGetSet.isEmpty()) {
   118                         w.write("public static void applyBindings() {\n");
   119                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   120                         w.write(className + ".class, new " + className + "(), ");
   121                         w.write("new String[] {\n");
   122                         String sep = "";
   123                         for (String n : propsGetSet) {
   124                             w.write(sep);
   125                             if (n == null) {
   126                                 w.write("    null");
   127                             } else {
   128                                 w.write("    \"" + n + "\"");
   129                             }
   130                             sep = ",\n";
   131                         }
   132                         w.write("\n  });\n}\n");
   133                         //w.write("static { applyBindings(); }\n");
   134                     }
   135                     w.append("}\n");
   136                 } finally {
   137                     w.close();
   138                 }
   139             } catch (IOException ex) {
   140                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   141                 return false;
   142             }
   143         }
   144         return true;
   145     }
   146 
   147     private InputStream openStream(String pkg, String name) throws IOException {
   148         try {
   149             FileObject fo = processingEnv.getFiler().getResource(
   150                 StandardLocation.SOURCE_PATH, pkg, name);
   151             return fo.openInputStream();
   152         } catch (IOException ex) {
   153             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   154         }
   155     }
   156 
   157     private static String type(String tag) {
   158         if (tag.equals("title")) {
   159             return "Title";
   160         }
   161         if (tag.equals("button")) {
   162             return "Button";
   163         }
   164         if (tag.equals("input")) {
   165             return "Input";
   166         }
   167         return "Element";
   168     }
   169 
   170     private static String cnstnt(String id) {
   171         return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
   172     }
   173 
   174     private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
   175         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   176         { //for (Element clazz : pe.getEnclosedElements()) {
   177           //  if (clazz.getKind() != ElementKind.CLASS) {
   178             //    continue;
   179            // }
   180             for (Element method : type.getEnclosedElements()) {
   181                 On oc = method.getAnnotation(On.class);
   182                 if (oc != null) {
   183                     for (String id : oc.id()) {
   184                         if (pp.tagNameForId(id) == null) {
   185                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   186                             return false;
   187                         }
   188                         ExecutableElement ee = (ExecutableElement)method;
   189                         boolean hasParam;
   190                         if (ee.getParameters().isEmpty()) {
   191                             hasParam = false;
   192                         } else {
   193                             if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
   194                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
   195                                 return false;
   196                             }
   197                             hasParam = true;
   198                         }
   199                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   200                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   201                             return false;
   202                         }
   203                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   204                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   205                             return false;
   206                         }
   207                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   208                             append(").perform(new Runnable() { public void run() {\n");
   209                         w.append("    ").append(type.getSimpleName().toString()).
   210                             append('.').append(ee.getSimpleName()).append("(");
   211                         if (hasParam) {
   212                             w.append("\"").append(id).append("\"");
   213                         }
   214                         w.append(");\n");
   215                         w.append("  }});\n");
   216                     }           
   217                 }
   218             }
   219         }
   220         return true;
   221     }
   222 
   223     @Override
   224     public Iterable<? extends Completion> getCompletions(
   225         Element element, AnnotationMirror annotation, 
   226         ExecutableElement member, String userText
   227     ) {
   228         if (!userText.startsWith("\"")) {
   229             return Collections.emptyList();
   230         }
   231         
   232         Element cls = findClass(element);
   233         Page p = cls.getAnnotation(Page.class);
   234         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   235         String pkg = pe.getQualifiedName().toString();
   236         ProcessPage pp;
   237         try {
   238             InputStream is = openStream(pkg, p.xhtml());
   239             pp = ProcessPage.readPage(is);
   240             is.close();
   241         } catch (IOException iOException) {
   242             return Collections.emptyList();
   243         }
   244         
   245         List<Completion> cc = new ArrayList<Completion>();
   246         userText = userText.substring(1);
   247         for (String id : pp.ids()) {
   248             if (id.startsWith(userText)) {
   249                 cc.add(Completions.of("\"" + id + "\"", id));
   250             }
   251         }
   252         return cc;
   253     }
   254     
   255     private static Element findClass(Element e) {
   256         if (e == null) {
   257             return null;
   258         }
   259         Page p = e.getAnnotation(Page.class);
   260         if (p != null) {
   261             return e;
   262         }
   263         return e.getEnclosingElement();
   264     }
   265 
   266     private static void generateProperties(
   267         Writer w, Property[] properties, Collection<String> props,
   268         Map<String,Collection<String>> deps
   269     ) throws IOException {
   270         for (Property p : properties) {
   271             final String tn = typeName(p);
   272             String[] gs = toGetSet(p.name(), tn);
   273 
   274             w.write("private static " + tn + " prop_" + p.name() + ";\n");
   275             w.write("public static " + tn + " " + gs[0] + "() {\n");
   276             w.write("  if (locked) throw new IllegalStateException();\n");
   277             w.write("  return prop_" + p.name() + ";\n");
   278             w.write("}\n");
   279             w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
   280             w.write("  if (locked) throw new IllegalStateException();\n");
   281             w.write("  prop_" + p.name() + " = v;\n");
   282             w.write("  if (ko != null) {\n");
   283             w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   284             final Collection<String> dependants = deps.get(p.name());
   285             if (dependants != null) {
   286                 for (String depProp : dependants) {
   287                     w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   288                 }
   289             }
   290             w.write("  }\n");
   291             w.write("}\n");
   292             
   293             props.add(p.name());
   294             props.add(gs[2]);
   295             props.add(gs[3]);
   296         }
   297     }
   298 
   299     private boolean generateComputedProperties(
   300         Writer w, Collection<? extends Element> arr, Collection<String> props,
   301         Map<String,Collection<String>> deps
   302     ) throws IOException {
   303         for (Element e : arr) {
   304             if (e.getKind() != ElementKind.METHOD) {
   305                 continue;
   306             }
   307             if (e.getAnnotation(ComputedProperty.class) == null) {
   308                 continue;
   309             }
   310             ExecutableElement ee = (ExecutableElement)e;
   311             final String tn = ee.getReturnType().toString();
   312             final String sn = ee.getSimpleName().toString();
   313             String[] gs = toGetSet(sn, tn);
   314             
   315             w.write("public static " + tn + " " + gs[0] + "() {\n");
   316             w.write("  if (locked) throw new IllegalStateException();\n");
   317             int arg = 0;
   318             for (VariableElement pe : ee.getParameters()) {
   319                 final String dn = pe.getSimpleName().toString();
   320                 final String dt = pe.asType().toString();
   321                 String[] call = toGetSet(dn, dt);
   322                 w.write("  " + dt + " arg" + (++arg) + " = ");
   323                 w.write(call[0] + "();\n");
   324                 
   325                 Collection<String> depends = deps.get(dn);
   326                 if (depends == null) {
   327                     depends = new LinkedHashSet<String>();
   328                     deps.put(dn, depends);
   329                 }
   330                 depends.add(sn);
   331             }
   332             w.write("  try {\n");
   333             w.write("    locked = true;\n");
   334             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   335             String sep = "";
   336             for (int i = 1; i <= arg; i++) {
   337                 w.write(sep);
   338                 w.write("arg" + i);
   339                 sep = ", ";
   340             }
   341             w.write(");\n");
   342             w.write("  } finally {\n");
   343             w.write("    locked = false;\n");
   344             w.write("  }\n");
   345             w.write("}\n");
   346             
   347             props.add(e.getSimpleName().toString());
   348             props.add(gs[2]);
   349             props.add(null);
   350         }
   351         
   352         return true;
   353     }
   354 
   355     private static String[] toGetSet(String name, String type) {
   356         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   357         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   358         if ("int".equals(type)) {
   359             bck2brwsrType = "I";
   360         }
   361         if ("double".equals(type)) {
   362             bck2brwsrType = "D";
   363         }
   364         String pref = "get";
   365         if ("boolean".equals(type)) {
   366             pref = "is";
   367             bck2brwsrType = "Z";
   368         }
   369         final String nu = n.replace('.', '_');
   370         return new String[]{
   371             pref + n, 
   372             "set" + n, 
   373             pref + nu + "__" + bck2brwsrType,
   374             "set" + nu + "__V" + bck2brwsrType
   375         };
   376     }
   377 
   378     private static String typeName(Property p) {
   379         try {
   380             return p.type().getName();
   381         } catch (MirroredTypeException ex) {
   382             return ex.getTypeMirror().toString();
   383         }
   384     }
   385 }