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.lang.annotation.Annotation;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Locale;
35 import javax.annotation.processing.AbstractProcessor;
36 import javax.annotation.processing.Completion;
37 import javax.annotation.processing.Completions;
38 import javax.annotation.processing.Processor;
39 import javax.annotation.processing.RoundEnvironment;
40 import javax.annotation.processing.SupportedAnnotationTypes;
41 import javax.lang.model.element.AnnotationMirror;
42 import javax.lang.model.element.AnnotationValue;
43 import javax.lang.model.element.Element;
44 import javax.lang.model.element.ElementKind;
45 import javax.lang.model.element.ExecutableElement;
46 import javax.lang.model.element.Modifier;
47 import javax.lang.model.element.PackageElement;
48 import javax.lang.model.element.TypeElement;
49 import javax.lang.model.element.VariableElement;
50 import javax.lang.model.type.MirroredTypeException;
51 import javax.lang.model.type.TypeMirror;
52 import javax.lang.model.util.Types;
53 import javax.tools.Diagnostic;
54 import javax.tools.FileObject;
55 import javax.tools.StandardLocation;
56 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
57 import org.apidesign.bck2brwsr.htmlpage.api.Model;
58 import org.apidesign.bck2brwsr.htmlpage.api.On;
59 import org.apidesign.bck2brwsr.htmlpage.api.Page;
60 import org.apidesign.bck2brwsr.htmlpage.api.Property;
61 import org.openide.util.lookup.ServiceProvider;
63 /** Annotation processor to process an XHTML page and generate appropriate
66 * @author Jaroslav Tulach <jtulach@netbeans.org>
68 @ServiceProvider(service=Processor.class)
69 @SupportedAnnotationTypes({
70 "org.apidesign.bck2brwsr.htmlpage.api.Model",
71 "org.apidesign.bck2brwsr.htmlpage.api.Page",
72 "org.apidesign.bck2brwsr.htmlpage.api.On"
74 public final class PageProcessor extends AbstractProcessor {
76 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
78 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
79 if (!processModel(e)) {
83 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
84 if (!processPage(e)) {
91 private InputStream openStream(String pkg, String name) throws IOException {
93 FileObject fo = processingEnv.getFiler().getResource(
94 StandardLocation.SOURCE_PATH, pkg, name);
95 return fo.openInputStream();
96 } catch (IOException ex) {
97 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
101 private boolean processModel(Element e) {
103 Model m = e.getAnnotation(Model.class);
107 String pkg = findPkgName(e);
109 String className = m.className();
111 StringWriter body = new StringWriter();
112 List<String> propsGetSet = new ArrayList<>();
113 Map<String, Collection<String>> propsDeps = new HashMap<>();
114 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
117 if (!generateProperties(body, m.properties(), propsGetSet, propsDeps)) {
120 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
121 w = new OutputStreamWriter(java.openOutputStream());
123 w.append("package " + pkg + ";\n");
124 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
125 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
126 w.append("final class ").append(className).append(" {\n");
127 w.append(" private Object json;\n");
128 w.append(" private boolean locked;\n");
129 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
130 w.append(body.toString());
135 } catch (IOException ex) {
136 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
142 private boolean processPage(Element e) {
144 Page p = e.getAnnotation(Page.class);
148 String pkg = findPkgName(e);
151 try (InputStream is = openStream(pkg, p.xhtml())) {
152 pp = ProcessPage.readPage(is);
154 } catch (IOException iOException) {
155 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
160 String className = p.className();
161 if (className.isEmpty()) {
162 int indx = p.xhtml().indexOf('.');
163 className = p.xhtml().substring(0, indx);
166 StringWriter body = new StringWriter();
167 List<String> propsGetSet = new ArrayList<>();
168 Map<String, Collection<String>> propsDeps = new HashMap<>();
169 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
172 if (!generateProperties(body, p.properties(), propsGetSet, propsDeps)) {
176 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
177 w = new OutputStreamWriter(java.openOutputStream());
179 w.append("package " + pkg + ";\n");
180 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
181 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
182 w.append("final class ").append(className).append(" {\n");
183 w.append(" private boolean locked;\n");
184 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
187 for (String id : pp.ids()) {
188 String tag = pp.tagNameForId(id);
189 String type = type(tag);
190 w.append(" ").append("public final ").
191 append(type).append(' ').append(cnstnt(id)).append(" = new ").
192 append(type).append("(\"").append(id).append("\");\n");
195 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
196 w.append(body.toString());
197 if (!propsGetSet.isEmpty()) {
198 w.write("public " + className + " applyBindings() {\n");
199 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
200 w.write(className + ".class, this, ");
201 w.write("new String[] {\n");
203 for (String n : propsGetSet) {
208 w.write(" \"" + n + "\"");
212 w.write("\n });\n return this;\n}\n");
214 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
215 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
222 } catch (IOException ex) {
223 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
229 private static String type(String tag) {
230 if (tag.equals("title")) {
233 if (tag.equals("button")) {
236 if (tag.equals("input")) {
239 if (tag.equals("canvas")) {
242 if (tag.equals("img")) {
248 private static String cnstnt(String id) {
249 return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
252 private boolean initializeOnClick(
253 String className, TypeElement type, Writer w, ProcessPage pp
254 ) throws IOException {
256 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
257 { //for (Element clazz : pe.getEnclosedElements()) {
258 // if (clazz.getKind() != ElementKind.CLASS) {
261 w.append(" public ").append(className).append("() {\n");
262 StringBuilder dispatch = new StringBuilder();
264 for (Element method : type.getEnclosedElements()) {
265 On oc = method.getAnnotation(On.class);
267 for (String id : oc.id()) {
269 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
273 if (pp.tagNameForId(id) == null) {
274 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
278 ExecutableElement ee = (ExecutableElement)method;
279 StringBuilder params = new StringBuilder();
281 boolean first = true;
282 for (VariableElement ve : ee.getParameters()) {
287 if (ve.asType() == stringType) {
288 params.append('"').append(id).append('"');
291 String rn = ve.asType().toString();
292 int last = rn.lastIndexOf('.');
294 rn = rn.substring(last + 1);
296 if (rn.equals(className)) {
297 params.append(className).append(".this");
300 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
301 "@On method can only accept String or " + className + " arguments",
307 if (!ee.getModifiers().contains(Modifier.STATIC)) {
308 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
312 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
313 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
317 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
318 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
321 append(" case ").append(dispatchCnt).append(": ").
322 append(type.getSimpleName().toString()).
323 append('.').append(ee.getSimpleName()).append("(").
325 append("); break;\n");
332 if (dispatchCnt > 0) {
333 w.append("class OnDispatch implements Runnable {\n");
334 w.append(" private final int dispatch;\n");
335 w.append(" OnDispatch(int d) { dispatch = d; }\n");
336 w.append(" public void run() {\n");
337 w.append(" switch (dispatch) {\n");
350 public Iterable<? extends Completion> getCompletions(
351 Element element, AnnotationMirror annotation,
352 ExecutableElement member, String userText
354 if (!userText.startsWith("\"")) {
355 return Collections.emptyList();
358 Element cls = findClass(element);
359 Page p = cls.getAnnotation(Page.class);
360 String pkg = findPkgName(cls);
363 InputStream is = openStream(pkg, p.xhtml());
364 pp = ProcessPage.readPage(is);
366 } catch (IOException iOException) {
367 return Collections.emptyList();
370 List<Completion> cc = new ArrayList<>();
371 userText = userText.substring(1);
372 for (String id : pp.ids()) {
373 if (id.startsWith(userText)) {
374 cc.add(Completions.of("\"" + id + "\"", id));
380 private static Element findClass(Element e) {
384 Page p = e.getAnnotation(Page.class);
388 return e.getEnclosingElement();
391 private boolean generateProperties(
392 Writer w, Property[] properties,
393 Collection<String> props, Map<String,Collection<String>> deps
394 ) throws IOException {
396 for (Property p : properties) {
399 String[] gs = toGetSet(p.name(), tn, p.array());
402 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
404 final Collection<String> dependants = deps.get(p.name());
405 if (dependants != null) {
406 for (String depProp : dependants) {
414 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
415 w.write(" if (locked) throw new IllegalStateException();\n");
416 w.write(" prop_" + p.name() + ".assign(ko);\n");
417 w.write(" return prop_" + p.name() + ";\n");
419 w.write("private Object[] " + gs[0] + "ToArray() {\n");
420 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
423 w.write("private " + tn + " prop_" + p.name() + ";\n");
424 w.write("public " + tn + " " + gs[0] + "() {\n");
425 w.write(" if (locked) throw new IllegalStateException();\n");
426 w.write(" return prop_" + p.name() + ";\n");
428 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
429 w.write(" if (locked) throw new IllegalStateException();\n");
430 w.write(" prop_" + p.name() + " = v;\n");
431 w.write(" if (ko != null) {\n");
432 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
433 final Collection<String> dependants = deps.get(p.name());
434 if (dependants != null) {
435 for (String depProp : dependants) {
436 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
451 private boolean generateComputedProperties(
452 Writer w, Property[] fixedProps,
453 Collection<? extends Element> arr, Collection<String> props,
454 Map<String,Collection<String>> deps
455 ) throws IOException {
457 for (Element e : arr) {
458 if (e.getKind() != ElementKind.METHOD) {
461 if (e.getAnnotation(ComputedProperty.class) == null) {
464 ExecutableElement ee = (ExecutableElement)e;
465 final TypeMirror rt = ee.getReturnType();
466 final Types tu = processingEnv.getTypeUtils();
467 TypeMirror ert = tu.erasure(rt);
468 String tn = ert.toString();
469 boolean array = false;
470 if (tn.equals("java.util.List")) {
474 final String sn = ee.getSimpleName().toString();
475 String[] gs = toGetSet(sn, tn, array);
477 w.write("public " + tn + " " + gs[0] + "() {\n");
478 w.write(" if (locked) throw new IllegalStateException();\n");
480 for (VariableElement pe : ee.getParameters()) {
481 final String dn = pe.getSimpleName().toString();
483 if (!verifyPropName(pe, dn, fixedProps)) {
487 final String dt = pe.asType().toString();
488 String[] call = toGetSet(dn, dt, false);
489 w.write(" " + dt + " arg" + (++arg) + " = ");
490 w.write(call[0] + "();\n");
492 Collection<String> depends = deps.get(dn);
493 if (depends == null) {
494 depends = new LinkedHashSet<>();
495 deps.put(dn, depends);
500 w.write(" locked = true;\n");
501 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
503 for (int i = 1; i <= arg; i++) {
509 w.write(" } finally {\n");
510 w.write(" locked = false;\n");
515 w.write("private Object[] " + gs[0] + "ToArray() {\n");
516 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
519 props.add(e.getSimpleName().toString());
528 private static String[] toGetSet(String name, String type, boolean array) {
529 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
530 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
531 if ("int".equals(type)) {
534 if ("double".equals(type)) {
538 if ("boolean".equals(type)) {
542 final String nu = n.replace('.', '_');
544 return new String[] {
547 "get" + nu + "ToArray___3Ljava_lang_Object_2",
554 pref + nu + "__" + bck2brwsrType,
555 "set" + nu + "__V" + bck2brwsrType
559 private String typeName(Property p) {
561 boolean isModel = false;
563 ret = p.type().getName();
564 } catch (MirroredTypeException ex) {
565 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
566 final Element e = processingEnv.getTypeUtils().asElement(tm);
567 final Model m = e == null ? null : e.getAnnotation(Model.class);
569 ret = findPkgName(e) + '.' + m.className();
576 String bt = findBoxedType(ret);
581 if (!isModel && !"java.lang.String".equals(ret)) {
582 String bt = findBoxedType(ret);
584 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Only primitive types supported in the mapping. Not " + ret);
590 private static String findBoxedType(String ret) {
591 if (ret.equals("byte")) {
592 return Byte.class.getName();
594 if (ret.equals("short")) {
595 return Short.class.getName();
597 if (ret.equals("char")) {
598 return Character.class.getName();
600 if (ret.equals("int")) {
601 return Integer.class.getName();
603 if (ret.equals("long")) {
604 return Long.class.getName();
606 if (ret.equals("float")) {
607 return Float.class.getName();
609 if (ret.equals("double")) {
610 return Double.class.getName();
615 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
616 StringBuilder sb = new StringBuilder();
618 for (Property property : existingProps) {
619 if (property.name().equals(propName)) {
624 sb.append(property.name());
628 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
629 propName + " is not one of known properties: " + sb
635 private static String findPkgName(Element e) {
637 if (e.getKind() == ElementKind.PACKAGE) {
638 return ((PackageElement)e).getQualifiedName().toString();
640 e = e.getEnclosingElement();