mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
feat(lab): build and run Lab builds of DroidDeck on the device itself (#2375)
* feat(lab): load an on-device Lab build over the installed app * feat(lab): build Lab builds on the device and report the APK commit to agents * fix(lab): dd-agent connects loopback adb before starting Claude Code * feat(lab): tell the app's own agent to continue after a Lab build restart * fix(lab): size the build heap from the device's memory * feat(lab): keep earlier Lab builds and list them in Updates * feat(lab): notify when DroidDeck comes back on a Lab build or turns one off * feat(lab): estimate the time left and compile the installed commit ahead of the first build * fix(lab): report a failed command as a failed build and update progress every five seconds * feat(lab): a kept build for another version can be rebuilt * feat(lab): record which installed commit the build caches are warm for * fix(lab): the app's agent hands its builds to the app, so they outlive the agent's turn * perf(lab): BuildConfig describes the installed base, so a Lab commit does not change it * perf(lab): compile with the Kotlin daemon, since in-process Kotlin compiles always redo the whole app * fix(lab): a build whose last task was up to date no longer counts as failed * feat(lab): dd-lab-build --explain logs why tasks ran and Kotlin's build report * fix(lab): keep a waiting build when another is staged or Lab is turned off, and never restart during a session * fix(lab): keep the installed build's label and exact commit, and refuse AppLanguage changes * fix(lab): setup verifies its downloads and waits for adb before preparing * fix(agent): quote apostrophes in opened URLs and keep the sign-in pid
This commit is contained in:
1 parent
2dbc007a95
commit
61031e3c4b
15 files changed
+1091
-5
No files matched your search
@@ -7,8 +7,11 @@ import com.droiddeck.launcher.session.EnhancedSessionLogShare
|
||||
import com.droiddeck.launcher.session.GpuClockPin
|
||||
|
||||
class App : Application() {
|
||||
override fun attachBaseContext(base: android.content.Context) =
|
||||
override fun attachBaseContext(base: android.content.Context) {
|
||||
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
|
||||
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName() else packageName
|
||||
com.droiddeck.launcher.lab.LabOverlay.load(this, process == packageName)
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
@@ -39,6 +42,7 @@ class App : Application() {
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
|
||||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.lab.LabNotice.started(this)
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||
|
||||
@@ -288,6 +288,8 @@ class AgentBridgeProvider : ContentProvider() {
|
||||
return JSONObject()
|
||||
.put("schema", SCHEMA)
|
||||
.put("build", BuildConfig.BUILD_LABEL)
|
||||
.put("apkCommit", com.droiddeck.launcher.lab.LabOverlay.apkCommit)
|
||||
.put("lab", com.droiddeck.launcher.lab.LabOverlay.active?.label ?: JSONObject.NULL)
|
||||
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
.put("runtime", JSONObject()
|
||||
.put("installed", LinuxRuntime.isInstalled(context))
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.lab
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadService
|
||||
|
||||
/**
|
||||
* Says what happened to a Lab build when the app starts, so a restart onto a new build does not
|
||||
* look like a crash, and a build Android or the safety checks turned off is not lost silently.
|
||||
*/
|
||||
object LabNotice {
|
||||
private const val CHANNEL_ID = "lab"
|
||||
private const val NOTIFICATION_ID = 4120
|
||||
|
||||
/** Where a start that just moved a Lab build into use opens; the agent that built it sets it. */
|
||||
@Volatile var openOnInstall: String = "updates"
|
||||
|
||||
fun started(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val active = LabOverlay.active
|
||||
val skipped = LabOverlay.skipped
|
||||
val current = LabOverlay.current(app)
|
||||
when {
|
||||
LabOverlay.promoted && active != null ->
|
||||
post(app, app.getString(R.string.lab_installed_title), app.getString(R.string.lab_installed_text, active.label), openOnInstall)
|
||||
skipped == LabOverlay.SKIPPED_APP_IMAGE && current != null ->
|
||||
post(app, app.getString(R.string.lab_paused_title), app.getString(R.string.lab_paused_text, current.label), "updates")
|
||||
skipped == LabOverlay.Reason.OTHER_INSTALL.name || skipped == LabOverlay.Reason.DID_NOT_START.name -> {
|
||||
val reason = if (skipped == LabOverlay.Reason.OTHER_INSTALL.name) R.string.lab_off_other_install else R.string.lab_off_did_not_start
|
||||
post(app, app.getString(R.string.lab_off_title), app.getString(reason), "updates")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun post(app: Context, title: String, text: String, nav: String) {
|
||||
val manager = app.getSystemService(NotificationManager::class.java) ?: return
|
||||
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, app.getString(R.string.upd_lab), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
val open = PendingIntent.getActivity(
|
||||
app, NOTIFICATION_ID,
|
||||
Intent(app, FrontEndActivity::class.java).putExtra(StoreDownloadService.EXTRA_NAV, nav)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
val notification = Notification.Builder(app, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setStyle(Notification.BigTextStyle().bigText(text))
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.build()
|
||||
runCatching { manager.notify(NOTIFICATION_ID, notification) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package com.droiddeck.launcher.lab
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Resources
|
||||
import android.content.res.loader.ResourcesLoader
|
||||
import android.content.res.loader.ResourcesProvider
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A Lab build: app code and resources an on-device agent built from this install's own commit,
|
||||
* loaded over the installed APK at startup so it can be tried without reinstalling or re-signing.
|
||||
*
|
||||
* `files/lab/next` holds a build waiting for the next start and `files/lab/active` the one in use,
|
||||
* each with `overlay.apk` (the build's dex files and linked resources) and `overlay.json`. A build
|
||||
* that is replaced, turned off or refused moves to `files/lab/builds`, so it can be used again.
|
||||
*/
|
||||
object LabOverlay {
|
||||
data class Info(val label: String, val baseCommit: String, val baseApk: String, val built: Long = 0)
|
||||
|
||||
enum class Reason { REPLACED, TURNED_OFF, OTHER_INSTALL, DID_NOT_START, UNREADABLE }
|
||||
|
||||
/** A build kept in `files/lab/builds`; [usable] when it was made for this install. */
|
||||
data class Saved(val dir: File, val info: Info?, val reason: Reason?, val usable: Boolean)
|
||||
|
||||
private const val TAG = "LabOverlay"
|
||||
private const val MAX_FAILED_STARTS = 2
|
||||
private const val STABLE_AFTER_MS = 10_000L
|
||||
private const val KEEP_BUILDS = 12
|
||||
const val SKIPPED_APP_IMAGE = "app image present"
|
||||
|
||||
/** The installed APK's commit; this class always comes from the APK, never from a Lab build. */
|
||||
val apkCommit: String = BuildConfig.SOURCE_COMMIT
|
||||
|
||||
@Volatile var active: Info? = null
|
||||
private set
|
||||
@Volatile var skipped: String? = null
|
||||
private set
|
||||
/** This start moved a newly staged build into use. */
|
||||
@Volatile var promoted = false
|
||||
private set
|
||||
|
||||
private var loader: Any? = null
|
||||
|
||||
@VisibleForTesting
|
||||
internal var injectDex: (ClassLoader, File) -> Unit = ::prependDex
|
||||
@VisibleForTesting
|
||||
internal var openResources: (File) -> Any? = { if (Build.VERSION.SDK_INT >= 30) createLoader(it) else null }
|
||||
@VisibleForTesting
|
||||
internal var appImage: (Context) -> Boolean = ::hasAppImage
|
||||
|
||||
fun root(context: Context) = File(context.filesDir, "lab")
|
||||
|
||||
/** Called from [Application.attachBaseContext], before any class the build may change is loaded. */
|
||||
fun load(app: Application, mainProcess: Boolean) {
|
||||
active = null
|
||||
skipped = null
|
||||
promoted = false
|
||||
try {
|
||||
val root = root(app)
|
||||
if (mainProcess) promoted = promote(root)
|
||||
val dir = File(root, "active")
|
||||
val apk = File(dir, "overlay.apk")
|
||||
val meta = File(dir, "overlay.json")
|
||||
if (!apk.isFile || !meta.isFile) return
|
||||
val info = parse(meta.readText()) ?: return refuse(root, mainProcess, Reason.UNREADABLE)
|
||||
if (!madeFor(app, info)) return refuse(root, mainProcess, Reason.OTHER_INSTALL)
|
||||
if (Build.VERSION.SDK_INT < 30) return skip("needs Android 11")
|
||||
// Classes in an app image are loaded before attachBaseContext and would ignore the overlay;
|
||||
// dd-lab-build recompiles the app without one (cmd package compile -m verify).
|
||||
if (appImage(app)) return skip(SKIPPED_APP_IMAGE)
|
||||
if (mainProcess) {
|
||||
val starts = failedStarts(root) + 1
|
||||
if (starts > MAX_FAILED_STARTS) return refuse(root, true, Reason.DID_NOT_START)
|
||||
File(root, "starts").writeText(starts.toString())
|
||||
}
|
||||
apk.setReadOnly()
|
||||
loader = openResources(apk)
|
||||
injectDex(app.classLoader, apk)
|
||||
active = info
|
||||
addLoader(app.resources)
|
||||
app.registerActivityLifecycleCallbacks(Callbacks(root, mainProcess))
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Lab build not loaded", e)
|
||||
skipped = e.message ?: e.javaClass.simpleName
|
||||
}
|
||||
}
|
||||
|
||||
/** The APK's path changes with every install and update of the app, so it pins a build to one install. */
|
||||
fun madeFor(context: Context, info: Info) = info.baseCommit == apkCommit && info.baseApk == context.applicationInfo.sourceDir
|
||||
|
||||
/** The build in `active`, whether or not this start loaded it. */
|
||||
fun current(context: Context): Info? = read(File(root(context), "active"))
|
||||
|
||||
/** A build staged for the next start. */
|
||||
fun pending(context: Context): Info? = read(File(root(context), "next"))
|
||||
|
||||
/** Kept builds, newest first. */
|
||||
fun saved(context: Context): List<Saved> = File(root(context), "builds").listFiles().orEmpty()
|
||||
.filter { File(it, "overlay.apk").isFile }
|
||||
.sortedByDescending { it.name.toLongOrNull() ?: 0L }
|
||||
.map { dir ->
|
||||
val info = read(dir)
|
||||
val reason = File(dir, "reason").takeIf { it.isFile }?.readText()?.trim()?.let { r -> Reason.entries.firstOrNull { it.name == r } }
|
||||
Saved(dir, info, reason, info != null && madeFor(context, info))
|
||||
}
|
||||
|
||||
/** Leaves the Lab build and restarts the app on the installed APK. */
|
||||
fun turnOff(context: Context) {
|
||||
val root = root(context)
|
||||
archive(root, File(root, "active"), Reason.TURNED_OFF)
|
||||
archive(root, File(root, "next"), Reason.TURNED_OFF)
|
||||
File(root, "next").deleteRecursively()
|
||||
File(root, "starts").delete()
|
||||
restart(context)
|
||||
}
|
||||
|
||||
/** Stages [build] for the next start and keeps a build that was waiting; the caller restarts the app. */
|
||||
fun stage(context: Context, build: Saved) {
|
||||
val root = root(context)
|
||||
val next = File(root, "next")
|
||||
val waiting = File(root, "next.replaced").apply { deleteRecursively() }
|
||||
next.renameTo(waiting)
|
||||
next.deleteRecursively()
|
||||
File(build.dir, "reason").delete()
|
||||
if (!build.dir.renameTo(next)) {
|
||||
waiting.renameTo(next)
|
||||
error("could not stage ${build.dir.name}")
|
||||
}
|
||||
archive(root, waiting, Reason.REPLACED)
|
||||
waiting.deleteRecursively()
|
||||
}
|
||||
|
||||
fun delete(build: Saved) {
|
||||
build.dir.deleteRecursively()
|
||||
}
|
||||
|
||||
/**
|
||||
* Android's background optimization can give the APK an app image again, which keeps a Lab
|
||||
* build from loading. Recompiling without one needs a shell, which the caller provides.
|
||||
*/
|
||||
fun needsRecompile(context: Context) = appImage(context)
|
||||
|
||||
fun recompileCommand(context: Context) = "cmd package compile -m verify -f ${context.packageName}"
|
||||
|
||||
fun restart(context: Context) {
|
||||
val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
||||
?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||
if (launch != null) context.startActivity(launch)
|
||||
Runtime.getRuntime().exit(0)
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun parse(json: String): Info? = runCatching {
|
||||
val o = JSONObject(json)
|
||||
Info(o.getString("label"), o.getString("baseCommit"), o.getString("baseApk"), o.optLong("built"))
|
||||
}.getOrNull()
|
||||
|
||||
private fun read(dir: File): Info? = File(dir, "overlay.json").takeIf { it.isFile && File(dir, "overlay.apk").isFile }?.let { parse(it.readText()) }
|
||||
|
||||
/** Moves `next` into use and keeps the build it replaces. Returns whether there was one to move. */
|
||||
@VisibleForTesting
|
||||
internal fun promote(root: File): Boolean {
|
||||
val next = File(root, "next")
|
||||
if (!File(next, "overlay.apk").isFile || !File(next, "overlay.json").isFile) return false
|
||||
val active = File(root, "active")
|
||||
archive(root, active, Reason.REPLACED)
|
||||
active.deleteRecursively()
|
||||
if (!next.renameTo(active)) return false
|
||||
File(root, "starts").delete()
|
||||
return true
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun archive(root: File, dir: File, reason: Reason) {
|
||||
if (!File(dir, "overlay.apk").isFile) return
|
||||
val builds = File(root, "builds").apply { mkdirs() }
|
||||
var stamp = System.currentTimeMillis()
|
||||
while (File(builds, stamp.toString()).exists()) stamp++
|
||||
val target = File(builds, stamp.toString())
|
||||
if (!dir.renameTo(target)) return
|
||||
File(target, "reason").writeText(reason.name)
|
||||
builds.listFiles().orEmpty().sortedByDescending { it.name.toLongOrNull() ?: 0L }.drop(KEEP_BUILDS).forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun failedStarts(root: File) = File(root, "starts").takeIf { it.isFile }?.readText()?.trim()?.toIntOrNull() ?: 0
|
||||
|
||||
private fun refuse(root: File, mainProcess: Boolean, reason: Reason) {
|
||||
skipped = reason.name
|
||||
Log.w(TAG, "Lab build turned off: $reason")
|
||||
if (!mainProcess) return
|
||||
archive(root, File(root, "active"), reason)
|
||||
File(root, "starts").delete()
|
||||
File(root, "last-off-reason").writeText(reason.name)
|
||||
}
|
||||
|
||||
private fun skip(reason: String) {
|
||||
skipped = reason
|
||||
Log.w(TAG, "Lab build not loaded: $reason")
|
||||
}
|
||||
|
||||
private fun hasAppImage(context: Context): Boolean {
|
||||
val apk = File(context.applicationInfo.sourceDir)
|
||||
val oat = File(apk.parentFile, "oat")
|
||||
return oat.listFiles().orEmpty().any { File(it, "${apk.nameWithoutExtension}.art").isFile }
|
||||
}
|
||||
|
||||
@RequiresApi(30)
|
||||
private fun createLoader(apk: File): ResourcesLoader =
|
||||
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { fd ->
|
||||
ResourcesLoader().apply { addProvider(ResourcesProvider.loadFromApk(fd)) }
|
||||
}
|
||||
|
||||
/** Gives [resources] the Lab build's resources; contexts made from them inherit it. */
|
||||
fun addLoader(resources: Resources) {
|
||||
if (Build.VERSION.SDK_INT < 30) return
|
||||
val current = loader as? ResourcesLoader ?: return
|
||||
resources.addLoaders(current)
|
||||
}
|
||||
|
||||
private fun prependDex(classLoader: ClassLoader, apk: File) {
|
||||
val pathList = field(Class.forName("dalvik.system.BaseDexClassLoader"), "pathList").get(classLoader)!!
|
||||
val elementsField = field(pathList.javaClass, "dexElements")
|
||||
@Suppress("UNCHECKED_CAST") val installed = elementsField.get(pathList) as Array<Any?>
|
||||
val errors = ArrayList<java.io.IOException>()
|
||||
val made = try {
|
||||
pathList.javaClass.getDeclaredMethod("makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java)
|
||||
.apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader)
|
||||
} catch (_: NoSuchMethodException) {
|
||||
pathList.javaClass.getDeclaredMethod(
|
||||
"makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java, Boolean::class.javaPrimitiveType,
|
||||
).apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader, false)
|
||||
}
|
||||
errors.firstOrNull()?.let { throw it }
|
||||
@Suppress("UNCHECKED_CAST") val added = made as Array<Any?>
|
||||
if (added.isEmpty()) error("no dex in ${apk.name}")
|
||||
val merged = java.lang.reflect.Array.newInstance(installed.javaClass.componentType!!, added.size + installed.size)
|
||||
System.arraycopy(added, 0, merged, 0, added.size)
|
||||
System.arraycopy(installed, 0, merged, added.size, installed.size)
|
||||
elementsField.set(pathList, merged)
|
||||
}
|
||||
|
||||
private fun field(type: Class<*>, name: String) = type.getDeclaredField(name).apply { isAccessible = true }
|
||||
|
||||
private class Callbacks(private val root: File, private val mainProcess: Boolean) : Application.ActivityLifecycleCallbacks {
|
||||
private var settled = false
|
||||
|
||||
override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) = addLoader(activity.resources)
|
||||
|
||||
override fun onActivityResumed(activity: Activity) {
|
||||
if (settled || !mainProcess) return
|
||||
settled = true
|
||||
Handler(Looper.getMainLooper()).postDelayed({ File(root, "starts").delete() }, STABLE_AFTER_MS)
|
||||
}
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
override fun onActivityStarted(activity: Activity) = Unit
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
override fun onActivityStopped(activity: Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,8 @@ object BuildWatermark {
|
||||
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
|
||||
|
||||
fun install(app: Application) {
|
||||
val lines = lines() ?: return
|
||||
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
|
||||
val lines = (listOfNotNull(lab) + lines().orEmpty()).ifEmpty { return }
|
||||
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
|
||||
if (activity is QuestXrActivity) return
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Code
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.lab.LabOverlay
|
||||
|
||||
/**
|
||||
* Lab builds on this device: the one in use, one waiting for a restart, and the kept ones.
|
||||
* [onRebuild] offers to build a kept one again for this install, when something can.
|
||||
*/
|
||||
@Composable
|
||||
internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
|
||||
val context = LocalContext.current
|
||||
var version by remember { mutableIntStateOf(0) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
val current = remember(version) { LabOverlay.current(context) }
|
||||
val pending = remember(version) { LabOverlay.pending(context) }
|
||||
val saved = remember(version) { LabOverlay.saved(context) }
|
||||
if (current == null && pending == null && saved.isEmpty()) return
|
||||
val active = LabOverlay.active
|
||||
val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE
|
||||
val restartFailed = stringResource(R.string.lab_restart_failed)
|
||||
val canRestart = !busy && !sessionRunning
|
||||
|
||||
/** Android may have given the APK an app image again, which a Lab build cannot load over. */
|
||||
fun restart() {
|
||||
busy = true
|
||||
error = null
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
if (LabOverlay.needsRecompile(context)) WirelessAdbFix.shell(context, LabOverlay.recompileCommand(context))
|
||||
}
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
busy = false
|
||||
if (result.isSuccess) LabOverlay.restart(context)
|
||||
else error = restartFailed.format(result.exceptionOrNull()?.message.orEmpty())
|
||||
}
|
||||
}, "lab-restart").start()
|
||||
}
|
||||
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
|
||||
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
|
||||
)
|
||||
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
val rows = mutableListOf<@Composable () -> Unit>()
|
||||
if (current != null) rows += {
|
||||
BuildRow(
|
||||
current, true,
|
||||
when {
|
||||
active != null -> stringResource(R.string.lab_in_use)
|
||||
paused -> stringResource(R.string.lab_paused_row)
|
||||
else -> stringResource(R.string.lab_not_loaded, LabOverlay.skipped.orEmpty())
|
||||
},
|
||||
warn = active == null,
|
||||
) {
|
||||
if (paused) PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
|
||||
SecondaryButton(stringResource(R.string.lab_turn_off), compact = true, enabled = canRestart) { LabOverlay.turnOff(context) }
|
||||
}
|
||||
}
|
||||
if (pending != null) rows += {
|
||||
BuildRow(pending, false, stringResource(R.string.lab_waiting), warn = false) {
|
||||
PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
|
||||
}
|
||||
}
|
||||
for (build in saved) rows += {
|
||||
var armed by remember(build.dir) { mutableStateOf(false) }
|
||||
val info = build.info
|
||||
BuildRow(
|
||||
info, false,
|
||||
when {
|
||||
armed -> stringResource(R.string.lab_delete_warning)
|
||||
!build.usable -> stringResource(R.string.lab_other_install)
|
||||
build.reason == LabOverlay.Reason.DID_NOT_START -> stringResource(R.string.lab_off_did_not_start)
|
||||
else -> stringResource(R.string.lab_kept)
|
||||
},
|
||||
warn = armed || !build.usable || build.reason == LabOverlay.Reason.DID_NOT_START,
|
||||
) {
|
||||
if (!build.usable && !armed && info != null && onRebuild != null) SecondaryButton(stringResource(R.string.lab_rebuild), compact = true, enabled = !busy) {
|
||||
onRebuild(info)
|
||||
}
|
||||
if (build.usable && !armed) SecondaryButton(stringResource(R.string.lab_use), compact = true, enabled = canRestart) {
|
||||
runCatching { LabOverlay.stage(context, build) }
|
||||
.onSuccess { version++; restart() }
|
||||
.onFailure { error = it.message }
|
||||
}
|
||||
SecondaryButton(stringResource(if (armed) R.string.lab_delete_confirm else R.string.lab_delete), compact = true, enabled = !busy) {
|
||||
if (armed) {
|
||||
LabOverlay.delete(build)
|
||||
version++
|
||||
} else armed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.forEachIndexed { index, row ->
|
||||
row()
|
||||
if (index < rows.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, fontSize = 12.5.sp, color = AttentionAmber, modifier = Modifier.padding(start = 2.dp, top = 8.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BuildRow(info: LabOverlay.Info?, current: Boolean, status: String, warn: Boolean, actions: @Composable () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(34.dp).clip(Shape12)
|
||||
.background(if (current) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) {
|
||||
Icon(Icons.Outlined.Code, null, tint = if (current) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(info?.label ?: "?", fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val built = info?.built?.takeIf { it > 0 }?.let { DateUtils.getRelativeTimeSpanString(it * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString() }
|
||||
Text(listOfNotNull(status, built).joinToString(" · "), fontSize = 12.5.sp, color = if (warn) AttentionAmber else colors.onSurfaceVariant,
|
||||
maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { actions() }
|
||||
}
|
||||
}
|
||||
@@ -120,11 +120,11 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
|
||||
StatusPanel(s, u, ua, me)
|
||||
Box(Modifier.height(18.dp))
|
||||
ChannelLabel()
|
||||
ChannelPicker(u, ua)
|
||||
ChannelPicker(u, ua, s.sessionRunning)
|
||||
} else {
|
||||
ChannelLabel()
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
|
||||
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
|
||||
Box(Modifier.weight(1f)) { ChannelPicker(u, ua, s.sessionRunning) }
|
||||
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
|
||||
}
|
||||
}
|
||||
@@ -262,7 +262,7 @@ private fun ChannelLabel() {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
|
||||
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, sessionRunning: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val catalog = u.catalog
|
||||
val tests = catalog?.tests.orEmpty()
|
||||
@@ -285,6 +285,7 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
|
||||
tests.forEach { t -> TestRow(t, u.follow.pr == t.pr) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
|
||||
}
|
||||
}
|
||||
LabBuilds(sessionRunning)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user