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.
Keep snackbars up, land results on their own TV, stop runaway keys
jesse-agent-23294a1d8f82aa3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 552b3be..93289fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,3 +21,6 @@ until this file has a section for its version.- **New:** An icon shows whether each device is a TV, projector, Fire TV or stick. [#18](../../pull/18)- **Improved:** The confirm before disabling suggested apps names every app. [#19](../../pull/19)- **Improved:** System updaters, Wi-Fi resources and Chrome's library are now protected. [#19](../../pull/19)+- **Fixed:** Done and error messages stay on screen long enough to read. [#20](../../pull/20)+- **Fixed:** Undo and results always go to the TV the action ran on. [#20](../../pull/20)+- **Fixed:** Holding a remote key no longer freezes the app or outlives the TV. [#20](../../pull/20)diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex 4f7436c..a1fee2d 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -37,12 +37,15 @@ import app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.ui.Copyimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreen+import app.tellyscope.ui.Doneimport app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.RemoteActionsimport app.tellyscope.ui.RemoteScreenimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.TellyscopeViewModelimport app.tellyscope.ui.theme.TellyscopeTheme+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.filterNotNullclass MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {@@ -117,8 +120,6 @@ class MainActivity : ComponentActivity() {@Composablefun TellyscopeApp(vm: TellyscopeViewModel) {val state by vm.state.collectAsStateWithLifecycle()- val done by vm.done.collectAsStateWithLifecycle()- val notice by vm.notice.collectAsStateWithLifecycle()val snackbar = remember { SnackbarHostState() }var adding by rememberSaveable { mutableStateOf(false) }var remote by rememberSaveable { mutableStateOf(false) }@@ -128,22 +129,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {val pickFile = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(vm::push) }val saveFile = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream"), vm::saveTo)- LaunchedEffect(done) {- val entry = done ?: return@LaunchedEffect- vm.doneShown()- val result = snackbar.showSnackbar(- message = Copy.done(entry.action, entry.label),- actionLabel = entry.undo?.let(Copy::undo),- duration = SnackbarDuration.Long,- )- if (result == SnackbarResult.ActionPerformed) vm.undo(entry)- }-- LaunchedEffect(notice) {- val message = notice ?: return@LaunchedEffect- vm.noticeShown()- snackbar.showSnackbar(message, duration = SnackbarDuration.Long)- }+ Snackbars(snackbar, vm.done, vm.notice, vm::doneShown, vm::noticeShown) { vm.undo(it.entry, it.deviceId) }// A newly connected TV becomes the selection; leave the add flow then, not on tap.LaunchedEffect(state.selectedId) { adding = false; remote = false }@@ -205,3 +191,35 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {)}}++/**+ * Shows each done and notice message once. They are collected rather than used as effect keys:+ * clearing a message changes the key, which would cancel its own snackbar before anyone saw it.+ */+@Composable+internal fun Snackbars(+ host: SnackbarHostState,+ done: StateFlow<Done?>,+ notice: StateFlow<String?>,+ doneShown: () -> Unit,+ noticeShown: () -> Unit,+ undo: (Done) -> Unit,+) {+ LaunchedEffect(host, done) {+ done.filterNotNull().collect { d ->+ doneShown()+ val result = host.showSnackbar(+ message = Copy.done(d.entry.action, d.entry.label),+ actionLabel = d.entry.undo?.let(Copy::undo),+ duration = SnackbarDuration.Long,+ )+ if (result == SnackbarResult.ActionPerformed) undo(d)+ }+ }+ LaunchedEffect(host, notice) {+ notice.filterNotNull().collect { message ->+ noticeShown()+ host.showSnackbar(message, duration = SnackbarDuration.Long)+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt b/app/src/main/java/app/tellyscope/ui/RemoteScreen.ktindex ef04cdd..670cbe5 100644--- a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt@@ -81,10 +81,11 @@ import app.tellyscope.adb.RemoteKeyimport app.tellyscope.data.DeviceStateimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch+import kotlinx.coroutines.yielddata class RemoteActions(- /** Suspends until the TV took the key, so a held key never queues up presses. */- val press: suspend (RemoteKey) -> Unit = {},+ /** Suspends until the TV answers, so a held key never queues up presses. False when it didn't take the key. */+ val press: suspend (RemoteKey) -> Boolean = { true },/** Returns why the text can't be typed, or null once it's sent. */val type: (String) -> String? = { null },val reboot: () -> Unit = {},@@ -94,6 +95,17 @@ data class RemoteActions(/** A held key repeats after this, then as fast as the TV takes them. */private const val REPEAT_AFTER_MS = 400L+/**+ * One press, then repeats while [held] for keys that repeat. Stops at the first key the TV didn't+ * take (refused, dropped, or no TV selected), and yields between repeats, so a press that answers+ * at once can't keep the main thread busy.+ */+internal suspend fun repeatWhileHeld(key: RemoteKey, held: () -> Boolean, press: suspend (RemoteKey) -> Boolean) {+ if (!press(key) || !key.repeats) return+ delay(REPEAT_AFTER_MS)+ while (held() && press(key)) yield()+}+@OptIn(ExperimentalMaterial3Api::class)@Composablefun RemoteScreen(@@ -171,7 +183,7 @@ fun RemoteScreen(/** The four arrows around a big OK, shaped like the remote in the user's other hand. */@Composable-private fun DPad(enabled: Boolean, press: suspend (RemoteKey) -> Unit) {+private fun DPad(enabled: Boolean, press: suspend (RemoteKey) -> Boolean) {Surface(Modifier.size(272.dp), shape = CircleShape, color = MaterialTheme.colorScheme.surfaceContainerHigh) {Box {val arrow = Modifier.size(80.dp)@@ -199,7 +211,7 @@ private fun DPad(enabled: Boolean, press: suspend (RemoteKey) -> Unit) {}@Composable-private fun RoundKey(key: RemoteKey, label: String, enabled: Boolean, press: suspend (RemoteKey) -> Unit, icon: @Composable () -> Unit) {+private fun RoundKey(key: RemoteKey, label: String, enabled: Boolean, press: suspend (RemoteKey) -> Boolean, icon: @Composable () -> Unit) {Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {KeySurface(key, label, enabled, press, CircleShape, MaterialTheme.colorScheme.secondaryContainer, Modifier.size(64.dp), icon)Text(label, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)@@ -211,7 +223,7 @@ private fun PillKey(key: RemoteKey,label: String,enabled: Boolean,- press: suspend (RemoteKey) -> Unit,+ press: suspend (RemoteKey) -> Boolean,modifier: Modifier = Modifier,content: @Composable () -> Unit,) = KeySurface(key, label, enabled, press, MaterialTheme.shapes.extraLarge, MaterialTheme.colorScheme.secondaryContainer, modifier.height(56.dp), content)@@ -225,7 +237,7 @@ private fun KeySurface(key: RemoteKey,label: String,enabled: Boolean,- press: suspend (RemoteKey) -> Unit,+ press: suspend (RemoteKey) -> Boolean,shape: Shape,color: Color,modifier: Modifier = Modifier,@@ -253,12 +265,7 @@ private fun KeySurface(interactions.tryEmit(p)haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)var held = true- scope.launch {- press(key)- if (!key.repeats) return@launch- delay(REPEAT_AFTER_MS)- while (held) press(key)- }+ scope.launch { repeatWhileHeld(key, { held }, press) }waitForUpOrCancellation()held = falseinteractions.tryEmit(PressInteraction.Release(p))diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex cb6a648..b52e3c0 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -117,6 +117,9 @@ data class UiState(val selected: Device? get() = devices.firstOrNull { it.id == selectedId }}+/** An action that went through on [deviceId]; the snackbar offers its undo. */+data class Done(val deviceId: String, val entry: HistoryEntry)+/** A restart in progress: [down] once the TV has dropped, so its coming back can be told apart from not having left. */data class Restart(val since: Long, val down: Boolean = false)@@ -136,9 +139,9 @@ class TellyscopeViewModel(private val _state = MutableStateFlow(UiState(now = clock()))val state: StateFlow<UiState> = _state.asStateFlow()- /** One-shot "done, undo?" messages for the snackbar. */- private val _done = MutableStateFlow<HistoryEntry?>(null)- val done: StateFlow<HistoryEntry?> = _done.asStateFlow()+ /** One-shot "done, undo?" messages for the snackbar, with the TV they happened on. */+ private val _done = MutableStateFlow<Done?>(null)+ val done: StateFlow<Done?> = _done.asStateFlow()/** One-shot snackbar lines: the TV refused, went away mid-action, or a restore or copy finished. */private val _notice = MutableStateFlow<String?>(null)@@ -283,7 +286,9 @@ class TellyscopeViewModel(mediumJob = viewModelScope.launch {// A TV that drops mid-read throws; the live flow ends and the offline card takes over.try {- _state.update { it.copy(device = it.device.copy(apps = source.apps(id!!))) }+ // Read first: update {} may run its block again, and must never call the TV.+ val apps = source.apps(id!!)+ updateDevice(id) { it.copy(apps = apps) }loadFiles()while (true) {val net = source.network(id!!)@@ -348,14 +353,22 @@ class TellyscopeViewModel(run(pkg, action)}- fun undo(entry: HistoryEntry) {+ /**+ * Undoes [entry] on the TV it happened on. The snackbar passes [deviceId] because the user may+ * have switched TVs since; History only lists the selected TV's entries.+ */+ fun undo(entry: HistoryEntry, deviceId: String? = _state.value.selectedId) {val undo = entry.undo ?: return- run(entry.packageName, undo, undoing = entry.id)+ run(entry.packageName, undo, undoing = entry.id, id = deviceId)}- private fun run(pkg: String, action: Action, undoing: Long? = null) {- val id = _state.value.selectedId ?: return- _state.update { it.copy(device = it.device.copy(pending = null, busy = pkg)) }+ /** Changes [id]'s page only while it is still the one shown; a result for another TV is dropped. */+ private fun updateDevice(id: String, f: (DeviceUi) -> DeviceUi) =+ _state.update { s -> if (s.selectedId == id) s.copy(device = f(s.device)) else s }++ private fun run(pkg: String, action: Action, undoing: Long? = null, id: String? = _state.value.selectedId) {+ if (id == null) return+ updateDevice(id) { it.copy(pending = null, busy = pkg) }viewModelScope.launch {// The source throws with the user-facing reason when the TV refuses.val (entry, apps) = try {@@ -364,13 +377,13 @@ class TellyscopeViewModel(throw e} catch (e: Exception) {// Anything else (a dropped socket) still must not crash the app.- _state.update { it.copy(device = it.device.copy(busy = null)) }+ updateDevice(id) { it.copy(busy = null) }_notice.value = e.message?.replaceFirstChar(Char::uppercase) ?: "That didn't work."return@launch}val history = source.history(id)- _state.update { s -> s.copy(device = s.device.copy(apps = apps, busy = null, history = history)) }- if (undoing == null) _done.value = entry+ updateDevice(id) { it.copy(apps = apps, busy = null, history = history) }+ if (undoing == null) _done.value = Done(id, entry)}}@@ -391,7 +404,7 @@ class TellyscopeViewModel(} catch (_: Exception) {SideloadUi(SideloadUi.Step.Failed, error = Copy.SIDELOAD_LOST)}- setSideload(ui)+ updateDevice(id) { it.copy(sideload = ui) }}}@@ -409,16 +422,16 @@ class TellyscopeViewModel(} catch (e: CancellationException) {throw e} catch (_: Exception) {- return@launch setSideload(ready.copy(step = SideloadUi.Step.Failed, error = Copy.SIDELOAD_LOST))+ return@launch updateDevice(id) { it.copy(sideload = ready.copy(step = SideloadUi.Step.Failed, error = Copy.SIDELOAD_LOST)) }}when (r) {InstallResult.Done -> {- setSideload(ready.copy(step = SideloadUi.Step.Installed))- runCatching { source.apps(id) }.onSuccess { apps -> _state.update { it.copy(device = it.device.copy(apps = apps)) } }+ updateDevice(id) { it.copy(sideload = ready.copy(step = SideloadUi.Step.Installed)) }+ runCatching { source.apps(id) }.onSuccess { apps -> updateDevice(id) { it.copy(apps = apps) } }+ }+ is InstallResult.Refused -> updateDevice(id) {+ it.copy(sideload = ready.copy(step = SideloadUi.Step.Failed, error = Copy.installRefused(r.reason, app.label), detail = r.detail))}- is InstallResult.Refused -> setSideload(- ready.copy(step = SideloadUi.Step.Failed, error = Copy.installRefused(r.reason, app.label), detail = r.detail),- )}}}@@ -565,9 +578,7 @@ class TellyscopeViewModel(}val apps = runCatching { source.apps(id) }.getOrNull()val history = source.history(id)- _state.update { s ->- s.copy(device = s.device.copy(apps = apps ?: s.device.apps, busy = null, history = history))- }+ updateDevice(id) { it.copy(apps = apps ?: it.apps, busy = null, history = history) }}}@@ -610,26 +621,25 @@ class TellyscopeViewModel(_notice.value = Copy.disabledSuggested(done, packages.size)val apps = runCatching { source.apps(id) }.getOrNull()val history = source.history(id)- _state.update { s ->- s.copy(device = s.device.copy(apps = apps ?: s.device.apps, busy = null, history = history))- }+ updateDevice(id) { it.copy(apps = apps ?: it.apps, busy = null, history = history) }loadLists(id)}}/**- * Sends one key and waits for the TV to take it. The remote screen holds a D-pad key by- * calling this in a loop. A lost TV shows once, not once per repeat.+ * 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.*/- suspend fun press(key: RemoteKey) {- val id = _state.value.selectedId ?: return- keys.withLock {+ suspend fun press(key: RemoteKey): Boolean {+ val id = _state.value.selectedId ?: return false+ return keys.withLock {try {- if (!source.press(id, key)) _notice.value = Copy.KEY_REFUSED+ source.press(id, key).also { if (!it) _notice.value = Copy.KEY_REFUSED }} catch (e: CancellationException) {throw e} catch (_: Exception) {_notice.value = Copy.REMOTE_LOST+ false}}}diff --git a/app/src/test/java/app/tellyscope/RemoteRepeatTest.kt b/app/src/test/java/app/tellyscope/RemoteRepeatTest.ktnew file mode 100644index 0000000..d84a1fe--- /dev/null+++ b/app/src/test/java/app/tellyscope/RemoteRepeatTest.kt@@ -0,0 +1,37 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import app.tellyscope.adb.RemoteKey+import app.tellyscope.ui.repeatWhileHeld+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Test++class RemoteRepeatTest {+ @Test fun heldKeyStopsWhenTheTvStopsTakingIt() = runTest {+ var presses = 0+ // Still held: only the TV's third "no" ends it.+ repeatWhileHeld(RemoteKey.UP, held = { true }) { presses++ < 2 }+ assertEquals(3, presses)+ }++ @Test fun noTvMeansOnePress() = runTest {+ var presses = 0+ repeatWhileHeld(RemoteKey.UP, held = { true }) { presses++; false }+ assertEquals(1, presses)+ }++ @Test fun releaseEndsTheRepeat() = runTest {+ var presses = 0+ var held = true+ repeatWhileHeld(RemoteKey.VOLUME_UP, held = { held }) { presses++; if (presses == 5) held = false; true }+ assertEquals(5, presses)+ }++ @Test fun okNeverRepeats() = runTest {+ var presses = 0+ repeatWhileHeld(RemoteKey.OK, held = { true }) { presses++; true }+ assertEquals(1, presses)+ }+}diff --git a/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.kt b/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.ktnew file mode 100644index 0000000..eb8aba9--- /dev/null+++ b/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.kt@@ -0,0 +1,151 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.lifecycle.viewModelScope+import app.tellyscope.adb.RemoteKey+import app.tellyscope.data.Action+import app.tellyscope.data.AppInfo+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.ScanHit+import app.tellyscope.data.ScanKind+import app.tellyscope.data.Snapshot+import app.tellyscope.data.Suggestions+import app.tellyscope.ui.Copy+import app.tellyscope.ui.TellyscopeViewModel+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.TestScope+import kotlinx.coroutines.test.advanceTimeBy+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.assertNull+import org.junit.Before+import org.junit.Test++/** Two online TVs; everything else comes from the empty fake. */+private class TwoTvs : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {+ var appsCalls = 0+ var appsDelayMs = 0L+ var actGate: CompletableDeferred<Unit>? = null+ val acted = mutableListOf<Pair<String, String>>()+ var pressFails = false++ override suspend fun known() = listOf("tv-a", "tv-b").map {+ Device(it, ScanHit(it, 5555, ScanKind.Classic, it, null), DeviceState.Online, null, null, null, 0L)+ }++ override fun live(deviceId: String): Flow<Snapshot> = emptyFlow()++ override suspend fun suggestions(deviceId: String) = Suggestions.Unavailable++ override suspend fun apps(deviceId: String): List<AppInfo> {+ appsCalls+++ delay(appsDelayMs)+ return listOf(AppInfo("app-on-$deviceId", "App", null, false, true, null, ""))+ }++ override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {+ acted += deviceId to packageName+ actGate?.await()+ return HistoryEntry(acted.size.toLong(), deviceId, 0L, action, packageName, "App", Action.Enable, null)+ }++ override suspend fun history(deviceId: String) = emptyList<HistoryEntry>()++ override suspend fun press(deviceId: String, key: RemoteKey): Boolean {+ if (pressFails) throw IllegalStateException("$deviceId is offline")+ return true+ }+}++@OptIn(ExperimentalCoroutinesApi::class)+class ResultsLandOnTheirTvTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private val source = TwoTvs()+ private lateinit var vm: TellyscopeViewModel++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ vm.viewModelScope.cancel()+ Dispatchers.resetMain()+ }++ @Test fun slowAppListIsReadOnce() = with(test) {+ // The state changes every second; a read inside update {} was retried on every change.+ source.appsDelayMs = 3_000+ vm = TellyscopeViewModel(source, clock = { 0L })+ advanceTimeBy(20_000)+ assertEquals(1, source.appsCalls)+ assertEquals(listOf("app-on-tv-a"), vm.state.value.device.apps?.map { it.packageName })+ }++ @Test fun resultForAnotherTvLeavesTheShownPageAlone() = with(test) {+ vm = TellyscopeViewModel(source, clock = { 0L })+ runCurrent()+ assertEquals("tv-a", vm.state.value.selectedId)++ source.actGate = CompletableDeferred()+ vm.propose("com.example", Action.Disable)+ vm.confirm()+ runCurrent()+ vm.select("tv-b")+ runCurrent()+ source.actGate!!.complete(Unit)+ runCurrent()++ val page = vm.state.value.device+ assertEquals("tv-b", vm.state.value.selectedId)+ assertEquals(listOf("app-on-tv-b"), page.apps?.map { it.packageName })+ assertNull(page.busy)+ assertEquals("tv-a", vm.done.value?.deviceId)+ }++ @Test fun snackbarUndoGoesToTheTvItCameFrom() = with(test) {+ vm = TellyscopeViewModel(source, clock = { 0L })+ runCurrent()+ vm.propose("com.example", Action.Disable)+ vm.confirm()+ runCurrent()+ val done = vm.done.value!!+ vm.select("tv-b")+ runCurrent()++ vm.undo(done.entry, done.deviceId)+ runCurrent()+ assertEquals("tv-a" to "com.example", source.acted.last())+ assertNull(vm.state.value.device.busy)+ }++ @Test fun lostTvStopsTheKey() = with(test) {+ vm = TellyscopeViewModel(source, clock = { 0L })+ runCurrent()+ source.pressFails = true+ var ok = true+ launchAndRun { ok = vm.press(RemoteKey.UP) }+ assertFalse(ok)+ assertEquals(Copy.REMOTE_LOST, vm.notice.value)+ }++ private fun TestScope.launchAndRun(block: suspend () -> Unit) {+ backgroundScope.launch { block() }+ runCurrent()+ }+}diff --git a/app/src/test/java/app/tellyscope/SnackbarsTest.kt b/app/src/test/java/app/tellyscope/SnackbarsTest.ktnew file mode 100644index 0000000..eb576f2--- /dev/null+++ b/app/src/test/java/app/tellyscope/SnackbarsTest.kt@@ -0,0 +1,62 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.runtime.remember+import androidx.compose.ui.test.junit4.v2.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import app.tellyscope.data.Action+import app.tellyscope.data.HistoryEntry+import app.tellyscope.ui.Copy+import app.tellyscope.ui.Done+import kotlinx.coroutines.flow.MutableStateFlow+import org.junit.Assert.assertEquals+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class SnackbarsTest {+ @get:Rule val compose = createComposeRule()++ private val done = MutableStateFlow<Done?>(null)+ private val notice = MutableStateFlow<String?>(null)+ private var undone: Done? = null++ private fun show() {+ // The snackbar times out on the test clock, so step it by hand.+ compose.mainClock.autoAdvance = false+ compose.setContent {+ val host = remember { SnackbarHostState() }+ Snackbars(host, done, notice, { done.value = null }, { notice.value = null }) { undone = it }+ SnackbarHost(host)+ }+ compose.mainClock.advanceTimeBy(100)+ }++ @Test fun noticeStaysOnScreen() {+ show()+ notice.value = "Turned 2 apps back on."+ compose.mainClock.advanceTimeBy(1_000)+ compose.onNodeWithText("Turned 2 apps back on.").assertExists()+ // Shown once: it was taken off the queue as it went up.+ assertEquals(null, notice.value)+ }++ @Test fun undoReachesTheTvTheActionRanOn() {+ show()+ val entry = HistoryEntry(7, "tv-a", 0L, Action.Disable, "com.example", "Example", Action.Enable, null)+ done.value = Done("tv-a", entry)+ compose.mainClock.advanceTimeBy(1_000)+ compose.onNodeWithText(Copy.done(Action.Disable, "Example")).assertExists()+ compose.onNodeWithText(Copy.undo(Action.Enable)).performClick()+ compose.mainClock.advanceTimeBy(1_000)+ assertEquals(Done("tv-a", entry), undone)+ }+}