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.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;
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.lang.model.util.Types;
50 import javax.tools.Diagnostic;
51 import javax.tools.FileObject;
52 import javax.tools.StandardLocation;
53 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
54 import org.apidesign.bck2brwsr.htmlpage.api.On;
55 import org.apidesign.bck2brwsr.htmlpage.api.Page;
56 import org.apidesign.bck2brwsr.htmlpage.api.Property;
57 import org.openide.util.lookup.ServiceProvider;
59 /** Annotation processor to process an XHTML page and generate appropriate
62 * @author Jaroslav Tulach <jtulach@netbeans.org>
64 @ServiceProvider(service=Processor.class)
65 @SupportedAnnotationTypes({
66 "org.apidesign.bck2brwsr.htmlpage.api.Page",
67 "org.apidesign.bck2brwsr.htmlpage.api.On"
69 public final class PageProcessor extends AbstractProcessor {
71 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
73 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
74 Page p = e.getAnnotation(Page.class);
78 PackageElement pe = (PackageElement)e.getEnclosingElement();
79 String pkg = pe.getQualifiedName().toString();
83 InputStream is = openStream(pkg, p.xhtml());
84 pp = ProcessPage.readPage(is);
86 } catch (IOException iOException) {
87 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
92 String className = p.className();
93 if (className.isEmpty()) {
94 int indx = p.xhtml().indexOf('.');
95 className = p.xhtml().substring(0, indx);
98 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
99 w = new OutputStreamWriter(java.openOutputStream());
101 w.append("package " + pkg + ";\n");
102 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
103 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
104 w.append("final class ").append(className).append(" {\n");
105 w.append(" private boolean locked;\n");
106 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
109 for (String id : pp.ids()) {
110 String tag = pp.tagNameForId(id);
111 String type = type(tag);
112 w.append(" ").append("public final ").
113 append(type).append(' ').append(cnstnt(id)).append(" = new ").
114 append(type).append("(\"").append(id).append("\");\n");
117 List<String> propsGetSet = new ArrayList<String>();
118 Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
119 if (!generateComputedProperties(w, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
122 generateProperties(w, p.properties(), propsGetSet, propsDeps);
123 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
124 if (!propsGetSet.isEmpty()) {
125 w.write("public " + className + " applyBindings() {\n");
126 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
127 w.write(className + ".class, this, ");
128 w.write("new String[] {\n");
130 for (String n : propsGetSet) {
135 w.write(" \"" + n + "\"");
139 w.write("\n });\n return this;\n}\n");
141 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
142 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
149 } catch (IOException ex) {
150 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
157 private InputStream openStream(String pkg, String name) throws IOException {
159 FileObject fo = processingEnv.getFiler().getResource(
160 StandardLocation.SOURCE_PATH, pkg, name);
161 return fo.openInputStream();
162 } catch (IOException ex) {
163 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
167 private static String type(String tag) {
168 if (tag.equals("title")) {
171 if (tag.equals("button")) {
174 if (tag.equals("input")) {
177 if (tag.equals("canvas")) {
180 if (tag.equals("img")) {
186 private static String cnstnt(String id) {
187 return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
190 private boolean initializeOnClick(
191 String className, TypeElement type, Writer w, ProcessPage pp
192 ) throws IOException {
194 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
195 { //for (Element clazz : pe.getEnclosedElements()) {
196 // if (clazz.getKind() != ElementKind.CLASS) {
199 w.append(" public ").append(className).append("() {\n");
200 StringBuilder dispatch = new StringBuilder();
202 for (Element method : type.getEnclosedElements()) {
203 On oc = method.getAnnotation(On.class);
205 for (String id : oc.id()) {
207 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
211 if (pp.tagNameForId(id) == null) {
212 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
216 ExecutableElement ee = (ExecutableElement)method;
217 StringBuilder params = new StringBuilder();
219 boolean first = true;
220 for (VariableElement ve : ee.getParameters()) {
225 if (ve.asType() == stringType) {
226 params.append('"').append(id).append('"');
229 String rn = ve.asType().toString();
230 int last = rn.lastIndexOf('.');
232 rn = rn.substring(last + 1);
234 if (rn.equals(className)) {
235 params.append(className).append(".this");
238 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
239 "@On method can only accept String or " + className + " arguments",
245 if (!ee.getModifiers().contains(Modifier.STATIC)) {
246 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
250 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
251 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
255 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
256 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
259 append(" case ").append(dispatchCnt).append(": ").
260 append(type.getSimpleName().toString()).
261 append('.').append(ee.getSimpleName()).append("(").
263 append("); break;\n");
270 if (dispatchCnt > 0) {
271 w.append("class OnDispatch implements Runnable {\n");
272 w.append(" private final int dispatch;\n");
273 w.append(" OnDispatch(int d) { dispatch = d; }\n");
274 w.append(" public void run() {\n");
275 w.append(" switch (dispatch) {\n");
288 public Iterable<? extends Completion> getCompletions(
289 Element element, AnnotationMirror annotation,
290 ExecutableElement member, String userText
292 if (!userText.startsWith("\"")) {
293 return Collections.emptyList();
296 Element cls = findClass(element);
297 Page p = cls.getAnnotation(Page.class);
298 PackageElement pe = (PackageElement) cls.getEnclosingElement();
299 String pkg = pe.getQualifiedName().toString();
302 InputStream is = openStream(pkg, p.xhtml());
303 pp = ProcessPage.readPage(is);
305 } catch (IOException iOException) {
306 return Collections.emptyList();
309 List<Completion> cc = new ArrayList<Completion>();
310 userText = userText.substring(1);
311 for (String id : pp.ids()) {
312 if (id.startsWith(userText)) {
313 cc.add(Completions.of("\"" + id + "\"", id));
319 private static Element findClass(Element e) {
323 Page p = e.getAnnotation(Page.class);
327 return e.getEnclosingElement();
330 private void generateProperties(
331 Writer w, Property[] properties, Collection<String> props,
332 Map<String,Collection<String>> deps
333 ) throws IOException {
334 for (Property p : properties) {
335 final String tn = typeName(p);
336 String[] gs = toGetSet(p.name(), tn, p.array());
339 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
341 final Collection<String> dependants = deps.get(p.name());
342 if (dependants != null) {
343 for (String depProp : dependants) {
351 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
352 w.write(" if (locked) throw new IllegalStateException();\n");
353 w.write(" prop_" + p.name() + ".assign(ko);\n");
354 w.write(" return prop_" + p.name() + ";\n");
356 w.write("private Object[] " + gs[0] + "ToArray() {\n");
357 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
360 w.write("private " + tn + " prop_" + p.name() + ";\n");
361 w.write("public " + tn + " " + gs[0] + "() {\n");
362 w.write(" if (locked) throw new IllegalStateException();\n");
363 w.write(" return prop_" + p.name() + ";\n");
365 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
366 w.write(" if (locked) throw new IllegalStateException();\n");
367 w.write(" prop_" + p.name() + " = v;\n");
368 w.write(" if (ko != null) {\n");
369 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
370 final Collection<String> dependants = deps.get(p.name());
371 if (dependants != null) {
372 for (String depProp : dependants) {
373 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
387 private boolean generateComputedProperties(
388 Writer w, Property[] fixedProps,
389 Collection<? extends Element> arr, Collection<String> props,
390 Map<String,Collection<String>> deps
391 ) throws IOException {
393 for (Element e : arr) {
394 if (e.getKind() != ElementKind.METHOD) {
397 if (e.getAnnotation(ComputedProperty.class) == null) {
400 ExecutableElement ee = (ExecutableElement)e;
401 final TypeMirror rt = ee.getReturnType();
402 final Types tu = processingEnv.getTypeUtils();
403 TypeMirror ert = tu.erasure(rt);
404 String tn = ert.toString();
405 boolean array = false;
406 if (tn.equals("java.util.List")) {
410 final String sn = ee.getSimpleName().toString();
411 String[] gs = toGetSet(sn, tn, array);
413 w.write("public " + tn + " " + gs[0] + "() {\n");
414 w.write(" if (locked) throw new IllegalStateException();\n");
416 for (VariableElement pe : ee.getParameters()) {
417 final String dn = pe.getSimpleName().toString();
419 if (!verifyPropName(pe, dn, fixedProps)) {
423 final String dt = pe.asType().toString();
424 String[] call = toGetSet(dn, dt, false);
425 w.write(" " + dt + " arg" + (++arg) + " = ");
426 w.write(call[0] + "();\n");
428 Collection<String> depends = deps.get(dn);
429 if (depends == null) {
430 depends = new LinkedHashSet<String>();
431 deps.put(dn, depends);
436 w.write(" locked = true;\n");
437 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
439 for (int i = 1; i <= arg; i++) {
445 w.write(" } finally {\n");
446 w.write(" locked = false;\n");
451 w.write("private Object[] " + gs[0] + "ToArray() {\n");
452 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
455 props.add(e.getSimpleName().toString());
464 private static String[] toGetSet(String name, String type, boolean array) {
465 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
466 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
467 if ("int".equals(type)) {
470 if ("double".equals(type)) {
474 if ("boolean".equals(type)) {
478 final String nu = n.replace('.', '_');
480 return new String[] {
483 "get" + nu + "ToArray___3Ljava_lang_Object_2",
490 pref + nu + "__" + bck2brwsrType,
491 "set" + nu + "__V" + bck2brwsrType
495 private String typeName(Property p) {
498 ret = p.type().getName();
499 } catch (MirroredTypeException ex) {
500 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
504 String bt = findBoxedType(ret);
509 if ("java.lang.String".equals(ret)) {
512 String bt = findBoxedType(ret);
516 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Only primitive types supported in the mapping. Not " + ret);
520 private static String findBoxedType(String ret) {
521 if (ret.equals("byte")) {
522 return Byte.class.getName();
524 if (ret.equals("short")) {
525 return Short.class.getName();
527 if (ret.equals("char")) {
528 return Character.class.getName();
530 if (ret.equals("int")) {
531 return Integer.class.getName();
533 if (ret.equals("long")) {
534 return Long.class.getName();
536 if (ret.equals("float")) {
537 return Float.class.getName();
539 if (ret.equals("double")) {
540 return Double.class.getName();
545 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
546 StringBuilder sb = new StringBuilder();
548 for (Property property : existingProps) {
549 if (property.name().equals(propName)) {
554 sb.append(property.name());
558 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
559 propName + " is not one of known properties: " + sb