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