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