From d058271f1e1953173e03db217a93c07221d5c03a Mon Sep 17 00:00:00 2001 From: Daniel Alome Date: Tue, 10 Nov 2026 15:57:21 +0100 Subject: [PATCH] ADFA-7068 | Speed up Compose Preview and fix lost edits, ClassNotFoundException and comment parsing Keep one compiler daemon for the plugin instead of one per preview screen, and warm it when a Compose file is shown. Call D8 through the API that exists so dexing stays in the daemon. Clear the class output folder before each compile. Save the open file before opening the preview (adds filesystem.write). Dex the project's compiled classes in the plugin and key the preview cache on them, because Quick Build rewrites the build's dex output without them. Show why a build was refused, point at an unbuilt project on unresolved references, and ignore comments when looking for @Preview. --- .../jetpack-compose-preview.html | 7 +- .../src/main/AndroidManifest.xml | 2 +- .../src/main/assets/docs/index.html | 7 +- .../composepreview/ComposePreviewFragment.kt | 18 ++- .../composepreview/ComposePreviewPlugin.kt | 33 +++++- .../composepreview/ComposePreviewViewModel.kt | 12 +- .../composepreview/compiler/CompilerDaemon.kt | 103 +++++++++++++++--- .../ComposePreviewRepositoryImpl.kt | 65 +++++++++-- .../domain/PreviewSourceParser.kt | 52 ++++++++- 9 files changed, 250 insertions(+), 49 deletions(-) diff --git a/plugins/Jetpack-Compose-Preview/jetpack-compose-preview.html b/plugins/Jetpack-Compose-Preview/jetpack-compose-preview.html index 63affd1b7..0e115d5fd 100644 --- a/plugins/Jetpack-Compose-Preview/jetpack-compose-preview.html +++ b/plugins/Jetpack-Compose-Preview/jetpack-compose-preview.html @@ -347,10 +347,11 @@

4.5 Class loading and theme recreation

4.6 Permissions

<meta-data android:name="plugin.permissions"
-           android:value="filesystem.read,project.structure,native.code" />
+ android:value="filesystem.read,filesystem.write,project.structure,native.code" />

Filesystem and project-structure access back source reading and module - resolution; native.code covers the bundled on-device toolchain. + resolution; filesystem.write lets the plugin save the open file + before it opens the preview; native.code covers the bundled on-device toolchain.

@@ -393,7 +394,7 @@

Runtime requirements

RequirementValue Min Android versionAPI 26 (Android 8) Min IDE version1.0.0 - Permissionsfilesystem.read, project.structure, native.code + Permissionsfilesystem.read, filesystem.write, project.structure, native.code Network accessNone diff --git a/plugins/Jetpack-Compose-Preview/src/main/AndroidManifest.xml b/plugins/Jetpack-Compose-Preview/src/main/AndroidManifest.xml index 0955ae891..d1691409d 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/AndroidManifest.xml +++ b/plugins/Jetpack-Compose-Preview/src/main/AndroidManifest.xml @@ -31,7 +31,7 @@ + android:value="filesystem.read,filesystem.write,project.structure,native.code" /> 4.5 Class loading and theme recreation

4.6 Permissions

<meta-data android:name="plugin.permissions"
-           android:value="filesystem.read,project.structure,native.code" />
+ android:value="filesystem.read,filesystem.write,project.structure,native.code" />

Filesystem and project-structure access back source reading and module - resolution; native.code covers the bundled on-device toolchain. + resolution; filesystem.write lets the plugin save the open file + before it opens the preview; native.code covers the bundled on-device toolchain.

@@ -393,7 +394,7 @@

Runtime requirements

