Need to merge in default branch: It contains automatic conversion of boxed types to primitive values which is needed by Knockout to display elements of arrays properly.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
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.
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.
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.
18 package org.apidesign.bck2brwsr.htmlpage;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStreamWriter;
23 import java.io.StringWriter;
24 import java.io.Writer;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.LinkedHashSet;
30 import java.util.List;
31 import java.util.Locale;
34 import javax.annotation.processing.AbstractProcessor;
35 import javax.annotation.processing.Completion;
36 import javax.annotation.processing.Completions;
37 import javax.annotation.processing.Processor;
38 import javax.annotation.processing.RoundEnvironment;
39 import javax.annotation.processing.SupportedAnnotationTypes;
40 import javax.lang.model.element.AnnotationMirror;
41 import javax.lang.model.element.Element;
42 import javax.lang.model.element.ElementKind;
43 import javax.lang.model.element.ExecutableElement;
44 import javax.lang.model.element.Modifier;
45 import javax.lang.model.element.PackageElement;
46 import javax.lang.model.element.TypeElement;
47 import javax.lang.model.element.VariableElement;
48 import javax.lang.model.type.MirroredTypeException;
49 import javax.lang.model.type.TypeKind;
50 import javax.lang.model.type.TypeMirror;
51 import javax.lang.model.util.Types;
52 import javax.tools.Diagnostic;
53 import javax.tools.FileObject;
54 import javax.tools.StandardLocation;
55 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
56 import org.apidesign.bck2brwsr.htmlpage.api.Model;
57 import org.apidesign.bck2brwsr.htmlpage.api.On;
58 import org.apidesign.bck2brwsr.htmlpage.api.Page;
59 import org.apidesign.bck2brwsr.htmlpage.api.Property;
60 import org.openide.util.lookup.ServiceProvider;
62 /** Annotation processor to process an XHTML page and generate appropriate
65 * @author Jaroslav Tulach <jtulach@netbeans.org>
67 @ServiceProvider(service=Processor.class)
68 @SupportedAnnotationTypes({
69 "org.apidesign.bck2brwsr.htmlpage.api.Model",
70 "org.apidesign.bck2brwsr.htmlpage.api.Page",
71 "org.apidesign.bck2brwsr.htmlpage.api.On"
73 public final class PageProcessor extends AbstractProcessor {
75 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
77 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
78 if (!processModel(e)) {
82 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
83 if (!processPage(e)) {
90 private InputStream openStream(String pkg, String name) throws IOException {
92 FileObject fo = processingEnv.getFiler().getResource(
93 StandardLocation.SOURCE_PATH, pkg, name);
94 return fo.openInputStream();
95 } catch (IOException ex) {
96 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
100 private boolean processModel(Element e) {
102 Model m = e.getAnnotation(Model.class);
106 String pkg = findPkgName(e);
108 String className = m.className();
110 StringWriter body = new StringWriter();
111 List<String> propsGetSet = new ArrayList<>();
112 Map<String, Collection<String>> propsDeps = new HashMap<>();
113 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
116 if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
119 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
120 w = new OutputStreamWriter(java.openOutputStream());
122 w.append("package " + pkg + ";\n");
123 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
124 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
125 w.append("final class ").append(className).append(" {\n");
126 w.append(" private Object json;\n");
127 w.append(" private boolean locked;\n");
128 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
129 w.append(body.toString());
134 } catch (IOException ex) {
135 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
141 private boolean processPage(Element e) {
143 Page p = e.getAnnotation(Page.class);
147 String pkg = findPkgName(e);
150 try (InputStream is = openStream(pkg, p.xhtml())) {
151 pp = ProcessPage.readPage(is);
153 } catch (IOException iOException) {
154 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
159 String className = p.className();
160 if (className.isEmpty()) {
161 int indx = p.xhtml().indexOf('.');
162 className = p.xhtml().substring(0, indx);
165 StringWriter body = new StringWriter();
166 List<String> propsGetSet = new ArrayList<>();
167 Map<String, Collection<String>> propsDeps = new HashMap<>();
168 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
171 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
175 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
176 w = new OutputStreamWriter(java.openOutputStream());
178 w.append("package " + pkg + ";\n");
179 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
180 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
181 w.append("final class ").append(className).append(" {\n");
182 w.append(" private boolean locked;\n");
183 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
186 for (String id : pp.ids()) {
187 String tag = pp.tagNameForId(id);
188 String type = type(tag);
189 w.append(" ").append("public final ").
190 append(type).append(' ').append(cnstnt(id)).append(" = new ").
191 append(type).append("(\"").append(id).append("\");\n");
194 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
195 w.append(body.toString());
196 if (!propsGetSet.isEmpty()) {
197 w.write("public " + className + " applyBindings() {\n");
198 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
199 w.write(className + ".class, this, ");
200 w.write("new String[] {\n");
202 for (String n : propsGetSet) {
207 w.write(" \"" + n + "\"");
211 w.write("\n });\n return this;\n}\n");
213 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
214 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
221 } catch (IOException ex) {
222 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
228 private static String type(String tag) {
229 if (tag.equals("title")) {
232 if (tag.equals("button")) {
235 if (tag.equals("input")) {
238 if (tag.equals("canvas")) {
241 if (tag.equals("img")) {
247 private static String cnstnt(String id) {
248 return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
251 private boolean initializeOnClick(
252 String className, TypeElement type, Writer w, ProcessPage pp
253 ) throws IOException {
255 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
256 { //for (Element clazz : pe.getEnclosedElements()) {
257 // if (clazz.getKind() != ElementKind.CLASS) {
260 w.append(" public ").append(className).append("() {\n");
261 StringBuilder dispatch = new StringBuilder();
263 for (Element method : type.getEnclosedElements()) {
264 On oc = method.getAnnotation(On.class);
266 for (String id : oc.id()) {
268 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
272 if (pp.tagNameForId(id) == null) {
273 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
277 ExecutableElement ee = (ExecutableElement)method;
278 StringBuilder params = new StringBuilder();
280 boolean first = true;
281 for (VariableElement ve : ee.getParameters()) {
286 if (ve.asType() == stringType) {
287 if (ve.getSimpleName().contentEquals("id")) {
288 params.append('"').append(id).append('"');
291 params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toString(ev, \"");
292 params.append(ve.getSimpleName().toString());
293 params.append("\")");
296 if (processingEnv.getTypeUtils().getPrimitiveType(TypeKind.DOUBLE) == ve.asType()) {
297 params.append("org.apidesign.bck2brwsr.htmlpage.ConvertTypes.toDouble(ev, \"");
298 params.append(ve.getSimpleName().toString());
299 params.append("\")");
302 String rn = ve.asType().toString();
303 int last = rn.lastIndexOf('.');
305 rn = rn.substring(last + 1);
307 if (rn.equals(className)) {
308 params.append(className).append(".this");
311 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
312 "@On method can only accept String named 'id' or " + className + " arguments",
318 if (!ee.getModifiers().contains(Modifier.STATIC)) {
319 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
323 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
324 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
328 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
329 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
332 append(" case ").append(dispatchCnt).append(": ").
333 append(type.getSimpleName().toString()).
334 append('.').append(ee.getSimpleName()).append("(").
336 append("); break;\n");
343 if (dispatchCnt > 0) {
344 w.append("class OnDispatch implements OnHandler {\n");
345 w.append(" private final int dispatch;\n");
346 w.append(" OnDispatch(int d) { dispatch = d; }\n");
347 w.append(" public void onEvent(Object ev) {\n");
348 w.append(" switch (dispatch) {\n");
361 public Iterable<? extends Completion> getCompletions(
362 Element element, AnnotationMirror annotation,
363 ExecutableElement member, String userText
365 if (!userText.startsWith("\"")) {
366 return Collections.emptyList();
369 Element cls = findClass(element);
370 Page p = cls.getAnnotation(Page.class);
371 String pkg = findPkgName(cls);
374 InputStream is = openStream(pkg, p.xhtml());
375 pp = ProcessPage.readPage(is);
377 } catch (IOException iOException) {
378 return Collections.emptyList();
381 List<Completion> cc = new ArrayList<>();
382 userText = userText.substring(1);
383 for (String id : pp.ids()) {
384 if (id.startsWith(userText)) {
385 cc.add(Completions.of("\"" + id + "\"", id));
391 private static Element findClass(Element e) {
395 Page p = e.getAnnotation(Page.class);
399 return e.getEnclosingElement();
402 private boolean generateProperties(
404 Writer w, Property[] properties,
405 Collection<String> props, Map<String,Collection<String>> deps
406 ) throws IOException {
408 for (Property p : properties) {
410 tn = typeName(where, p);
411 String[] gs = toGetSet(p.name(), tn, p.array());
414 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
416 final Collection<String> dependants = deps.get(p.name());
417 if (dependants != null) {
418 for (String depProp : dependants) {
426 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
427 w.write(" if (locked) throw new IllegalStateException();\n");
428 w.write(" prop_" + p.name() + ".assign(ko);\n");
429 w.write(" return prop_" + p.name() + ";\n");
431 w.write("private Object[] " + gs[0] + "ToArray() {\n");
432 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
435 w.write("private " + tn + " prop_" + p.name() + ";\n");
436 w.write("public " + tn + " " + gs[0] + "() {\n");
437 w.write(" if (locked) throw new IllegalStateException();\n");
438 w.write(" return prop_" + p.name() + ";\n");
440 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
441 w.write(" if (locked) throw new IllegalStateException();\n");
442 w.write(" prop_" + p.name() + " = v;\n");
443 w.write(" if (ko != null) {\n");
444 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
445 final Collection<String> dependants = deps.get(p.name());
446 if (dependants != null) {
447 for (String depProp : dependants) {
448 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
463 private boolean generateComputedProperties(
464 Writer w, Property[] fixedProps,
465 Collection<? extends Element> arr, Collection<String> props,
466 Map<String,Collection<String>> deps
467 ) throws IOException {
469 for (Element e : arr) {
470 if (e.getKind() != ElementKind.METHOD) {
473 if (e.getAnnotation(ComputedProperty.class) == null) {
476 ExecutableElement ee = (ExecutableElement)e;
477 final TypeMirror rt = ee.getReturnType();
478 final Types tu = processingEnv.getTypeUtils();
479 TypeMirror ert = tu.erasure(rt);
480 String tn = ert.toString();
481 boolean array = false;
482 if (tn.equals("java.util.List")) {
486 final String sn = ee.getSimpleName().toString();
487 String[] gs = toGetSet(sn, tn, array);
489 w.write("public " + tn + " " + gs[0] + "() {\n");
490 w.write(" if (locked) throw new IllegalStateException();\n");
492 for (VariableElement pe : ee.getParameters()) {
493 final String dn = pe.getSimpleName().toString();
495 if (!verifyPropName(pe, dn, fixedProps)) {
499 final String dt = pe.asType().toString();
500 String[] call = toGetSet(dn, dt, false);
501 w.write(" " + dt + " arg" + (++arg) + " = ");
502 w.write(call[0] + "();\n");
504 Collection<String> depends = deps.get(dn);
505 if (depends == null) {
506 depends = new LinkedHashSet<>();
507 deps.put(dn, depends);
512 w.write(" locked = true;\n");
513 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
515 for (int i = 1; i <= arg; i++) {
521 w.write(" } finally {\n");
522 w.write(" locked = false;\n");
527 w.write("private Object[] " + gs[0] + "ToArray() {\n");
528 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
531 props.add(e.getSimpleName().toString());
540 private static String[] toGetSet(String name, String type, boolean array) {
541 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
542 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
543 if ("int".equals(type)) {
546 if ("double".equals(type)) {
550 if ("boolean".equals(type)) {
554 final String nu = n.replace('.', '_');
556 return new String[] {
559 "get" + nu + "ToArray___3Ljava_lang_Object_2",
566 pref + nu + "__" + bck2brwsrType,
567 "set" + nu + "__V" + bck2brwsrType
571 private String typeName(Element where, Property p) {
573 boolean isModel = false;
575 ret = p.type().getName();
576 } catch (MirroredTypeException ex) {
577 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
578 final Element e = processingEnv.getTypeUtils().asElement(tm);
579 final Model m = e == null ? null : e.getAnnotation(Model.class);
581 ret = findPkgName(e) + '.' + m.className();
588 String bt = findBoxedType(ret);
593 if (!isModel && !"java.lang.String".equals(ret)) {
594 String bt = findBoxedType(ret);
596 processingEnv.getMessager().printMessage(
597 Diagnostic.Kind.ERROR,
598 "Only primitive types supported in the mapping. Not " + ret,
606 private static String findBoxedType(String ret) {
607 if (ret.equals("boolean")) {
608 return Boolean.class.getName();
610 if (ret.equals("byte")) {
611 return Byte.class.getName();
613 if (ret.equals("short")) {
614 return Short.class.getName();
616 if (ret.equals("char")) {
617 return Character.class.getName();
619 if (ret.equals("int")) {
620 return Integer.class.getName();
622 if (ret.equals("long")) {
623 return Long.class.getName();
625 if (ret.equals("float")) {
626 return Float.class.getName();
628 if (ret.equals("double")) {
629 return Double.class.getName();
634 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
635 StringBuilder sb = new StringBuilder();
637 for (Property property : existingProps) {
638 if (property.name().equals(propName)) {
643 sb.append(property.name());
647 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
648 propName + " is not one of known properties: " + sb
654 private static String findPkgName(Element e) {
656 if (e.getKind() == ElementKind.PACKAGE) {
657 return ((PackageElement)e).getQualifiedName().toString();
659 e = e.getEnclosingElement();