javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/PageProcessor.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 22 Jan 2013 22:49:03 +0100
branchmodel
changeset 535 0867fd166be9
parent 530 3ce069ec3312
child 543 1adce93fea0f
permissions -rw-r--r--
Sometimes we get FQN, sometimes just a simple name. Strip package for consistency.
     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 boolean locked;\n");
    99                     if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
   100                         return false;
   101                     }
   102                     for (String id : pp.ids()) {
   103                         String tag = pp.tagNameForId(id);
   104                         String type = type(tag);
   105                         w.append("  ").append("public final ").
   106                             append(type).append(' ').append(cnstnt(id)).append(" = new ").
   107                             append(type).append("(\"").append(id).append("\");\n");
   108                     }
   109                     List<String> propsGetSet = new ArrayList<String>();
   110                     Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
   111                     generateComputedProperties(w, e.getEnclosedElements(), propsGetSet, propsDeps);
   112                     generateProperties(w, p.properties(), propsGetSet, propsDeps);
   113                     w.append("  private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
   114                     if (!propsGetSet.isEmpty()) {
   115                         w.write("public " + className + " applyBindings() {\n");
   116                         w.write("  ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
   117                         w.write(className + ".class, this, ");
   118                         w.write("new String[] {\n");
   119                         String sep = "";
   120                         for (String n : propsGetSet) {
   121                             w.write(sep);
   122                             if (n == null) {
   123                                 w.write("    null");
   124                             } else {
   125                                 w.write("    \"" + n + "\"");
   126                             }
   127                             sep = ",\n";
   128                         }
   129                         w.write("\n  });\n  return this;\n}\n");
   130                         
   131                         w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
   132                         w.write("  org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
   133                         w.write("}\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         if (tag.equals("canvas")) {
   168             return "Canvas";
   169         }
   170         if (tag.equals("img")) {
   171             return "Image";
   172         }
   173         return "Element";
   174     }
   175 
   176     private static String cnstnt(String id) {
   177         return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
   178     }
   179 
   180     private boolean initializeOnClick(
   181         String className, TypeElement type, Writer w, ProcessPage pp
   182     ) throws IOException {
   183         TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
   184         { //for (Element clazz : pe.getEnclosedElements()) {
   185           //  if (clazz.getKind() != ElementKind.CLASS) {
   186             //    continue;
   187            // }
   188             w.append("  public ").append(className).append("() {\n");
   189             StringBuilder dispatch = new StringBuilder();
   190             int dispatchCnt = 0;
   191             for (Element method : type.getEnclosedElements()) {
   192                 On oc = method.getAnnotation(On.class);
   193                 if (oc != null) {
   194                     for (String id : oc.id()) {
   195                         if (pp.tagNameForId(id) == null) {
   196                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
   197                             return false;
   198                         }
   199                         ExecutableElement ee = (ExecutableElement)method;
   200                         StringBuilder params = new StringBuilder();
   201                         {
   202                             boolean first = true;
   203                             for (VariableElement ve : ee.getParameters()) {
   204                                 if (!first) {
   205                                     params.append(", ");
   206                                 }
   207                                 first = false;
   208                                 if (ve.asType() == stringType) {
   209                                     params.append('"').append(id).append('"');
   210                                     continue;
   211                                 }
   212                                 String rn = ve.asType().toString();
   213                                 int last = rn.lastIndexOf('.');
   214                                 if (last >= 0) {
   215                                     rn = rn.substring(last + 1);
   216                                 }
   217                                 if (rn.equals(className)) {
   218                                     params.append(className).append(".this");
   219                                     continue;
   220                                 }
   221                                 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, 
   222                                     "@On method can only accept String or " + className + " arguments",
   223                                     ee
   224                                 );
   225                                 return false;
   226                             }
   227                         }
   228                         if (!ee.getModifiers().contains(Modifier.STATIC)) {
   229                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
   230                             return false;
   231                         }
   232                         if (ee.getModifiers().contains(Modifier.PRIVATE)) {
   233                             processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
   234                             return false;
   235                         }
   236                         w.append("  OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
   237                             append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
   238 
   239                         dispatch.
   240                             append("      case ").append(dispatchCnt).append(": ").
   241                             append(type.getSimpleName().toString()).
   242                             append('.').append(ee.getSimpleName()).append("(").
   243                             append(params).
   244                             append("); break;\n");
   245                         
   246                         dispatchCnt++;
   247                     }
   248                 }
   249             }
   250             w.append("  }\n");
   251             if (dispatchCnt > 0) {
   252                 w.append("class OnDispatch implements Runnable {\n");
   253                 w.append("  private final int dispatch;\n");
   254                 w.append("  OnDispatch(int d) { dispatch = d; }\n");
   255                 w.append("  public void run() {\n");
   256                 w.append("    switch (dispatch) {\n");
   257                 w.append(dispatch);
   258                 w.append("    }\n");
   259                 w.append("  }\n");
   260                 w.append("}\n");
   261             }
   262             
   263 
   264         }
   265         return true;
   266     }
   267 
   268     @Override
   269     public Iterable<? extends Completion> getCompletions(
   270         Element element, AnnotationMirror annotation, 
   271         ExecutableElement member, String userText
   272     ) {
   273         if (!userText.startsWith("\"")) {
   274             return Collections.emptyList();
   275         }
   276         
   277         Element cls = findClass(element);
   278         Page p = cls.getAnnotation(Page.class);
   279         PackageElement pe = (PackageElement) cls.getEnclosingElement();
   280         String pkg = pe.getQualifiedName().toString();
   281         ProcessPage pp;
   282         try {
   283             InputStream is = openStream(pkg, p.xhtml());
   284             pp = ProcessPage.readPage(is);
   285             is.close();
   286         } catch (IOException iOException) {
   287             return Collections.emptyList();
   288         }
   289         
   290         List<Completion> cc = new ArrayList<Completion>();
   291         userText = userText.substring(1);
   292         for (String id : pp.ids()) {
   293             if (id.startsWith(userText)) {
   294                 cc.add(Completions.of("\"" + id + "\"", id));
   295             }
   296         }
   297         return cc;
   298     }
   299     
   300     private static Element findClass(Element e) {
   301         if (e == null) {
   302             return null;
   303         }
   304         Page p = e.getAnnotation(Page.class);
   305         if (p != null) {
   306             return e;
   307         }
   308         return e.getEnclosingElement();
   309     }
   310 
   311     private static void generateProperties(
   312         Writer w, Property[] properties, Collection<String> props,
   313         Map<String,Collection<String>> deps
   314     ) throws IOException {
   315         for (Property p : properties) {
   316             final String tn = typeName(p);
   317             String[] gs = toGetSet(p.name(), tn);
   318 
   319             w.write("private " + tn + " prop_" + p.name() + ";\n");
   320             w.write("public " + tn + " " + gs[0] + "() {\n");
   321             w.write("  if (locked) throw new IllegalStateException();\n");
   322             w.write("  return prop_" + p.name() + ";\n");
   323             w.write("}\n");
   324             w.write("public void " + gs[1] + "(" + tn + " v) {\n");
   325             w.write("  if (locked) throw new IllegalStateException();\n");
   326             w.write("  prop_" + p.name() + " = v;\n");
   327             w.write("  if (ko != null) {\n");
   328             w.write("    ko.valueHasMutated(\"" + p.name() + "\");\n");
   329             final Collection<String> dependants = deps.get(p.name());
   330             if (dependants != null) {
   331                 for (String depProp : dependants) {
   332                     w.write("    ko.valueHasMutated(\"" + depProp + "\");\n");
   333                 }
   334             }
   335             w.write("  }\n");
   336             w.write("}\n");
   337             
   338             props.add(p.name());
   339             props.add(gs[2]);
   340             props.add(gs[3]);
   341             props.add(gs[0]);
   342         }
   343     }
   344 
   345     private boolean generateComputedProperties(
   346         Writer w, Collection<? extends Element> arr, Collection<String> props,
   347         Map<String,Collection<String>> deps
   348     ) throws IOException {
   349         for (Element e : arr) {
   350             if (e.getKind() != ElementKind.METHOD) {
   351                 continue;
   352             }
   353             if (e.getAnnotation(ComputedProperty.class) == null) {
   354                 continue;
   355             }
   356             ExecutableElement ee = (ExecutableElement)e;
   357             final String tn = ee.getReturnType().toString();
   358             final String sn = ee.getSimpleName().toString();
   359             String[] gs = toGetSet(sn, tn);
   360             
   361             w.write("public " + tn + " " + gs[0] + "() {\n");
   362             w.write("  if (locked) throw new IllegalStateException();\n");
   363             int arg = 0;
   364             for (VariableElement pe : ee.getParameters()) {
   365                 final String dn = pe.getSimpleName().toString();
   366                 final String dt = pe.asType().toString();
   367                 String[] call = toGetSet(dn, dt);
   368                 w.write("  " + dt + " arg" + (++arg) + " = ");
   369                 w.write(call[0] + "();\n");
   370                 
   371                 Collection<String> depends = deps.get(dn);
   372                 if (depends == null) {
   373                     depends = new LinkedHashSet<String>();
   374                     deps.put(dn, depends);
   375                 }
   376                 depends.add(sn);
   377             }
   378             w.write("  try {\n");
   379             w.write("    locked = true;\n");
   380             w.write("    return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
   381             String sep = "";
   382             for (int i = 1; i <= arg; i++) {
   383                 w.write(sep);
   384                 w.write("arg" + i);
   385                 sep = ", ";
   386             }
   387             w.write(");\n");
   388             w.write("  } finally {\n");
   389             w.write("    locked = false;\n");
   390             w.write("  }\n");
   391             w.write("}\n");
   392             
   393             props.add(e.getSimpleName().toString());
   394             props.add(gs[2]);
   395             props.add(null);
   396             props.add(gs[0]);
   397         }
   398         
   399         return true;
   400     }
   401 
   402     private static String[] toGetSet(String name, String type) {
   403         String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
   404         String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
   405         if ("int".equals(type)) {
   406             bck2brwsrType = "I";
   407         }
   408         if ("double".equals(type)) {
   409             bck2brwsrType = "D";
   410         }
   411         String pref = "get";
   412         if ("boolean".equals(type)) {
   413             pref = "is";
   414             bck2brwsrType = "Z";
   415         }
   416         final String nu = n.replace('.', '_');
   417         return new String[]{
   418             pref + n, 
   419             "set" + n, 
   420             pref + nu + "__" + bck2brwsrType,
   421             "set" + nu + "__V" + bck2brwsrType
   422         };
   423     }
   424 
   425     private static String typeName(Property p) {
   426         try {
   427             return p.type().getName();
   428         } catch (MirroredTypeException ex) {
   429             return ex.getTypeMirror().toString();
   430         }
   431     }
   432 }