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