fragmentClass, Class builderClass) {
25 | super(builderClass);
26 | this.fragmentClass = fragmentClass;
27 | }
28 |
29 | public F instantiate() {
30 | F fragment = null;
31 | try {
32 | fragment = fragmentClass.cast(fragmentClass.newInstance());
33 | } catch (InstantiationException ignored) {
34 | } catch (IllegalAccessException ignored) {
35 | }
36 | setArgs(fragment, getBundle());
37 | return fragment;
38 | }
39 |
40 | protected abstract void setArgs(F fragment, Bundle bundle);
41 |
42 | public Bundle getArgs() {
43 | return getBundle();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GClassMember.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.xkor.genaroid.tree;
17 |
18 | import javax.lang.model.element.Element;
19 |
20 | public abstract class GClassMember extends GElement {
21 | private GClass gClass;
22 | private String signature;
23 |
24 | public GClassMember(GClass gClass, Element element) {
25 | super(element);
26 | this.gClass = gClass;
27 | }
28 |
29 | public static String getMemberSignature(Element element) {
30 | if (element == null) {
31 | return null;
32 | }
33 | return element.toString();
34 | }
35 |
36 | public GClass getGClass() {
37 | return gClass;
38 | }
39 |
40 | @Override
41 | public GUnit getGUnit() {
42 | return gClass.getGUnit();
43 | }
44 |
45 | public String getMemberSignature(){
46 | if (signature == null) {
47 | signature = getMemberSignature(getElement());
48 | }
49 | return signature;
50 | }
51 |
52 | public void setMemberSignature(String signature) {
53 | this.signature = signature;
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/wrap/BaseUiContainerWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.wrap;
18 |
19 | import com.sun.tools.javac.code.Symbol.MethodSymbol;
20 | import com.sun.tools.javac.model.JavacElements;
21 |
22 | public abstract class BaseUiContainerWrapper extends BaseClassWrapper {
23 | protected BaseUiContainerWrapper(JavacElements utils, String classFullName) {
24 | super(utils, classFullName);
25 | }
26 |
27 | public MethodSymbol getOnCreateMethod() {
28 | return (MethodSymbol) getMember("onCreate");
29 | }
30 |
31 | public MethodSymbol getOnStartMethod() {
32 | return (MethodSymbol) getMember("onStart");
33 | }
34 |
35 | public MethodSymbol getOnResumeMethod() {
36 | return (MethodSymbol) getMember("onResume");
37 | }
38 |
39 | public MethodSymbol getOnSaveInstanceStateMethod() {
40 | return (MethodSymbol) getMember("onSaveInstanceState");
41 | }
42 |
43 | public MethodSymbol getOnPauseMethod() {
44 | return (MethodSymbol) getMember("onPause");
45 | }
46 |
47 | public MethodSymbol getOnStopMethod() {
48 | return (MethodSymbol) getMember("onStop");
49 | }
50 |
51 | public MethodSymbol getOnDestroyMethod() {
52 | return (MethodSymbol) getMember("onDestroy");
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/wrap/BaseFragmentWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.wrap;
18 |
19 | import com.sun.tools.javac.code.Symbol.MethodSymbol;
20 | import com.sun.tools.javac.model.JavacElements;
21 |
22 | public abstract class BaseFragmentWrapper extends BaseUiContainerWrapper {
23 | protected BaseFragmentWrapper(JavacElements utils, String classFullName) {
24 | super(utils, classFullName);
25 | }
26 |
27 | public MethodSymbol getOnAttachMethod() {
28 | return (MethodSymbol) getMember("onAttach");
29 | }
30 |
31 | public MethodSymbol getOnCreateViewMethod() {
32 | return (MethodSymbol) getMember("onCreateView");
33 | }
34 |
35 | public MethodSymbol getOnViewCreatedMethod() {
36 | return (MethodSymbol) getMember("onViewCreated");
37 | }
38 |
39 | public MethodSymbol getOnActivityCreatedMethod() {
40 | return (MethodSymbol) getMember("onActivityCreated");
41 | }
42 |
43 | public MethodSymbol getOnRestartMethod() {
44 | return (MethodSymbol) getMember("onRestart");
45 | }
46 |
47 | public MethodSymbol getOnDestroyViewMethod() {
48 | return (MethodSymbol) getMember("onDestroyView");
49 | }
50 |
51 | public MethodSymbol getOnDetachMethod() {
52 | return (MethodSymbol) getMember("onDetach");
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/common/src/main/java/net/xkor/genaroid/annotations/ViewById.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.annotations;
18 |
19 | import android.support.annotation.IdRes;
20 |
21 | import java.lang.annotation.ElementType;
22 | import java.lang.annotation.Retention;
23 | import java.lang.annotation.RetentionPolicy;
24 | import java.lang.annotation.Target;
25 |
26 | /**
27 | *
28 | * Use it on {@link android.view.View} or {@link android.view.View} subtype
29 | * fields in a view related class.
30 | *
31 | *
32 | * The annotation value should be one of R.id.* fields.
33 | *
34 | *
35 | *
36 | * Example :
37 | *
38 | *
39 | * public class MyActivity extends GenaroidActivity {
40 | *
41 | * @ViewById(R.id.myTextView)
42 | * TextView textView;
43 | *
44 | * @Override
45 | * protected void onCreate(Bundle savedInstanceState) {
46 | * super.onCreate(savedInstanceState);
47 | * setContentView(R.layout.my_activity);
48 | * myEditText.setText("Date: " + new Date());
49 | * }
50 | * }
51 | *
52 | *
53 | *
54 | */
55 | @Retention(RetentionPolicy.SOURCE)
56 | @Target(ElementType.FIELD)
57 | public @interface ViewById {
58 | /**
59 | * The R.id.* field which refers to the injected View.
60 | *
61 | * @return the id of the View
62 | */
63 | @IdRes int value();
64 | }
65 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GField.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.xkor.genaroid.tree;
17 |
18 | import com.sun.tools.javac.tree.JCTree.JCModifiers;
19 | import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
20 |
21 | import net.xkor.genaroid.GenaroidEnvironment;
22 |
23 | import javax.lang.model.element.Element;
24 |
25 | public class GField extends GClassMember {
26 | private JCVariableDecl variableDecl;
27 |
28 | public GField(GClass gClass, JCVariableDecl variableDecl, Element element) {
29 | super(gClass, element);
30 | this.variableDecl = variableDecl;
31 | }
32 |
33 | public static GField getGField(GenaroidEnvironment environment, Element element) {
34 | GClass gClass = GClass.getGClass(environment, element.getEnclosingElement());
35 | JCVariableDecl variableDecl = (JCVariableDecl) environment.getUtils().getTree(element);
36 |
37 | String memberName = GClassMember.getMemberSignature(element);
38 | GField field = (GField) gClass.getMember(memberName);
39 | if (field == null) {
40 | field = new GField(gClass, variableDecl, element);
41 | gClass.putMember(field);
42 | }
43 |
44 | return field;
45 | }
46 |
47 | @Override
48 | public JCVariableDecl getTree() {
49 | return variableDecl;
50 | }
51 |
52 | @Override
53 | protected JCModifiers getModifiers() {
54 | return getTree().getModifiers();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/compiler/build.gradle:
--------------------------------------------------------------------------------
1 | Properties properties = new Properties()
2 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
3 | def sdkDir = properties.getProperty('sdk.dir')
4 |
5 | repositories {
6 | maven { url "$sdkDir/extras/android/m2repository/" }
7 | }
8 |
9 | apply plugin: 'java'
10 | apply plugin: 'maven'
11 | apply plugin: 'maven-publish'
12 | apply plugin: 'com.jfrog.bintray'
13 |
14 | sourceSets {
15 | main.java.srcDirs += "$projectDir/../common/src/main/java"
16 | }
17 |
18 | sourceCompatibility = 1.7
19 | targetCompatibility = 1.7
20 |
21 | dependencies {
22 | compile files("${System.properties['java.home']}/../lib/tools.jar")
23 | compile 'com.squareup:javapoet:1.2.0'
24 | compile 'com.android.support:support-annotations:23.4.0'
25 | compile 'com.google.auto.service:auto-service:1.0-rc2'
26 | compile 'org.jetbrains:annotations-java5:15.0'
27 | }
28 |
29 | javadoc {
30 | options {
31 | links "http://docs.oracle.com/javase/7/docs/api/"
32 | linksOffline "http://d.android.com/reference", "$sdkDir/docs/reference"
33 | }
34 | failOnError false
35 | }
36 |
37 | task javadocJar(type: Jar) {
38 | classifier = 'javadoc'
39 | from javadoc
40 | }
41 |
42 | task sourcesJar(type: Jar) {
43 | classifier = 'sources'
44 | from sourceSets.main.allSource
45 | }
46 |
47 | artifacts {
48 | archives sourcesJar, javadocJar
49 | }
50 |
51 | publishing {
52 | publications {
53 | mavenJava(MavenPublication) {
54 | from components.java
55 |
56 | artifact sourcesJar
57 | artifact javadocJar
58 | }
59 | }
60 | }
61 |
62 | bintray {
63 | if (project.hasProperty("bintrayApiKey")) {
64 | user = bintrayUserName
65 | key = bintrayApiKey
66 | }
67 |
68 | publications = ['mavenJava']
69 | publish = true
70 | pkg {
71 | repo = 'maven'
72 | name = 'genaroid:compiler'
73 | websiteUrl = 'https://github.com/ixkor/genaroid'
74 | issueTrackerUrl = ''
75 | vcsUrl = 'https://github.com/ixkor/genaroid.git'
76 | licenses = ['Apache-2.0']
77 | publicDownloadNumbers = true
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/wrap/ActivityWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.wrap;
18 |
19 | import com.sun.tools.javac.code.Symbol;
20 | import com.sun.tools.javac.code.Symbol.MethodSymbol;
21 | import com.sun.tools.javac.model.JavacElements;
22 | import com.sun.tools.javac.util.Filter;
23 |
24 | public class ActivityWrapper extends BaseUiContainerWrapper {
25 | protected ActivityWrapper(JavacElements utils, String classFullName) {
26 | super(utils, classFullName);
27 | }
28 |
29 | public ActivityWrapper(JavacElements utils) {
30 | super(utils, "android.app.Activity");
31 | }
32 |
33 | @Override
34 | public MethodSymbol getOnCreateMethod() {
35 | return (MethodSymbol) getMember("onCreate", new Filter() {
36 | @Override
37 | public boolean accepts(Symbol symbol) {
38 | return symbol.asType().getParameterTypes().size() == 1;
39 | }
40 | });
41 | }
42 |
43 | public MethodSymbol getOnContentChangedMethod() {
44 | return (MethodSymbol) getMember("onContentChanged");
45 | }
46 |
47 | public MethodSymbol getOnRestartMethod() {
48 | return (MethodSymbol) getMember("onRestart");
49 | }
50 |
51 | public MethodSymbol getOnNewIntentMethod() {
52 | return (MethodSymbol) getMember("onNewIntent");
53 | }
54 |
55 | @Override
56 | public MethodSymbol getOnSaveInstanceStateMethod() {
57 | return (MethodSymbol) getMember("onSaveInstanceState", new Filter() {
58 | @Override
59 | public boolean accepts(Symbol symbol) {
60 | return symbol.asType().getParameterTypes().size() == 1;
61 | }
62 | });
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/example/src/main/java/net/xkor/genaroid/example/BaseActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.example;
18 |
19 | import android.accounts.Account;
20 | import android.os.Bundle;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.view.View;
23 |
24 | import net.xkor.genaroid.annotations.BuilderParam;
25 | import net.xkor.genaroid.annotations.GActivity;
26 | import net.xkor.genaroid.annotations.InstanceState;
27 | import net.xkor.genaroid.annotations.ViewById;
28 |
29 | import java.io.Serializable;
30 | import java.util.ArrayList;
31 |
32 | @GActivity(R.layout.activity_main)
33 | public class BaseActivity extends AppCompatActivity {
34 |
35 | @ViewById(R.id.testId)
36 | private View test;
37 |
38 | @ViewById(R.id.testId)
39 | private View test5;
40 |
41 | @InstanceState
42 | private int intField;
43 |
44 | @InstanceState
45 | private String stringField;
46 |
47 | @InstanceState
48 | private int[] intArrayField;
49 |
50 | @InstanceState
51 | private float floatField;
52 |
53 | @InstanceState
54 | private Bundle bundleField;
55 |
56 | @InstanceState
57 | private TestClass serField;
58 |
59 | @InstanceState
60 | private Account accountField;
61 | @InstanceState
62 | private Account[] accountsField;
63 | @InstanceState
64 | private ArrayList accountListField;
65 |
66 | @InstanceState
67 | private ArrayList stringArrayField;
68 |
69 | @BuilderParam(value = "testKey", optional = true)
70 | private int testArg;
71 |
72 | @BuilderParam("testKey2")
73 | private int testArg2;
74 |
75 | @BuilderParam()
76 | private int testArg4;
77 |
78 | private static class TestClass implements Serializable {
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/example/src/main/java/net/xkor/genaroid/example/LoginFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.example;
18 |
19 | import android.os.Bundle;
20 | import android.text.TextUtils;
21 | import android.view.View;
22 | import android.widget.Button;
23 | import android.widget.EditText;
24 | import android.widget.Toast;
25 |
26 | import net.xkor.genaroid.Genaroid;
27 | import net.xkor.genaroid.annotations.BuilderParam;
28 | import net.xkor.genaroid.annotations.GFragment;
29 | import net.xkor.genaroid.annotations.InstanceState;
30 | import net.xkor.genaroid.annotations.OnClick;
31 | import net.xkor.genaroid.annotations.ViewById;
32 |
33 | @GFragment(R.layout.login_fragment)
34 | public class LoginFragment extends BaseFragment {
35 | @BuilderParam()
36 | private String lastLogin;
37 |
38 | @ViewById(R.id.login)
39 | private EditText loginField;
40 | @ViewById(R.id.password)
41 | private EditText passwordField;
42 | @ViewById(R.id.sign_in)
43 | private Button signInButton;
44 |
45 | @InstanceState
46 | private String authError;
47 |
48 | @Override
49 | public void onViewCreated(View view, Bundle savedInstanceState) {
50 | super.onViewCreated(view, savedInstanceState);
51 | loginField.setText(lastLogin);
52 | loginField.setError(authError);
53 | }
54 |
55 | @OnClick(R.id.sign_in)
56 | private void signInClick() {
57 | if (TextUtils.isEmpty(loginField.getText())) {
58 | authError = "Login is empty";
59 | loginField.setError(authError);
60 | }
61 | // do auth...
62 | }
63 |
64 | @OnClick({R.id.login, R.id.password, R.id.sign_in})
65 | private void clickTest(View view) {
66 | Toast.makeText(getActivity(), "clickTest", Toast.LENGTH_LONG).show();
67 | new LoginFragment_BundleBuilderTest_Builder()
68 | .testParam("gfgfdg")
69 | .getBundle();
70 | }
71 |
72 | private class BundleBuilderTest {
73 | @BuilderParam(optional = true)
74 | private String testParam;
75 |
76 | public BundleBuilderTest(Bundle bundle) {
77 | Genaroid.readParams(this, bundle);
78 | }
79 |
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/PluginsManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import net.xkor.genaroid.GenaroidEnvironment;
20 |
21 | import java.util.Collections;
22 | import java.util.HashMap;
23 | import java.util.Iterator;
24 | import java.util.LinkedHashSet;
25 | import java.util.Map;
26 | import java.util.ServiceLoader;
27 | import java.util.Set;
28 |
29 | import javax.tools.Diagnostic;
30 |
31 | public class PluginsManager {
32 |
33 | private final Set plugins = new LinkedHashSet<>();
34 | private final Map, GenaroidPlugin> pluginsMap = new HashMap<>();
35 |
36 | public PluginsManager(GenaroidEnvironment environment) {
37 | ServiceLoader serviceLoader = ServiceLoader.load(GenaroidPlugin.class, GenaroidPlugin.class.getClassLoader());
38 | for (GenaroidPlugin plugin : serviceLoader) {
39 | pluginsMap.put(plugin.getClass(), plugin);
40 | }
41 |
42 | Iterator pluginsIterator = pluginsMap.values().iterator();
43 | while (pluginsIterator.hasNext()) {
44 | GenaroidPlugin plugin = pluginsIterator.next();
45 | try {
46 | plugin.init(this, environment);
47 | } catch (Throwable error) {
48 | pluginsIterator.remove();
49 | environment.getMessager().printMessage(Diagnostic.Kind.ERROR,
50 | "Can not initialize genaroid plugin " + plugin.getClass().getName());
51 | }
52 | }
53 |
54 | for (GenaroidPlugin plugin : pluginsMap.values()) {
55 | addPlugin(plugin);
56 | }
57 | }
58 |
59 | private void addPlugin(GenaroidPlugin plugin) {
60 | if (plugin != null) {
61 | for (Class extends GenaroidPlugin> dependencyClass : plugin.getDependencies()) {
62 | addPlugin(getPlugin(dependencyClass));
63 | }
64 | plugins.add(plugin);
65 | }
66 | }
67 |
68 | public T getPlugin(Class pluginClass) {
69 | return pluginClass.cast(pluginsMap.get(pluginClass));
70 | }
71 |
72 | public Iterable getPlugins() {
73 | return Collections.unmodifiableCollection(plugins);
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/GenaroidPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import net.xkor.genaroid.GenaroidEnvironment;
22 |
23 | import org.jetbrains.annotations.NotNull;
24 | import org.jetbrains.annotations.Nullable;
25 |
26 | import java.lang.annotation.Retention;
27 | import java.lang.annotation.RetentionPolicy;
28 | import java.util.Arrays;
29 | import java.util.Collections;
30 | import java.util.HashSet;
31 | import java.util.Set;
32 |
33 | public abstract class GenaroidPlugin {
34 |
35 | @NotNull
36 | private final Set> dependencies = new HashSet<>();
37 | private PluginsManager pluginsManager;
38 | private GenaroidEnvironment environment;
39 |
40 | public abstract void process();
41 |
42 | @NonNull
43 | public abstract Set getSupportedAnnotationTypes();
44 |
45 | @NotNull
46 | public Set getSupportedOptions() {
47 | return Collections.emptySet();
48 | }
49 |
50 | @NonNull
51 | public final Set> getDependencies() {
52 | return dependencies;
53 | }
54 |
55 | public final void addDependency(@NotNull Class extends GenaroidPlugin> pluginClass) {
56 | dependencies.add(pluginClass);
57 | }
58 |
59 | protected final void init(@NotNull PluginsManager pluginsManager, @NotNull GenaroidEnvironment environment) {
60 | this.pluginsManager = pluginsManager;
61 | this.environment = environment;
62 | Class> clazz = this.getClass();
63 | while (!clazz.equals(GenaroidPlugin.class)) {
64 | Dependencies pluginDependencies = clazz.getAnnotation(Dependencies.class);
65 | if (pluginDependencies != null) {
66 | dependencies.addAll(Arrays.asList(pluginDependencies.value()));
67 | }
68 |
69 | clazz = clazz.getSuperclass();
70 | }
71 | init();
72 | }
73 |
74 | protected void init() {
75 | }
76 |
77 | @Nullable
78 | protected final T getPlugin(Class pluginClass) {
79 | return pluginsManager.getPlugin(pluginClass);
80 | }
81 |
82 | protected GenaroidEnvironment getEnvironment() {
83 | return environment;
84 | }
85 |
86 | @Retention(RetentionPolicy.RUNTIME)
87 | public @interface Dependencies {
88 | Class extends GenaroidPlugin>[] value() default {};
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/core/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.neenbedankt.android-apt'
3 | apply plugin: 'maven'
4 | apply plugin: 'maven-publish'
5 | apply plugin: 'com.jfrog.bintray'
6 |
7 | android {
8 | compileSdkVersion 23
9 | buildToolsVersion "23.0.1"
10 |
11 | defaultConfig {
12 | minSdkVersion 11
13 | }
14 |
15 | sourceCompatibility = 1.7
16 | targetCompatibility = 1.7
17 |
18 | sourceSets {
19 | main.java.srcDirs += "$projectDir/../common/src/main/java"
20 | }
21 | }
22 |
23 | dependencies {
24 | provided 'com.android.support:support-v4:23.1.1'
25 | provided 'com.android.support:support-annotations:23.1.1'
26 | //noinspection GradleDynamicVersion
27 | apt 'net.xkor.genaroid:compiler:+'
28 | }
29 |
30 | task sourcesJar(type: Jar) {
31 | from android.sourceSets.main.java.srcDirs
32 | classifier = 'sources'
33 | }
34 |
35 | afterEvaluate {
36 | javadoc.classpath += files(android.libraryVariants.collect { variant ->
37 | variant.javaCompile.classpath.files
38 | })
39 | }
40 |
41 | task javadoc(type: Javadoc) {
42 | source = android.sourceSets.main.java.srcDirs
43 | exclude '**/BuildConfig.java'
44 | exclude '**/R.java'
45 |
46 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
47 | options {
48 | links "http://docs.oracle.com/javase/7/docs/api/"
49 | linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference"
50 | }
51 | failOnError false
52 | }
53 |
54 | task javadocJar(type: Jar, dependsOn: javadoc) {
55 | classifier = 'javadoc'
56 | from javadoc.destinationDir
57 | }
58 |
59 | artifacts {
60 | archives sourcesJar, javadocJar
61 | }
62 |
63 | publishing {
64 | publications {
65 | mavenJava(MavenPublication) {
66 | artifact sourcesJar
67 | artifact javadocJar
68 |
69 | android.libraryVariants.all { variant ->
70 | def name = variant.buildType.name
71 | if (name.equals(com.android.builder.core.BuilderConstants.DEBUG)) {
72 | return; // Skip debug builds.
73 | }
74 | def task = project.tasks.create "jar${name.capitalize()}", Jar
75 | task.dependsOn variant.javaCompile
76 | task.from variant.javaCompile.destinationDir
77 | task.exclude '**/BuildConfig.class'
78 | artifact task
79 | }
80 | }
81 | }
82 | }
83 |
84 | bintray {
85 | if (project.hasProperty("bintrayApiKey")) {
86 | user = bintrayUserName
87 | key = bintrayApiKey
88 | }
89 |
90 | publications = ['mavenJava']
91 | publish = true
92 | pkg {
93 | repo = 'maven'
94 | name = 'genaroid:core'
95 | websiteUrl = 'https://github.com/ixkor/genaroid'
96 | issueTrackerUrl = ''
97 | vcsUrl = 'https://github.com/ixkor/genaroid.git'
98 | licenses = ['Apache-2.0']
99 | publicDownloadNumbers = true
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | **Genaroid** is an Open Source library that **speeds up** Android development.
4 | It takes care of the **plumbing**, and lets you concentrate on what's really important. By **simplifying** your code, it facilitates its **maintenance**.
5 |
6 | [  ](https://bintray.com/ixkor/maven/genaroid:compiler/_latestVersion)
7 |
8 | Example:
9 | ```java
10 | @GFragment(R.layout.login_fragment)
11 | public class LoginFragment extends BaseFragment {
12 | @BuilderParam
13 | private String lastLogin;
14 |
15 | @ViewById(R.id.login)
16 | private EditText loginField;
17 | @ViewById(R.id.password)
18 | private EditText passwordField;
19 | @ViewById(R.id.sign_in)
20 | private Button signInButton;
21 |
22 | @InstanceState
23 | private String authError;
24 |
25 | @Override
26 | public void onViewCreated(View view, Bundle savedInstanceState) {
27 | super.onViewCreated(view, savedInstanceState);
28 | loginField.setText(lastLogin);
29 | loginField.setError(authError);
30 | }
31 |
32 | @OnClick(R.id.sign_in)
33 | private void signInClick() {
34 | if (TextUtils.isEmpty(loginField.getText())) {
35 | authError = "Login is empty";
36 | loginField.setError(authError);
37 | }
38 | // do auth...
39 | }
40 | }
41 |
42 | // instantiate fragment:
43 | LoginFragment fragment = new LoginFragmentBuilder("last login").instantiate();
44 | ```
45 |
46 | ## Configuration
47 | Gradle:
48 | ```groovy
49 | buildscript {
50 | dependencies {
51 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
52 | }
53 | }
54 |
55 | apply plugin: 'com.neenbedankt.android-apt'
56 |
57 | dependencies {
58 | compile 'net.xkor.genaroid:core:1.3.0'
59 | apt 'net.xkor.genaroid:compiler:1.3.0'
60 | }
61 | ```
62 |
63 | ## Available Annotations:
64 | * [@ViewById](https://github.com/ixkor/genaroid/wiki#viewbyid) - inject view to Activity, Fragment or other object field;
65 | * [@InstanceState](https://github.com/ixkor/genaroid/wiki#instancestate) - save and restore a field value when Activity or Fragment are recreated;
66 | * [@BuilderParam](https://github.com/ixkor/genaroid/wiki#builderparam) - add a field to Activity or Fragment builder;
67 | * [@GActivity and @GFragment](https://github.com/ixkor/genaroid/wiki#gactivity-and-gfragment);
68 | * [@OnClick and other events](https://github.com/ixkor/genaroid/wiki#events);
69 | * [@CustomListener](https://github.com/ixkor/genaroid/wiki#customlistener) - user defined events;
70 |
71 | [Full documentation](https://github.com/ixkor/genaroid/wiki)
72 |
73 | ## License
74 | Copyright 2013 Aleksei Skoriatin
75 |
76 | Licensed under the Apache License, Version 2.0 (the "License");
77 | you may not use this file except in compliance with the License.
78 | You may obtain a copy of the License at
79 |
80 | http://www.apache.org/licenses/LICENSE-2.0
81 |
82 | Unless required by applicable law or agreed to in writing, software
83 | distributed under the License is distributed on an "AS IS" BASIS,
84 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85 | See the License for the specific language governing permissions and
86 | limitations under the License.
87 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GElement.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.tree;
18 |
19 | import com.sun.tools.javac.code.Symbol;
20 | import com.sun.tools.javac.code.Type;
21 | import com.sun.tools.javac.tree.JCTree;
22 | import com.sun.tools.javac.tree.JCTree.JCAnnotation;
23 | import com.sun.tools.javac.tree.JCTree.JCModifiers;
24 |
25 | import net.xkor.genaroid.GenaroidEnvironment;
26 |
27 | import java.lang.annotation.Annotation;
28 |
29 | import javax.lang.model.element.AnnotationMirror;
30 | import javax.lang.model.element.Element;
31 |
32 | public abstract class GElement {
33 | private Element element;
34 | private String name;
35 |
36 | public GElement(Element element) {
37 | this.element = element;
38 | }
39 |
40 | public static String getName(Element element) {
41 | if (element == null) {
42 | return null;
43 | }
44 | return element.getSimpleName().toString();
45 | }
46 |
47 | public Element getElement() {
48 | return element;
49 | }
50 |
51 | public String getName() {
52 | if (name == null) {
53 | name = getName(element);
54 | }
55 | return name;
56 | }
57 |
58 | public void setName(String name) {
59 | this.name = name;
60 | }
61 |
62 | protected GenaroidEnvironment getEnvironment() {
63 | return getGUnit().getEnvironment();
64 | }
65 |
66 | public abstract GUnit getGUnit();
67 |
68 | public abstract JCTree getTree();
69 |
70 | protected abstract JCModifiers getModifiers();
71 |
72 | public JCAnnotation getAnnotation(Symbol.ClassSymbol annotationClass) {
73 | return getEnvironment().findAnnotation(getModifiers(), annotationClass);
74 | }
75 |
76 | public void removeAnnotation(JCAnnotation annotation) {
77 | getEnvironment().removeAnnotation(getModifiers(), annotation);
78 | }
79 |
80 | public JCAnnotation extractAnnotation(Symbol.ClassSymbol annotationClass) {
81 | JCAnnotation annotation = getAnnotation(annotationClass);
82 | if (annotation != null) {
83 | removeAnnotation(annotation);
84 | }
85 | return annotation;
86 | }
87 |
88 | public AnnotationMirror findAnnotationMirror(Type annotationType) {
89 | for (AnnotationMirror mirror : getElement().getAnnotationMirrors()) {
90 | if (mirror.getAnnotationType() == annotationType) {
91 | return mirror;
92 | }
93 | }
94 | return null;
95 | }
96 |
97 | public T getAnnotation(Class annotationClass) {
98 | return getElement().getAnnotation(annotationClass);
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/wrap/BaseClassWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.wrap;
18 |
19 | import com.sun.tools.javac.code.Symbol;
20 | import com.sun.tools.javac.model.JavacElements;
21 | import com.sun.tools.javac.util.Filter;
22 |
23 | import java.util.HashMap;
24 | import java.util.Iterator;
25 |
26 | public class BaseClassWrapper {
27 | private static final Filter noFilter = new Filter() {
28 | public boolean accepts(Symbol var1) {
29 | return true;
30 | }
31 | };
32 | private final JavacElements utils;
33 | private final String classFullName;
34 | private final Symbol.ClassSymbol classSymbol;
35 | private final HashMap membersCache = new HashMap<>();
36 | private final HashMap deepMethodsCache = new HashMap<>();
37 |
38 | public BaseClassWrapper(JavacElements utils, String classFullName) {
39 | this.utils = utils;
40 | this.classFullName = classFullName;
41 | classSymbol = utils.getTypeElement(classFullName);
42 | }
43 |
44 | public String getClassFullName() {
45 | return classFullName;
46 | }
47 |
48 | public Symbol.ClassSymbol getClassSymbol() {
49 | return classSymbol;
50 | }
51 |
52 | protected JavacElements getUtils() {
53 | return utils;
54 | }
55 |
56 | public Symbol getMember(String name) {
57 | return getMember(name, noFilter);
58 | }
59 |
60 | public Symbol getMember(String name, Filter filter) {
61 | Symbol member = membersCache.get(name);
62 | if (member == null) {
63 | Iterator iterator = classSymbol.members().getElementsByName(utils.getName(name), filter).iterator();
64 | if (iterator.hasNext()) {
65 | member = iterator.next();
66 | membersCache.put(name, member);
67 | }
68 | }
69 | return member;
70 | }
71 |
72 | public Symbol.MethodSymbol getMethodRecursive(String name) {
73 | return getMethodRecursive(name, noFilter);
74 | }
75 |
76 | public Symbol.MethodSymbol getMethodRecursive(String name, Filter filter) {
77 | Symbol.MethodSymbol methodSymbol = deepMethodsCache.get(name);
78 | if (methodSymbol == null) {
79 | methodSymbol = (Symbol.MethodSymbol) getMember(name, filter);
80 | }
81 | Symbol.ClassSymbol classSymbol = getClassSymbol();
82 | while (classSymbol != null && methodSymbol == null) {
83 | classSymbol = (Symbol.ClassSymbol) classSymbol.getSuperclass().asElement();
84 | Iterator iterator = classSymbol.members().getElementsByName(utils.getName(name), filter).iterator();
85 | if (iterator.hasNext()) {
86 | methodSymbol = (Symbol.MethodSymbol) iterator.next();
87 | deepMethodsCache.put(name, methodSymbol);
88 | return methodSymbol;
89 | }
90 | }
91 | return methodSymbol;
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/core/src/main/java/net/xkor/genaroid/Genaroid.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid;
18 |
19 | import android.app.Activity;
20 | import android.app.Fragment;
21 | import android.os.Bundle;
22 | import android.support.annotation.LayoutRes;
23 | import android.support.annotation.NonNull;
24 | import android.support.annotation.Nullable;
25 | import android.view.LayoutInflater;
26 | import android.view.View;
27 | import android.view.ViewGroup;
28 |
29 | import net.xkor.genaroid.internal.Bindable;
30 | import net.xkor.genaroid.internal.Inflatable;
31 | import net.xkor.genaroid.internal.Parameterizable;
32 | import net.xkor.genaroid.internal.Restorable;
33 |
34 | public final class Genaroid {
35 | public static void bind(@NonNull Object object, @NonNull View rootView) {
36 | if (object instanceof Bindable) {
37 | ((Bindable) object)._gen_bind(rootView);
38 | }
39 | }
40 |
41 | public static void bind(@NonNull Activity activity) {
42 | bind(activity, activity.findViewById(android.R.id.content));
43 | }
44 |
45 | public static void unbind(@NonNull Object object) {
46 | if (object instanceof Bindable) {
47 | ((Bindable) object)._gen_unbind();
48 | }
49 | }
50 |
51 | public static void saveInstanceState(@NonNull Object object, @NonNull Bundle outState) {
52 | if (object instanceof Restorable) {
53 | ((Restorable) object)._gen_saveInstanceState(outState);
54 | }
55 | }
56 |
57 | public static void restoreInstanceState(@NonNull Object object, @Nullable Bundle savedState) {
58 | if (object instanceof Restorable && savedState != null) {
59 | ((Restorable) object)._gen_restoreInstanceState(savedState);
60 | }
61 | }
62 |
63 | public static void readParams(@NonNull Object object, @Nullable Bundle params) {
64 | if (object instanceof Parameterizable && params != null) {
65 | ((Parameterizable) object)._gen_readParams(params);
66 | }
67 | }
68 |
69 | public static void readParams(@NonNull Activity activity) {
70 | if (activity.getIntent() != null) {
71 | readParams(activity, activity.getIntent().getExtras());
72 | }
73 | }
74 |
75 | public static void readParams(@NonNull Fragment fragment) {
76 | readParams(fragment, fragment.getArguments());
77 | }
78 |
79 | public static void readParams(@NonNull android.support.v4.app.Fragment fragment) {
80 | readParams(fragment, fragment.getArguments());
81 | }
82 |
83 | @LayoutRes
84 | public static int getLayoutId(@NonNull Object object) {
85 | if (object instanceof Inflatable) {
86 | return ((Inflatable) object)._gen_getLayoutId();
87 | }
88 | return 0;
89 | }
90 |
91 | @Nullable
92 | public static View inflate(@NonNull Object fragment, @NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
93 | int layoutId = Genaroid.getLayoutId(fragment);
94 | if (layoutId != 0) {
95 | return inflater.inflate(layoutId, container, false);
96 | } else {
97 | return null;
98 | }
99 | }
100 |
101 | public static void setContentView(@NonNull Activity activity) {
102 | int layoutId = Genaroid.getLayoutId(activity);
103 | if (layoutId != 0) {
104 | activity.setContentView(layoutId);
105 | }
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/ViewByIdPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import com.google.auto.service.AutoService;
22 | import com.sun.tools.javac.code.Symbol;
23 | import com.sun.tools.javac.model.JavacElements;
24 | import com.sun.tools.javac.tree.JCTree;
25 | import com.sun.tools.javac.tree.JCTree.JCAssign;
26 | import com.sun.tools.javac.tree.JCTree.JCExpression;
27 |
28 | import net.xkor.genaroid.annotations.ViewById;
29 | import net.xkor.genaroid.tree.GClass;
30 | import net.xkor.genaroid.tree.GField;
31 | import net.xkor.genaroid.wrap.BindableWrapper;
32 | import net.xkor.genaroid.wrap.ViewWrapper;
33 |
34 | import org.jetbrains.annotations.Nullable;
35 |
36 | import java.util.Collections;
37 | import java.util.HashMap;
38 | import java.util.Map;
39 | import java.util.Set;
40 |
41 | import javax.tools.Diagnostic;
42 |
43 | @AutoService(GenaroidPlugin.class)
44 | public class ViewByIdPlugin extends GenaroidPlugin {
45 |
46 | private static final String ANNOTATION_CLASS_NAME = ViewById.class.getCanonicalName();
47 |
48 | private Map> fieldsMap = new HashMap<>();
49 |
50 | @Override
51 | public void process() {
52 | fieldsMap.clear();
53 |
54 | JavacElements utils = getEnvironment().getUtils();
55 | Symbol.ClassSymbol viewByIdType = utils.getTypeElement(ANNOTATION_CLASS_NAME);
56 | ViewWrapper viewWrapper = new ViewWrapper(utils);
57 | BindableWrapper bindableWrapper = new BindableWrapper(utils);
58 |
59 | Set allFields = getEnvironment().getGElementsAnnotatedWith(ViewById.class, GField.class);
60 | for (GField field : allFields) {
61 | JCTree.JCAnnotation annotation = field.extractAnnotation(viewByIdType);
62 | JCTree fieldType = field.getTree().getType();
63 | JCExpression value = annotation.getArguments().get(0);
64 | if (value instanceof JCAssign) {
65 | value = ((JCAssign) value).rhs;
66 | }
67 | if (!getEnvironment().getTypes().isSubtype(((Symbol.VarSymbol) field.getElement()).asType(), viewWrapper.getClassSymbol().asType())) {
68 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
69 | "Annotation " + viewByIdType.getSimpleName() + " can be applied only to field with type extended of View",
70 | field.getElement());
71 | }
72 |
73 | field.getGClass().implementInBestParent(bindableWrapper.getClassSymbol(), allFields);
74 |
75 | field.getGClass().overrideMethod(bindableWrapper.getBindMethod(), true)
76 | .prependCode("this.%s = (%s) $p0.findViewById(%s);", field.getName(), fieldType, value);
77 | field.getGClass().overrideMethod(bindableWrapper.getUnbindMethod(), true)
78 | .prependCode("this.%s = null;", field.getName());
79 |
80 | Map classFieldsMap = fieldsMap.get(field.getGClass());
81 | if (classFieldsMap == null) {
82 | classFieldsMap = new HashMap<>();
83 | fieldsMap.put(field.getGClass(), classFieldsMap);
84 | }
85 | classFieldsMap.put(value.toString(), field);
86 | }
87 | }
88 |
89 | @Nullable
90 | public GField findFieldForResource(GClass gClass, String resource) {
91 | Map classFieldsMap = fieldsMap.get(gClass);
92 | if (classFieldsMap != null) {
93 | return classFieldsMap.get(resource);
94 | }
95 | return null;
96 | }
97 |
98 | @NonNull
99 | @Override
100 | public Set getSupportedAnnotationTypes() {
101 | return Collections.singleton(ANNOTATION_CLASS_NAME);
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/core/src/main/java/net/xkor/genaroid/builders/IntentBaseBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.builders;
18 |
19 | import android.annotation.TargetApi;
20 | import android.app.Activity;
21 | import android.app.Service;
22 | import android.content.BroadcastReceiver;
23 | import android.content.ComponentName;
24 | import android.content.Context;
25 | import android.content.Intent;
26 | import android.net.Uri;
27 | import android.os.Build;
28 | import android.os.Bundle;
29 |
30 | public class IntentBaseBuilder> extends BundleBaseBuilder {
31 | private Context context;
32 | private Intent intent;
33 |
34 | protected IntentBaseBuilder(Intent intent, Class builderClass) {
35 | super(builderClass);
36 | this.intent = intent;
37 | }
38 |
39 | public T context(Context context) {
40 | this.context = context;
41 | return builderClass.cast(this);
42 | }
43 |
44 | public T action(String action) {
45 | intent.setAction(action);
46 | return builderClass.cast(this);
47 | }
48 |
49 | public T service(Class extends Service> service) {
50 | return setClass(service);
51 | }
52 |
53 | public T activity(Class extends Activity> activity) {
54 | return setClass(activity);
55 | }
56 |
57 | public T receiver(Class extends BroadcastReceiver> receiver) {
58 | return setClass(receiver);
59 | }
60 |
61 | public T component(ComponentName component) {
62 | intent.setComponent(component);
63 | return builderClass.cast(this);
64 | }
65 |
66 | public T className(Context context, String className) {
67 | intent.setClassName(context, className);
68 | this.context = context;
69 | return builderClass.cast(this);
70 | }
71 |
72 | public T className(String packageName, String className) {
73 | intent.setClassName(packageName, className);
74 | return builderClass.cast(this);
75 | }
76 |
77 | public T setPackage(String pack) {
78 | intent.setPackage(pack);
79 | return builderClass.cast(this);
80 | }
81 |
82 | public T flag(int flag) {
83 | return this.flags(flag);
84 | }
85 |
86 | public T flags(int... flags) {
87 | for (int flag : flags) {
88 | intent.addFlags(flag);
89 | }
90 | return builderClass.cast(this);
91 | }
92 |
93 | public T extras(Bundle extras) {
94 | getBundle().putAll(extras);
95 | return builderClass.cast(this);
96 | }
97 |
98 | public T extras(Intent intent) {
99 | getBundle().putAll(intent.getExtras());
100 | return builderClass.cast(this);
101 | }
102 |
103 | public T data(Uri data) {
104 | intent.setData(data);
105 | return builderClass.cast(this);
106 | }
107 |
108 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
109 | public T dataNormalize(Uri data) {
110 | intent.setDataAndNormalize(data);
111 | return builderClass.cast(this);
112 | }
113 |
114 | public T type(String type) {
115 | intent.setType(type);
116 | return builderClass.cast(this);
117 | }
118 |
119 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
120 | public T typeNormalize(String type) {
121 | intent.setTypeAndNormalize(type);
122 | return builderClass.cast(this);
123 | }
124 |
125 | public void start() {
126 | context.startActivity(getIntent());
127 | }
128 |
129 | public void startForResult(Activity activity, int requestCode) {
130 | activity.startActivityForResult(getIntent(), requestCode);
131 | }
132 |
133 | public void startForResult(int requestCode) {
134 | if (context instanceof Activity) {
135 | startForResult((Activity) context, requestCode);
136 | } else {
137 | throw new IllegalArgumentException("Method startForResult(int requestCode) can not be called when context parameter is not Activity.");
138 | }
139 | }
140 |
141 | public Intent getIntent() {
142 | intent.putExtras(getBundle());
143 | return intent;
144 | }
145 |
146 | private T setClass(Class> cls) {
147 | intent.setClass(context, cls);
148 | return builderClass.cast(this);
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/InstanceStatePlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import com.google.auto.service.AutoService;
22 | import com.sun.tools.javac.code.Symbol;
23 | import com.sun.tools.javac.code.Type;
24 | import com.sun.tools.javac.code.Types;
25 | import com.sun.tools.javac.model.JavacElements;
26 | import com.sun.tools.javac.tree.JCTree;
27 |
28 | import net.xkor.genaroid.annotations.InstanceState;
29 | import net.xkor.genaroid.tree.GField;
30 | import net.xkor.genaroid.tree.GMethod;
31 | import net.xkor.genaroid.wrap.BaseClassWrapper;
32 | import net.xkor.genaroid.wrap.BundleWrapper;
33 |
34 | import java.util.Collections;
35 | import java.util.Set;
36 |
37 | import javax.tools.Diagnostic;
38 |
39 | @AutoService(GenaroidPlugin.class)
40 | public class InstanceStatePlugin extends GenaroidPlugin {
41 | private static final String ANNOTATION_CLASS_NAME = InstanceState.class.getCanonicalName();
42 |
43 | @Override
44 | public void process() {
45 | JavacElements utils = getEnvironment().getUtils();
46 | Types types = getEnvironment().getTypes();
47 | Symbol.ClassSymbol instanceStateType = utils.getTypeElement(ANNOTATION_CLASS_NAME);
48 | BundleWrapper bundleWrapper = new BundleWrapper(getEnvironment());
49 | RestorableWrapper restorableWrapper = new RestorableWrapper(utils);
50 |
51 | Set allFields = getEnvironment().getGElementsAnnotatedWith(InstanceState.class, GField.class);
52 | for (GField field : allFields) {
53 | JCTree.JCAnnotation annotation = field.extractAnnotation(instanceStateType);
54 | Type fieldType = ((Symbol.VarSymbol) field.getElement()).asType();
55 | Symbol.MethodSymbol putMethod = bundleWrapper.getMethodForType(fieldType, false);
56 | Symbol.MethodSymbol getMethod = bundleWrapper.getMethodForType(fieldType, true);
57 | String fieldNameInBundle = "_gen_" + field.getGClass().getName() + "_" + field.getName();
58 |
59 | if (putMethod == null || getMethod == null) {
60 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
61 | "Can't found getter and putter for type of field " + field.getName(),
62 | field.getElement());
63 | continue;
64 | }
65 |
66 | field.getGClass().implementInBestParent(restorableWrapper.getClassSymbol(), allFields);
67 |
68 | GMethod onSaveInstanceStateMethod = field.getGClass().overrideMethod(restorableWrapper.getSaveInstanceStateMethod(), true);
69 | onSaveInstanceStateMethod.prependCode("$p0.%s(\"%s\", this.%s);",
70 | putMethod.getSimpleName(), fieldNameInBundle, field.getName());
71 |
72 | GMethod onCreateMethod = field.getGClass().overrideMethod(restorableWrapper.getRestoreInstanceStateMethod(), true);
73 | String methodName = getMethod.getSimpleName().toString();
74 | String template;
75 | if (methodName.equals("getSerializable")) {
76 | template = "this.%s = (%s) $p0.%s(\"%s\");";
77 | } else if (methodName.equals("getParcelableArray")) {
78 | fieldType = types.elemtype(fieldType);
79 | template = "this.%s = net.xkor.genaroid.Utils.castParcelableArray(%s.class, $p0.%s(\"%s\"));";
80 | } else {
81 | template = "this.%s = $p0.%3$s(\"%4$s\");";
82 | }
83 | onCreateMethod.prependCode(template, field.getName(), fieldType, methodName, fieldNameInBundle);
84 | }
85 | }
86 |
87 | @NonNull
88 | @Override
89 | public Set getSupportedAnnotationTypes() {
90 | return Collections.singleton(ANNOTATION_CLASS_NAME);
91 | }
92 |
93 | private class RestorableWrapper extends BaseClassWrapper {
94 | public RestorableWrapper(JavacElements utils) {
95 | super(utils, "net.xkor.genaroid.internal.Restorable");
96 | }
97 |
98 | public Symbol.MethodSymbol getSaveInstanceStateMethod() {
99 | return (Symbol.MethodSymbol) getMember("_gen_saveInstanceState");
100 | }
101 |
102 | public Symbol.MethodSymbol getRestoreInstanceStateMethod() {
103 | return (Symbol.MethodSymbol) getMember("_gen_restoreInstanceState");
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GMethod.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.tree;
18 |
19 | import com.sun.tools.javac.code.Symbol;
20 | import com.sun.tools.javac.tree.JCTree;
21 | import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
22 | import com.sun.tools.javac.tree.JCTree.JCModifiers;
23 | import com.sun.tools.javac.tree.JCTree.JCStatement;
24 | import com.sun.tools.javac.util.List;
25 | import com.sun.tools.javac.util.Name;
26 |
27 | import net.xkor.genaroid.GenaroidEnvironment;
28 |
29 | import javax.lang.model.element.Element;
30 |
31 | public class GMethod extends GClassMember {
32 | JCMethodDecl methodDecl;
33 |
34 | public GMethod(GClass gClass, JCMethodDecl methodDecl, Element element) {
35 | super(gClass, element);
36 | this.methodDecl = methodDecl;
37 | }
38 |
39 | public static GMethod getGMethod(GenaroidEnvironment environment, Element element) {
40 | GClass gClass = GClass.getGClass(environment, element.getEnclosingElement());
41 | JCMethodDecl methodDecl = (JCMethodDecl) environment.getUtils().getTree(element);
42 |
43 | String memberName = GClassMember.getMemberSignature(element);
44 | GMethod method = (GMethod) gClass.getMember(memberName);
45 | if (method == null) {
46 | method = new GMethod(gClass, methodDecl, element);
47 | gClass.putMember(method);
48 | }
49 |
50 | return method;
51 | }
52 |
53 | @Override
54 | public JCMethodDecl getTree() {
55 | return methodDecl;
56 | }
57 |
58 | @Override
59 | public Symbol.MethodSymbol getElement() {
60 | return (Symbol.MethodSymbol) super.getElement();
61 | }
62 |
63 | @Override
64 | protected JCModifiers getModifiers() {
65 | return getTree().getModifiers();
66 | }
67 |
68 | public Name getParamName(int index) {
69 | return methodDecl.getParameters().get(index).getName();
70 | }
71 |
72 | public GMethod appendCode(JCStatement code) {
73 | methodDecl.getBody().stats = methodDecl.getBody().stats.append(code);
74 | return this;
75 | }
76 |
77 | public void appendCodeAfterSuper(JCStatement code) {
78 | String superCall = "super." + getName() + "(";
79 | List newBody = List.nil();
80 | boolean added = false;
81 | for (JCStatement statement : methodDecl.getBody().stats) {
82 | newBody = newBody.append(statement);
83 | if (!added && statement.toString().startsWith(superCall)) {
84 | newBody = newBody.append(code);
85 | added = true;
86 | }
87 | }
88 | methodDecl.getBody().stats = newBody;
89 | }
90 |
91 | public GMethod appendCodeAfterSuper(String code, Object... args) {
92 | appendCodeAfterSuper(codeToStatement(code, args));
93 | return this;
94 | }
95 |
96 | public GMethod appendCode(String code, Object... args) {
97 | appendCode(codeToStatement(code, args));
98 | return this;
99 | }
100 |
101 | private JCStatement codeToStatement(String code, Object[] args) {
102 | for (int i = 0; i < methodDecl.getParameters().size(); i++) {
103 | code = code.replace("$p" + i, getParamName(i));
104 | }
105 | return getEnvironment().createParser(String.format(code, args)).parseStatement();
106 | }
107 |
108 | public GMethod prependCode(JCStatement code) {
109 | methodDecl.getBody().stats = methodDecl.getBody().stats.prepend(code);
110 | return this;
111 | }
112 |
113 | public GMethod prependCode(String code, Object... args) {
114 | prependCode(codeToStatement(code, args));
115 | return this;
116 | }
117 |
118 | public List getBody() {
119 | return methodDecl.getBody().stats;
120 | }
121 |
122 | public void setBody(List body) {
123 | methodDecl.getBody().stats = body;
124 | }
125 |
126 | public GMethod appendSuperCall() {
127 | StringBuilder superCallSource = new StringBuilder("super.");
128 | superCallSource.append(getName());
129 | superCallSource.append("(");
130 |
131 | for (JCTree.JCVariableDecl param : methodDecl.getParameters()) {
132 | if (superCallSource.charAt(superCallSource.length() - 1) != '(') {
133 | superCallSource.append(", ");
134 | }
135 | superCallSource.append(param.getName());
136 | }
137 | superCallSource.append(");");
138 |
139 | appendCode(superCallSource.toString());
140 | return this;
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/GenaroidProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid;
18 |
19 | import com.google.auto.service.AutoService;
20 | import com.sun.tools.javac.util.List;
21 |
22 | import net.xkor.genaroid.plugins.GenaroidPlugin;
23 | import net.xkor.genaroid.plugins.PluginsManager;
24 | import net.xkor.genaroid.tree.GUnit;
25 |
26 | import java.io.IOException;
27 | import java.io.Writer;
28 | import java.util.HashSet;
29 | import java.util.Set;
30 |
31 | import javax.annotation.processing.AbstractProcessor;
32 | import javax.annotation.processing.ProcessingEnvironment;
33 | import javax.annotation.processing.Processor;
34 | import javax.annotation.processing.RoundEnvironment;
35 | import javax.lang.model.SourceVersion;
36 | import javax.lang.model.element.TypeElement;
37 | import javax.tools.Diagnostic;
38 | import javax.tools.JavaFileObject;
39 |
40 | @AutoService(Processor.class)
41 | public class GenaroidProcessor extends AbstractProcessor {
42 | private int counter = 0;
43 | private GenaroidEnvironment genaroidEnvironment = new GenaroidEnvironment();
44 | private PluginsManager pluginsManager;
45 |
46 | @Override
47 | public void init(ProcessingEnvironment procEnv) {
48 | super.init(procEnv);
49 | genaroidEnvironment.init(procEnv);
50 | pluginsManager = new PluginsManager(genaroidEnvironment);
51 | }
52 |
53 | @Override
54 | public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
55 | if (annotations == null || annotations.isEmpty() || counter > 0) {
56 | return false;
57 | }
58 | counter++;
59 | genaroidEnvironment.setRoundEnvironment(roundEnv);
60 |
61 | try {
62 | long startTime = System.currentTimeMillis();
63 | for (GenaroidPlugin plugin : pluginsManager.getPlugins()) {
64 | long pluginStartTime = System.currentTimeMillis();
65 | plugin.process();
66 | if (genaroidEnvironment.isDebugMode()) {
67 | long processTime = System.currentTimeMillis() - pluginStartTime;
68 | processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, plugin.getClass().getSimpleName() + " time: " + processTime + "ms");
69 | }
70 | }
71 | if (genaroidEnvironment.isDebugMode()) {
72 | long processTime = System.currentTimeMillis() - startTime;
73 | processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Genaroid process time: " + processTime + "ms");
74 |
75 | for (GUnit unit : genaroidEnvironment.getUnits()) {
76 | try {
77 | JavaFileObject source = processingEnv.getFiler().createSourceFile(
78 | unit.getCompilationUnit().getPackageName() + "." + unit.getName());
79 | Writer writer = source.openWriter();
80 | writer.write(getUnitSourceString(unit));
81 | writer.flush();
82 | writer.close();
83 | unit.getCompilationUnit().defs = List.nil();
84 | } catch (IOException error) {
85 | processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, Utils.getStackTrace(error));
86 | }
87 | }
88 | }
89 | } catch (Throwable e) {
90 | processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, Utils.getStackTrace(e));
91 | return false;
92 | }
93 |
94 | return true;
95 | }
96 |
97 | private String getUnitSourceString(GUnit unit) {
98 | return unit.getCompilationUnit().toString()
99 | // remove empty constructors
100 | .replaceAll("\\s*(public|private)\\s+\\w*\\(\\)\\s*\\{\\s*super\\(\\);\\s*\\}", "");
101 | }
102 |
103 | @Override
104 | public Set getSupportedAnnotationTypes() {
105 | HashSet types = new HashSet<>();
106 | for (GenaroidPlugin processor : pluginsManager.getPlugins()) {
107 | types.addAll(processor.getSupportedAnnotationTypes());
108 | }
109 | return types;
110 | }
111 |
112 | @Override
113 | public SourceVersion getSupportedSourceVersion() {
114 | return SourceVersion.latestSupported();
115 | }
116 |
117 | @Override
118 | public Set getSupportedOptions() {
119 | HashSet types = new HashSet<>();
120 | types.add(GenaroidEnvironment.DEBUG_MODE_OPTION_NAME);
121 | for (GenaroidPlugin processor : pluginsManager.getPlugins()) {
122 | types.addAll(processor.getSupportedOptions());
123 | }
124 | return types;
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/wrap/BundleWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.wrap;
18 |
19 | import com.sun.tools.javac.code.Symbol;
20 | import com.sun.tools.javac.code.Symbol.MethodSymbol;
21 | import com.sun.tools.javac.code.Type;
22 | import com.sun.tools.javac.code.Types;
23 | import com.sun.tools.javac.tree.JCTree;
24 | import com.sun.tools.javac.util.Name;
25 |
26 | import net.xkor.genaroid.GenaroidEnvironment;
27 | import net.xkor.genaroid.tree.GField;
28 |
29 | import java.util.HashSet;
30 |
31 | public class BundleWrapper extends BaseClassWrapper {
32 | private final Types types;
33 | private final GenaroidEnvironment environment;
34 | private final HashSet classes = new HashSet<>();
35 | private final Type parcelableType;
36 | private final Type serializableType;
37 | private final Type arrayListType;
38 | private final Type sparseArrayType;
39 |
40 | public BundleWrapper(GenaroidEnvironment environment) {
41 | super(environment.getUtils(), "android.os.Bundle");
42 | this.environment = environment;
43 | types = environment.getTypes();
44 |
45 | addType("java.lang.String");
46 | addType("java.lang.Integer");
47 | addType("java.lang.CharSequence");
48 | addType("android.os.Bundle");
49 | addType("android.util.Size");
50 | addType("android.util.SizeF");
51 |
52 | parcelableType = getType("android.os.Parcelable");
53 | serializableType = getType("java.io.Serializable");
54 | arrayListType = getType("java.util.ArrayList");
55 | sparseArrayType = getType("android.util.SparseArray");
56 | }
57 |
58 | private void addType(String typeName) {
59 | classes.add(getType(typeName));
60 | }
61 |
62 | private Type getType(String typeName) {
63 | return getUtils().getTypeElement(typeName).asType();
64 | }
65 |
66 | public MethodSymbol getMethodForType(Type fieldType, boolean isGetter) {
67 | String prefix = isGetter ? "get" : "put";
68 | if (types.isArray(fieldType)) {
69 | return getMethod(types.elemtype(fieldType), prefix, "Array");
70 | } else if (types.isSameType(fieldType.asElement().asType(), arrayListType)) {
71 | return getMethod(fieldType.getTypeArguments().get(0), prefix, "ArrayList");
72 | } else if (types.isSameType(fieldType.asElement().asType(), sparseArrayType)) {
73 | Type typeArg = fieldType.getTypeArguments().get(0);
74 | if (types.isSubtype(typeArg, parcelableType)) {
75 | return getMethodRecursive(prefix + "SparseParcelableArray");
76 | }
77 | } else {
78 | return getMethod(fieldType, prefix, "");
79 | }
80 | return null;
81 | }
82 |
83 | private Type findBundleType(Type type) {
84 | if (type.isPrimitive()) {
85 | return type;
86 | } else {
87 | if (classes.contains(type)) {
88 | return type;
89 | } else if (types.isSubtype(type, parcelableType)) {
90 | return parcelableType;
91 | } else if (types.isSubtype(type, serializableType)) {
92 | return serializableType;
93 | }
94 | }
95 | return null;
96 | }
97 |
98 | public MethodSymbol getMethod(Type type, String prefix, String suffix) {
99 | type = findBundleType(type);
100 | if (type == null) {
101 | return null;
102 | }
103 |
104 | String typeName = type.asElement().getSimpleName().toString();
105 | String mainNamePart;
106 | if (type.isPrimitive()) {
107 | mainNamePart = Character.toString(typeName.charAt(0)).toUpperCase() + typeName.substring(1);
108 | } else {
109 | mainNamePart = typeName;
110 | }
111 | return getMethodRecursive(prefix + mainNamePart + suffix);
112 | }
113 |
114 | public JCTree.JCStatement getReadStatement(GField field, String fieldNameInBundle, Name bundleParam) {
115 | Type fieldType = ((Symbol.VarSymbol) field.getElement()).asType();
116 | Symbol.MethodSymbol getMethod = getMethodForType(fieldType, true);
117 | String methodName = getMethod.getSimpleName().toString();
118 | String template;
119 | if (methodName.equals("getSerializable")) {
120 | template = "this.%1$s = (%2$s) %3$s.%4$s(%5$s);";
121 | } else if (methodName.equals("getParcelableArray")) {
122 | fieldType = types.elemtype(fieldType);
123 | template = "this.%1$s = net.xkor.genaroid.Utils.castParcelableArray(%2$s.class, %3$s.%4$s(%5$s));";
124 | } else {
125 | template = "this.%1$s = %3$s.%4$s(%5$s);";
126 | }
127 | template = "if (%3$s.containsKey(%5$s)) {\n" + template + "\n}";
128 | String restoreCode = String.format(
129 | template, field.getName(), fieldType, bundleParam, methodName, fieldNameInBundle);
130 | return environment.createParser(restoreCode).parseStatement();
131 | }
132 |
133 | }
134 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/GActivityPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import com.google.auto.service.AutoService;
22 | import com.sun.tools.javac.code.Symbol;
23 | import com.sun.tools.javac.model.JavacElements;
24 | import com.sun.tools.javac.tree.JCTree;
25 |
26 | import net.xkor.genaroid.GenaroidEnvironment;
27 | import net.xkor.genaroid.annotations.GActivity;
28 | import net.xkor.genaroid.annotations.InjectGenaroidCall;
29 | import net.xkor.genaroid.tree.GClass;
30 | import net.xkor.genaroid.tree.GMethod;
31 | import net.xkor.genaroid.wrap.ActivityWrapper;
32 | import net.xkor.genaroid.wrap.InflatableWrapper;
33 |
34 | import java.util.ArrayList;
35 | import java.util.Collections;
36 | import java.util.Set;
37 |
38 | import javax.tools.Diagnostic;
39 |
40 | @AutoService(GenaroidPlugin.class)
41 | public class GActivityPlugin extends GenaroidPlugin {
42 |
43 | private static final String ANNOTATION_CLASS_NAME = GActivity.class.getCanonicalName();
44 | private ArrayList sortedActivities;
45 |
46 | public java.util.List getActivities() {
47 | return sortedActivities;
48 | }
49 |
50 | @Override
51 | public void process() {
52 | JavacElements utils = getEnvironment().getUtils();
53 | Symbol.ClassSymbol instanceStateType = utils.getTypeElement(ANNOTATION_CLASS_NAME);
54 | ActivityWrapper activityWrapper = new ActivityWrapper(utils);
55 | InflatableWrapper inflatableWrapper = new InflatableWrapper(utils);
56 |
57 | Set activities = getEnvironment().getGElementsAnnotatedWith(GActivity.class, GClass.class);
58 | sortedActivities = new ArrayList<>(activities);
59 | Collections.sort(sortedActivities, GClass.HIERARCHY_LEVEL_COMPARATOR);
60 |
61 | for (GClass activity : activities) {
62 | JCTree.JCAnnotation jcAnnotation = activity.extractAnnotation(instanceStateType);
63 | GActivity annotation = activity.getAnnotation(GActivity.class);
64 |
65 | if (!activity.isSubClass(activityWrapper.getClassSymbol())) {
66 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
67 | "Annotation " + instanceStateType.getSimpleName() + " can be applied only to subclasses of Activity",
68 | activity.getElement());
69 | continue;
70 | }
71 |
72 | if (annotation.value() != 0) {
73 | String layoutId = String.valueOf(annotation.value());
74 | for (JCTree.JCExpression value : jcAnnotation.getArguments()) {
75 | if (value instanceof JCTree.JCAssign) {
76 | if (((JCTree.JCAssign) value).lhs.toString().equals("value")) {
77 | layoutId = ((JCTree.JCAssign) value).rhs.toString();
78 | }
79 | } else {
80 | layoutId = value.toString();
81 | }
82 | }
83 |
84 | activity.implementIfNeeded(inflatableWrapper.getClassSymbol());
85 | activity.overrideMethod(inflatableWrapper.getGetLayoutIdMethod(), false)
86 | .appendCode("return %s;", layoutId);
87 | }
88 |
89 | if (activity.isBaseWithAnnotation(GActivity.class)) {
90 | activity.getGUnit().addNewImports(GenaroidEnvironment.GENAROID_MAIN_CLASS);
91 | GMethod onCreateMethod = activity.overrideMethod(activityWrapper.getOnCreateMethod(), true);
92 |
93 | if ((annotation.injectCalls() & InjectGenaroidCall.INSTANCE_STATE) != 0) {
94 | activity.overrideMethod(activityWrapper.getOnSaveInstanceStateMethod(), true)
95 | .appendCode("Genaroid.saveInstanceState(this, $p0);");
96 | onCreateMethod.prependCode("Genaroid.restoreInstanceState(this, $p0);");
97 | }
98 |
99 | if ((annotation.injectCalls() & InjectGenaroidCall.BIND) != 0) {
100 | activity.overrideMethod(activityWrapper.getOnContentChangedMethod(), true)
101 | .appendCode("Genaroid.bind(this);");
102 | }
103 |
104 | if ((annotation.injectCalls() & InjectGenaroidCall.READ_PARAMS) != 0) {
105 | onCreateMethod.prependCode("Genaroid.readParams(this);");
106 | activity.overrideMethod(activityWrapper.getOnNewIntentMethod(), true)
107 | .appendCode("Genaroid.readParams(this, $p0.getExtras());");
108 | }
109 |
110 | if ((annotation.injectCalls() & InjectGenaroidCall.INFLATE_LAYOUT) != 0) {
111 | onCreateMethod.appendCodeAfterSuper("Genaroid.setContentView(this);");
112 | }
113 | }
114 | }
115 | }
116 |
117 | @NonNull
118 | @Override
119 | public Set getSupportedAnnotationTypes() {
120 | return Collections.singleton(ANNOTATION_CLASS_NAME);
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GUnit.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.tree;
18 |
19 | import com.sun.tools.javac.tree.JCTree;
20 | import com.sun.tools.javac.tree.JCTree.JCClassDecl;
21 | import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
22 | import com.sun.tools.javac.tree.JCTree.JCImport;
23 | import com.sun.tools.javac.tree.TreeMaker;
24 | import com.sun.tools.javac.util.List;
25 | import com.sun.tools.javac.util.Pair;
26 |
27 | import net.xkor.genaroid.GenaroidEnvironment;
28 |
29 | import java.util.Collection;
30 | import java.util.HashMap;
31 |
32 | import javax.lang.model.element.Element;
33 | import javax.lang.model.element.Modifier;
34 |
35 | public class GUnit {
36 | private static final String ANONYMOUS_CLASS_PREFIX = "__fake__";
37 |
38 | private JCCompilationUnit compilationUnit;
39 | private GenaroidEnvironment environment;
40 | private HashMap classes = new HashMap<>();
41 |
42 | public GUnit(JCCompilationUnit compilationUnit, GenaroidEnvironment environment) {
43 | this.compilationUnit = compilationUnit;
44 | this.environment = environment;
45 | }
46 |
47 | @SafeVarargs
48 | private static List mergeImports(List mergedImports, List... importLists) {
49 | for (List imports : importLists) {
50 | for (JCImport imp : imports) {
51 | mergedImports = appendImport(mergedImports, imp);
52 | }
53 | }
54 | return mergedImports;
55 | }
56 |
57 | private static List appendImport(List imports, JCImport addImport) {
58 | for (JCImport imp : imports) {
59 | if (imp.toString().equals(addImport.toString())) {
60 | return imports;
61 | }
62 | }
63 | return imports.append(addImport);
64 | }
65 |
66 | public static GUnit getGUnit(GenaroidEnvironment environment, Element element) {
67 | Pair pair = environment.getTreeAndTopLevel(element);
68 | GUnit unit = environment.getUnit(pair.snd.getSourceFile().getName());
69 | if (unit == null) {
70 | unit = new GUnit(pair.snd, environment);
71 | environment.putUnit(unit);
72 | }
73 | return unit;
74 | }
75 |
76 | public static GUnit findGUnit(GenaroidEnvironment environment, Element element) {
77 | Pair pair = environment.getTreeAndTopLevel(element);
78 | return pair == null ? null : environment.getUnit(pair.snd.getSourceFile().getName());
79 | }
80 |
81 | public Collection getGClasses() {
82 | return classes.values();
83 | }
84 |
85 | public GClass getGClass(String className) {
86 | return classes.get(className);
87 | }
88 |
89 | public void putGClass(GClass gClass) {
90 | classes.put(gClass.getName(), gClass);
91 | }
92 |
93 | public JCCompilationUnit getCompilationUnit() {
94 | return compilationUnit;
95 | }
96 |
97 | public GenaroidEnvironment getEnvironment() {
98 | return environment;
99 | }
100 |
101 | public GClass createAnonymousClass(JCClassDecl owner) {
102 | TreeMaker maker = environment.getMaker().at(owner.getStartPosition());
103 | JCClassDecl classDecl = maker.AnonymousClassDef(maker.Modifiers(0), List.nil());
104 | return new GClass(this, classDecl, null);
105 | }
106 |
107 | // public GClass createOrGetAnonymousClass(String tag) {
108 | // String className = ANONYMOUS_CLASS_PREFIX + tag;
109 | // GClass gClass = getGClass(className);
110 | // if (gClass == null) {
111 | // gClass = createAnonymousClass();
112 | // gClass.setName(className);
113 | // putGClass(gClass);
114 | // }
115 | // return gClass;
116 | // }
117 | //
118 | // public GClass findAnonymousClass(String tag) {
119 | // String className = ANONYMOUS_CLASS_PREFIX + tag;
120 | // return getGClass(className);
121 | // }
122 |
123 | public void addNewImports(List newImports) {
124 | List defs = List.nil();
125 | defs = defs.appendList(List.convert(JCTree.class, mergeImports(compilationUnit.getImports(), newImports)));
126 | defs = defs.appendList(compilationUnit.getTypeDecls());
127 | compilationUnit.defs = defs;
128 | }
129 |
130 | public void addNewImports(String... imports) {
131 | TreeMaker maker = environment.getMaker();
132 | List newImports = List.nil();
133 | for (String newImport : imports) {
134 | newImports = newImports.append(maker.Import(environment.createParser(newImport).parseType(), false));
135 | }
136 |
137 | addNewImports(newImports);
138 | }
139 |
140 | public String getName() {
141 | for (JCTree type : compilationUnit.getTypeDecls()) {
142 | if (type instanceof JCClassDecl && ((JCClassDecl) type).getModifiers().getFlags().contains(Modifier.PUBLIC)) {
143 | return ((JCClassDecl) type).getSimpleName().toString();
144 | }
145 | }
146 | return null;
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/core/src/main/java/net/xkor/genaroid/builders/BundleBaseBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.builders;
18 |
19 | import android.os.Bundle;
20 | import android.os.Parcelable;
21 |
22 | import java.io.Serializable;
23 | import java.util.ArrayList;
24 |
25 | public class BundleBaseBuilder> {
26 | protected final Class builderClass;
27 | private Bundle bundle = new Bundle();
28 |
29 | protected BundleBaseBuilder(Class builderClass) {
30 | this.builderClass = builderClass;
31 | }
32 |
33 | public T put(String key, boolean value) {
34 | bundle.putBoolean(key, value);
35 | return builderClass.cast(this);
36 | }
37 |
38 | public T put(String key, byte value) {
39 | bundle.putByte(key, value);
40 | return builderClass.cast(this);
41 | }
42 |
43 | public T put(String key, char value) {
44 | bundle.putChar(key, value);
45 | return builderClass.cast(this);
46 | }
47 |
48 | public T put(String key, double value) {
49 | bundle.putDouble(key, value);
50 | return builderClass.cast(this);
51 | }
52 |
53 | public T put(String key, float value) {
54 | bundle.putFloat(key, value);
55 | return builderClass.cast(this);
56 | }
57 |
58 | public T put(String key, int value) {
59 | bundle.putInt(key, value);
60 | return builderClass.cast(this);
61 | }
62 |
63 | public T put(String key, long value) {
64 | bundle.putLong(key, value);
65 | return builderClass.cast(this);
66 | }
67 |
68 | public T put(String key, short value) {
69 | bundle.putShort(key, value);
70 | return builderClass.cast(this);
71 | }
72 |
73 | public T put(String key, String value) {
74 | bundle.putString(key, value);
75 | return builderClass.cast(this);
76 | }
77 |
78 | public T put(String key, byte[] value) {
79 | bundle.putByteArray(key, value);
80 | return builderClass.cast(this);
81 | }
82 |
83 | public T put(String key, boolean[] value) {
84 | bundle.putBooleanArray(key, value);
85 | return builderClass.cast(this);
86 | }
87 |
88 | public T put(String key, char[] value) {
89 | bundle.putCharArray(key, value);
90 | return builderClass.cast(this);
91 | }
92 |
93 | public T put(String key, double[] value) {
94 | bundle.putDoubleArray(key, value);
95 | return builderClass.cast(this);
96 | }
97 |
98 | public T put(String key, float[] value) {
99 | bundle.putFloatArray(key, value);
100 | return builderClass.cast(this);
101 | }
102 |
103 | public T put(String key, int[] value) {
104 | bundle.putIntArray(key, value);
105 | return builderClass.cast(this);
106 | }
107 |
108 | public T put(String key, long[] value) {
109 | bundle.putLongArray(key, value);
110 | return builderClass.cast(this);
111 | }
112 |
113 | public T put(String key, short[] value) {
114 | bundle.putShortArray(key, value);
115 | return builderClass.cast(this);
116 | }
117 |
118 | public T put(String key, Bundle value) {
119 | bundle.putBundle(key, value);
120 | return builderClass.cast(this);
121 | }
122 |
123 | public T put(String key, CharSequence value) {
124 | bundle.putCharSequence(key, value);
125 | return builderClass.cast(this);
126 | }
127 |
128 | public T put(String key, Parcelable value) {
129 | bundle.putParcelable(key, value);
130 | return builderClass.cast(this);
131 | }
132 |
133 | public T put(String key, Serializable value) {
134 | bundle.putSerializable(key, value);
135 | return builderClass.cast(this);
136 | }
137 |
138 | public T put(String key, CharSequence[] value) {
139 | bundle.putCharSequenceArray(key, value);
140 | return builderClass.cast(this);
141 | }
142 |
143 | public T put(String key, Parcelable[] value) {
144 | bundle.putParcelableArray(key, value);
145 | return builderClass.cast(this);
146 | }
147 |
148 | public T put(String key, String[] value) {
149 | bundle.putStringArray(key, value);
150 | return builderClass.cast(this);
151 | }
152 |
153 | public T putCharSequenceList(String key, ArrayList value) {
154 | bundle.putCharSequenceArrayList(key, value);
155 | return builderClass.cast(this);
156 | }
157 |
158 | public T putIntegerList(String key, ArrayList value) {
159 | bundle.putIntegerArrayList(key, value);
160 | return builderClass.cast(this);
161 | }
162 |
163 | public T putParcelableList(String key, ArrayList extends Parcelable> value) {
164 | bundle.putParcelableArrayList(key, value);
165 | return builderClass.cast(this);
166 | }
167 |
168 | public T putStringList(String key, ArrayList value) {
169 | bundle.putStringArrayList(key, value);
170 | return builderClass.cast(this);
171 | }
172 |
173 | public Bundle getBundle() {
174 | return bundle;
175 | }
176 |
177 | protected void setBundle(Bundle bundle) {
178 | this.bundle = bundle;
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/GFragmentPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import com.google.auto.service.AutoService;
22 | import com.sun.tools.javac.code.Symbol;
23 | import com.sun.tools.javac.model.JavacElements;
24 | import com.sun.tools.javac.tree.JCTree;
25 |
26 | import net.xkor.genaroid.GenaroidEnvironment;
27 | import net.xkor.genaroid.annotations.GFragment;
28 | import net.xkor.genaroid.annotations.InjectGenaroidCall;
29 | import net.xkor.genaroid.tree.GClass;
30 | import net.xkor.genaroid.tree.GMethod;
31 | import net.xkor.genaroid.wrap.BaseFragmentWrapper;
32 | import net.xkor.genaroid.wrap.FragmentWrapper;
33 | import net.xkor.genaroid.wrap.InflatableWrapper;
34 | import net.xkor.genaroid.wrap.SupportFragmentWrapper;
35 |
36 | import java.util.ArrayList;
37 | import java.util.Collections;
38 | import java.util.Set;
39 |
40 | import javax.tools.Diagnostic;
41 |
42 | @AutoService(GenaroidPlugin.class)
43 | public class GFragmentPlugin extends GenaroidPlugin {
44 |
45 | private static final String ANNOTATION_CLASS_NAME = GFragment.class.getCanonicalName();
46 |
47 | private ArrayList sortedFragments;
48 |
49 | public java.util.List getFragments() {
50 | return sortedFragments;
51 | }
52 |
53 | @Override
54 | public void process() {
55 | JavacElements utils = getEnvironment().getUtils();
56 | Symbol.ClassSymbol instanceStateType = utils.getTypeElement(ANNOTATION_CLASS_NAME);
57 | BaseFragmentWrapper nativeFragmentWrapper = new FragmentWrapper(utils);
58 | BaseFragmentWrapper supportFragmentWrapper = new SupportFragmentWrapper(utils);
59 | InflatableWrapper inflatableWrapper = new InflatableWrapper(utils);
60 |
61 | Set fragments = getEnvironment().getGElementsAnnotatedWith(GFragment.class, GClass.class);
62 | sortedFragments = new ArrayList<>(fragments);
63 | Collections.sort(sortedFragments, GClass.HIERARCHY_LEVEL_COMPARATOR);
64 |
65 | for (GClass fragment : sortedFragments) {
66 | JCTree.JCAnnotation jcAnnotation = fragment.extractAnnotation(instanceStateType);
67 | GFragment annotation = fragment.getAnnotation(GFragment.class);
68 |
69 | BaseFragmentWrapper fragmentWrapper;
70 | if (fragment.isSubClass(supportFragmentWrapper.getClassSymbol())) {
71 | fragmentWrapper = supportFragmentWrapper;
72 | } else if (fragment.isSubClass(nativeFragmentWrapper.getClassSymbol())) {
73 | fragmentWrapper = nativeFragmentWrapper;
74 | } else {
75 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
76 | "Annotation " + instanceStateType.getSimpleName() + " can be applied only to subclasses of Fragment",
77 | fragment.getElement());
78 | continue;
79 | }
80 |
81 | if (annotation.value() != 0) {
82 | String layoutId = String.valueOf(annotation.value());
83 | for (JCTree.JCExpression value : jcAnnotation.getArguments()) {
84 | if (value instanceof JCTree.JCAssign) {
85 | if (((JCTree.JCAssign) value).lhs.toString().equals("value")) {
86 | layoutId = ((JCTree.JCAssign) value).rhs.toString();
87 | }
88 | } else {
89 | layoutId = value.toString();
90 | }
91 | }
92 |
93 | fragment.implementIfNeeded(inflatableWrapper.getClassSymbol());
94 | fragment.overrideMethod(inflatableWrapper.getGetLayoutIdMethod(), false)
95 | .appendCode("return %s;", layoutId);
96 | }
97 |
98 | if (fragment.isBaseWithAnnotation(GFragment.class)) {
99 | fragment.getGUnit().addNewImports(GenaroidEnvironment.GENAROID_MAIN_CLASS);
100 | GMethod onCreateMethod = fragment.overrideMethod(fragmentWrapper.getOnCreateMethod(), true);
101 |
102 | if ((annotation.injectCalls() & InjectGenaroidCall.INSTANCE_STATE) != 0) {
103 | fragment.overrideMethod(fragmentWrapper.getOnSaveInstanceStateMethod(), true)
104 | .appendCode("Genaroid.saveInstanceState(this, $p0);");
105 | onCreateMethod.prependCode("Genaroid.restoreInstanceState(this, $p0);");
106 | }
107 |
108 | if ((annotation.injectCalls() & InjectGenaroidCall.BIND) != 0) {
109 | fragment.overrideMethod(fragmentWrapper.getOnViewCreatedMethod(), true)
110 | .appendCode("Genaroid.bind(this, $p0);");
111 | fragment.overrideMethod(fragmentWrapper.getOnDestroyViewMethod(), true)
112 | .appendCode("Genaroid.unbind(this);");
113 | }
114 |
115 | if ((annotation.injectCalls() & InjectGenaroidCall.READ_PARAMS) != 0) {
116 | onCreateMethod.prependCode("Genaroid.readParams(this);");
117 | }
118 |
119 | if ((annotation.injectCalls() & InjectGenaroidCall.INFLATE_LAYOUT) != 0) {
120 | GMethod onCreateViewMethod = fragment.overrideMethod(fragmentWrapper.getOnCreateViewMethod(), false);
121 | if (onCreateViewMethod.getBody().size() > 0) {
122 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
123 | "You can not override method onCreateView when the injectCalls parameter of GFragment annotation contains InjectGenaroidCall.INFLATE_LAYOUT value",
124 | fragment.getElement());
125 | continue;
126 | }
127 | onCreateViewMethod.appendCode("return Genaroid.inflate(this, $p0, $p1);");
128 | }
129 | }
130 | }
131 | }
132 |
133 | @NonNull
134 | @Override
135 | public Set getSupportedAnnotationTypes() {
136 | return Collections.singleton(ANNOTATION_CLASS_NAME);
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/GenaroidEnvironment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid;
18 |
19 | import com.sun.tools.javac.api.JavacTrees;
20 | import com.sun.tools.javac.code.Symbol;
21 | import com.sun.tools.javac.code.Type;
22 | import com.sun.tools.javac.code.Types;
23 | import com.sun.tools.javac.model.JavacElements;
24 | import com.sun.tools.javac.model.JavacTypes;
25 | import com.sun.tools.javac.parser.Parser;
26 | import com.sun.tools.javac.parser.ParserFactory;
27 | import com.sun.tools.javac.processing.JavacProcessingEnvironment;
28 | import com.sun.tools.javac.tree.JCTree;
29 | import com.sun.tools.javac.tree.JCTree.JCAnnotation;
30 | import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
31 | import com.sun.tools.javac.tree.JCTree.JCExpression;
32 | import com.sun.tools.javac.tree.JCTree.JCModifiers;
33 | import com.sun.tools.javac.tree.TreeMaker;
34 | import com.sun.tools.javac.util.List;
35 | import com.sun.tools.javac.util.Pair;
36 |
37 | import net.xkor.genaroid.tree.GClass;
38 | import net.xkor.genaroid.tree.GElement;
39 | import net.xkor.genaroid.tree.GField;
40 | import net.xkor.genaroid.tree.GMethod;
41 | import net.xkor.genaroid.tree.GUnit;
42 |
43 | import org.jetbrains.annotations.NotNull;
44 | import org.jetbrains.annotations.Nullable;
45 |
46 | import java.lang.annotation.Annotation;
47 | import java.lang.reflect.InvocationTargetException;
48 | import java.lang.reflect.Method;
49 | import java.util.ArrayList;
50 | import java.util.Collection;
51 | import java.util.HashMap;
52 | import java.util.HashSet;
53 | import java.util.Set;
54 |
55 | import javax.annotation.processing.Messager;
56 | import javax.annotation.processing.ProcessingEnvironment;
57 | import javax.annotation.processing.RoundEnvironment;
58 | import javax.lang.model.element.Element;
59 | import javax.lang.model.type.TypeKind;
60 |
61 | public class GenaroidEnvironment {
62 | public static final String GENAROID_MAIN_CLASS = "net.xkor.genaroid.Genaroid";
63 | public static final String DEBUG_MODE_OPTION_NAME = "genaroidDebugMode";
64 |
65 | private JavacProcessingEnvironment javacProcessingEnv;
66 | private RoundEnvironment roundEnvironment;
67 | private TreeMaker maker;
68 | private ParserFactory parserFactory;
69 | private Method newParserMethod;
70 | private JavacElements utils;
71 | private JavacTrees trees;
72 | private JavacTypes typeUtils;
73 | private Types types;
74 |
75 | private JCExpression voidType;
76 | private Symbol.ClassSymbol objectClass;
77 |
78 | private HashMap units = new HashMap<>();
79 | private boolean debugMode;
80 |
81 | public void init(ProcessingEnvironment procEnv) {
82 | javacProcessingEnv = (JavacProcessingEnvironment) procEnv;
83 | maker = TreeMaker.instance(javacProcessingEnv.getContext());
84 | parserFactory = ParserFactory.instance(javacProcessingEnv.getContext());
85 | utils = javacProcessingEnv.getElementUtils();
86 | typeUtils = javacProcessingEnv.getTypeUtils();
87 | trees = JavacTrees.instance(javacProcessingEnv);
88 | types = Types.instance(javacProcessingEnv.getContext());
89 |
90 | voidType = maker.Type((Type) typeUtils.getNoType(TypeKind.VOID));
91 | objectClass = utils.getTypeElement("java.lang.Object");
92 |
93 | debugMode = Boolean.parseBoolean(getOption(DEBUG_MODE_OPTION_NAME));
94 |
95 | // reflection
96 | try {
97 | newParserMethod = ParserFactory.class.getMethod("newParser", CharSequence.class, Boolean.TYPE, Boolean.TYPE, Boolean.TYPE);
98 | } catch (NoSuchMethodException ignored) {
99 | }
100 | }
101 |
102 | @Nullable
103 | public String getOption(@NotNull String optionName) {
104 | return javacProcessingEnv.getOptions().get(optionName);
105 | }
106 |
107 | public Pair getTreeAndTopLevel(Element e) {
108 | return utils.getTreeAndTopLevel(e, null, null);
109 | }
110 |
111 | public RoundEnvironment getRoundEnvironment() {
112 | return roundEnvironment;
113 | }
114 |
115 | public void setRoundEnvironment(RoundEnvironment roundEnvironment) {
116 | this.roundEnvironment = roundEnvironment;
117 | }
118 |
119 | public Set getGElementsAnnotatedWith(Class extends Annotation> annotationClass, Class elementClass) {
120 | return getGElementsAnnotatedWith(roundEnvironment.getElementsAnnotatedWith(annotationClass), elementClass);
121 | }
122 |
123 | public Set getGElementsAnnotatedWith(Symbol.ClassSymbol annotationClass, Class elementClass) {
124 | return getGElementsAnnotatedWith(roundEnvironment.getElementsAnnotatedWith(annotationClass), elementClass);
125 | }
126 |
127 | private Set getGElementsAnnotatedWith(Set extends Element> elements, Class elementClass) {
128 | Set result = new HashSet<>();
129 | for (Element element : elements) {
130 | GElement gElement = null;
131 | switch (element.getKind()) {
132 | case CLASS:
133 | gElement = GClass.getGClass(this, element);
134 | break;
135 | case FIELD:
136 | gElement = GField.getGField(this, element);
137 | break;
138 | case METHOD:
139 | gElement = GMethod.getGMethod(this, element);
140 | break;
141 | }
142 | if (gElement != null && elementClass.isAssignableFrom(gElement.getClass())) {
143 | result.add(elementClass.cast(gElement));
144 | }
145 | }
146 | return result;
147 | }
148 |
149 | public void removeAnnotation(JCModifiers modifiers, JCAnnotation annotation) {
150 | ArrayList elementAnnotations = new ArrayList<>(modifiers.annotations);
151 | elementAnnotations.remove(annotation);
152 | modifiers.annotations = List.from(
153 | elementAnnotations.toArray(new JCAnnotation[elementAnnotations.size()]));
154 | }
155 |
156 | public void removeAnnotation(JCModifiers modifiers, T annotation) {
157 | ArrayList elementAnnotations = new ArrayList<>(modifiers.annotations);
158 | elementAnnotations.remove(annotation);
159 | modifiers.annotations = List.from(
160 | elementAnnotations.toArray(new JCAnnotation[elementAnnotations.size()]));
161 | }
162 |
163 | public JCAnnotation findAnnotation(JCModifiers modifiers, Symbol.ClassSymbol annotationClass) {
164 | for (JCAnnotation annotation : modifiers.annotations) {
165 | if (equalAnnotation(annotation, annotationClass)) {
166 | return annotation;
167 | }
168 | }
169 | return null;
170 | }
171 |
172 | public boolean equalAnnotation(JCAnnotation jcAnnotation, Symbol.ClassSymbol annotationClass) {
173 | String name = jcAnnotation.getAnnotationType().toString();
174 | return name.equals(annotationClass.className()) || name.equals(annotationClass.getSimpleName().toString());
175 | }
176 |
177 | public TreeMaker getMaker() {
178 | return maker;
179 | }
180 |
181 | public JavacElements getUtils() {
182 | return utils;
183 | }
184 |
185 | public JCExpression getVoidType() {
186 | return voidType;
187 | }
188 |
189 | public JCExpression typeToTree(Type type) {
190 | return typeToTree(type.asElement());
191 | }
192 |
193 | public JCExpression typeToTree(Symbol.TypeSymbol typeSymbol) {
194 | return createParser(typeSymbol.getQualifiedName().toString()).parseType();
195 | }
196 |
197 | public Parser createParser(String sources) {
198 | try {
199 | return (Parser) newParserMethod.invoke(parserFactory, sources, false, false, false);
200 | } catch (IllegalAccessException | InvocationTargetException ignored) {
201 | }
202 | return null;
203 | }
204 |
205 | public JCTree.JCStatement codeToStatement(String code, Object... args) {
206 | return createParser(String.format(code, args)).parseStatement();
207 | }
208 |
209 | public JCTree.JCExpression codeToExpression(String code, Object... args) {
210 | return createParser(String.format(code, args)).parseExpression();
211 | }
212 |
213 | public JavacTypes getTypeUtils() {
214 | return typeUtils;
215 | }
216 |
217 | public Types getTypes() {
218 | return types;
219 | }
220 |
221 | public GUnit getUnit(String sourceFile) {
222 | return units.get(sourceFile);
223 | }
224 |
225 | public void putUnit(GUnit unit) {
226 | units.put(unit.getCompilationUnit().getSourceFile().getName(), unit);
227 | }
228 |
229 | public Collection getUnits() {
230 | return units.values();
231 | }
232 |
233 | public Collection getClasses() {
234 | ArrayList classes = new ArrayList<>();
235 | for (GUnit unit : units.values()) {
236 | classes.addAll(unit.getGClasses());
237 | }
238 | return classes;
239 | }
240 |
241 | public Messager getMessager() {
242 | return javacProcessingEnv.getMessager();
243 | }
244 |
245 | public boolean isDebugMode() {
246 | return debugMode;
247 | }
248 |
249 | public JavacProcessingEnvironment getJavacProcessingEnv() {
250 | return javacProcessingEnv;
251 | }
252 |
253 | public Symbol.ClassSymbol getObjectClass() {
254 | return objectClass;
255 | }
256 |
257 | }
258 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/tree/GClass.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.tree;
18 |
19 | import com.sun.tools.javac.code.Flags;
20 | import com.sun.tools.javac.code.Symbol;
21 | import com.sun.tools.javac.code.Type;
22 | import com.sun.tools.javac.model.JavacElements;
23 | import com.sun.tools.javac.tree.JCTree;
24 | import com.sun.tools.javac.tree.JCTree.JCClassDecl;
25 | import com.sun.tools.javac.tree.JCTree.JCExpression;
26 | import com.sun.tools.javac.tree.JCTree.JCIdent;
27 | import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
28 | import com.sun.tools.javac.tree.JCTree.JCModifiers;
29 | import com.sun.tools.javac.tree.JCTree.JCNewClass;
30 | import com.sun.tools.javac.tree.JCTree.JCStatement;
31 | import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
32 | import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
33 | import com.sun.tools.javac.tree.TreeMaker;
34 | import com.sun.tools.javac.util.Filter;
35 | import com.sun.tools.javac.util.List;
36 | import com.sun.tools.javac.util.Name;
37 |
38 | import net.xkor.genaroid.GenaroidEnvironment;
39 |
40 | import java.lang.annotation.Annotation;
41 | import java.util.Collection;
42 | import java.util.Comparator;
43 | import java.util.HashMap;
44 | import java.util.Set;
45 |
46 | import javax.lang.model.element.Element;
47 |
48 | public class GClass extends GElement {
49 | private static final Filter methodsFilter = new Filter() {
50 | public boolean accepts(Symbol symbol) {
51 | return symbol instanceof Symbol.MethodSymbol;
52 | }
53 | };
54 | private GUnit unit;
55 | private JCClassDecl classDecl;
56 | private HashMap members = new HashMap<>();
57 |
58 | private int hierarchyLevel = -1;
59 | public static final Comparator HIERARCHY_LEVEL_COMPARATOR = new Comparator() {
60 | @Override
61 | public int compare(GClass class1, GClass class2) {
62 | return class1.getHierarchyLevel() - class2.getHierarchyLevel();
63 | }
64 | };
65 | private HashMap, Boolean> baseClassForAnnotion = new HashMap<>();
66 |
67 | public GClass(GUnit unit, JCClassDecl classDecl, Element element) {
68 | super(element);
69 | this.unit = unit;
70 | this.classDecl = classDecl;
71 | }
72 |
73 | public static GClass getGClass(GenaroidEnvironment environment, Element element) {
74 | JCClassDecl classDecl = (JCClassDecl) environment.getUtils().getTree(element);
75 | GUnit unit = GUnit.getGUnit(environment, element);
76 |
77 | String className = GElement.getName(element);
78 | GClass gClass = unit.getGClass(className);
79 | if (gClass == null) {
80 | gClass = new GClass(unit, classDecl, element);
81 | unit.putGClass(gClass);
82 | }
83 | return gClass;
84 | }
85 |
86 | public static GClass findGClass(GenaroidEnvironment environment, Element element) {
87 | GUnit unit = GUnit.findGUnit(environment, element);
88 | if (unit == null) {
89 | return null;
90 | }
91 |
92 | String className = GElement.getName(element);
93 | return unit.getGClass(className);
94 | }
95 |
96 | public JCClassDecl getClassDecl() {
97 | return classDecl;
98 | }
99 |
100 | @Override
101 | public Symbol.ClassSymbol getElement() {
102 | return (Symbol.ClassSymbol) super.getElement();
103 | }
104 |
105 | @Override
106 | public GUnit getGUnit() {
107 | return unit;
108 | }
109 |
110 | @Override
111 | public JCClassDecl getTree() {
112 | return classDecl;
113 | }
114 |
115 | @Override
116 | protected JCModifiers getModifiers() {
117 | return getTree().getModifiers();
118 | }
119 |
120 | public Collection getMembers() {
121 | return members.values();
122 | }
123 |
124 | public GClassMember getMember(String memberSignature) {
125 | return members.get(memberSignature);
126 | }
127 |
128 | public void putMember(GClassMember member) {
129 | members.put(member.getMemberSignature(), member);
130 | }
131 |
132 | public int getHierarchyLevel() {
133 | if (hierarchyLevel == -1) {
134 | hierarchyLevel = getSubClassLevel(getEnvironment().getObjectClass());
135 | }
136 | return hierarchyLevel;
137 | }
138 |
139 | public int getSubClassLevel(Symbol.ClassSymbol baseClass) {
140 | if (baseClass.isInterface()) {
141 | throw new IllegalArgumentException("Parameter baseClass should be class, not interface.");
142 | }
143 | int level = 0;
144 | Symbol.ClassSymbol currentClass = getElement();
145 | while (currentClass != baseClass) {
146 | level++;
147 | currentClass = (Symbol.ClassSymbol) currentClass.getSuperclass().asElement();
148 | if (currentClass == null) {
149 | return -1;
150 | }
151 | }
152 | return level;
153 | }
154 |
155 | public boolean isSubClass(Symbol.TypeSymbol base) {
156 | return getElement().isSubClass(base, getEnvironment().getTypes());
157 | }
158 |
159 | public boolean isSubClass(GClass base) {
160 | return isSubClass(base.getElement());
161 | }
162 |
163 | public void implementInBestParent(Symbol.ClassSymbol interfaceType, Set members) {
164 | if (!isSubClass(interfaceType)) {
165 | GClass classToImplement = this;
166 | for (GClassMember member : members) {
167 | if (member.getGClass() != classToImplement && classToImplement.isSubClass(member.getGClass())) {
168 | classToImplement = member.getGClass();
169 | }
170 | }
171 | classToImplement.implement(interfaceType);
172 | }
173 | }
174 |
175 | public void implementIfNeeded(Symbol.ClassSymbol interfaceType) {
176 | if (!isSubClass(interfaceType)) {
177 | GClass classToImplement = this;
178 | Symbol.ClassSymbol currentClass = getElement();
179 | while (currentClass != null) {
180 | if (classToImplement != null && classToImplement.isImplementedByProcessor(interfaceType)) {
181 | return;
182 | }
183 | currentClass = (Symbol.ClassSymbol) currentClass.getSuperclass().asElement();
184 | classToImplement = GClass.findGClass(getEnvironment(), currentClass);
185 | }
186 | implement(interfaceType);
187 | }
188 | }
189 |
190 | public void fixImplementation(Symbol.ClassSymbol interfaceType) {
191 | if (isImplementedByProcessor(interfaceType)) {
192 | Symbol.ClassSymbol currentClass = getElement();
193 | while (currentClass != null) {
194 | currentClass = (Symbol.ClassSymbol) currentClass.getSuperclass().asElement();
195 | GClass parentClass = GClass.findGClass(getEnvironment(), currentClass);
196 | if (parentClass != null && parentClass.isImplementedByProcessor(interfaceType)) {
197 | parentClass.fixImplementation(interfaceType);
198 | removeInterface(interfaceType);
199 | overrideInterfaceMethods(interfaceType);
200 | }
201 | }
202 | }
203 | }
204 |
205 | private void removeInterface(Symbol.ClassSymbol interfaceType) {
206 | String name = interfaceType.getQualifiedName().toString();
207 | List interfaces = List.nil();
208 | for (JCExpression jcInterface : classDecl.implementing) {
209 | if (!name.equals(jcInterface.toString())) {
210 | interfaces = interfaces.append(jcInterface);
211 | }
212 | }
213 | classDecl.implementing = interfaces;
214 | }
215 |
216 | public void implement(Symbol.ClassSymbol interfaceType) {
217 | if (!interfaceType.isInterface()) {
218 | throw new RuntimeException("Can not implement non interface type");
219 | }
220 | if (isImplementedByProcessor(interfaceType)) {
221 | return;
222 | }
223 |
224 | JCExpression jcInterface = getEnvironment().createParser(interfaceType.getQualifiedName().toString()).parseType();
225 | classDecl.implementing = classDecl.implementing.append(jcInterface);
226 |
227 | overrideInterfaceMethods(interfaceType);
228 | }
229 |
230 | private void overrideInterfaceMethods(Symbol.ClassSymbol interfaceType) {
231 | do {
232 | for (Symbol symbol : interfaceType.members().getElements(methodsFilter)) {
233 | overrideMethod((Symbol.MethodSymbol) symbol, false);
234 | }
235 | interfaceType = (Symbol.ClassSymbol) interfaceType.getSuperclass().asElement();
236 | } while (interfaceType != null);
237 | }
238 |
239 | public boolean isImplementedByProcessor(Symbol.ClassSymbol interfaceType) {
240 | String interfaceName = interfaceType.getQualifiedName().toString();
241 | for (JCExpression expression : classDecl.implementing) {
242 | if (expression.toString().equals(interfaceName)) {
243 | return true;
244 | }
245 | }
246 | return false;
247 | }
248 |
249 | public GField createOrGetField(long modifiers, String name, String type, JCTree.JCExpression init) {
250 | GField field = (GField) getMember(name);
251 | if (field == null) {
252 | TreeMaker maker = getEnvironment().getMaker();
253 | JavacElements utils = getEnvironment().getUtils();
254 | JCVariableDecl variableDecl = maker.VarDef(maker.Modifiers(modifiers), utils.getName(name),
255 | maker.Ident(utils.getName(type)), init);
256 |
257 | field = new GField(this, variableDecl, null);
258 | field.setName(name);
259 | field.setMemberSignature(name);
260 | putMember(field);
261 | classDecl.defs = classDecl.defs.append(variableDecl);
262 | }
263 |
264 | return field;
265 | }
266 |
267 | public GMethod overrideMethod(Symbol.MethodSymbol methodSymbol, boolean addSupperCall) {
268 | String memberSignature = GClassMember.getMemberSignature(methodSymbol);
269 | GMethod method = (GMethod) getMember(memberSignature);
270 | if (method != null) {
271 | return method;
272 | }
273 |
274 | if (getElement() != null) {
275 | for (Element member : getElement().getEnclosedElements()) {
276 | String signature = GClassMember.getMemberSignature(member);
277 | if (member instanceof Symbol.MethodSymbol && signature.equals(memberSignature)) {
278 | return GMethod.getGMethod(getEnvironment(), member);
279 | }
280 | }
281 | }
282 |
283 | TreeMaker maker = getEnvironment().getMaker().forToplevel(getGUnit().getCompilationUnit());
284 | JavacElements utils = getEnvironment().getUtils();
285 |
286 | String typeName = methodSymbol.getReturnType().asElement().getQualifiedName().toString();
287 | JCExpression returnType = getEnvironment().createParser(typeName).parseType();
288 | List params = List.nil();
289 | int paramNum = 0;
290 | for (Type paramType : methodSymbol.asType().getParameterTypes()) {
291 | Name paramName = utils.getName("param" + paramNum++);
292 | JCExpression returnTypeName = getEnvironment().typeToTree(paramType);
293 | params = params.append(maker.at(getTree().getStartPosition()).VarDef(maker.Modifiers(Flags.PARAMETER), paramName, returnTypeName, null));
294 | }
295 | long modifiers = methodSymbol.flags() & (Flags.PUBLIC | Flags.PRIVATE | Flags.PROTECTED);
296 | JCTree.JCAnnotation overrideAnnotation = maker.Annotation(maker.Ident(utils.getName("Override")), List.nil());
297 |
298 | JCMethodDecl methodDecl = maker.MethodDef(
299 | maker.Modifiers(modifiers, List.of(overrideAnnotation)),
300 | utils.getName(methodSymbol.getSimpleName()),
301 | returnType,
302 | List.nil(),
303 | params,
304 | List.nil(),
305 | maker.Block(0, List.nil()),
306 | null);
307 |
308 | method = new GMethod(this, methodDecl, null);
309 | method.setName(methodSymbol.getSimpleName().toString());
310 | method.setMemberSignature(memberSignature);
311 |
312 | if (addSupperCall) {
313 | method.appendSuperCall();
314 | }
315 |
316 | putMember(method);
317 | classDecl.defs = classDecl.defs.append(methodDecl);
318 |
319 | return method;
320 | }
321 |
322 | public JCNewClass createNewInstance(String className, List params) {
323 | TreeMaker maker = getEnvironment().getMaker();
324 | JavacElements utils = getEnvironment().getUtils();
325 | JCIdent ident = maker.Ident(utils.getName(className));
326 | return maker.NewClass(null, null, ident, params, getTree());
327 | }
328 |
329 | public JCNewClass createNewInstance(List params) {
330 | return createNewInstance(getName(), params);
331 | }
332 |
333 | public boolean isBaseWithAnnotation(Class annotationClass) {
334 | Boolean result = baseClassForAnnotion.get(annotationClass);
335 | if (result != null) {
336 | return result;
337 | }
338 |
339 | result = true;
340 | Symbol.ClassSymbol currentClass = getElement();
341 | while (currentClass != null) {
342 | currentClass = (Symbol.ClassSymbol) currentClass.getSuperclass().asElement();
343 | if (currentClass != null && ((Element) currentClass).getAnnotation(annotationClass) != null) {
344 | result = false;
345 | break;
346 | }
347 | }
348 |
349 | baseClassForAnnotion.put(annotationClass, result);
350 | return result;
351 | }
352 | }
353 |
--------------------------------------------------------------------------------
/compiler/src/main/java/net/xkor/genaroid/plugins/ListenersPlugin.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Aleksei Skoriatin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed To in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.xkor.genaroid.plugins;
18 |
19 | import android.support.annotation.NonNull;
20 |
21 | import com.google.auto.service.AutoService;
22 | import com.sun.tools.javac.code.Symbol;
23 | import com.sun.tools.javac.code.Type;
24 | import com.sun.tools.javac.code.Types;
25 | import com.sun.tools.javac.model.JavacElements;
26 | import com.sun.tools.javac.tree.JCTree;
27 | import com.sun.tools.javac.tree.TreeMaker;
28 | import com.sun.tools.javac.util.Filter;
29 | import com.sun.tools.javac.util.List;
30 |
31 | import net.xkor.genaroid.annotations.CustomListener;
32 | import net.xkor.genaroid.tree.GClass;
33 | import net.xkor.genaroid.tree.GField;
34 | import net.xkor.genaroid.tree.GMethod;
35 | import net.xkor.genaroid.wrap.BindableWrapper;
36 |
37 | import java.lang.annotation.ElementType;
38 | import java.lang.annotation.Target;
39 | import java.util.Collection;
40 | import java.util.Collections;
41 | import java.util.HashMap;
42 | import java.util.HashSet;
43 | import java.util.Set;
44 |
45 | import javax.lang.model.element.Element;
46 | import javax.lang.model.type.DeclaredType;
47 | import javax.lang.model.type.MirroredTypeException;
48 | import javax.lang.model.type.PrimitiveType;
49 | import javax.lang.model.type.TypeKind;
50 | import javax.tools.Diagnostic;
51 |
52 | @AutoService(GenaroidPlugin.class)
53 | @GenaroidPlugin.Dependencies(ViewByIdPlugin.class)
54 | public class ListenersPlugin extends GenaroidPlugin {
55 |
56 | private static final String ANNOTATION_CLASS_NAME = CustomListener.class.getCanonicalName();
57 | private static final String[] STANDARD_LISTENER_ANNOTATIONS = new String[]{
58 | "net.xkor.genaroid.annotations.OnClick",
59 | "net.xkor.genaroid.annotations.OnItemClick",
60 | "net.xkor.genaroid.annotations.OnLongClick",
61 | "net.xkor.genaroid.annotations.OnItemLongClick",
62 | "net.xkor.genaroid.annotations.OnItemSelected",
63 | "net.xkor.genaroid.annotations.OnNothingSelected",
64 | };
65 |
66 | private ViewByIdPlugin viewByIdPlugin;
67 |
68 | @Override
69 | protected void init() {
70 | super.init();
71 | viewByIdPlugin = getPlugin(ViewByIdPlugin.class);
72 | }
73 |
74 | @Override
75 | public void process() {
76 | JavacElements utils = getEnvironment().getUtils();
77 | Types types = getEnvironment().getTypes();
78 | TreeMaker maker = getEnvironment().getMaker();
79 | BindableWrapper bindableWrapper = new BindableWrapper(utils);
80 | PrimitiveType intType = getEnvironment().getTypeUtils().getPrimitiveType(TypeKind.INT);
81 |
82 | HashMap listeners = new HashMap<>();
83 | Collection annotations = getListenerAnnotations();
84 | for (Symbol.ClassSymbol annotationSymbol : annotations) {
85 | CustomListener customListener = ((Element) annotationSymbol).getAnnotation(CustomListener.class);
86 | Target target = ((Element) annotationSymbol).getAnnotation(Target.class);
87 | boolean validAnnotation = true;
88 | if (target == null || target.value().length != 1 || target.value()[0] != ElementType.METHOD) {
89 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
90 | "Annotation " + annotationSymbol.getSimpleName() + " must be annotated by @Target(ElementType.METHOD)",
91 | annotationSymbol);
92 | validAnnotation = false;
93 | }
94 | for (Symbol member : annotationSymbol.members().getElements()) {
95 | if (member instanceof Symbol.MethodSymbol) {
96 | if (!"value".equals(member.name.toString())) {
97 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
98 | "Annotation " + annotationSymbol.getSimpleName() + " must has only value parameter",
99 | annotationSymbol);
100 | validAnnotation = false;
101 | }
102 |
103 | Type returnType = member.type.asMethodType().getReturnType();
104 | if (!types.isArray(returnType) || !types.elemtype(returnType).equals(intType)) {
105 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
106 | "Annotation " + annotationSymbol.getSimpleName() + " must has value parameter with int[] type",
107 | annotationSymbol);
108 | validAnnotation = false;
109 | }
110 | }
111 | }
112 |
113 | Symbol.ClassSymbol listenerClassSymbol;
114 | try {
115 | Class> clazz = customListener.listenerClass();
116 | listenerClassSymbol = utils.getTypeElement(clazz.getCanonicalName());
117 | } catch (MirroredTypeException exception) {
118 | DeclaredType classTypeMirror = (DeclaredType) exception.getTypeMirror();
119 | listenerClassSymbol = (Symbol.ClassSymbol) classTypeMirror.asElement();
120 | }
121 |
122 | Symbol.ClassSymbol targetClassSymbol;
123 | try {
124 | Class> clazz = customListener.targetClass();
125 | targetClassSymbol = utils.getTypeElement(clazz.getCanonicalName());
126 | } catch (MirroredTypeException exception) {
127 | DeclaredType classTypeMirror = (DeclaredType) exception.getTypeMirror();
128 | targetClassSymbol = (Symbol.ClassSymbol) classTypeMirror.asElement();
129 | }
130 |
131 | Symbol.MethodSymbol listenerSetter = null;
132 | for (Symbol member : targetClassSymbol.members().getElementsByName(utils.getName(customListener.listenerSetterName()))) {
133 | if (member instanceof Symbol.MethodSymbol) {
134 | Symbol.MethodSymbol method = (Symbol.MethodSymbol) member;
135 | List params = method.asType().asMethodType().getParameterTypes();
136 | if (params.size() == 1 && params.get(0).asElement() == listenerClassSymbol) {
137 | listenerSetter = method;
138 | }
139 | }
140 | }
141 | if (listenerSetter == null) {
142 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
143 | String.format("Can not found method %s(%s) in class %s", customListener.listenerSetterName(), listenerClassSymbol.getQualifiedName(), targetClassSymbol.getQualifiedName()),
144 | annotationSymbol);
145 | validAnnotation = false;
146 | }
147 |
148 | Symbol.MethodSymbol listenerMethod = null;
149 | ListenerMethodFilter listenerMethodFilter = new ListenerMethodFilter(customListener.listenerMethodName());
150 | for (Symbol member : listenerClassSymbol.members().getElements(listenerMethodFilter)) {
151 | if (listenerMethod != null) {
152 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
153 | String.format("Listener class %s contains more one method, please specify method by a listenerSetterName parameter", listenerClassSymbol.getQualifiedName()),
154 | annotationSymbol);
155 | validAnnotation = false;
156 | }
157 | listenerMethod = (Symbol.MethodSymbol) member;
158 | }
159 | if (listenerMethod == null) {
160 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
161 | String.format("Listener class %s doesn't contains one method %s", listenerClassSymbol.getQualifiedName(), customListener.listenerSetterName()),
162 | annotationSymbol);
163 | validAnnotation = false;
164 | }
165 |
166 | if (!validAnnotation) {
167 | continue;
168 | }
169 |
170 | Set methods = getEnvironment().getGElementsAnnotatedWith(annotationSymbol, GMethod.class);
171 |
172 | for (GMethod method : methods) {
173 | JCTree.JCAnnotation annotation = method.extractAnnotation(annotationSymbol);
174 | JCTree.JCExpression value = annotation.getArguments().get(0);
175 | Set viewIds = new HashSet<>();
176 | if (value instanceof JCTree.JCAssign) {
177 | value = ((JCTree.JCAssign) value).rhs;
178 | }
179 | if (value instanceof JCTree.JCNewArray) {
180 | List elems = ((JCTree.JCNewArray) value).elems;
181 | for (JCTree.JCExpression elem : elems) {
182 | viewIds.add(elem.toString());
183 | }
184 | } else {
185 | viewIds.add(value.toString());
186 | }
187 |
188 | maker.toplevel = method.getGClass().getGUnit().getCompilationUnit();
189 | method.getGClass().implementIfNeeded(bindableWrapper.getClassSymbol());
190 | for (String viewId : viewIds) {
191 | String listenerVarName = "listener" + Integer.toHexString((method.getGClass().getElement().getQualifiedName() + "_" + viewId + "_" + listenerSetter.getQualifiedName() + "_" + listenerClassSymbol.getQualifiedName()).hashCode());
192 | GClass listenerImplementor = listeners.get(listenerVarName);
193 | if (listenerImplementor == null) {
194 | listenerImplementor = method.getGClass().getGUnit().createAnonymousClass(method.getGClass().getClassDecl());
195 | listenerImplementor.implement(listenerClassSymbol);
196 | listeners.put(listenerVarName, listenerImplementor);
197 | JCTree.JCExpression listenerType = getEnvironment().typeToTree(listenerClassSymbol);
198 | JCTree.JCVariableDecl listenerStatement = maker.VarDef(maker.Modifiers(0),
199 | utils.getName(listenerVarName), listenerType,
200 | maker.NewClass(null, null, listenerType, List.nil(), listenerImplementor.getTree()));
201 | GMethod bindMethod = method.getGClass().overrideMethod(bindableWrapper.getBindMethod(), true)
202 | .appendCode(listenerStatement);
203 | GMethod unbindMethod = method.getGClass().overrideMethod(bindableWrapper.getUnbindMethod(), true);
204 | GField fieldForResource = viewByIdPlugin.findFieldForResource(method.getGClass(), viewId);
205 | if (fieldForResource == null) {
206 | bindMethod.appendCode("((%s) $p0.findViewById(%s)).%s(%s);",
207 | targetClassSymbol.getQualifiedName(), viewId, listenerSetter.getSimpleName(), listenerVarName);
208 | unbindMethod.prependCode("((%s) $p0.findViewById(%s)).%s(null);",
209 | targetClassSymbol.getQualifiedName(), viewId, listenerSetter.getSimpleName());
210 | } else {
211 | boolean isSubClass = fieldForResource.getTree().getType().type.asElement()
212 | .isSubClass(targetClassSymbol, getEnvironment().getTypes());
213 | if (isSubClass) {
214 | bindMethod.appendCode("this.%s.%s(%s);", fieldForResource.getName(),
215 | listenerSetter.getSimpleName(), listenerVarName);
216 | unbindMethod.prependCode("this.%s.%s(null);", fieldForResource.getName(),
217 | listenerSetter.getSimpleName());
218 | } else {
219 | bindMethod.appendCode("((%s) this.%s).%s(%s);",
220 | targetClassSymbol.getQualifiedName(),
221 | fieldForResource.getName(), listenerSetter.getSimpleName(),
222 | listenerVarName);
223 | unbindMethod.prependCode("((%s) this.%s).%s(null);",
224 | targetClassSymbol.getQualifiedName(),
225 | fieldForResource.getName(), listenerSetter.getSimpleName());
226 | }
227 | }
228 | }
229 | GMethod listenerOverridedMethod = listenerImplementor.overrideMethod(listenerMethod, false);
230 | List listenerParameters = listenerMethod.getParameters();
231 | List paramList = List.nil();
232 | int paramNum = 0;
233 | boolean allParamsFound = true;
234 | for (Symbol.VarSymbol param : method.getElement().getParameters()) {
235 | boolean found = false;
236 | for (; paramNum < listenerParameters.size(); paramNum++) {
237 | if (types.isSameType(listenerParameters.get(paramNum).asType(), param.asType())) {
238 | paramList = paramList.append(maker.Ident(listenerOverridedMethod.getParamName(paramNum)));
239 | found = true;
240 | paramNum++;
241 | break;
242 | }
243 | }
244 | allParamsFound &= found;
245 | if (!found) {
246 | getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
247 | "Can not found listener parameter with type " + param.asType().toString(),
248 | method.getElement());
249 | }
250 | }
251 | if (allParamsFound) {
252 | listenerOverridedMethod.appendCode(maker.Exec(maker.Apply(null, maker.Ident(method.getElement()), paramList)));
253 | }
254 | }
255 | }
256 | }
257 |
258 | for (GClass gClass : getEnvironment().getClasses()) {
259 | gClass.fixImplementation(bindableWrapper.getClassSymbol());
260 | }
261 | }
262 |
263 | private HashSet getListenerAnnotations() {
264 | HashSet annotations = new HashSet<>();
265 | for (String annotationName : STANDARD_LISTENER_ANNOTATIONS) {
266 | annotations.add(getEnvironment().getUtils().getTypeElement(annotationName));
267 | }
268 | for (Element element : getEnvironment().getRoundEnvironment().getElementsAnnotatedWith(CustomListener.class)) {
269 | annotations.add((Symbol.ClassSymbol) element);
270 | }
271 | return annotations;
272 | }
273 |
274 | @NonNull
275 | @Override
276 | public Set getSupportedAnnotationTypes() {
277 | return Collections.singleton(ANNOTATION_CLASS_NAME);
278 | }
279 |
280 | private static class ListenerMethodFilter implements Filter {
281 | private final String listenerMethodName;
282 |
283 | public ListenerMethodFilter(String listenerMethodName) {
284 | this.listenerMethodName = listenerMethodName;
285 | }
286 |
287 | @Override
288 | public boolean accepts(Symbol symbol) {
289 | return (symbol instanceof Symbol.MethodSymbol) && (listenerMethodName.length() == 0 || listenerMethodName.equals(symbol.name.toString()));
290 | }
291 | }
292 | }
293 |
--------------------------------------------------------------------------------