Skip to content

Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.

Show Debloat's progress and result, the way Reset TV does

jesse-agent-23258e394097fd7
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.kt
index ece1448..30f684d 100644
--- a/app/src/main/java/app/tellyscope/MainActivity.kt
+++ b/app/src/main/java/app/tellyscope/MainActivity.kt
@@ -55,6 +55,7 @@ import app.tellyscope.ui.AccessScreen
import app.tellyscope.ui.AdvancedScreen
import app.tellyscope.ui.ConnectScreen
import app.tellyscope.ui.Copy
+import app.tellyscope.ui.DebloatRunScreen
import app.tellyscope.ui.DebloatScreen
import app.tellyscope.ui.DeviceActions
import app.tellyscope.ui.DeviceTabsScreen
@@ -338,6 +339,9 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
later = vm::launcherLater,
),
)
+ } else if (debloat && state.device.debloat != null) {
+ // Leaving mid-run only closes the screen; the run goes on, and History has each app.
+ DebloatRunScreen(state.device.debloat!!, back = { vm.closeDebloat(); debloat = false }, retry = vm::retryDebloat)
} else if (debloat) {
// Its own back handler closes the list search before leaving.
DebloatScreen(
@@ -392,7 +396,8 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
saveFile = { f -> vm.saving(f); saveFile.launch(f.name) },
cancelTransfer = vm::cancelTransfer,
remote = { remote = true },
- debloat = { debloat = true },
+ // A run that finished while Debloat was closed is done with.
+ debloat = { vm.closeDebloat(); debloat = true },
advanced = { advanced = true },
history = { history = true },
reset = { vm.openReset(); resetting = true },
diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.kt
index 83236ed..a19306c 100644
--- a/app/src/main/java/app/tellyscope/ui/Copy.kt
+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt
@@ -273,12 +273,6 @@ object Copy {
fun mb(v: Int) = if (v >= 1024) "%.1f GB".format(v / 1024.0) else "$v MB"
- fun disabledSuggested(done: Int, of: Int) = when {
- done == of -> "Disabled $done ${if (done == 1) "app" else "apps"}. Undo any of them from History."
- done == 0 -> "The TV didn't disable any of them."
- else -> "Disabled $done of $of apps; the TV refused the rest. Undo any of them from History."
- }
-
fun uninstallTitle(app: String) = "Uninstall $app?"
/** The confirm for the launcher on Home: Home goes back first, and a failed step stops it. */
@@ -642,6 +636,16 @@ object Copy {
fun stillHome(app: String) = "$app is still the home screen"
fun tryAgain(app: String?) = if (app != null) "Try $app again" else "Try again"
+ /** Debloat while it turns the ticked apps off, then its result. */
+ fun disablingApps(done: Int, of: Int) = "Turning off apps: $done of $of. Keep the TV on and connected."
+ const val DISABLING = "Disabling…"
+ const val DISABLING_NOTE = "Nothing is deleted. Turn any back on from History."
+ const val DEBLOAT_DONE = "Debloat done"
+ const val DEBLOAT_PARTLY = "Debloat partly done"
+ const val DEBLOAT_RESULT_TEXT = "Nothing was deleted; undo any of them from History."
+ fun turnedOff(done: Int, of: Int) = if (done == of) "Turned off ${apps(of)}" else "Turned off $done of ${apps(of)}"
+ fun stillOn(app: String) = "$app is still on"
+
/** Under History in the menu, and on top of the History screen: apps Restore everything turns back on. */
fun stillOff(n: Int) = if (n == 1) "1 app still off" else "$n apps still off"
fun stillOffTitle(n: Int) = if (n == 1) "1 app Tellyscope turned off is still off" else "$n apps Tellyscope turned off are still off"
diff --git a/app/src/main/java/app/tellyscope/ui/DebloatRunScreen.kt b/app/src/main/java/app/tellyscope/ui/DebloatRunScreen.kt
new file mode 100644
index 0000000..b46e6ca
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/DebloatRunScreen.kt
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.Warning
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+
+/**
+ * Debloat after "Yes, disable them": the ticked apps, each marked done, running, waiting or
+ * refused with the TV's reason, under a bar pinned to the top. Then Reset TV's result layout.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun DebloatRunScreen(run: DebloatRun, back: () -> Unit, retry: () -> Unit) {
+ BackHandler(onBack = back)
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ title = { Text("Debloat") },
+ navigationIcon = { IconButton(onClick = back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") } },
+ )
+ },
+ bottomBar = {
+ Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
+ when {
+ !run.ran -> Button(onClick = {}, enabled = false) { Text(Copy.DISABLING) }
+ run.failed.isEmpty() -> Button(onClick = back) { Text("Done") }
+ else -> {
+ TextButton(onClick = back) { Text("Done") }
+ val one = run.failed.keys.singleOrNull()?.let { pkg -> run.apps.first { it.packageName == pkg }.label }
+ Button(onClick = retry) { Text(Copy.tryAgain(one)) }
+ }
+ }
+ }
+ },
+ ) { pad ->
+ Column(Modifier.fillMaxSize().padding(pad)) {
+ if (run.ran) Result(run) else Progress(run)
+ }
+ }
+}
+
+private enum class Mark { Done, Running, Waiting, Failed }
+
+@Composable
+private fun Progress(run: DebloatRun) {
+ val c = MaterialTheme.colorScheme
+ // Pinned: the bar and the count stay in view while the list scrolls.
+ LinearProgressIndicator(
+ progress = { run.at.toFloat() / run.apps.size.coerceAtLeast(1) },
+ modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 8.dp),
+ )
+ Text(
+ Copy.disablingApps(run.at, run.apps.size),
+ style = MaterialTheme.typography.bodyMedium,
+ color = c.onSurfaceVariant,
+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 16.dp),
+ )
+ LazyColumn(contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 24.dp)) {
+ itemsIndexed(run.apps, key = { _, a -> a.packageName }) { i, a ->
+ val why = run.failed[a.packageName]
+ val mark = when {
+ why != null -> Mark.Failed
+ i < run.at -> Mark.Done
+ i == run.at -> Mark.Running
+ else -> Mark.Waiting
+ }
+ Surface(color = c.surfaceContainerLow, shape = groupShape(i, run.apps.size), modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
+ // Name over package, as the confirm shows them.
+ Column(Modifier.weight(1f)) {
+ Text(a.label, style = MaterialTheme.typography.bodyLarge)
+ Text(a.packageName, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)
+ if (why != null) Text(reason(why), style = MaterialTheme.typography.bodyMedium, color = c.error)
+ }
+ Spacer(Modifier.width(16.dp))
+ when (mark) {
+ Mark.Done -> Icon(HistoryIcons.TurnedOn, contentDescription = "Done", tint = c.primary)
+ Mark.Running -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
+ Mark.Waiting -> Icon(ResetIcons.Waiting, contentDescription = "Waiting", tint = c.onSurfaceVariant)
+ Mark.Failed -> Icon(Icons.Default.Warning, contentDescription = "Didn't turn off", tint = c.error)
+ }
+ }
+ }
+ }
+ item {
+ Text(
+ Copy.DISABLING_NOTE,
+ style = MaterialTheme.typography.bodySmall,
+ color = c.onSurfaceVariant,
+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp),
+ )
+ }
+ }
+}
+
+/** After the run: what turned off, then one row per app still on, with the TV's reason. */
+@Composable
+private fun Result(run: DebloatRun) {
+ val ok = run.failed.isEmpty()
+ val still = run.apps.filter { it.packageName in run.failed }
+ val off = run.apps.size - still.size
+ // No "Turned off 0 of n" row with a tick when the TV refused every one.
+ val top = if (off > 0) 1 else 0
+ LazyColumn(contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 32.dp, bottom = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ item { ResultHead(ok, if (ok) Copy.DEBLOAT_DONE else Copy.DEBLOAT_PARTLY, Copy.DEBLOAT_RESULT_TEXT) }
+ if (off > 0) item { ResultRow(Copy.turnedOff(off, run.apps.size), null, groupShape(0, top + still.size)) }
+ itemsIndexed(still) { i, a -> ResultRow(Copy.stillOn(a.label), reason(run.failed.getValue(a.packageName)), groupShape(i + top, top + still.size)) }
+ }
+}
+
+/** The TV's reason as a sentence. */
+private fun reason(why: String) = why.replaceFirstChar(Char::uppercase).trimEnd('.') + "."
diff --git a/app/src/main/java/app/tellyscope/ui/ListsCard.kt b/app/src/main/java/app/tellyscope/ui/ListsCard.kt
index 130d017..90687d8 100644
--- a/app/src/main/java/app/tellyscope/ui/ListsCard.kt
+++ b/app/src/main/java/app/tellyscope/ui/ListsCard.kt
@@ -71,6 +71,7 @@ import app.tellyscope.data.DeviceKind
import app.tellyscope.data.DeviceState
import app.tellyscope.data.ListEntry
import app.tellyscope.data.RELEASES
+import app.tellyscope.data.ResetApp
import app.tellyscope.data.Suggested
import app.tellyscope.data.SuggestedGroup
import app.tellyscope.data.Suggestions
@@ -88,14 +89,16 @@ private fun Muted(text: String) {
/**
* Debloat opens on the apps to turn off, under a card naming what they came from: this TV's model
* list, else its maker's lists, unticked, else the TV's own apps to pick by hand. "Not this TV?"
- * searches every list instead. The confirm names each app before anything runs.
+ * searches every list instead. The confirm names each app before anything runs; once it's
+ * confirmed, MainActivity shows [DebloatRunScreen] in its place.
*/
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun DebloatScreen(
lists: Suggestions?,
onPick: (String) -> Unit,
- onDisable: (List<String>) -> Unit,
+ /** The ticked apps, name and package, in the order the confirm lists them. */
+ onDisable: (List<ResetApp>) -> Unit,
back: () -> Unit,
snackbar: SnackbarHostState = remember { SnackbarHostState() },
/** The user's own list source, null for the default; set in Settings. */
@@ -148,7 +151,7 @@ fun DebloatScreen(
if (confirming && groups != null) {
// The dialog's list is exactly what gets disabled.
val apps = groups.flatMap { it.packages }.filter { it.pkg in ticked }
- DisableDialog(apps, onDisable = { confirming = false; onDisable(apps.map { it.pkg }); back() }, onDismiss = { confirming = false }, enabled = !busy)
+ DisableDialog(apps, onDisable = { confirming = false; onDisable(apps.map { ResetApp(it.pkg, it.label) }) }, onDismiss = { confirming = false }, enabled = !busy)
}
val use = { marked?.let { if (it != ready?.list?.id) { chosen = it; onPick(it) } }; searching = false }
val keyboard = LocalSoftwareKeyboardController.current
diff --git a/app/src/main/java/app/tellyscope/ui/ResetScreen.kt b/app/src/main/java/app/tellyscope/ui/ResetScreen.kt
index 1fbcd39..cfa4f62 100644
--- a/app/src/main/java/app/tellyscope/ui/ResetScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/ResetScreen.kt
@@ -53,6 +53,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
+import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.PathParser
@@ -260,10 +261,8 @@ private fun AppList(apps: List<ResetApp>) {
private const val SHOWN = 7
/** After a run: a cookie badge, what changed, and per part what worked, with the first failure's reason. */
-@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun Result(plan: ResetPlan, failed: List<ResetFailure>) {
- val c = MaterialTheme.colorScheme
val ok = failed.isEmpty()
fun failures(part: ResetPart) = failed.filter { it.part == part }
val on = plan.turnOn.size - failures(ResetPart.TurnOn).size
@@ -271,25 +270,7 @@ private fun Result(plan: ResetPlan, failed: List<ResetFailure>) {
val home = plan.home?.takeIf { failures(ResetPart.Home).isEmpty() }
LazyColumn(contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 32.dp, bottom = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
item {
- Box(
- Modifier.size(96.dp).clip(MaterialShapes.Cookie9Sided.toShape()).background(if (ok) c.primaryContainer else c.errorContainer),
- contentAlignment = Alignment.Center,
- ) {
- Icon(if (ok) Icons.Default.Check else Icons.Default.Warning, contentDescription = null, Modifier.size(44.dp), tint = if (ok) c.onPrimaryContainer else c.onErrorContainer)
- }
- Text(
- if (ok) Copy.RESET_DONE else Copy.RESET_PARTLY,
- style = MaterialTheme.typography.headlineSmall,
- textAlign = TextAlign.Center,
- modifier = Modifier.padding(top = 24.dp),
- )
- Text(
- if (ok) Copy.resetDoneText(on + back, home?.toLabel) else Copy.resetPartlyText(failed.size),
- style = MaterialTheme.typography.bodyMedium,
- color = c.onSurfaceVariant,
- textAlign = TextAlign.Center,
- modifier = Modifier.padding(start = 8.dp, end = 8.dp, top = 12.dp, bottom = 24.dp),
- )
+ ResultHead(ok, if (ok) Copy.RESET_DONE else Copy.RESET_PARTLY, if (ok) Copy.resetDoneText(on + back, home?.toLabel) else Copy.resetPartlyText(failed.size))
}
val rows = ResetPart.entries.filter { count(plan, it) > 0 }
itemsIndexed(rows) { i, part ->
@@ -301,16 +282,46 @@ private fun Result(plan: ResetPlan, failed: List<ResetFailure>) {
ResetPart.Home -> plan.home!!.let { if (miss.all { m -> m.app != null }) Copy.isHome(it.toLabel) else Copy.stillHome(it.fromLabel) }
}
val why = miss.firstOrNull()?.let { f -> (f.app?.takeIf { f.part != ResetPart.Home }?.let { "${it.label}: " } ?: "") + f.reason.replaceFirstChar(Char::uppercase).trimEnd('.') + "." }
- Surface(color = c.surfaceContainerLow, shape = groupShape(i, rows.size), modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
- Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
- if (miss.isEmpty()) Icon(HistoryIcons.TurnedOn, contentDescription = null, tint = c.primary)
- else Icon(Icons.Default.Warning, contentDescription = null, tint = c.error)
- Spacer(Modifier.width(16.dp))
- Column(Modifier.weight(1f)) {
- Text(line, style = MaterialTheme.typography.bodyLarge)
- if (why != null) Text(why, style = MaterialTheme.typography.bodyMedium, color = c.error)
- }
- }
+ ResultRow(line, why, groupShape(i, rows.size))
+ }
+ }
+}
+
+/** The top of a result, shared with Debloat's: a cookie badge, a check or a warning, the title and what happened. */
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+@Composable
+internal fun ResultHead(ok: Boolean, title: String, text: String) {
+ val c = MaterialTheme.colorScheme
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Box(
+ Modifier.size(96.dp).clip(MaterialShapes.Cookie9Sided.toShape()).background(if (ok) c.primaryContainer else c.errorContainer),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(if (ok) Icons.Default.Check else Icons.Default.Warning, contentDescription = null, Modifier.size(44.dp), tint = if (ok) c.onPrimaryContainer else c.onErrorContainer)
+ }
+ Text(title, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 24.dp))
+ Text(
+ text,
+ style = MaterialTheme.typography.bodyMedium,
+ color = c.onSurfaceVariant,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.padding(start = 8.dp, end = 8.dp, top = 12.dp, bottom = 24.dp),
+ )
+ }
+}
+
+/** One grouped row of a result: what worked, or what didn't with [why] in red under it. */
+@Composable
+internal fun ResultRow(line: String, why: String?, shape: Shape) {
+ val c = MaterialTheme.colorScheme
+ Surface(color = c.surfaceContainerLow, shape = shape, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
+ if (why == null) Icon(HistoryIcons.TurnedOn, contentDescription = null, tint = c.primary)
+ else Icon(Icons.Default.Warning, contentDescription = null, tint = c.error)
+ Spacer(Modifier.width(16.dp))
+ Column(Modifier.weight(1f)) {
+ Text(line, style = MaterialTheme.typography.bodyLarge)
+ if (why != null) Text(why, style = MaterialTheme.typography.bodyMedium, color = c.error)
}
}
}
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
index 8f009f1..0b39719 100644
--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -36,6 +36,7 @@ import app.tellyscope.data.NetworkInfo
import app.tellyscope.data.NotAnApp
import app.tellyscope.data.PhoneStorage
import app.tellyscope.data.PickedApp
+import app.tellyscope.data.ResetApp
import app.tellyscope.data.ResetFailure
import app.tellyscope.data.ResetPart
import app.tellyscope.data.ResetPlan
@@ -128,6 +129,20 @@ data class DeviceUi(
val launcherCardHidden: Boolean = true,
/** Reset TV, while its screen is open; null otherwise. */
val reset: ResetUi? = null,
+ /** Debloat's run, from "Yes, disable them" until its screen closes; null otherwise. */
+ val debloat: DebloatRun? = null,
+)
+
+/**
+ * Debloat turning off the ticked [apps], in order. [at] counts the ones the TV has answered for,
+ * and [failed] holds why each refused one is still on. [ran] once the last has answered; Try again
+ * runs just the failed ones.
+ */
+data class DebloatRun(
+ val apps: List<ResetApp>,
+ val at: Int = 0,
+ val failed: Map<String, String> = emptyMap(),
+ val ran: Boolean = false,
)
/**
@@ -1499,33 +1514,48 @@ class TellyscopeViewModel(
viewModelScope.launch(Dispatchers.IO) { keyHaptics?.on = on }
}
- /** Disables the ticked suggestions one by one, each recorded in History with its own undo. */
- fun disableSuggested(packages: List<String>) {
+ /** Disables the ticked suggestions one by one, each recorded in History with its own undo; Debloat shows how far. */
+ fun disableSuggested(apps: List<ResetApp>) {
val id = _state.value.selectedId ?: return
- _state.update { it.copy(device = it.device.copy(busy = DISABLING)) }
+ _state.update { it.copy(device = it.device.copy(busy = DISABLING, debloat = DebloatRun(apps))) }
viewModelScope.launch {
- var done = 0
// One change for the whole list: the TV's stats are read again once, after the last app.
source.batch(id) {
- for (pkg in packages) {
- try {
- source.act(id, Action.Disable, pkg)
- done++
+ for (app in apps) {
+ val why = try {
+ source.act(id, Action.Disable, app.packageName)
+ null
} catch (e: CancellationException) {
throw e
- } catch (_: Exception) {
- // The TV refused this one or dropped; the count says so.
+ } catch (e: Exception) {
+ // The TV refused this one or dropped; its row says why.
+ e.message ?: "the TV refused"
+ }
+ updateDevice(id) { d ->
+ d.copy(debloat = d.debloat?.let { r -> r.copy(at = r.at + 1, failed = if (why == null) r.failed else r.failed + (app.packageName to why)) })
}
}
}
- _notice.value = Copy.disabledSuggested(done, packages.size)
- val apps = runCatching { source.apps(id) }.getOrNull()
+ val read = runCatching { source.apps(id) }.getOrNull()
val history = source.history(id)
- updateDevice(id) { it.copy(apps = apps ?: it.apps, busy = null, history = history) }
- loadLists(id) { apps ?: source.apps(id) }
+ updateDevice(id) { it.copy(apps = read ?: it.apps, busy = null, history = history, debloat = it.debloat?.copy(ran = true)) }
+ loadLists(id) { read ?: source.apps(id) }
}
}
+ /** Try again on Debloat's result: just the apps the TV refused. */
+ fun retryDebloat() {
+ val run = _state.value.device.debloat ?: return
+ if (_state.value.device.busy != null) return
+ disableSuggested(run.apps.filter { it.packageName in run.failed })
+ }
+
+ /** Debloat closed: a finished run is forgotten, one still going shows again when it reopens. */
+ fun closeDebloat() {
+ val id = _state.value.selectedId ?: return
+ updateDevice(id) { if (it.busy == DISABLING) it else it.copy(debloat = null) }
+ }
+
/**
* Sends one key and waits for the TV to take it; false when it didn't. The remote screen holds
* a D-pad key by calling this in a loop, which stops at the first false, so a lost TV shows once.
diff --git a/app/src/test/java/app/tellyscope/DebloatRunTest.kt b/app/src/test/java/app/tellyscope/DebloatRunTest.kt
new file mode 100644
index 0000000..eb47fa4
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/DebloatRunTest.kt
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import androidx.lifecycle.viewModelScope
+import app.tellyscope.data.Action
+import app.tellyscope.data.Device
+import app.tellyscope.data.DeviceSource
+import app.tellyscope.data.DeviceState
+import app.tellyscope.data.FakeDeviceSource
+import app.tellyscope.data.HistoryEntry
+import app.tellyscope.data.ResetApp
+import app.tellyscope.data.ScanHit
+import app.tellyscope.data.ScanKind
+import app.tellyscope.data.Snapshot
+import app.tellyscope.ui.DISABLING
+import app.tellyscope.ui.TellyscopeViewModel
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.setMain
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+
+private val KIDS = ResetApp("com.google.android.youtube.tvkids", "YouTube Kids")
+private val SPORTS = ResetApp("com.google.android.tvrecommendations.sports", "Sports")
+private val FEEDBACK = ResetApp("com.google.android.feedback", "Google Feedback")
+
+/** A TV that turns apps off when asked, except the ones in [refuse], and can hold the next one at [gate]. */
+private class RefusingTv : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {
+ val refuse = mutableMapOf<String, String>()
+ val asked = mutableListOf<String>()
+ var gate: CompletableDeferred<Unit>? = null
+
+ override suspend fun known() = listOf(Device("tv", ScanHit("tv", 5555, ScanKind.Classic, "tv", null), DeviceState.Online, null, null, null, 0L))
+
+ override fun live(deviceId: String): Flow<Snapshot> = emptyFlow()
+
+ override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {
+ gate?.await()
+ asked += packageName
+ refuse[packageName]?.let { throw IllegalStateException(it) }
+ return HistoryEntry(1, deviceId, 0, action, packageName, packageName, Action.Enable, null)
+ }
+}
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class DebloatRunTest {
+ private val dispatcher = StandardTestDispatcher()
+ private val test = TestScope(dispatcher)
+ private val source = RefusingTv()
+ private lateinit var vm: TellyscopeViewModel
+
+ @Before fun setUp() = Dispatchers.setMain(dispatcher)
+
+ @After fun tearDown() {
+ vm.viewModelScope.cancel()
+ Dispatchers.resetMain()
+ }
+
+ private fun TestScope.open() {
+ vm = TellyscopeViewModel(source, clock = { 0L })
+ runCurrent()
+ }
+
+ private val run get() = vm.state.value.device.debloat
+
+ @Test fun eachAppIsMarkedAndARefusedOneKeepsItsReason() = with(test) {
+ open()
+ source.refuse[SPORTS.packageName] = "the TV refused it"
+ vm.disableSuggested(listOf(KIDS, SPORTS, FEEDBACK))
+ runCurrent()
+ val r = run!!
+ assertTrue(r.ran)
+ assertEquals(3, r.at)
+ assertEquals(mapOf(SPORTS.packageName to "the TV refused it"), r.failed)
+ assertNull(vm.state.value.device.busy)
+ // The result replaces the old snackbar.
+ assertNull(vm.notice.value)
+ }
+
+ @Test fun theCountMovesAsEachAppAnswers() = with(test) {
+ open()
+ val gate = CompletableDeferred<Unit>()
+ source.gate = gate
+ vm.disableSuggested(listOf(KIDS, SPORTS))
+ runCurrent()
+ // Debloat switches to progress at once, before the TV has answered for any app.
+ assertEquals(0, run!!.at)
+ assertFalse(run!!.ran)
+ assertEquals(DISABLING, vm.state.value.device.busy)
+ source.gate = null
+ gate.complete(Unit)
+ runCurrent()
+ assertEquals(2, run!!.at)
+ assertTrue(run!!.ran)
+ }
+
+ @Test fun tryAgainRunsOnlyTheRefusedApps() = with(test) {
+ open()
+ source.refuse[SPORTS.packageName] = "the TV refused it"
+ vm.disableSuggested(listOf(KIDS, SPORTS, FEEDBACK))
+ runCurrent()
+ source.refuse.clear()
+ source.asked.clear()
+ vm.retryDebloat()
+ runCurrent()
+ assertEquals(listOf(SPORTS.packageName), source.asked)
+ assertEquals(listOf(SPORTS), run!!.apps)
+ assertTrue(run!!.failed.isEmpty())
+ }
+
+ @Test fun closingMidRunKeepsTheRunAndClosingAfterForgetsIt() = with(test) {
+ open()
+ val gate = CompletableDeferred<Unit>()
+ source.gate = gate
+ vm.disableSuggested(listOf(KIDS))
+ runCurrent()
+ vm.closeDebloat()
+ assertNotNull(run)
+ source.gate = null
+ gate.complete(Unit)
+ runCurrent()
+ vm.closeDebloat()
+ assertNull(run)
+ }
+}