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.List;
28 import java.util.Locale;
30 import javax.annotation.processing.AbstractProcessor;
31 import javax.annotation.processing.Completion;
32 import javax.annotation.processing.Completions;
33 import javax.annotation.processing.Processor;
34 import javax.annotation.processing.RoundEnvironment;
35 import javax.annotation.processing.SupportedAnnotationTypes;
36 import javax.lang.model.element.AnnotationMirror;
37 import javax.lang.model.element.Element;
38 import javax.lang.model.element.ElementKind;
39 import javax.lang.model.element.ExecutableElement;
40 import javax.lang.model.element.Modifier;
41 import javax.lang.model.element.PackageElement;
42 import javax.lang.model.element.TypeElement;
43 import javax.lang.model.element.VariableElement;
44 import javax.lang.model.type.MirroredTypeException;
45 import javax.lang.model.type.TypeMirror;
46 import javax.tools.Diagnostic;
47 import javax.tools.FileObject;
48 import javax.tools.StandardLocation;
49 import org.apidesign.bck2brwsr.htmlpage.api.ComputedProperty;
50 import org.apidesign.bck2brwsr.htmlpage.api.On;
51 import org.apidesign.bck2brwsr.htmlpage.api.Page;
52 import org.apidesign.bck2brwsr.htmlpage.api.Property;
53 import org.openide.util.lookup.ServiceProvider;
55 /** Annotation processor to process an XHTML page and generate appropriate
58 * @author Jaroslav Tulach <jtulach@netbeans.org>
60 @ServiceProvider(service=Processor.class)
61 @SupportedAnnotationTypes({
62 "org.apidesign.bck2brwsr.htmlpage.api.Page",
63 "org.apidesign.bck2brwsr.htmlpage.api.On"
65 public final class PageProcessor extends AbstractProcessor {
67 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
68 for (Element e : roundEnv.getElementsAnnotatedWith(Page.class)) {
69 Page p = e.getAnnotation(Page.class);
70 PackageElement pe = (PackageElement)e.getEnclosingElement();
71 String pkg = pe.getQualifiedName().toString();
75 InputStream is = openStream(pkg, p.xhtml());
76 pp = ProcessPage.readPage(is);
78 } catch (IOException iOException) {
79 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't read " + p.xhtml(), e);
83 String className = p.className();
84 if (className.isEmpty()) {
85 int indx = p.xhtml().indexOf('.');
86 className = p.xhtml().substring(0, indx);
89 FileObject java = processingEnv.getFiler().createSourceFile(pkg + '.' + className, e);
90 w = new OutputStreamWriter(java.openOutputStream());
92 w.append("package " + pkg + ";\n");
93 w.append("import org.apidesign.bck2brwsr.htmlpage.api.*;\n");
94 w.append("class ").append(className).append(" {\n");
95 w.append(" private ").append(className).append("() {}\n");
96 for (String id : pp.ids()) {
97 String tag = pp.tagNameForId(id);
98 String type = type(tag);
99 w.append(" ").append("public static final ").
100 append(type).append(' ').append(cnstnt(id)).append(" = new ").
101 append(type).append("(\"").append(id).append("\");\n");
103 w.append(" static {\n");
104 if (!initializeOnClick((TypeElement) e, w, pp)) {
108 List<String> propsGetSet = new ArrayList<String>();
109 generateProperties(w, p.properties(), propsGetSet);
110 generateComputedProperties(w, e.getEnclosedElements(), propsGetSet);
111 w.append(" private static org.apidesign.bck2brwsr.htmlpage.Knockout ko;\n");
112 if (!propsGetSet.isEmpty()) {
113 w.write("public static void applyBindings() {\n");
114 w.write(" ko = org.apidesign.bck2brwsr.htmlpage.Knockout.applyBindings(");
115 w.write(className + ".class, new " + className + "(), ");
116 w.write("new String[] {\n");
118 for (String n : propsGetSet) {
123 w.write(" \"" + n + "\"");
127 w.write("\n });\n}\n");
128 //w.write("static { applyBindings(); }\n");
134 } catch (IOException ex) {
135 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Can't create " + className + ".java", e);
142 private InputStream openStream(String pkg, String name) throws IOException {
144 FileObject fo = processingEnv.getFiler().getResource(
145 StandardLocation.SOURCE_PATH, pkg, name);
146 return fo.openInputStream();
147 } catch (IOException ex) {
148 return processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, pkg, name).openInputStream();
152 private static String type(String tag) {
153 if (tag.equals("title")) {
156 if (tag.equals("button")) {
159 if (tag.equals("input")) {
165 private static String cnstnt(String id) {
166 return id.toUpperCase(Locale.ENGLISH).replace('.', '_');
169 private boolean initializeOnClick(TypeElement type, Writer w, ProcessPage pp) throws IOException {
170 TypeMirror stringType = processingEnv.getElementUtils().getTypeElement("java.lang.String").asType();
171 { //for (Element clazz : pe.getEnclosedElements()) {
172 // if (clazz.getKind() != ElementKind.CLASS) {
175 for (Element method : type.getEnclosedElements()) {
176 On oc = method.getAnnotation(On.class);
178 for (String id : oc.id()) {
179 if (pp.tagNameForId(id) == null) {
180 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "id = " + id + " does not exist in the HTML page. Found only " + pp.ids(), method);
183 ExecutableElement ee = (ExecutableElement)method;
185 if (ee.getParameters().isEmpty()) {
188 if (ee.getParameters().size() != 1 || ee.getParameters().get(0).asType() != stringType) {
189 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method should either have no arguments or one String argument", ee);
194 if (!ee.getModifiers().contains(Modifier.STATIC)) {
195 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method has to be static", ee);
198 if (ee.getModifiers().contains(Modifier.PRIVATE)) {
199 processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@On method can't be private", ee);
202 w.append(" OnEvent." + oc.event()).append(".of(").append(cnstnt(id)).
203 append(").perform(new Runnable() { public void run() {\n");
204 w.append(" ").append(type.getSimpleName().toString()).
205 append('.').append(ee.getSimpleName()).append("(");
207 w.append("\"").append(id).append("\"");
219 public Iterable<? extends Completion> getCompletions(
220 Element element, AnnotationMirror annotation,
221 ExecutableElement member, String userText
223 if (!userText.startsWith("\"")) {
224 return Collections.emptyList();
227 Element cls = findClass(element);
228 Page p = cls.getAnnotation(Page.class);
229 PackageElement pe = (PackageElement) cls.getEnclosingElement();
230 String pkg = pe.getQualifiedName().toString();
233 InputStream is = openStream(pkg, p.xhtml());
234 pp = ProcessPage.readPage(is);
236 } catch (IOException iOException) {
237 return Collections.emptyList();
240 List<Completion> cc = new ArrayList<Completion>();
241 userText = userText.substring(1);
242 for (String id : pp.ids()) {
243 if (id.startsWith(userText)) {
244 cc.add(Completions.of("\"" + id + "\"", id));
250 private static Element findClass(Element e) {
254 Page p = e.getAnnotation(Page.class);
258 return e.getEnclosingElement();
261 private static void generateProperties(
262 Writer w, Property[] properties, Collection<String> props
263 ) throws IOException {
264 for (Property p : properties) {
265 final String tn = typeName(p);
266 String[] gs = toGetSet(p.name(), tn);
268 w.write("private static " + tn + " prop_" + p.name() + ";\n");
269 w.write("public static " + tn + " " + gs[0] + "() {\n");
270 w.write(" return prop_" + p.name() + ";\n");
272 w.write("public static void " + gs[1] + "(" + tn + " v) {\n");
273 w.write(" prop_" + p.name() + " = v;\n");
274 w.write(" if (ko != null) ko.valueHasMutated(\"" + p.name() + "\");\n");
283 private void generateComputedProperties(
284 Writer w, Collection<? extends Element> arr, Collection<String> props
285 ) throws IOException {
286 for (Element e : arr) {
287 if (e.getKind() != ElementKind.METHOD) {
290 if (e.getAnnotation(ComputedProperty.class) == null) {
293 ExecutableElement ee = (ExecutableElement)e;
294 final String tn = ee.getReturnType().toString();
295 String[] gs = toGetSet(ee.getSimpleName().toString(), tn);
297 w.write("public static " + tn + " " + gs[0] + "() {\n");
298 w.write(" return " + e.getEnclosingElement().getSimpleName() + '.' + e.getSimpleName() + "(");
300 for (VariableElement pe : ee.getParameters()) {
301 String[] call = toGetSet(pe.getSimpleName().toString(), pe.asType().toString());
303 w.write(call[0] + "()");
309 props.add(e.getSimpleName().toString());
315 private static String[] toGetSet(String name, String type) {
316 String n = Character.toUpperCase(name.charAt(0)) + name.substring(1);
317 String bck2brwsrType = "L" + type.replace('.', '_') + "_2";
318 if ("int".equals(type)) {
321 if ("double".equals(type)) {
325 if ("boolean".equals(type)) {
332 pref + n + "__" + bck2brwsrType,
333 "set" + n + "__V" + bck2brwsrType
337 private static String typeName(Property p) {
339 return p.type().getName();
340 } catch (MirroredTypeException ex) {
341 if (ex.getTypeMirror().getKind().isPrimitive()) {
342 return ex.getTypeMirror().toString();