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.TypeMirror;
50 import javax.lang.model.util.Types;
51 import javax.tools.Diagnostic;
52 import javax.tools.FileObject;
53 import javax.tools.StandardLocation;
54 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
55 import org.apidesign.bck2brwsr.htmlpage.api.Model;
56 import org.apidesign.bck2brwsr.htmlpage.api.On;
57 import org.apidesign.bck2brwsr.htmlpage.api.Page;
58 import org.apidesign.bck2brwsr.htmlpage.api.Property;
59 import org.openide.util.lookup.ServiceProvider;
61 /** Annotation processor to process an XHTML page and generate appropriate
64 * @author Jaroslav Tulach <jtulach@netbeans.org>
66 @ServiceProvider(service=Processor.class)
67 @SupportedAnnotationTypes({
68 "org.apidesign.bck2brwsr.htmlpage.api.Model",
69 "org.apidesign.bck2brwsr.htmlpage.api.Page",
70 "org.apidesign.bck2brwsr.htmlpage.api.On"
72 public final class PageProcessor extends AbstractProcessor {
74 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
76 for (Element e : roundEnv.getElementsAnnotatedWith(Model.class)) {
77 if (!processModel(e)) {
81 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
82 if (!processPage(e)) {
89 private InputStream openStream(String pkg, String name) throws IOException {
91 FileObject fo = processingEnv.getFiler().getResource(
92 StandardLocation.SOURCE_PATH, pkg, name);
93 return fo.openInputStream();
94 } catch (IOException ex) {
95 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
99 private boolean processModel(Element e) {
101 Model m = e.getAnnotation(Model.class);
105 String pkg = findPkgName(e);
107 String className = m.className();
109 StringWriter body = new StringWriter();
110 List<String> propsGetSet = new ArrayList<>();
111 Map<String, Collection<String>> propsDeps = new HashMap<>();
112 if (!generateComputedProperties(body, m.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
115 if (!generateProperties(e, body, m.properties(), propsGetSet, propsDeps)) {
118 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
119 w = new OutputStreamWriter(java.openOutputStream());
121 w.append("package " + pkg + ";\n");
122 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
123 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
124 w.append("final class ").append(className).append(" {\n");
125 w.append(" private Object json;\n");
126 w.append(" private boolean locked;\n");
127 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
128 w.append(body.toString());
133 } catch (IOException ex) {
134 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
140 private boolean processPage(Element e) {
142 Page p = e.getAnnotation(Page.class);
146 String pkg = findPkgName(e);
149 try (InputStream is = openStream(pkg, p.xhtml())) {
150 pp = ProcessPage.readPage(is);
152 } catch (IOException iOException) {
153 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
158 String className = p.className();
159 if (className.isEmpty()) {
160 int indx = p.xhtml().indexOf('.');
161 className = p.xhtml().substring(0, indx);
164 StringWriter body = new StringWriter();
165 List<String> propsGetSet = new ArrayList<>();
166 Map<String, Collection<String>> propsDeps = new HashMap<>();
167 if (!generateComputedProperties(body, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
170 if (!generateProperties(e, body, p.properties(), propsGetSet, propsDeps)) {
174 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
175 w = new OutputStreamWriter(java.openOutputStream());
177 w.append("package " + pkg + ";\n");
178 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
179 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
180 w.append("final class ").append(className).append(" {\n");
181 w.append(" private boolean locked;\n");
182 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
185 for (String id : pp.ids()) {
186 String tag = pp.tagNameForId(id);
187 String type = type(tag);
188 w.append(" ").append("public final ").
189 append(type).append(' ').append(cnstnt(id)).append(" = new ").
190 append(type).append("(\"").append(id).append("\");\n");
193 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
194 w.append(body.toString());
195 if (!propsGetSet.isEmpty()) {
196 w.write("public " + className + " applyBindings() {\n");
197 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
198 w.write(className + ".class, this, ");
199 w.write("new String[] {\n");
201 for (String n : propsGetSet) {
206 w.write(" \"" + n + "\"");
210 w.write("\n });\n return this;\n}\n");
212 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
213 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
220 } catch (IOException ex) {
221 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
227 private static String type(String tag) {
228 if (tag.equals("title")) {
231 if (tag.equals("button")) {
234 if (tag.equals("input")) {
237 if (tag.equals("canvas")) {
240 if (tag.equals("img")) {
246 private static String cnstnt(String id) {
247 return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
250 private boolean initializeOnClick(
251 String className, TypeElement type, Writer w, ProcessPage pp
252 ) throws IOException {
254 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
255 { //for (Element clazz : pe.getEnclosedElements()) {
256 // if (clazz.getKind() != ElementKind.CLASS) {
259 w.append(" public ").append(className).append("() {\n");
260 StringBuilder dispatch = new StringBuilder();
262 for (Element method : type.getEnclosedElements()) {
263 On oc = method.getAnnotation(On.class);
265 for (String id : oc.id()) {
267 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
271 if (pp.tagNameForId(id) == null) {
272 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
276 ExecutableElement ee = (ExecutableElement)method;
277 StringBuilder params = new StringBuilder();
279 boolean first = true;
280 for (VariableElement ve : ee.getParameters()) {
285 if (ve.asType() == stringType) {
286 params.append('"').append(id).append('"');
289 String rn = ve.asType().toString();
290 int last = rn.lastIndexOf('.');
292 rn = rn.substring(last + 1);
294 if (rn.equals(className)) {
295 params.append(className).append(".this");
298 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
299 "@On method can only accept String or " + className + " arguments",
305 if (!ee.getModifiers().contains(Modifier.STATIC)) {
306 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
310 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
311 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
315 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
316 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
319 append(" case ").append(dispatchCnt).append(": ").
320 append(type.getSimpleName().toString()).
321 append('.').append(ee.getSimpleName()).append("(").
323 append("); break;\n");
330 if (dispatchCnt > 0) {
331 w.append("class OnDispatch implements Runnable {\n");
332 w.append(" private final int dispatch;\n");
333 w.append(" OnDispatch(int d) { dispatch = d; }\n");
334 w.append(" public void run() {\n");
335 w.append(" switch (dispatch) {\n");
348 public Iterable<? extends Completion> getCompletions(
349 Element element, AnnotationMirror annotation,
350 ExecutableElement member, String userText
352 if (!userText.startsWith("\"")) {
353 return Collections.emptyList();
356 Element cls = findClass(element);
357 Page p = cls.getAnnotation(Page.class);
358 String pkg = findPkgName(cls);
361 InputStream is = openStream(pkg, p.xhtml());
362 pp = ProcessPage.readPage(is);
364 } catch (IOException iOException) {
365 return Collections.emptyList();
368 List<Completion> cc = new ArrayList<>();
369 userText = userText.substring(1);
370 for (String id : pp.ids()) {
371 if (id.startsWith(userText)) {
372 cc.add(Completions.of("\"" + id + "\"", id));
378 private static Element findClass(Element e) {
382 Page p = e.getAnnotation(Page.class);
386 return e.getEnclosingElement();
389 private boolean generateProperties(
391 Writer w, Property[] properties,
392 Collection<String> props, Map<String,Collection<String>> deps
393 ) throws IOException {
395 for (Property p : properties) {
397 tn = typeName(where, p);
398 String[] gs = toGetSet(p.name(), tn, p.array());
401 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
403 final Collection<String> dependants = deps.get(p.name());
404 if (dependants != null) {
405 for (String depProp : dependants) {
413 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
414 w.write(" if (locked) throw new IllegalStateException();\n");
415 w.write(" prop_" + p.name() + ".assign(ko);\n");
416 w.write(" return prop_" + p.name() + ";\n");
418 w.write("private Object[] " + gs[0] + "ToArray() {\n");
419 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
422 w.write("private " + tn + " prop_" + p.name() + ";\n");
423 w.write("public " + tn + " " + gs[0] + "() {\n");
424 w.write(" if (locked) throw new IllegalStateException();\n");
425 w.write(" return prop_" + p.name() + ";\n");
427 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
428 w.write(" if (locked) throw new IllegalStateException();\n");
429 w.write(" prop_" + p.name() + " = v;\n");
430 w.write(" if (ko != null) {\n");
431 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
432 final Collection<String> dependants = deps.get(p.name());
433 if (dependants != null) {
434 for (String depProp : dependants) {
435 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
450 private boolean generateComputedProperties(
451 Writer w, Property[] fixedProps,
452 Collection<? extends Element> arr, Collection<String> props,
453 Map<String,Collection<String>> deps
454 ) throws IOException {
456 for (Element e : arr) {
457 if (e.getKind() != ElementKind.METHOD) {
460 if (e.getAnnotation(ComputedProperty.class) == null) {
463 ExecutableElement ee = (ExecutableElement)e;
464 final TypeMirror rt = ee.getReturnType();
465 final Types tu = processingEnv.getTypeUtils();
466 TypeMirror ert = tu.erasure(rt);
467 String tn = ert.toString();
468 boolean array = false;
469 if (tn.equals("java.util.List")) {
473 final String sn = ee.getSimpleName().toString();
474 String[] gs = toGetSet(sn, tn, array);
476 w.write("public " + tn + " " + gs[0] + "() {\n");
477 w.write(" if (locked) throw new IllegalStateException();\n");
479 for (VariableElement pe : ee.getParameters()) {
480 final String dn = pe.getSimpleName().toString();
482 if (!verifyPropName(pe, dn, fixedProps)) {
486 final String dt = pe.asType().toString();
487 String[] call = toGetSet(dn, dt, false);
488 w.write(" " + dt + " arg" + (++arg) + " = ");
489 w.write(call[0] + "();\n");
491 Collection<String> depends = deps.get(dn);
492 if (depends == null) {
493 depends = new LinkedHashSet<>();
494 deps.put(dn, depends);
499 w.write(" locked = true;\n");
500 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
502 for (int i = 1; i <= arg; i++) {
508 w.write(" } finally {\n");
509 w.write(" locked = false;\n");
514 w.write("private Object[] " + gs[0] + "ToArray() {\n");
515 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
518 props.add(e.getSimpleName().toString());
527 private static String[] toGetSet(String name, String type, boolean array) {
528 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
529 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
530 if ("int".equals(type)) {
533 if ("double".equals(type)) {
537 if ("boolean".equals(type)) {
541 final String nu = n.replace('.', '_');
543 return new String[] {
546 "get" + nu + "ToArray___3Ljava_lang_Object_2",
553 pref + nu + "__" + bck2brwsrType,
554 "set" + nu + "__V" + bck2brwsrType
558 private String typeName(Element where, Property p) {
560 boolean isModel = false;
562 ret = p.type().getName();
563 } catch (MirroredTypeException ex) {
564 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
565 final Element e = processingEnv.getTypeUtils().asElement(tm);
566 final Model m = e == null ? null : e.getAnnotation(Model.class);
568 ret = findPkgName(e) + '.' + m.className();
575 String bt = findBoxedType(ret);
580 if (!isModel && !"java.lang.String".equals(ret)) {
581 String bt = findBoxedType(ret);
583 processingEnv.getMessager().printMessage(
584 Diagnostic.Kind.ERROR,
585 "Only primitive types supported in the mapping. Not " + ret,
593 private static String findBoxedType(String ret) {
594 if (ret.equals("byte")) {
595 return Byte.class.getName();
597 if (ret.equals("short")) {
598 return Short.class.getName();
600 if (ret.equals("char")) {
601 return Character.class.getName();
603 if (ret.equals("int")) {
604 return Integer.class.getName();
606 if (ret.equals("long")) {
607 return Long.class.getName();
609 if (ret.equals("float")) {
610 return Float.class.getName();
612 if (ret.equals("double")) {
613 return Double.class.getName();
618 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
619 StringBuilder sb = new StringBuilder();
621 for (Property property : existingProps) {
622 if (property.name().equals(propName)) {
627 sb.append(property.name());
631 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
632 propName + " is not one of known properties: " + sb
638 private static String findPkgName(Element e) {
640 if (e.getKind() == ElementKind.PACKAGE) {
641 return ((PackageElement)e).getQualifiedName().toString();
643 e = e.getEnclosingElement();