Implemented building Kotlin Android projects with Jack toolchain enabled

#KT-13275 Fixed
Implemented KotlinJillTask for converting kotlin classes to jace format which could be consumed by Jack transform task
This commit is contained in:
Vyacheslav Gerasimov
2017-01-29 22:45:14 +03:00
parent 29ac01f2e2
commit 7bd6314ee1
92 changed files with 2020 additions and 16 deletions
@@ -8,6 +8,8 @@ import java.io.File
class KotlinAndroidGradleCLIOnly : AbstractKotlinAndroidGradleTests(gradleVersion = "2.3", androidGradlePluginVersion = "1.5.+")
class KotlinAndroidWithJackGradleCLIOnly : AbstractKotlinAndroidWithJackGradleTests(gradleVersion = "3.3", androidGradlePluginVersion = "2.3.+")
abstract class AbstractKotlinAndroidGradleTests(
private val gradleVersion: String,
private val androidGradlePluginVersion: String
@@ -17,8 +19,6 @@ abstract class AbstractKotlinAndroidGradleTests(
super.defaultBuildOptions().copy(androidHome = File("../../../dependencies/android-sdk-for-tests"),
androidGradlePluginVersion = androidGradlePluginVersion)
@Test
fun testSimpleCompile() {
val project = Project("AndroidProject", gradleVersion)
@@ -196,4 +196,176 @@ fun getSomething() = 10
assertNotContains("Changed dependencies of configuration .+ after it has been included in dependency resolution".toRegex())
}
}
}
}
abstract class AbstractKotlinAndroidWithJackGradleTests(
private val gradleVersion: String,
private val androidGradlePluginVersion: String
) : BaseGradleIT() {
fun getEnvJDK_18() = System.getenv()["JDK_18"]
override fun defaultBuildOptions() =
super.defaultBuildOptions().copy(androidHome = File("../../../dependencies/android-sdk-for-tests"),
androidGradlePluginVersion = androidGradlePluginVersion, javaHome = File(getEnvJDK_18()))
@Test
fun testSimpleCompile() {
val project = Project("AndroidJackProject", gradleVersion)
project.build("build", "test") {
assertSuccessful()
assertContains(
":Lib:compileReleaseKotlin",
":compileFlavor1DebugKotlin",
":zipKotlinClassesForFlavor1Debug",
":transformKotlinClassesWithJillForFlavor1Debug",
":compileFlavor2DebugKotlin",
":zipKotlinClassesForFlavor2Debug",
":transformKotlinClassesWithJillForFlavor2Debug",
":compileFlavor1JnidebugKotlin",
":zipKotlinClassesForFlavor1Jnidebug",
":transformKotlinClassesWithJillForFlavor1Jnidebug",
":compileFlavor1ReleaseKotlin",
":zipKotlinClassesForFlavor1Release",
":transformKotlinClassesWithJillForFlavor1Release",
":compileFlavor2JnidebugKotlin",
":zipKotlinClassesForFlavor2Jnidebug",
":transformKotlinClassesWithJillForFlavor2Jnidebug",
":compileFlavor2ReleaseKotlin",
":zipKotlinClassesForFlavor2Release",
":transformKotlinClassesWithJillForFlavor2Release",
":compileFlavor1DebugUnitTestKotlin",
"InternalDummyTest PASSED"
)
checkKotlinGradleBuildServices()
}
// Run the build second time, assert everything is up-to-date
project.build("build") {
assertSuccessful()
assertContains(
":Lib:compileReleaseKotlin UP-TO-DATE",
":compileFlavor1DebugKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor1Debug UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor1Debug UP-TO-DATE",
":compileFlavor2DebugKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor2Debug UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor2Debug UP-TO-DATE",
":compileFlavor1JnidebugKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor1Jnidebug UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor1Jnidebug UP-TO-DATE",
":compileFlavor1ReleaseKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor1Release UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor1Release UP-TO-DATE",
":compileFlavor2JnidebugKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor2Jnidebug UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor2Jnidebug UP-TO-DATE",
":compileFlavor2ReleaseKotlin UP-TO-DATE",
":zipKotlinClassesForFlavor2Release UP-TO-DATE",
":transformKotlinClassesWithJillForFlavor2Release UP-TO-DATE"
)
}
project.build("build", "--rerun-tasks") {
assertSuccessful()
assertContains(
":Lib:compileReleaseKotlin",
":compileFlavor1DebugKotlin",
":zipKotlinClassesForFlavor1Debug",
":transformKotlinClassesWithJillForFlavor1Debug",
":compileFlavor2DebugKotlin",
":zipKotlinClassesForFlavor2Debug",
":transformKotlinClassesWithJillForFlavor2Debug",
":compileFlavor1JnidebugKotlin",
":zipKotlinClassesForFlavor1Jnidebug",
":transformKotlinClassesWithJillForFlavor1Jnidebug",
":compileFlavor1ReleaseKotlin",
":zipKotlinClassesForFlavor1Release",
":transformKotlinClassesWithJillForFlavor1Release",
":compileFlavor2JnidebugKotlin",
":zipKotlinClassesForFlavor2Jnidebug",
":transformKotlinClassesWithJillForFlavor2Jnidebug",
":compileFlavor2ReleaseKotlin",
":zipKotlinClassesForFlavor2Release",
":transformKotlinClassesWithJillForFlavor2Release",
":compileFlavor1DebugUnitTestKotlin",
"InternalDummyTest PASSED"
)
checkKotlinGradleBuildServices()
}
}
@Test
fun testDagger() {
val project = Project("AndroidDaggerJackProject", gradleVersion)
val options = defaultBuildOptions().copy(incremental = false)
project.build("assembleDebug", options = options) {
assertSuccessful()
assertContains(
":kaptDebugKotlin",
":compileDebugKotlin",
":zipKotlinClassesForDebug",
":transformKotlinClassesWithJillForDebug",
":transformJackWithJackForDebug"
)
}
}
@Test
fun testAndroidExtensions() {
val project = Project("AndroidExtensionsJackProject", gradleVersion)
val options = defaultBuildOptions().copy(incremental = false)
project.build("assembleDebug", options = options) {
assertSuccessful()
assertContains(
":compileDebugKotlin",
":zipKotlinClassesForDebug",
":transformKotlinClassesWithJillForDebug",
":transformJackWithJackForDebug"
)
}
}
@Test
fun testIcepick() {
val project = Project("AndroidIcepickJackProject", gradleVersion)
val options = defaultBuildOptions().copy(incremental = false)
project.build("assembleDebug", options = options) {
assertSuccessful()
assertContains(
":kaptDebugKotlin",
":compileDebugKotlin",
":zipKotlinClassesForDebug",
":transformKotlinClassesWithJillForDebug",
":transformJackWithJackForDebug"
)
}
}
}
@@ -24,6 +24,7 @@ abstract class BaseGradleIT {
@Before
fun setUp() {
workingDir = FileUtil.createTempDirectory("BaseGradleIT", null)
acceptAndroidSdkLicenses()
}
@After
@@ -31,34 +32,59 @@ abstract class BaseGradleIT {
workingDir.deleteRecursively()
}
// https://developer.android.com/studio/intro/update.html#download-with-gradle
fun acceptAndroidSdkLicenses() = defaultBuildOptions().androidHome?.let {
val sdkLicenses = File(it, "licenses")
sdkLicenses.mkdirs()
val sdkLicense = File(sdkLicenses, "android-sdk-license")
if (!sdkLicense.exists()) {
sdkLicense.createNewFile()
sdkLicense.writeText("8933bad161af4178b1185d1a37fbf41ea5269c55")
}
val sdkPreviewLicense = File(sdkLicenses, "android-sdk-preview-license")
if (!sdkPreviewLicense.exists()) {
sdkPreviewLicense.writeText("84831b9409646a918e30573bab4c9c91346d8abd")
}
}
companion object {
@JvmStatic
protected val ranDaemonVersions = hashMapOf<String, Int>()
val resourcesRootFile = File("src/test/resources")
val MAX_DAEMON_RUNS = 30
fun getEnvJDK_18() = System.getenv()["JDK_18"]
@AfterClass
@JvmStatic
@Synchronized
@Suppress("unused")
fun tearDownAll() {
ranDaemonVersions.keys.forEach { stopDaemon(it) }
// Latest gradle requires Java > 7
val environmentVariables = hashMapOf<String, String>()
getEnvJDK_18()?.let { environmentVariables["JAVA_HOME"] = it }
ranDaemonVersions.keys.forEach { stopDaemon(it, environmentVariables) }
ranDaemonVersions.clear()
}
fun stopDaemon(ver: String) {
fun stopDaemon(ver: String, environmentVariables: Map<String, String> = mapOf()) {
println("Stopping gradle daemon v$ver")
val wrapperDir = File(resourcesRootFile, "GradleWrapper-$ver")
val cmd = createGradleCommand(arrayListOf("-stop"))
val result = runProcess(cmd, wrapperDir)
val result = runProcess(cmd, wrapperDir, environmentVariables)
assert(result.isSuccessful) { "Could not stop daemon: $result" }
}
@Synchronized
fun prepareDaemon(version: String) {
fun prepareDaemon(version: String, environmentVariables: Map<String, String> = mapOf()) {
val useCount = ranDaemonVersions.get(version)
if (useCount == null || useCount > MAX_DAEMON_RUNS) {
stopDaemon(version)
stopDaemon(version, environmentVariables)
ranDaemonVersions.put(version, 1)
}
else {
@@ -73,6 +99,7 @@ abstract class BaseGradleIT {
val daemonOptionSupported: Boolean = true,
val incremental: Boolean? = null,
val androidHome: File? = null,
val javaHome: File? = null,
val androidGradlePluginVersion: String? = null,
val forceOutputToStdout: Boolean = false,
val debug: Boolean = false,
@@ -140,7 +167,7 @@ abstract class BaseGradleIT {
val env = createEnvironmentVariablesMap(options)
if (options.withDaemon) {
prepareDaemon(wrapperVersion)
prepareDaemon(wrapperVersion, env)
}
println("<=== Test build: ${this.projectName} $cmd ===>")
@@ -284,13 +311,16 @@ abstract class BaseGradleIT {
addAll(options.freeCommandLineArgs)
}
private fun Project.createEnvironmentVariablesMap(options: BuildOptions): Map<String, String> =
private fun createEnvironmentVariablesMap(options: BuildOptions): Map<String, String> =
hashMapOf<String, String>().apply {
val sdkDir = options.androidHome
if (sdkDir != null) {
options.androidHome?.let { sdkDir ->
sdkDir.parentFile.mkdirs()
put("ANDROID_HOME", sdkDir.canonicalPath)
}
options.javaHome?.let {
put("JAVA_HOME", it.canonicalPath)
}
}
private fun String.normalize() = this.lineSequence().joinToString(SYSTEM_LINE_SEPARATOR)
@@ -0,0 +1,6 @@
#Mon Jan 23 22:08:28 MSK 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,41 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.dagger.kotlin"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.google.dagger:dagger:2.2'
kapt 'com.google.dagger:dagger-compiler:2.2'
provided 'org.glassfish:javax.annotation:10.0-b28'
}
@@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/yan/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.dagger.kotlin">
<application
android:allowBackup="true"
android:label="app_name"
android:name=".DemoApplication">
<activity
android:label="app_name"
android:name=".ui.HomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,44 @@
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dagger.kotlin
import android.content.Context
import android.content.Context.LOCATION_SERVICE
import android.location.LocationManager
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* A module for Android-specific dependencies which require a [Context] or
* [android.app.Application] to create.
*/
@Module class AndroidModule(private val application: BaseApplication) {
/**
* Allow the application context to be injected but require that it be annotated with
* [@Annotation][ForApplication] to explicitly differentiate it from an activity context.
*/
@Provides @Singleton @ForApplication
fun provideApplicationContext(): Context {
return application
}
@Provides @Singleton
fun provideLocationManager(): LocationManager {
return application.getSystemService(LOCATION_SERVICE) as LocationManager
}
}
@@ -0,0 +1,13 @@
package com.example.dagger.kotlin
import com.example.dagger.kotlin.ui.HomeActivity
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AndroidModule::class))
interface ApplicationComponent {
fun inject(application: BaseApplication)
fun inject(homeActivity: HomeActivity)
fun inject(demoActivity: DemoActivity)
}
@@ -0,0 +1,11 @@
package com.example.dagger.kotlin
import android.app.Application
abstract class BaseApplication : Application() {
protected fun initDaggerComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder().androidModule(AndroidModule(this)).build()
}
}
@@ -0,0 +1,12 @@
package com.example.dagger.kotlin
import android.app.Activity
import android.os.Bundle
abstract class DemoActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Perform injection so that when this call returns all dependencies will be available for use.
(application as DemoApplication).component.inject(this)
}
}
@@ -0,0 +1,13 @@
package com.example.dagger.kotlin
class DemoApplication : BaseApplication() {
lateinit var component: ApplicationComponent
override fun onCreate() {
super.onCreate()
val component = initDaggerComponent()
component.inject(this) // As of now, LocationManager should be injected into this.
this.component = component
}
}
@@ -0,0 +1,6 @@
package com.example.dagger.kotlin
import javax.inject.Qualifier
@Qualifier
annotation class ForApplication
@@ -0,0 +1,9 @@
package com.example.dagger.kotlin
import android.app.Activity
class UseRJavaActivity : Activity() {
fun useRJava() {
val app_name = getResources().getString(R.string.app_name)
}
}
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dagger.kotlin.ui
import android.location.LocationManager
import android.os.Bundle
import com.example.dagger.kotlin.DemoActivity
import com.example.dagger.kotlin.DemoApplication
import com.example.dagger.kotlin.R
import kotlinx.android.synthetic.main.activity_main.locationInfo
import javax.inject.Inject
class HomeActivity : DemoActivity() {
@Inject
lateinit var locationManager: LocationManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as DemoApplication).component.inject(this)
// TODO do something with the injected dependencies here!
locationInfo.text = "Injected LocationManager:\n$locationManager"
}
}
@@ -0,0 +1,5 @@
package com.example.dagger.kotlin
fun useBuildConfigJava() {
if (BuildConfig.APPLICATION_ID != "com.example.dagger.kotlin") throw AssertionError()
}
@@ -0,0 +1,10 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".ui.HomeActivity">
<TextView android:id="@+id/locationInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp" />
</RelativeLayout>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">kotlin</string>
</resources>
@@ -0,0 +1,8 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
@@ -0,0 +1,18 @@
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.android.tools.build:gradle:$android_tools_version"
}
}
allprojects {
repositories {
mavenLocal()
mavenCentral()
}
}
@@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.jvmargs=-Xmx1536M
@@ -0,0 +1,27 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 23
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.dagger.kotlin"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
jackOptions { enabled true }
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidextensions">
<application android:label="app_name">
<activity
android:label="app_name"
android:name="com.example.androidextensions.MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,30 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androidextensions
import android.os.Bundle
import android.app.Activity
import kotlinx.android.synthetic.main.activity_main.textView
class HomeActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.textView.setText("Hello, world!")
}
}
@@ -0,0 +1,9 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">kotlin</string>
</resources>
@@ -0,0 +1,20 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.android.tools.build:gradle:$android_tools_version"
}
}
allprojects {
repositories {
mavenLocal()
jcenter()
}
}
@@ -0,0 +1,43 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
dependencies {
compile "frankiesardo:icepick:3.2.0"
kapt "frankiesardo:icepick-processor:3.2.0"
compile 'org.parceler:parceler-api:1.1.5'
kapt 'org.parceler:parceler:1.1.5'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
android {
compileSdkVersion 23
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.icepick.kotlin"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
jackOptions { enabled true }
}
lintOptions {
abortOnError false
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
repositories {
mavenCentral()
maven {
url "https://clojars.org/repo/"
}
mavenLocal()
}
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.frankiesardo.icepick"
android:versionCode="1"
android:versionName="1.0">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,28 @@
package com.github.frankiesardo.icepick
import android.content.Context
import android.os.Parcelable
import android.util.AttributeSet
import com.sample.icepick.lib.BaseCustomView
import icepick.State
class CustomView : BaseCustomView {
@JvmField @State
var textColor: Int? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setTextColorWithAnotherMethod(color: Int) {
this.textColor = color
setTextColor(textColor!!)
}
override fun onRestoreInstanceState(state: Parcelable) {
super.onRestoreInstanceState(state)
if (textColor != null) {
setTextColorWithAnotherMethod(textColor!!)
}
}
}
@@ -0,0 +1,19 @@
package com.github.frankiesardo.icepick
import org.parceler.Parcel
@Parcel
class Example {
lateinit var name: String
@JvmField
var age: Int = 0
constructor() { /*Required empty bean constructor*/
}
constructor(age: Int, name: String) {
this.age = age
this.name = name
}
}
@@ -0,0 +1,18 @@
package com.github.frankiesardo.icepick
import android.os.Bundle
import android.os.Parcelable
import org.parceler.Parcels
import icepick.Bundler
class ExampleBundler : Bundler<Any> {
override fun put(s: String, example: Any, bundle: Bundle) {
bundle.putParcelable(s, Parcels.wrap(example))
}
override fun get(s: String, bundle: Bundle): Any {
return Parcels.unwrap<Any>(bundle.getParcelable<Parcelable>(s))
}
}
@@ -0,0 +1,49 @@
package com.github.frankiesardo.icepick
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.sample.icepick.lib.BaseActivity
import icepick.State
class MainActivity : BaseActivity() {
@JvmField @State(MyBundler::class)
var message: String? = null
lateinit var customView: CustomView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
customView = findViewById(R.id.custom_view) as CustomView
updateText()
}
private fun updateText() {
val defaultText = if (message == null || baseMessage == null) {
"Use the menu to add some state"
} else {
baseMessage + message
}
customView.text = defaultText
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return super.onPrepareOptionsMenu(menu)
}
override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean {
if (item.itemId == R.id.action_add_state) {
customView.setBackgroundColorWithAnotherMethod(Color.BLUE)
customView.setTextColorWithAnotherMethod(Color.WHITE)
baseMessage = "This state will be automagically "
message = "saved and restored"
updateText()
return true
}
return super.onMenuItemSelected(featureId, item)
}
}
@@ -0,0 +1,17 @@
package com.github.frankiesardo.icepick
import android.os.Bundle
import icepick.Bundler
class MyBundler : Bundler<String> {
override fun put(key: String, value: String?, bundle: Bundle) {
if (value != null) {
bundle.putString(key, value + "*")
}
}
override fun get(key: String, bundle: Bundle): String? {
return bundle.getString(key)
}
}
@@ -0,0 +1,24 @@
package com.sample.icepick.lib
import android.app.Activity
import android.os.Bundle
import android.os.Parcelable
import icepick.Icepick
import icepick.State
import android.util.Log
open class BaseActivity : Activity() {
@JvmField @State
var baseMessage: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Icepick.restoreInstanceState(this, savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Icepick.saveInstanceState(this, outState)
}
}
@@ -0,0 +1,34 @@
package com.sample.icepick.lib
import android.content.Context
import android.os.Parcelable
import android.util.AttributeSet
import android.widget.TextView
import icepick.Icepick
import icepick.State
open class BaseCustomView : TextView {
@JvmField @State
var backgroundColor: Int? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setBackgroundColorWithAnotherMethod(color: Int) {
this.backgroundColor = color
setBackgroundColor(color)
}
override fun onSaveInstanceState(): Parcelable {
return Icepick.saveInstanceState(this, super.onSaveInstanceState())
}
override fun onRestoreInstanceState(state: Parcelable) {
super.onRestoreInstanceState(Icepick.restoreInstanceState(this, state))
if (backgroundColor != null) {
setBackgroundColorWithAnotherMethod(backgroundColor!!)
}
}
}
@@ -0,0 +1,12 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.github.frankiesardo.icepick.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="@+id/custom_view"/>
</LinearLayout>
@@ -0,0 +1,7 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_add_state"
android:title="@string/action_add_state"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Icepick</string>
<string name="action_add_state">Add some state</string>
</resources>
@@ -0,0 +1,11 @@
buildscript {
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$android_tools_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
@@ -0,0 +1,52 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
dependencies {
compile project(':Lib')
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile 'junit:junit:4.12'
}
android {
compileSdkVersion 22
buildToolsVersion "25.0.1"
sourceSets {
main.java.srcDirs += 'src/main/java2'
main.kotlin.srcDirs += 'root/kotlin'
test.kotlin.srcDirs += 'src/test/kotlin'
}
defaultConfig {
minSdkVersion 7
targetSdkVersion 22
jackOptions { enabled true }
}
buildTypes {
jnidebug.initWith(buildTypes.debug)
jnidebug {
applicationIdSuffix ".jnidebug"
jniDebuggable true
}
}
productFlavors {
flavor1 {
applicationId "com.example.flavor1"
versionCode 20
}
flavor2 {
applicationId "com.example.flavor2"
minSdkVersion 14
}
}
publishNonDefault true
kotlinOptions {
noJdk = true
}
}
@@ -0,0 +1,59 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.test.androidalfa
import android.content.Intent
import android.os.Bundle
import android.app.Activity
import android.view.Menu
import android.view.View
import android.widget.Button
import org.jetbrains.kotlin.gradle.test.androidalfa.R
import lib.*
open class MainActivity2: Activity() {
protected override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
libUtil()
var next: Button = findViewById(R.id.Button02) as Button
next.setOnClickListener(object: View.OnClickListener {
public override fun onClick(view: View): Unit {
val intent: Intent = Intent()
setResult(Activity.RESULT_OK, intent)
finish()
}
})
}
public override fun onCreateOptionsMenu(menu: Menu?): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true
}
}
fun foo() {
bar()
}
fun bar() {
}
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle
import android.app.Application
import android.test.ApplicationTestCase
class InternalDummyApplicationTest : ApplicationTestCase<Application>(Application::class.java) {
init {
val dummy = InternalDummy("World")
assert("Hello World!" == dummy.greeting) { "Expected: 'Hello World!'. Actual value: ${dummy.greeting}" }
}
}
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.jetbrains.kotlin.gradle.test.androidalfa"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="org.jetbrains.kotlin.gradle.test.androidalfa.MainActivity"
android:label="@string/title_activity_main_activity1" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="org.jetbrains.kotlin.gradle.test.androidalfa.MainActivity2"
android:label="@string/title_activity_main_activity2" >
</activity>
</application>
</manifest>
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package foo;
import bar.*;
public class FooJavaClass {
void f() {
new FooKotlinClass();
new BarJavaClass();
new BarKotlinClass();
}
}
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package foo
import bar.*
class FooKotlinClass {
fun f() {
FooJavaClass()
BarJavaClass()
BarKotlinClass()
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle
internal class InternalDummy(private val name: String) {
internal val greeting: String
get() = "Hello $name!"
}
@@ -0,0 +1,52 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.test.androidalfa;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import org.jetbrains.kotlin.gradle.test.androidalfa.R;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.Button01);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity2.class);
startActivityForResult(myIntent, 0);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bar;
import foo.*;
public class BarJavaClass {
void f() {
new BarKotlinClass();
new FooJavaClass();
new FooKotlinClass();
}
}
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bar
import foo.*
class BarKotlinClass {
fun f() {
BarJavaClass()
FooJavaClass()
FooKotlinClass()
}
}
@@ -0,0 +1,24 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Activity 1" />
<Button android:text="Next"
android:id="@+id/Button01"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
@@ -0,0 +1,24 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Activity 2" />
<Button android:text="Next"
android:id="@+id/Button02"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
@@ -0,0 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndroidAlfa</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title_activity_main_activity1">MainActivity1</string>
<string name="title_activity_main_activity2">MainActivity2</string>
</resources>
@@ -0,0 +1,20 @@
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
@@ -0,0 +1,28 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle
import org.junit.Assert
import org.junit.Test
class InternalDummyTest {
@Test
fun testInternalDummy() {
val dummy = InternalDummy("World")
Assert.assertEquals("Hello World!", dummy.greeting)
}
}
@@ -0,0 +1,19 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
dependencies {
compile files('libs/android-support-v4.jar')
// unused but needed for IncrementalCompilationMultiProjectIT.testAndroid to check if non-local dependency affects IC
compile 'io.reactivex:rxjava:1.1.9'
compile 'com.loopj.android:android-async-http:1.4.9'
}
android {
compileSdkVersion 22
buildToolsVersion "25.0.1"
defaultConfig {
minSdkVersion 7
targetSdkVersion 22
}
}
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.jetbrains.kotlin.gradle.test.android.libalfa"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="org.jetbrains.kotlin.gradle.test.android.libalfa.LibMainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,39 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.test.android.libalfa;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class LibMainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lib_activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lib_main, menu);
return true;
}
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lib
fun libUtil(): String = "libUtil"
@@ -0,0 +1,16 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".LibMainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
@@ -0,0 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
@@ -0,0 +1,4 @@
<resources>
<!-- Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw600dp devices (e.g. 7" tablets) here. -->
</resources>
@@ -0,0 +1,5 @@
<resources>
<!-- Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. -->
<dimen name="activity_horizontal_margin">128dp</dimen>
</resources>
@@ -0,0 +1,11 @@
<resources>
<!--
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
<!-- API 11 theme customizations can go here. -->
</style>
</resources>
@@ -0,0 +1,12 @@
<resources>
<!--
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
</resources>
@@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">LibAlfa</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
@@ -0,0 +1,20 @@
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
@@ -0,0 +1,18 @@
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.android.tools.build:gradle:$android_tools_version"
}
}
allprojects {
repositories {
mavenLocal()
mavenCentral()
}
}
+1 -1
View File
@@ -69,7 +69,7 @@
<dependency>
<groupId>com.android.tools.build</groupId>
<artifactId>gradle</artifactId>
<version>1.1.0</version>
<version>2.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -213,6 +213,11 @@ class Kapt3KotlinGradleSubplugin : KotlinGradleSubplugin<KotlinCompile> {
// Add generated source dir as a source root for kotlinCompile and javaCompile
kotlinCompile.source(sourcesOutputDir)
javaCompile.source(sourcesOutputDir)
variantData?.let {
if (AndroidGradleWrapper.isJackEnabled(it)) {
AndroidGradleWrapper.addSourceToJack(it, sourcesOutputDir)
}
}
val pluginOptions = kaptTask.pluginOptions
val compilerPluginId = getCompilerPluginId()
@@ -226,6 +231,12 @@ class Kapt3KotlinGradleSubplugin : KotlinGradleSubplugin<KotlinCompile> {
val options = javaCompile.options
options.compilerArgs = options.compilerArgs.filter { !it.startsWith("-proc:") } + "-proc:none"
}
variantData?.let {
if (AndroidGradleWrapper.isJackEnabled(it)) {
AndroidGradleWrapper.disableJackAnnotationProcessing(it)
}
}
}
private val BaseVariantData<*>.sourceProviders: List<SourceProvider>
@@ -17,6 +17,7 @@ import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.api.tasks.compile.JavaCompile
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptionsImpl
@@ -25,6 +26,7 @@ import org.jetbrains.kotlin.gradle.internal.Kapt3GradleSubplugin
import org.jetbrains.kotlin.gradle.internal.Kapt3KotlinGradleSubplugin
import org.jetbrains.kotlin.gradle.internal.initKapt
import org.jetbrains.kotlin.gradle.plugin.android.AndroidGradleWrapper
import org.jetbrains.kotlin.gradle.plugin.android.KotlinJillTask
import org.jetbrains.kotlin.gradle.tasks.*
import org.jetbrains.kotlin.incremental.configureMultiProjectIncrementalCompilation
import org.jetbrains.kotlin.incremental.multiproject.ArtifactDifferenceRegistryProviderAndroidWrapper
@@ -364,7 +366,8 @@ internal open class KotlinAndroidPlugin(
val variantDataName = variantData.name
logger.kotlinDebug("Process variant [$variantDataName]")
val javaTask = AndroidGradleWrapper.getJavaCompile(variantData)
val javaTask = AndroidGradleWrapper.getJavaTask(variantData)
if (javaTask == null) {
logger.info("KOTLIN: javaTask is missing for $variantDataName, so Kotlin files won't be compiled for it")
continue
@@ -434,6 +437,30 @@ internal open class KotlinAndroidPlugin(
configureMultiProjectIncrementalCompilation(project, kotlinTask, javaTask, kotlinAfterJavaTask,
artifactDifferenceRegistryProvider, artifactFile)
}
if (AndroidGradleWrapper.isJackEnabled(variantData)) {
val scope = variantData.scope
val kotlinDestinationDir = kotlinTask.destinationDir
val jarPath = File(kotlinDestinationDir.parent, kotlinDestinationDir.name + ".jar")
val zipTaskName = scope.getTaskName("zipKotlinClassesFor")
project.tasks.create(zipTaskName, Zip::class.java) { zipTask ->
zipTask.from(kotlinDestinationDir)
zipTask.destinationDir = File(jarPath.parent)
zipTask.archiveName = jarPath.name
zipTask.dependsOn(kotlinTask)
}
val kotlinJillTaskName = scope.getTaskName("transformKotlinClassesWithJillFor")
val jillOutputFilePath = File(jarPath.absolutePath + ".jill")
project.tasks.create(kotlinJillTaskName, KotlinJillTask::class.java) { jillTask ->
jillTask.buildTools = variantData.scope.globalScope.androidBuilder.targetInfo.buildTools
jillTask.inputJarFile = jarPath
jillTask.outputJillFile = jillOutputFilePath
jillTask.dependsOn(zipTaskName)
}
AndroidGradleWrapper.configureJackTask(variantData, jillOutputFilePath, kotlinJillTaskName)
}
}
}
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.gradle.plugin.android
import com.android.build.api.transform.*
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.BasePlugin
import com.android.build.gradle.api.AndroidSourceSet
@@ -23,8 +24,9 @@ import com.android.build.gradle.api.ApkVariant
import com.android.build.gradle.api.BaseVariant
import com.android.build.gradle.api.TestVariant
import com.android.build.gradle.internal.VariantManager
import com.android.build.gradle.internal.pipeline.OriginalStream
import com.android.build.gradle.internal.pipeline.TransformTask
import com.android.build.gradle.internal.variant.BaseVariantData
import com.android.builder.dependency.LibraryDependency
import com.android.builder.model.SourceProvider
import org.gradle.api.file.ConfigurableFileTree
import org.gradle.api.internal.DefaultDomainObjectSet
@@ -64,7 +66,85 @@ class AndroidGradleWrapper {
}
@Nullable
static AbstractCompile getJavaCompile(Object baseVariantData) {
private static getJackOptions(@NotNull Object variantData) {
def variantConfiguration = variantData.variantConfiguration
if (variantConfiguration.getMetaClass().getMetaMethod("getJackOptions")) {
return variantConfiguration.getJackOptions()
}
return null
}
static boolean isJackEnabled(@NotNull Object variantData) {
return getJackOptions(variantData)?.enabled ?: false
}
@Nullable
static AbstractCompile getJavaTask(@NotNull Object variantData) {
if (isJackEnabled(variantData)) {
return getJavacTask(variantData)
}
else {
return getJavaCompile(variantData)
}
}
@Nullable
private static AbstractCompile getJavacTask(@NotNull Object baseVariantData) {
if (baseVariantData.getMetaClass().getMetaProperty("javacTask")) {
return baseVariantData.javacTask
}
return null
}
@Nullable
private static TransformTask getJackTask(@NotNull Object variantData) {
def compilerTask = variantData.javaCompilerTask
if (compilerTask instanceof TransformTask) {
return compilerTask
}
return null
}
@Nullable
private static getJackTransform(@NotNull Object variantData) {
return getJackTask(variantData)?.transform
}
static addSourceToJack(@NotNull Object variantData, @NotNull File sourceFolder) {
getJackTransform(variantData)?.addSource(sourceFolder)
}
static disableJackAnnotationProcessing(@NotNull Object variantData) {
def jackOptions = getJackTransform(variantData)?.options
jackOptions?.setAnnotationProcessorOutputDirectory(null)
jackOptions?.setAnnotationProcessorNames([])
jackOptions?.setAnnotationProcessorClassPath([])
jackOptions?.setAnnotationProcessorOptions([:])
}
static configureJackTask(
@NotNull Object variantData,
@NotNull File jillOutputFile,
@NotNull String kotlinJillTaskName) {
def jackTask = getJackTask(variantData)
// There is no Jack task for some variants
if (jackTask == null) {
return
}
def jillOutputStream = OriginalStream.builder()
.addContentType(QualifiedContent.DefaultContentType.CLASSES)
.addScope(QualifiedContent.Scope.PROJECT)
.setJar(jillOutputFile)
.setDependency(kotlinJillTaskName)
.build()
jackTask.consumedInputStreams.add(jillOutputStream)
jackTask.dependsOn(kotlinJillTaskName)
}
@Nullable
private static AbstractCompile getJavaCompile(@NotNull Object baseVariantData) {
if (baseVariantData.getMetaClass().getMetaProperty("javaCompileTask")) {
return baseVariantData.javaCompileTask
}
@@ -0,0 +1,52 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin.android
import com.android.builder.core.BuildToolsServiceLoader
import com.android.jill.api.v01.Api01Config
import com.android.sdklib.BuildToolInfo
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import java.io.File
open class KotlinJillTask : DefaultTask() {
@InputFile
lateinit var inputJarFile: File
@OutputFile
lateinit var outputJillFile: File
lateinit var buildTools: BuildToolInfo
@TaskAction
fun transform() {
val jillProvider = BuildToolsServiceLoader.INSTANCE
.forVersion(buildTools)
.getServiceLoader(BuildToolsServiceLoader.JILL)
.firstOrNull() ?: error("Jill provider not found")
outputJillFile.parentFile.mkdirs()
val config01: Api01Config = jillProvider.createConfig(Api01Config::class.java)
config01.setInputJavaBinaryFile(inputJarFile)
config01.setOutputJackFile(outputJillFile)
config01.task.run()
}
}