Cleanup Android Extensions code

This commit is contained in:
Yan Zhulanow
2015-10-21 21:02:20 +03:00
parent dc7171e953
commit a6e9ee9323
18 changed files with 47 additions and 57 deletions
@@ -23,11 +23,11 @@ import java.util.HashMap
class AndroidXmlHandler(private val elementCallback: (String, String) -> Unit) : DefaultHandler() { class AndroidXmlHandler(private val elementCallback: (String, String) -> Unit) : DefaultHandler() {
override fun startDocument() { override fun startDocument() {
super<DefaultHandler>.startDocument() super.startDocument()
} }
override fun endDocument() { override fun endDocument() {
super<DefaultHandler>.endDocument() super.endDocument()
} }
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) { override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
@@ -47,7 +47,7 @@ class AndroidXmlHandler(private val elementCallback: (String, String) -> Unit) :
public fun Attributes.toMap(): HashMap<String, String> { public fun Attributes.toMap(): HashMap<String, String> {
val res = HashMap<String, String>() val res = HashMap<String, String>()
for (index in 0..getLength() - 1) { for (index in 0..length - 1) {
val attrName = getLocalName(index)!! val attrName = getLocalName(index)!!
val attrVal = getValue(index)!! val attrVal = getValue(index)!!
res[attrName] = attrVal res[attrName] = attrVal
@@ -67,12 +67,6 @@ open class Context(val buffer: StringBuffer = StringBuffer(), private var indent
return child return child
} }
public fun adopt<T : Context>(c: T, inheritIndent: Boolean = true): T {
children.add(c)
if (inheritIndent) c.currentIndent = currentIndent
return c
}
public fun absorbChildren(noIndent: Boolean = true) { public fun absorbChildren(noIndent: Boolean = true) {
for (child in children) { for (child in children) {
child.absorbChildren() child.absorbChildren()
@@ -45,7 +45,7 @@ public class AndroidOnDestroyClassBuilderInterceptorExtension : ClassBuilderInte
return AndroidOnDestroyCollectorClassBuilder(delegateFactory.newClassBuilder(origin), bindingContext) return AndroidOnDestroyCollectorClassBuilder(delegateFactory.newClassBuilder(origin), bindingContext)
} }
override fun getClassBuilderMode() = delegateFactory.getClassBuilderMode() override fun getClassBuilderMode() = delegateFactory.classBuilderMode
override fun asText(builder: ClassBuilder?): String? { override fun asText(builder: ClassBuilder?): String? {
return delegateFactory.asText((builder as AndroidOnDestroyCollectorClassBuilder).delegateClassBuilder) return delegateFactory.asText((builder as AndroidOnDestroyCollectorClassBuilder).delegateClassBuilder)
@@ -16,9 +16,7 @@
package org.jetbrains.kotlin.android.synthetic.diagnostic package org.jetbrains.kotlin.android.synthetic.diagnostic
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.android.synthetic.AndroidConst import org.jetbrains.kotlin.android.synthetic.AndroidConst
import org.jetbrains.kotlin.android.synthetic.CliAndroidDeclarationsProvider
import org.jetbrains.kotlin.android.synthetic.res.SyntheticFileGenerator import org.jetbrains.kotlin.android.synthetic.res.SyntheticFileGenerator
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
@@ -26,7 +24,6 @@ import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.constants.StringValue import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.android.synthetic.diagnostic.ErrorsAndroid.* import org.jetbrains.kotlin.android.synthetic.diagnostic.ErrorsAndroid.*
import org.jetbrains.kotlin.extensions.ExternalDeclarationsProvider
public class AndroidExtensionPropertiesCallChecker : CallChecker { public class AndroidExtensionPropertiesCallChecker : CallChecker {
override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) { override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) {
@@ -65,17 +65,17 @@ public abstract class AndroidLayoutXmlFileManager(val project: Project) {
list list
} }
val layoutNameToXmls = allLayoutPsiFiles val layoutNameToXmlFiles = allLayoutPsiFiles
.groupBy { it.name.substringBeforeLast('.') } .groupBy { it.name.substringBeforeLast('.') }
.mapValues { it.getValue().sortedBy { it.parent!!.name.length() } } .mapValues { it.getValue().sortedBy { it.parent!!.name.length() } }
return layoutNameToXmls return layoutNameToXmlFiles
} }
companion object { companion object {
public fun getInstance(module: Module): AndroidLayoutXmlFileManager { public fun getInstance(module: Module): AndroidLayoutXmlFileManager? {
val service = ModuleServiceManager.getService(module, javaClass<AndroidLayoutXmlFileManager>()) val service = ModuleServiceManager.getService(module, AndroidLayoutXmlFileManager::class.java)
return service ?: module.getComponent(javaClass<AndroidLayoutXmlFileManager>())!! return service ?: module.getComponent(AndroidLayoutXmlFileManager::class.java)
} }
} }
@@ -85,7 +85,7 @@ public open class CliSyntheticFileGenerator(
} }
private companion object { private companion object {
private val LOG: Logger = Logger.getInstance(javaClass) private val LOG: Logger = Logger.getInstance(CliSyntheticFileGenerator::class.java)
} }
} }
@@ -41,7 +41,7 @@ public abstract class AbstractAndroidBoxTest : AbstractBlackBoxCodegenTest() {
} }
private fun createEnvironmentForConfiguration(configuration: CompilerConfiguration, path: String) { private fun createEnvironmentForConfiguration(configuration: CompilerConfiguration, path: String) {
val layoutPaths = File(path).listFiles { it.name.startsWith("layout") && it.isDirectory() }!!.map { "$path${it.name}/" } val layoutPaths = File(path).listFiles { it.name.startsWith("layout") && it.isDirectory }!!.map { "$path${it.name}/" }
val manifestPath = path + "AndroidManifest.xml" val manifestPath = path + "AndroidManifest.xml"
val supportV4 = File(path).name.startsWith("support") val supportV4 = File(path).name.startsWith("support")
myEnvironment = createAndroidTestEnvironment(configuration, layoutPaths, manifestPath, supportV4) myEnvironment = createAndroidTestEnvironment(configuration, layoutPaths, manifestPath, supportV4)
@@ -83,7 +83,7 @@ public abstract class AbstractAndroidBoxTest : AbstractBlackBoxCodegenTest() {
if (additionalFiles != null) files.add(relativePath(file)) if (additionalFiles != null) files.add(relativePath(file))
} }
else -> { else -> {
if (file.getName().endsWith(".kt")) files.add(relativePath(file)) if (file.name.endsWith(".kt")) files.add(relativePath(file))
} }
} }
return true return true
@@ -41,9 +41,9 @@ public abstract class AbstractAndroidXml2KConversionTest : UsefulTestCase() {
val actual = parser.gen().toMap { it.name } val actual = parser.gen().toMap { it.name }
val expectedLayoutFiles = testDirectory.listFiles { val expectedLayoutFiles = testDirectory
it.isFile() && it.name.endsWith(".kt") .listFiles { it.isFile && it.name.endsWith(".kt") }
}?.toMap { it.name.substringBefore(".kt") } ?: mapOf() ?.toMap { it.name.substringBefore(".kt") } ?: mapOf()
assertEquals(expectedLayoutFiles.size(), actual.size()) assertEquals(expectedLayoutFiles.size(), actual.size())
@@ -59,12 +59,11 @@ public abstract class AbstractAndroidXml2KConversionTest : UsefulTestCase() {
doTest(path) doTest(path)
fail("NoAndroidManifestFound not thrown") fail("NoAndroidManifestFound not thrown")
} }
catch (e: SyntheticFileGenerator.NoAndroidManifestFound) { catch (e: SyntheticFileGenerator.NoAndroidManifestFound) {}
}
} }
private fun getEnvironment(): KotlinCoreEnvironment { private fun getEnvironment(): KotlinCoreEnvironment {
val configuration = KotlinTestUtils.compilerConfigurationForTests(ConfigurationKind.ALL, TestJdkKind.ANDROID_API) val configuration = KotlinTestUtils.compilerConfigurationForTests(ConfigurationKind.ALL, TestJdkKind.ANDROID_API)
return KotlinCoreEnvironment.createForTests(getTestRootDisposable()!!, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES) return KotlinCoreEnvironment.createForTests(testRootDisposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES)
} }
} }
@@ -33,16 +33,16 @@ import org.jetbrains.kotlin.psi.KtSimpleNameExpression
public class AndroidGotoDeclarationHandler : GotoDeclarationHandler { public class AndroidGotoDeclarationHandler : GotoDeclarationHandler {
override fun getGotoDeclarationTargets(sourceElement: PsiElement?, offset: Int, editor: Editor?): Array<PsiElement>? { override fun getGotoDeclarationTargets(sourceElement: PsiElement?, offset: Int, editor: Editor?): Array<PsiElement>? {
if (sourceElement is LeafPsiElement && sourceElement.getParent() is KtSimpleNameExpression) { if (sourceElement is LeafPsiElement && sourceElement.parent is KtSimpleNameExpression) {
val resolved = KtSimpleNameReference(sourceElement.getParent() as KtSimpleNameExpression).resolve() val resolved = KtSimpleNameReference(sourceElement.parent as KtSimpleNameExpression).resolve()
val property = resolved as? KtProperty ?: return null val property = resolved as? KtProperty ?: return null
val moduleInfo = sourceElement.getModuleInfo() val moduleInfo = sourceElement.getModuleInfo()
if (moduleInfo !is ModuleSourceInfo) return null if (moduleInfo !is ModuleSourceInfo) return null
val parser = ModuleServiceManager.getService(moduleInfo.module, javaClass<SyntheticFileGenerator>())!! val parser = ModuleServiceManager.getService(moduleInfo.module, SyntheticFileGenerator::class.java)!!
val psiElements = parser.layoutXmlFileManager.propertyToXmlAttributes(property) val psiElements = parser.layoutXmlFileManager.propertyToXmlAttributes(property)
val valueElements = psiElements.map { (it as? XmlAttribute)?.getValueElement() as? PsiElement }.filterNotNull() val valueElements = psiElements.map { (it as? XmlAttribute)?.valueElement as? PsiElement }.filterNotNull()
if (valueElements.isNotEmpty()) return valueElements.toTypedArray() if (valueElements.isNotEmpty()) return valueElements.toTypedArray()
} }
return null return null
@@ -75,7 +75,7 @@ public class AndroidPsiTreeChangePreprocessor : PsiTreeChangePreprocessor, Simpl
val module = projectFileIndex.getModuleForFile(xmlFile.virtualFile) val module = projectFileIndex.getModuleForFile(xmlFile.virtualFile)
if (module != null) { if (module != null) {
val resourceManager = AndroidLayoutXmlFileManager.getInstance(module) val resourceManager = AndroidLayoutXmlFileManager.getInstance(module) ?: return false
val resDirectories = resourceManager.getModuleResDirectories() val resDirectories = resourceManager.getModuleResDirectories()
val baseDirectory = xmlFile.parent?.parent?.virtualFile val baseDirectory = xmlFile.parent?.parent?.virtualFile
@@ -31,7 +31,7 @@ public class IDEAndroidExternalDeclarationsProvider(private val project: Project
if (moduleInfo !is ModuleSourceInfo) return listOf() if (moduleInfo !is ModuleSourceInfo) return listOf()
val module = moduleInfo.module val module = moduleInfo.module
val parser = ModuleServiceManager.getService(module, javaClass<SyntheticFileGenerator>()) as? IDESyntheticFileGenerator val parser = ModuleServiceManager.getService(module, SyntheticFileGenerator::class.java) as? IDESyntheticFileGenerator
val syntheticFiles = parser?.getSyntheticFiles() val syntheticFiles = parser?.getSyntheticFiles()
syntheticFiles?.forEach { it.moduleInfo = moduleInfo } syntheticFiles?.forEach { it.moduleInfo = moduleInfo }
@@ -30,7 +30,7 @@ public class IDEAndroidLayoutXmlFileManager(val module: Module) : AndroidLayoutX
override val androidModuleInfo: AndroidModuleInfo? by lazy { module.androidFacet?.toAndroidModuleInfo() } override val androidModuleInfo: AndroidModuleInfo? by lazy { module.androidFacet?.toAndroidModuleInfo() }
override fun propertyToXmlAttributes(property: KtProperty): List<PsiElement> { override fun propertyToXmlAttributes(property: KtProperty): List<PsiElement> {
val fqPath = property.getFqName()?.pathSegments() ?: return listOf() val fqPath = property.fqName?.pathSegments() ?: return listOf()
if (fqPath.size() <= AndroidConst.SYNTHETIC_PACKAGE_PATH_LENGTH) return listOf() if (fqPath.size() <= AndroidConst.SYNTHETIC_PACKAGE_PATH_LENGTH) return listOf()
val layoutPackageName = fqPath[AndroidConst.SYNTHETIC_PACKAGE_PATH_LENGTH].asString() val layoutPackageName = fqPath[AndroidConst.SYNTHETIC_PACKAGE_PATH_LENGTH].asString()
@@ -61,6 +61,6 @@ public abstract class AbstractAndroidCompletionTest : KotlinAndroidTestCase() {
settings.AUTOCOMPLETE_ON_CODE_COMPLETION = codeCompletionOldValue settings.AUTOCOMPLETE_ON_CODE_COMPLETION = codeCompletionOldValue
settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = smartTypeCompletionOldValue settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = smartTypeCompletionOldValue
super<KotlinAndroidTestCase>.tearDown() super.tearDown()
} }
} }
@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.android package org.jetbrains.kotlin.android
import com.intellij.codeInsight.TargetElementUtilBase import com.intellij.codeInsight.TargetElementUtil
import kotlin.test.* import kotlin.test.*
public abstract class AbstractAndroidFindUsagesTest : KotlinAndroidTestCase() { public abstract class AbstractAndroidFindUsagesTest : KotlinAndroidTestCase() {
@@ -29,8 +29,8 @@ public abstract class AbstractAndroidFindUsagesTest : KotlinAndroidTestCase() {
val virtualFile = f.copyFileToProject(path + getTestName(true) + ".kt", "src/" + getTestName(true) + ".kt"); val virtualFile = f.copyFileToProject(path + getTestName(true) + ".kt", "src/" + getTestName(true) + ".kt");
f.configureFromExistingVirtualFile(virtualFile) f.configureFromExistingVirtualFile(virtualFile)
val targetElement = TargetElementUtilBase.findTargetElement( val targetElement = TargetElementUtil.findTargetElement(
f.getEditor(), TargetElementUtilBase.ELEMENT_NAME_ACCEPTED or TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED) f.editor, TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)
assertNotNull(targetElement) assertNotNull(targetElement)
val propUsages = f.findUsages(targetElement!!) val propUsages = f.findUsages(targetElement!!)
@@ -31,9 +31,9 @@ public abstract class AbstractAndroidGotoTest : KotlinAndroidTestCase() {
val virtualFile = f.copyFileToProject(path + getTestName(true) + ".kt", "src/" + getTestName(true) + ".kt"); val virtualFile = f.copyFileToProject(path + getTestName(true) + ".kt", "src/" + getTestName(true) + ".kt");
f.configureFromExistingVirtualFile(virtualFile) f.configureFromExistingVirtualFile(virtualFile)
val resolved = GotoDeclarationAction.findTargetElement(f.getProject(), f.getEditor(), f.getCaretOffset()) val resolved = GotoDeclarationAction.findTargetElement(f.project, f.editor, f.caretOffset)
if (f.getElementAtCaret() !is KtProperty) kotlin.test.fail("element at caret must be a property, not a ${f.getElementAtCaret().javaClass}") if (f.elementAtCaret !is KtProperty) kotlin.test.fail("element at caret must be a property, not a ${f.elementAtCaret.javaClass}")
kotlin.test.assertEquals("\"@+id/${(f.getElementAtCaret() as KtProperty).getName()}\"", resolved?.getText()) kotlin.test.assertEquals("\"@+id/${(f.elementAtCaret as KtProperty).name}\"", resolved?.text)
} }
} }
@@ -30,13 +30,13 @@ public class SamePluginVersionsTest {
private fun extractIdeaVersion(pluginFile: File, pluginXml: String): Pair<String, String> { private fun extractIdeaVersion(pluginFile: File, pluginXml: String): Pair<String, String> {
val matcher = IDEA_VERSION_PATTERN.matcher(pluginXml) val matcher = IDEA_VERSION_PATTERN.matcher(pluginXml)
assertTrue("Can't find tag <idea-version> in ${pluginFile.getAbsolutePath()}", matcher.find()) assertTrue("Can't find tag <idea-version> in ${pluginFile.absolutePath}", matcher.find())
return matcher.group(1) to matcher.group(2) return matcher.group(1) to matcher.group(2)
} }
private fun extractPluginVersion(pluginFile: File, pluginXml: String): String { private fun extractPluginVersion(pluginFile: File, pluginXml: String): String {
val matcher = PLUGIN_VERSION_PATTERN.matcher(pluginXml) val matcher = PLUGIN_VERSION_PATTERN.matcher(pluginXml)
assertTrue("Can't find tag <version> in ${pluginFile.getAbsolutePath()}", matcher.find()) assertTrue("Can't find tag <version> in ${pluginFile.absolutePath}", matcher.find())
return matcher.group(1) return matcher.group(1)
} }
@@ -26,7 +26,7 @@ import com.intellij.util.PathUtil
public class KotlinAndroidJpsPlugin : KotlinJpsCompilerArgumentsProvider { public class KotlinAndroidJpsPlugin : KotlinJpsCompilerArgumentsProvider {
override fun getExtraArguments(moduleBuildTarget: ModuleBuildTarget, context: CompileContext): List<String> { override fun getExtraArguments(moduleBuildTarget: ModuleBuildTarget, context: CompileContext): List<String> {
val module = moduleBuildTarget.getModule() val module = moduleBuildTarget.module
val pluginId = ANDROID_COMPILER_PLUGIN_ID val pluginId = ANDROID_COMPILER_PLUGIN_ID
val resPath = getAndroidResPath(module) val resPath = getAndroidResPath(module)
val manifestFile = getAndroidManifest(module) val manifestFile = getAndroidManifest(module)
@@ -38,17 +38,17 @@ public class KotlinAndroidJpsPlugin : KotlinJpsCompilerArgumentsProvider {
} }
override fun getClasspath(moduleBuildTarget: ModuleBuildTarget, context: CompileContext): List<String> { override fun getClasspath(moduleBuildTarget: ModuleBuildTarget, context: CompileContext): List<String> {
val inJar = File(PathUtil.getJarPathForClass(javaClass)).isFile() val inJar = File(PathUtil.getJarPathForClass(javaClass)).isFile
val manifestFile = getAndroidManifest(moduleBuildTarget.getModule()) val manifestFile = getAndroidManifest(moduleBuildTarget.module)
return if (manifestFile != null) { return if (manifestFile != null) {
listOf( listOf(
if (inJar) { if (inJar) {
val libDirectory = File(PathUtil.getJarPathForClass(javaClass)).getParentFile().getParentFile() val libDirectory = File(PathUtil.getJarPathForClass(javaClass)).parentFile.parentFile
File(libDirectory, JAR_FILE_NAME).getAbsolutePath() File(libDirectory, JAR_FILE_NAME).absolutePath
} else { } else {
// We're in tests now (in out/production/android-jps-plugin) // We're in tests now (in out/production/android-jps-plugin)
val kotlinProjectDirectory = File(PathUtil.getJarPathForClass(javaClass)).getParentFile().getParentFile().getParentFile() val kotlinProjectDirectory = File(PathUtil.getJarPathForClass(javaClass)).parentFile.parentFile.parentFile
File(kotlinProjectDirectory, "dist/kotlinc/lib/$JAR_FILE_NAME").getAbsolutePath() File(kotlinProjectDirectory, "dist/kotlinc/lib/$JAR_FILE_NAME").absolutePath
}) })
} }
else listOf() else listOf()
@@ -57,12 +57,12 @@ public class KotlinAndroidJpsPlugin : KotlinJpsCompilerArgumentsProvider {
private fun getAndroidResPath(module: JpsModule): String? { private fun getAndroidResPath(module: JpsModule): String? {
val extension = AndroidJpsUtil.getExtension(module) ?: return null val extension = AndroidJpsUtil.getExtension(module) ?: return null
val path = AndroidJpsUtil.getResourceDirForCompilationPath(extension) val path = AndroidJpsUtil.getResourceDirForCompilationPath(extension)
return File(path!!.getAbsolutePath() + "/layout").getAbsolutePath() return File(path!!.absolutePath + "/layout").absolutePath
} }
private fun getAndroidManifest(module: JpsModule): String? { private fun getAndroidManifest(module: JpsModule): String? {
val extension = AndroidJpsUtil.getExtension(module) ?: return null val extension = AndroidJpsUtil.getExtension(module) ?: return null
return AndroidJpsUtil.getManifestFileForCompilationPath(extension)!!.getAbsolutePath() return AndroidJpsUtil.getManifestFileForCompilationPath(extension)!!.absolutePath
} }
companion object { companion object {
@@ -43,10 +43,10 @@ public abstract class AbstractAndroidJpsTestCase : JpsBuildTestCase() {
} }
public fun deleteDirectory(path: File): Boolean { public fun deleteDirectory(path: File): Boolean {
if (path.exists() && path.isDirectory()) { if (path.exists() && path.isDirectory) {
val files = path.listFiles() val files = path.listFiles()
for (i in files.indices) { for (i in files.indices) {
if (files[i].isDirectory()) { if (files[i].isDirectory) {
deleteDirectory(files[i]) deleteDirectory(files[i])
} }
else { else {
@@ -61,9 +61,9 @@ public abstract class AbstractAndroidJpsTestCase : JpsBuildTestCase() {
val jdkName = "java_sdk" val jdkName = "java_sdk"
addJdk(jdkName) addJdk(jdkName)
val properties = JpsAndroidSdkProperties("android-21", jdkName) val properties = JpsAndroidSdkProperties("android-21", jdkName)
val sdkPath = getHomePath() + "/../dependencies/androidSDK" val sdkPath = homePath + "/../dependencies/androidSDK"
val library = myModel.getGlobal().addSdk(SDK_NAME, sdkPath, "", JpsAndroidSdkType.INSTANCE, JpsSimpleElementImpl(properties)) val library = myModel.global.addSdk(SDK_NAME, sdkPath, "", JpsAndroidSdkType.INSTANCE, JpsSimpleElementImpl(properties))
library.addRoot(File(sdkPath + "/platforms/android-21/android.jar"), JpsOrderRootType.COMPILED) library.addRoot(File(sdkPath + "/platforms/android-21/android.jar"), JpsOrderRootType.COMPILED)
return library.getProperties() return library.properties
} }
} }