-
Notifications
You must be signed in to change notification settings - Fork 24
ADFA-2959 | Catch composition errors and handle preview crashes #1326
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
108 changes: 108 additions & 0 deletions
108
...-preview/src/main/java/com/itsaky/androidide/compose/preview/runtime/ComposableInvoker.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| package com.itsaky.androidide.compose.preview.runtime | ||
|
|
||
| import androidx.compose.runtime.Composer | ||
| import java.lang.reflect.InvocationTargetException | ||
| import java.lang.reflect.Method | ||
| import java.lang.reflect.Modifier as ReflectModifier | ||
| import kotlin.math.ceil | ||
|
|
||
| class PreviewSetupException(message: String, cause: Throwable? = null) : Exception(message, cause) | ||
|
|
||
| object ComposableInvoker { | ||
|
|
||
| fun findComposableMethod(clazz: Class<*>, functionName: String): Method? { | ||
| val methods = clazz.declaredMethods | ||
|
|
||
| methods.find { it.name == functionName }?.let { | ||
| it.isAccessible = true | ||
| return it | ||
| } | ||
|
|
||
| val candidates = methods.filter { method -> | ||
| !method.name.contains("\$default") && | ||
| (method.name.startsWith("$functionName\$") || method.name == "${functionName}\$lambda") | ||
| } | ||
|
|
||
| return candidates.minByOrNull { it.parameterCount }?.also { it.isAccessible = true } | ||
| } | ||
|
|
||
| fun invokeSafely(clazz: Class<*>, method: Method, composer: Composer) { | ||
| val isStatic = ReflectModifier.isStatic(method.modifiers) | ||
|
|
||
| val instance = if (isStatic) { | ||
| null | ||
| } else { | ||
| try { | ||
| clazz.getDeclaredConstructor().newInstance() | ||
| } catch (e: Exception) { | ||
| throw PreviewSetupException("Failed to create instance for ${clazz.simpleName}", e) | ||
| } | ||
| } | ||
|
|
||
| if (!isStatic && instance == null) { | ||
| throw PreviewSetupException("Failed to create instance for ${clazz.simpleName}") | ||
| } | ||
|
|
||
| when (val signature = ComposeSignature.analyze(method)) { | ||
| is ComposeSignature.NoArgs -> executeInvocation { method.invoke(instance) } | ||
| is ComposeSignature.WithComposer -> invokeWithComposer(method, instance, signature, composer) | ||
| is ComposeSignature.Unsupported -> { | ||
| throw PreviewSetupException("Unsupported signature: ${signature.reason}") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun invokeWithComposer( | ||
| method: Method, | ||
| instance: Any?, | ||
| signature: ComposeSignature.WithComposer, | ||
| composer: Composer | ||
| ) { | ||
| val args = arrayOfNulls<Any>(signature.totalParams) | ||
| val realParamsCount = signature.composerIndex | ||
|
|
||
| for (i in 0 until realParamsCount) { | ||
| args[i] = getDefaultValue(signature.types[i]) | ||
| } | ||
|
|
||
| args[signature.composerIndex] = composer | ||
|
|
||
| val changedInts = if (realParamsCount == 0) 1 else ceil(realParamsCount / COMPOSE_PARAMS_PER_CHANGED_INT).toInt() | ||
| val changedStartIndex = signature.composerIndex + 1 | ||
| val changedEndIndex = minOf(changedStartIndex + changedInts, signature.totalParams) | ||
|
|
||
| args.fill(COMPOSE_CHANGED_EVALUATE_ALL, fromIndex = changedStartIndex, toIndex = changedEndIndex) | ||
| args.fill(COMPOSE_DEFAULT_USE_ALL_DEFAULTS, fromIndex = changedEndIndex, toIndex = signature.totalParams) | ||
|
|
||
| executeInvocation { method.invoke(instance, *args) } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| private fun executeInvocation(action: () -> Unit) { | ||
| try { | ||
| action() | ||
| } catch (e: InvocationTargetException) { | ||
| throw e.targetException ?: e | ||
| } catch (e: Exception) { | ||
| throw PreviewSetupException("Reflection invocation failed", e) | ||
| } | ||
| } | ||
|
|
||
| private fun getDefaultValue(type: Class<*>): Any? { | ||
| if (!type.isPrimitive) return null | ||
| return when (type) { | ||
| Int::class.javaPrimitiveType -> 0 | ||
| Boolean::class.javaPrimitiveType -> false | ||
| Float::class.javaPrimitiveType -> 0f | ||
| Double::class.javaPrimitiveType -> 0.0 | ||
| Long::class.javaPrimitiveType -> 0L | ||
| Byte::class.javaPrimitiveType -> 0.toByte() | ||
| Short::class.javaPrimitiveType -> 0.toShort() | ||
| Char::class.javaPrimitiveType -> '\u0000' | ||
| else -> null | ||
| } | ||
| } | ||
|
|
||
| private const val COMPOSE_PARAMS_PER_CHANGED_INT = 10.0 | ||
| private const val COMPOSE_CHANGED_EVALUATE_ALL = 0 | ||
| private const val COMPOSE_DEFAULT_USE_ALL_DEFAULTS = -1 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
...e-preview/src/main/java/com/itsaky/androidide/compose/preview/runtime/ComposeSignature.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package com.itsaky.androidide.compose.preview.runtime | ||
|
|
||
| import java.lang.reflect.Method | ||
|
|
||
| sealed class ComposeSignature { | ||
| object NoArgs : ComposeSignature() | ||
|
|
||
| class WithComposer( | ||
| val composerIndex: Int, | ||
| val totalParams: Int, | ||
| val types: Array<Class<*>> | ||
| ) : ComposeSignature() | ||
|
|
||
| class Unsupported(val reason: String) : ComposeSignature() | ||
|
|
||
| companion object { | ||
| fun analyze(method: Method): ComposeSignature { | ||
| val types = method.parameterTypes | ||
| val paramCount = types.size | ||
|
|
||
| if (paramCount == 0) return NoArgs | ||
|
|
||
| val composerIndex = types.indexOfFirst { it.name == "androidx.compose.runtime.Composer" } | ||
|
|
||
| if (composerIndex == -1) { | ||
| return Unsupported("No Composer parameter found in ${method.name}") | ||
| } | ||
|
|
||
| for (i in (composerIndex + 1) until paramCount) { | ||
| if (types[i] != Int::class.javaPrimitiveType && types[i] != Integer::class.java) { | ||
| return Unsupported("Expected Int at index $i after Composer, but found ${types[i].simpleName}") | ||
| } | ||
| } | ||
|
|
||
| return WithComposer(composerIndex, paramCount, types) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.