javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Jan 2013 21:01:46 +0100
branchmodel
changeset 496 a06c98795b01
parent 492 854286e49061
child 498 607f062485cc
permissions -rw-r--r--
Refresh the knockout model when a setter is called
     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.List;
    28 import java.util.Locale;
    29 import java.util.Set;
    30 import javax.annotation.processing.AbstractProcessor;
    31 import javax.annotation.processing.Completion;
    32 import javax.annotation.processing.Completions;
    33 import javax.annotation.processing.Processor;
    34 import javax.annotation.processing.RoundEnvironment;
    35 import javax.annotation.processing.SupportedAnnotationTypes;
    36 import javax.lang.model.element.AnnotationMirror;
    37 import javax.lang.model.element.Element;
    38 import javax.lang.model.element.ElementKind;
    39 import javax.lang.model.element.ExecutableElement;
    40 import javax.lang.model.element.Modifier;
    41 import javax.lang.model.element.PackageElement;
    42 import javax.lang.model.element.TypeElement;
    43 import javax.lang.model.element.VariableElement;
    44 import javax.lang.model.type.MirroredTypeException;
    45 import javax.lang.model.type.TypeMirror;
    46 import javax.tools.Diagnostic;
    47 import javax.tools.FileObject;
    48 import javax.tools.StandardLocation;
    49 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
    50 import org.apidesign.bck2brwsr.htmlpage.api.On;
    51 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    52 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    53 import org.openide.util.lookup.ServiceProvider;
    54 
    55 /** Annotation processor to process an XHTML page and generate appropriate 
    56  * "id" file.
    57  *
    58  * @author Jaroslav Tulach <jtulach@netbeans.org>
    59  */
    60 @ServiceProvider(service=Processor.class)
    61 @SupportedAnnotationTypes({
    62     "org.apidesign.bck2brwsr.htmlpage.api.Page",
    63     "org.apidesign.bck2brwsr.htmlpage.api.On"
    64 })
    65 public final class PageProcessor extends AbstractProcessor {
    66     @Override
    67     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    68         for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
    69             Page p = e.getAnnotation(Page.class);
    70             PackageElement pe = (PackageElement)e.getEnclosingElement();
    71             String pkg = pe.getQualifiedName().toString();
    72             
    73             ProcessPage pp;
    74             try {
    75                 InputStream is = openStream(pkg, p.xhtml());
    76                 pp = ProcessPage.readPage(is);
    77                 is.close();
    78             } catch (IOException iOException) {
    79                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
    80                 return false;
    81             }
    82             Writer w;
    83             String className = p.className();
    84             if (className.isEmpty()) {
    85                 int indx = p.xhtml().indexOf('.');
    86                 className = p.xhtml().substring(0, indx);
    87             }
    88             try {
    89                 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
    90                 w = new OutputStreamWriter(java.openOutputStream());
    91                 try {
    92                     w.append("package " + pkg + ";\n");
    93                     w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
    94                     w.append("class ").append(className).append(" {\n");
    95                     w.append("  private ").append(className).append("() {}\n");
    96                     for (String id : pp.ids()) {
    97                         String tag = pp.tagNameForId(id);
    98                         String type = type(tag);
    99                         w.append("  ").append("public static final ").
   100                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   101                             append(type).append("(\"").append(id).append("\");\n");
   102                     }
   103                     w.append("  static {\n");
   104                     if (!initializeOnClick((TypeElement) e, w, pp)) {
   105                         return false;
   106                     }
   107                     w.append("  }\n");
   108                     List<String> propsGetSet = new ArrayList<String>();
   109                     generateProperties(w, p.properties(), propsGetSet);
   110                     generateComputedProperties(w, e.getEnclosedElements(), propsGetSet);
   111                     w.append("  private static org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   112                     if (!propsGetSet.isEmpty()) {
   113                         w.write("public static void applyBindings() {\n");
   114                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   115                         w.write(className + ".class, new " + className + "(), ");
   116                         w.write("new String[] {\n");
   117                         String sep = "";
   118                         for (String n : propsGetSet) {
   119                             w.write(sep);
   120                             if (n == null) {
   121                                 w.write("    null");
   122                             } else {
   123                                 w.write("    \"" + n + "\"");
   124                             }
   125                             sep = ",\n";
   126                         }
   127                         w.write("\n  });\n}\n");
   128                         //w.write("static { applyBindings(); }\n");
   129                     }
   130                     w.append("}\n");
   131                 } finally {
   132                     w.close();
   133                 }
   134             } catch (IOException ex) {
   135                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
   136                 return false;
   137             }
   138         }
   139         return true;
   140     }
   141 
   142     private InputStream openStream(String pkg, String name) throws IOException {
   143         try {
   144             FileObject fo = processingEnv.getFiler().getResource(
   145                 StandardLocation.SOURCE_PATH, pkg, name);
   146             return fo.openInputStream();
   147         } catch (IOException ex) {
   148             return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
   149         }
   150     }
   151 
   152     private static String type(String tag) {
   153         if (tag.equals("title")) {
   154             return "Title";
   155         }
   156         if (tag.equals("button")) {
   157             return "Button";
   158         }
   159         if (tag.equals("input")) {
   160             return "Input";
   161         }
   162         return "Element";
   163     }
   164 
   165     private static String cnstnt(String id) {
   166         return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
   167     }
   168 
   169     private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
   170         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   171         { //for (Element clazz : pe.getEnclosedElements()) {
   172           //  if (clazz.getKind() != ElementKind.CLASS) {
   173             //    continue;
   174            // }
   175             for (Element method : type.getEnclosedElements()) {
   176                 On oc = method.getAnnotation(On.class);
   177                 if (oc != null) {
   178                     for (String id : oc.id()) {
   179                         if (pp.tagNameForId(id) == null) {
   180                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   181                             return false;
   182                         }
   183                         ExecutableElement ee = (ExecutableElement)method;
   184                         boolean hasParam;
   185                         if (ee.getParameters().isEmpty()) {
   186                             hasParam = false;
   187                         } else {
   188                             if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
   189                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
   190                                 return false;
   191                             }
   192                             hasParam = true;
   193                         }
   194                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   195                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   196                             return false;
   197                         }
   198                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   199                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   200                             return false;
   201                         }
   202                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   203                             append(").perform(new Runnable() { public void run() {\n");
   204                         w.append("    ").append(type.getSimpleName().toString()).
   205                             append('.').append(ee.getSimpleName()).append("(");
   206                         if (hasParam) {
   207                             w.append("\"").append(id).append("\"");
   208                         }
   209                         w.append(");\n");
   210                         w.append("  }});\n");
   211                     }           
   212                 }
   213             }
   214         }
   215         return true;
   216     }
   217 
   218     @Override
   219     public Iterable<? extends Completion> getCompletions(
   220         Element element, AnnotationMirror annotation, 
   221         ExecutableElement member, String userText
   222     ) {
   223         if (!userText.startsWith("\"")) {
   224             return Collections.emptyList();
   225         }
   226         
   227         Element cls = findClass(element);
   228         Page p = cls.getAnnotation(Page.class);
   229         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   230         String pkg = pe.getQualifiedName().toString();
   231         ProcessPage pp;
   232         try {
   233             InputStream is = openStream(pkg, p.xhtml());
   234             pp = ProcessPage.readPage(is);
   235             is.close();
   236         } catch (IOException iOException) {
   237             return Collections.emptyList();
   238         }
   239         
   240         List<Completion> cc = new ArrayList<Completion>();
   241         userText = userText.substring(1);
   242         for (String id : pp.ids()) {
   243             if (id.startsWith(userText)) {
   244                 cc.add(Completions.of("\"" + id + "\"", id));
   245             }
   246         }
   247         return cc;
   248     }
   249     
   250     private static Element findClass(Element e) {
   251         if (e == null) {
   252             return null;
   253         }
   254         Page p = e.getAnnotation(Page.class);
   255         if (p != null) {
   256             return e;
   257         }
   258         return e.getEnclosingElement();
   259     }
   260 
   261     private static void generateProperties(
   262         Writer w, Property[] properties, Collection<String> props
   263     ) throws IOException {
   264         for (Property p : properties) {
   265             final String tn = typeName(p);
   266             String[] gs = toGetSet(p.name(), tn);
   267 
   268             w.write("private static " + tn + " prop_" + p.name() + ";\n");
   269             w.write("public static " + tn + " " + gs[0] + "() {\n");
   270             w.write("  return prop_" + p.name() + ";\n");
   271             w.write("}\n");
   272             w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
   273             w.write("  prop_" + p.name() + " = v;\n");
   274             w.write("  if (ko != null) ko.valueHasMutated(\"" + p.name() + "\");\n");
   275             w.write("}\n");
   276             
   277             props.add(p.name());
   278             props.add(gs[2]);
   279             props.add(gs[3]);
   280         }
   281     }
   282 
   283     private void generateComputedProperties(
   284         Writer w, Collection<? extends Element> arr, Collection<String> props
   285     ) throws IOException {
   286         for (Element e : arr) {
   287             if (e.getKind() != ElementKind.METHOD) {
   288                 continue;
   289             }
   290             if (e.getAnnotation(ComputedProperty.class) == null) {
   291                 continue;
   292             }
   293             ExecutableElement ee = (ExecutableElement)e;
   294             final String tn = ee.getReturnType().toString();
   295             String[] gs = toGetSet(ee.getSimpleName().toString(), tn);
   296 
   297             w.write("public static " + tn + " " + gs[0] + "() {\n");
   298             w.write("  return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   299             String sep = "";
   300             for (VariableElement pe : ee.getParameters()) {
   301                 String[] call = toGetSet(pe.getSimpleName().toString(), pe.asType().toString());
   302                 w.write(sep);
   303                 w.write(call[0] + "()");
   304                 sep = ", ";
   305             }
   306             w.write(");\n");
   307             w.write("}\n");
   308             
   309             props.add(e.getSimpleName().toString());
   310             props.add(gs[2]);
   311             props.add(null);
   312         }
   313     }
   314 
   315     private static String[] toGetSet(String name, String type) {
   316         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   317         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   318         if ("int".equals(type)) {
   319             bck2brwsrType = "I";
   320         }
   321         if ("double".equals(type)) {
   322             bck2brwsrType = "D";
   323         }
   324         String pref = "get";
   325         if ("boolean".equals(type)) {
   326             pref = "is";
   327             bck2brwsrType = "Z";
   328         }
   329         return new String[]{
   330             pref + n, 
   331             "set" + n, 
   332             pref + n + "__" + bck2brwsrType,
   333             "set" + n + "__V" + bck2brwsrType
   334         };
   335     }
   336 
   337     private static String typeName(Property p) {
   338         try {
   339             return p.type().getName();
   340         } catch (MirroredTypeException ex) {
   341             if (ex.getTypeMirror().getKind().isPrimitive()) {
   342                 return ex.getTypeMirror().toString();
   343             }
   344             throw ex;
   345         }
   346     }
   347 }