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.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;
58 /** Annotation processor to process an XHTML page and generate appropriate
61 * @author Jaroslav Tulach <jtulach@netbeans.org>
63 @ServiceProvider(service=Processor.class)
64 @SupportedAnnotationTypes({
65 "org.apidesign.bck2brwsr.htmlpage.api.Page",
66 "org.apidesign.bck2brwsr.htmlpage.api.On"
68 public final class PageProcessor extends AbstractProcessor {
70 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
72 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
73 Page p = e.getAnnotation(Page.class);
77 PackageElement pe = (PackageElement)e.getEnclosingElement();
78 String pkg = pe.getQualifiedName().toString();
82 InputStream is = openStream(pkg, p.xhtml());
83 pp = ProcessPage.readPage(is);
85 } catch (IOException iOException) {
86 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
91 String className = p.className();
92 if (className.isEmpty()) {
93 int indx = p.xhtml().indexOf('.');
94 className = p.xhtml().substring(0, indx);
97 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
98 w = new OutputStreamWriter(java.openOutputStream());
100 w.append("package " + pkg + ";\n");
101 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
102 w.append("import org.apidesign.bck2brwsr.htmlpage.KOList;\n");
103 w.append("final class ").append(className).append(" {\n");
104 w.append(" private boolean locked;\n");
105 if (!initializeOnClick(className, (TypeElement) e, w, pp)) {
108 for (String id : pp.ids()) {
109 String tag = pp.tagNameForId(id);
110 String type = type(tag);
111 w.append(" ").append("public final ").
112 append(type).append(' ').append(cnstnt(id)).append(" = new ").
113 append(type).append("(\"").append(id).append("\");\n");
116 List<String> propsGetSet = new ArrayList<String>();
117 Map<String,Collection<String>> propsDeps = new HashMap<String, Collection<String>>();
118 if (!generateComputedProperties(w, p.properties(), e.getEnclosedElements(), propsGetSet, propsDeps)) {
121 generateProperties(w, p.properties(), propsGetSet, propsDeps);
122 w.append(" private org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
123 if (!propsGetSet.isEmpty()) {
124 w.write("public " + className + " applyBindings() {\n");
125 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
126 w.write(className + ".class, this, ");
127 w.write("new String[] {\n");
129 for (String n : propsGetSet) {
134 w.write(" \"" + n + "\"");
138 w.write("\n });\n return this;\n}\n");
140 w.write("public void triggerEvent(Element e, OnEvent ev) {\n");
141 w.write(" org.apidesign.bck2brwsr.htmlpage.Knockout.triggerEvent(e.getId(), ev.getElementPropertyName());\n");
148 } catch (IOException ex) {
149 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
156 private InputStream openStream(String pkg, String name) throws IOException {
158 FileObject fo = processingEnv.getFiler().getResource(
159 StandardLocation.SOURCE_PATH, pkg, name);
160 return fo.openInputStream();
161 } catch (IOException ex) {
162 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
166 private static String type(String tag) {
167 if (tag.equals("title")) {
170 if (tag.equals("button")) {
173 if (tag.equals("input")) {
176 if (tag.equals("canvas")) {
179 if (tag.equals("img")) {
185 private static String cnstnt(String id) {
186 return id.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
189 private boolean initializeOnClick(
190 String className, TypeElement type, Writer w, ProcessPage pp
191 ) throws IOException {
193 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
194 { //for (Element clazz : pe.getEnclosedElements()) {
195 // if (clazz.getKind() != ElementKind.CLASS) {
198 w.append(" public ").append(className).append("() {\n");
199 StringBuilder dispatch = new StringBuilder();
201 for (Element method : type.getEnclosedElements()) {
202 On oc = method.getAnnotation(On.class);
204 for (String id : oc.id()) {
206 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " not found in HTML page.");
210 if (pp.tagNameForId(id) == null) {
211 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
215 ExecutableElement ee = (ExecutableElement)method;
216 StringBuilder params = new StringBuilder();
218 boolean first = true;
219 for (VariableElement ve : ee.getParameters()) {
224 if (ve.asType() == stringType) {
225 params.append('"').append(id).append('"');
228 String rn = ve.asType().toString();
229 int last = rn.lastIndexOf('.');
231 rn = rn.substring(last + 1);
233 if (rn.equals(className)) {
234 params.append(className).append(".this");
237 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
238 "@On method can only accept String or " + className + " arguments",
244 if (!ee.getModifiers().contains(Modifier.STATIC)) {
245 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
249 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
250 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
254 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
255 append(").perform(new OnDispatch(" + dispatchCnt + "));\n");
258 append(" case ").append(dispatchCnt).append(": ").
259 append(type.getSimpleName().toString()).
260 append('.').append(ee.getSimpleName()).append("(").
262 append("); break;\n");
269 if (dispatchCnt > 0) {
270 w.append("class OnDispatch implements Runnable {\n");
271 w.append(" private final int dispatch;\n");
272 w.append(" OnDispatch(int d) { dispatch = d; }\n");
273 w.append(" public void run() {\n");
274 w.append(" switch (dispatch) {\n");
287 public Iterable<? extends Completion> getCompletions(
288 Element element, AnnotationMirror annotation,
289 ExecutableElement member, String userText
291 if (!userText.startsWith("\"")) {
292 return Collections.emptyList();
295 Element cls = findClass(element);
296 Page p = cls.getAnnotation(Page.class);
297 PackageElement pe = (PackageElement) cls.getEnclosingElement();
298 String pkg = pe.getQualifiedName().toString();
301 InputStream is = openStream(pkg, p.xhtml());
302 pp = ProcessPage.readPage(is);
304 } catch (IOException iOException) {
305 return Collections.emptyList();
308 List<Completion> cc = new ArrayList<Completion>();
309 userText = userText.substring(1);
310 for (String id : pp.ids()) {
311 if (id.startsWith(userText)) {
312 cc.add(Completions.of("\"" + id + "\"", id));
318 private static Element findClass(Element e) {
322 Page p = e.getAnnotation(Page.class);
326 return e.getEnclosingElement();
329 private void generateProperties(
330 Writer w, Property[] properties, Collection<String> props,
331 Map<String,Collection<String>> deps
332 ) throws IOException {
333 for (Property p : properties) {
334 final String tn = typeName(p);
335 String[] gs = toGetSet(p.name(), tn, p.array());
338 w.write("private KOList<" + tn + "> prop_" + p.name() + " = new KOList<" + tn + ">(\""
340 final Collection<String> dependants = deps.get(p.name());
341 if (dependants != null) {
342 for (String depProp : dependants) {
350 w.write("public java.util.List<" + tn + "> " + gs[0] + "() {\n");
351 w.write(" if (locked) throw new IllegalStateException();\n");
352 w.write(" prop_" + p.name() + ".assign(ko);\n");
353 w.write(" return prop_" + p.name() + ";\n");
355 w.write("private Object[] " + gs[0] + "ToArray() {\n");
356 w.write(" return " + gs[0] + "().toArray(new Object[0]);\n");
359 w.write("private " + tn + " prop_" + p.name() + ";\n");
360 w.write("public " + tn + " " + gs[0] + "() {\n");
361 w.write(" if (locked) throw new IllegalStateException();\n");
362 w.write(" return prop_" + p.name() + ";\n");
364 w.write("public void " + gs[1] + "(" + tn + " v) {\n");
365 w.write(" if (locked) throw new IllegalStateException();\n");
366 w.write(" prop_" + p.name() + " = v;\n");
367 w.write(" if (ko != null) {\n");
368 w.write(" ko.valueHasMutated(\"" + p.name() + "\");\n");
369 final Collection<String> dependants = deps.get(p.name());
370 if (dependants != null) {
371 for (String depProp : dependants) {
372 w.write(" ko.valueHasMutated(\"" + depProp + "\");\n");
386 private boolean generateComputedProperties(
387 Writer w, Property[] fixedProps,
388 Collection<? extends Element> arr, Collection<String> props,
389 Map<String,Collection<String>> deps
390 ) throws IOException {
392 for (Element e : arr) {
393 if (e.getKind() != ElementKind.METHOD) {
396 if (e.getAnnotation(ComputedProperty.class) == null) {
399 ExecutableElement ee = (ExecutableElement)e;
400 final TypeMirror rt = ee.getReturnType();
401 TypeMirror ert = processingEnv.getTypeUtils().erasure(rt);
402 final String tn = ert.toString();
403 final String sn = ee.getSimpleName().toString();
404 String[] gs = toGetSet(sn, tn, false);
406 w.write("public " + tn + " " + gs[0] + "() {\n");
407 w.write(" if (locked) throw new IllegalStateException();\n");
409 for (VariableElement pe : ee.getParameters()) {
410 final String dn = pe.getSimpleName().toString();
412 if (!verifyPropName(pe, dn, fixedProps)) {
416 final String dt = pe.asType().toString();
417 String[] call = toGetSet(dn, dt, false);
418 w.write(" " + dt + " arg" + (++arg) + " = ");
419 w.write(call[0] + "();\n");
421 Collection<String> depends = deps.get(dn);
422 if (depends == null) {
423 depends = new LinkedHashSet<String>();
424 deps.put(dn, depends);
429 w.write(" locked = true;\n");
430 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
432 for (int i = 1; i <= arg; i++) {
438 w.write(" } finally {\n");
439 w.write(" locked = false;\n");
443 props.add(e.getSimpleName().toString());
452 private static String[] toGetSet(String name, String type, boolean array) {
453 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
454 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
455 if ("int".equals(type)) {
458 if ("double".equals(type)) {
462 if ("boolean".equals(type)) {
466 final String nu = n.replace('.', '_');
468 return new String[] {
471 "get" + nu + "ToArray___3Ljava_lang_Object_2",
478 pref + nu + "__" + bck2brwsrType,
479 "set" + nu + "__V" + bck2brwsrType
483 private String typeName(Property p) {
486 ret = p.type().getName();
487 } catch (MirroredTypeException ex) {
488 TypeMirror tm = processingEnv.getTypeUtils().erasure(ex.getTypeMirror());
492 if (ret.equals("byte")) {
493 return Byte.class.getName();
495 if (ret.equals("short")) {
496 return Short.class.getName();
498 if (ret.equals("char")) {
499 return Character.class.getName();
501 if (ret.equals("int")) {
502 return Integer.class.getName();
504 if (ret.equals("long")) {
505 return Long.class.getName();
507 if (ret.equals("float")) {
508 return Float.class.getName();
510 if (ret.equals("double")) {
511 return Double.class.getName();
517 private boolean verifyPropName(Element e, String propName, Property[] existingProps) {
518 StringBuilder sb = new StringBuilder();
520 for (Property property : existingProps) {
521 if (property.name().equals(propName)) {
526 sb.append(property.name());
530 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
531 propName + " is not one of known properties: " + sb