RequirementValue Min Android versionAPI 26 (Android 8) Min IDE version1.0.0 - Permissionsfilesystem.read, project.structure, native.code + Permissionsfilesystem.read, filesystem.write, project.structure, native.code Network accessNone diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewFragment.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewFragment.kt index f530ec7db..da0676b8b 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewFragment.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewFragment.kt @@ -23,6 +23,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.itsaky.androidide.plugins.base.PluginFragmentHelper +import com.itsaky.androidide.plugins.services.GradleTaskResult import com.itsaky.androidide.plugins.services.IdeBuildService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -207,14 +208,19 @@ class ComposePreviewFragment : Fragment() { val task = if (modulePath.isNotEmpty()) "$modulePath:assemble$variant" else "assemble$variant" LOG.info("Compose preview triggering build: {}", task) - buildService.executeTasks(task).whenComplete { success, error -> + buildService.executeTasks(listOf(task), emptyList()).whenComplete { result, error -> view?.post { buildTriggered = false - if (error == null && success == true) { - viewModel.refreshAfterBuild(pluginContext) - } else { - LOG.error("Compose preview build failed", error) - viewModel.setBuildFailed() + when { + error == null && result is GradleTaskResult.Success -> viewModel.refreshAfterBuild(pluginContext) + result is GradleTaskResult.Refused -> { + LOG.error("Compose preview build refused: {}", result.reason) + viewModel.setBuildFailed(result.reason) + } + else -> { + LOG.error("Compose preview build failed: {}", result, error) + viewModel.setBuildFailed() + } } } } diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewPlugin.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewPlugin.kt index 413d58be2..2215e20ec 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewPlugin.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewPlugin.kt @@ -13,6 +13,12 @@ import com.itsaky.androidide.plugins.extensions.UIExtension import com.itsaky.androidide.plugins.services.IdeEditorService import com.itsaky.androidide.plugins.services.IdeEnvironmentService import com.itsaky.androidide.plugins.services.IdeUIService +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import org.appdevforall.composepreview.compiler.SharedCompilerDaemon +import org.appdevforall.composepreview.domain.blankComments /** * Entry point for the extracted Jetpack Compose preview feature. @@ -24,6 +30,7 @@ import com.itsaky.androidide.plugins.services.IdeUIService class ComposePreviewPlugin : IPlugin, UIExtension, DocumentationExtension { private lateinit var context: PluginContext + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) override fun initialize(context: PluginContext): Boolean { this.context = context @@ -35,9 +42,12 @@ class ComposePreviewPlugin : IPlugin, UIExtension, DocumentationExtension { override fun activate(): Boolean = true - override fun deactivate(): Boolean = true + override fun deactivate(): Boolean { + SharedCompilerDaemon.shutdown() + return true + } - override fun dispose() = Unit + override fun dispose() = SharedCompilerDaemon.shutdown() override fun getToolbarActions(): List = listOf( ToolbarAction( @@ -100,19 +110,30 @@ class ComposePreviewPlugin : IPlugin, UIExtension, DocumentationExtension { } ComposePreviewState.set(file.absolutePath, source) - context.services.get(IdeUIService::class.java) - ?.openPluginScreen(PLUGIN_ID, ComposePreviewFragment::class.java.name, "Compose Preview") + scope.launch { + try { + if (editor?.saveFile(file) != true) { + context.logger.warn("Compose Preview could not save ${file.name} before opening") + } + } catch (e: SecurityException) { + context.logger.warn("Compose Preview is not allowed to save ${file.name}: ${e.message}") + } + context.services.get(IdeUIService::class.java) + ?.openPluginScreen(PLUGIN_ID, ComposePreviewFragment::class.java.name, "Compose Preview") + } } private fun hasComposePreview(): Boolean { val editor = context.services.get(IdeEditorService::class.java) ?: return false val file = editor.getCurrentFile() ?: return false val source = editor.getCurrentFileContent() ?: return false - return isComposePreviewSource(file.name, source) + if (!isComposePreviewSource(file.name, source)) return false + SharedCompilerDaemon.warmUpOnce(context.androidContext) + return true } private fun isComposePreviewSource(fileName: String, source: String): Boolean = - fileName.endsWith(".kt") && PREVIEW_REGEX.containsMatchIn(source) + fileName.endsWith(".kt") && PREVIEW_REGEX.containsMatchIn(blankComments(source)) companion object { const val PLUGIN_ID = "org.appdevforall.composepreview" diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewViewModel.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewViewModel.kt index 4116bbc93..1d58d1b2b 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewViewModel.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/ComposePreviewViewModel.kt @@ -236,8 +236,9 @@ class ComposePreviewViewModel( .onFailure { error -> val diagnostics = if (error is CompilationException) error.diagnostics else emptyList() LOG.error("compile: FAILED - {} ({} diagnostic(s))", error.message, diagnostics.size) + val message = error.message ?: "Compilation failed" _previewState.value = PreviewState.Error( - message = error.message ?: "Compilation failed", + message = if (UNRESOLVED_REFERENCE in message) "$NOT_BUILT_HINT\n\n$message" else message, diagnostics = diagnostics ) } @@ -268,8 +269,10 @@ class ComposePreviewViewModel( _previewState.value = PreviewState.Building } - fun setBuildFailed() { - _previewState.value = PreviewState.Error("Build failed. Check build output for details.") + fun setBuildFailed(reason: String? = null) { + _previewState.value = PreviewState.Error( + if (reason == null) "Build failed. Check build output for details." else "Build did not start: $reason" + ) } fun refreshAfterBuild(context: Context) { @@ -336,5 +339,8 @@ class ComposePreviewViewModel( companion object { private val LOG = LoggerFactory.getLogger(ComposePreviewViewModel::class.java) private const val DEBOUNCE_MS = 500L + private const val UNRESOLVED_REFERENCE = "unresolved reference" + private const val NOT_BUILT_HINT = + "This file uses code the last build does not contain. Build the project, then open the preview again." } } diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/compiler/CompilerDaemon.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/compiler/CompilerDaemon.kt index fb8020581..3b2ec35e2 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/compiler/CompilerDaemon.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/compiler/CompilerDaemon.kt @@ -1,5 +1,6 @@ package org.appdevforall.composepreview.compiler +import android.content.Context import org.appdevforall.composepreview.Environment import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -18,6 +19,7 @@ import java.io.File import java.io.InputStreamReader import java.io.OutputStreamWriter import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean class CompilerDaemon( private val classpathManager: ComposeClasspathManager, @@ -33,6 +35,9 @@ class CompilerDaemon( private val timeoutScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private var isStartingUp = false + @Volatile + private var warmed = false + private val wrapperDir = File(workDir, "daemon").apply { mkdirs() } private val wrapperClass = File(wrapperDir, "CompilerWrapper.class") @@ -82,28 +87,28 @@ class CompilerDaemon( } } + suspend fun dex(classesDir: File, outputDir: File): DexResult = + dex(classesDir.walkTopDown().filter { it.extension == "class" }.toList(), outputDir) + suspend fun dex( - classesDir: File, - outputDir: File + classFiles: List, + outputDir: File, + extraClasspath: List = emptyList() ): DexResult = mutex.withLock { withContext(Dispatchers.IO) { ensureDaemonRunning() outputDir.mkdirs() - val classFiles = classesDir.walkTopDown() - .filter { it.extension == "class" } - .toList() - if (classFiles.isEmpty()) { return@withContext DexResult( success = false, dexFile = null, - errorOutput = "No .class files found in $classesDir" + errorOutput = "No .class files to dex" ) } - val d8Args = buildD8Args(classFiles, outputDir) + val d8Args = buildD8Args(classFiles, outputDir, extraClasspath) val argsLine = "DEX\u0000" + d8Args.joinToString("\u0000") + "\n" try { @@ -145,12 +150,16 @@ class CompilerDaemon( } } - private fun buildD8Args(classFiles: List, outputDir: File): List = buildList { + private fun buildD8Args( + classFiles: List, + outputDir: File, + extraClasspath: List + ): List = buildList { add("--release") add("--min-api") add("21") - classpathManager.getRuntimeJars() + (classpathManager.getRuntimeJars() + extraClasspath.filter { it.isFile && it !in classFiles }) .filter { it.exists() } .forEach { jar -> add("--classpath") @@ -294,6 +303,7 @@ class CompilerDaemon( } fun stopDaemon() { + warmed = false idleTimeoutJob?.cancel() idleTimeoutJob = null @@ -336,6 +346,18 @@ class CompilerDaemon( timeoutScope.cancel() } + suspend fun warmUp(classpath: String, composePlugin: File) { + if (warmed && daemonProcess?.isAlive == true) return + val dir = File(workDir, "warmup").apply { mkdirs() } + val source = File(dir, "WarmUp.kt").apply { writeText(WARM_UP_SOURCE) } + val classesDir = File(dir, "classes") + val startedAt = System.currentTimeMillis() + val compiled = compile(listOf(source), classesDir, classpath, composePlugin) + val dexed = compiled.success && dex(classesDir, File(dir, "dex")).success + warmed = dexed + LOG.info("Compiler daemon warm-up took {} ms, success={}", System.currentTimeMillis() - startedAt, dexed) + } + suspend fun startEagerly() = mutex.withLock { withContext(Dispatchers.IO) { if (daemonProcess?.isAlive == true) return@withContext @@ -363,10 +385,23 @@ class CompilerDaemon( companion object { private val LOG = LoggerFactory.getLogger(CompilerDaemon::class.java) - private const val IDLE_TIMEOUT_MS = 120_000L + private const val IDLE_TIMEOUT_MS = 300_000L private const val SHUTDOWN_TIMEOUT_SECONDS = 5L private const val COMPILE_TIMEOUT_MS = 300_000L - private const val WRAPPER_VERSION = 2 + private const val WRAPPER_VERSION = 3 + + private val WARM_UP_SOURCE = """ + package warmup + + import androidx.compose.foundation.layout.Column + import androidx.compose.material3.Text + import androidx.compose.runtime.Composable + + @Composable + fun WarmUp() { + Column { Text("warm") } + } + """.trimIndent() private val WRAPPER_SOURCE = """ import java.io.*; @@ -378,6 +413,7 @@ class CompilerDaemon( private static Method kotlinExecMethod; private static Method d8ParseMethod; private static Method d8RunMethod; + private static Object d8Origin; private static Class d8CommandClass; public static void main(String[] args) throws Exception { @@ -433,12 +469,15 @@ class CompilerDaemon( private static void handleDex(String[] d8Args) throws Exception { if (d8CommandClass == null) { d8CommandClass = Class.forName("com.android.tools.r8.D8Command"); - d8ParseMethod = d8CommandClass.getMethod("parse", String[].class); + Class originClass = Class.forName("com.android.tools.r8.origin.Origin"); + d8Origin = originClass.getMethod("root").invoke(null); + d8ParseMethod = d8CommandClass.getMethod("parse", String[].class, originClass); Class d8Class = Class.forName("com.android.tools.r8.D8"); d8RunMethod = d8Class.getMethod("run", d8CommandClass); } - Object cmd = d8ParseMethod.invoke(null, (Object) d8Args); + Object builder = d8ParseMethod.invoke(null, d8Args, d8Origin); + Object cmd = builder.getClass().getMethod("build").invoke(builder); d8RunMethod.invoke(null, cmd); System.out.println("DEX_SUCCESS"); } @@ -446,3 +485,39 @@ class CompilerDaemon( """.trimIndent() } } + +object SharedCompilerDaemon { + private val LOG = LoggerFactory.getLogger(SharedCompilerDaemon::class.java) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val warmUpRequested = AtomicBoolean(false) + private var daemon: CompilerDaemon? = null + + @Synchronized + fun get(classpathManager: ComposeClasspathManager, workDir: File): CompilerDaemon = + daemon ?: CompilerDaemon(classpathManager, workDir).also { daemon = it } + + fun warmUpOnce(context: Context) { + if (!warmUpRequested.compareAndSet(false, true)) return + scope.launch { + try { + val classpathManager = ComposeClasspathManager(context) + if (!classpathManager.ensureComposeJarsExtracted()) return@launch + get(classpathManager, workDirFor(context)).warmUp( + classpathManager.getCompilationClasspath(), + classpathManager.getCompilerPlugin() + ) + } catch (e: Exception) { + LOG.warn("Compiler daemon warm-up failed", e) + } + } + } + + @Synchronized + fun shutdown() { + daemon?.shutdown() + daemon = null + warmUpRequested.set(false) + } + + fun workDirFor(context: Context): File = File(context.cacheDir, "compose_preview_work").apply { mkdirs() } +} diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/data/repository/ComposePreviewRepositoryImpl.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/data/repository/ComposePreviewRepositoryImpl.kt index 017f06e8f..37edbf935 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/data/repository/ComposePreviewRepositoryImpl.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/data/repository/ComposePreviewRepositoryImpl.kt @@ -7,6 +7,7 @@ import org.appdevforall.composepreview.compiler.ComposeClasspathManager import org.appdevforall.composepreview.compiler.ComposeCompiler import org.appdevforall.composepreview.compiler.ComposeDexCompiler import org.appdevforall.composepreview.compiler.DexCache +import org.appdevforall.composepreview.compiler.SharedCompilerDaemon import org.appdevforall.composepreview.data.source.ProjectContext import org.appdevforall.composepreview.data.source.ProjectContextSource import org.appdevforall.composepreview.domain.model.ParsedPreviewSource @@ -80,7 +81,7 @@ class ComposePreviewRepositoryImpl( private fun initializeInfrastructure(context: Context): ComposeClasspathManager { val cacheDir = context.cacheDir - val work = File(cacheDir, "compose_preview_work").apply { mkdirs() } + val work = SharedCompilerDaemon.workDirFor(context) workDir = work dexCache = DexCache(File(cacheDir, "compose_dex_cache")) @@ -88,7 +89,7 @@ class ComposePreviewRepositoryImpl( val cpManager = ComposeClasspathManager(context) classpathManager = cpManager compiler = ComposeCompiler(cpManager, work) - compilerDaemon = CompilerDaemon(cpManager, work) + compilerDaemon = SharedCompilerDaemon.get(cpManager, work) dexCompiler = ComposeDexCompiler(cpManager) return cpManager } @@ -120,17 +121,20 @@ class ComposePreviewRepositoryImpl( val generatedClassName = "${fileName}Kt" val fullClassName = "${parsedSource.packageName}.$generatedClassName" - val sourceHash = cache.computeSourceHash(source) + val projectDex = projectClassesDex(context, cache, compilerDaemon, workDir) + val startedAt = System.currentTimeMillis() + val projectDexFiles = projectDex.files + context.projectDexFiles + val sourceHash = cache.computeSourceHash(source + '\u0000' + projectDex.signature) val cached = cache.getCachedDex(sourceHash) if (cached != null) { LOG.info("Using cached DEX for hash: {}, runtimeDex={}, projectDexFiles={}", - sourceHash, runtimeDex?.absolutePath ?: "null", context.projectDexFiles.size) + sourceHash, runtimeDex?.absolutePath ?: "null", projectDexFiles.size) return@runCatching CompilationResult( dexFile = cached.dexFile, className = fullClassName, runtimeDex = runtimeDex, - projectDexFiles = context.projectDexFiles + projectDexFiles = projectDexFiles ) } @@ -141,7 +145,10 @@ class ComposePreviewRepositoryImpl( val sourceFile = File(packageDir, "$fileName.kt") sourceFile.writeText(source) - val classesDir = File(workDir, "classes").apply { mkdirs() } + val classesDir = File(workDir, "classes").apply { + deleteRecursively() + mkdirs() + } LOG.debug("Compiling source: {}", sourceFile.absolutePath) LOG.info("Using {} project classpaths for compilation", context.compileClasspaths.size) @@ -199,6 +206,7 @@ class ComposePreviewRepositoryImpl( ) } + val compiledAt = System.currentTimeMillis() val dexDir = File(workDir, "dex").apply { mkdirs() } LOG.debug("Converting to DEX") @@ -240,18 +248,56 @@ class ComposePreviewRepositoryImpl( LOG.warn("Failed to cache DEX file (non-fatal): {}", e.message) } - LOG.info("Preview ready: {} with {} previews, {} project DEX files", - fullClassName, parsedSource.previewConfigs.size, context.projectDexFiles.size) + val finishedAt = System.currentTimeMillis() + LOG.info("Preview ready: {} with {} previews, {} project DEX files; kotlinc {} ms, d8 {} ms, total {} ms", + fullClassName, parsedSource.previewConfigs.size, projectDexFiles.size, + compiledAt - startedAt, finishedAt - compiledAt, finishedAt - startedAt) CompilationResult( dexFile = dexFile, className = fullClassName, runtimeDex = runtimeDex, - projectDexFiles = context.projectDexFiles + projectDexFiles = projectDexFiles ) } } + private data class ProjectDex(val signature: String, val files: List) + + private suspend fun projectClassesDex( + context: ProjectContext, + cache: DexCache, + daemon: CompilerDaemon?, + workDir: File + ): ProjectDex { + val inputs = context.intermediateClasspaths + .flatMap { root -> + if (root.isDirectory) root.walkTopDown().filter { it.extension == "class" }.toList() else listOf(root) + } + .filter { it.isFile } + .sortedBy { it.absolutePath } + val signature = cache.computeSourceHash( + inputs.joinToString("|") { "${it.absolutePath}:${it.lastModified()}:${it.length()}" } + ) + if (inputs.isEmpty() || daemon == null) return ProjectDex(signature, emptyList()) + + val root = File(workDir, "project-dex") + val outDir = File(root, signature) + val done = File(outDir, "done") + if (!done.exists()) { + root.deleteRecursively() + val startedAt = System.currentTimeMillis() + val result = daemon.dex(inputs, outDir, context.compileClasspaths) + if (!result.success) { + LOG.warn("Could not dex the project's compiled classes: {}", result.errorOutput) + return ProjectDex(signature, emptyList()) + } + done.createNewFile() + LOG.info("Dexed {} project class inputs in {} ms", inputs.size, System.currentTimeMillis() - startedAt) + } + return ProjectDex(signature, outDir.listFiles { file -> file.extension == "dex" }.orEmpty().sortedBy { it.name }) + } + override fun computeSourceHash(source: String): String { val cache = dexCache if (cache == null) { @@ -262,7 +308,6 @@ class ComposePreviewRepositoryImpl( } override fun reset() { - compilerDaemon?.shutdown() classpathManager = null compiler = null compilerDaemon = null diff --git a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/domain/PreviewSourceParser.kt b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/domain/PreviewSourceParser.kt index 50cb2de39..b4ef9ef94 100644 --- a/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/domain/PreviewSourceParser.kt +++ b/plugins/Jetpack-Compose-Preview/src/main/kotlin/org/appdevforall/composepreview/domain/PreviewSourceParser.kt @@ -5,12 +5,58 @@ import org.appdevforall.composepreview.domain.model.ParsedPreviewSource import org.slf4j.LoggerFactory import kotlin.math.roundToInt +internal fun blankComments(source: String): String { + val out = StringBuilder(source) + var i = 0 + fun blank(from: Int, end: Int) { + for (k in from until end) if (out[k] != '\n') out[k] = ' ' + } + while (i < source.length) { + when { + source.startsWith("//", i) -> { + val end = source.indexOf('\n', i).let { if (it < 0) source.length else it } + blank(i, end) + i = end + } + source.startsWith("/*", i) -> { + var depth = 1 + var j = i + 2 + while (j < source.length && depth > 0) { + when { + source.startsWith("/*", j) -> { depth++; j += 2 } + source.startsWith("*/", j) -> { depth--; j += 2 } + else -> j++ + } + } + blank(i, j) + i = j + } + source.startsWith("\"\"\"", i) -> { + val end = source.indexOf("\"\"\"", i + 3) + i = if (end < 0) source.length else end + 3 + } + source[i] == '"' || source[i] == '\'' -> { + val quote = source[i] + i++ + while (i < source.length && source[i] != quote && source[i] != '\n') { + if (source[i] == '\\') i++ + i++ + } + i++ + } + else -> i++ + } + } + return out.toString() +} + class PreviewSourceParser { fun parse(source: String): ParsedPreviewSource? { - val packageName = extractPackageName(source) ?: return null - val className = extractClassName(source) - val previewConfigs = detectAllPreviewFunctions(source, packageName) + val code = blankComments(source) + val packageName = extractPackageName(code) ?: return null + val className = extractClassName(code) + val previewConfigs = detectAllPreviewFunctions(code, packageName) return ParsedPreviewSource(packageName, className, previewConfigs) }