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