From 7db70efa5942ba2111a62871bf4f03d294297344 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:37:19 -0800 Subject: [PATCH 01/10] ADFA-7201: style: spotless reformat, no functional change Brings the files the warning fixes touch under the Spotless ratchet first, so the fix commits that follow show only the fixes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../ksp/inflater/ViewAdapterIndexGenerator.kt | 461 ++--- .../lsp/java/providers/DiagnosticsProvider.kt | 664 +++---- .../lsp/java/utils/AnalyzeTimer.java | 190 +- .../lsp/java/utils/JavaParserUtils.kt | 1645 +++++++++-------- .../lsp/java/visitors/FindCompletionsAt.java | 210 +-- .../services/NoOpAsyncExecutionService.kt | 219 ++- .../manager/services/IdeThemeServiceImpl.kt | 83 +- .../uidesigner/models/UiWidgetCategory.kt | 6 +- .../internal/adapters/AdapterViewAdapter.kt | 37 +- .../inflater/internal/utils/ViewFactory.kt | 88 +- 10 files changed, 1873 insertions(+), 1730 deletions(-) diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt index 261a8b9084..d3c8e2dd94 100644 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt +++ b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt @@ -50,231 +50,238 @@ import javax.lang.model.element.Modifier.STATIC * * @author Akash Yadav */ -class ViewAdapterIndexGenerator(private val logger: KSPLogger) { - - private val indexClassBuilder = - TypeSpec.classBuilder(INDEX_CLASS_NAME) - .addModifiers(PUBLIC, FINAL) - .addSuperinterface(viewAdapterInterface) - private val indexAddStatements = CodeBlock.builder() - - fun init() { - val adapterType = - ParameterizedTypeName.get( - ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME), - WildcardTypeName.subtypeOf(viewClass) - ) - val mapOfStringToViewAdapter = - ParameterizedTypeName.get( - ClassName.get(Map::class.java), - ClassName.get(String::class.java), - adapterType - ) - indexClassBuilder.addField( - FieldSpec.builder(mapOfStringToViewAdapter, INDEX_MAP_FIELD, PRIVATE, STATIC, FINAL).build() - ) - - indexAddStatements.addStatement( - "final var adapters = new \$T()", - ParameterizedTypeName.get( - ClassName.get(HashMap::class.java), - ClassName.get(String::class.java), - adapterType - ) - ) - - // addPrivateConstructor(indexClassBuilder) - - val indexImpl = ClassName.get(INDEX_PACKAGE_NAME, INDEX_CLASS_NAME) - indexClassBuilder.addField( - FieldSpec.builder(indexImpl, "INSTANCE", PUBLIC, STATIC, FINAL) - .initializer("new \$T()", indexImpl) - .build() - ) - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getAdapter") - .addAnnotation(Override::class.java) - .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) - .addModifiers(PUBLIC) - .addParameter(String::class.java, "view", FINAL) - .returns(adapterType) - .addStatement("var adapter = \$L.get(\$L)", INDEX_MAP_FIELD, "view") - .beginControlFlow("if (adapter == null)") - .addStatement("adapter = \$L.get(\$S)", INDEX_MAP_FIELD, VIEW_CLASS) - .endControlFlow() - .addStatement("return adapter") - .build() - ) - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getViewAdapter") - .addAnnotation(Override::class.java) - .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) - .addModifiers(PUBLIC) - .addParameter(String::class.java, "view", FINAL) - .returns(adapterType) - .addStatement("return \$L.get(\$L)", INDEX_MAP_FIELD, "view") - .build() - ) - - val listOfViewAdapters = - ParameterizedTypeName.get(ClassName.get(java.util.List::class.java), adapterType) - val mapOfGroupToListOfViewAdapter = - ParameterizedTypeName.get( - ClassName.get(Map::class.java), - ClassName.get(IncludeInDesigner.Group::class.java), - listOfViewAdapters - ) - - indexClassBuilder.addField( - FieldSpec.builder( - mapOfGroupToListOfViewAdapter, - INDEX_PROVIDER_MAP_FIELD, - PRIVATE, - STATIC, - FINAL - ) - .build() - ) - - indexAddStatements.addStatement( - "final var providers = new \$T()", - ParameterizedTypeName.get( - ClassName.get(HashMap::class.java), - ClassName.get(IncludeInDesigner.Group::class.java), - listOfViewAdapters - ) - ) - - val nonNull = ClassName.get("androidx.annotation", "NonNull") - val groupParam = - ParameterSpec.builder(IncludeInDesigner.Group::class.java, "group", FINAL).build() - - indexClassBuilder.addMethod( - MethodSpec.methodBuilder("getWidgetProviders") - .addAnnotation(Override::class.java) - .addAnnotation(nonNull) - .addModifiers(PUBLIC) - .returns(listOfViewAdapters) - .addParameter(groupParam) - .addStatement("return \$L.get(group)", INDEX_PROVIDER_MAP_FIELD) - .build() - ) - } - - @OptIn(KspExperimental::class) - fun addViewAdapter(sym: KSClassDeclaration): Boolean { - val block = CodeBlock.builder() - - val viewAdapter = - sym.getKSAnnotationsByType(ViewAdapter::class).iterator().run { - val result = next() - if (hasNext()) { - logger.error("${ViewAdapter::class.simpleName} can only be applied once.", sym) - return false - } - result - } - - val includeInDesigner = - if (sym.isAnnotationPresent(IncludeInDesigner::class)) { - sym.getAnnotationsByType(IncludeInDesigner::class).iterator().run { - val result = next() - if (hasNext()) { - logger.error("${IncludeInDesigner::class.simpleName} can only be applied once.", sym) - return false - } - result - } - } else null - - val requiresApi = - if (sym.isAnnotationPresent(RequiresApi::class)) - sym.getAnnotationsByType(RequiresApi::class).iterator().next() - else null - - val viewName = getViewName(viewAdapter) - val moduleNs = getModuleNs(viewAdapter) - - val adapterTypeName = ClassName.get(sym.packageName.asString(), sym.simpleName.asString()) - val viewTypeName = - ClassName.get(viewName.substringBeforeLast('.'), viewName.substringAfterLast('.')) - - requiresApi?.let { annotation -> - val api = if (annotation.value == 1) annotation.api else annotation.value - val androidBuild = ClassName.get("android.os", "Build") - block.beginControlFlow("if(\$T.VERSION.SDK_INT >= \$L)", androidBuild, api) - } - - block.addStatement( - "final var adapter = new \$T()", - ParameterizedTypeName.get(adapterTypeName, viewTypeName) - ) - - block.addStatement("adapter.\$L(\$S)", METHOD_SET_MODULE, moduleNs) - block.addStatement("adapters.put(\$S, adapter)", viewName) - - if (includeInDesigner != null) { - assertOverridesCreateWidget(sym) - block.addStatement( - "providers.computeIfAbsent(\$T.\$L, g -> new \$T<>()).add(adapter)", - ClassName.get(IncludeInDesigner.Group::class.java), - includeInDesigner.group, - ClassName.get(java.util.ArrayList::class.java) - ) - } - - requiresApi?.let { block.endControlFlow() } - - indexAddStatements.add("{\n") - indexAddStatements.indent() - indexAddStatements.add(block.build()) - indexAddStatements.unindent() - indexAddStatements.add("}\n") - - return true - } - - fun generate(out: OutputStream) { - val javaCollections = ClassName.get(Collections::class.java) - - indexAddStatements.addStatement( - "\$L = \$T.unmodifiableMap(adapters)", - INDEX_MAP_FIELD, - javaCollections - ) - - indexAddStatements.addStatement( - "\$L = \$T.unmodifiableMap(providers)", - INDEX_PROVIDER_MAP_FIELD, - javaCollections - ) - - indexClassBuilder.addStaticBlock(indexAddStatements.build()) - - OutputStreamWriter(out).use { - val file = JavaFile.builder(INDEX_PACKAGE_NAME, indexClassBuilder.build()) - file.build().writeTo(it) - } - } - - private fun assertOverridesCreateWidget(sym: KSClassDeclaration): Boolean { - return sym.declarations - .filter { it is KSFunctionDeclaration } - .find { ADAPTER_FUNC_CREATE_WIDGET == it.simpleName.asString() } != null - } - - private fun getViewName(viewAdapter: KSAnnotation): String { - return getViewType(viewAdapter).declaration.qualifiedName!!.asString() - } - - private fun getViewType(viewAdapter: KSAnnotation) = - (getAnnotationArg(viewAdapter, "forView") as KSType) - - private fun getModuleNs(viewAdapter: KSAnnotation) = - (getAnnotationArg(viewAdapter, "moduleNamespace") as String) - - private fun getAnnotationArg(viewAdapter: KSAnnotation, arg: String) = - viewAdapter.arguments.first { it.name!!.asString() == arg }.value +class ViewAdapterIndexGenerator( + private val logger: KSPLogger, +) { + private val indexClassBuilder = + TypeSpec + .classBuilder(INDEX_CLASS_NAME) + .addModifiers(PUBLIC, FINAL) + .addSuperinterface(viewAdapterInterface) + private val indexAddStatements = CodeBlock.builder() + + fun init() { + val adapterType = + ParameterizedTypeName.get( + ClassName.get(ADAPTER_BASE_CLASS_PCK, ADAPTER_BASE_CLASS_NAME), + WildcardTypeName.subtypeOf(viewClass), + ) + val mapOfStringToViewAdapter = + ParameterizedTypeName.get( + ClassName.get(Map::class.java), + ClassName.get(String::class.java), + adapterType, + ) + indexClassBuilder.addField( + FieldSpec.builder(mapOfStringToViewAdapter, INDEX_MAP_FIELD, PRIVATE, STATIC, FINAL).build(), + ) + + indexAddStatements.addStatement( + "final var adapters = new \$T()", + ParameterizedTypeName.get( + ClassName.get(HashMap::class.java), + ClassName.get(String::class.java), + adapterType, + ), + ) + + // addPrivateConstructor(indexClassBuilder) + + val indexImpl = ClassName.get(INDEX_PACKAGE_NAME, INDEX_CLASS_NAME) + indexClassBuilder.addField( + FieldSpec + .builder(indexImpl, "INSTANCE", PUBLIC, STATIC, FINAL) + .initializer("new \$T()", indexImpl) + .build(), + ) + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getAdapter") + .addAnnotation(Override::class.java) + .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) + .addModifiers(PUBLIC) + .addParameter(String::class.java, "view", FINAL) + .returns(adapterType) + .addStatement("var adapter = \$L.get(\$L)", INDEX_MAP_FIELD, "view") + .beginControlFlow("if (adapter == null)") + .addStatement("adapter = \$L.get(\$S)", INDEX_MAP_FIELD, VIEW_CLASS) + .endControlFlow() + .addStatement("return adapter") + .build(), + ) + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getViewAdapter") + .addAnnotation(Override::class.java) + .addAnnotation(ClassName.get("androidx.annotation", "Nullable")) + .addModifiers(PUBLIC) + .addParameter(String::class.java, "view", FINAL) + .returns(adapterType) + .addStatement("return \$L.get(\$L)", INDEX_MAP_FIELD, "view") + .build(), + ) + + val listOfViewAdapters = + ParameterizedTypeName.get(ClassName.get(java.util.List::class.java), adapterType) + val mapOfGroupToListOfViewAdapter = + ParameterizedTypeName.get( + ClassName.get(Map::class.java), + ClassName.get(IncludeInDesigner.Group::class.java), + listOfViewAdapters, + ) + + indexClassBuilder.addField( + FieldSpec + .builder( + mapOfGroupToListOfViewAdapter, + INDEX_PROVIDER_MAP_FIELD, + PRIVATE, + STATIC, + FINAL, + ).build(), + ) + + indexAddStatements.addStatement( + "final var providers = new \$T()", + ParameterizedTypeName.get( + ClassName.get(HashMap::class.java), + ClassName.get(IncludeInDesigner.Group::class.java), + listOfViewAdapters, + ), + ) + + val nonNull = ClassName.get("androidx.annotation", "NonNull") + val groupParam = + ParameterSpec.builder(IncludeInDesigner.Group::class.java, "group", FINAL).build() + + indexClassBuilder.addMethod( + MethodSpec + .methodBuilder("getWidgetProviders") + .addAnnotation(Override::class.java) + .addAnnotation(nonNull) + .addModifiers(PUBLIC) + .returns(listOfViewAdapters) + .addParameter(groupParam) + .addStatement("return \$L.get(group)", INDEX_PROVIDER_MAP_FIELD) + .build(), + ) + } + + @OptIn(KspExperimental::class) + fun addViewAdapter(sym: KSClassDeclaration): Boolean { + val block = CodeBlock.builder() + + val viewAdapter = + sym.getKSAnnotationsByType(ViewAdapter::class).iterator().run { + val result = next() + if (hasNext()) { + logger.error("${ViewAdapter::class.simpleName} can only be applied once.", sym) + return false + } + result + } + + val includeInDesigner = + if (sym.isAnnotationPresent(IncludeInDesigner::class)) { + sym.getAnnotationsByType(IncludeInDesigner::class).iterator().run { + val result = next() + if (hasNext()) { + logger.error("${IncludeInDesigner::class.simpleName} can only be applied once.", sym) + return false + } + result + } + } else { + null + } + + val requiresApi = + if (sym.isAnnotationPresent(RequiresApi::class)) { + sym.getAnnotationsByType(RequiresApi::class).iterator().next() + } else { + null + } + + val viewName = getViewName(viewAdapter) + val moduleNs = getModuleNs(viewAdapter) + + val adapterTypeName = ClassName.get(sym.packageName.asString(), sym.simpleName.asString()) + val viewTypeName = + ClassName.get(viewName.substringBeforeLast('.'), viewName.substringAfterLast('.')) + + requiresApi?.let { annotation -> + val api = if (annotation.value == 1) annotation.api else annotation.value + val androidBuild = ClassName.get("android.os", "Build") + block.beginControlFlow("if(\$T.VERSION.SDK_INT >= \$L)", androidBuild, api) + } + + block.addStatement( + "final var adapter = new \$T()", + ParameterizedTypeName.get(adapterTypeName, viewTypeName), + ) + + block.addStatement("adapter.\$L(\$S)", METHOD_SET_MODULE, moduleNs) + block.addStatement("adapters.put(\$S, adapter)", viewName) + + if (includeInDesigner != null) { + assertOverridesCreateWidget(sym) + block.addStatement( + "providers.computeIfAbsent(\$T.\$L, g -> new \$T<>()).add(adapter)", + ClassName.get(IncludeInDesigner.Group::class.java), + includeInDesigner.group, + ClassName.get(java.util.ArrayList::class.java), + ) + } + + requiresApi?.let { block.endControlFlow() } + + indexAddStatements.add("{\n") + indexAddStatements.indent() + indexAddStatements.add(block.build()) + indexAddStatements.unindent() + indexAddStatements.add("}\n") + + return true + } + + fun generate(out: OutputStream) { + val javaCollections = ClassName.get(Collections::class.java) + + indexAddStatements.addStatement( + "\$L = \$T.unmodifiableMap(adapters)", + INDEX_MAP_FIELD, + javaCollections, + ) + + indexAddStatements.addStatement( + "\$L = \$T.unmodifiableMap(providers)", + INDEX_PROVIDER_MAP_FIELD, + javaCollections, + ) + + indexClassBuilder.addStaticBlock(indexAddStatements.build()) + + OutputStreamWriter(out).use { + val file = JavaFile.builder(INDEX_PACKAGE_NAME, indexClassBuilder.build()) + file.build().writeTo(it) + } + } + + private fun assertOverridesCreateWidget(sym: KSClassDeclaration): Boolean = + sym.declarations + .filter { it is KSFunctionDeclaration } + .find { ADAPTER_FUNC_CREATE_WIDGET == it.simpleName.asString() } != null + + private fun getViewName(viewAdapter: KSAnnotation): String = getViewType(viewAdapter).declaration.qualifiedName!!.asString() + + private fun getViewType(viewAdapter: KSAnnotation) = (getAnnotationArg(viewAdapter, "forView") as KSType) + + private fun getModuleNs(viewAdapter: KSAnnotation) = (getAnnotationArg(viewAdapter, "moduleNamespace") as String) + + private fun getAnnotationArg( + viewAdapter: KSAnnotation, + arg: String, + ) = viewAdapter.arguments.first { it.name!!.asString() == arg }.value } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt index abb6a33168..6ad6c2c3e1 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt @@ -1,318 +1,346 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -package com.itsaky.androidide.lsp.java.providers - -import com.itsaky.androidide.lsp.java.compiler.CompileTask -import com.itsaky.androidide.lsp.java.models.DiagnosticCode -import com.itsaky.androidide.lsp.java.models.DiagnosticCode.EMPTY_BLOCK -import com.itsaky.androidide.lsp.java.models.DiagnosticCode.UNUSED_THROWS -import com.itsaky.androidide.lsp.java.visitors.DiagnosticVisitor -import com.itsaky.androidide.lsp.models.DiagnosticItem -import com.itsaky.androidide.lsp.models.DiagnosticSeverity -import com.itsaky.androidide.lsp.models.DiagnosticSeverity.WARNING -import com.itsaky.androidide.models.Range -import com.itsaky.androidide.progress.ProgressManager.Companion.abortIfCancelled -import com.itsaky.androidide.projects.FileManager -import com.itsaky.androidide.utils.DocumentUtils.isSameFile -import jdkx.lang.model.element.Element -import jdkx.tools.Diagnostic -import jdkx.tools.JavaFileObject -import openjdk.source.tree.BlockTree -import openjdk.source.tree.ClassTree -import openjdk.source.tree.CompilationUnitTree -import openjdk.source.tree.LineMap -import openjdk.source.tree.MethodTree -import openjdk.source.tree.VariableTree -import openjdk.source.util.TreePath -import openjdk.source.util.Trees -import java.nio.file.Path -import java.nio.file.Paths -import java.util.Locale -import java.util.regex.Pattern - -/** - * Finds errors and warnings from a compilation task. - * - * @author Akash Yadav - */ -object DiagnosticsProvider { - /** - * Finds diagnostics from the given task (only the diagnostics for the given file). The task - * should be a valid task. - * - * As the file might be too long, the diagnostics list must be sorted so we can quickly binary - * search the list when needed. - * - * @param task The compilation task to get diagnostics from. - * @param file The file of which the diagnostics must be extracted. - * @return The list of diagnostics retrieved from the task. Never null. - */ - @JvmStatic - fun findDiagnostics(task: CompileTask, file: Path?): List { - val result = mutableListOf() - var root: CompilationUnitTree? = null - for (tree in task.roots) { - abortIfCancelled() - val path = Paths.get(tree.sourceFile.toUri()) - if (isSameFile(path, file!!)) { - root = tree - break - } - } - - abortIfCancelled() - - if (root == null) { - // CompilationUnitTree for the file was not found - // Can't do anything... - return result - } - - addCompilerErrors(task, root, result) - abortIfCancelled() - addDiagnosticsByVisiting(task, root, result) - abortIfCancelled() - return result - } - - private fun addDiagnosticsByVisiting( - task: CompileTask, - root: CompilationUnitTree, - result: MutableList - ) { - val notThrown = mutableMapOf() - val scanner = DiagnosticVisitor(task.task) - scanner.scan(root, notThrown) - for (unusedEl in scanner.notUsed()) { - warnUnused(task, unusedEl)?.also { result.add(it) } - } - - for (location in notThrown.keys) { - result.add(warnNotThrown(task, notThrown[location], location!!)) - } - - for (path in scanner.emptyBlocks.keys) { - result.add(warnEmptyBlock(task, path, scanner.emptyBlocks[path]!!)) - } - } - - private fun warnEmptyBlock(task: CompileTask, path: TreePath, name: String): DiagnosticItem { - val trees = Trees.instance(task.task) - val thisTree = path.leaf - val code = EMPTY_BLOCK - - val root = task.root() - val lines = task.root().lineMap - val positions = trees.sourcePositions - val start = positions.getStartPosition(root, thisTree) - val end = positions.getEndPosition(root, thisTree) - return DiagnosticItem( - source = "", - code = code.id, - message = "'$name' statement has empty body", - severity = WARNING, - range = - Range(getPosition(start, lines), getPosition(end, lines)).apply { - this.start.index = start.toInt() - this.end.index = end.toInt() - } - ) - } - - private fun addCompilerErrors( - task: CompileTask, - root: CompilationUnitTree, - result: MutableList - ) { - for (diagnostic in task.diagnostics) { - if (diagnostic.source == null || diagnostic.source!!.toUri() != root.sourceFile.toUri()) { - continue - } - if (diagnostic.startPosition == -1L || diagnostic.endPosition == -1L) { - continue - } - result.add(asDiagnosticItem(diagnostic, root.lineMap)) - } - } - - private fun warnNotThrown(task: CompileTask, name: String?, path: TreePath): DiagnosticItem { - val trees = Trees.instance(task.task) - val pos = trees.sourcePositions - val root = path.compilationUnit - val lines = root.lineMap - val start = pos.getStartPosition(root, path.leaf) - val end = pos.getEndPosition(root, path.leaf) - return DiagnosticItem( - message = String.format("'%s' is not thrown in the body of the method", name), - range = - Range(getPosition(start, lines), getPosition(end, lines)).apply { - this.start.index = start.toInt() - this.end.index = end.toInt() - }, - code = UNUSED_THROWS.id, - severity = DiagnosticSeverity.INFO, - source = "" - ) - } - - private fun warnUnused(task: CompileTask, unusedEl: Element): DiagnosticItem? { - val trees = Trees.instance(task.task) - val path = trees.getPath(unusedEl) ?: throw RuntimeException("$unusedEl has no path") - val root = path.compilationUnit - val leaf = path.leaf - val pos = trees.sourcePositions - var start = pos.getStartPosition(root, leaf).toInt() - var end = pos.getEndPosition(root, leaf).toInt() - - if (leaf is VariableTree) { - val offset = pos.getEndPosition(root, leaf.type).toInt() - if (offset != -1) { - start = offset - } - } - - val file = Paths.get(root.sourceFile.toUri()) - val contents = FileManager.getDocumentContents(file) - var name = unusedEl.simpleName - if (name.contentEquals("")) { - name = unusedEl.enclosingElement.simpleName - } - - val region = try { - contents.subSequence(start, end) - } catch (err: IndexOutOfBoundsException) { - // might happen if the file contents were changed after the file was compiled for analysis - return null - } - - val matcher = Pattern.compile("\\b$name\\b").matcher(region) - if (matcher.find()) { - start += matcher.start() - end = start + name.length - } - - val message = String.format("'%s' is not used", name) - val code: DiagnosticCode - val severity: DiagnosticSeverity - when (leaf) { - is VariableTree -> { - when (path.parentPath.leaf) { - is MethodTree -> { - code = DiagnosticCode.UNUSED_PARAM - severity = DiagnosticSeverity.HINT - } - is BlockTree -> { - code = DiagnosticCode.UNUSED_LOCAL - severity = DiagnosticSeverity.INFO - } - is ClassTree -> { - code = DiagnosticCode.UNUSED_FIELD - severity = DiagnosticSeverity.INFO - } - else -> { - code = DiagnosticCode.UNUSED_OTHER - severity = DiagnosticSeverity.HINT - } - } - } - is MethodTree -> { - code = DiagnosticCode.UNUSED_METHOD - severity = DiagnosticSeverity.INFO - } - is ClassTree -> { - code = DiagnosticCode.UNUSED_CLASS - severity = DiagnosticSeverity.INFO - } - else -> { - code = DiagnosticCode.UNUSED_OTHER - severity = DiagnosticSeverity.INFO - } - } - - return asDiagnosticItem(severity, code.id, message, start.toLong(), end.toLong(), root) - } - - private fun asDiagnosticItem( - severity: DiagnosticSeverity, - code: String, - message: String, - start: Long, - end: Long, - root: CompilationUnitTree - ): DiagnosticItem { - return DiagnosticItem( - message = message, - code = code, - severity = severity, - range = - Range(getPosition(start, root.lineMap), getPosition(end, root.lineMap)).apply { - this.start.index = start.toInt() - this.end.index = end.toInt() - }, - source = "" - ) - } - - private fun asDiagnosticItem( - diagnostic: Diagnostic, - lines: LineMap - ): DiagnosticItem { - abortIfCancelled() - val result = - DiagnosticItem( - range = getDiagnosticRange(diagnostic, lines), - severity = severityFor(diagnostic.kind), - code = diagnostic.code, - message = diagnostic.getMessage(Locale.getDefault()), - source = "" - ) - result.range.start.index = diagnostic.startPosition.toInt() - result.range.end.index = diagnostic.endPosition.toInt() - result.extra = diagnostic - return result - } - - private fun getDiagnosticRange( - diagnostic: Diagnostic, - lines: LineMap - ): Range { - abortIfCancelled() - val start = getPosition(diagnostic.startPosition, lines) - val end = getPosition(diagnostic.endPosition, lines) - return Range(start, end) - } - - private fun getPosition(position: Long, lines: LineMap): com.itsaky.androidide.models.Position { - abortIfCancelled() - // decrement the numbers - // to convert 1-based indexes to 0-based - val line = (lines.getLineNumber(position) - 1).toInt() - val column = (lines.getColumnNumber(position) - 1).toInt() - return com.itsaky.androidide.models.Position(line, column) - } - - private fun severityFor(kind: Diagnostic.Kind): DiagnosticSeverity { - return when (kind) { - Diagnostic.Kind.ERROR -> DiagnosticSeverity.ERROR - Diagnostic.Kind.WARNING, - Diagnostic.Kind.MANDATORY_WARNING -> WARNING - Diagnostic.Kind.NOTE -> DiagnosticSeverity.INFO - Diagnostic.Kind.OTHER -> DiagnosticSeverity.HINT - else -> DiagnosticSeverity.HINT - } - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +package com.itsaky.androidide.lsp.java.providers + +import com.itsaky.androidide.lsp.java.compiler.CompileTask +import com.itsaky.androidide.lsp.java.models.DiagnosticCode +import com.itsaky.androidide.lsp.java.models.DiagnosticCode.EMPTY_BLOCK +import com.itsaky.androidide.lsp.java.models.DiagnosticCode.UNUSED_THROWS +import com.itsaky.androidide.lsp.java.visitors.DiagnosticVisitor +import com.itsaky.androidide.lsp.models.DiagnosticItem +import com.itsaky.androidide.lsp.models.DiagnosticSeverity +import com.itsaky.androidide.lsp.models.DiagnosticSeverity.WARNING +import com.itsaky.androidide.models.Range +import com.itsaky.androidide.progress.ProgressManager.Companion.abortIfCancelled +import com.itsaky.androidide.projects.FileManager +import com.itsaky.androidide.utils.DocumentUtils.isSameFile +import jdkx.lang.model.element.Element +import jdkx.tools.Diagnostic +import jdkx.tools.JavaFileObject +import openjdk.source.tree.BlockTree +import openjdk.source.tree.ClassTree +import openjdk.source.tree.CompilationUnitTree +import openjdk.source.tree.LineMap +import openjdk.source.tree.MethodTree +import openjdk.source.tree.VariableTree +import openjdk.source.util.TreePath +import openjdk.source.util.Trees +import java.nio.file.Path +import java.nio.file.Paths +import java.util.Locale +import java.util.regex.Pattern + +/** + * Finds errors and warnings from a compilation task. + * + * @author Akash Yadav + */ +object DiagnosticsProvider { + /** + * Finds diagnostics from the given task (only the diagnostics for the given file). The task + * should be a valid task. + * + * As the file might be too long, the diagnostics list must be sorted so we can quickly binary + * search the list when needed. + * + * @param task The compilation task to get diagnostics from. + * @param file The file of which the diagnostics must be extracted. + * @return The list of diagnostics retrieved from the task. Never null. + */ + @JvmStatic + fun findDiagnostics( + task: CompileTask, + file: Path?, + ): List { + val result = mutableListOf() + var root: CompilationUnitTree? = null + for (tree in task.roots) { + abortIfCancelled() + val path = Paths.get(tree.sourceFile.toUri()) + if (isSameFile(path, file!!)) { + root = tree + break + } + } + + abortIfCancelled() + + if (root == null) { + // CompilationUnitTree for the file was not found + // Can't do anything... + return result + } + + addCompilerErrors(task, root, result) + abortIfCancelled() + addDiagnosticsByVisiting(task, root, result) + abortIfCancelled() + return result + } + + private fun addDiagnosticsByVisiting( + task: CompileTask, + root: CompilationUnitTree, + result: MutableList, + ) { + val notThrown = mutableMapOf() + val scanner = DiagnosticVisitor(task.task) + scanner.scan(root, notThrown) + for (unusedEl in scanner.notUsed()) { + warnUnused(task, unusedEl)?.also { result.add(it) } + } + + for (location in notThrown.keys) { + result.add(warnNotThrown(task, notThrown[location], location!!)) + } + + for (path in scanner.emptyBlocks.keys) { + result.add(warnEmptyBlock(task, path, scanner.emptyBlocks[path]!!)) + } + } + + private fun warnEmptyBlock( + task: CompileTask, + path: TreePath, + name: String, + ): DiagnosticItem { + val trees = Trees.instance(task.task) + val thisTree = path.leaf + val code = EMPTY_BLOCK + + val root = task.root() + val lines = task.root().lineMap + val positions = trees.sourcePositions + val start = positions.getStartPosition(root, thisTree) + val end = positions.getEndPosition(root, thisTree) + return DiagnosticItem( + source = "", + code = code.id, + message = "'$name' statement has empty body", + severity = WARNING, + range = + Range(getPosition(start, lines), getPosition(end, lines)).apply { + this.start.index = start.toInt() + this.end.index = end.toInt() + }, + ) + } + + private fun addCompilerErrors( + task: CompileTask, + root: CompilationUnitTree, + result: MutableList, + ) { + for (diagnostic in task.diagnostics) { + if (diagnostic.source == null || diagnostic.source!!.toUri() != root.sourceFile.toUri()) { + continue + } + if (diagnostic.startPosition == -1L || diagnostic.endPosition == -1L) { + continue + } + result.add(asDiagnosticItem(diagnostic, root.lineMap)) + } + } + + private fun warnNotThrown( + task: CompileTask, + name: String?, + path: TreePath, + ): DiagnosticItem { + val trees = Trees.instance(task.task) + val pos = trees.sourcePositions + val root = path.compilationUnit + val lines = root.lineMap + val start = pos.getStartPosition(root, path.leaf) + val end = pos.getEndPosition(root, path.leaf) + return DiagnosticItem( + message = String.format("'%s' is not thrown in the body of the method", name), + range = + Range(getPosition(start, lines), getPosition(end, lines)).apply { + this.start.index = start.toInt() + this.end.index = end.toInt() + }, + code = UNUSED_THROWS.id, + severity = DiagnosticSeverity.INFO, + source = "", + ) + } + + private fun warnUnused( + task: CompileTask, + unusedEl: Element, + ): DiagnosticItem? { + val trees = Trees.instance(task.task) + val path = trees.getPath(unusedEl) ?: throw RuntimeException("$unusedEl has no path") + val root = path.compilationUnit + val leaf = path.leaf + val pos = trees.sourcePositions + var start = pos.getStartPosition(root, leaf).toInt() + var end = pos.getEndPosition(root, leaf).toInt() + + if (leaf is VariableTree) { + val offset = pos.getEndPosition(root, leaf.type).toInt() + if (offset != -1) { + start = offset + } + } + + val file = Paths.get(root.sourceFile.toUri()) + val contents = FileManager.getDocumentContents(file) + var name = unusedEl.simpleName + if (name.contentEquals("")) { + name = unusedEl.enclosingElement.simpleName + } + + val region = + try { + contents.subSequence(start, end) + } catch (err: IndexOutOfBoundsException) { + // might happen if the file contents were changed after the file was compiled for analysis + return null + } + + val matcher = Pattern.compile("\\b$name\\b").matcher(region) + if (matcher.find()) { + start += matcher.start() + end = start + name.length + } + + val message = String.format("'%s' is not used", name) + val code: DiagnosticCode + val severity: DiagnosticSeverity + when (leaf) { + is VariableTree -> { + when (path.parentPath.leaf) { + is MethodTree -> { + code = DiagnosticCode.UNUSED_PARAM + severity = DiagnosticSeverity.HINT + } + + is BlockTree -> { + code = DiagnosticCode.UNUSED_LOCAL + severity = DiagnosticSeverity.INFO + } + + is ClassTree -> { + code = DiagnosticCode.UNUSED_FIELD + severity = DiagnosticSeverity.INFO + } + + else -> { + code = DiagnosticCode.UNUSED_OTHER + severity = DiagnosticSeverity.HINT + } + } + } + + is MethodTree -> { + code = DiagnosticCode.UNUSED_METHOD + severity = DiagnosticSeverity.INFO + } + + is ClassTree -> { + code = DiagnosticCode.UNUSED_CLASS + severity = DiagnosticSeverity.INFO + } + + else -> { + code = DiagnosticCode.UNUSED_OTHER + severity = DiagnosticSeverity.INFO + } + } + + return asDiagnosticItem(severity, code.id, message, start.toLong(), end.toLong(), root) + } + + private fun asDiagnosticItem( + severity: DiagnosticSeverity, + code: String, + message: String, + start: Long, + end: Long, + root: CompilationUnitTree, + ): DiagnosticItem = + DiagnosticItem( + message = message, + code = code, + severity = severity, + range = + Range(getPosition(start, root.lineMap), getPosition(end, root.lineMap)).apply { + this.start.index = start.toInt() + this.end.index = end.toInt() + }, + source = "", + ) + + private fun asDiagnosticItem( + diagnostic: Diagnostic, + lines: LineMap, + ): DiagnosticItem { + abortIfCancelled() + val result = + DiagnosticItem( + range = getDiagnosticRange(diagnostic, lines), + severity = severityFor(diagnostic.kind), + code = diagnostic.code, + message = diagnostic.getMessage(Locale.getDefault()), + source = "", + ) + result.range.start.index = diagnostic.startPosition.toInt() + result.range.end.index = diagnostic.endPosition.toInt() + result.extra = diagnostic + return result + } + + private fun getDiagnosticRange( + diagnostic: Diagnostic, + lines: LineMap, + ): Range { + abortIfCancelled() + val start = getPosition(diagnostic.startPosition, lines) + val end = getPosition(diagnostic.endPosition, lines) + return Range(start, end) + } + + private fun getPosition( + position: Long, + lines: LineMap, + ): com.itsaky.androidide.models.Position { + abortIfCancelled() + // decrement the numbers + // to convert 1-based indexes to 0-based + val line = (lines.getLineNumber(position) - 1).toInt() + val column = (lines.getColumnNumber(position) - 1).toInt() + return com.itsaky.androidide.models + .Position(line, column) + } + + private fun severityFor(kind: Diagnostic.Kind): DiagnosticSeverity = + when (kind) { + Diagnostic.Kind.ERROR -> DiagnosticSeverity.ERROR + + Diagnostic.Kind.WARNING, + Diagnostic.Kind.MANDATORY_WARNING, + -> WARNING + + Diagnostic.Kind.NOTE -> DiagnosticSeverity.INFO + + Diagnostic.Kind.OTHER -> DiagnosticSeverity.HINT + + else -> DiagnosticSeverity.HINT + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/AnalyzeTimer.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/AnalyzeTimer.java index f3a7cced45..ab55e62346 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/AnalyzeTimer.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/AnalyzeTimer.java @@ -1,93 +1,97 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ - -package com.itsaky.androidide.lsp.java.utils; - -import android.os.Handler; -import androidx.annotation.NonNull; -import java.util.Objects; - -/** - * A timer which helps the language server to run a lint check after a specified interval. - * - * @author Akash Yadav - */ -public class AnalyzeTimer { - - public static final long DEFAULT_INTERVAL = 400; - @NonNull private final Handler timerHandler; - @NonNull private final Runnable timerCallback; - private long interval; - private boolean started; - - /** - * Creates a new AnalyzeTimer instance. - * - * @param timerCallback The callback that will be invoked after the timer has ended. - */ - public AnalyzeTimer(@NonNull Runnable timerCallback) { - this.timerHandler = new Handler(); - this.interval = DEFAULT_INTERVAL; - this.timerCallback = timerCallback; - - Objects.requireNonNull(this.timerCallback, "Callback cannot be null"); - } - - /** - * Get the interval set to this timer. - * - * @return The interval. - */ - public long getInterval() { - return interval; - } - - /** - * Set the interval for the lint timer. - * - * @param interval The interval after which timerCallback will be called. - */ - public void setInterval(long interval) { - this.interval = interval; - - if (this.interval <= 0) { - throw new IllegalArgumentException("Invalid interval specified for timer."); - } - } - - /** Starts the timer. */ - public void start() { - restart(); - } - - /** Restarts the timer. */ - public void restart() { - timerHandler.removeCallbacks(timerCallback); - timerHandler.postDelayed(timerCallback, interval); - started = true; - } - - /** Shutdown the timer. Cancels any running timers. */ - public void cancel() { - timerHandler.removeCallbacks(timerCallback); - started = false; - } - - public boolean isStarted() { - return started; - } -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.lsp.java.utils; + +import android.os.Handler; +import androidx.annotation.NonNull; +import java.util.Objects; + +/** + * A timer which helps the language server to run a lint check after a specified interval. + * + * @author Akash Yadav + */ +public class AnalyzeTimer { + + public static final long DEFAULT_INTERVAL = 400; + @NonNull + private final Handler timerHandler; + @NonNull + private final Runnable timerCallback; + private long interval; + private boolean started; + + /** + * Creates a new AnalyzeTimer instance. + * + * @param timerCallback + * The callback that will be invoked after the timer has ended. + */ + public AnalyzeTimer(@NonNull Runnable timerCallback) { + this.timerHandler = new Handler(); + this.interval = DEFAULT_INTERVAL; + this.timerCallback = timerCallback; + + Objects.requireNonNull(this.timerCallback, "Callback cannot be null"); + } + + /** Shutdown the timer. Cancels any running timers. */ + public void cancel() { + timerHandler.removeCallbacks(timerCallback); + started = false; + } + + /** + * Get the interval set to this timer. + * + * @return The interval. + */ + public long getInterval() { + return interval; + } + + public boolean isStarted() { + return started; + } + + /** Restarts the timer. */ + public void restart() { + timerHandler.removeCallbacks(timerCallback); + timerHandler.postDelayed(timerCallback, interval); + started = true; + } + + /** + * Set the interval for the lint timer. + * + * @param interval + * The interval after which timerCallback will be called. + */ + public void setInterval(long interval) { + this.interval = interval; + + if (this.interval <= 0) { + throw new IllegalArgumentException("Invalid interval specified for timer."); + } + } + + /** Starts the timer. */ + public void start() { + restart(); + } +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt index 7f0c5c83fb..d2f17b8999 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt @@ -1,789 +1,856 @@ -/* - * This file is part of AndroidIDE. - * - * AndroidIDE is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * AndroidIDE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with AndroidIDE. If not, see . - */ -@file:Suppress("unused", "MemberVisibilityCanBePrivate") - -package com.itsaky.androidide.lsp.java.utils - -import androidx.annotation.NonNull -import androidx.annotation.Nullable -import com.github.javaparser.StaticJavaParser -import com.github.javaparser.ast.CompilationUnit -import com.github.javaparser.ast.ImportDeclaration -import com.github.javaparser.ast.Node -import com.github.javaparser.ast.NodeList -import com.github.javaparser.ast.PackageDeclaration -import com.github.javaparser.ast.body.BodyDeclaration -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration -import com.github.javaparser.ast.body.FieldDeclaration -import com.github.javaparser.ast.body.MethodDeclaration -import com.github.javaparser.ast.body.Parameter -import com.github.javaparser.ast.body.ReceiverParameter -import com.github.javaparser.ast.body.VariableDeclarator -import com.github.javaparser.ast.expr.AnnotationExpr -import com.github.javaparser.ast.expr.AssignExpr -import com.github.javaparser.ast.expr.BooleanLiteralExpr -import com.github.javaparser.ast.expr.CharLiteralExpr -import com.github.javaparser.ast.expr.DoubleLiteralExpr -import com.github.javaparser.ast.expr.Expression -import com.github.javaparser.ast.expr.FieldAccessExpr -import com.github.javaparser.ast.expr.IntegerLiteralExpr -import com.github.javaparser.ast.expr.LiteralExpr -import com.github.javaparser.ast.expr.LongLiteralExpr -import com.github.javaparser.ast.expr.MarkerAnnotationExpr -import com.github.javaparser.ast.expr.MemberValuePair -import com.github.javaparser.ast.expr.MethodCallExpr -import com.github.javaparser.ast.expr.Name -import com.github.javaparser.ast.expr.NameExpr -import com.github.javaparser.ast.expr.NormalAnnotationExpr -import com.github.javaparser.ast.expr.NullLiteralExpr -import com.github.javaparser.ast.expr.SimpleName -import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr -import com.github.javaparser.ast.expr.StringLiteralExpr -import com.github.javaparser.ast.expr.SuperExpr -import com.github.javaparser.ast.expr.VariableDeclarationExpr -import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName -import com.github.javaparser.ast.stmt.BlockStmt -import com.github.javaparser.ast.stmt.ExpressionStmt -import com.github.javaparser.ast.stmt.ReturnStmt -import com.github.javaparser.ast.stmt.Statement -import com.github.javaparser.ast.type.ArrayType -import com.github.javaparser.ast.type.PrimitiveType -import com.github.javaparser.ast.type.PrimitiveType.Primitive.BOOLEAN -import com.github.javaparser.ast.type.PrimitiveType.Primitive.BYTE -import com.github.javaparser.ast.type.PrimitiveType.Primitive.CHAR -import com.github.javaparser.ast.type.PrimitiveType.Primitive.DOUBLE -import com.github.javaparser.ast.type.PrimitiveType.Primitive.FLOAT -import com.github.javaparser.ast.type.PrimitiveType.Primitive.INT -import com.github.javaparser.ast.type.PrimitiveType.Primitive.LONG -import com.github.javaparser.ast.type.PrimitiveType.Primitive.SHORT -import com.github.javaparser.ast.type.ReferenceType -import com.github.javaparser.ast.type.Type -import com.github.javaparser.ast.type.TypeParameter -import com.github.javaparser.printer.DefaultPrettyPrinter -import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration -import com.github.javaparser.printer.configuration.PrinterConfiguration -import com.itsaky.androidide.lsp.java.utils.TypeUtils.toType -import com.itsaky.androidide.lsp.java.visitors.PrettyPrintingVisitor -import jdkx.lang.model.element.ExecutableElement -import jdkx.lang.model.element.Modifier -import jdkx.lang.model.element.TypeParameterElement -import jdkx.lang.model.element.VariableElement -import jdkx.lang.model.type.ExecutableType -import jdkx.lang.model.type.TypeKind -import jdkx.lang.model.type.TypeMirror -import jdkx.lang.model.type.TypeVariable -import openjdk.source.tree.AnnotationTree -import openjdk.source.tree.AssignmentTree -import openjdk.source.tree.BlockTree -import openjdk.source.tree.ClassTree -import openjdk.source.tree.CompilationUnitTree -import openjdk.source.tree.ErroneousTree -import openjdk.source.tree.ExpressionStatementTree -import openjdk.source.tree.ExpressionTree -import openjdk.source.tree.IdentifierTree -import openjdk.source.tree.ImportTree -import openjdk.source.tree.LiteralTree -import openjdk.source.tree.MemberSelectTree -import openjdk.source.tree.MethodInvocationTree -import openjdk.source.tree.MethodTree -import openjdk.source.tree.PackageTree -import openjdk.source.tree.StatementTree -import openjdk.source.tree.Tree -import openjdk.source.tree.TypeParameterTree -import openjdk.source.tree.VariableTree -import org.jetbrains.annotations.Contract -import java.util.function.Predicate -import java.util.stream.IntStream -import java.util.stream.Stream -import kotlin.jvm.optionals.getOrNull - -object JavaParserUtils { - - /** - * Collects all the type names from the given node. - * - * @param type The method to get types from. - * @return A set of fully qualified names of the types in the given node. - */ - fun collectImports(type: ExecutableType): MutableSet { - val types = mutableSetOf() - val returnType = type.returnType - if (returnType != null) { - if ( - returnType.kind != TypeKind.VOID && - returnType.kind != TypeKind.TYPEVAR && - !returnType.kind.isPrimitive - ) { - val fqn = getTypeToImport(returnType) - if (fqn != null) { - types.add(fqn) - } - } - } - if (type.thrownTypes != null) { - for (thrown in type.thrownTypes) { - val fqn = getTypeToImport(thrown) - if (fqn != null) { - types.add(fqn) - } - } - } - for (t in type.parameterTypes) { - if (t.kind.isPrimitive) { - continue - } - val fqn = getTypeToImport(t) - if (fqn != null) { - types.add(fqn) - } - } - return types - } - - @Nullable - private fun getTypeToImport(type: TypeMirror): String? { - if (type.kind.isPrimitive) { - return null - } - if (type.kind == TypeKind.TYPEVAR) { - return null - } - var fqn = toType(type).toString() - if (type.kind == TypeKind.ARRAY) { - fqn = removeArray(fqn) - } - - return removeDiamond(fqn) - } - - fun printMethod( - method: ExecutableElement, - parameterizedType: ExecutableType?, - source: MethodTree, - ): MethodDeclaration { - val methodDeclaration: MethodDeclaration = toMethodDeclaration(source, parameterizedType) - printMethodInternal(methodDeclaration, method) - return methodDeclaration - } - - fun printMethod( - method: ExecutableElement?, - parameterizedType: ExecutableType?, - source: ExecutableElement, - ): MethodDeclaration { - val methodDeclaration: MethodDeclaration = toMethodDeclaration(method, parameterizedType) - printMethodInternal(methodDeclaration, source) - return methodDeclaration - } - - private fun printMethodInternal( - methodDeclaration: MethodDeclaration, - method: ExecutableElement, - ) { - methodDeclaration.addMarkerAnnotation(Override::class.java) - val recentlyNonNull = methodDeclaration.getAnnotationByName("RecentlyNonNull") - if (recentlyNonNull.isPresent) { - methodDeclaration.remove(recentlyNonNull.get()) - methodDeclaration.addMarkerAnnotation(NonNull::class.java) - } - - val blockStmt = BlockStmt() - if (method.modifiers.contains(Modifier.ABSTRACT)) { - methodDeclaration.removeModifier(com.github.javaparser.ast.Modifier.Keyword.ABSTRACT) - if (methodDeclaration.type.isClassOrInterfaceType) { - blockStmt.addStatement(ReturnStmt(NullLiteralExpr())) - } - if (methodDeclaration.type.isPrimitiveType) { - val type = methodDeclaration.type.asPrimitiveType() - blockStmt.addStatement(ReturnStmt(getReturnExpr(type))) - } - } else { - val methodCallExpr = MethodCallExpr() - methodCallExpr.name = methodDeclaration.name - methodCallExpr.arguments = - methodDeclaration.parameters - .stream() - .map { obj: Parameter -> obj.nameAsExpression } - .collect(NodeList.toNodeList()) - methodCallExpr.setScope(SuperExpr()) - if (methodDeclaration.type.isVoidType) { - blockStmt.addStatement(methodCallExpr) - } else { - blockStmt.addStatement(ReturnStmt(methodCallExpr)) - } - } - methodDeclaration.setBody(blockStmt) - } - - private fun getReturnExpr(type: PrimitiveType): Expression { - return when (type.type) { - BOOLEAN -> BooleanLiteralExpr() - BYTE, - DOUBLE, - CHAR, - SHORT, - LONG, - FLOAT, - INT -> IntegerLiteralExpr("0") - - else -> NullLiteralExpr() - } - } - - @Suppress("Since15") - fun toCompilationUnit(tree: CompilationUnitTree): CompilationUnit { - val compilationUnit = CompilationUnit() - compilationUnit.setPackageDeclaration(toPackageDeclaration(tree.getPackage())) - tree.imports.forEach { importTree: ImportTree? -> - compilationUnit.addImport(toImportDeclaration(importTree!!)) - } - compilationUnit.types = - tree.typeDecls - .stream() - .map { toClassOrInterfaceDeclaration(it) } - .collect(NodeList.toNodeList()) - return compilationUnit - } - - @Suppress("Since15") - fun toPackageDeclaration(tree: PackageTree): PackageDeclaration { - val declaration = PackageDeclaration() - declaration.setName(tree.packageName.toString()) - return declaration - } - - fun toImportDeclaration(tree: ImportTree): ImportDeclaration { - val name = tree.qualifiedIdentifier.toString() - val isAsterisk = name.endsWith("*") - return ImportDeclaration(name, tree.isStatic, isAsterisk) - } - - fun toClassOrInterfaceDeclaration(tree: Tree?): ClassOrInterfaceDeclaration? { - return if (tree is ClassTree) { - toClassOrInterfaceDeclaration(tree as ClassTree?) - } else null - } - - fun toBlockStatement(tree: BlockTree): BlockStmt { - val blockStmt = BlockStmt() - blockStmt.statements = - tree.statements.stream().map { toStatement(it) }.collect(NodeList.toNodeList()) - return blockStmt - } - - fun toStatement(tree: StatementTree?): Statement? { - if (tree is ExpressionStatementTree) { - return toExpressionStatement((tree as ExpressionStatementTree?)!!) - } - return if (tree is VariableTree) { - toVariableDeclarationExpression((tree as VariableTree?)!!) - } else StaticJavaParser.parseStatement(tree.toString()) - } - - fun toExpressionStatement(tree: ExpressionStatementTree): ExpressionStmt { - val expressionStmt = ExpressionStmt() - expressionStmt.expression = toExpression(tree.expression) - return expressionStmt - } - - fun toExpression(tree: ExpressionTree?): Expression? { - if (tree is MethodInvocationTree) { - return toMethodCallExpression((tree as MethodInvocationTree?)!!) - } - if (tree is MemberSelectTree) { - return toFieldAccessExpression((tree as MemberSelectTree?)!!) - } - if (tree is IdentifierTree) { - return toNameExpr((tree as IdentifierTree?)!!) - } - if (tree is LiteralTree) { - return toLiteralExpression((tree as LiteralTree?)!!) - } - if (tree is AssignmentTree) { - return toAssignExpression((tree as AssignmentTree?)!!) - } - if (tree is ErroneousTree) { - val erroneousTree = tree as ErroneousTree? - if (erroneousTree!!.errorTrees.isNotEmpty()) { - val errorTree = erroneousTree.errorTrees[0] - return toExpression(errorTree as ExpressionTree) - } - } - return null - } - - private fun toAssignExpression(tree: AssignmentTree): AssignExpr { - val assignExpr = AssignExpr() - assignExpr.target = toExpression(tree.variable) - assignExpr.value = toExpression(tree.expression) - return assignExpr - } - - fun toVariableDeclarationExpression(tree: VariableTree): ExpressionStmt { - val expr = VariableDeclarationExpr() - expr.modifiers = - tree.modifiers.flags.stream().map { toModifier(it) }.collect(NodeList.toNodeList()) - val declarator = VariableDeclarator() - declarator.setName(tree.name.toString()) - declarator.setInitializer(toExpression(tree.initializer)) - declarator.type = toType(tree.type) - expr.addVariable(declarator) - val stmt = ExpressionStmt() - stmt.expression = expr - return stmt - } - - fun toNameExpr(tree: IdentifierTree): NameExpr { - val nameExpr = NameExpr() - nameExpr.setName(tree.name.toString()) - return nameExpr - } - - fun toLiteralExpression(tree: LiteralTree): LiteralExpr? { - val value = tree.value - if (value is String) { - return StringLiteralExpr(value) - } - if (value is Boolean) { - return BooleanLiteralExpr(value) - } - if (value is Int) { - return IntegerLiteralExpr(value.toString()) - } - if (value is Char) { - return CharLiteralExpr(value) - } - if (value is Long) { - return LongLiteralExpr(value.toString()) - } - return if (value is Double) { - DoubleLiteralExpr(value) - } else null - } - - fun toMethodCallExpression(tree: MethodInvocationTree): MethodCallExpr { - val expr = MethodCallExpr() - if (tree.methodSelect is MemberSelectTree) { - val methodSelect = tree.methodSelect as MemberSelectTree - expr.setScope(toExpression(methodSelect.expression)) - expr.setName(methodSelect.identifier.toString()) - } - expr.arguments = tree.arguments.stream().map { toExpression(it) }.collect(NodeList.toNodeList()) - expr.setTypeArguments( - tree.typeArguments.stream().map { toType(it) }.collect(NodeList.toNodeList()) - ) - if (tree.methodSelect is IdentifierTree) { - expr.name = toNameExpr((tree.methodSelect as IdentifierTree)).name - } - return expr - } - - fun toFieldAccessExpression(tree: MemberSelectTree): FieldAccessExpr { - val fieldAccessExpr = FieldAccessExpr() - fieldAccessExpr.setName(tree.identifier.toString()) - fieldAccessExpr.scope = toExpression(tree.expression) - return fieldAccessExpr - } - - fun toClassOrInterfaceDeclaration(tree: ClassTree): ClassOrInterfaceDeclaration { - val declaration = ClassOrInterfaceDeclaration() - declaration.setName(tree.simpleName.toString()) - declaration.extendedTypes = - NodeList.nodeList(TypeUtils.toClassOrInterfaceType(tree.extendsClause)) - declaration.typeParameters = - tree.typeParameters.stream().map { toTypeParameter(it) }.collect(NodeList.toNodeList()) - declaration.typeParameters = - tree.typeParameters.stream().map { toTypeParameter(it) }.collect(NodeList.toNodeList()) - declaration.implementedTypes = - tree.implementsClause - .stream() - .map { TypeUtils.toClassOrInterfaceType(it) } - .collect(NodeList.toNodeList()) - declaration.modifiers = - tree.modifiers.flags.stream().map { toModifier(it) }.collect(NodeList.toNodeList()) - declaration.members = - tree.members.stream().map { toBodyDeclaration(it) }.collect(NodeList.toNodeList()) - return declaration - } - - fun toBodyDeclaration(tree: Tree?): BodyDeclaration<*>? { - if (tree is MethodTree) { - return toMethodDeclaration((tree as MethodTree?)!!, null) - } - return if (tree is VariableTree) { - toFieldDeclaration((tree as VariableTree?)!!) - } else null - } - - fun toFieldDeclaration(tree: VariableTree): FieldDeclaration { - val declaration = FieldDeclaration() - declaration.modifiers = - tree.modifiers.flags.stream().map { toModifier(it) }.collect(NodeList.toNodeList()) - val declarator = VariableDeclarator() - declarator.setName(tree.name.toString()) - val initializer = toExpression(tree.initializer) - if (initializer != null) { - declarator.setInitializer(initializer) - } - val type = toType(tree.type) - if (type != null) { - declarator.type = type - } - declaration.addVariable(declarator) - return declaration - } - - fun toMethodDeclaration(method: MethodTree, type: ExecutableType?): MethodDeclaration { - val methodDeclaration = MethodDeclaration() - methodDeclaration.annotations = - method.modifiers.annotations.stream().map { toAnnotation(it) }.collect(NodeList.toNodeList()) - methodDeclaration.setName(method.name.toString()) - val returnType = - if (type != null) { - toType(type.returnType) - } else { - toType(method.returnType) - } - if (returnType != null) { - methodDeclaration.type = getTypeWithoutBounds(returnType) - } - methodDeclaration.modifiers = - method.modifiers.flags.stream().map { toModifier(it) }.collect(NodeList.toNodeList()) - methodDeclaration.parameters = - method.parameters - .map { variable -> - return@map toParameter(variable).also { param -> - val firstType = getTypeWithoutBounds(param.type) - param.type = firstType - } - } - .toNodeList() - methodDeclaration.typeParameters = - method.typeParameters - .mapNotNull { - return@mapNotNull toType(it as Tree?)?.toTypeParameter()?.getOrNull() - } - .toNodeList() - if (method.body != null) { - methodDeclaration.setBody(toBlockStatement(method.body)) - } - if (method.receiverParameter != null) { - methodDeclaration.setReceiverParameter(toReceiverParameter(method.receiverParameter)) - } - return methodDeclaration - } - - fun toAnnotation(tree: AnnotationTree): AnnotationExpr { - if (tree.arguments.isEmpty()) { - val expr = MarkerAnnotationExpr() - expr.setName(toType(tree.annotationType).toString()) - return expr - } - if (tree.arguments.size == 1) { - val expr = SingleMemberAnnotationExpr() - expr.setName(toType(tree.annotationType).toString()) - expr.memberValue = toExpression(tree.arguments[0]) - return expr - } - val expr = NormalAnnotationExpr() - expr.setName(toType(tree.annotationType).toString()) - expr.pairs = - tree.arguments - .map { - return@map if (it is AssignmentTree) { - val assignExpr = toAssignExpression((it as AssignmentTree?)!!) - val pair = MemberValuePair() - pair.setName(assignExpr.target.toString()) - pair.value = assignExpr.value - pair - } else null - } - .toNodeList() - return expr - } - - fun toParameter(tree: VariableTree): Parameter { - val parameter = Parameter() - parameter.type = toType(tree.type) - tree.modifiers.flags.map { toModifier(it) }.toNodeList().also { parameter.modifiers = it } - parameter.setName(tree.name.toString()) - return parameter - } - - /** - * Convert a parameter into [Parameter] object. This method is called from source files, giving - * their accurate names. - */ - fun toParameter(type: TypeMirror?, name: VariableTree): Parameter { - val parameter = Parameter() - parameter.setType(EditHelper.printType(type)) - parameter.setName(name.name.toString()) - parameter.modifiers = name.modifiers.flags.map { toModifier(it) }.toNodeList() - parameter.setName(name.name.toString()) - return parameter - } - - fun toTypeParameter(type: TypeParameterTree): TypeParameter? { - return StaticJavaParser.parseTypeParameter(type.toString()) - } - - fun toReceiverParameter(parameter: VariableTree): ReceiverParameter { - val receiverParameter = ReceiverParameter() - receiverParameter.setName(parameter.name.toString()) - receiverParameter.type = toType(parameter.type) - return receiverParameter - } - - fun toMethodDeclaration(method: ExecutableElement?, type: ExecutableType?): MethodDeclaration { - val methodDeclaration = MethodDeclaration() - val returnType = - if (type != null) { - toType(type.returnType) - } else { - toType(method!!.returnType) - } - if (returnType != null) { - methodDeclaration.type = getTypeWithoutBounds(returnType) - } - methodDeclaration.isDefault = method!!.isDefault - methodDeclaration.setName(method.simpleName.toString()) - methodDeclaration.setModifiers( - *method.modifiers - .stream() - .map { com.github.javaparser.ast.Modifier.Keyword.valueOf(it!!.name) } - .asArray() - ) - methodDeclaration.parameters = - IntStream.range(0, method.parameters.size) - .mapToObj { - return@mapToObj toParameter(type!!.parameterTypes[it], - method.parameters[it]).also { parameter -> - val firstType = getTypeWithoutBounds(parameter.type) - parameter.type = firstType - } - } - .collect(NodeList.toNodeList()) - methodDeclaration.typeParameters = - type!! - .typeVariables - .mapNotNull { toType(it as TypeMirror?)?.toTypeParameter()?.getOrNull() } - .toNodeList() - return methodDeclaration - } - - fun getFirstArrayType(type: Type): Type { - if (type.isTypeParameter) { - val typeParameter = type.asTypeParameter() - if (typeParameter!!.typeBound.isNonEmpty) { - val first = typeParameter.typeBound.first - if (first!!.isPresent) { - return ArrayType(first.get()) - } - } - } - return type - } - - fun getFirstType(type: Type): Type { - if (type.isTypeParameter) { - val typeParameter = type.asTypeParameter() - if (typeParameter!!.typeBound.isNonEmpty) { - val first = typeParameter.typeBound.first - if (first!!.isPresent) { - return first.get() - } - } - } - if (!type.isClassOrInterfaceType) { - return type - } - - val typeArguments = type.asClassOrInterfaceType().typeArguments - if (!typeArguments!!.isPresent || !typeArguments.get().isNonEmpty) { - return type - } - - val first = typeArguments.get().first - if (!first!!.isPresent || !first.get().isTypeParameter) { - return type - } - - val typeBound = first.get().asTypeParameter().typeBound - if (!typeBound!!.isNonEmpty) { - return type - } - - val first1 = typeBound.first - if (!first1!!.isPresent) { - return type - } - - type.asClassOrInterfaceType().setTypeArguments(first1.get()) - return type - } - - fun getTypeWithoutBounds(type: Type): Type { - if (type.isArrayType && !type.asArrayType().componentType.isTypeParameter) { - return type - } - if (!type.isArrayType && !type.isTypeParameter) { - return type - } - if (type is NodeWithSimpleName<*>) { - return StaticJavaParser.parseClassOrInterfaceType( - (type as NodeWithSimpleName<*>).nameAsString - ) - } - return if (type.isArrayType) { - ArrayType(getTypeWithoutBounds(type.asArrayType().componentType)) - } else type - } - - @Contract("_ -> new") - fun toModifier(modifier: Modifier): com.github.javaparser.ast.Modifier { - return com.github.javaparser.ast.Modifier( - com.github.javaparser.ast.Modifier.Keyword.valueOf(modifier.name) - ) - } - - /** - * Convert a parameter into [Parameter] object. This method is called from compiled class files, - * giving inaccurate parameter names - */ - fun toParameter(type: TypeMirror?, name: VariableElement?): Parameter { - val parameter = Parameter() - parameter.setType(EditHelper.printType(type)) - if (parameter.type.isArrayType) { - if ((type as openjdk.tools.javac.code.Type.ArrayType?)!!.isVarargs) { - parameter.type = parameter.type.asArrayType().componentType - parameter.isVarArgs = true - } - } - parameter.setName(name!!.simpleName.toString()) - parameter.modifiers = name.modifiers.map { toModifier(it) }.toNodeList() - parameter.setName(name.simpleName.toString()) - return parameter - } - - fun toTypeParameter(type: TypeParameterElement): TypeParameter? { - return StaticJavaParser.parseTypeParameter(type.toString()) - } - - fun toTypeParameter(typeVariable: TypeVariable): TypeParameter? { - return StaticJavaParser.parseTypeParameter(typeVariable.toString()) - } - - fun getClassNames(type: Type): MutableList { - val classNames: MutableList = ArrayList() - if (type.isClassOrInterfaceType) { - classNames.add(type.asClassOrInterfaceType().name.asString()) - } - if (type.isWildcardType) { - val wildcardType = type.asWildcardType() - wildcardType!!.extendedType.ifPresent { t: ReferenceType? -> - classNames.addAll(getClassNames(t!!)) - } - wildcardType.superType.ifPresent { t: ReferenceType? -> - classNames.addAll(getClassNames(t!!)) - } - } - if (type.isArrayType) { - classNames.addAll(getClassNames(type.asArrayType().componentType)) - } - if (type.isIntersectionType) { - type - .asIntersectionType() - .elements - .stream() - .map { getClassNames(it) } - .forEach { c: MutableList? -> classNames.addAll(c!!) } - } - return classNames - } - - /** - * Print a node declaration into its string representation - * - * @param node node to print - * @param delegate callback to whether a class name should be printed as fully qualified names - * @return String representation of the method declaration properly formatted - */ - fun prettyPrint(node: Node?, delegate: Predicate?): String? { - val configuration: PrinterConfiguration = DefaultPrinterConfiguration() - val visitor: PrettyPrintingVisitor = - object : PrettyPrintingVisitor(configuration) { - override fun visit(n: SimpleName?, arg: Void?) { - printOrphanCommentsBeforeThisChildNode(n) - printComment(n!!.comment, arg) - val identifier = n.identifier - if (delegate!!.test(identifier)) { - printer.print(identifier) - } else { - printer.print(getSimpleName(identifier)) - } - } - - override fun visit(n: Name?, arg: Void?) { - super.visit(n, arg) - } - } - val prettyPrinter = DefaultPrettyPrinter({ visitor }, configuration) - return prettyPrinter.print(node) - } - - @JvmStatic - fun getSimpleName(className: String?): String { - var name = className - name = removeDiamond(name!!) - val dot = name.lastIndexOf('.') - if (dot == -1) { - return name - } - return if (name.startsWith("? extends")) { - "? extends " + name.substring(dot + 1) - } else name.substring(dot + 1) - } - - fun removeDiamond(className: String): String { - var name = className - if (name.contains("<")) { - name = name.substring(0, name.indexOf('<')) - } - return name - } - - fun removeArray(className: String): String { - var name = className - if (name.contains("[")) { - name = name.substring(0, name.indexOf('[')) - } - return name - } -} - -private fun Collection.toNodeList(): NodeList { - return NodeList(this) -} - -private inline fun Stream.asArray(): Array { - val arr = mutableListOf() - for (element in this) { - arr.add(element) - } - - return arr.toTypedArray() -} +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ +@file:Suppress("unused", "MemberVisibilityCanBePrivate") + +package com.itsaky.androidide.lsp.java.utils + +import androidx.annotation.NonNull +import androidx.annotation.Nullable +import com.github.javaparser.StaticJavaParser +import com.github.javaparser.ast.CompilationUnit +import com.github.javaparser.ast.ImportDeclaration +import com.github.javaparser.ast.Node +import com.github.javaparser.ast.NodeList +import com.github.javaparser.ast.PackageDeclaration +import com.github.javaparser.ast.body.BodyDeclaration +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration +import com.github.javaparser.ast.body.FieldDeclaration +import com.github.javaparser.ast.body.MethodDeclaration +import com.github.javaparser.ast.body.Parameter +import com.github.javaparser.ast.body.ReceiverParameter +import com.github.javaparser.ast.body.VariableDeclarator +import com.github.javaparser.ast.expr.AnnotationExpr +import com.github.javaparser.ast.expr.AssignExpr +import com.github.javaparser.ast.expr.BooleanLiteralExpr +import com.github.javaparser.ast.expr.CharLiteralExpr +import com.github.javaparser.ast.expr.DoubleLiteralExpr +import com.github.javaparser.ast.expr.Expression +import com.github.javaparser.ast.expr.FieldAccessExpr +import com.github.javaparser.ast.expr.IntegerLiteralExpr +import com.github.javaparser.ast.expr.LiteralExpr +import com.github.javaparser.ast.expr.LongLiteralExpr +import com.github.javaparser.ast.expr.MarkerAnnotationExpr +import com.github.javaparser.ast.expr.MemberValuePair +import com.github.javaparser.ast.expr.MethodCallExpr +import com.github.javaparser.ast.expr.Name +import com.github.javaparser.ast.expr.NameExpr +import com.github.javaparser.ast.expr.NormalAnnotationExpr +import com.github.javaparser.ast.expr.NullLiteralExpr +import com.github.javaparser.ast.expr.SimpleName +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr +import com.github.javaparser.ast.expr.StringLiteralExpr +import com.github.javaparser.ast.expr.SuperExpr +import com.github.javaparser.ast.expr.VariableDeclarationExpr +import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName +import com.github.javaparser.ast.stmt.BlockStmt +import com.github.javaparser.ast.stmt.ExpressionStmt +import com.github.javaparser.ast.stmt.ReturnStmt +import com.github.javaparser.ast.stmt.Statement +import com.github.javaparser.ast.type.ArrayType +import com.github.javaparser.ast.type.PrimitiveType +import com.github.javaparser.ast.type.PrimitiveType.Primitive.BOOLEAN +import com.github.javaparser.ast.type.PrimitiveType.Primitive.BYTE +import com.github.javaparser.ast.type.PrimitiveType.Primitive.CHAR +import com.github.javaparser.ast.type.PrimitiveType.Primitive.DOUBLE +import com.github.javaparser.ast.type.PrimitiveType.Primitive.FLOAT +import com.github.javaparser.ast.type.PrimitiveType.Primitive.INT +import com.github.javaparser.ast.type.PrimitiveType.Primitive.LONG +import com.github.javaparser.ast.type.PrimitiveType.Primitive.SHORT +import com.github.javaparser.ast.type.ReferenceType +import com.github.javaparser.ast.type.Type +import com.github.javaparser.ast.type.TypeParameter +import com.github.javaparser.printer.DefaultPrettyPrinter +import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration +import com.github.javaparser.printer.configuration.PrinterConfiguration +import com.itsaky.androidide.lsp.java.utils.TypeUtils.toType +import com.itsaky.androidide.lsp.java.visitors.PrettyPrintingVisitor +import jdkx.lang.model.element.ExecutableElement +import jdkx.lang.model.element.Modifier +import jdkx.lang.model.element.TypeParameterElement +import jdkx.lang.model.element.VariableElement +import jdkx.lang.model.type.ExecutableType +import jdkx.lang.model.type.TypeKind +import jdkx.lang.model.type.TypeMirror +import jdkx.lang.model.type.TypeVariable +import openjdk.source.tree.AnnotationTree +import openjdk.source.tree.AssignmentTree +import openjdk.source.tree.BlockTree +import openjdk.source.tree.ClassTree +import openjdk.source.tree.CompilationUnitTree +import openjdk.source.tree.ErroneousTree +import openjdk.source.tree.ExpressionStatementTree +import openjdk.source.tree.ExpressionTree +import openjdk.source.tree.IdentifierTree +import openjdk.source.tree.ImportTree +import openjdk.source.tree.LiteralTree +import openjdk.source.tree.MemberSelectTree +import openjdk.source.tree.MethodInvocationTree +import openjdk.source.tree.MethodTree +import openjdk.source.tree.PackageTree +import openjdk.source.tree.StatementTree +import openjdk.source.tree.Tree +import openjdk.source.tree.TypeParameterTree +import openjdk.source.tree.VariableTree +import org.jetbrains.annotations.Contract +import java.util.function.Predicate +import java.util.stream.IntStream +import java.util.stream.Stream +import kotlin.jvm.optionals.getOrNull + +object JavaParserUtils { + /** + * Collects all the type names from the given node. + * + * @param type The method to get types from. + * @return A set of fully qualified names of the types in the given node. + */ + fun collectImports(type: ExecutableType): MutableSet { + val types = mutableSetOf() + val returnType = type.returnType + if (returnType != null) { + if ( + returnType.kind != TypeKind.VOID && + returnType.kind != TypeKind.TYPEVAR && + !returnType.kind.isPrimitive + ) { + val fqn = getTypeToImport(returnType) + if (fqn != null) { + types.add(fqn) + } + } + } + if (type.thrownTypes != null) { + for (thrown in type.thrownTypes) { + val fqn = getTypeToImport(thrown) + if (fqn != null) { + types.add(fqn) + } + } + } + for (t in type.parameterTypes) { + if (t.kind.isPrimitive) { + continue + } + val fqn = getTypeToImport(t) + if (fqn != null) { + types.add(fqn) + } + } + return types + } + + @Nullable + private fun getTypeToImport(type: TypeMirror): String? { + if (type.kind.isPrimitive) { + return null + } + if (type.kind == TypeKind.TYPEVAR) { + return null + } + var fqn = toType(type).toString() + if (type.kind == TypeKind.ARRAY) { + fqn = removeArray(fqn) + } + + return removeDiamond(fqn) + } + + fun printMethod( + method: ExecutableElement, + parameterizedType: ExecutableType?, + source: MethodTree, + ): MethodDeclaration { + val methodDeclaration: MethodDeclaration = toMethodDeclaration(source, parameterizedType) + printMethodInternal(methodDeclaration, method) + return methodDeclaration + } + + fun printMethod( + method: ExecutableElement?, + parameterizedType: ExecutableType?, + source: ExecutableElement, + ): MethodDeclaration { + val methodDeclaration: MethodDeclaration = toMethodDeclaration(method, parameterizedType) + printMethodInternal(methodDeclaration, source) + return methodDeclaration + } + + private fun printMethodInternal( + methodDeclaration: MethodDeclaration, + method: ExecutableElement, + ) { + methodDeclaration.addMarkerAnnotation(Override::class.java) + val recentlyNonNull = methodDeclaration.getAnnotationByName("RecentlyNonNull") + if (recentlyNonNull.isPresent) { + methodDeclaration.remove(recentlyNonNull.get()) + methodDeclaration.addMarkerAnnotation(NonNull::class.java) + } + + val blockStmt = BlockStmt() + if (method.modifiers.contains(Modifier.ABSTRACT)) { + methodDeclaration.removeModifier(com.github.javaparser.ast.Modifier.Keyword.ABSTRACT) + if (methodDeclaration.type.isClassOrInterfaceType) { + blockStmt.addStatement(ReturnStmt(NullLiteralExpr())) + } + if (methodDeclaration.type.isPrimitiveType) { + val type = methodDeclaration.type.asPrimitiveType() + blockStmt.addStatement(ReturnStmt(getReturnExpr(type))) + } + } else { + val methodCallExpr = MethodCallExpr() + methodCallExpr.name = methodDeclaration.name + methodCallExpr.arguments = + methodDeclaration.parameters + .stream() + .map { obj: Parameter -> obj.nameAsExpression } + .collect(NodeList.toNodeList()) + methodCallExpr.setScope(SuperExpr()) + if (methodDeclaration.type.isVoidType) { + blockStmt.addStatement(methodCallExpr) + } else { + blockStmt.addStatement(ReturnStmt(methodCallExpr)) + } + } + methodDeclaration.setBody(blockStmt) + } + + private fun getReturnExpr(type: PrimitiveType): Expression = + when (type.type) { + BOOLEAN -> BooleanLiteralExpr() + + BYTE, + DOUBLE, + CHAR, + SHORT, + LONG, + FLOAT, + INT, + -> IntegerLiteralExpr("0") + + else -> NullLiteralExpr() + } + + @Suppress("Since15") + fun toCompilationUnit(tree: CompilationUnitTree): CompilationUnit { + val compilationUnit = CompilationUnit() + compilationUnit.setPackageDeclaration(toPackageDeclaration(tree.getPackage())) + tree.imports.forEach { importTree: ImportTree? -> + compilationUnit.addImport(toImportDeclaration(importTree!!)) + } + compilationUnit.types = + tree.typeDecls + .stream() + .map { toClassOrInterfaceDeclaration(it) } + .collect(NodeList.toNodeList()) + return compilationUnit + } + + @Suppress("Since15") + fun toPackageDeclaration(tree: PackageTree): PackageDeclaration { + val declaration = PackageDeclaration() + declaration.setName(tree.packageName.toString()) + return declaration + } + + fun toImportDeclaration(tree: ImportTree): ImportDeclaration { + val name = tree.qualifiedIdentifier.toString() + val isAsterisk = name.endsWith("*") + return ImportDeclaration(name, tree.isStatic, isAsterisk) + } + + fun toClassOrInterfaceDeclaration(tree: Tree?): ClassOrInterfaceDeclaration? = + if (tree is ClassTree) { + toClassOrInterfaceDeclaration(tree as ClassTree?) + } else { + null + } + + fun toBlockStatement(tree: BlockTree): BlockStmt { + val blockStmt = BlockStmt() + blockStmt.statements = + tree.statements + .stream() + .map { toStatement(it) } + .collect(NodeList.toNodeList()) + return blockStmt + } + + fun toStatement(tree: StatementTree?): Statement? { + if (tree is ExpressionStatementTree) { + return toExpressionStatement((tree as ExpressionStatementTree?)!!) + } + return if (tree is VariableTree) { + toVariableDeclarationExpression((tree as VariableTree?)!!) + } else { + StaticJavaParser.parseStatement(tree.toString()) + } + } + + fun toExpressionStatement(tree: ExpressionStatementTree): ExpressionStmt { + val expressionStmt = ExpressionStmt() + expressionStmt.expression = toExpression(tree.expression) + return expressionStmt + } + + fun toExpression(tree: ExpressionTree?): Expression? { + if (tree is MethodInvocationTree) { + return toMethodCallExpression((tree as MethodInvocationTree?)!!) + } + if (tree is MemberSelectTree) { + return toFieldAccessExpression((tree as MemberSelectTree?)!!) + } + if (tree is IdentifierTree) { + return toNameExpr((tree as IdentifierTree?)!!) + } + if (tree is LiteralTree) { + return toLiteralExpression((tree as LiteralTree?)!!) + } + if (tree is AssignmentTree) { + return toAssignExpression((tree as AssignmentTree?)!!) + } + if (tree is ErroneousTree) { + val erroneousTree = tree as ErroneousTree? + if (erroneousTree!!.errorTrees.isNotEmpty()) { + val errorTree = erroneousTree.errorTrees[0] + return toExpression(errorTree as ExpressionTree) + } + } + return null + } + + private fun toAssignExpression(tree: AssignmentTree): AssignExpr { + val assignExpr = AssignExpr() + assignExpr.target = toExpression(tree.variable) + assignExpr.value = toExpression(tree.expression) + return assignExpr + } + + fun toVariableDeclarationExpression(tree: VariableTree): ExpressionStmt { + val expr = VariableDeclarationExpr() + expr.modifiers = + tree.modifiers.flags + .stream() + .map { toModifier(it) } + .collect(NodeList.toNodeList()) + val declarator = VariableDeclarator() + declarator.setName(tree.name.toString()) + declarator.setInitializer(toExpression(tree.initializer)) + declarator.type = toType(tree.type) + expr.addVariable(declarator) + val stmt = ExpressionStmt() + stmt.expression = expr + return stmt + } + + fun toNameExpr(tree: IdentifierTree): NameExpr { + val nameExpr = NameExpr() + nameExpr.setName(tree.name.toString()) + return nameExpr + } + + fun toLiteralExpression(tree: LiteralTree): LiteralExpr? { + val value = tree.value + if (value is String) { + return StringLiteralExpr(value) + } + if (value is Boolean) { + return BooleanLiteralExpr(value) + } + if (value is Int) { + return IntegerLiteralExpr(value.toString()) + } + if (value is Char) { + return CharLiteralExpr(value) + } + if (value is Long) { + return LongLiteralExpr(value.toString()) + } + return if (value is Double) { + DoubleLiteralExpr(value) + } else { + null + } + } + + fun toMethodCallExpression(tree: MethodInvocationTree): MethodCallExpr { + val expr = MethodCallExpr() + if (tree.methodSelect is MemberSelectTree) { + val methodSelect = tree.methodSelect as MemberSelectTree + expr.setScope(toExpression(methodSelect.expression)) + expr.setName(methodSelect.identifier.toString()) + } + expr.arguments = + tree.arguments + .stream() + .map { toExpression(it) } + .collect(NodeList.toNodeList()) + expr.setTypeArguments( + tree.typeArguments + .stream() + .map { toType(it) } + .collect(NodeList.toNodeList()), + ) + if (tree.methodSelect is IdentifierTree) { + expr.name = toNameExpr((tree.methodSelect as IdentifierTree)).name + } + return expr + } + + fun toFieldAccessExpression(tree: MemberSelectTree): FieldAccessExpr { + val fieldAccessExpr = FieldAccessExpr() + fieldAccessExpr.setName(tree.identifier.toString()) + fieldAccessExpr.scope = toExpression(tree.expression) + return fieldAccessExpr + } + + fun toClassOrInterfaceDeclaration(tree: ClassTree): ClassOrInterfaceDeclaration { + val declaration = ClassOrInterfaceDeclaration() + declaration.setName(tree.simpleName.toString()) + declaration.extendedTypes = + NodeList.nodeList(TypeUtils.toClassOrInterfaceType(tree.extendsClause)) + declaration.typeParameters = + tree.typeParameters + .stream() + .map { toTypeParameter(it) } + .collect(NodeList.toNodeList()) + declaration.typeParameters = + tree.typeParameters + .stream() + .map { toTypeParameter(it) } + .collect(NodeList.toNodeList()) + declaration.implementedTypes = + tree.implementsClause + .stream() + .map { TypeUtils.toClassOrInterfaceType(it) } + .collect(NodeList.toNodeList()) + declaration.modifiers = + tree.modifiers.flags + .stream() + .map { toModifier(it) } + .collect(NodeList.toNodeList()) + declaration.members = + tree.members + .stream() + .map { toBodyDeclaration(it) } + .collect(NodeList.toNodeList()) + return declaration + } + + fun toBodyDeclaration(tree: Tree?): BodyDeclaration<*>? { + if (tree is MethodTree) { + return toMethodDeclaration((tree as MethodTree?)!!, null) + } + return if (tree is VariableTree) { + toFieldDeclaration((tree as VariableTree?)!!) + } else { + null + } + } + + fun toFieldDeclaration(tree: VariableTree): FieldDeclaration { + val declaration = FieldDeclaration() + declaration.modifiers = + tree.modifiers.flags + .stream() + .map { toModifier(it) } + .collect(NodeList.toNodeList()) + val declarator = VariableDeclarator() + declarator.setName(tree.name.toString()) + val initializer = toExpression(tree.initializer) + if (initializer != null) { + declarator.setInitializer(initializer) + } + val type = toType(tree.type) + if (type != null) { + declarator.type = type + } + declaration.addVariable(declarator) + return declaration + } + + fun toMethodDeclaration( + method: MethodTree, + type: ExecutableType?, + ): MethodDeclaration { + val methodDeclaration = MethodDeclaration() + methodDeclaration.annotations = + method.modifiers.annotations + .stream() + .map { toAnnotation(it) } + .collect(NodeList.toNodeList()) + methodDeclaration.setName(method.name.toString()) + val returnType = + if (type != null) { + toType(type.returnType) + } else { + toType(method.returnType) + } + if (returnType != null) { + methodDeclaration.type = getTypeWithoutBounds(returnType) + } + methodDeclaration.modifiers = + method.modifiers.flags + .stream() + .map { toModifier(it) } + .collect(NodeList.toNodeList()) + methodDeclaration.parameters = + method.parameters + .map { variable -> + return@map toParameter(variable).also { param -> + val firstType = getTypeWithoutBounds(param.type) + param.type = firstType + } + }.toNodeList() + methodDeclaration.typeParameters = + method.typeParameters + .mapNotNull { + return@mapNotNull toType(it as Tree?)?.toTypeParameter()?.getOrNull() + }.toNodeList() + if (method.body != null) { + methodDeclaration.setBody(toBlockStatement(method.body)) + } + if (method.receiverParameter != null) { + methodDeclaration.setReceiverParameter(toReceiverParameter(method.receiverParameter)) + } + return methodDeclaration + } + + fun toAnnotation(tree: AnnotationTree): AnnotationExpr { + if (tree.arguments.isEmpty()) { + val expr = MarkerAnnotationExpr() + expr.setName(toType(tree.annotationType).toString()) + return expr + } + if (tree.arguments.size == 1) { + val expr = SingleMemberAnnotationExpr() + expr.setName(toType(tree.annotationType).toString()) + expr.memberValue = toExpression(tree.arguments[0]) + return expr + } + val expr = NormalAnnotationExpr() + expr.setName(toType(tree.annotationType).toString()) + expr.pairs = + tree.arguments + .map { + return@map if (it is AssignmentTree) { + val assignExpr = toAssignExpression((it as AssignmentTree?)!!) + val pair = MemberValuePair() + pair.setName(assignExpr.target.toString()) + pair.value = assignExpr.value + pair + } else { + null + } + }.toNodeList() + return expr + } + + fun toParameter(tree: VariableTree): Parameter { + val parameter = Parameter() + parameter.type = toType(tree.type) + tree.modifiers.flags + .map { toModifier(it) } + .toNodeList() + .also { parameter.modifiers = it } + parameter.setName(tree.name.toString()) + return parameter + } + + /** + * Convert a parameter into [Parameter] object. This method is called from source files, giving + * their accurate names. + */ + fun toParameter( + type: TypeMirror?, + name: VariableTree, + ): Parameter { + val parameter = Parameter() + parameter.setType(EditHelper.printType(type)) + parameter.setName(name.name.toString()) + parameter.modifiers = + name.modifiers.flags + .map { toModifier(it) } + .toNodeList() + parameter.setName(name.name.toString()) + return parameter + } + + fun toTypeParameter(type: TypeParameterTree): TypeParameter? = StaticJavaParser.parseTypeParameter(type.toString()) + + fun toReceiverParameter(parameter: VariableTree): ReceiverParameter { + val receiverParameter = ReceiverParameter() + receiverParameter.setName(parameter.name.toString()) + receiverParameter.type = toType(parameter.type) + return receiverParameter + } + + fun toMethodDeclaration( + method: ExecutableElement?, + type: ExecutableType?, + ): MethodDeclaration { + val methodDeclaration = MethodDeclaration() + val returnType = + if (type != null) { + toType(type.returnType) + } else { + toType(method!!.returnType) + } + if (returnType != null) { + methodDeclaration.type = getTypeWithoutBounds(returnType) + } + methodDeclaration.isDefault = method!!.isDefault + methodDeclaration.setName(method.simpleName.toString()) + methodDeclaration.setModifiers( + *method.modifiers + .stream() + .map { + com.github.javaparser.ast.Modifier.Keyword + .valueOf(it!!.name) + }.asArray(), + ) + methodDeclaration.parameters = + IntStream + .range(0, method.parameters.size) + .mapToObj { + return@mapToObj toParameter( + type!!.parameterTypes[it], + method.parameters[it], + ).also { parameter -> + val firstType = getTypeWithoutBounds(parameter.type) + parameter.type = firstType + } + }.collect(NodeList.toNodeList()) + methodDeclaration.typeParameters = + type!! + .typeVariables + .mapNotNull { toType(it as TypeMirror?)?.toTypeParameter()?.getOrNull() } + .toNodeList() + return methodDeclaration + } + + fun getFirstArrayType(type: Type): Type { + if (type.isTypeParameter) { + val typeParameter = type.asTypeParameter() + if (typeParameter!!.typeBound.isNonEmpty) { + val first = typeParameter.typeBound.first + if (first!!.isPresent) { + return ArrayType(first.get()) + } + } + } + return type + } + + fun getFirstType(type: Type): Type { + if (type.isTypeParameter) { + val typeParameter = type.asTypeParameter() + if (typeParameter!!.typeBound.isNonEmpty) { + val first = typeParameter.typeBound.first + if (first!!.isPresent) { + return first.get() + } + } + } + if (!type.isClassOrInterfaceType) { + return type + } + + val typeArguments = type.asClassOrInterfaceType().typeArguments + if (!typeArguments!!.isPresent || !typeArguments.get().isNonEmpty) { + return type + } + + val first = typeArguments.get().first + if (!first!!.isPresent || !first.get().isTypeParameter) { + return type + } + + val typeBound = first.get().asTypeParameter().typeBound + if (!typeBound!!.isNonEmpty) { + return type + } + + val first1 = typeBound.first + if (!first1!!.isPresent) { + return type + } + + type.asClassOrInterfaceType().setTypeArguments(first1.get()) + return type + } + + fun getTypeWithoutBounds(type: Type): Type { + if (type.isArrayType && !type.asArrayType().componentType.isTypeParameter) { + return type + } + if (!type.isArrayType && !type.isTypeParameter) { + return type + } + if (type is NodeWithSimpleName<*>) { + return StaticJavaParser.parseClassOrInterfaceType( + (type as NodeWithSimpleName<*>).nameAsString, + ) + } + return if (type.isArrayType) { + ArrayType(getTypeWithoutBounds(type.asArrayType().componentType)) + } else { + type + } + } + + @Contract("_ -> new") + fun toModifier(modifier: Modifier): com.github.javaparser.ast.Modifier = + com.github.javaparser.ast.Modifier( + com.github.javaparser.ast.Modifier.Keyword + .valueOf(modifier.name), + ) + + /** + * Convert a parameter into [Parameter] object. This method is called from compiled class files, + * giving inaccurate parameter names + */ + fun toParameter( + type: TypeMirror?, + name: VariableElement?, + ): Parameter { + val parameter = Parameter() + parameter.setType(EditHelper.printType(type)) + if (parameter.type.isArrayType) { + if ((type as openjdk.tools.javac.code.Type.ArrayType?)!!.isVarargs) { + parameter.type = parameter.type.asArrayType().componentType + parameter.isVarArgs = true + } + } + parameter.setName(name!!.simpleName.toString()) + parameter.modifiers = name.modifiers.map { toModifier(it) }.toNodeList() + parameter.setName(name.simpleName.toString()) + return parameter + } + + fun toTypeParameter(type: TypeParameterElement): TypeParameter? = StaticJavaParser.parseTypeParameter(type.toString()) + + fun toTypeParameter(typeVariable: TypeVariable): TypeParameter? = StaticJavaParser.parseTypeParameter(typeVariable.toString()) + + fun getClassNames(type: Type): MutableList { + val classNames: MutableList = ArrayList() + if (type.isClassOrInterfaceType) { + classNames.add(type.asClassOrInterfaceType().name.asString()) + } + if (type.isWildcardType) { + val wildcardType = type.asWildcardType() + wildcardType!!.extendedType.ifPresent { t: ReferenceType? -> + classNames.addAll(getClassNames(t!!)) + } + wildcardType.superType.ifPresent { t: ReferenceType? -> + classNames.addAll(getClassNames(t!!)) + } + } + if (type.isArrayType) { + classNames.addAll(getClassNames(type.asArrayType().componentType)) + } + if (type.isIntersectionType) { + type + .asIntersectionType() + .elements + .stream() + .map { getClassNames(it) } + .forEach { c: MutableList? -> classNames.addAll(c!!) } + } + return classNames + } + + /** + * Print a node declaration into its string representation + * + * @param node node to print + * @param delegate callback to whether a class name should be printed as fully qualified names + * @return String representation of the method declaration properly formatted + */ + fun prettyPrint( + node: Node?, + delegate: Predicate?, + ): String? { + val configuration: PrinterConfiguration = DefaultPrinterConfiguration() + val visitor: PrettyPrintingVisitor = + object : PrettyPrintingVisitor(configuration) { + override fun visit( + n: SimpleName?, + arg: Void?, + ) { + printOrphanCommentsBeforeThisChildNode(n) + printComment(n!!.comment, arg) + val identifier = n.identifier + if (delegate!!.test(identifier)) { + printer.print(identifier) + } else { + printer.print(getSimpleName(identifier)) + } + } + + override fun visit( + n: Name?, + arg: Void?, + ) { + super.visit(n, arg) + } + } + val prettyPrinter = DefaultPrettyPrinter({ visitor }, configuration) + return prettyPrinter.print(node) + } + + @JvmStatic + fun getSimpleName(className: String?): String { + var name = className + name = removeDiamond(name!!) + val dot = name.lastIndexOf('.') + if (dot == -1) { + return name + } + return if (name.startsWith("? extends")) { + "? extends " + name.substring(dot + 1) + } else { + name.substring(dot + 1) + } + } + + fun removeDiamond(className: String): String { + var name = className + if (name.contains("<")) { + name = name.substring(0, name.indexOf('<')) + } + return name + } + + fun removeArray(className: String): String { + var name = className + if (name.contains("[")) { + name = name.substring(0, name.indexOf('[')) + } + return name + } +} + +private fun Collection.toNodeList(): NodeList = NodeList(this) + +private inline fun Stream.asArray(): Array { + val arr = mutableListOf() + for (element in this) { + arr.add(element) + } + + return arr.toTypedArray() +} diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/visitors/FindCompletionsAt.java b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/visitors/FindCompletionsAt.java index 41deeb3b72..d4691d4d20 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/visitors/FindCompletionsAt.java +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/visitors/FindCompletionsAt.java @@ -33,109 +33,109 @@ public class FindCompletionsAt extends TreePathScanner { - // private static final ILogger LOG = ILogger.newInstance("FindCompletionsAt"); - private final JavacTask task; - private CompilationUnitTree root; - - public FindCompletionsAt(JavacTask task) { - this.task = task; - } - - @Override - public TreePath visitCompilationUnit(CompilationUnitTree t, Long find) { - root = t; - return reduce(super.visitCompilationUnit(t, find), getCurrentPath()); - } - - @Override - public TreePath visitIdentifier(IdentifierTree t, Long find) { - SourcePositions pos = Trees.instance(task).getSourcePositions(); - long start = pos.getStartPosition(root, t); - long end = pos.getEndPosition(root, t); - if (start <= find && find <= end) { - return getCurrentPath(); - } - return super.visitIdentifier(t, find); - } - - @Override - public TreePath visitMemberSelect(MemberSelectTree t, Long find) { - SourcePositions pos = Trees.instance(task).getSourcePositions(); - long start = pos.getEndPosition(root, t.getExpression()) + 1; - long end = pos.getEndPosition(root, t); - if (start <= find && find <= end) { - return getCurrentPath(); - } - return super.visitMemberSelect(t, find); - } - - @Override - public TreePath visitMemberReference(MemberReferenceTree t, Long find) { - SourcePositions pos = Trees.instance(task).getSourcePositions(); - long start = pos.getEndPosition(root, t.getQualifierExpression()) + 2; - long end = pos.getEndPosition(root, t); - if (start <= find && find <= end) { - return getCurrentPath(); - } - return super.visitMemberReference(t, find); - } - - @Override - public TreePath visitCase(CaseTree t, Long find) { - SourcePositions pos = Trees.instance(task).getSourcePositions(); - - // check if the cursor is in the case expression - // default statements have null expression - // In case of an identifier tree, we have to check for both, variables and switch constants - // in - // CompletionProvider - if (t.getExpression() != null && !(t.getExpression() instanceof IdentifierTree)) { - long start = pos.getStartPosition(root, t.getExpression()); - long end = pos.getEndPosition(root, t.getExpression()); - if (start <= find && find <= end) { - return new TreePath(getCurrentPath(), t.getExpression()); - } - } - - long start = pos.getStartPosition(root, t) + "case".length(); - long end = pos.getEndPosition(root, t.getExpression()); - if (start <= find && find <= end) { - return getCurrentPath().getParentPath(); - } - - return super.visitCase(t, find); - } - - @Override - public TreePath visitImport(ImportTree t, Long find) { - SourcePositions pos = Trees.instance(task).getSourcePositions(); - long start = pos.getStartPosition(root, t.getQualifiedIdentifier()); - long end = pos.getEndPosition(root, t.getQualifiedIdentifier()); - if (start <= find && find <= end) { - return getCurrentPath(); - } - return super.visitImport(t, find); - } - - @Override - public TreePath visitErroneous(ErroneousTree t, Long find) { - if (t.getErrorTrees() == null) { - return null; - } - for (Tree e : t.getErrorTrees()) { - TreePath found = scan(e, find); - if (found != null) { - return found; - } - } - return null; - } - - @Override - public TreePath reduce(TreePath a, TreePath b) { - if (a != null) { - return a; - } - return b; - } + // private static final ILogger LOG = ILogger.newInstance("FindCompletionsAt"); + private final JavacTask task; + private CompilationUnitTree root; + + public FindCompletionsAt(JavacTask task) { + this.task = task; + } + + @Override + public TreePath reduce(TreePath a, TreePath b) { + if (a != null) { + return a; + } + return b; + } + + @Override + public TreePath visitCase(CaseTree t, Long find) { + SourcePositions pos = Trees.instance(task).getSourcePositions(); + + // check if the cursor is in the case expression + // default statements have null expression + // In case of an identifier tree, we have to check for both, variables and switch constants + // in + // CompletionProvider + if (t.getExpression() != null && !(t.getExpression() instanceof IdentifierTree)) { + long start = pos.getStartPosition(root, t.getExpression()); + long end = pos.getEndPosition(root, t.getExpression()); + if (start <= find && find <= end) { + return new TreePath(getCurrentPath(), t.getExpression()); + } + } + + long start = pos.getStartPosition(root, t) + "case".length(); + long end = pos.getEndPosition(root, t.getExpression()); + if (start <= find && find <= end) { + return getCurrentPath().getParentPath(); + } + + return super.visitCase(t, find); + } + + @Override + public TreePath visitCompilationUnit(CompilationUnitTree t, Long find) { + root = t; + return reduce(super.visitCompilationUnit(t, find), getCurrentPath()); + } + + @Override + public TreePath visitErroneous(ErroneousTree t, Long find) { + if (t.getErrorTrees() == null) { + return null; + } + for (Tree e : t.getErrorTrees()) { + TreePath found = scan(e, find); + if (found != null) { + return found; + } + } + return null; + } + + @Override + public TreePath visitIdentifier(IdentifierTree t, Long find) { + SourcePositions pos = Trees.instance(task).getSourcePositions(); + long start = pos.getStartPosition(root, t); + long end = pos.getEndPosition(root, t); + if (start <= find && find <= end) { + return getCurrentPath(); + } + return super.visitIdentifier(t, find); + } + + @Override + public TreePath visitImport(ImportTree t, Long find) { + SourcePositions pos = Trees.instance(task).getSourcePositions(); + long start = pos.getStartPosition(root, t.getQualifiedIdentifier()); + long end = pos.getEndPosition(root, t.getQualifiedIdentifier()); + if (start <= find && find <= end) { + return getCurrentPath(); + } + return super.visitImport(t, find); + } + + @Override + public TreePath visitMemberReference(MemberReferenceTree t, Long find) { + SourcePositions pos = Trees.instance(task).getSourcePositions(); + long start = pos.getEndPosition(root, t.getQualifierExpression()) + 2; + long end = pos.getEndPosition(root, t); + if (start <= find && find <= end) { + return getCurrentPath(); + } + return super.visitMemberReference(t, find); + } + + @Override + public TreePath visitMemberSelect(MemberSelectTree t, Long find) { + SourcePositions pos = Trees.instance(task).getSourcePositions(); + long start = pos.getEndPosition(root, t.getExpression()) + 1; + long end = pos.getEndPosition(root, t); + if (start <= find && find <= end) { + return getCurrentPath(); + } + return super.visitMemberSelect(t, find); + } } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt index bc88cd8739..965f462451 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt @@ -31,127 +31,162 @@ import java.util.function.Consumer * analysis thread or deadlock against the project read/write lock. */ internal class NoOpAsyncExecutionService : AsyncExecutionService() { + private val executor: AppUIExecutor = NoOpAppUIExecutor() - private val executor: AppUIExecutor = NoOpAppUIExecutor() + override fun createExecutor(backgroundExecutor: Executor): ExpirableExecutor = NoOpExpirableExecutor(backgroundExecutor) - override fun createExecutor(backgroundExecutor: Executor): ExpirableExecutor = - NoOpExpirableExecutor(backgroundExecutor) + override fun createUIExecutor(modalityState: ModalityState): AppUIExecutor = executor - override fun createUIExecutor(modalityState: ModalityState): AppUIExecutor = executor + override fun createWriteThreadExecutor(modalityState: ModalityState): AppUIExecutor = executor - override fun createWriteThreadExecutor(modalityState: ModalityState): AppUIExecutor = executor - - override fun buildNonBlockingReadAction(callable: Callable): NonBlockingReadAction = - NoOpNonBlockingReadAction(callable) + override fun buildNonBlockingReadAction(callable: Callable): NonBlockingReadAction = NoOpNonBlockingReadAction(callable) } private class NoOpAppUIExecutor : AppUIExecutor { - override fun later(): AppUIExecutor = this - override fun withDocumentsCommitted(project: Project): AppUIExecutor = this - override fun inSmartMode(project: Project): AppUIExecutor = this - override fun expireWith(disposable: Disposable): AppUIExecutor = this - - override fun execute(runnable: Runnable) { - ApplicationManager.getApplication().invokeLater(runnable) - } - - override fun submit(callable: Callable): CancellablePromise { - val future = CompletableFuture() - ApplicationManager.getApplication().invokeLater { - try { future.complete(callable.call()) } - catch (e: Throwable) { future.completeExceptionally(e) } - } - return future.asCancellablePromise() - } - - override fun submit(runnable: Runnable): CancellablePromise<*> { - val future = CompletableFuture() - ApplicationManager.getApplication().invokeLater { - try { runnable.run(); future.complete(null) } - catch (e: Throwable) { future.completeExceptionally(e) } - } - return future.asCancellablePromise() - } + override fun later(): AppUIExecutor = this + + override fun withDocumentsCommitted(project: Project): AppUIExecutor = this + + override fun inSmartMode(project: Project): AppUIExecutor = this + + override fun expireWith(disposable: Disposable): AppUIExecutor = this + + override fun execute(runnable: Runnable) { + ApplicationManager.getApplication().invokeLater(runnable) + } + + override fun submit(callable: Callable): CancellablePromise { + val future = CompletableFuture() + ApplicationManager.getApplication().invokeLater { + try { + future.complete(callable.call()) + } catch (e: Throwable) { + future.completeExceptionally(e) + } + } + return future.asCancellablePromise() + } + + override fun submit(runnable: Runnable): CancellablePromise<*> { + val future = CompletableFuture() + ApplicationManager.getApplication().invokeLater { + try { + runnable.run() + future.complete(null) + } catch (e: Throwable) { + future.completeExceptionally(e) + } + } + return future.asCancellablePromise() + } } -private class NoOpExpirableExecutor(private val exec: Executor) : ExpirableExecutor { - override fun expireWith(disposable: Disposable): ExpirableExecutor = this +private class NoOpExpirableExecutor( + private val exec: Executor, +) : ExpirableExecutor { + override fun expireWith(disposable: Disposable): ExpirableExecutor = this - override fun execute(runnable: Runnable) = exec.execute(runnable) + override fun execute(runnable: Runnable) = exec.execute(runnable) - override fun submit(callable: Callable): CancellablePromise = - CompletableFuture.supplyAsync({ callable.call() }, exec).asCancellablePromise() + override fun submit(callable: Callable): CancellablePromise = + CompletableFuture.supplyAsync({ callable.call() }, exec).asCancellablePromise() - override fun submit(runnable: Runnable): CancellablePromise<*> = - CompletableFuture.runAsync(runnable, exec).thenApply { null }.asCancellablePromise() + override fun submit(runnable: Runnable): CancellablePromise<*> = + CompletableFuture.runAsync(runnable, exec).thenApply { null }.asCancellablePromise() } -private class NoOpNonBlockingReadAction(private val callable: Callable) : NonBlockingReadAction { - override fun inSmartMode(project: Project): NonBlockingReadAction = this - override fun withDocumentsCommitted(project: Project): NonBlockingReadAction = this - override fun expireWhen(condition: BooleanSupplier): NonBlockingReadAction = this - override fun wrapProgress(indicator: ProgressIndicator): NonBlockingReadAction = this - override fun expireWith(disposable: Disposable): NonBlockingReadAction = this - override fun finishOnUiThread(modalityState: ModalityState, uiThreadAction: Consumer): NonBlockingReadAction = this - override fun coalesceBy(vararg equality: Any): NonBlockingReadAction = this +private class NoOpNonBlockingReadAction( + private val callable: Callable, +) : NonBlockingReadAction { + override fun inSmartMode(project: Project): NonBlockingReadAction = this + + override fun withDocumentsCommitted(project: Project): NonBlockingReadAction = this + + override fun expireWhen(condition: BooleanSupplier): NonBlockingReadAction = this + + override fun wrapProgress(indicator: ProgressIndicator): NonBlockingReadAction = this + + override fun expireWith(disposable: Disposable): NonBlockingReadAction = this - override fun submit(backgroundThreadExecutor: Executor): CancellablePromise = - CompletableFuture.supplyAsync({ callable.call() }, backgroundThreadExecutor) - .asCancellablePromise() + override fun finishOnUiThread( + modalityState: ModalityState, + uiThreadAction: Consumer, + ): NonBlockingReadAction = this - override fun executeSynchronously(): T = callable.call() + override fun coalesceBy(vararg equality: Any): NonBlockingReadAction = this + + override fun submit(backgroundThreadExecutor: Executor): CancellablePromise = + CompletableFuture + .supplyAsync({ callable.call() }, backgroundThreadExecutor) + .asCancellablePromise() + + override fun executeSynchronously(): T = callable.call() } -private fun CompletableFuture.asCancellablePromise(): CancellablePromise = - CompletableFutureCancellablePromise(this) +private fun CompletableFuture.asCancellablePromise(): CancellablePromise = CompletableFutureCancellablePromise(this) private class CompletableFutureCancellablePromise( - private val future: CompletableFuture + private val future: CompletableFuture, ) : CancellablePromise { + // Future + override fun cancel(mayInterruptIfRunning: Boolean): Boolean = future.cancel(mayInterruptIfRunning) - // Future - override fun cancel(mayInterruptIfRunning: Boolean): Boolean = future.cancel(mayInterruptIfRunning) - override fun isCancelled(): Boolean = future.isCancelled - override fun isDone(): Boolean = future.isDone - override fun get(): T = future.get() - override fun get(timeout: Long, unit: TimeUnit): T = future.get(timeout, unit) + override fun isCancelled(): Boolean = future.isCancelled - // CancellablePromise - override fun cancel() { future.cancel(true) } + override fun isDone(): Boolean = future.isDone - override fun onSuccess(handler: Consumer): CancellablePromise { - future.thenAccept(handler) - return this - } + override fun get(): T = future.get() - override fun onError(handler: Consumer): CancellablePromise { - future.exceptionally { e -> handler.accept(e); null } - return this - } + override fun get( + timeout: Long, + unit: TimeUnit, + ): T = future.get(timeout, unit) - override fun onProcessed(handler: Consumer): CancellablePromise { - future.whenComplete { value, _ -> handler.accept(value) } - return this + // CancellablePromise + override fun cancel() { + future.cancel(true) } - // Promise - override fun getState(): Promise.State = when { - future.isCancelled || future.isCompletedExceptionally -> Promise.State.REJECTED - future.isDone -> Promise.State.SUCCEEDED - else -> Promise.State.PENDING - } - - override fun processed(child: Promise): Promise = this + override fun onSuccess(handler: Consumer): CancellablePromise { + future.thenAccept(handler) + return this + } - override fun blockingGet(timeout: Int, unit: TimeUnit): T = future.get(timeout.toLong(), unit) + override fun onError(handler: Consumer): CancellablePromise { + future.exceptionally { e -> + handler.accept(e) + null + } + return this + } - override fun then(handler: Function): Promise = - future.thenApply { handler.`fun`(it) }.asCancellablePromise() + override fun onProcessed(handler: Consumer): CancellablePromise { + future.whenComplete { value, _ -> handler.accept(value) } + return this + } - override fun thenAsync( - handler: Function> - ): Promise = future.thenCompose { value -> - @Suppress("UNCHECKED_CAST") - (handler.`fun`(value) as CompletableFutureCancellablePromise).future - }.asCancellablePromise() + // Promise + override fun getState(): Promise.State = + when { + future.isCancelled || future.isCompletedExceptionally -> Promise.State.REJECTED + future.isDone -> Promise.State.SUCCEEDED + else -> Promise.State.PENDING + } + + override fun processed(child: Promise): Promise = this + + override fun blockingGet( + timeout: Int, + unit: TimeUnit, + ): T = future.get(timeout.toLong(), unit) + + override fun then(handler: Function): Promise = + future.thenApply { handler.`fun`(it) }.asCancellablePromise() + + override fun thenAsync(handler: Function>): Promise = + future + .thenCompose { value -> + @Suppress("UNCHECKED_CAST") + (handler.`fun`(value) as CompletableFutureCancellablePromise).future + }.asCancellablePromise() } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt index 29d8b91189..3e5be9bdd6 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt @@ -9,47 +9,46 @@ import com.itsaky.androidide.plugins.services.ThemeChangeListener import com.itsaky.androidide.utils.isSystemInDarkMode class IdeThemeServiceImpl( - private val context: Context + private val context: Context, ) : IdeThemeService { - - private val listeners = mutableListOf() - private var lastKnownDarkMode: Boolean = false - - private val configCallback = object : ComponentCallbacks { - override fun onConfigurationChanged(newConfig: Configuration) { - val isDark = isDarkMode() - if (isDark != lastKnownDarkMode) { - lastKnownDarkMode = isDark - listeners.forEach { it.onThemeChanged(isDark) } - } - } - - override fun onLowMemory() {} - } - - init { - lastKnownDarkMode = isDarkMode() - context.registerComponentCallbacks(configCallback) - } - - override fun isDarkMode(): Boolean { - return when (AppCompatDelegate.getDefaultNightMode()) { - AppCompatDelegate.MODE_NIGHT_YES -> true - AppCompatDelegate.MODE_NIGHT_NO -> false - else -> context.isSystemInDarkMode() - } - } - - override fun addThemeChangeListener(listener: ThemeChangeListener) { - listeners.add(listener) - } - - override fun removeThemeChangeListener(listener: ThemeChangeListener) { - listeners.remove(listener) - } - - fun dispose() { - context.unregisterComponentCallbacks(configCallback) - listeners.clear() - } + private val listeners = mutableListOf() + private var lastKnownDarkMode: Boolean = false + + private val configCallback = + object : ComponentCallbacks { + override fun onConfigurationChanged(newConfig: Configuration) { + val isDark = isDarkMode() + if (isDark != lastKnownDarkMode) { + lastKnownDarkMode = isDark + listeners.forEach { it.onThemeChanged(isDark) } + } + } + + override fun onLowMemory() {} + } + + init { + lastKnownDarkMode = isDarkMode() + context.registerComponentCallbacks(configCallback) + } + + override fun isDarkMode(): Boolean = + when (AppCompatDelegate.getDefaultNightMode()) { + AppCompatDelegate.MODE_NIGHT_YES -> true + AppCompatDelegate.MODE_NIGHT_NO -> false + else -> context.isSystemInDarkMode() + } + + override fun addThemeChangeListener(listener: ThemeChangeListener) { + listeners.add(listener) + } + + override fun removeThemeChangeListener(listener: ThemeChangeListener) { + listeners.remove(listener) + } + + fun dispose() { + context.unregisterComponentCallbacks(configCallback) + listeners.clear() + } } diff --git a/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt b/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt index 2df8029440..002feff920 100644 --- a/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt +++ b/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt @@ -20,4 +20,8 @@ package com.itsaky.androidide.uidesigner.models import androidx.annotation.StringRes import com.itsaky.androidide.inflater.models.UiWidget -data class UiWidgetCategory(@StringRes val label: Int, var widgets: List = emptyList(), var isExpanded: Boolean = false) \ No newline at end of file +data class UiWidgetCategory( + @StringRes val label: Int, + var widgets: List = emptyList(), + var isExpanded: Boolean = false, +) diff --git a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt index 44ac2e514f..fb870cb024 100644 --- a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt +++ b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt @@ -30,28 +30,25 @@ import com.itsaky.androidide.inflater.internal.ViewGroupImpl * @author Akash Yadav */ abstract class AdapterViewAdapter> : ViewGroupAdapter() { + companion object { + const val ADAPTER_DEFAULT_ITEM_COUNT = 3 + } - companion object { - const val ADAPTER_DEFAULT_ITEM_COUNT = 3 - } + override fun applyBasic(view: IView) { + super.applyBasic(view) + (view.view as AdapterView).adapter = newSimpleAdapter(view.view.context) + if (view is ViewGroupImpl) { + view.childrenModifiable = false + } + } - override fun applyBasic(view: IView) { - super.applyBasic(view) - (view.view as AdapterView).adapter = newSimpleAdapter(view.view.context) - if (view is ViewGroupImpl) { - view.childrenModifiable = false - } - } + protected open fun newSimpleAdapter(ctx: Context): ArrayAdapter = + newSimpleAdapter(ctx, newAdapterItems(ADAPTER_DEFAULT_ITEM_COUNT)) - protected open fun newSimpleAdapter(ctx: Context): ArrayAdapter { - return newSimpleAdapter(ctx, newAdapterItems(ADAPTER_DEFAULT_ITEM_COUNT)) - } + protected open fun newSimpleAdapter( + ctx: Context, + items: Array, + ): ArrayAdapter = ArrayAdapter(ctx, layout.simple_list_item_1, items) - protected open fun newSimpleAdapter(ctx: Context, items: Array): ArrayAdapter { - return ArrayAdapter(ctx, layout.simple_list_item_1, items) - } - - protected open fun newAdapterItems(size: Int): Array { - return Array(size) { "Item $it" } - } + protected open fun newAdapterItems(size: Int): Array = Array(size) { "Item $it" } } diff --git a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt index 64025d7fbb..32a7bc1a1c 100644 --- a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt +++ b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt @@ -28,51 +28,53 @@ import java.lang.reflect.Method /** @author Akash Yadav */ object ViewFactory { + private val log = LoggerFactory.getLogger(ViewFactory::class.java) - private val log = LoggerFactory.getLogger(ViewFactory::class.java) + fun createViewInstance( + name: String, + context: Context, + ): View { + val adapter = ViewAdapterIndexImpl.INSTANCE.getViewAdapter(name) + return try { + if (adapter != null) { + // Check if adapter can create the view instance + val view = adapter.onCreateView(name, context) + if (view != null) { + return view + } + } - fun createViewInstance(name: String, context: Context): View { - val adapter = ViewAdapterIndexImpl.INSTANCE.getViewAdapter(name) - return try { - if (adapter != null) { - // Check if adapter can create the view instance - val view = adapter.onCreateView(name, context) - if (view != null) { - return view - } - } + val klass = javaClass.classLoader!!.loadClass(name) + val constructor = klass.getConstructor(Context::class.java) + constructor.newInstance(context) as View + } catch (err: Throwable) { + log.error("Failed to create view instance for view: {}", name, err) + throw RuntimeException(err) + } + } - val klass = javaClass.classLoader!!.loadClass(name) - val constructor = klass.getConstructor(Context::class.java) - constructor.newInstance(context) as View - } catch (err: Throwable) { - log.error("Failed to create view instance for view: {}", name, err) - throw RuntimeException(err) - } - } + fun generateLayoutParams(parent: ViewGroup): LayoutParams { + return try { + var clazz: Class = parent.javaClass + var method: Method? + while (true) { + try { + method = clazz.getDeclaredMethod("generateDefaultLayoutParams") + break + } catch (e: Throwable) { + // ignored + } - fun generateLayoutParams(parent: ViewGroup): LayoutParams { - return try { - var clazz: Class = parent.javaClass - var method: Method? - while (true) { - try { - method = clazz.getDeclaredMethod("generateDefaultLayoutParams") - break - } catch (e: Throwable) { - /* ignored */ - } - - clazz = clazz.superclass - } - if (method != null) { - method.isAccessible = true - return method.invoke(parent) as LayoutParams - } - log.error("Unable to create default params for view parent: {}", parent) - LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) - } catch (th: Throwable) { - throw InflateException("Unable to create layout params for parent: $parent", th) - } - } + clazz = clazz.superclass + } + if (method != null) { + method.isAccessible = true + return method.invoke(parent) as LayoutParams + } + log.error("Unable to create default params for view parent: {}", parent) + LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) + } catch (th: Throwable) { + throw InflateException("Unable to create layout params for parent: $parent", th) + } + } } From 3328756c458a26057cb49314aa43aa6053fd4393 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:54:55 -0800 Subject: [PATCH 02/10] ADFA-7201: Drop the redundant code the Kotlin compiler flags Removes Elvis operators, safe calls, casts and an else branch that the compiler proves can never matter: - plugin-manager PluginManifest, templates-impl ZipTemplateReader: Gson ignores Kotlin nullability, so the null fallbacks stay, as orEmpty() calls the compiler accepts on non-null types. - lsp/kotlin refactor: mainReference and resolveToSymbols() never return null, and lambda.symbol is already a KaAnonymousFunctionSymbol. - lsp/java: the when over Diagnostic.Kind is exhaustive; the debugger's source file is already smart-cast. - lsp/jvm-symbol-index: KmProperty.getter is never null. - xml-inflater ViewFactory: the superclass walk now asserts non-null instead of assigning a nullable Class to a non-null variable. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../lsp/java/debug/utils/ModelUtils.kt | 2 +- .../lsp/java/providers/DiagnosticsProvider.kt | 2 -- .../indexing/jvm/KotlinMetadataScanner.kt | 3 ++- .../utils/refactor/InlineVariablePlanner.kt | 12 +++++------- .../lsp/kotlin/utils/refactor/MethodSignature.kt | 16 ++++++++-------- .../lsp/kotlin/utils/refactor/Occurrences.kt | 12 ++++++------ .../plugins/manager/loaders/PluginManifest.kt | 14 ++++++++------ .../templates/impl/zip/ZipTemplateReader.kt | 5 +++-- .../inflater/internal/utils/ViewFactory.kt | 4 +++- 9 files changed, 36 insertions(+), 34 deletions(-) diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt index aaa8d71717..ed6d99e7b5 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/utils/ModelUtils.kt @@ -58,7 +58,7 @@ fun Location.asLspLocation(useDeclTypeName: Boolean = true): LspLocation { logger.info("No source found for location: {}", this) } - return@mapNotNull fo as SourceFileObject? + return@mapNotNull fo }?.firstOrNull() // TODO: Maybe allow the user to choose which source file to open? val source = diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt index 6ad6c2c3e1..e8229080e7 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/providers/DiagnosticsProvider.kt @@ -340,7 +340,5 @@ object DiagnosticsProvider { Diagnostic.Kind.NOTE -> DiagnosticSeverity.INFO Diagnostic.Kind.OTHER -> DiagnosticSeverity.HINT - - else -> DiagnosticSeverity.HINT } } diff --git a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KotlinMetadataScanner.kt b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KotlinMetadataScanner.kt index 50ae6bdaac..4ab385c049 100644 --- a/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KotlinMetadataScanner.kt +++ b/lsp/jvm-symbol-index/src/main/kotlin/org/appdevforall/codeonthego/indexing/jvm/KotlinMetadataScanner.kt @@ -419,7 +419,8 @@ object KotlinMetadataScanner { receiverTypeDisplayName = receiverType?.let { kmTypeToDisplayName(it) } ?: "", isConst = prop.isConst, isLateinit = prop.isLateinit, - hasGetter = prop.getter != null, + // Every Kotlin property has a getter, so KmProperty.getter is never null. + hasGetter = true, hasSetter = prop.setter != null, isDelegated = prop.isDelegated, isTypeNullable = prop.returnType.isNullable, diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/InlineVariablePlanner.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/InlineVariablePlanner.kt index c6363619a4..dc47dcb851 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/InlineVariablePlanner.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/InlineVariablePlanner.kt @@ -8,7 +8,6 @@ import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.resolution.KaCallableMemberCall import org.jetbrains.kotlin.analysis.api.resolution.KaImplicitReceiverValue import org.jetbrains.kotlin.analysis.api.resolution.successfulCallOrNull -import org.jetbrains.kotlin.analysis.api.symbols.KaAnonymousFunctionSymbol import org.jetbrains.kotlin.analysis.api.types.KaFunctionType import org.jetbrains.kotlin.com.intellij.psi.PsiComment import org.jetbrains.kotlin.com.intellij.psi.PsiElement @@ -297,8 +296,8 @@ private fun KaSession.resolveTargetAt( val referenced = runCatching { reference.mainReference - ?.resolveToSymbols() - ?.firstNotNullOfOrNull { symbol -> runCatching { symbol.psi }.getOrNull() } + .resolveToSymbols() + .firstNotNullOfOrNull { symbol -> runCatching { symbol.psi }.getOrNull() } }.getOrNull() ?: return TargetResolution.Refused(InlineRefusal.NotAVariable) if (referenced is KtProperty) { @@ -317,9 +316,9 @@ private fun KaSession.resolvesToTarget( target: KtProperty, ): Boolean = runCatching { - reference.mainReference?.resolveToSymbols()?.any { symbol -> + reference.mainReference.resolveToSymbols().any { symbol -> runCatching { symbol.psi }.getOrNull() === target - } == true + } }.getOrDefault(false) /** @@ -544,8 +543,7 @@ private fun KaSession.changesImplicitReceiverBetween( */ private fun KaSession.introducesReceiver(lambda: KtFunctionLiteral): Boolean = runCatching { - val symbol = lambda.symbol as? KaAnonymousFunctionSymbol - if (symbol?.receiverParameter != null) return true + if (lambda.symbol.receiverParameter != null) return true ((lambda.parent as? KtLambdaExpression)?.expressionType as? KaFunctionType)?.hasReceiver == true }.getOrDefault(false) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt index 5f17525f96..fddc444dff 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt @@ -138,7 +138,7 @@ internal fun KaSession.buildCandidate( if (declared != null && (declared !is KtProperty || outputs.writtenAfter.isNotEmpty())) { return refuse(ExtractionRefusal.OutputNotReturnable(declared.name.orEmpty())) } - val output = declared as? KtProperty + val output: KtProperty? = declared // The tail-return exception holds only when nothing else flows out (R8). if (tailReturn && output != null) return refuse(ExtractionRefusal.ExitsRegion) @@ -356,7 +356,7 @@ private fun KaSession.capturedParameters( // resolves. The ancestor test below already lets every selector resolving to a non-local member // through, which is what a guard would have bought. val resolved = - runCatching { reference.mainReference?.resolveToSymbols()?.firstOrNull() }.getOrNull() ?: continue + runCatching { reference.mainReference.resolveToSymbols().firstOrNull() }.getOrNull() ?: continue val name = reference.getReferencedName() // A local class or object is not a callable, so it used to fail the cast below and be silently @@ -538,8 +538,8 @@ private fun KaSession.outputsOf( private fun KaSession.resolvedPsi(reference: KtSimpleNameExpression): PsiElement? = runCatching { reference.mainReference - ?.resolveToSymbols() - ?.firstOrNull() + .resolveToSymbols() + .firstOrNull() ?.psi }.getOrNull() @@ -556,7 +556,7 @@ private fun KaSession.reassignedOuterVar( if (!reference.isWriteTarget()) continue val symbol = runCatching { - (reference.mainReference?.resolveToSymbols()?.firstOrNull() as? KaVariableSymbol)?.takeIf { !it.isVal } + (reference.mainReference.resolveToSymbols().firstOrNull() as? KaVariableSymbol)?.takeIf { !it.isVal } }.getOrNull() ?: continue val declarationPsi = runCatching { symbol.psi }.getOrNull() ?: continue if (!PsiTreeUtil.isAncestor(enclosing, declarationPsi, true)) continue @@ -763,7 +763,7 @@ private fun KaSession.usesBackingField( if (enclosing !is KtPropertyAccessor) return false return simpleNamesIn(elements).any { reference -> reference.getReferencedName() == BACKING_FIELD_NAME && - runCatching { reference.mainReference?.resolveToSymbols()?.firstOrNull() }.getOrNull() is KaBackingFieldSymbol + runCatching { reference.mainReference.resolveToSymbols().firstOrNull() }.getOrNull() is KaBackingFieldSymbol } } @@ -804,8 +804,8 @@ private fun KaSession.innerImplicitReceiver( val symbol = runCatching { thisExpression.instanceReference.mainReference - ?.resolveToSymbols() - ?.firstOrNull() + .resolveToSymbols() + .firstOrNull() }.getOrNull() val lambda = lambdaOwning(symbol) ?: continue if (isBoundOutsideRegion(enclosing, lambda, span)) return constructNameFor(lambda) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/Occurrences.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/Occurrences.kt index 1e122698ee..9a062c3ab1 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/Occurrences.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/Occurrences.kt @@ -77,8 +77,8 @@ private fun KaSession.resolvesToSameDeclaration( b: KtSimpleNameExpression, ): Boolean = runCatching { - val symbolA = a.mainReference?.resolveToSymbols()?.firstOrNull() ?: return false - val symbolB = b.mainReference?.resolveToSymbols()?.firstOrNull() ?: return false + val symbolA = a.mainReference.resolveToSymbols().firstOrNull() ?: return false + val symbolB = b.mainReference.resolveToSymbols().firstOrNull() ?: return false val psiA = symbolA.declarationPsi() val psiB = symbolB.declarationPsi() if (psiA != null || psiB != null) psiA === psiB else symbolA == symbolB @@ -131,7 +131,7 @@ internal fun KaSession.referencedDeclarationCeiling(candidate: KtExpression): Ps var deepest: PsiElement? = null var deepestDepth = -1 for (reference in candidate.collectDescendantsOfType()) { - val symbol = runCatching { reference.mainReference?.resolveToSymbols()?.firstOrNull() }.getOrNull() ?: continue + val symbol = runCatching { reference.mainReference.resolveToSymbols().firstOrNull() }.getOrNull() ?: continue val body = constrainingBodyFor(reference, symbol) ?: continue val depth = depthOf(body) if (depth > deepestDepth) { @@ -193,7 +193,7 @@ internal fun KaSession.writeOffsetsFor( .collectDescendantsOfType() .mapNotNull { reference -> runCatching { - (reference.mainReference?.resolveToSymbols()?.firstOrNull() as? KaVariableSymbol) + (reference.mainReference.resolveToSymbols().firstOrNull() as? KaVariableSymbol) ?.takeIf { !it.isVal } ?.psi }.getOrNull() @@ -206,8 +206,8 @@ internal fun KaSession.writeOffsetsFor( .filter { reference -> runCatching { reference.mainReference - ?.resolveToSymbols() - ?.firstOrNull() + .resolveToSymbols() + .firstOrNull() ?.psi }.getOrNull() in mutableDeclarations }.map { it.textRange.startOffset } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/loaders/PluginManifest.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/loaders/PluginManifest.kt index 0c01444301..1dafa42680 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/loaders/PluginManifest.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/loaders/PluginManifest.kt @@ -130,9 +130,11 @@ object PluginManifestParser { fun toJson(manifest: PluginManifest): String = gson.toJson(manifest) + // Gson ignores Kotlin nullability and the defaults, so a manifest missing a list leaves it null + // here despite the non-null type. Hence the null checks and orEmpty() calls below. @Suppress("SENSELESS_COMPARISON") private fun PluginManifest.normalize(): PluginManifest { - val normalizedActions = (buildActions ?: emptyList()).map { it.normalize() } + val normalizedActions = buildActions.orEmpty().map { it.normalize() } val normalizedRevision = normalizeProvenanceValue(vcsRevision) val normalizedTimestamp = normalizeProvenanceValue(buildTimestamp) return if ( @@ -141,9 +143,9 @@ object PluginManifestParser { normalizedRevision !== vcsRevision || normalizedTimestamp !== buildTimestamp ) { copy( - permissions = permissions ?: emptyList(), - dependencies = dependencies ?: emptyList(), - extensions = extensions ?: emptyList(), + permissions = permissions.orEmpty(), + dependencies = dependencies.orEmpty(), + extensions = extensions.orEmpty(), buildActions = normalizedActions, vcsRevision = normalizedRevision, buildTimestamp = normalizedTimestamp, @@ -157,8 +159,8 @@ object PluginManifestParser { private fun ManifestBuildAction.normalize(): ManifestBuildAction { if (arguments == null || environment == null || timeoutMs == 0L) { return copy( - arguments = arguments ?: emptyList(), - environment = environment ?: emptyMap(), + arguments = arguments.orEmpty(), + environment = environment.orEmpty(), timeoutMs = if (timeoutMs == 0L) 600_000 else timeoutMs, ) } diff --git a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateReader.kt b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateReader.kt index a8d4c4b5b1..8742a50e62 100644 --- a/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateReader.kt +++ b/templates-impl/src/main/java/com/itsaky/androidide/templates/impl/zip/ZipTemplateReader.kt @@ -83,11 +83,12 @@ object ZipTemplateReader { val userWidgets = mutableListOf>() val params = mutableMapOf>() + // Gson ignores Kotlin nullability, so a parameter without a label leaves `label` null. metaJson.parameters?.user?.text?.forEach { textParam -> val param = stringParameter { name = 0 - nameStr = textParam.label ?: "" + nameStr = textParam.label.orEmpty() default = textParam.default ?: "" } userWidgets.add(TextFieldWidget(param)) @@ -98,7 +99,7 @@ object ZipTemplateReader { val param = booleanParameter { name = 0 - nameStr = checkboxParam.label ?: "" + nameStr = checkboxParam.label.orEmpty() default = checkboxParam.default ?: false } userWidgets.add(CheckBoxWidget(param)) diff --git a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt index 32a7bc1a1c..7c069db795 100644 --- a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt +++ b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/utils/ViewFactory.kt @@ -65,7 +65,9 @@ object ViewFactory { // ignored } - clazz = clazz.superclass + // ViewGroup declares generateDefaultLayoutParams, so the walk stops before it runs out of + // superclasses. + clazz = checkNotNull(clazz.superclass) } if (method != null) { method.isAccessible = true From 3e61cdfda223cab03e2ddcc2cd6af280519186b0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:55:13 -0800 Subject: [PATCH 03/10] ADFA-7201: Fix annotation targets, opt-ins and deprecated overrides - @param: targets on the @StringRes/@DrawableRes constructor properties in xml-inflater UiWidget, lsp/java ExtractionPlan and uidesigner UiWidgetCategory, which keeps today's placement (KT-73255). - @OptIn(ExperimentalCoroutinesApi) where editor-treesitter and lsp/java use the CloseableCoroutineDispatcher that newSingleThreadContext returns. - @Deprecated on overrides of deprecated members: plugin-manager IdeThemeServiceImpl.onLowMemory and lsp/kotlin NoOpAsyncExecutionService. That file implements IntelliJ's deprecated executor interfaces, which have no replacement, so it also suppresses DEPRECATION at file level, the only scope that reaches its imports. - lsp/xml compiles against jaxp, which holds URIResolverExtensionManager's supertypes. xml-dom already ships it at runtime. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../io/github/rosemoe/sora/editor/ts/TsAnalyzeWorker.kt | 3 +++ .../com/itsaky/androidide/lsp/java/debug/EventHandler.kt | 3 +++ .../androidide/lsp/java/refactor/ExtractionPlan.kt | 2 +- .../compiler/services/NoOpAsyncExecutionService.kt | 9 ++++++++- lsp/xml/build.gradle.kts | 3 +++ .../plugins/manager/services/IdeThemeServiceImpl.kt | 1 + .../androidide/uidesigner/models/UiWidgetCategory.kt | 2 +- .../com/itsaky/androidide/inflater/models/UiWidget.kt | 4 ++-- 8 files changed, 22 insertions(+), 5 deletions(-) diff --git a/editor-treesitter/src/main/java/io/github/rosemoe/sora/editor/ts/TsAnalyzeWorker.kt b/editor-treesitter/src/main/java/io/github/rosemoe/sora/editor/ts/TsAnalyzeWorker.kt index 321291936b..f4b0fa2c76 100644 --- a/editor-treesitter/src/main/java/io/github/rosemoe/sora/editor/ts/TsAnalyzeWorker.kt +++ b/editor-treesitter/src/main/java/io/github/rosemoe/sora/editor/ts/TsAnalyzeWorker.kt @@ -67,6 +67,8 @@ class TsAnalyzeWorker( @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) private val analyzerContext = newSingleThreadContext("TsAnalyzeWorkerContext") + // analyzerContext's type, CloseableCoroutineDispatcher, is itself experimental. + @OptIn(ExperimentalCoroutinesApi::class) private val analyzerScope = CoroutineScope(analyzerContext) private val messageChannel = LinkedBlockingQueue>() private var analyzerJob: Job? = null @@ -141,6 +143,7 @@ class TsAnalyzeWorker( } } + @OptIn(ExperimentalCoroutinesApi::class) private fun releaseResources() { document.close() analyzerContext.close() diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt index 11bc795056..3d49e4062a 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/debug/EventHandler.kt @@ -51,6 +51,9 @@ internal class EventHandler( @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class) private val adapterContext = newSingleThreadContext("JDWPEventHandler") + + // adapterContext's type, CloseableCoroutineDispatcher, is itself experimental. + @OptIn(ExperimentalCoroutinesApi::class) private val adapterScope = CoroutineScope(adapterContext) private var eventsJob: Job? = null diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ExtractionPlan.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ExtractionPlan.kt index 86dcc19607..2e805930cd 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ExtractionPlan.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ExtractionPlan.kt @@ -43,7 +43,7 @@ sealed interface AnchorForm { * part, filled positionally. */ data class ScopeLabel( - @StringRes val res: Int, + @param:StringRes val res: Int, val argument: String? = null, ) diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt index 965f462451..8c019e94a1 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/compiler/services/NoOpAsyncExecutionService.kt @@ -1,4 +1,7 @@ -@file:Suppress("UnstableApiUsage") +// AsyncExecutionService's abstract createExecutor, createUIExecutor and createWriteThreadExecutor return +// the deprecated ExpirableExecutor and AppUIExecutor, and have no replacement. Implementing them is this +// file's whole job, and only a file-level suppression reaches the imports. +@file:Suppress("UnstableApiUsage", "DEPRECATION") package com.itsaky.androidide.lsp.kotlin.compiler.services @@ -33,6 +36,7 @@ import java.util.function.Consumer internal class NoOpAsyncExecutionService : AsyncExecutionService() { private val executor: AppUIExecutor = NoOpAppUIExecutor() + @Deprecated("Deprecated in Java") override fun createExecutor(backgroundExecutor: Executor): ExpirableExecutor = NoOpExpirableExecutor(backgroundExecutor) override fun createUIExecutor(modalityState: ModalityState): AppUIExecutor = executor @@ -43,10 +47,13 @@ internal class NoOpAsyncExecutionService : AsyncExecutionService() { } private class NoOpAppUIExecutor : AppUIExecutor { + @Deprecated("Deprecated in Java") override fun later(): AppUIExecutor = this + @Deprecated("Deprecated in Java") override fun withDocumentsCommitted(project: Project): AppUIExecutor = this + @Deprecated("Deprecated in Java") override fun inSmartMode(project: Project): AppUIExecutor = this override fun expireWith(disposable: Disposable): AppUIExecutor = this diff --git a/lsp/xml/build.gradle.kts b/lsp/xml/build.gradle.kts index 11d6375667..9c3b941307 100644 --- a/lsp/xml/build.gradle.kts +++ b/lsp/xml/build.gradle.kts @@ -60,4 +60,7 @@ dependencies { compileOnly(projects.common) compileOnly(libs.common.antlr4) + // URIResolverExtensionManager's supertypes live here. xml-dom already ships it at runtime but keeps + // it off our compile classpath. + compileOnly(libs.composite.jaxp) } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt index 3e5be9bdd6..c5cb30b3ab 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeThemeServiceImpl.kt @@ -24,6 +24,7 @@ class IdeThemeServiceImpl( } } + @Deprecated("Deprecated in Java") override fun onLowMemory() {} } diff --git a/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt b/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt index 002feff920..3febfcea8b 100644 --- a/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt +++ b/uidesigner/src/main/java/com/itsaky/androidide/uidesigner/models/UiWidgetCategory.kt @@ -21,7 +21,7 @@ import androidx.annotation.StringRes import com.itsaky.androidide.inflater.models.UiWidget data class UiWidgetCategory( - @StringRes val label: Int, + @param:StringRes val label: Int, var widgets: List = emptyList(), var isExpanded: Boolean = false, ) diff --git a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/models/UiWidget.kt b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/models/UiWidget.kt index 1ed4fb9a11..e609a20eb3 100644 --- a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/models/UiWidget.kt +++ b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/models/UiWidget.kt @@ -36,8 +36,8 @@ import com.itsaky.androidide.utils.dpToPx open class UiWidget( val name: String, - @StringRes val label: Int, - @DrawableRes val icon: Int, + @param:StringRes val label: Int, + @param:DrawableRes val icon: Int, ) { constructor( klass: Class, From a72373f0eb1721a23c8a9eff4ab128cddbe00c85 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:55:14 -0800 Subject: [PATCH 04/10] ADFA-7201: Replace or suppress deprecated API uses in Kotlin Replaced: - editor: IDEEditorSearcher overrides replaceCurrentMatch, which the deprecated replaceThis only forwards to, and ReplaceAction calls it. IDEEditor disables sora's own search action mode, so nothing else reaches the override. - lsp/java JavaParserUtils: the stdlib first() after the existing emptiness checks, instead of NodeList.getFirst(). - lsp/kotlin MethodSignature: the variable and getter calls' own receivers, instead of their deprecated partiallyAppliedSymbol. Suppressed, each at the narrowest scope with its reason in a comment: - lsp/java CaseTrees.kt: the vendored javac still marks the switch-rule API deprecated, with no replacement; ScopeChain and CandidateExpressions go through these accessors. - lsp/external: rootUri, which servers older than workspaceFolders read. - floating-window: SOFT_INPUT_ADJUST_RESIZE; its replacement needs a Window, and an overlay has none. - editor: ViewCompat.getWindowInsetsController, for the same reason, and announceForAccessibility, whose suggested replacements describe state rather than read out a line. - xml-inflater AdapterViewAdapter: the unchecked AdapterView cast, which erasure makes uncheckable. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../editor/ui/EditorSearchLayout.kt | 3 +++ .../itsaky/androidide/editor/ui/IDEEditor.kt | 6 +++++ .../androidide/editor/ui/ReplaceAction.kt | 2 +- .../rosemoe/sora/widget/IDEEditorSearcher.kt | 4 +-- .../floating/window/OverlayLayoutParams.kt | 3 +++ .../lsp/external/ExternalLanguageServer.kt | 2 ++ .../lsp/java/refactor/CandidateExpressions.kt | 2 +- .../androidide/lsp/java/refactor/CaseTrees.kt | 23 +++++++++++++++++ .../lsp/java/refactor/ScopeChain.kt | 6 ++--- .../lsp/java/utils/JavaParserUtils.kt | 25 ++++++------------- .../kotlin/utils/refactor/MethodSignature.kt | 18 +++++++++---- .../internal/adapters/AdapterViewAdapter.kt | 6 ++++- 12 files changed, 70 insertions(+), 30 deletions(-) create mode 100644 lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CaseTrees.kt diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/EditorSearchLayout.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/EditorSearchLayout.kt index 1c39f28eb7..57ae43c96e 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/EditorSearchLayout.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/EditorSearchLayout.kt @@ -246,6 +246,9 @@ class EditorSearchLayout( findInFileBinding.searchInput.requestFocus() findInFileBinding.searchInput.post { + // The replacement, WindowCompat.getInsetsController, needs a Window, and this layout can sit in a + // floating overlay, which has none. This call works from the view. + @Suppress("DEPRECATION") ViewCompat.getWindowInsetsController(findInFileBinding.searchInput)?.show(WindowInsetsCompat.Type.ime()) } } diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt index f6720b7181..b32056bd63 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/IDEEditor.kt @@ -771,6 +771,9 @@ open class IDEEditor } else { "Line ${line + 1}: $lineContent" } + // Deprecated in API 36 for live regions and pane titles, which describe a view's state, not + // a one-off readout of the line under the finger. + @Suppress("DEPRECATION") announceForAccessibility(announcement) } } @@ -1073,6 +1076,9 @@ open class IDEEditor } else { "Line ${line + 1}, column ${column + 1}: $lineContent" } + // Deprecated in API 36 for live regions and pane titles, which describe a view's state, not a + // one-off readout of the caret's line. + @Suppress("DEPRECATION") announceForAccessibility(announcement) } // endregion Accessibility diff --git a/editor/src/main/java/com/itsaky/androidide/editor/ui/ReplaceAction.kt b/editor/src/main/java/com/itsaky/androidide/editor/ui/ReplaceAction.kt index a877752496..729c016d4b 100644 --- a/editor/src/main/java/com/itsaky/androidide/editor/ui/ReplaceAction.kt +++ b/editor/src/main/java/com/itsaky/androidide/editor/ui/ReplaceAction.kt @@ -49,7 +49,7 @@ object ReplaceAction { return@setPositiveButton } - editor.searcher.replaceThis(input.text.toString()) + editor.searcher.replaceCurrentMatch(input.text.toString()) } builder.setNeutralButton(R.string.replaceAll) { dialog, _ -> dialog.dismiss() diff --git a/editor/src/main/java/io/github/rosemoe/sora/widget/IDEEditorSearcher.kt b/editor/src/main/java/io/github/rosemoe/sora/widget/IDEEditorSearcher.kt index 627b8da76d..8f9881d484 100644 --- a/editor/src/main/java/io/github/rosemoe/sora/widget/IDEEditorSearcher.kt +++ b/editor/src/main/java/io/github/rosemoe/sora/widget/IDEEditorSearcher.kt @@ -65,9 +65,9 @@ open class IDEEditorSearcher( super.replaceAll(replacement, whenFinished) } - override fun replaceThis(replacement: String) { + override fun replaceCurrentMatch(replacement: String) { markSearching() - super.replaceThis(replacement) + super.replaceCurrentMatch(replacement) } override fun gotoNext(): Boolean { diff --git a/floating-window/src/main/java/com/itsaky/androidide/floating/window/OverlayLayoutParams.kt b/floating-window/src/main/java/com/itsaky/androidide/floating/window/OverlayLayoutParams.kt index 2f68b799c9..b3f2481610 100644 --- a/floating-window/src/main/java/com/itsaky/androidide/floating/window/OverlayLayoutParams.kt +++ b/floating-window/src/main/java/com/itsaky/androidide/floating/window/OverlayLayoutParams.kt @@ -39,6 +39,9 @@ object OverlayLayoutParams { gravity = Gravity.TOP or Gravity.START x = state.bounds.x y = state.bounds.y + // The replacement, Window.setDecorFitsSystemWindows, needs a Window, which an overlay added + // through WindowManager.addView does not have. + @Suppress("DEPRECATION") softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE } diff --git a/lsp/external/src/main/java/com/itsaky/androidide/lsp/external/ExternalLanguageServer.kt b/lsp/external/src/main/java/com/itsaky/androidide/lsp/external/ExternalLanguageServer.kt index 87d5a10c76..aeae6eb40c 100644 --- a/lsp/external/src/main/java/com/itsaky/androidide/lsp/external/ExternalLanguageServer.kt +++ b/lsp/external/src/main/java/com/itsaky/androidide/lsp/external/ExternalLanguageServer.kt @@ -495,6 +495,8 @@ class ExternalLanguageServer( private fun initializeParams(): InitializeParams = InitializeParams().apply { val root = workspaceRoot?.toPath() + // LSP deprecates rootUri for workspaceFolders, but servers that predate folders read only rootUri. + @Suppress("DEPRECATION") rootUri = root?.toLspUri() workspaceFolders = root?.let { listOf(WorkspaceFolder(it.toLspUri(), it.fileName.toString())) } initializationOptions = this@ExternalLanguageServer.initializationOptions.takeIf { it.isNotEmpty() } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CandidateExpressions.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CandidateExpressions.kt index 030cbdc590..945d66ff83 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CandidateExpressions.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CandidateExpressions.kt @@ -200,7 +200,7 @@ private fun isCaseLabel(path: TreePath): Boolean { while (current != null) { val leaf = current.leaf if (leaf is StatementTree && leaf !is CaseTree) return false - if (leaf is CaseTree) return leaf.body !== child + if (leaf is CaseTree) return leaf.ruleBody !== child child = leaf current = current.parentPath } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CaseTrees.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CaseTrees.kt new file mode 100644 index 0000000000..1c89289dad --- /dev/null +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/CaseTrees.kt @@ -0,0 +1,23 @@ +package com.itsaky.androidide.lsp.java.refactor + +import openjdk.source.tree.CaseTree +import openjdk.source.tree.Tree + +// The vendored javac still marks CaseTree's switch-rule API (getCaseKind, CaseKind, getBody) deprecated, +// as JDK 12 did while switch rules were a preview. JDK 14 made that API standard and it has no +// replacement, so these accessors keep the suppressions in one place. + +/** Whether this case is a `case L ->` rule. */ +@Suppress("DEPRECATION") +internal val CaseTree.isRule: Boolean + get() = caseKind == CaseTree.CaseKind.RULE + +/** Whether this case is a `case L:` statement group. */ +@Suppress("DEPRECATION") +internal val CaseTree.isStatementGroup: Boolean + get() = caseKind == CaseTree.CaseKind.STATEMENT + +/** The expression or statement after a rule's arrow, or null for a statement group. */ +@Suppress("DEPRECATION") +internal val CaseTree.ruleBody: Tree? + get() = body diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ScopeChain.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ScopeChain.kt index 60b0e7292a..02cb36c72d 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ScopeChain.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/refactor/ScopeChain.kt @@ -138,7 +138,7 @@ private fun frameFor( return expressionBodyFrame(LAMBDA, inner, innerSpan, parent, root, positions, fileText, indentUnit, "return") } - if (parent is CaseTree && parent.caseKind == CaseTree.CaseKind.RULE && parent.body === inner) { + if (parent is CaseTree && parent.isRule && parent.ruleBody === inner) { return when { inner is ExpressionTree -> { // `case A -> value;` parses the body as the expression and takes the `;` separately, so the @@ -155,7 +155,7 @@ private fun frameFor( } } - if (parent is CaseTree && parent.caseKind == CaseTree.CaseKind.STATEMENT && inner !is BlockTree) { + if (parent is CaseTree && parent.isStatementGroup && inner !is BlockTree) { return caseGroupFrame(parent, root, positions) } @@ -326,7 +326,7 @@ private fun blockLabel( is SynchronizedTree -> ScopeLabel(R.string.label_extract_scope_synchronized_block) - is CaseTree -> if (owner.caseKind == CaseTree.CaseKind.RULE) SWITCH_RULE else SWITCH_CASE + is CaseTree -> if (owner.isRule) SWITCH_RULE else SWITCH_CASE else -> ScopeLabel(R.string.label_extract_scope_block) } diff --git a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt index d2f17b8999..5b599e94fe 100644 --- a/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt +++ b/lsp/java/src/main/java/com/itsaky/androidide/lsp/java/utils/JavaParserUtils.kt @@ -642,14 +642,13 @@ object JavaParserUtils { return methodDeclaration } + // NodeList.getFirst() returns an Optional and clashes with List.getFirst(), so Kotlin deprecates it. + // These use the stdlib first() after an emptiness check instead. fun getFirstArrayType(type: Type): Type { if (type.isTypeParameter) { val typeParameter = type.asTypeParameter() if (typeParameter!!.typeBound.isNonEmpty) { - val first = typeParameter.typeBound.first - if (first!!.isPresent) { - return ArrayType(first.get()) - } + return ArrayType(typeParameter.typeBound.first()) } } return type @@ -659,10 +658,7 @@ object JavaParserUtils { if (type.isTypeParameter) { val typeParameter = type.asTypeParameter() if (typeParameter!!.typeBound.isNonEmpty) { - val first = typeParameter.typeBound.first - if (first!!.isPresent) { - return first.get() - } + return typeParameter.typeBound.first() } } if (!type.isClassOrInterfaceType) { @@ -674,22 +670,17 @@ object JavaParserUtils { return type } - val first = typeArguments.get().first - if (!first!!.isPresent || !first.get().isTypeParameter) { + val first = typeArguments.get().first() + if (!first.isTypeParameter) { return type } - val typeBound = first.get().asTypeParameter().typeBound + val typeBound = first.asTypeParameter().typeBound if (!typeBound!!.isNonEmpty) { return type } - val first1 = typeBound.first - if (!first1!!.isPresent) { - return type - } - - type.asClassOrInterfaceType().setTypeArguments(first1.get()) + type.asClassOrInterfaceType().setTypeArguments(typeBound.first()) return type } diff --git a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt index fddc444dff..c9fd133a85 100644 --- a/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt +++ b/lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/refactor/MethodSignature.kt @@ -836,11 +836,19 @@ private fun KaSession.implicitReceiverLambdaFor(reference: KtSimpleNameExpressio // Defensive only. A compound assignment (`n += 1` inside `apply { }`) redirects to the whole // compound access, but the resolver flags that redirect and still hands back a plain variable // access, so the branch above already catches it in this version. - val applied = - call?.successfulCallOrNull>()?.partiallyAppliedSymbol - ?: call?.successfulCallOrNull()?.variableCall?.partiallyAppliedSymbol - ?: call?.successfulCallOrNull()?.getterCall?.partiallyAppliedSymbol - receiverLambda(applied?.dispatchReceiver) ?: receiverLambda(applied?.extensionReceiver) + // The variable and getter calls carry their receivers themselves; their partiallyAppliedSymbol is + // deprecated. + val receivers = + call?.successfulCallOrNull>()?.partiallyAppliedSymbol?.let { + it.dispatchReceiver to it.extensionReceiver + } + ?: call?.successfulCallOrNull()?.variableCall?.let { + it.dispatchReceiver to it.extensionReceiver + } + ?: call?.successfulCallOrNull()?.getterCall?.let { + it.dispatchReceiver to it.extensionReceiver + } + receiverLambda(receivers?.first) ?: receiverLambda(receivers?.second) }.getOrNull() private fun receiverLambda(receiver: KaReceiverValue?): KtFunctionLiteral? = lambdaOwning((receiver as? KaImplicitReceiverValue)?.symbol) diff --git a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt index fb870cb024..5b8f00e302 100644 --- a/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt +++ b/xml-inflater/src/main/java/com/itsaky/androidide/inflater/internal/adapters/AdapterViewAdapter.kt @@ -36,7 +36,11 @@ abstract class AdapterViewAdapter> : ViewGroupAdapter() { override fun applyBasic(view: IView) { super.applyBasic(view) - (view.view as AdapterView).adapter = newSimpleAdapter(view.view.context) + // The adapter type argument is erased, so no cast can check it. The ArrayAdapter below is both a + // ListAdapter and a SpinnerAdapter, which every platform AdapterView accepts. + @Suppress("UNCHECKED_CAST") + val adapterView = view.view as AdapterView + adapterView.adapter = newSimpleAdapter(view.view.context) if (view is ViewGroupImpl) { view.childrenModifiable = false } From f3bcc8e4d7b80a841e79b87c7d3f1605b3888034 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 09:55:27 -0800 Subject: [PATCH 05/10] ADFA-7201: Clear the javac deprecation notes in xml-inflater, lsp/java and app Found with -Xlint:deprecation on each module's compileV8DebugJavaWithJavac. - app: two layouts used androidx.legacy.widget.Space, a copy of the platform Space kept for API levels below 14. They now use Space. - xml-inflater: VectorMasterDrawable's getOpacity() override is marked @Deprecated like the abstract method it must implement. The KSP- generated ViewAdapterIndexImpl suppresses deprecation, since it registers adapters for deprecated widgets (AbsoluteLayout, AnalogClock, DigitalClock) that layouts can still use. The generator also names List::class instead of java.util.List::class, which Kotlin warns about. - lsp/java: AnalyzeTimer passes Looper.myLooper() to Handler explicitly, the choice Handler() made implicitly. FindCompletionsAt reads the case expression once, under a suppression: the vendored javac deprecates getExpression() and its replacement getExpressions() alike. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../ksp/inflater/ViewAdapterIndexGenerator.kt | 12 ++++++++++-- .../main/res/layout/debugger_variable_item.xml | 6 +++--- .../res/layout/layout_editor_bottom_sheet.xml | 2 +- .../androidide/lsp/java/utils/AnalyzeTimer.java | 5 ++++- .../lsp/java/visitors/FindCompletionsAt.java | 15 ++++++++++----- .../vectormaster/VectorMasterDrawable.java | 2 ++ 6 files changed, 30 insertions(+), 12 deletions(-) diff --git a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt index d3c8e2dd94..7f02ec046d 100644 --- a/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt +++ b/annotation-processors-ksp/src/main/kotlin/com/itsaky/androidide/annotations/ksp/inflater/ViewAdapterIndexGenerator.kt @@ -28,6 +28,7 @@ import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSType import com.itsaky.androidide.annotations.inflater.ViewAdapter import com.itsaky.androidide.annotations.uidesigner.IncludeInDesigner +import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.FieldSpec @@ -56,7 +57,14 @@ class ViewAdapterIndexGenerator( private val indexClassBuilder = TypeSpec .classBuilder(INDEX_CLASS_NAME) - .addModifiers(PUBLIC, FINAL) + // The index registers adapters for deprecated platform widgets (AbsoluteLayout, AnalogClock, + // DigitalClock) that layouts can still use. + .addAnnotation( + AnnotationSpec + .builder(SuppressWarnings::class.java) + .addMember("value", "\$S", "deprecation") + .build(), + ).addModifiers(PUBLIC, FINAL) .addSuperinterface(viewAdapterInterface) private val indexAddStatements = CodeBlock.builder() @@ -124,7 +132,7 @@ class ViewAdapterIndexGenerator( ) val listOfViewAdapters = - ParameterizedTypeName.get(ClassName.get(java.util.List::class.java), adapterType) + ParameterizedTypeName.get(ClassName.get(List::class.java), adapterType) val mapOfGroupToListOfViewAdapter = ParameterizedTypeName.get( ClassName.get(Map::class.java), diff --git a/app/src/main/res/layout/debugger_variable_item.xml b/app/src/main/res/layout/debugger_variable_item.xml index f2206b1af0..6decdd43d7 100644 --- a/app/src/main/res/layout/debugger_variable_item.xml +++ b/app/src/main/res/layout/debugger_variable_item.xml @@ -18,7 +18,7 @@ app:layout_constraintTop_toTopOf="parent" app:tint="?attr/colorPrimary" /> - - - - Date: Sun, 22 Nov 2026 09:55:27 -0800 Subject: [PATCH 06/10] ADFA-7201: Fix the Gradle 9 deprecations our own build scripts cause - settings.gradle.kts included :compose-preview, whose directory left the tree when ADFA-3598 moved the preview into a plugin. Gradle 9 fails on a missing project directory. - build-info's generateBuildInfo and tooling-api-impl's copyJar called Task.project in their actions. They now take the project, or the directory provider, while configuring. The remaining Gradle 9 deprecations come from third-party plugins: the Android Gradle plugin's own DSL classes (isCrunchPngs, isUseProguard, isWearAppUnbundled), gradle-maven-publish-plugin 0.27.0's publishToMavenCentral (StartParameter.isConfigurationCacheRequested) and Shadow 8.1.1's ShadowCopyAction (FileTreeElement.getMode). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- build-info/build.gradle.kts | 6 ++++-- settings.gradle.kts | 1 - subprojects/tooling-api-impl/build.gradle.kts | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/build-info/build.gradle.kts b/build-info/build.gradle.kts index 738c794c11..768ff3534d 100644 --- a/build-info/build.gradle.kts +++ b/build-info/build.gradle.kts @@ -47,6 +47,8 @@ tasks.create("generateBuildInfo") { val buildInfoPath = "com/itsaky/androidide/buildinfo/BuildInfo.java" val buildInfo = buildInfoGenDir.get().file(buildInfoPath) val buildInfoIn = project.file("src/main/java/$buildInfoPath.in") + // Task.project is deprecated at execution time, so take it while configuring. + val gitProject = project doLast { buildInfoIn.replaceContents( @@ -66,8 +68,8 @@ tasks.create("generateBuildInfo") { "FDROID_BUILD_VERSION_NAME" to (FDroidConfig.fDroidVersionName ?: "null"), "FDROID_BUILD_VERSION_CODE" to (FDroidConfig.fDroidVersionCode ?: -1).toString(), "CI_BUILD" to CI.isCiBuild.toString(), - "CI_GIT_BRANCH" to CI.branchName(project), - "CI_COMMIT_HASH" to CI.commitHash(project), + "CI_GIT_BRANCH" to CI.branchName(gitProject), + "CI_COMMIT_HASH" to CI.commitHash(gitProject), "REPO_HOST" to ProjectConfig.REPO_HOST, "REPO_OWNER" to ProjectConfig.REPO_OWNER, "REPO_NAME" to ProjectConfig.REPO_NAME, diff --git a/settings.gradle.kts b/settings.gradle.kts index 9f1934fb77..6f93869d15 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -190,7 +190,6 @@ include( ":plugin-api", ":plugin-api:plugin-builder", ":plugin-manager", - ":compose-preview", ":floating-window", ) diff --git a/subprojects/tooling-api-impl/build.gradle.kts b/subprojects/tooling-api-impl/build.gradle.kts index da2c16cf09..435ce9c732 100644 --- a/subprojects/tooling-api-impl/build.gradle.kts +++ b/subprojects/tooling-api-impl/build.gradle.kts @@ -37,9 +37,9 @@ tasks.register("deleteExistingJarFiles") { } tasks.register("copyJar") { + // Task.project is deprecated at execution time, so resolve the directory while configuring. + val libsDir = project.layout.buildDirectory.dir("libs") doLast { - val libsDir = project.layout.buildDirectory.dir("libs") - copy { from(libsDir) into(libsDir) From 1cf703b628bbe0cd9b787afb6d0196100cf71338 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 10:44:03 -0800 Subject: [PATCH 07/10] ADFA-7201: style: spotless reformat, no functional change Brings the files the warning fixes touch under the Spotless ratchet first, so the fix commits that follow show only the fixes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../tasks/AddBrotliFileToAssetsTask.kt | 39 +- .../plugins/tasks/AddExternalAssetTask.kt | 174 ++-- .../tasks/GradleWrapperGeneratorTask.kt | 96 ++- .../plugins/tasks/IDEWrapperGenerator.java | 802 +++++++++--------- 4 files changed, 548 insertions(+), 563 deletions(-) diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt index 2a6723079d..a97954ec7c 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt @@ -26,23 +26,28 @@ import java.io.File * Adds the provided file to assets in brotli compressed form. */ abstract class AddBrotliFileToAssetsTask : AddFileToAssetsTask() { - override fun doCopy(inFile: File, outFile: File) { - val brotliOut = File(outFile.path + ".br") - Brotli4jLoader.ensureAvailability() + override fun doCopy( + inFile: File, + outFile: File, + ) { + val brotliOut = File(outFile.path + ".br") + Brotli4jLoader.ensureAvailability() - val start = System.nanoTime() - val params = Encoder.Parameters() - .setQuality(11) - .setWindow(24) + val start = System.nanoTime() + val params = + Encoder + .Parameters() + .setQuality(11) + .setWindow(24) - BrotliOutputStream(brotliOut.outputStream(), params).use { out -> - inFile.inputStream().use { input -> - input.copyTo(out) - } - } + BrotliOutputStream(brotliOut.outputStream(), params).use { out -> + inFile.inputStream().use { input -> + input.copyTo(out) + } + } - val end = System.nanoTime() - val durationMs = (end - start) / (1_000_000) - project.logger.lifecycle("brotli time: ${durationMs}ms") - } -} \ No newline at end of file + val end = System.nanoTime() + val durationMs = (end - start) / (1_000_000) + project.logger.lifecycle("brotli time: ${durationMs}ms") + } +} diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt index a47cf0e933..29e9b5b4a5 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt @@ -22,93 +22,91 @@ import java.security.MessageDigest * @author Akash Yadav */ abstract class AddExternalAssetTask : DefaultTask() { - - /** - * The asset to be added. - */ - @get:Input - abstract val asset: Property - - /** - * The directory where the asset should be cached. - */ - @get:InputDirectory - abstract val cacheDir: DirectoryProperty - - /** - * The directory where the asset should be added. Optional only for JAR dependency assets. - */ - @get:OutputDirectory - @get:Optional - abstract val outputDir: DirectoryProperty - - @TaskAction - fun addAsset() { - val asset = asset.get() - val cacheDir = cacheDir.asFile.get().also { it.mkdirs() } - val cachedFile = asset.fetchSourceInto(cacheDir) - - if (asset is ExternalJarDependencyConfiguration) { - // no need to process further - return - } - - val outputDir = outputDir.asFile.get() - val destFile = asset.resolveDestFile(outputDir) - val destDir = destFile.parentFile!! - if (!destDir.exists() && !destDir.mkdirs()) { - throw IllegalStateException("Unable to create directory $destDir") - } - - val digest = MessageDigest.getInstance("SHA-256") - if (destFile.exists()) { - if (digest.sha256(cachedFile) != digest.sha256(destFile)) { - logger.quiet("Checksum mismatch. Deleting {}.", destFile) - destFile.delete() - } else { - logger.quiet("Asset {} already exists.", destFile) - return - } - } - - cachedFile.copyTo(destFile) - } - - private fun AssetConfiguration.fetchSourceInto( - cacheDir: File, - ): File = when (this.source) { - is AssetSource.External -> fetchExternalSourceInto(cacheDir) - } - - private fun AssetConfiguration.fetchExternalSourceInto( - cacheDir: File - ): File { - val source = this.source as AssetSource.External - val dest = this.resolveCacheFile(cacheDir) - val destDir = dest.parentFile!! - if (!destDir.exists() && !destDir.mkdirs()) { - throw IllegalStateException("Unable to create directory $destDir") - } - - DownloadUtils.downloadFile( - url = source.url.toURL(), - destination = dest, - sha256Checksum = source.sha256Checksum, - logger = project.logger - ) - - return dest - } + /** + * The asset to be added. + */ + @get:Input + abstract val asset: Property + + /** + * The directory where the asset should be cached. + */ + @get:InputDirectory + abstract val cacheDir: DirectoryProperty + + /** + * The directory where the asset should be added. Optional only for JAR dependency assets. + */ + @get:OutputDirectory + @get:Optional + abstract val outputDir: DirectoryProperty + + @TaskAction + fun addAsset() { + val asset = asset.get() + val cacheDir = cacheDir.asFile.get().also { it.mkdirs() } + val cachedFile = asset.fetchSourceInto(cacheDir) + + if (asset is ExternalJarDependencyConfiguration) { + // no need to process further + return + } + + val outputDir = outputDir.asFile.get() + val destFile = asset.resolveDestFile(outputDir) + val destDir = destFile.parentFile!! + if (!destDir.exists() && !destDir.mkdirs()) { + throw IllegalStateException("Unable to create directory $destDir") + } + + val digest = MessageDigest.getInstance("SHA-256") + if (destFile.exists()) { + if (digest.sha256(cachedFile) != digest.sha256(destFile)) { + logger.quiet("Checksum mismatch. Deleting {}.", destFile) + destFile.delete() + } else { + logger.quiet("Asset {} already exists.", destFile) + return + } + } + + cachedFile.copyTo(destFile) + } + + private fun AssetConfiguration.fetchSourceInto(cacheDir: File): File = + when (this.source) { + is AssetSource.External -> fetchExternalSourceInto(cacheDir) + } + + private fun AssetConfiguration.fetchExternalSourceInto(cacheDir: File): File { + val source = this.source as AssetSource.External + val dest = this.resolveCacheFile(cacheDir) + val destDir = dest.parentFile!! + if (!destDir.exists() && !destDir.mkdirs()) { + throw IllegalStateException("Unable to create directory $destDir") + } + + DownloadUtils.downloadFile( + url = source.url.toURL(), + destination = dest, + sha256Checksum = source.sha256Checksum, + logger = project.logger, + ) + + return dest + } } -private fun AssetConfiguration.resolveDestFile(outputDir: File): File = when(this) { - is RawAssetConfiguration -> outputDir.resolve(this.assetPath) - is JniLibAssetConfiguration -> outputDir.resolve("${this.abi.abi}/lib${this.libName}.so") - is ExternalJarDependencyConfiguration -> outputDir.resolve(this.jarName) -} - -private fun AssetConfiguration.resolveCacheFile(cacheDir: File): File = when (this) { - is RawAssetConfiguration -> cacheDir.resolve(this.assetPath) - is JniLibAssetConfiguration -> cacheDir.resolve("lib${this.libName}_${this.abi.abi}.so") - is ExternalJarDependencyConfiguration -> cacheDir.resolve(this.jarName) -} +private fun AssetConfiguration.resolveDestFile(outputDir: File): File = + when (this) { + is RawAssetConfiguration -> outputDir.resolve(this.assetPath) + is JniLibAssetConfiguration -> outputDir.resolve("${this.abi.abi}/lib${this.libName}.so") + is ExternalJarDependencyConfiguration -> outputDir.resolve(this.jarName) + } + +private fun AssetConfiguration.resolveCacheFile(cacheDir: File): File = + when (this) { + is RawAssetConfiguration -> cacheDir.resolve(this.assetPath) + is JniLibAssetConfiguration -> cacheDir.resolve("lib${this.libName}_${this.abi.abi}.so") + is ExternalJarDependencyConfiguration -> cacheDir.resolve(this.jarName) + } diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt index 12415d0b38..05c72fa96f 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt @@ -33,58 +33,62 @@ import java.util.zip.ZipOutputStream * @author Akash Yadav */ abstract class GradleWrapperGeneratorTask : DefaultTask() { + /** + * The output directory. + */ + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty - /** - * The output directory. - */ - @get:OutputDirectory - abstract val outputDirectory: DirectoryProperty + // TODO change gradle version to constants.LOCAL_GRADLE_DISTRIBUTION_VERSION + @TaskAction + fun generateGradleWrapperZip() { + val outputDirectory = + this.outputDirectory + .get() + .file("data/common") + .asFile + outputDirectory.mkdirs() - //TODO change gradle version to constants.LOCAL_GRADLE_DISTRIBUTION_VERSION - @TaskAction - fun generateGradleWrapperZip() { - val outputDirectory = this.outputDirectory.get().file("data/common").asFile - outputDirectory.mkdirs() + val destFile = outputDirectory.resolve("gradle-wrapper.zip") - val destFile = outputDirectory.resolve("gradle-wrapper.zip") + if (destFile.exists()) { + destFile.delete() + } - if (destFile.exists()) { - destFile.delete() - } + val stagingDir = File(outputDirectory, "staging") + if (stagingDir.exists()) { + stagingDir.deleteRecursively() + } + stagingDir.mkdirs() - val stagingDir = File(outputDirectory, "staging") - if (stagingDir.exists()) { - stagingDir.deleteRecursively() - } - stagingDir.mkdirs() + // Generate the files + val generator = IDEWrapperGenerator() + generator.jarFile = File(stagingDir, "gradle/wrapper/gradle-wrapper.jar") + generator.scriptFile = File(stagingDir, "gradlew") + generator.gradleVersion = GRADLE_DISTRIBUTION_VERSION + generator.distributionType = Wrapper.DistributionType.BIN - // Generate the files - val generator = IDEWrapperGenerator() - generator.jarFile = File(stagingDir, "gradle/wrapper/gradle-wrapper.jar") - generator.scriptFile = File(stagingDir, "gradlew") - generator.gradleVersion = GRADLE_DISTRIBUTION_VERSION - generator.distributionType = Wrapper.DistributionType.BIN + generator.generate(project) - generator.generate(project) + // Archive all generated files + ZipOutputStream(destFile.outputStream().buffered()).use { zipOut -> + stagingDir + .walk(direction = FileWalkDirection.TOP_DOWN) + .filter { it.isFile } + .forEach { file -> + if (file.name != "gradlew.bat") { + val entry = ZipEntry(file.relativeTo(stagingDir).path) + zipOut.putNextEntry(entry) + file.inputStream().buffered().use { fileInStream -> + fileInStream.transferTo(zipOut) + } + } + } - // Archive all generated files - ZipOutputStream(destFile.outputStream().buffered()).use { zipOut -> - stagingDir.walk(direction = FileWalkDirection.TOP_DOWN) - .filter { it.isFile } - .forEach { file -> - if (file.name != "gradlew.bat") { - val entry = ZipEntry(file.relativeTo(stagingDir).path) - zipOut.putNextEntry(entry) - file.inputStream().buffered().use { fileInStream -> - fileInStream.transferTo(zipOut) - } - } - } + zipOut.flush() + } - zipOut.flush() - } - - // finally, delete the staging directory - stagingDir.deleteRecursively() - } -} \ No newline at end of file + // finally, delete the staging directory + stagingDir.deleteRecursively() + } +} diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java index 34dcd87fcb..0c8c3271d5 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java @@ -35,7 +35,17 @@ import com.itsaky.androidide.plugins.tasks.internal.WrapperDefaults; import com.itsaky.androidide.plugins.tasks.internal.WrapperGenerator; - +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import javax.annotation.Nullable; +import javax.inject.Inject; +import kotlin.io.FilesKt; import org.gradle.api.GradleException; import org.gradle.api.Incubating; import org.gradle.api.Project; @@ -55,421 +65,389 @@ import org.gradle.wrapper.Logger; import org.gradle.wrapper.WrapperExecutor; -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import javax.annotation.Nullable; -import javax.inject.Inject; - -import kotlin.io.FilesKt; - /** - *

Generates scripts (for *nix and windows) which allow you to build your project with Gradle, - * without having to install Gradle. + *

+ * Generates scripts (for *nix and windows) which allow you to build your project with Gradle, without having to install Gradle. * - *

When a user executes a wrapper script the first time, the script downloads and installs the - * appropriate Gradle distribution and runs the build against this downloaded distribution. Any - * installed Gradle distribution is ignored when using the wrapper scripts. + *

+ * When a user executes a wrapper script the first time, the script downloads and installs the appropriate Gradle distribution and runs the build against this downloaded distribution. Any installed Gradle distribution is ignored when using the wrapper scripts. * - *

The scripts generated by this task are intended to be committed to your version control - * system. This task also generates a small {@code gradle-wrapper.jar} bootstrap JAR file and - * properties file which should also be committed to your VCS. The scripts delegates to this JAR. + *

+ * The scripts generated by this task are intended to be committed to your version control system. This task also generates a small {@code gradle-wrapper.jar} bootstrap JAR file and properties file which should also be committed to your VCS. The scripts delegates to this JAR. */ public class IDEWrapperGenerator { - public static final String DEFAULT_DISTRIBUTION_PARENT_NAME = WrapperDefaults.DISTRIBUTION_PATH; - - private File scriptFile = new File(WrapperDefaults.SCRIPT_PATH); - private File jarFile = new File(WrapperDefaults.JAR_FILE_PATH); - private String distributionPath = DEFAULT_DISTRIBUTION_PARENT_NAME; - private PathBase distributionBase = WrapperDefaults.DISTRIBUTION_BASE; - private String distributionUrl; - private String distributionSha256Sum; - private final GradleVersionResolver gradleVersionResolver = new GradleVersionResolver(); - private DistributionType distributionType = WrapperDefaults.DISTRIBUTION_TYPE; - private String archivePath = WrapperDefaults.ARCHIVE_PATH; - private PathBase archiveBase = WrapperDefaults.ARCHIVE_BASE; - private final int networkTimeout = WrapperDefaults.NETWORK_TIMEOUT; - private boolean distributionUrlConfigured = false; - - void generate(Project project) { - final var isOffline = project.getGradle().getStartParameter().isOffline(); - File jarFileDestination = getJarFile(); - File unixScript = getScriptFile(); - File propertiesFile = getPropertiesFile(); - Properties existingProperties = - propertiesFile.exists() ? GUtil.loadProperties(propertiesFile) : null; - - checkProperties(existingProperties); - validateDistributionUrl(propertiesFile.getParentFile(), isOffline); - - WrapperGenerator.generate(archiveBase, archivePath, distributionBase, distributionPath, - getDistributionSha256Sum(existingProperties), propertiesFile, jarFileDestination, - FilesKt.relativeTo(jarFileDestination, unixScript.getParentFile()).getPath(), unixScript, getBatchScript(), getDistributionUrl(), - getValidateDistributionUrl(), networkTimeout); - } - - private void checkProperties(Properties existingProperties) { - String checksumProperty = existingProperties != null ? existingProperties.getProperty( - WrapperExecutor.DISTRIBUTION_SHA_256_SUM, null) : null; - - if (!isCurrentVersion() && distributionSha256Sum == null && checksumProperty != null) { - throw new GradleException( - "gradle-wrapper.properties contains distributionSha256Sum property, but the wrapper configuration does not have one. Specify one in the wrapper task configuration or with the --gradle-distribution-sha256-sum task option"); - } - } - - private static final String DISTRIBUTION_URL_EXCEPTION_MESSAGE = "Test of distribution url %s failed. Please check the values set with --gradle-distribution-url and --gradle-version."; - - private void validateDistributionUrl(File uriRoot, boolean isOffline) { - if (distributionUrlConfigured && getValidateDistributionUrl()) { - String url = getDistributionUrl(); - URI uri = getDistributionUri(uriRoot, url); - if (uri.getScheme().equals("file")) { - if (!Files.exists(Paths.get(uri).toAbsolutePath())) { - throw new UncheckedIOException(String.format(DISTRIBUTION_URL_EXCEPTION_MESSAGE, url)); - } - } else if (uri.getScheme().startsWith("http") && !isOffline) { - try { - new Download(new Logger(true), "gradlew", Download.UNKNOWN_VERSION).sendHeadRequest(uri); - } catch (Exception e) { - throw new UncheckedIOException(String.format(DISTRIBUTION_URL_EXCEPTION_MESSAGE, url), e); - } - } - } - } - - private static URI getDistributionUri(File uriRoot, String url) { - try { - return WrapperDistributionUrlConverter.convertDistributionUrl(url, uriRoot); - } catch (URISyntaxException e) { - throw new GradleException("Distribution URL String cannot be parsed: " + url, e); - } - } - - private String getDistributionSha256Sum(Properties existingProperties) { - if (distributionSha256Sum != null) { - return distributionSha256Sum; - } else if (isCurrentVersion() && existingProperties != null) { - return existingProperties.getProperty(WrapperExecutor.DISTRIBUTION_SHA_256_SUM, null); - } else { - return null; - } - } - - private boolean isCurrentVersion() { - return GradleVersion.current().equals(gradleVersionResolver.getGradleVersion()); - } - - /** - * Returns the file to write the wrapper script to. - */ - - public File getScriptFile() { - return scriptFile; - } - - /** - * The file to write the wrapper script to. - * - * @since 4.0 - */ - public void setScriptFile(File scriptFile) { - this.scriptFile = scriptFile; - } - - /** - * Returns the file to write the wrapper batch script to. - */ - - public File getBatchScript() { - return WrapperGenerator.getBatchScript(getScriptFile()); - } - - /** - * Returns the file to write the wrapper jar file to. - */ - - public File getJarFile() { - return this.jarFile; - } - - /** - * The file to write the wrapper jar file to. - * - * @since 4.0 - */ - public void setJarFile(File jarFile) { - this.jarFile = jarFile; - } - - /** - * Returns the file to write the wrapper properties to. - */ - - public File getPropertiesFile() { - return WrapperGenerator.getPropertiesFile(getJarFile()); - } - - /** - * Returns the path where the gradle distributions needed by the wrapper are unzipped. The path is - * relative to the distribution base directory - * - * @see #setDistributionPath(String) - */ - - public String getDistributionPath() { - return distributionPath; - } - - /** - * Sets the path where the gradle distributions needed by the wrapper are unzipped. The path is - * relative to the distribution base directory - * - * @see #setDistributionPath(String) - */ - public void setDistributionPath(String distributionPath) { - this.distributionPath = distributionPath; - } - - /** - * Set Wrapper versions resources. - * - * @since 8.1 - */ - @Incubating - public void setWrapperVersionsResources(WrapperVersionsResources wrapperVersionsResources) { - DefaultWrapperVersionsResources defaultWrapperVersionsResources = (DefaultWrapperVersionsResources) wrapperVersionsResources; - gradleVersionResolver.setTextResources(defaultWrapperVersionsResources.getLatest(), - defaultWrapperVersionsResources.getReleaseCandidate(), - defaultWrapperVersionsResources.getNightly(), - defaultWrapperVersionsResources.getReleaseNightly()); - } - - /** - * Returns the gradle version for the wrapper. - * - * @throws GradleException if the label that can be provided via {@link #setGradleVersion(String)} - * can not be resolved at the moment. For example, there is not a - * `release-candidate` available at all times. - * @see #setGradleVersion(String) - */ - - public String getGradleVersion() { - return gradleVersionResolver.getGradleVersion().getVersion(); - } - - /** - * The version of the gradle distribution required by the wrapper. This is usually the same - * version of Gradle you use for building your project. The following labels are allowed to - * specify a version: {@code latest}, {@code release-candidate}, {@code nightly}, and - * {@code release-nightly} - * - *

The resulting distribution url is validated before it is written to the - * gradle-wrapper.properties file. - */ - @Option(option = "gradle-version", description = - "The version of the Gradle distribution required by the wrapper. " - + "The following labels are allowed: latest, release-candidate, nightly, and release-nightly.") - public void setGradleVersion(String gradleVersion) { - distributionUrlConfigured = true; - this.gradleVersionResolver.setGradleVersionString(gradleVersion); - } - - /** - * Returns the type of the Gradle distribution to be used by the wrapper. - * - * @see #setDistributionType(DistributionType) - */ - - public DistributionType getDistributionType() { - return distributionType; - } - - /** - * The type of the Gradle distribution to be used by the wrapper. By default, this is - * {@link DistributionType#BIN}, which is the binary-only Gradle distribution without - * documentation. - * - * @see DistributionType - */ - @Option(option = "distribution-type", description = "The type of the Gradle distribution to be used by the wrapper.") - public void setDistributionType(DistributionType distributionType) { - this.distributionType = distributionType; - } - - /** - * The list of available gradle distribution types. - */ - @OptionValues("distribution-type") - public List getAvailableDistributionTypes() { - return Arrays.asList(DistributionType.values()); - } - - /** - * The URL to download the gradle distribution from. - * - *

If not set, the download URL is the default for the specified {@link #getGradleVersion()}. - * - *

If {@link #getGradleVersion()} is not set, will return null. - * - *

The wrapper downloads a certain distribution only once and caches it. If your distribution - * base is the project, you might submit the distribution to your version control system. That way - * no download is necessary at all. This might be in particular interesting, if you provide a - * custom gradle snapshot to the wrapper, because you don't need to provide a download server - * then. - */ - - public String getDistributionUrl() { - if (distributionUrl != null) { - return distributionUrl; - } - - return WrapperGenerator.getDistributionUrl(gradleVersionResolver.getGradleVersion(), - distributionType); - } - - /** - * The URL to download the gradle distribution from. - * - *

If not set, the download URL is the default for the specified {@link #getGradleVersion()}. - * - *

If {@link #getGradleVersion()} is not set, will return null. - * - *

The wrapper downloads a certain distribution and caches it. If your distribution base is - * the project, you might submit the distribution to your version control system. That way no - * download is necessary at all. This might be in particular interesting, if you provide a custom - * gradle snapshot to the wrapper, because you don't need to provide a download server then. - * - *

The distribution url is validated before it is written to the gradle-wrapper.properties - * file. - */ - @Option(option = "gradle-distribution-url", description = "The URL to download the Gradle distribution from.") - public void setDistributionUrl(String url) { - distributionUrlConfigured = true; - this.distributionUrl = url; - } - - /** - * The SHA-256 hash sum of the gradle distribution. - * - *

If not set, the hash sum of the gradle distribution is not verified. - * - *

The wrapper allows for verification of the downloaded Gradle distribution via SHA-256 hash - * sum comparison. This increases security against targeted attacks by preventing a - * man-in-the-middle attacker from tampering with the downloaded Gradle distribution. - * - * @since 4.5 - */ - @Nullable - @Optional - - public String getDistributionSha256Sum() { - return distributionSha256Sum; - } - - /** - * The SHA-256 hash sum of the gradle distribution. - * - *

If not set, the hash sum of the gradle distribution is not verified. - * - *

The wrapper allows for verification of the downloaded Gradle distribution via SHA-256 hash - * sum comparison. This increases security against targeted attacks by preventing a - * man-in-the-middle attacker from tampering with the downloaded Gradle distribution. - * - * @since 4.5 - */ - @Option(option = "gradle-distribution-sha256-sum", description = "The SHA-256 hash sum of the gradle distribution.") - public void setDistributionSha256Sum(@Nullable String distributionSha256Sum) { - this.distributionSha256Sum = distributionSha256Sum; - } - - /** - * The distribution base specifies whether the unpacked wrapper distribution should be stored in - * the project or in the gradle user home dir. - */ - - public PathBase getDistributionBase() { - return distributionBase; - } - - /** - * The distribution base specifies whether the unpacked wrapper distribution should be stored in - * the project or in the gradle user home dir. - */ - public void setDistributionBase(PathBase distributionBase) { - this.distributionBase = distributionBase; - } - - /** - * Returns the path where the gradle distributions archive should be saved (i.e. the parent dir). - * The path is relative to the archive base directory. - */ - - public String getArchivePath() { - return archivePath; - } - - /** - * Set's the path where the gradle distributions archive should be saved (i.e. the parent dir). - * The path is relative to the parent dir specified with {@link #getArchiveBase()}. - */ - public void setArchivePath(String archivePath) { - this.archivePath = archivePath; - } - - /** - * The archive base specifies whether the unpacked wrapper distribution should be stored in the - * project or in the gradle user home dir. - */ - - public PathBase getArchiveBase() { - return archiveBase; - } - - /** - * The archive base specifies whether the unpacked wrapper distribution should be stored in the - * project or in the gradle user home dir. - */ - public void setArchiveBase(PathBase archiveBase) { - this.archiveBase = archiveBase; - } - - /** - * The network timeout specifies how many ms to wait for when the wrapper is performing network - * operations, such as downloading the wrapper jar. - * - * @since 7.6 - */ - - @Incubating - @Optional - @Option(option = "network-timeout", description = "Timeout in ms to use when the wrapper is performing network operations.") - public Integer getNetworkTimeout() { - return networkTimeout; - } - - /** - * Indicates if this task will validate the distribution url that has been configured. - * - * @return whether this task will validate the distribution url - * @since 8.2 - */ - @Incubating - - @Option(option = "validate-url", description = "Sets task to validate the configured distribution url.") - public Boolean getValidateDistributionUrl() { - return Boolean.parseBoolean(System.getProperty("androidide.wrapper.validateUrl", "false")); - } - - @Inject - protected FileLookup getFileLookup() { - throw new UnsupportedOperationException(); - } + public static final String DEFAULT_DISTRIBUTION_PARENT_NAME = WrapperDefaults.DISTRIBUTION_PATH; + + private static final String DISTRIBUTION_URL_EXCEPTION_MESSAGE = "Test of distribution url %s failed. Please check the values set with --gradle-distribution-url and --gradle-version."; + + private static URI getDistributionUri(File uriRoot, String url) { + try { + return WrapperDistributionUrlConverter.convertDistributionUrl(url, uriRoot); + } catch (URISyntaxException e) { + throw new GradleException("Distribution URL String cannot be parsed: " + url, e); + } + } + + private File scriptFile = new File(WrapperDefaults.SCRIPT_PATH); + private File jarFile = new File(WrapperDefaults.JAR_FILE_PATH); + private String distributionPath = DEFAULT_DISTRIBUTION_PARENT_NAME; + private PathBase distributionBase = WrapperDefaults.DISTRIBUTION_BASE; + private String distributionUrl; + private String distributionSha256Sum; + private final GradleVersionResolver gradleVersionResolver = new GradleVersionResolver(); + private DistributionType distributionType = WrapperDefaults.DISTRIBUTION_TYPE; + private String archivePath = WrapperDefaults.ARCHIVE_PATH; + private PathBase archiveBase = WrapperDefaults.ARCHIVE_BASE; + + private final int networkTimeout = WrapperDefaults.NETWORK_TIMEOUT; + + private boolean distributionUrlConfigured = false; + + /** + * The archive base specifies whether the unpacked wrapper distribution should be stored in the project or in the gradle user home dir. + */ + + public PathBase getArchiveBase() { + return archiveBase; + } + + /** + * Returns the path where the gradle distributions archive should be saved (i.e. the parent dir). The path is relative to the archive base directory. + */ + + public String getArchivePath() { + return archivePath; + } + + /** + * The list of available gradle distribution types. + */ + @OptionValues("distribution-type") + public List getAvailableDistributionTypes() { + return Arrays.asList(DistributionType.values()); + } + + /** + * Returns the file to write the wrapper batch script to. + */ + + public File getBatchScript() { + return WrapperGenerator.getBatchScript(getScriptFile()); + } + + /** + * The distribution base specifies whether the unpacked wrapper distribution should be stored in the project or in the gradle user home dir. + */ + + public PathBase getDistributionBase() { + return distributionBase; + } + + /** + * Returns the path where the gradle distributions needed by the wrapper are unzipped. The path is relative to the distribution base directory + * + * @see #setDistributionPath(String) + */ + + public String getDistributionPath() { + return distributionPath; + } + + /** + * The SHA-256 hash sum of the gradle distribution. + * + *

+ * If not set, the hash sum of the gradle distribution is not verified. + * + *

+ * The wrapper allows for verification of the downloaded Gradle distribution via SHA-256 hash sum comparison. This increases security against targeted attacks by preventing a man-in-the-middle attacker from tampering with the downloaded Gradle distribution. + * + * @since 4.5 + */ + @Nullable + @Optional + + public String getDistributionSha256Sum() { + return distributionSha256Sum; + } + + /** + * Returns the type of the Gradle distribution to be used by the wrapper. + * + * @see #setDistributionType(DistributionType) + */ + + public DistributionType getDistributionType() { + return distributionType; + } + + /** + * The URL to download the gradle distribution from. + * + *

+ * If not set, the download URL is the default for the specified {@link #getGradleVersion()}. + * + *

+ * If {@link #getGradleVersion()} is not set, will return null. + * + *

+ * The wrapper downloads a certain distribution only once and caches it. If your distribution base is the project, you might submit the distribution to your version control system. That way no download is necessary at all. This might be in particular interesting, if you provide a custom gradle snapshot to the wrapper, because you don't need to provide a download server then. + */ + + public String getDistributionUrl() { + if (distributionUrl != null) { + return distributionUrl; + } + + return WrapperGenerator.getDistributionUrl(gradleVersionResolver.getGradleVersion(), + distributionType); + } + + /** + * Returns the gradle version for the wrapper. + * + * @throws GradleException + * if the label that can be provided via {@link #setGradleVersion(String)} can not be resolved at the moment. For example, there is not a `release-candidate` available at all times. + * @see #setGradleVersion(String) + */ + + public String getGradleVersion() { + return gradleVersionResolver.getGradleVersion().getVersion(); + } + + /** + * Returns the file to write the wrapper jar file to. + */ + + public File getJarFile() { + return this.jarFile; + } + + /** + * The network timeout specifies how many ms to wait for when the wrapper is performing network operations, such as downloading the wrapper jar. + * + * @since 7.6 + */ + + @Incubating + @Optional + @Option(option = "network-timeout", description = "Timeout in ms to use when the wrapper is performing network operations.") + public Integer getNetworkTimeout() { + return networkTimeout; + } + + /** + * Returns the file to write the wrapper properties to. + */ + + public File getPropertiesFile() { + return WrapperGenerator.getPropertiesFile(getJarFile()); + } + + /** + * Returns the file to write the wrapper script to. + */ + + public File getScriptFile() { + return scriptFile; + } + + /** + * Indicates if this task will validate the distribution url that has been configured. + * + * @return whether this task will validate the distribution url + * @since 8.2 + */ + @Incubating + + @Option(option = "validate-url", description = "Sets task to validate the configured distribution url.") + public Boolean getValidateDistributionUrl() { + return Boolean.parseBoolean(System.getProperty("androidide.wrapper.validateUrl", "false")); + } + + /** + * The archive base specifies whether the unpacked wrapper distribution should be stored in the project or in the gradle user home dir. + */ + public void setArchiveBase(PathBase archiveBase) { + this.archiveBase = archiveBase; + } + + /** + * Set's the path where the gradle distributions archive should be saved (i.e. the parent dir). The path is relative to the parent dir specified with {@link #getArchiveBase()}. + */ + public void setArchivePath(String archivePath) { + this.archivePath = archivePath; + } + + /** + * The distribution base specifies whether the unpacked wrapper distribution should be stored in the project or in the gradle user home dir. + */ + public void setDistributionBase(PathBase distributionBase) { + this.distributionBase = distributionBase; + } + + /** + * Sets the path where the gradle distributions needed by the wrapper are unzipped. The path is relative to the distribution base directory + * + * @see #setDistributionPath(String) + */ + public void setDistributionPath(String distributionPath) { + this.distributionPath = distributionPath; + } + + /** + * The SHA-256 hash sum of the gradle distribution. + * + *

+ * If not set, the hash sum of the gradle distribution is not verified. + * + *

+ * The wrapper allows for verification of the downloaded Gradle distribution via SHA-256 hash sum comparison. This increases security against targeted attacks by preventing a man-in-the-middle attacker from tampering with the downloaded Gradle distribution. + * + * @since 4.5 + */ + @Option(option = "gradle-distribution-sha256-sum", description = "The SHA-256 hash sum of the gradle distribution.") + public void setDistributionSha256Sum(@Nullable String distributionSha256Sum) { + this.distributionSha256Sum = distributionSha256Sum; + } + + /** + * The type of the Gradle distribution to be used by the wrapper. By default, this is {@link DistributionType#BIN}, which is the binary-only Gradle distribution without documentation. + * + * @see DistributionType + */ + @Option(option = "distribution-type", description = "The type of the Gradle distribution to be used by the wrapper.") + public void setDistributionType(DistributionType distributionType) { + this.distributionType = distributionType; + } + + /** + * The URL to download the gradle distribution from. + * + *

+ * If not set, the download URL is the default for the specified {@link #getGradleVersion()}. + * + *

+ * If {@link #getGradleVersion()} is not set, will return null. + * + *

+ * The wrapper downloads a certain distribution and caches it. If your distribution base is the project, you might submit the distribution to your version control system. That way no download is necessary at all. This might be in particular interesting, if you provide a custom gradle snapshot to the wrapper, because you don't need to provide a download server then. + * + *

+ * The distribution url is validated before it is written to the gradle-wrapper.properties file. + */ + @Option(option = "gradle-distribution-url", description = "The URL to download the Gradle distribution from.") + public void setDistributionUrl(String url) { + distributionUrlConfigured = true; + this.distributionUrl = url; + } + + /** + * The version of the gradle distribution required by the wrapper. This is usually the same version of Gradle you use for building your project. The following labels are allowed to specify a version: {@code latest}, {@code release-candidate}, {@code nightly}, and {@code release-nightly} + * + *

+ * The resulting distribution url is validated before it is written to the gradle-wrapper.properties file. + */ + @Option(option = "gradle-version", description = "The version of the Gradle distribution required by the wrapper. " + + "The following labels are allowed: latest, release-candidate, nightly, and release-nightly.") + public void setGradleVersion(String gradleVersion) { + distributionUrlConfigured = true; + this.gradleVersionResolver.setGradleVersionString(gradleVersion); + } + + /** + * The file to write the wrapper jar file to. + * + * @since 4.0 + */ + public void setJarFile(File jarFile) { + this.jarFile = jarFile; + } + + /** + * The file to write the wrapper script to. + * + * @since 4.0 + */ + public void setScriptFile(File scriptFile) { + this.scriptFile = scriptFile; + } + + /** + * Set Wrapper versions resources. + * + * @since 8.1 + */ + @Incubating + public void setWrapperVersionsResources(WrapperVersionsResources wrapperVersionsResources) { + DefaultWrapperVersionsResources defaultWrapperVersionsResources = (DefaultWrapperVersionsResources) wrapperVersionsResources; + gradleVersionResolver.setTextResources(defaultWrapperVersionsResources.getLatest(), + defaultWrapperVersionsResources.getReleaseCandidate(), + defaultWrapperVersionsResources.getNightly(), + defaultWrapperVersionsResources.getReleaseNightly()); + } + + @Inject + protected FileLookup getFileLookup() { + throw new UnsupportedOperationException(); + } + + void generate(Project project) { + final var isOffline = project.getGradle().getStartParameter().isOffline(); + File jarFileDestination = getJarFile(); + File unixScript = getScriptFile(); + File propertiesFile = getPropertiesFile(); + Properties existingProperties = propertiesFile.exists() ? GUtil.loadProperties(propertiesFile) : null; + + checkProperties(existingProperties); + validateDistributionUrl(propertiesFile.getParentFile(), isOffline); + + WrapperGenerator.generate(archiveBase, archivePath, distributionBase, distributionPath, + getDistributionSha256Sum(existingProperties), propertiesFile, jarFileDestination, + FilesKt.relativeTo(jarFileDestination, unixScript.getParentFile()).getPath(), unixScript, getBatchScript(), getDistributionUrl(), + getValidateDistributionUrl(), networkTimeout); + } + + private void checkProperties(Properties existingProperties) { + String checksumProperty = existingProperties != null ? existingProperties.getProperty( + WrapperExecutor.DISTRIBUTION_SHA_256_SUM, null) : null; + + if (!isCurrentVersion() && distributionSha256Sum == null && checksumProperty != null) { + throw new GradleException( + "gradle-wrapper.properties contains distributionSha256Sum property, but the wrapper configuration does not have one. Specify one in the wrapper task configuration or with the --gradle-distribution-sha256-sum task option"); + } + } + + private String getDistributionSha256Sum(Properties existingProperties) { + if (distributionSha256Sum != null) { + return distributionSha256Sum; + } else if (isCurrentVersion() && existingProperties != null) { + return existingProperties.getProperty(WrapperExecutor.DISTRIBUTION_SHA_256_SUM, null); + } else { + return null; + } + } + + private boolean isCurrentVersion() { + return GradleVersion.current().equals(gradleVersionResolver.getGradleVersion()); + } + + private void validateDistributionUrl(File uriRoot, boolean isOffline) { + if (distributionUrlConfigured && getValidateDistributionUrl()) { + String url = getDistributionUrl(); + URI uri = getDistributionUri(uriRoot, url); + if (uri.getScheme().equals("file")) { + if (!Files.exists(Paths.get(uri).toAbsolutePath())) { + throw new UncheckedIOException(String.format(DISTRIBUTION_URL_EXCEPTION_MESSAGE, url)); + } + } else if (uri.getScheme().startsWith("http") && !isOffline) { + try { + new Download(new Logger(true), "gradlew", Download.UNKNOWN_VERSION).sendHeadRequest(uri); + } catch (Exception e) { + throw new UncheckedIOException(String.format(DISTRIBUTION_URL_EXCEPTION_MESSAGE, url), e); + } + } + } + } } From 72563ac4afe0a53e822a32efb21bc4501f1eb5b7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 10:59:29 -0800 Subject: [PATCH 08/10] ADFA-7201: Take the remaining Task.project calls out of task actions Gradle 9 deprecates Task.project at execution time. Review found more calls than the local runs had reached, because these tasks run only on CI, only on demand, or late in packaging: - app recompressApk (runs on CI): reads -PrecompressAbi and -PrecompressBuildName as Gradle property providers while configuring, and logs through the task's own logger. - app downloadDocDb: resolves assets/ while configuring and logs through the task's logger. - build-logic GradleWrapperGeneratorTask reads the offline flag when the task is created and hands it to IDEWrapperGenerator.generate(). AddBrotliFileToAssetsTask and AddExternalAssetTask log through the task's logger. termux-app's versionName task does the same, but it is vendored code, nothing invokes it, and it is not part of the APK build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- app/build.gradle.kts | 26 ++++++++++--------- .../tasks/AddBrotliFileToAssetsTask.kt | 2 +- .../plugins/tasks/AddExternalAssetTask.kt | 2 +- .../tasks/GradleWrapperGeneratorTask.kt | 5 +++- .../plugins/tasks/IDEWrapperGenerator.java | 4 +-- 5 files changed, 21 insertions(+), 18 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 55c5fdec0f..fb9b1c882f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -736,11 +736,13 @@ androidComponents.onVariants { variant -> } tasks.register("downloadDocDb") { + // Task.project is deprecated at execution time, so resolve the destination while configuring. + val docDbDir = rootProject.projectDir.resolve("assets") doLast { val githubRepo = "appdevforall/OfflineDocumentationTools" val latestReleaseApiUrl = "https://api.github.com/repos/$githubRepo/releases/latest" - project.logger.lifecycle("Fetching latest release metadata...") + logger.lifecycle("Fetching latest release metadata...") try { val jsonResponse = URI(latestReleaseApiUrl).toURL().readText() val jsonObject = JSONObject(jsonResponse) @@ -761,22 +763,19 @@ tasks.register("downloadDocDb") { val dbName = "documentation.db" if (assetUrl != null && assetName != null) { - val destinationPath = - project.rootProject.projectDir - .resolve("assets/$dbName") - .toPath() + val destinationPath = docDbDir.resolve(dbName).toPath() - project.logger.lifecycle("Downloading : $assetUrl as $destinationPath") + logger.lifecycle("Downloading : $assetUrl as $destinationPath") URL(assetUrl).openStream().use { input -> Files.copy(input, destinationPath, StandardCopyOption.REPLACE_EXISTING) println("Download complete: $destinationPath") } } else { - project.logger.lifecycle("No `.sqlite` asset found in the latest release.") + logger.lifecycle("No `.sqlite` asset found in the latest release.") } } catch (e: Exception) { - project.logger.lifecycle("Failed to fetch documentation.db info: ${e.message}") + logger.lifecycle("Failed to fetch documentation.db info: ${e.message}") } } } @@ -1069,6 +1068,9 @@ tasks.register("assembleAssets") { } tasks.register("recompressApk") { + // Task.project is deprecated at execution time, so read the properties while configuring. + val abiProperty = providers.gradleProperty("recompressAbi") + val buildNameProperty = providers.gradleProperty("recompressBuildName") doLast { // abi/buildName are set by the assemble finalizers below; the project // properties allow a standalone run against an already-built APK: @@ -1078,14 +1080,14 @@ tasks.register("recompressApk") { if (extraProps.has("abi")) { extraProps["abi"].toString() } else { - project.findProperty("recompressAbi")?.toString() + abiProperty.orNull ?: error("recompressApk: set -PrecompressAbi=v7|v8") } val buildName: String = if (extraProps.has("buildName")) { extraProps["buildName"].toString() } else { - project.findProperty("recompressBuildName")?.toString() + buildNameProperty.orNull ?: error("recompressApk: set -PrecompressBuildName=debug|release") } val noCompressExtensions = @@ -1098,13 +1100,13 @@ tasks.register("recompressApk") { noCompressRelease } - project.logger.lifecycle("Calling recompressApk abi:$abi buildName:$buildName") + logger.lifecycle("Calling recompressApk abi:$abi buildName:$buildName") val start = System.nanoTime() recompressApk(abi, buildName, noCompressExtensions) val durationMs = "%.2f".format((System.nanoTime() - start) / 1_000_000.0) - project.logger.lifecycle("recompressApk completed in ${durationMs}ms") + logger.lifecycle("recompressApk completed in ${durationMs}ms") } } diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt index a97954ec7c..6f586c9f6c 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddBrotliFileToAssetsTask.kt @@ -48,6 +48,6 @@ abstract class AddBrotliFileToAssetsTask : AddFileToAssetsTask() { val end = System.nanoTime() val durationMs = (end - start) / (1_000_000) - project.logger.lifecycle("brotli time: ${durationMs}ms") + logger.lifecycle("brotli time: ${durationMs}ms") } } diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt index 29e9b5b4a5..539c1c9679 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/AddExternalAssetTask.kt @@ -90,7 +90,7 @@ abstract class AddExternalAssetTask : DefaultTask() { url = source.url.toURL(), destination = dest, sha256Checksum = source.sha256Checksum, - logger = project.logger, + logger = this@AddExternalAssetTask.logger, ) return dest diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt index 05c72fa96f..56947021a0 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/GradleWrapperGeneratorTask.kt @@ -39,6 +39,9 @@ abstract class GradleWrapperGeneratorTask : DefaultTask() { @get:OutputDirectory abstract val outputDirectory: DirectoryProperty + // Read while configuring: Task.project is deprecated at execution time. + private val offline = project.gradle.startParameter.isOffline + // TODO change gradle version to constants.LOCAL_GRADLE_DISTRIBUTION_VERSION @TaskAction fun generateGradleWrapperZip() { @@ -68,7 +71,7 @@ abstract class GradleWrapperGeneratorTask : DefaultTask() { generator.gradleVersion = GRADLE_DISTRIBUTION_VERSION generator.distributionType = Wrapper.DistributionType.BIN - generator.generate(project) + generator.generate(offline) // Archive all generated files ZipOutputStream(destFile.outputStream().buffered()).use { zipOut -> diff --git a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java index 0c8c3271d5..1f7b9b569a 100644 --- a/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java +++ b/composite-builds/build-logic/plugins/src/main/java/com/itsaky/androidide/plugins/tasks/IDEWrapperGenerator.java @@ -48,7 +48,6 @@ import kotlin.io.FilesKt; import org.gradle.api.GradleException; import org.gradle.api.Incubating; -import org.gradle.api.Project; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.file.FileLookup; import org.gradle.api.tasks.Optional; @@ -393,8 +392,7 @@ protected FileLookup getFileLookup() { throw new UnsupportedOperationException(); } - void generate(Project project) { - final var isOffline = project.getGradle().getStartParameter().isOffline(); + void generate(boolean isOffline) { File jarFileDestination = getJarFile(); File unixScript = getScriptFile(); File propertiesFile = getPropertiesFile(); From 2f2a3185ed03e35ca6d18ae5f66a8d2d02ebcd9c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 10:59:29 -0800 Subject: [PATCH 09/10] ADFA-7201: Stop describing compose-preview as a module in the docs ADFA-3598 moved the Compose preview into a .cgp plugin, and this PR drops its stale include from settings.gradle.kts. ARCHITECTURE.md no longer lists it as a module, and ADR 0009 says it existed then. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- ARCHITECTURE.md | 4 ++-- docs/adr/0009-jetpack-compose-for-new-ui.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 04c6b3ecf2..cfd4c2a883 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -15,7 +15,7 @@ Feature code layers as **UI → ViewModel → Repository → data source**, with - **Data sources** — Room (`RecentProjectRoomDatabase` + DAO, `suspend` functions), raw SQLite (`SQLiteOpenHelper`, e.g. `common/.../documentation/DocumentationContentSource`), the filesystem/preferences, the embedded `tooling-api` (on-device Gradle), and external clients (Gemini via the Google GenAI SDK, on-device llama.cpp, JGit). Most are exposed through `suspend` functions. - **Repositories** — e.g. `agent/repository/GeminiRepository`, `repositories/PluginRepository`, `repositories/TemplateRepository`, `repositories/BreakpointRepository`. They wrap data sources and hide threading/IO from the ViewModel. - **ViewModels** — run work in `viewModelScope` on `Dispatchers.IO`, hold a private `MutableStateFlow`/`MutableSharedFlow`, and expose read-only `StateFlow`/`SharedFlow`. One-shot effects (toasts, navigation, dialogs) go through a separate `SharedFlow` of a sealed `*UiEffect` type. -- **UI (Fragments / Activities / Views)** — collect state in a lifecycle-aware coroutine and render it; user actions return to the ViewModel as method calls or sealed `*UiEvent` intents. The existing UI is **Android Views + Fragments + RecyclerView adapters**; new UI is Jetpack Compose ([ADR 0009](docs/adr/0009-jetpack-compose-for-new-ui.md)) — first used in the Manager screen (`ui/compose/ManagerScreen.kt`, ADFA-4928). (`compose-preview` previews the *user's* Compose code, not CoGo's own.) +- **UI (Fragments / Activities / Views)** — collect state in a lifecycle-aware coroutine and render it; user actions return to the ViewModel as method calls or sealed `*UiEvent` intents. The existing UI is **Android Views + Fragments + RecyclerView adapters**; new UI is Jetpack Compose ([ADR 0009](docs/adr/0009-jetpack-compose-for-new-ui.md)) — first used in the Manager screen (`ui/compose/ManagerScreen.kt`, ADFA-4928). (The `compose-preview` plugin, a `.cgp` since ADFA-3598, previews the *user's* Compose code, not CoGo's own.) ``` ┌─────────────────────────────────────────────┐ @@ -84,7 +84,7 @@ Strategy: **layer-and-subsystem based**, not feature-by-feature. The Gradle buil | Build engine | `subprojects:tooling-api*`, `gradle-plugin*`, `subprojects:projects`, `subprojects:builder-model-impl` | Runs a real Gradle build of the user's project out-of-process and streams events back. | | Quick Build (experimental, see [EXPERIMENTS.md](EXPERIMENTS.md)) | `quickbuild:core`, `quickbuild:daemon`, `quickbuild:protocol`, `quickbuild:runtime` | Live-reloads the user's app on every save in seconds, by running it as a generated proxy app instead of doing a full Gradle rebuild. | | Language tooling | `lsp:{api,java,kotlin,xml,external,indexing,refactor-core,ui,…}`, `lexers`, `editor*`, `editor-treesitter` | Language servers, indexing, the Sora-based editor and highlighting, and the tree-sitter document outline (`editor/.../language/outline`, rendered by `app`'s sidebar `OutlineFragment`). Grammars come from android-tree-sitter's Maven artifacts, except JavaScript's, which `subprojects:tree-sitter-javascript` builds from vendored source because android-tree-sitter publishes none. `lsp:refactor-core` holds the language-agnostic half of the refactorings (offset spans, block geometry, rewrite composition, name primitives) so `lsp:java` and `lsp:kotlin` share one copy; `lsp:ui` holds the Compose sheets they share. Neither depends on a language server. `lsp:external` adapts a plugin's stdio language server to `ILanguageServer` over LSP4J; `app`'s `PluginLanguageSupport` installs plugin grammars and servers; for the JavaScript types the IDE highlights, it installs only a plugin's server. | -| UI design tooling | `layouteditor`, `uidesigner`, `xml-inflater`, `vectormaster`, `compose-preview` | Visual/XML design surfaces for the *user's* app. | +| UI design tooling | `layouteditor`, `uidesigner`, `xml-inflater`, `vectormaster` | Visual/XML design surfaces for the *user's* app. | | Shell | `termux:{termux-app,termux-shared,termux-view,termux-emulator}` | Embedded Termux shell and terminal. | | Plugin system | `plugin-api`, `plugin-api:plugin-builder`, `plugin-manager` | In-app plugin SDK + manager — `AndroidManifest.xml` `` contract, permissions, extensions. See [plugin-api.md](docs/plugin-api.md) for the API surface & compatibility policy. | | On-device AI | `llama-api`, `llama-impl` | llama.cpp integration, shipped as a per-flavor native AAR. | diff --git a/docs/adr/0009-jetpack-compose-for-new-ui.md b/docs/adr/0009-jetpack-compose-for-new-ui.md index 0b162a9281..6e35cf3ae7 100644 --- a/docs/adr/0009-jetpack-compose-for-new-ui.md +++ b/docs/adr/0009-jetpack-compose-for-new-ui.md @@ -24,7 +24,7 @@ That split has a cost: two ways to build a screen, manual view-state wiring, boi **Positive** - One way to build new screens; less boilerplate (no binding/`findViewById`), state-driven rendering that maps cleanly onto the existing `StateFlow` UDF. -- UI logic is easier to test and preview (`compose-preview` already exists in the tree). +- UI logic is easier to test and preview (`compose-preview` already existed in the tree; ADFA-3598 later moved it into a plugin). **Negative / costs** - A **mixed codebase** for the foreseeable future — Compose and Views coexist; contributors must know both, and interop (`ComposeView` / `AndroidView`) is needed at the seams. From b0439ef26f7a89b41ff4f8258f7112073b1db646 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 11:41:17 -0800 Subject: [PATCH 10/10] ADFA-7201: Drop the compose-preview citation from ADR 0009 compose-preview previews the user's Compose code, not CoGo's own UI, so it never supported this ADR's point about CoGo's screens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- docs/adr/0009-jetpack-compose-for-new-ui.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/0009-jetpack-compose-for-new-ui.md b/docs/adr/0009-jetpack-compose-for-new-ui.md index 6e35cf3ae7..c5e5d1d53b 100644 --- a/docs/adr/0009-jetpack-compose-for-new-ui.md +++ b/docs/adr/0009-jetpack-compose-for-new-ui.md @@ -24,7 +24,7 @@ That split has a cost: two ways to build a screen, manual view-state wiring, boi **Positive** - One way to build new screens; less boilerplate (no binding/`findViewById`), state-driven rendering that maps cleanly onto the existing `StateFlow` UDF. -- UI logic is easier to test and preview (`compose-preview` already existed in the tree; ADFA-3598 later moved it into a plugin). +- UI logic is easier to test and preview. **Negative / costs** - A **mixed codebase** for the foreseeable future — Compose and Views coexist; contributors must know both, and interop (`ComposeView` / `AndroidView`) is needed at the seams.