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