├── .gitignore ├── gradle.properties ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── kotlin │ └── ru │ │ └── rabota │ │ └── synthmigrate │ │ ├── dialog │ │ ├── Tab.kt │ │ ├── SynthMigrateDialogView.kt │ │ ├── SynthMigrateDialogPresenter.kt │ │ ├── SynthMigrateDialog.kt │ │ └── SynthMigrateDialog.form │ │ ├── models │ │ ├── ReplaceResult.kt │ │ ├── ReplaceModel.kt │ │ ├── Element.kt │ │ └── MigrateSettings.kt │ │ ├── migration │ │ ├── generate │ │ │ └── variable │ │ │ │ ├── PsiPackageExtension.kt │ │ │ │ ├── FindViewBindingEtensions.kt │ │ │ │ ├── AddPrefixToViewExpression.kt │ │ │ │ └── GenerateBindingVariable.kt │ │ ├── importutill │ │ │ ├── DeleteSynthImport.kt │ │ │ └── InsertNewImport.kt │ │ ├── collect │ │ │ ├── RelevantFileUtil.kt │ │ │ ├── CollectRelevantPsiFile.kt │ │ │ ├── AndroidLayoutUtils.kt │ │ │ └── CollectLayoutIds.kt │ │ ├── MigrateHelper.kt │ │ ├── StringExtensions.kt │ │ └── ReplaceHelper.kt │ │ ├── Extensions.kt │ │ └── ShowMigrateSettingAction.kt │ └── resources │ └── META-INF │ └── plugin.xml ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | build/ -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'SyntheticMigratePlugin' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RabotaRu/synthetic-migrate-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/dialog/Tab.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.dialog 2 | 3 | enum class Tab { 4 | MIGRATE, REPLACE 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/models/ReplaceResult.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.models 2 | 3 | data class ReplaceResult( 4 | var replaceCount: Int = 0, 5 | var errorMessage: String? = null 6 | ) -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/models/ReplaceModel.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.models 2 | 3 | data class ReplaceModel( 4 | var replaceFrom: String = "", 5 | var replaceTo: String = "", 6 | var import: String? = null 7 | ) -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/models/Element.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.models 2 | 3 | data class Element( 4 | val viewId: String, 5 | val viewName: String?, 6 | val parent: Element? = null, 7 | var layout: String? = null 8 | ) -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/dialog/SynthMigrateDialogView.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.dialog 2 | 3 | interface SynthMigrateDialogView { 4 | 5 | fun clearMigrateInputs() 6 | 7 | fun clearReplaceInputs() 8 | 9 | fun showError(title: String, message: String) 10 | 11 | fun showSuccess(text: String) 12 | 13 | fun dispose() 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/generate/variable/PsiPackageExtension.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.generate.variable 2 | 3 | import com.android.tools.idea.npw.project.getPackageForApplication 4 | import com.intellij.openapi.module.Module 5 | import org.jetbrains.android.facet.AndroidFacet 6 | 7 | fun Module.getDefaultPackage(): String? { 8 | return AndroidFacet.getInstance(this)?.getPackageForApplication() 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/Extensions.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate 2 | 3 | import com.intellij.openapi.command.WriteCommandAction 4 | import com.intellij.openapi.project.Project 5 | import com.intellij.psi.PsiFile 6 | import com.intellij.psi.search.FilenameIndex 7 | import com.intellij.psi.search.GlobalSearchScope 8 | 9 | fun Project.executeWrite(runnable: Runnable) { 10 | WriteCommandAction.runWriteCommandAction(this, runnable) 11 | } 12 | 13 | fun GlobalSearchScope.findFiles(project: Project, fileName: String): Array { 14 | return FilenameIndex.getFilesByName(project, fileName, this) 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/ShowMigrateSettingAction.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate 2 | 3 | import com.intellij.openapi.actionSystem.AnAction 4 | import com.intellij.openapi.actionSystem.AnActionEvent 5 | import com.intellij.openapi.actionSystem.PlatformDataKeys 6 | 7 | class ShowMigrateSettingAction : AnAction() { 8 | 9 | override fun actionPerformed(e: AnActionEvent) { 10 | val project = e.getData(PlatformDataKeys.PROJECT) ?: return 11 | val dialog = SynthMigrateDialog(project) 12 | dialog.pack() 13 | dialog.setLocationRelativeTo(null) 14 | dialog.isVisible = true 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/models/MigrateSettings.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.models 2 | 3 | data class MigrateSettings( 4 | var parentClassName: String? = null, 5 | var baseClassName: String? = null, 6 | var bindingVariableName: String? = null, 7 | var methodInitName: String? = null, 8 | var isLocalVariable: Boolean = false, 9 | var initTemplate: String = "", 10 | var imports: String? = null 11 | ) { 12 | companion object { 13 | const val DEFAULT_BINDING_NAME = "binding" 14 | } 15 | 16 | val hasInitMethod: Boolean 17 | get() = !methodInitName.isNullOrBlank() 18 | 19 | fun getNotNullBindingVariableName(): String = bindingVariableName ?: DEFAULT_BINDING_NAME 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/importutill/DeleteSynthImport.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.importutill 2 | 3 | import com.intellij.psi.PsiFile 4 | import com.intellij.psi.util.PsiTreeUtil 5 | import org.jetbrains.kotlin.psi.KtImportList 6 | import ru.rabota.synthmigrate.executeWrite 7 | import ru.rabota.synthmigrate.migration.collect.CollectRelevantPsiFile.Companion.PART_SYNTHETIC_IMPORT 8 | 9 | class DeleteSynthImport { 10 | 11 | operator fun invoke(psiFile: PsiFile) { 12 | val ktImports = PsiTreeUtil.findChildOfType(psiFile, KtImportList::class.java) 13 | 14 | ktImports?.imports?.forEach { psiImportStatementBase -> 15 | println(psiImportStatementBase.text) 16 | if (psiImportStatementBase.text.contains(PART_SYNTHETIC_IMPORT)) { 17 | psiFile.project.executeWrite { 18 | psiImportStatementBase.delete() 19 | } 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/collect/RelevantFileUtil.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.collect 2 | 3 | import org.jetbrains.kotlin.psi.KtClass 4 | import org.jetbrains.kotlin.psi.KtFile 5 | 6 | fun KtFile.hasRelevantParent( 7 | className: String?, 8 | nameCheckClass: String? = null, 9 | returnIfNull: Boolean = true 10 | ): Boolean { 11 | val parentClassName = if (!className.isNullOrBlank()) { 12 | className 13 | } else return returnIfNull 14 | 15 | return classes.filter { psiClass -> nameCheckClass?.let { psiClass.name == it } ?: true }.any { psiClass -> 16 | println() 17 | println(psiClass.name) 18 | var superClass = psiClass.superClass 19 | while (superClass != null && superClass.name != parentClassName) { 20 | println(superClass.name) 21 | superClass = superClass.superClass 22 | } 23 | println(superClass?.name) 24 | return superClass != null 25 | } 26 | } 27 | 28 | fun KtClass.hasRelevantParent(className: String?, returnIfNull: Boolean = true): Boolean { 29 | return containingKtFile.hasRelevantParent(className, name, returnIfNull) 30 | } -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | ru.rabota.synthmigrate.SyntheticMigratePlugin 3 | Synthetic Migrate 4 | Rabota.ru 5 | 6 | 9 | 10 | 12 | com.intellij.modules.platform 13 | com.intellij.modules.lang 14 | com.intellij.modules.java 15 | org.jetbrains.kotlin 16 | org.jetbrains.android 17 | 18 | 19 | 20 | 21 | 22 | 23 | 26 | 27 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/collect/CollectRelevantPsiFile.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.collect 2 | 3 | import com.intellij.psi.PsiDirectory 4 | import com.intellij.psi.PsiFile 5 | import org.jetbrains.kotlin.psi.KtImportList 6 | import org.jetbrains.kotlin.psi.KtTreeVisitorVoid 7 | import ru.rabota.synthmigrate.models.MigrateSettings 8 | 9 | class CollectRelevantPsiFile( 10 | private val migrateSettings: MigrateSettings 11 | ) { 12 | 13 | companion object { 14 | const val PART_SYNTHETIC_IMPORT = "kotlinx.android.synthetic" 15 | } 16 | 17 | operator fun invoke(rootDirectory: PsiDirectory): MutableList { 18 | val relevantFiles = mutableListOf() 19 | rootDirectory.accept(object : KtTreeVisitorVoid() { 20 | override fun visitImportList(importList: KtImportList) { 21 | super.visitImportList(importList) 22 | //обходим импорты и ищем синтетику 23 | if (importList.text.contains(PART_SYNTHETIC_IMPORT)) { 24 | //проверяем importList.parent, тобишь файл в котором эти импорты содержаться, на наличие 25 | //того что классы там наследуется от класса из migrateSettings.parentClassName 26 | if (importList.containingKtFile.hasRelevantParent(migrateSettings.parentClassName)) { 27 | relevantFiles.add(importList.parent as PsiFile) 28 | } 29 | } 30 | } 31 | }) 32 | 33 | return relevantFiles 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/generate/variable/FindViewBindingEtensions.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.generate.variable 2 | 3 | import org.jetbrains.kotlin.nj2k.postProcessing.resolve 4 | import org.jetbrains.kotlin.psi.KtClass 5 | import ru.rabota.synthmigrate.migration.snakeToUpperCamelCase 6 | 7 | private const val VIEW_BINDING_POSTFIX = "Binding" 8 | private const val LAYOUT_PREFIX = "R.layout." 9 | 10 | //ищем R.layout в текущем классе и выдергиваем название лэйаута в камел кейс + ViewBinding, 11 | // если нет идем в суперклассы и там ищем 12 | //takeWhile сделано чтобы если например после лэйаута есть какие то посторонние символы 13 | // типо закрытия скобок мы их случайно в название не притащили 14 | fun KtClass.findViewBindingType(): String? { 15 | val layout = body?.children?.firstOrNull { it.text.contains(LAYOUT_PREFIX) }?.text 16 | 17 | return layout?.substringAfter(LAYOUT_PREFIX)?.takeWhile { char -> 18 | char.isLetterOrDigit() || char == '_' 19 | }?.snakeToUpperCamelCase()?.toViewBindingName() ?: findViewBindingInSuperClass() 20 | } 21 | 22 | //смотрим суперклассы на предмет R.layout 23 | fun KtClass.findViewBindingInSuperClass(): String? { 24 | var viewBinding: String? 25 | superTypeListEntries.forEach { superType -> 26 | val userType = superType.typeAsUserType 27 | val resolvedReference = userType?.referenceExpression?.resolve() as? KtClass 28 | viewBinding = resolvedReference?.findViewBindingType() 29 | if (viewBinding != null) return viewBinding 30 | } 31 | return null 32 | } 33 | 34 | private fun String.toViewBindingName(): String { 35 | return "$this${VIEW_BINDING_POSTFIX}" 36 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/generate/variable/AddPrefixToViewExpression.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.generate.variable 2 | 3 | import com.intellij.psi.PsiElement 4 | import com.intellij.psi.util.PsiTreeUtil 5 | import com.intellij.psi.util.elementType 6 | import com.intellij.psi.xml.XmlElementType 7 | import org.jetbrains.kotlin.psi.KtPsiFactory 8 | import org.jetbrains.kotlin.psi.KtReferenceExpression 9 | import ru.rabota.synthmigrate.executeWrite 10 | import ru.rabota.synthmigrate.migration.snakeToLowerCamelCase 11 | import ru.rabota.synthmigrate.models.MigrateSettings 12 | 13 | class AddPrefixToViewExpression( 14 | private val migrateSettings: MigrateSettings 15 | ) { 16 | operator fun invoke(psiElement: PsiElement) { 17 | val expressions = PsiTreeUtil.findChildrenOfType(psiElement, KtReferenceExpression::class.java) 18 | expressions.forEach { referenceExpression -> 19 | referenceExpression.addViewBinding() 20 | } 21 | } 22 | 23 | private fun PsiElement.addViewBinding() { 24 | val isView = references.any { ref -> 25 | val resolve = ref.resolve() 26 | println(ref) 27 | println("element " + ref.element) 28 | println("resolve $resolve") 29 | 30 | println("----") 31 | resolve.elementType == XmlElementType.XML_ATTRIBUTE_VALUE 32 | } 33 | 34 | if (isView) { 35 | val newExpression = KtPsiFactory(project) 36 | .createExpression( 37 | "${migrateSettings.getNotNullBindingVariableName()}.${text.snakeToLowerCamelCase()}" 38 | ) 39 | project.executeWrite { 40 | replace(newExpression) 41 | } 42 | } 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/collect/AndroidLayoutUtils.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.collect 2 | 3 | import com.intellij.openapi.module.ModuleUtil 4 | import com.intellij.openapi.project.Project 5 | import com.intellij.psi.PsiElement 6 | import com.intellij.psi.PsiFile 7 | import com.intellij.psi.search.EverythingGlobalScope 8 | import ru.rabota.synthmigrate.findFiles 9 | 10 | object AndroidLayoutUtils { 11 | 12 | fun getLayoutName(layout: String?): String? { 13 | if (layout == null || !layout.startsWith("@") || !layout.contains("/")) { 14 | return null // it's not layout identifier 15 | } 16 | val parts = layout.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() 17 | return if (parts.size != 2) { 18 | null // not enough parts 19 | } else parts[1] 20 | } 21 | 22 | 23 | fun findLayoutResourceFile(element: PsiElement, project: Project, fileName: String): PsiFile? { 24 | 25 | val module = ModuleUtil.findModuleForPsiElement(element) 26 | 27 | var files: Array? = null 28 | if (module != null) { 29 | // 在模块范围搜索文件 30 | files = module.getModuleWithDependenciesAndLibrariesScope(false).findFiles(project, fileName) 31 | } 32 | 33 | if (files == null || files.isEmpty()) { 34 | // 在整个工程范围搜索文件 35 | files = EverythingGlobalScope(project).findFiles(project, fileName) 36 | } 37 | 38 | if (files.isEmpty()) {// 没找到文件 39 | return null 40 | } 41 | 42 | // TODO - we have a problem here - we still can have multiple layouts (some coming from a dependency) 43 | // we need to resolve R class properly and find the proper layout for the R class 44 | return files[0] 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/importutill/InsertNewImport.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.importutill 2 | 3 | import com.intellij.openapi.project.Project 4 | import com.intellij.psi.PsiFile 5 | import com.intellij.psi.util.PsiTreeUtil 6 | import org.jetbrains.kotlin.psi.KtImportDirective 7 | import org.jetbrains.kotlin.psi.KtImportList 8 | import org.jetbrains.kotlin.psi.KtPsiFactory 9 | import org.jetbrains.kotlin.resolve.ImportPath 10 | import ru.rabota.synthmigrate.executeWrite 11 | 12 | class InsertNewImport { 13 | 14 | operator fun invoke(listImport: List, psiFile: PsiFile) { 15 | val ktImports = PsiTreeUtil.findChildOfType(psiFile, KtImportList::class.java) 16 | 17 | val listImportDirective = createListImportDirective(psiFile.project, listImport) 18 | val lastImport = ktImports?.imports?.lastOrNull() 19 | psiFile.project.executeWrite { 20 | listImportDirective.forEach { ktImports?.addBefore(it, lastImport) } 21 | } 22 | } 23 | 24 | operator fun invoke(newImports: List, newImportsString: String?, psiFile: PsiFile) { 25 | val listString = newImportsString?.split("\n") ?: emptyList() 26 | var result = newImports.toMutableList() 27 | result.addAll(listString) 28 | result = result.filter { it.isNotBlank() }.distinct().toMutableList() 29 | if (result.isNotEmpty()) invoke(result, psiFile) 30 | } 31 | 32 | 33 | private fun createListImportDirective(project: Project, listImport: List): List { 34 | if (listImport.isEmpty()) return emptyList() 35 | return listImport.mapNotNull { importPath -> 36 | if (importPath.isNotBlank()) { 37 | KtPsiFactory(project).createImportDirective(ImportPath.fromString(importPath)) 38 | } else null 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/MigrateHelper.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration 2 | 3 | import com.intellij.openapi.project.Project 4 | import com.intellij.openapi.project.guessProjectDir 5 | import com.intellij.psi.PsiDirectory 6 | import com.intellij.psi.PsiFile 7 | import com.intellij.psi.PsiManager 8 | import ru.rabota.synthmigrate.migration.collect.CollectRelevantPsiFile 9 | import ru.rabota.synthmigrate.migration.generate.variable.AddPrefixToViewExpression 10 | import ru.rabota.synthmigrate.migration.generate.variable.GenerateBindingVariable 11 | import ru.rabota.synthmigrate.migration.importutill.DeleteSynthImport 12 | import ru.rabota.synthmigrate.migration.importutill.InsertNewImport 13 | import ru.rabota.synthmigrate.models.MigrateSettings 14 | 15 | class MigrateHelper( 16 | private val project: Project, 17 | private val migrateSettings: MigrateSettings 18 | ) { 19 | 20 | private val relevantFiles = mutableListOf() 21 | 22 | private lateinit var rootDirectory: PsiDirectory 23 | 24 | fun startMigrate() { 25 | val projectDir = project.guessProjectDir() ?: return 26 | rootDirectory = PsiManager.getInstance(project).findDirectory(projectDir) ?: return 27 | 28 | val collectRelevantPsiFile = CollectRelevantPsiFile(migrateSettings) 29 | relevantFiles.addAll(collectRelevantPsiFile.invoke(rootDirectory)) 30 | 31 | 32 | val insertNewImport = InsertNewImport() 33 | val deleteSynthImport = DeleteSynthImport() 34 | 35 | val generateBindingVariable = GenerateBindingVariable( 36 | migrateSettings, 37 | AddPrefixToViewExpression(migrateSettings) 38 | ) 39 | 40 | relevantFiles.forEach { psiFile -> 41 | val imports = generateBindingVariable.invoke(psiFile) 42 | insertNewImport(imports, migrateSettings.imports, psiFile) 43 | deleteSynthImport.invoke(psiFile) 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/StringExtensions.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration 2 | 3 | fun String.templateReplaceType(viewBinding: String): String { 4 | return replace("", viewBinding.snakeToUpperCamelCase(), ignoreCase = true) 5 | } 6 | 7 | fun String.templateReplaceOldType(oldSuperType: String, viewBinding: String?): String { 8 | val viewBindingType = viewBinding ?: "" 9 | val indexOpenGeneric = oldSuperType.indexOf("<") 10 | val indexCloseGeneric = oldSuperType.indexOf(">") 11 | val oldGenericParams = if(indexOpenGeneric != -1) { 12 | oldSuperType.substring(indexOpenGeneric + 1, indexCloseGeneric).split(",") 13 | } else { 14 | emptyList() 15 | } 16 | 17 | val indexStartParams = oldSuperType.indexOf("(") 18 | val indexEndParams = oldSuperType.indexOf(")") 19 | 20 | val oldParams = if(indexStartParams > 0) { 21 | oldSuperType.substring(indexStartParams + 1, indexEndParams).split(",") 22 | } else { 23 | emptyList() 24 | } 25 | 26 | var result = this 27 | oldGenericParams.forEachIndexed { index, s -> 28 | result = result.replace("<$index>", s) 29 | } 30 | 31 | if(result.contains("(")) { 32 | oldParams.forEachIndexed { index, s -> 33 | result = result.replace("[$index]", s) 34 | } 35 | } else { 36 | result += "()" 37 | } 38 | 39 | result = result.replace(Regex("\\[[0-9]+\\],?"),"") 40 | result = result.replace(Regex("<[0-9]+>,?"),"") 41 | result = result.replace(Regex("<\\s?>"), "") 42 | 43 | return result.templateReplaceType(viewBindingType) 44 | } 45 | 46 | fun String.snakeToLowerCamelCase(): String { 47 | val snakeRegex = "_[a-zA-Z]".toRegex() 48 | return snakeRegex.replace(this) { 49 | it.value.replace("_", "") 50 | .toUpperCase() 51 | } 52 | } 53 | 54 | fun String.snakeToUpperCamelCase(): String { 55 | return this.snakeToLowerCamelCase().capitalize() 56 | } 57 | 58 | fun StringBuilder.removePrefix(prefix: String) { 59 | replace(0, length, (this as CharSequence).removePrefix(prefix).toString()) 60 | } 61 | 62 | fun StringBuilder.replace(oldValue: String, newValue: String) { 63 | replace(0, length, (this as CharSequence).replace(oldValue.toRegex(), newValue)) 64 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/ReplaceHelper.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration 2 | 3 | import com.intellij.openapi.project.Project 4 | import com.intellij.openapi.project.guessProjectDir 5 | import com.intellij.psi.PsiManager 6 | import org.jetbrains.kotlin.nj2k.postProcessing.resolve 7 | import org.jetbrains.kotlin.psi.* 8 | import org.jetbrains.kotlin.resolve.ImportPath 9 | import ru.rabota.synthmigrate.executeWrite 10 | import ru.rabota.synthmigrate.migration.generate.variable.findViewBindingType 11 | import ru.rabota.synthmigrate.models.ReplaceModel 12 | import ru.rabota.synthmigrate.models.ReplaceResult 13 | 14 | class ReplaceHelper( 15 | private val project: Project 16 | ) { 17 | 18 | private val replaceResult = ReplaceResult() 19 | 20 | fun replace(replaceModel: ReplaceModel): ReplaceResult { 21 | val notFoundResult = ReplaceResult(errorMessage = "Не найденана директория проекта") 22 | val projectDir = project.guessProjectDir() ?: return notFoundResult 23 | val rootDirectory = PsiManager.getInstance(project).findDirectory(projectDir) ?: return notFoundResult 24 | 25 | rootDirectory.accept(object : KtTreeVisitorVoid() { 26 | override fun visitClass(klass: KtClass) { 27 | super.visitClass(klass) 28 | klass.superTypeListEntries.forEach { superType -> 29 | val superKElement = superType.typeAsUserType?.referenceExpression?.resolve() as? KtElement 30 | if (superKElement?.name == replaceModel.replaceFrom && 31 | klass.isWritable 32 | ) { 33 | println("Start replace ${superType.text}") 34 | println("for class ${klass.name}") 35 | klass.replaceSupertype(superType, replaceModel) 36 | println("------") 37 | } 38 | } 39 | } 40 | }) 41 | return replaceResult 42 | } 43 | 44 | private fun KtClass.replaceSupertype( 45 | ktSuperTypeEntry: KtSuperTypeListEntry, 46 | replaceModel: ReplaceModel 47 | ) { 48 | val factory = KtPsiFactory(project) 49 | val viewBindingType = findViewBindingType() 50 | val formattedReplaceTo = 51 | replaceModel.replaceTo.templateReplaceOldType(ktSuperTypeEntry.text, viewBindingType) 52 | println("Formatted $formattedReplaceTo") 53 | replaceResult.replaceCount++ 54 | val newSuperType = kotlin.runCatching { factory.createSuperTypeCallEntry(formattedReplaceTo) } 55 | .getOrNull() ?: factory.createSuperTypeEntry(formattedReplaceTo) 56 | 57 | project.executeWrite { 58 | ktSuperTypeEntry.replace(newSuperType) 59 | } 60 | 61 | containingKtFile.replaceImport(replaceModel) 62 | } 63 | 64 | private fun KtFile.replaceImport(replaceModel: ReplaceModel) { 65 | if (replaceModel.import.isNullOrBlank()) return 66 | val factory = KtPsiFactory(project) 67 | importDirectives.forEach { import -> 68 | if (import.text.contains(replaceModel.replaceFrom)) { 69 | val newImport = factory.createImportDirective( 70 | ImportPath.fromString(replaceModel.import ?: String()) 71 | ) 72 | project.executeWrite { 73 | import.replace(newImport) 74 | } 75 | } 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/collect/CollectLayoutIds.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.collect 2 | 3 | import com.intellij.psi.PsiDirectory 4 | import com.intellij.psi.PsiFile 5 | import com.intellij.psi.XmlRecursiveElementVisitor 6 | import com.intellij.psi.xml.XmlFile 7 | import org.xml.sax.Attributes 8 | import org.xml.sax.helpers.DefaultHandler 9 | import ru.rabota.synthmigrate.models.Element 10 | import javax.xml.parsers.SAXParserFactory 11 | 12 | class CollectLayoutIds { 13 | 14 | companion object { 15 | private const val PART_PATH_TO_LAYOUT = "res/layout" 16 | } 17 | 18 | //layout_name - список айдишек 19 | operator fun invoke(rootDirectory: PsiDirectory): Map> { 20 | val result = mutableMapOf>() 21 | 22 | rootDirectory.accept(object : XmlRecursiveElementVisitor() { 23 | 24 | override fun visitXmlFile(file: XmlFile?) { 25 | super.visitXmlFile(file) 26 | if (file == null) return 27 | if (file.isPhysical && file.virtualFile.path.contains(PART_PATH_TO_LAYOUT)) { 28 | val ids = file.getAndroidViewElements() 29 | println(file.name) 30 | println(ids) 31 | if (ids.isNotEmpty()) { 32 | result[file.name] = file.getAndroidViewElements() 33 | } 34 | } 35 | } 36 | 37 | }) 38 | 39 | return result 40 | } 41 | } 42 | 43 | private fun PsiFile.getAndroidViewElements(parent: Element? = null): List { 44 | 45 | val elements = mutableListOf() 46 | 47 | val factory = SAXParserFactory.newInstance() 48 | val parser = factory.newSAXParser() 49 | 50 | val handler = object : DefaultHandler() { 51 | override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) { 52 | // get element ID 53 | val id = attributes?.getValue("android:id") 54 | ?: "" // missing android:id attribute 55 | // check if there is defined custom class 56 | var name: String? = qName 57 | val clazz = attributes?.getValue("class") 58 | if (clazz != null) { 59 | name = clazz 60 | } 61 | var element: Element? = null 62 | try { 63 | id.split("/").lastOrNull()?.let { clearId -> 64 | element = Element(clearId, name, parent) 65 | elements.add(element!!) 66 | } 67 | } catch (e: Exception) { 68 | e.printStackTrace() 69 | } 70 | 71 | 72 | if ("include".equals(qName, ignoreCase = true)) { 73 | val layout = attributes?.getValue("layout") 74 | 75 | if (layout != null) { 76 | val project = this@getAndroidViewElements.project 77 | val layoutName = AndroidLayoutUtils.getLayoutName(layout) 78 | element?.layout = layoutName 79 | val include = if (layoutName == null) null else 80 | AndroidLayoutUtils.findLayoutResourceFile(this@getAndroidViewElements, project, "$layoutName.xml") 81 | 82 | if (include != null) { 83 | elements.addAll(include.getAndroidViewElements(element)) 84 | } 85 | } 86 | } 87 | 88 | 89 | } 90 | } 91 | 92 | kotlin.runCatching { parser.parse(this.text.byteInputStream(), handler) } 93 | 94 | return elements 95 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/dialog/SynthMigrateDialogPresenter.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.dialog 2 | 3 | import com.intellij.openapi.project.Project 4 | import ru.rabota.synthmigrate.migration.MigrateHelper 5 | import ru.rabota.synthmigrate.migration.ReplaceHelper 6 | import ru.rabota.synthmigrate.models.MigrateSettings 7 | import ru.rabota.synthmigrate.models.ReplaceModel 8 | import java.lang.ref.WeakReference 9 | 10 | class SynthMigrateDialogPresenter( 11 | private val project: Project 12 | ) { 13 | 14 | companion object { 15 | private const val VALIDATE_ERROR_TITLE = "Ошибка валидации" 16 | } 17 | 18 | private var weakView: WeakReference? = null 19 | 20 | private val view: SynthMigrateDialogView? 21 | get() = weakView?.get() 22 | 23 | private var currentTab: Tab = Tab.MIGRATE 24 | 25 | private val replaceHelper = ReplaceHelper(project) 26 | 27 | fun attachView(dialogView: SynthMigrateDialogView) { 28 | this.weakView = WeakReference(dialogView) 29 | } 30 | 31 | fun detachView() { 32 | weakView = null 33 | } 34 | 35 | fun onClearClick() { 36 | when (currentTab) { 37 | Tab.MIGRATE -> view?.clearMigrateInputs() 38 | Tab.REPLACE -> view?.clearReplaceInputs() 39 | } 40 | } 41 | 42 | fun onMigrateClick(migrateSettings: MigrateSettings) { 43 | val isValid = validateFields(migrateSettings) 44 | if (isValid) { 45 | val migrateHelper = MigrateHelper(project, migrateSettings) 46 | migrateHelper.startMigrate() 47 | view?.showSuccess("Успешно мигрировали") 48 | } 49 | } 50 | 51 | fun onReplaceClick(replaceModel: ReplaceModel) { 52 | val result = replaceHelper.replace(replaceModel) 53 | val errMsg = result.errorMessage 54 | if (errMsg == null) { 55 | view?.showSuccess("Успешно заменили ${result.replaceCount} наследований") 56 | } else { 57 | view?.showError("Ошибка", errMsg) 58 | } 59 | } 60 | 61 | fun onCancelClick() { 62 | view?.dispose() 63 | } 64 | 65 | fun onTabChange() { 66 | currentTab = when (currentTab) { 67 | Tab.REPLACE -> Tab.MIGRATE 68 | Tab.MIGRATE -> Tab.REPLACE 69 | } 70 | } 71 | 72 | private fun validateFields(replaceModel: ReplaceModel): Boolean { 73 | var isValid = true 74 | val errorMessage = StringBuilder() 75 | if (replaceModel.replaceFrom.isBlank()) { 76 | errorMessage.append("Заполните поле \"Что заменяем\"") 77 | isValid = false 78 | } 79 | 80 | if (replaceModel.replaceTo.isBlank()) { 81 | errorMessage.append("\n") 82 | errorMessage.append("Заполните поле \"На что заменяем\"") 83 | isValid = false 84 | } 85 | if (!isValid) { 86 | view?.showError(VALIDATE_ERROR_TITLE, errorMessage.toString()) 87 | } 88 | return isValid 89 | } 90 | 91 | private fun validateFields(migrateSettings: MigrateSettings): Boolean { 92 | var isValid = true 93 | val errorMessage = StringBuilder() 94 | if (migrateSettings.initTemplate.isBlank()) { 95 | errorMessage.append("Заполните поле \"Шаблон инициализации\"") 96 | isValid = false 97 | } 98 | if (migrateSettings.isLocalVariable && migrateSettings.methodInitName.isNullOrBlank()) { 99 | errorMessage.append("\n") 100 | errorMessage.append("Заполните поле \"Метод инициализации\" или уберите галочку с локальной переменной") 101 | isValid = false 102 | } 103 | 104 | if (!isValid) { 105 | view?.showError(VALIDATE_ERROR_TITLE, errorMessage.toString()) 106 | } 107 | 108 | return isValid 109 | } 110 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/dialog/SynthMigrateDialog.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate 2 | 3 | import com.intellij.openapi.project.Project 4 | import com.intellij.openapi.ui.Messages 5 | import ru.rabota.synthmigrate.dialog.SynthMigrateDialogPresenter 6 | import ru.rabota.synthmigrate.dialog.SynthMigrateDialogView 7 | import ru.rabota.synthmigrate.models.MigrateSettings 8 | import ru.rabota.synthmigrate.models.ReplaceModel 9 | import java.awt.event.KeyEvent 10 | import java.awt.event.WindowAdapter 11 | import java.awt.event.WindowEvent 12 | import javax.swing.* 13 | 14 | class SynthMigrateDialog( 15 | private val project: Project 16 | ) : JDialog(), SynthMigrateDialogView { 17 | 18 | private lateinit var contentPane: JPanel 19 | private lateinit var buttonMigrate: JButton 20 | private lateinit var buttonCancel: JButton 21 | private lateinit var parentClassName: JTextField 22 | private lateinit var baseClassName: JTextField 23 | private lateinit var bindingVariableName: JTextField 24 | private lateinit var methodInitName: JTextField 25 | private lateinit var isLocalVariableCheckBox: JCheckBox 26 | private lateinit var initTemplate: JTextField 27 | private lateinit var imports: JTextArea 28 | private lateinit var replaceFrom: JTextField 29 | private lateinit var replaceTo: JTextField 30 | private lateinit var replacePanel: JPanel 31 | private lateinit var buttonClear: JButton 32 | private lateinit var allContent: JPanel 33 | private lateinit var btnReplace: JButton 34 | private lateinit var btnClearReplace: JButton 35 | private lateinit var replaceImports: JTextField 36 | private lateinit var tabPanel: JTabbedPane 37 | 38 | private val presenter by lazy { SynthMigrateDialogPresenter(project) } 39 | 40 | 41 | init { 42 | setContentPane(contentPane) 43 | 44 | presenter.attachView(this) 45 | 46 | initUi() 47 | } 48 | 49 | private fun initUi() { 50 | isModal = true 51 | getRootPane().defaultButton = buttonMigrate 52 | 53 | defaultCloseOperation = DO_NOTHING_ON_CLOSE 54 | addWindowListener(object : WindowAdapter() { 55 | override fun windowClosing(e: WindowEvent) { 56 | presenter.onCancelClick() 57 | } 58 | }) 59 | 60 | contentPane.registerKeyboardAction( 61 | { presenter.onCancelClick() }, 62 | KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), 63 | JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 64 | ) 65 | 66 | tabPanel.addChangeListener { presenter.onTabChange() } 67 | 68 | 69 | btnReplace.addActionListener { presenter.onReplaceClick(createReplaceModel()) } 70 | btnClearReplace.addActionListener { presenter.onClearClick() } 71 | buttonCancel.addActionListener { presenter.onCancelClick() } 72 | buttonMigrate.addActionListener { presenter.onMigrateClick(createSetting()) } 73 | buttonClear.addActionListener { presenter.onClearClick() } 74 | } 75 | 76 | override fun showSuccess(text: String) { 77 | Messages.showInfoMessage(project, text, "Успех") 78 | } 79 | 80 | override fun clearMigrateInputs() { 81 | parentClassName.text = String() 82 | baseClassName.text = String() 83 | bindingVariableName.text = String() 84 | methodInitName.text = String() 85 | isLocalVariableCheckBox.isSelected = false 86 | initTemplate.text = String() 87 | imports.text = String() 88 | } 89 | 90 | override fun clearReplaceInputs() { 91 | replaceFrom.text = String() 92 | replaceTo.text = String() 93 | replaceImports.text = String() 94 | } 95 | 96 | override fun showError(title: String, message: String) { 97 | Messages.showWarningDialog(project, message, title) 98 | } 99 | 100 | private fun createSetting(): MigrateSettings { 101 | return MigrateSettings( 102 | parentClassName = parentClassName.text.takeIf { !it.isNullOrBlank() }, 103 | baseClassName = baseClassName.text.takeIf { !it.isNullOrBlank() }, 104 | bindingVariableName = bindingVariableName.text.takeIf { !it.isNullOrBlank() }, 105 | methodInitName = methodInitName.text.takeIf { !it.isNullOrBlank() }, 106 | isLocalVariable = isLocalVariableCheckBox.isSelected, 107 | initTemplate = initTemplate.text, 108 | imports = imports.text.takeIf { !it.isNullOrBlank() } 109 | ) 110 | } 111 | 112 | private fun createReplaceModel(): ReplaceModel { 113 | return ReplaceModel( 114 | replaceFrom = replaceFrom.text, 115 | replaceTo = replaceTo.text, 116 | import = replaceImports.text.takeIf { !it.isNullOrBlank() } 117 | ) 118 | } 119 | 120 | override fun dispose() { 121 | super.dispose() 122 | presenter.detachView() 123 | } 124 | } -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/migration/generate/variable/GenerateBindingVariable.kt: -------------------------------------------------------------------------------- 1 | package ru.rabota.synthmigrate.migration.generate.variable 2 | 3 | import com.intellij.psi.PsiFile 4 | import com.intellij.psi.util.PsiTreeUtil 5 | import org.jetbrains.kotlin.idea.util.module 6 | import org.jetbrains.kotlin.psi.KtBlockExpression 7 | import org.jetbrains.kotlin.psi.KtClass 8 | import org.jetbrains.kotlin.psi.KtPsiFactory 9 | import org.jetbrains.kotlin.psi.psiUtil.findFunctionByName 10 | import ru.rabota.synthmigrate.executeWrite 11 | import ru.rabota.synthmigrate.migration.collect.hasRelevantParent 12 | import ru.rabota.synthmigrate.migration.removePrefix 13 | import ru.rabota.synthmigrate.migration.replace 14 | import ru.rabota.synthmigrate.migration.templateReplaceType 15 | import ru.rabota.synthmigrate.models.MigrateSettings 16 | 17 | 18 | class GenerateBindingVariable( 19 | private val settings: MigrateSettings, 20 | private val addPrefixToViewExpression: AddPrefixToViewExpression 21 | ) { 22 | 23 | companion object { 24 | private const val VAL = "val" 25 | private const val LATE_INIT = "lateinit var" 26 | private const val SUPER_PREFIX = "super." 27 | private const val PRIVATE = "private" 28 | private const val OVERRIDE = "override" 29 | } 30 | 31 | operator fun invoke(psiFile: PsiFile): List { 32 | val imports = mutableSetOf() 33 | 34 | val ktClasses = PsiTreeUtil.findChildrenOfType(psiFile, KtClass::class.java) 35 | 36 | ktClasses.forEach { klass -> 37 | val isRelevantClass = klass.hasRelevantParent(settings.parentClassName) 38 | 39 | if (isRelevantClass) { 40 | println("Relevant class ${klass.name}") 41 | val hasBaseClass = klass.hasRelevantParent(settings.baseClassName, returnIfNull = false) 42 | println("Has base class $hasBaseClass") 43 | val viewBindingType = klass.generateBindingInClass(hasBaseClass) 44 | addPrefixToViewExpression.invoke(klass) 45 | val import = klass.module?.getDefaultPackage() 46 | if (viewBindingType != null && import != null) { 47 | imports.add("$import.databinding.$viewBindingType") 48 | } 49 | } 50 | } 51 | 52 | return imports.toList() 53 | } 54 | 55 | private fun KtClass.generateBindingInClass(hasBaseClass: Boolean = false): String? { 56 | val modifier = if (hasBaseClass) OVERRIDE else PRIVATE 57 | val bindingBuilder = StringBuilder("$modifier $VAL") 58 | 59 | val viewBindingType = findViewBindingType() ?: return null 60 | val initExpression = settings.initTemplate.templateReplaceType(viewBindingType) 61 | 62 | if (settings.hasInitMethod) { 63 | if (!settings.isLocalVariable) { 64 | bindingBuilder.clear() 65 | bindingBuilder.append("$modifier $LATE_INIT") 66 | } 67 | } 68 | bindingBuilder.append(" ") 69 | bindingBuilder.append(settings.getNotNullBindingVariableName()) 70 | 71 | if (!settings.hasInitMethod) { 72 | bindingBuilder.append(initExpression) 73 | writeInClass(bindingBuilder.toString()) 74 | } else { 75 | if (settings.isLocalVariable) { 76 | bindingBuilder.append(initExpression) 77 | bindingBuilder.removePrefix(modifier) 78 | writeInFunction(bindingBuilder.toString()) 79 | } else { 80 | bindingBuilder.append(" :$viewBindingType") 81 | writeInClass(bindingBuilder.toString()) 82 | bindingBuilder.removePrefix(modifier) 83 | bindingBuilder.removePrefix(LATE_INIT) 84 | bindingBuilder.replace(":$viewBindingType", "") 85 | bindingBuilder.append(initExpression) 86 | writeInFunction(bindingBuilder.toString().trim(), inClassDeclared = true) 87 | } 88 | } 89 | return viewBindingType 90 | } 91 | 92 | private fun KtClass.writeInClass(expression: String) { 93 | val childAnchor = body?.children?.firstOrNull() 94 | val factory = KtPsiFactory(project) 95 | val psiElement = factory.createProperty(expression) 96 | project.executeWrite { 97 | body?.addBefore(psiElement, childAnchor) 98 | } 99 | } 100 | 101 | private fun KtClass.writeInFunction(expression: String, inClassDeclared: Boolean = false) { 102 | val func = findFunctionByName(settings.methodInitName ?: "") ?: return 103 | println("FUN ${func.name}") 104 | println(func.text) 105 | 106 | val functionBody = func.children.firstOrNull { it is KtBlockExpression } 107 | val childAnchor = 108 | functionBody?.children?.firstOrNull { it.text.contains(SUPER_PREFIX) } ?: functionBody?.firstChild 109 | 110 | print("Child anchor ${childAnchor?.text}") 111 | 112 | val factory = KtPsiFactory(project) 113 | val psiElement = if (inClassDeclared) { 114 | factory.createExpression(expression) 115 | } else { 116 | factory.createProperty(expression) 117 | } 118 | 119 | project.executeWrite { 120 | if (inClassDeclared) { 121 | val whiteSpace = factory.createWhiteSpace("\n") 122 | functionBody?.addAfter(whiteSpace, childAnchor) 123 | } else { 124 | functionBody?.addAfter(psiElement, childAnchor) 125 | } 126 | } 127 | if (inClassDeclared) { 128 | val sibling = childAnchor?.nextSibling 129 | project.executeWrite { 130 | functionBody?.addAfter(psiElement, sibling) 131 | } 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Synthetic Migrate Plugin 2 | 3 | ## Описание 4 | Плагин для Android Studio/Intelij IDEA с помощью которого можно мигрировать кодовую базу с котлиновской синтетики на view-binding. 5 | Поддерживает Android Studio 4.1+ и Intelij IDEA 2020.1+ 6 | 7 | ## Установка 8 | 1. Скачать jar [из последнего релиза](https://github.com/RabotaRu/synthetic-migrate-plugin/releases/) 9 | 2. Preferences -> Plugins -> Settings -> Install Plugin From Disk Снимок экрана 2022-04-15 в 16 16 27 10 | 3. Выбрать jar 11 | 4. Перезагрузить студию 12 | 5. Точка входа в плагин появится в верхнем меню 13 | Снимок экрана 2022-05-16 в 15 40 01 14 | 15 | 16 | 17 | 18 | # Описание интерфейса 19 | 20 | ## Первый таб - Миграция 21 | 22 | Снимок экрана 2022-04-15 в 16 34 13 23 | 24 | ### Описание 25 | В первом табе происходит настройка миграции, указание сущности которая будет мигрировать, то как будет инициализироваться view binding, где будет инициализироваться, указание доп импортов и т.д. 26 | 27 | **Чекбокс "Локальная переменная"** - если он установлен, то binding переменная будет создана в методе указанном в поле "Метод инициализации", так что после того как чекбокс становиться активным поле "Метод инициализиации" становиться обязательным 28 | 29 | **Поле "Родительский класс"** - это обязательное поле, которое заполняется именем родительского класса сущности которую нужно перевести на view binding. Например нам нужно перевести все сущности которые наследуются от Fragment, значит пишем там Fragment. 30 | 31 | **Поле "Название базового класса"** - поле в которе вводится название базового класса сущности. Например нужно перевести все фрагменты на view binding, и есть базовый абстрактный класс BaseFragment, в котором переменная binding установленная абстрактной, следовательно нужно в каждом наследнике BaseFragment переопределять эту переменную. Значит указываем в Поле "Родительский класс" Fragment, в этом поле BaseFragment. И плагин везде где родитель BaseFragment - переопределит binding переменную(добавит override), а где только Fragment - создаст новую. 32 | 33 | **Поле "Название binding переменной"** - то как будет называться генерируемая переменная. По умолчания binding 34 | 35 | **Поле "Метод инициализации"** - поле которое нужно заполнить если необходимо инициализировать view binding переменную в каком то методе. Она используется как в связке с Чекбоксом "Локальная переменная", так и без него. 36 | 1. Если выбран чекбокс и заполнено это поле, то переменная будет создана исключительно в в том методе, который указан в поле 37 | 2. Чекбокс не выбран и заполнено поле, будет создана глобальная переменная с lateinit и инициализирована в методе который указан в этом поле 38 | 39 | **Поле "Шаблон инициализации"** - поле в котором прописывается то как будет инициализирована переменная. Т.к. инициализация сопрежена с обращения к, сгенерированным view binding плагином, классами, то в этом поле можно указать , где это сгенерированный view binding класс, для обрабатываемого класса. Например есть делегат, с помощью которого нужно инициализировать во всех фрагментах binding. Для Фрагмента с лэйаутом R.layout.fragment_search эта инициализация должно выглядеть так val binding by fragmentBindingDelegate(FragmentSearchViewBinding::bind). Значит нужно вписать в это поле by fragmentBindingDelegate(::bind). И тогда в каждом фрагменте, где плагин сможет найти лэйаут будет подставлен класс сгенеренный на основе этого лэйаута. 40 | 41 | **Поле "Необходимы импорты"** - плагин по умолчанию удаляет все импорты с синтетикой и добавляет импорты с view binding. На иногда необходимы еще некоторые импорты, например когда используешь тот же делегат для инициализации. Например: ru.rabota.app2.delegate.viewbinding и тогда в списке импортов у каждого обработанного файла появится import ru.rabota.app2.delegate.viewbinding. Это поле так же имеет правило: один импорт - одна строка 42 | 43 | **Кнопка "Мигрировать"** - запускает процесс генерации переменной и замены импортов. После нажатия все повиснет и это нормально. После выполнения миграции появится диалог о завершении 44 | 45 | **Кнопка "Сбросить"** - сбрасывает все настройки и очищает поля в этом табе 46 | 47 | **Кнопка "Отмена"** - закрывает диалог 48 | 49 | 50 | ## Второй таб - Замена родительского класса 51 | 52 | Снимок экрана 2022-04-15 в 16 38 02 53 | 54 | ### Описание 55 | 56 | Второй таб позволяет заменять родительские классы. Это необходимо если во время переезда на view-binding в родительском классе добавился новый generic и чтобы во всех наследуемых классах руками его не добавлять может пригодится эта фича. 57 | 58 | **Поле "Что заменяем"** - в этом поле указывается класс от которого наследуются и который изменился/заменился. Например у был класс BaseFragment и стал BaseFragment и везде нужно подставить этот ViewBinding. Значит в этом поле указывается имя такого класса который необходимо заменить т.е. BaseFragment 59 | 60 | **Поле "На что заменяем"** - в этом поле указывается выражение на которое заменяется класс указанный выше. Это поле имеет 2 особенности: 61 | 1. Когда заменяем BaseFragment на BaseFragment, нужно добавить view binding класс и сохранить имеющуюся уже там viewmodel класс. И тут нам на помощь приходит & , где type аналогичен type из шаблона инициализации, а , где index это индекс generic'а, начиная с 0. 62 | В этом примере в поле будет записано BaseFragment<, <0>>. Где <0> - это ViewModel 63 | 2. Так же много где есть аргументы в первичном конструкторе, для того что бы они не исчезли при замене указывается [index] - где index это индекс аргумента, начиная с 0. Например есть BaseItem(abs, test), заменить на SuperItemBase(abs, test). Значит в этом поле нужно указать SuperItemBase<>([0],[1]) 64 | 65 | **Поле "Необходимый импорт"** - импорт который добавляется в процессе замены в каждый обработанный файл. Например: ru.rabota.app2.delegate.viewbinding и тогда в списке импортов у каждого обработанного файла появится import ru.rabota.app2.delegate.viewbinding 66 | 67 | **Кнопка "Заменить"** - запускает процесс замены 68 | 69 | **Кнопка "Очистить"** - очищает поля 70 | 71 | 72 | # Примеры использования 73 | 74 | ## Миграция фрагментов 75 | 76 | Снимок экрана 2022-04-15 в 16 43 29 77 | Здесь во всех фрагментах сгенерится переменная с именем binding, а в тех кто наследовался от BaseFragment переменная биндинг будет override. Инициализация будет такая binding by someDelegate(NameViewBinding::bind). И в каждый обработанный файл добавиться импорт ru.rabota.app2.delegate.someDelegate. И у всех вьюшек в каждом классе вначале появится binding. 78 | 79 | ## Миграция итемов списка 80 | 81 | Снимок экрана 2022-04-15 в 16 45 19 82 | На данном скриншоте приведен пример миграции итема списка. Т.е. во всех классах с родителем Item, в методе onBind будет сгенерирована переменная с названием itemBinding и инициализирована так: itemBinding = NameViewBinding.bind(viewHolder.itemView) 83 | 84 | ## Добавления во всех наследованиях нового дженерика 85 | 86 | Снимок экрана 2022-04-15 в 16 47 13 87 | В этом примере во все наследования от BaseFragment будет добавлен generic c типом биндинга который был найден в классе. Например: 88 | было MainFragment: BaseFragment() 89 | станет MainFragment: BaseFragment() 90 | И так же во всех классах которые наследуются от BaseFragment, первый дженерик сохранится за счет того что было прописано <0>, и добавится новый с типом биндинга за счет добавления 91 | 92 | ## Добавления во всех наследованиях нового аргумента 93 | 94 | Снимок экрана 2022-04-15 в 16 51 49 95 | В этом примере происходит замена наследования с добавлением нового аргумента и сохранением старого. Например: 96 | было MainItem(orientation: Int, data: Int): BaseItem(orientation) 97 | станет MainItem(orientation: Int, data: Int): BaseItem(orientation, data) 98 | И так же во всех классах которые наследуются от BaseItem, первый аргумент сохранится за счет того что было прописано [0], и добавится новый за счет добавления data 99 | 100 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/main/kotlin/ru/rabota/synthmigrate/dialog/SynthMigrateDialog.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 |
454 | --------------------------------------------------------------------------------