Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions plugins/Jetpack-Compose-Preview/jetpack-compose-preview.html
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,11 @@ <h3>4.5 Class loading and theme recreation</h3>

<h3>4.6 Permissions</h3>
<pre><code>&lt;meta-data android:name="plugin.permissions"
android:value="filesystem.read,project.structure,native.code" /&gt;</code></pre>
android:value="filesystem.read,filesystem.write,project.structure,native.code" /&gt;</code></pre>
<p>
Filesystem and project-structure access back source reading and module
resolution; <code>native.code</code> covers the bundled on-device toolchain.
resolution; <code>filesystem.write</code> lets the plugin save the open file
before it opens the preview; <code>native.code</code> covers the bundled on-device toolchain.
</p>
</section>

Expand Down Expand Up @@ -393,7 +394,7 @@ <h3>Runtime requirements</h3>
<tr><th>Requirement</th><th>Value</th></tr>
<tr><td>Min Android version</td><td>API 26 (Android 8)</td></tr>
<tr><td>Min IDE version</td><td>1.0.0</td></tr>
<tr><td>Permissions</td><td><code>filesystem.read</code>, <code>project.structure</code>, <code>native.code</code></td></tr>
<tr><td>Permissions</td><td><code>filesystem.read</code>, <code>filesystem.write</code>, <code>project.structure</code>, <code>native.code</code></td></tr>
<tr><td>Network access</td><td>None</td></tr>
</table>
</section>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

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

<meta-data
android:name="plugin.main_class"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,11 @@ <h3>4.5 Class loading and theme recreation</h3>

<h3>4.6 Permissions</h3>
<pre><code>&lt;meta-data android:name="plugin.permissions"
android:value="filesystem.read,project.structure,native.code" /&gt;</code></pre>
android:value="filesystem.read,filesystem.write,project.structure,native.code" /&gt;</code></pre>
<p>
Filesystem and project-structure access back source reading and module
resolution; <code>native.code</code> covers the bundled on-device toolchain.
resolution; <code>filesystem.write</code> lets the plugin save the open file
before it opens the preview; <code>native.code</code> covers the bundled on-device toolchain.
</p>
</section>

Expand Down Expand Up @@ -393,7 +394,7 @@ <h3>Runtime requirements</h3>
<tr><th>Requirement</th><th>Value</th></tr>
<tr><td>Min Android version</td><td>API 26 (Android 8)</td></tr>
<tr><td>Min IDE version</td><td>1.0.0</td></tr>
<tr><td>Permissions</td><td><code>filesystem.read</code>, <code>project.structure</code>, <code>native.code</code></td></tr>
<tr><td>Permissions</td><td><code>filesystem.read</code>, <code>filesystem.write</code>, <code>project.structure</code>, <code>native.code</code></td></tr>
<tr><td>Network access</td><td>None</td></tr>
</table>
</section>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 -> {
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved
LOG.error("Compose preview build failed: {}", result, error)
viewModel.setBuildFailed()
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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<ToolbarAction> = listOf(
ToolbarAction(
Expand Down Expand Up @@ -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) {
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved
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))
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved

companion object {
const val PLUGIN_ID = "org.appdevforall.composepreview"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOT_BUILT_HINT is added for any error containing "unresolved reference", including a typo in the file being previewed. Txt("hi") tells the user to build the project, which can't fix it. The match is also case-sensitive, so "Unresolved reference" doesn't get the hint.

diagnostics = diagnostics
)
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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."
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand All @@ -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")

Expand Down Expand Up @@ -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<File>,
outputDir: File,
extraClasspath: List<File> = 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 {
Expand Down Expand Up @@ -145,12 +150,16 @@ class CompilerDaemon(
}
}

private fun buildD8Args(classFiles: List<File>, outputDir: File): List<String> = buildList {
private fun buildD8Args(
classFiles: List<File>,
outputDir: File,
extraClasspath: List<File>
): List<String> = 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")
Expand Down Expand Up @@ -294,6 +303,7 @@ class CompilerDaemon(
}

fun stopDaemon() {
warmed = false
idleTimeoutJob?.cancel()
idleTimeoutJob = null

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.*;
Expand All @@ -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 {
Expand Down Expand Up @@ -433,16 +469,55 @@ 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");
}
}
""".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 }
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved

fun warmUpOnce(context: Context) {
if (!warmUpRequested.compareAndSet(false, true)) return
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved
scope.launch {
try {
val classpathManager = ComposeClasspathManager(context)
if (!classpathManager.ensureComposeJarsExtracted()) return@launch
Comment thread
Daniel-ADFA marked this conversation as resolved.
Resolved
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() }
}
Loading
Loading