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.
Install a recommended home screen from the TV's Play Store
jesse-agent-232e0d35b99d585
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fffb23c..c718fa9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ until this file has a section for its version.## Unreleased+- **New:** Install a recommended home screen from the TV's Play Store, then switch to it.- **Improved:** Setting a launcher as default asks separately before turning on its accessibility service, and the TV's page offers to turn it on later.- **Fixed:** A TV that removes this phone's access logs you out instead of re-asking. [#149](../../pull/149)- **New:** A connection left open after Remove offers Check again and Restart the TV. [#148](../../pull/148)diff --git a/NOTICE b/NOTICEindex 656495c..9cb238e 100644--- a/NOTICE+++ b/NOTICE@@ -38,6 +38,8 @@ those of "bluetooth", "headphones", "keyboard", "mouse", "sports_esports","usb", "speaker" and "settings_input_hdmi". The logged-out page and thelogged-out badge on a TV's chip use that of "logout"; the dialog that asksabout a launcher's accessibility service that of "accessibility_new".+The install-a-launcher flow uses those of "download", "error_outline",+"info" (outlined) and "code".--------------------------------------------------------------------------------Store badges in docs/badges/ (README only, not in the app)diff --git a/README.md b/README.mdindex 685dac3..8a99e55 100644--- a/README.md+++ b/README.md@@ -80,7 +80,7 @@ Tellyscope is a phone app that talks to your Android TV, Google TV or Fire TV ov- **The main jobs up front.** Big **Install app**, **Debloat** and **Send file** tiles sit right under the vitals. Debloat shows a count while the TV's list still has apps on, or while apps Tellyscope turned off are back on, often after a TV update. When there's nothing left, it opens Apps instead. Below the tiles, one line says how many apps on the TV's list are off. If any came back on, a red line says so. Below that are the TV's Android version, when it last updated, and **Check for updates**, which opens the TV's own update screen. The Apps tab has an **Install app** button, and Files has **Upload files**.- **Advanced.** Every number in one place: memory, storage, CPU, temperature, uptime and screen state, CPU and RAM by app, processes, network and data used, and the TV's address.- **Apps.** Every app on the TV with its real name and icon, under three buttons: **Running** (what's using memory now), **Installed** (only the apps you put on the TV) and **Built-in** (what came with it). The buttons stay pinned under the bar as you scroll. Stop, disable or turn back on any app that isn't protected; each button says what it will do and asks first. Apps you installed yourself also offer **Uninstall**, which asks in a dialog that names the app and says it can't be undone. On Running and Built-in, the protected apps sit last under **System**, which folds away with a tap and stays folded until you open it again. **Search apps** sits under the buttons and pins with them. Tap it and the field moves to the top, the TV and the buttons step aside, and every matching app shows in one list. ← or Back brings them back.-- **Another home screen.** With a second launcher such as Projectivy installed, its row in Apps offers **Set as default launcher**. Tellyscope makes it Home, checks that Home really opens it, and only then disables the old launcher, so the TV can't switch back by itself. The one exception: a stock launcher that outranks the rest, e.g. Android TV Home, is turned off first and turned back on if Home still doesn't open the new one. One Undo in History turns the old launcher back on and makes it Home again. Later, the new launcher's row offers **Switch home back to** the one it replaced, or the TV's own if there was no switch: it's turned back on if it's off and made Home, and the added launcher stays, free to uninstall. For a launcher that keeps Home with its own accessibility service, such as Projectivy (the ones marked in [`launchers.json`](app/src/main/assets/launchers.json)), Set as default then asks separately whether to turn that service on, for TVs whose Home button opens their own launcher whatever the default is: **Turn it on** or **Switch without it**. Without it, the TV's page says Home may still open the TV's own launcher, with **Got it** and **Turn on**, and the launcher's row keeps **Turn on**. Undo and Switch home back turn it off again, and any other accessibility services stay as they were. Settings and other apps that only answer Home as a fallback are never offered as launchers. On Google TV, the Apps row and the Live tab are part of the old launcher and go with it.+- **Another home screen.** On a TV with the Play Store, Apps shows a card that offers a better home screen, and Tweaks keeps **Choose one** after **Not now** puts the card away for that TV. Pick one of four recommended launchers (Projectivy, AT4K, Dispatch or the open-source FLauncher), and Tellyscope opens its Play Store page on the TV, waits for the install and then offers to make it Home. If the Store doesn't open, it says so and offers another launcher or a retry. With a second launcher such as Projectivy installed, its row in Apps offers **Set as default launcher**. Tellyscope makes it Home, checks that Home really opens it, and only then disables the old launcher, so the TV can't switch back by itself. The one exception: a stock launcher that outranks the rest, e.g. Android TV Home, is turned off first and turned back on if Home still doesn't open the new one. One Undo in History turns the old launcher back on and makes it Home again. Later, the new launcher's row offers **Switch home back to** the one it replaced, or the TV's own if there was no switch: it's turned back on if it's off and made Home, and the added launcher stays, free to uninstall. For a launcher that keeps Home with its own accessibility service, such as Projectivy (the ones marked in [`launchers.json`](app/src/main/assets/launchers.json)), Set as default then asks separately whether to turn that service on, for TVs whose Home button opens their own launcher whatever the default is: **Turn it on** or **Switch without it**. Without it, the TV's page says Home may still open the TV's own launcher, with **Got it** and **Turn on**, and the launcher's row keeps **Turn on**. Undo and Switch home back turn it off again, and any other accessibility services stay as they were. Settings and other apps that only answer Home as a fallback are never offered as launchers. On Google TV, the Apps row and the Live tab are part of the old launcher and go with it.- **Debloat.** It finds your TV among 300+ tested clean-up lists (adapted from [cleanyourtv](https://github.com/Gathin23/cleanyourtv)) and opens on every app it will turn off, with the model on top. With no list for the model, it shows apps from the maker's other lists, none ticked. With none for the maker either, you tick the TV's own apps by hand; the ones it needs aren't shown. **Not this TV?** searches every list. Your pick is remembered, and the TV's page then says how many of the list's apps are still on. Apps are pre-ticked only when the TV runs the Android version the list was tested on; untick anything you use, and you confirm before anything is disabled. If you'd rather not trust our lists, point the app at your own fork of them under **Advanced** in Settings (see [CONTRIBUTING](CONTRIBUTING.md#using-your-own-lists)).<img src="docs/screenshots/clean-home.jpg" alt="A TV home screen after debloating: the inputs and the user's own apps, with no ads or suggestions" width="100%">diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.ktindex b357ce6..249e7a4 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt@@ -162,6 +162,23 @@ class Actions(private val shell: AdbShell) {return serviceOn(service) == on}+ /** Opens the Play Store on the TV at [pkg]'s page. False when it didn't: no Store, or it refused the link. */+ suspend fun openStore(pkg: String): Boolean {+ require(PACKAGE.matches(pkg)) { "not a package name: $pkg" }+ val r = shell.shell("${Commands.OPEN_STORE} 'market://details?id=$pkg' 2>&1")+ return r.exitCode == 0 && "Error" !in r.output+ }++ /** `pm path` names an installed package's APK and prints nothing for one that isn't. */+ suspend fun installed(pkg: String): Boolean {+ require(PACKAGE.matches(pkg)) { "not a package name: $pkg" }+ return shell.shell("pm path $pkg 2>/dev/null").output.lineSequence().any { it.startsWith("package:") }+ }++ /** Whether the Play Store is the app on screen. */+ suspend fun storeOnScreen(): Boolean =+ shell.shell(Commands.RESUMED).output.lineSequence().any { "ResumedActivity" in it && " ${Commands.PLAY_STORE}/" in it }+/** The activity Home opens, or null when Android would ask (its chooser lives in `android`). */private suspend fun currentHome(): String? =activitiesIn(shell.shell(Commands.HOME_ACTIVITY).output).singleOrNull()?.takeUnless { it.startsWith("android/") }diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt b/adb/src/main/kotlin/app/tellyscope/adb/Commands.ktindex 6d0bcb0..dae5b00 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt@@ -53,6 +53,11 @@ internal object Commands {"cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER 2>/dev/null"const val A11Y_SERVICES = "cmd package query-services --brief -a android.accessibilityservice.AccessibilityService"const val A11Y_ON = "settings get secure enabled_accessibility_services"+ const val PLAY_STORE = "com.android.vending"+ /** Opens a `market://` link in the Play Store only; `-W` waits, so a refusal prints an Error. */+ const val OPEN_STORE = "am start -W -a android.intent.action.VIEW -p $PLAY_STORE -d"+ /** The app on screen: `mResumedActivity` up to Android 13, `topResumedActivity` from 14. */+ const val RESUMED = "dumpsys activity activities | grep -E 'mResumedActivity|topResumedActivity'"private fun List<String>.batch() = joinToString("; echo $SEP; ") { "$it 2>/dev/null" }diff --git a/adb/src/test/kotlin/app/tellyscope/adb/PlayStoreTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/PlayStoreTest.ktnew file mode 100644index 0000000..5c1d535--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/PlayStoreTest.kt@@ -0,0 +1,44 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class PlayStoreTest {+ private val pkg = "com.spocky.projengmenu"++ @Test fun opensTheStoreAtTheLaunchersPage() = runTest {+ val sh = FakeShell(mapOf("am start" to ok("Starting: Intent { act=android.intent.action.VIEW }\nStatus: ok\nLaunchState: COLD\n")))+ assertTrue(Actions(sh).openStore(pkg))+ assertEquals("am start -W -a android.intent.action.VIEW -p com.android.vending -d 'market://details?id=$pkg' 2>&1", sh.ran.single())+ }++ @Test fun noStoreIsAnError() = runTest {+ // Fire TV, or a Store that's off: am resolves nothing and says so, still exiting 0 on some builds.+ val sh = FakeShell(mapOf("am start" to ok("Starting: Intent { ... }\nError: Activity not started, unable to resolve Intent { ... }\n")))+ assertFalse(Actions(sh).openStore(pkg))+ }++ @Test fun onlyAPackageNameGoesIntoTheLink() = runTest {+ assertFailsWith<IllegalArgumentException> { Actions(FakeShell()).openStore("x' ; reboot ; '") }+ assertFailsWith<IllegalArgumentException> { Actions(FakeShell()).installed("x; reboot") }+ }++ @Test fun installedIsWhatPmPathNames() = runTest {+ assertTrue(Actions(FakeShell(mapOf("pm path" to ok("package:/data/app/~~x==/$pkg-1/base.apk\n")))).installed(pkg))+ assertFalse(Actions(FakeShell()).installed(pkg))+ }++ @Test fun theStoreOnScreenOnEitherAndroid() = runTest {+ val old = " mResumedActivity: ActivityRecord{1a2b u0 com.android.vending/com.google.android.finsky.activities.MainActivity t12}\n"+ val new = " topResumedActivity=ActivityRecord{3c4d u0 com.android.vending/com.google.android.finsky.tvmainactivity.TvMainActivity t40}\n"+ val elsewhere = " mResumedActivity: ActivityRecord{5e6f u0 com.google.android.tvlauncher/.MainActivity t3}\n"+ assertTrue(Actions(FakeShell(mapOf("dumpsys activity" to ok(old)))).storeOnScreen())+ assertTrue(Actions(FakeShell(mapOf("dumpsys activity" to ok(new)))).storeOnScreen())+ assertFalse(Actions(FakeShell(mapOf("dumpsys activity" to ok(elsewhere)))).storeOnScreen())+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex f444ece..942e995 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -57,6 +57,8 @@ import app.tellyscope.ui.DebloatScreenimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceTabsScreenimport app.tellyscope.ui.Done+import app.tellyscope.ui.LauncherActions+import app.tellyscope.ui.LauncherScreenimport app.tellyscope.ui.LoggedOutScreenimport app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.RemoteActions@@ -310,6 +312,18 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {back = { settings = false },snackbar = snackbar,)+ } else if (state.device.launcher != null) {+ BackHandler { vm.closeLauncherFlow() }+ LauncherScreen(+ state.selected!!, state.device.launcher!!, state.device.apps,+ LauncherActions(+ close = vm::closeLauncherFlow,+ install = vm::installLauncher,+ chooseAnother = vm::pickLauncher,+ switch = vm::switchToLauncher,+ later = vm::launcherLater,+ ),+ )} else if (debloat) {// Its own back handler closes the list search before leaving.DebloatScreen(@@ -340,6 +354,8 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {cancel = vm::cancel,homeServiceOn = vm::homeServiceOn,dismissServiceNote = vm::dismissServiceNote,+ installLauncher = vm::openLauncherFlow,+ hideLauncherCard = vm::hideLauncherCard,undo = vm::undo,reconnect = { state.selectedId?.let(vm::reconnect) },forget = vm::forget,diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 86e9723..b594204 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -80,11 +80,9 @@ class AdbDeviceSource(context: Context) : DeviceSource {@Volatile private var statsFor: Pair<String, StatsProfile>? = nullprivate val hits = ConcurrentHashMap<String, ScanHit>()private val store = DeviceStore(File(appContext.filesDir, "devices.tsv"))+ private val launchers by lazy { parseLaunchers(appContext.assets.open("launchers.json").bufferedReader().use { it.readText() }) }/** Launchers whose accessibility service a switch may turn on: only those `launchers.json` names. */- private val serviceLaunchers by lazy {- parseLaunchers(appContext.assets.open("launchers.json").bufferedReader().use { it.readText() })- .filter { it.accessibility }.map { it.pkg }.toSet()- }+ private val serviceLaunchers by lazy { launchers.filter { it.accessibility }.map { it.pkg }.toSet() }private val saved = ConcurrentHashMap<String, SavedDevice>()/** Remembered TVs that haven't answered since launch: shown offline, not "connecting". */private val restoring = ConcurrentHashMap.newKeySet<String>()@@ -96,6 +94,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val book = HistoryBook(File(appContext.filesDir, "history.tsv"))private val names = NameBook(File(appContext.filesDir, "names.tsv"))private val docks = DockBook(File(appContext.filesDir, "docks.tsv"))+ /** TVs whose Apps tab got Not now on the card about a better home screen. */+ private val launcherCards = FoldBook(File(appContext.filesDir, "launcher-card.properties"))private val mine = MineBook(File(appContext.filesDir, "mine.tsv"))/** Last label seen per package, so history entries read like the app list. */private val labels = ConcurrentHashMap<String, String>()@@ -398,6 +398,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {version = "",icon = name.icon,removable = p.name in userInstalled,+ home = p.name == homeOptions?.current,homeInstead = homeOptions?.takeIf { p.name in it.others }?.current,homeBack = back?.takeIf { p.name == homeOptions?.current }?.let { names[it.pkg]?.label ?: AppNames.fallback(it.pkg) },homeService = p.name in serviceLaunchers,@@ -578,6 +579,25 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun history(deviceId: String): List<HistoryEntry> = book.entries(key(deviceId))+ override suspend fun openStore(deviceId: String, packageName: String): Boolean {+ // Only a launcher the bundled list names: the Store link is the one thing this opens.+ if (launchers.none { it.pkg == packageName }) return false+ return Actions(session(deviceId)).openStore(packageName)+ }++ override suspend fun storeState(deviceId: String, packageName: String): StoreState {+ val actions = Actions(session(deviceId))+ return when {+ actions.installed(packageName) -> StoreState.Installed+ actions.storeOnScreen() -> StoreState.InStore+ else -> StoreState.Elsewhere+ }+ }++ override suspend fun launcherCardHidden(deviceId: String): Boolean = key(deviceId) in launcherCards.folded()++ override suspend fun hideLauncherCard(deviceId: String) = launcherCards.set(key(deviceId), true)+override suspend fun restoreAll(deviceId: String): List<HistoryEntry> {// Only what is still off now: the user may have turned some back on from the TV itself.val off = disabledPackages(deviceId)diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex dc5d2d3..96fc3f3 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -82,6 +82,17 @@ interface DeviceSource {/** Puts away the TV page's card about [packageName]'s service being off, until the next switch. */suspend fun dismissServiceNote(deviceId: String, packageName: String) {}+ /** Opens the Play Store on the TV at [packageName]'s page, a launcher from the bundled list; false when it didn't open. */+ suspend fun openStore(deviceId: String, packageName: String): Boolean = false++ /** Whether [packageName] is installed yet, and if not, whether the Store is still on screen. */+ suspend fun storeState(deviceId: String, packageName: String): StoreState = StoreState.Elsewhere++ /** Not now on the Apps tab's card about getting a better home screen, kept per TV. */+ suspend fun launcherCardHidden(deviceId: String): Boolean = false++ suspend fun hideLauncherCard(deviceId: String) {}+/** Everything Tellyscope changed on this TV, newest first. Survives app restarts. */suspend fun history(deviceId: String): List<HistoryEntry>diff --git a/app/src/main/java/app/tellyscope/data/FoldBook.kt b/app/src/main/java/app/tellyscope/data/FoldBook.ktindex 2e30c30..660fd71 100644--- a/app/src/main/java/app/tellyscope/data/FoldBook.kt+++ b/app/src/main/java/app/tellyscope/data/FoldBook.kt@@ -7,7 +7,8 @@ import java.util.Properties/*** Which Apps tabs have their System section folded, kept in [file] so a fold the user chose- * stays across restarts until they open it again. Unfolded until told otherwise.+ * stays across restarts until they open it again. Unfolded until told otherwise. The same book+ * keeps, in its own file, which TVs put away the card about a better home screen.*/class FoldBook(private val file: File) {@Synchronizeddiff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.ktindex ffe874f..b9f02ec 100644--- a/app/src/main/java/app/tellyscope/data/Model.kt+++ b/app/src/main/java/app/tellyscope/data/Model.kt@@ -124,6 +124,8 @@ data class AppInfo(val iconAccent: Long? = null,/** Installed by the user (`pm list packages -3`), so Uninstall is offered. Never for apps that came with the TV. */val removable: Boolean = false,+ /** The launcher Home opens now. */+ val home: Boolean = false,/** Another launcher that can replace the current home screen, [homeInstead]: "Set as default launcher" is offered. */val homeInstead: String? = null,/** On the home screen the user added: the name of the launcher "Switch home back" returns to. */@@ -142,6 +144,9 @@ data class AppInfo(val tvHome: Boolean = true,)+/** Where an install from the Play Store stands, read every few seconds while the TV shows the Store. */+enum class StoreState { Installed, InStore, Elsewhere }+/** An app on the Remote's dock. [label] is kept so it can be named after the app is gone. */data class Docked(val packageName: String, val label: String)diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex a33a1f4..8880e9e 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -123,6 +123,55 @@ object Copy {const val TV_OWN_LAUNCHER = "the TV's own launcher"+ /** Install a home screen: the Apps tab's card, the picker, the wait for the Store, and its dead ends. */+ const val BETTER_HOME = "Get a better home screen"++ fun betterHomeText(current: String?) =+ "Swap ${current ?: "the TV's home screen"} for a launcher without ads. Free on the Play Store; switch back any time."++ const val CHOOSE_ONE = "Choose one"+ const val CHOOSE_HOME = "Choose a home screen"+ const val CHOOSE_HOME_TEXT = "Each one replaces the TV's home screen. Tellyscope opens it in the Play Store on the TV; you install it with the remote."+ const val RECOMMENDED = "Recommended"+ const val USES_SERVICE = "Uses an accessibility service"+ const val NO_SERVICE = "Open source · no accessibility service"+ const val OPEN_IN_STORE = "Open in Play Store"+ const val INSTALL_HOME = "Install a home screen"+ const val INSTALL_IT = "Install it on your TV"++ fun installItText(name: String) =+ "The Play Store is open on the TV, on $name's page. Use the remote to select Install. Tellyscope moves on by itself once it's installed."++ fun storeOn(tv: String) = "Play Store on $tv"++ const val WAITING_INSTALL = "Waiting for install…"+ const val DOWNLOADS_TAKE = "Downloads can take a minute. Tellyscope can't see the download, only when it's done."+ const val OPEN_STORE_AGAIN = "Open Play Store again"+ const val MAKE_IT_HOME = "Make it the home screen?"++ fun isInstalled(name: String) = "$name is installed."++ fun launcherLater(name: String) = "$name is installed. To use it later, open its row and choose $MAKE_HOME."++ fun launcherInstalled(name: String) = "$name is installed. Press Home on the remote to pick it."++ const val NO_STORE = "The Play Store didn't open"++ fun noStoreText(tv: String, name: String) =+ "$tv didn't open the Play Store for Tellyscope. On the TV, open the Play Store yourself and search for $name. " ++ "Tellyscope keeps watching and moves on once it's installed."++ const val CHOOSE_ANOTHER = "Choose another"++ fun notInstalled(name: String) = "$name isn't installed"++ const val NOT_INSTALLED_TEXT =+ "The Play Store closed on the TV before it was installed. If the Store said it isn't available for this TV, choose another launcher."++ /** The Tweaks row that reopens it after Not now on the card. */+ const val ANOTHER_HOME = "Another home screen"+ const val ANOTHER_HOME_TEXT = "Install a launcher from the Play Store, like Projectivy or FLauncher. Switch back any time."+fun serviceOffText(app: String) = "$app's accessibility service is off, so the TV can take Home back."private val GOOGLE_HOMES = setOf("com.google.android.tvlauncher", "com.google.android.apps.tv.launcherx")diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 7d4d4af..16f41a6 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -80,6 +80,10 @@ data class DeviceActions(val homeServiceOn: (String) -> Unit = {},/** Got it on the TV page's card about that service being off. */val dismissServiceNote: (String) -> Unit = {},+ /** Opens Install a home screen, from the Apps tab's card or Tweaks. */+ val installLauncher: () -> Unit = {},+ /** Not now on the Apps tab's card about a better home screen. */+ val hideLauncherCard: () -> Unit = {},val undo: (HistoryEntry) -> Unit = {},val reconnect: () -> Unit = {},val forget: (String) -> Unit = {},diff --git a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt b/app/src/main/java/app/tellyscope/ui/DeviceTabs.ktindex 8fbb1e6..a86b9b5 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt@@ -321,6 +321,9 @@ fun DeviceTabsScreen(below = { SearchPill(enabled = !offline) { searching = true } },) { appsTab = AppsTab.entries[it] }}+ if (!offline && offerLauncher(ui.apps, ui.launcherCardHidden)) item(key = "launcherCard") {+ LauncherCard(ui.apps.firstOrNull { it.home }?.label, onNotNow = actions.hideLauncherCard, onChoose = actions.installLauncher)+ }val split = splitApps(ui.apps, procs, appsTab)if (split.apps.isEmpty() && split.system.isEmpty()) item {// Away, the TV can't say what's running, rather than nothing is.diff --git a/app/src/main/java/app/tellyscope/ui/HomeServiceUi.kt b/app/src/main/java/app/tellyscope/ui/HomeServiceUi.ktindex 3548e4d..dee060b 100644--- a/app/src/main/java/app/tellyscope/ui/HomeServiceUi.kt+++ b/app/src/main/java/app/tellyscope/ui/HomeServiceUi.kt@@ -30,6 +30,7 @@ import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.dpimport app.tellyscope.data.AppInfo@@ -57,7 +58,6 @@ fun ServiceDialog(app: String, other: String, onTurnOn: () -> Unit, dismissLabel*/@Composablefun ServiceOffCard(app: AppInfo, onTurnOn: () -> Unit, onDismiss: () -> Unit) {- val c = MaterialTheme.colorSchemevar asking by rememberSaveable { mutableStateOf(false) }if (asking) {ServiceDialog(@@ -66,30 +66,45 @@ fun ServiceOffCard(app: AppInfo, onTurnOn: () -> Unit, onDismiss: () -> Unit) {dismissLabel = Copy.NOT_NOW, onOther = { asking = false }, onDismiss = { asking = false },)}+ HomeNoteCard(+ Icons.Default.Home, Copy.serviceOffTitle(app.homeBack), Copy.serviceOffText(app.label),+ Copy.GOT_IT, onDismiss, Copy.TURN_ON, onAction = { asking = true },+ modifier = Modifier.testTag("serviceOff"),+ )+}++/** A note about the home screen in the TV's own pages: neutral card, icon tile, a text button and a tonal one. */+@Composable+fun HomeNoteCard(+ icon: ImageVector,+ title: String,+ text: String,+ dismissLabel: String,+ onDismiss: () -> Unit,+ actionLabel: String,+ onAction: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val c = MaterialTheme.colorSchemeCard(colors = CardDefaults.cardColors(containerColor = c.surfaceContainer),shape = MaterialTheme.shapes.large,- modifier = Modifier.fillMaxWidth().testTag("serviceOff"),+ modifier = modifier.fillMaxWidth(),) {Column(Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 12.dp)) {Row {Box(Modifier.size(40.dp).background(c.tertiaryContainer, CircleShape), contentAlignment = Alignment.Center) {- Icon(Icons.Default.Home, contentDescription = null, tint = c.onTertiaryContainer, modifier = Modifier.size(24.dp))+ Icon(icon, contentDescription = null, tint = c.onTertiaryContainer, modifier = Modifier.size(24.dp))}Spacer(Modifier.width(16.dp))Column(Modifier.weight(1f)) {- Text(Copy.serviceOffTitle(app.homeBack), style = MaterialTheme.typography.titleMedium)- Text(- Copy.serviceOffText(app.label),- style = MaterialTheme.typography.bodyMedium,- color = c.onSurfaceVariant,- modifier = Modifier.padding(top = 4.dp),- )+ Text(title, style = MaterialTheme.typography.titleMedium)+ Text(text, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))}}Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {- TextButton(onClick = onDismiss) { Text(Copy.GOT_IT) }- FilledTonalButton(onClick = { asking = true }) { Text(Copy.TURN_ON) }+ TextButton(onClick = onDismiss) { Text(dismissLabel) }+ FilledTonalButton(onClick = onAction) { Text(actionLabel) }}}}diff --git a/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.ktnew file mode 100644index 0000000..e6a337e--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt@@ -0,0 +1,301 @@+// SPDX-License-Identifier: GPL-3.0-only+// Download, ErrorOutline, InfoOutline and Code are the Material Icons "download", "error_outline", "info" (outlined)+// and "code" (Apache-2.0), see NOTICE.++package app.tellyscope.ui++import androidx.compose.foundation.background+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.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.rememberScrollState+import androidx.compose.foundation.selection.selectable+import androidx.compose.foundation.selection.selectableGroup+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Check+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.outlined.Home+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LoadingIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.RadioButton+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.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.PathFillType+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.vector.PathParser+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import app.tellyscope.data.Action+import app.tellyscope.data.AppInfo+import app.tellyscope.data.Device++/** The Play Store's package: a TV without it (Fire TV) gets no card and no Tweaks row. */+const val PLAY_STORE = "com.android.vending"++/**+ * Install a home screen is offered on the Apps tab while the TV has the Play Store and no second+ * launcher, until Not now; Tweaks offers it whenever the Store is there.+ */+internal fun hasPlayStore(apps: List<AppInfo>) = apps.any { it.packageName == PLAY_STORE && it.enabled }++internal fun offerLauncher(apps: List<AppInfo>, hidden: Boolean) =+ !hidden && hasPlayStore(apps) && apps.none { it.homeInstead != null || it.homeBack != null }++data class LauncherActions(+ val close: () -> Unit = {},+ /** Opens the Store on the TV at that launcher's page, and watches for the install. */+ val install: (String) -> Unit = {},+ /** Back to the picker with that launcher still chosen. */+ val chooseAnother: (String) -> Unit = {},+ /** Yes on the installed launcher, with its accessibility service or without. */+ val switch: (service: Boolean) -> Unit = {},+ val later: () -> Unit = {},+)++/** The Apps tab's card: a launcher without ads, from the Play Store. Not now puts it away on this TV. */+@Composable+fun LauncherCard(current: String?, onNotNow: () -> Unit, onChoose: () -> Unit) {+ HomeNoteCard(Icons.Outlined.Home, Copy.BETTER_HOME, Copy.betterHomeText(current), Copy.NOT_NOW, onNotNow, Copy.CHOOSE_ONE, onChoose)+}++/**+ * Install a home screen, as one full screen: the picker, then the wait while the TV shows the+ * Play Store, then the switch, which ends in the same yes for the accessibility service as Set as+ * default. A TV that didn't open the Store, and a Store closed without installing, each say so.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LauncherScreen(device: Device, flow: LauncherFlow, apps: List<AppInfo>, actions: LauncherActions) {+ var chosen by rememberSaveable(flow.step, flow.pkg) { mutableStateOf(flow.pkg) }+ var askService by rememberSaveable(flow.step) { mutableStateOf(false) }+ val label = launcherName(flow.pkg)+ val app = apps.firstOrNull { it.packageName == flow.pkg }+ val current = app?.let { homeLabel(apps, it) }+ if (askService && app != null && current != null) {+ ServiceDialog(+ app.label, current,+ onTurnOn = { actions.switch(true) },+ dismissLabel = Copy.SWITCH_WITHOUT, onOther = { actions.switch(false) }, onDismiss = { askService = false },+ )+ }+ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(if (flow.step == LauncherFlow.Step.Pick) Copy.CHOOSE_HOME else Copy.INSTALL_HOME) },+ navigationIcon = { IconButton(onClick = actions.close) { Icon(Icons.Default.Close, contentDescription = "Close") } },+ )+ },+ bottomBar = {+ Row(+ Modifier.fillMaxWidth().navigationBarsPadding().padding(16.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ when (flow.step) {+ LauncherFlow.Step.Pick -> Button(onClick = { actions.install(chosen) }, contentPadding = ButtonDefaults.ButtonWithIconContentPadding) {+ Icon(OpenInNew, contentDescription = null, Modifier.size(18.dp))+ Spacer(Modifier.width(8.dp))+ Text(Copy.OPEN_IN_STORE)+ }+ LauncherFlow.Step.Waiting -> TextButton(onClick = { actions.install(flow.pkg) }) { Text(Copy.OPEN_STORE_AGAIN) }+ LauncherFlow.Step.Installed -> {+ TextButton(onClick = actions.later) { Text(Copy.NOT_NOW) }+ Button(onClick = { if (app?.homeService == true) askService = true else actions.switch(false) }, enabled = current != null) {+ Text(Copy.confirm(Action.Home))+ }+ }+ LauncherFlow.Step.NoStore -> {+ TextButton(onClick = { actions.chooseAnother(flow.pkg) }) { Text(Copy.CHOOSE_ANOTHER) }+ Button(onClick = { actions.install(flow.pkg) }) { Text(Copy.TRY_AGAIN) }+ }+ LauncherFlow.Step.Left -> {+ TextButton(onClick = { actions.chooseAnother(flow.pkg) }) { Text(Copy.CHOOSE_ANOTHER) }+ Button(onClick = { actions.install(flow.pkg) }) { Text(Copy.OPEN_STORE_AGAIN) }+ }+ }+ }+ },+ ) { pad ->+ Column(+ Modifier.fillMaxSize().padding(pad).verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(20.dp),+ ) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Icon(DeviceIcons.Tv, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(connectTitle(device), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ val c = MaterialTheme.colorScheme+ when (flow.step) {+ LauncherFlow.Step.Pick -> Picker(chosen) { chosen = it }+ LauncherFlow.Step.Waiting -> {+ Hero(LauncherIcons.Download, c.secondaryContainer, c.onSecondaryContainer)+ Headed(Copy.INSTALL_IT, bold(Copy.installItText(label), label, "Install"))+ Surface(shape = MaterialTheme.shapes.large, color = c.surfaceContainer, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ LetterTile(flow.pkg)+ Spacer(Modifier.width(16.dp))+ Column {+ Text(label, style = MaterialTheme.typography.bodyLarge)+ Text(Copy.storeOn(name(device)), style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant)+ }+ }+ WaitingLine()+ }+ }+ Text(Copy.DOWNLOADS_TAKE, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ }+ LauncherFlow.Step.Installed -> {+ Hero(Icons.Default.Check, c.secondaryContainer, c.onSecondaryContainer)+ val explain = if (app != null && current != null && app.homeInstead != null) {+ " " + Copy.explainHome(app.label, app.packageName, current, app.homeInstead, app.homeService)+ } else {+ ""+ }+ Headed(Copy.MAKE_IT_HOME, AnnotatedString(Copy.isInstalled(label) + explain))+ }+ LauncherFlow.Step.NoStore -> {+ Hero(LauncherIcons.ErrorOutline, c.errorContainer, c.onErrorContainer)+ Headed(Copy.NO_STORE, bold(Copy.noStoreText(name(device), label), label))+ Surface(shape = MaterialTheme.shapes.large, color = c.surfaceContainer, modifier = Modifier.fillMaxWidth()) {+ Box(Modifier.padding(16.dp)) { WaitingLine() }+ }+ }+ LauncherFlow.Step.Left -> {+ Hero(LauncherIcons.InfoOutline, c.surfaceContainerHighest, c.onSurfaceVariant)+ Headed(Copy.notInstalled(label), AnnotatedString(Copy.NOT_INSTALLED_TEXT))+ }+ }+ }+ }+}++/** The four launchers as one segmented list, one chosen: rounded ends, small gaps, the chosen one filled. */+@Composable+private fun Picker(chosen: String, onChoose: (String) -> Unit) {+ val c = MaterialTheme.colorScheme+ Text(Copy.CHOOSE_HOME_TEXT, style = MaterialTheme.typography.bodyLarge)+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(Copy.RECOMMENDED, style = MaterialTheme.typography.labelLarge, color = c.primary, modifier = Modifier.padding(bottom = 8.dp))+ Column(Modifier.selectableGroup(), verticalArrangement = Arrangement.spacedBy(2.dp)) {+ RECOMMENDED.forEachIndexed { i, l ->+ val big = 16.dp+ val small = 4.dp+ val shape = RoundedCornerShape(+ topStart = if (i == 0) big else small, topEnd = if (i == 0) big else small,+ bottomStart = if (i == RECOMMENDED.lastIndex) big else small, bottomEnd = if (i == RECOMMENDED.lastIndex) big else small,+ )+ val on = l.pkg == chosen+ Surface(+ shape = shape,+ color = if (on) c.secondaryContainer else c.surfaceContainer,+ modifier = Modifier.fillMaxWidth().selectable(on, role = Role.RadioButton) { onChoose(l.pkg) },+ ) {+ Row(Modifier.padding(start = 16.dp, top = 16.dp, bottom = 16.dp, end = 8.dp)) {+ LetterTile(l.pkg)+ Spacer(Modifier.width(16.dp))+ Column(Modifier.weight(1f)) {+ Text(l.name, style = MaterialTheme.typography.bodyLarge)+ Text(l.about, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant)+ Row(Modifier.padding(top = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(if (l.accessibility) DeviceIcons.Accessibility else LauncherIcons.Code, null, Modifier.size(14.dp), tint = c.onSurfaceVariant)+ Spacer(Modifier.width(6.dp))+ Text(if (l.accessibility) Copy.USES_SERVICE else Copy.NO_SERVICE, style = MaterialTheme.typography.labelMedium, color = c.onSurfaceVariant)+ }+ }+ RadioButton(selected = on, onClick = null)+ }+ }+ }+ }+ }+}++/** No launcher icon exists on the phone before it's installed, so each has a letter in its own colour. */+@Composable+private fun LetterTile(pkg: String) {+ val l = RECOMMENDED.firstOrNull { it.pkg == pkg }+ Box(+ Modifier.size(40.dp).background(l?.let { Color(it.tile) } ?: MaterialTheme.colorScheme.secondaryContainer, MaterialTheme.shapes.medium),+ contentAlignment = Alignment.Center,+ ) {+ Text(launcherName(pkg).take(1), color = Color.White, style = MaterialTheme.typography.titleMedium)+ }+}++@Composable+private fun Hero(icon: ImageVector, bg: Color, fg: Color) {+ Box(Modifier.size(64.dp).background(bg, CircleShape), contentAlignment = Alignment.Center) {+ Icon(icon, null, Modifier.size(32.dp), tint = fg)+ }+}++@Composable+private fun Headed(title: String, text: AnnotatedString) {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(title, style = MaterialTheme.typography.headlineMedium)+ Text(text, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+}++/** No progress to show: the TV says nothing until the launcher is in. */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+private fun WaitingLine() {+ Row(verticalAlignment = Alignment.CenterVertically) {+ LoadingIndicator(Modifier.size(24.dp))+ Spacer(Modifier.width(12.dp))+ Text(Copy.WAITING_INSTALL, style = MaterialTheme.typography.bodyMedium)+ }+}++/** [text] with each of [words] in medium weight, where it first appears. */+private fun bold(text: String, vararg words: String) = buildAnnotatedString {+ append(text)+ words.forEach { w -> text.indexOf(w).takeIf { it >= 0 }?.let { addStyle(SpanStyle(fontWeight = FontWeight.Medium), it, it + w.length) } }+}++private object LauncherIcons {+ // Absolute commands only: Compose's path parser misplaces a relative move after a close.+ val Download = icon("Download", "M5 20H19V18H5ZM19 9H15V3H9V9H5L12 16Z")+ val ErrorOutline = icon("ErrorOutline", "M12 2A10 10 0 1 0 12 22A10 10 0 1 0 12 2ZM12 4A8 8 0 1 1 12 20A8 8 0 1 1 12 4ZM11 7H13V13H11ZM11 15H13V17H11Z")+ val InfoOutline = icon("InfoOutline", "M12 2A10 10 0 1 0 12 22A10 10 0 1 0 12 2ZM12 4A8 8 0 1 1 12 20A8 8 0 1 1 12 4ZM11 11H13V17H11ZM11 7H13V9H11Z")+ val Code = icon("Code", "M9.4 16.6L4.8 12L9.4 7.4L8 6L2 12L8 18ZM14.6 16.6L19.2 12L14.6 7.4L16 6L22 12L16 18Z")++ private fun icon(name: String, path: String) = ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f)+ .addPath(PathParser().parsePathString(path).toNodes(), pathFillType = PathFillType.EvenOdd, fill = SolidColor(Color.Black))+ .build()+}diff --git a/app/src/main/java/app/tellyscope/ui/Recommended.kt b/app/src/main/java/app/tellyscope/ui/Recommended.ktnew file mode 100644index 0000000..4e10551--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/Recommended.kt@@ -0,0 +1,21 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.ui++import app.tellyscope.data.AppNames++/**+ * A launcher Install a home screen offers, from the bundled `launchers.json`: its name, a line on+ * what it's like, and the letter tile's colour (there's no icon to show before it's installed).+ */+data class Recommended(val pkg: String, val name: String, val about: String, val accessibility: Boolean, val tile: Long)++/** In the picker's order. [Recommended.accessibility] matches `launchers.json`; a test holds them together. */+val RECOMMENDED = listOf(+ Recommended("com.spocky.projengmenu", "Projectivy Launcher", "The most popular. Rows, wallpapers and icons you can change.", true, 0xFF3D5AFE),+ Recommended("com.overdevs.at4k", "AT4K Launcher", "A clean home screen in the Google TV style, without the ads.", true, 0xFF6A1B9A),+ Recommended("com.spauldhaliwal.dispatch", "Dispatch", "Minimal: a fast list of your apps and inputs.", true, 0xFFC62828),+ Recommended("me.efesser.flauncher", "FLauncher", "Simple: your apps in rows, nothing else.", false, 0xFF2E7D32),+)++fun launcherName(pkg: String) = RECOMMENDED.firstOrNull { it.pkg == pkg }?.name ?: AppNames.fallback(pkg)diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 504d708..c266808 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -41,6 +41,7 @@ import app.tellyscope.data.ScanHitimport app.tellyscope.data.ScanKindimport app.tellyscope.data.ScanProgressimport app.tellyscope.data.Snapshot+import app.tellyscope.data.StoreStateimport app.tellyscope.data.Suggestionsimport app.tellyscope.data.TvAccessimport app.tellyscope.data.TvSettings@@ -113,8 +114,21 @@ data class DeviceUi(val peripherals: List<Peripheral>? = null,/** "Remove all other access", while it runs; null otherwise. */val removal: Removal? = null,+ /** Install a home screen, while it's open; null otherwise. */+ val launcher: LauncherFlow? = null,+ /** Not now on the Apps tab's home-screen card, for this TV. True until read, so the card never flashes. */+ val launcherCardHidden: Boolean = true,)+/**+ * Install a home screen: pick a launcher ([Step.Pick]), install it from the Play Store the TV+ * opens at its page ([Step.Waiting], or [Step.NoStore] when the Store didn't open and the user+ * searches by hand), then switch to it ([Step.Installed]). [Step.Left]: the Store closed first.+ */+data class LauncherFlow(val step: Step = Step.Pick, val pkg: String = RECOMMENDED.first().pkg) {+ enum class Step { Pick, Waiting, NoStore, Left, Installed }+}+/*** "Remove all other access", one step at a time. The TV's keys are cleared ([Step.Revoking], or* by hand in Developer options when the call isn't available: [Step.Manual]); Tellyscope then@@ -254,6 +268,9 @@ const val SCREENSHOT = "screenshot"/** [DeviceUi.busy] value while the TV's connection prompt is being answered. */const val ANSWERING = "request"+/** How often Install a home screen asks the TV whether the launcher is in yet. */+const val STORE_POLL_MS = 3_000L+/** Where a removal ends, from the re-read after it: never Done on a guess. */fun outcome(access: TvAccess?): Removal = when {access?.connected == null || access.allowed == null -> Removal(Removal.Step.Unconfirmed)@@ -308,6 +325,8 @@ class TellyscopeViewModel(private var accessJob: Job? = null/** Runs the removal across the reconnect it causes, so [select] doesn't stop it. */private var removalJob: Job? = null+ /** Watches the TV for a launcher's install from the Play Store. */+ private var launcherJob: Job? = nullprivate var updateJob: Job? = null/** The fingerprint the user waved away on the phone; its prompt stays hidden while the TV shows it. */private var dismissedRequest: String? = null@@ -451,6 +470,7 @@ class TellyscopeViewModel(fun select(id: String?) {liveJob?.cancel()+ launcherJob?.cancel()mediumJob?.cancel()listsJob?.cancel()requestJob?.cancel()@@ -467,7 +487,8 @@ class TellyscopeViewModel(viewModelScope.launch {val history = source.history(device.id)val dock = source.dock(device.id)- _state.update { if (it.selectedId == device.id) it.copy(device = it.device.copy(history = history, dock = dock)) else it }+ val hidden = source.launcherCardHidden(device.id)+ _state.update { if (it.selectedId == device.id) it.copy(device = it.device.copy(history = history, dock = dock, launcherCardHidden = hidden)) else it }}if (device.state != DeviceState.Online) returnliveJob = viewModelScope.launch {@@ -625,6 +646,105 @@ class TellyscopeViewModel(}}+ /** Opens Install a home screen on its picker. */+ fun openLauncherFlow() {+ val id = _state.value.selectedId ?: return+ updateDevice(id) { it.copy(launcher = LauncherFlow()) }+ }++ /** Not now on the Apps tab's card: it stays away on this TV, and Tweaks keeps the way in. */+ fun hideLauncherCard() {+ val id = _state.value.selectedId ?: return+ updateDevice(id) { it.copy(launcherCardHidden = true) }+ viewModelScope.launch { runCatching { source.hideLauncherCard(id) } }+ }++ /** Back to the picker, [pkg] still chosen; Choose another from a dead end. */+ fun pickLauncher(pkg: String) {+ val id = _state.value.selectedId ?: return+ launcherJob?.cancel()+ updateDevice(id) { it.copy(launcher = LauncherFlow(LauncherFlow.Step.Pick, pkg)) }+ }++ fun closeLauncherFlow() {+ val id = _state.value.selectedId ?: return+ launcherJob?.cancel()+ updateDevice(id) { it.copy(launcher = null) }+ }++ /**+ * Opens the Play Store on the TV at [pkg]'s page, then checks every few seconds whether it's+ * installed, or the Store has closed without it. Where the Store didn't open, it keeps+ * checking while the user searches by hand.+ */+ fun installLauncher(pkg: String) {+ val id = _state.value.selectedId ?: return+ launcherJob?.cancel()+ val step = { s: LauncherFlow.Step -> updateDevice(id) { it.copy(launcher = it.launcher?.let { _ -> LauncherFlow(s, pkg) }) } }+ step(LauncherFlow.Step.Waiting)+ launcherJob = viewModelScope.launch {+ val opened = try {+ source.openStore(id, pkg)+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ false+ }+ if (!opened) step(LauncherFlow.Step.NoStore)+ var seen = opened+ while (true) {+ delay(STORE_POLL_MS)+ val now = try {+ source.storeState(id, pkg)+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ continue // a dropped read: the next one tells+ }+ when (now) {+ StoreState.Installed -> {+ val apps = try {+ source.apps(id)+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ null+ }+ apps?.let { a -> updateDevice(id) { it.copy(apps = a) } }+ // No way to offer it as Home (the TV asks each time): say where to find it instead.+ if (apps?.firstOrNull { it.packageName == pkg }?.homeInstead == null) {+ updateDevice(id) { it.copy(launcher = null) }+ _notice.value = Copy.launcherInstalled(launcherName(pkg))+ } else {+ step(LauncherFlow.Step.Installed)+ }+ return@launch+ }+ StoreState.InStore -> seen = true+ StoreState.Elsewhere -> if (seen) {+ step(LauncherFlow.Step.Left)+ return@launch+ }+ }+ }+ }+ }++ /** Yes on the installed launcher, with its accessibility service or without; the flow closes and the switch runs. */+ fun switchToLauncher(service: Boolean) {+ val id = _state.value.selectedId ?: return+ val pkg = _state.value.device.launcher?.pkg ?: return+ updateDevice(id) { it.copy(launcher = null) }+ run(pkg, Action.Home, id = id) { source.makeHome(it, pkg, service) }+ }++ /** Not now on the installed launcher: where to switch later. */+ fun launcherLater() {+ val pkg = _state.value.device.launcher?.pkg ?: return+ closeLauncherFlow()+ _notice.value = Copy.launcherLater(launcherName(pkg))+ }+/** Ad-blocking Private DNS through [host], or back to Automatic with null. */fun setDns(host: String?) = change(Tweak.PRIVATE_DNS, TvSettings.dns(host))diff --git a/app/src/main/java/app/tellyscope/ui/TweaksBlock.kt b/app/src/main/java/app/tellyscope/ui/TweaksBlock.ktindex df11b05..09b81d4 100644--- a/app/src/main/java/app/tellyscope/ui/TweaksBlock.kt+++ b/app/src/main/java/app/tellyscope/ui/TweaksBlock.kt@@ -56,6 +56,7 @@ fun TweaksBlock(ui: DeviceUi, actions: DeviceActions) {}ButtonRow(Copy.CACHES_TITLE, Copy.CACHES_TEXT, Copy.CACHES_BUTTON, enabled = ui.busy == null, actions.clearCaches)ButtonRow(Copy.SCREENSHOT_TITLE, Copy.SCREENSHOT_TEXT, Copy.SCREENSHOT_BUTTON, enabled = ui.busy == null, actions.screenshot)+ if (hasPlayStore(ui.apps)) ButtonRow(Copy.ANOTHER_HOME, Copy.ANOTHER_HOME_TEXT, Copy.CHOOSE_ONE, enabled = ui.busy == null, actions.installLauncher)if (askDns) DnsDialog(onDismiss = { askDns = false }) { host -> askDns = false; actions.setDns(host) }}diff --git a/app/src/test/java/app/tellyscope/LauncherFlowTest.kt b/app/src/test/java/app/tellyscope/LauncherFlowTest.ktnew file mode 100644index 0000000..652f964--- /dev/null+++ b/app/src/test/java/app/tellyscope/LauncherFlowTest.kt@@ -0,0 +1,251 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.compose.ui.test.junit4.v2.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.lifecycle.viewModelScope+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.StoreState+import app.tellyscope.data.Suggestions+import app.tellyscope.ui.Copy+import app.tellyscope.ui.LauncherActions+import app.tellyscope.ui.LauncherCard+import app.tellyscope.ui.LauncherFlow+import app.tellyscope.ui.LauncherScreen+import app.tellyscope.ui.PLAY_STORE+import app.tellyscope.ui.STORE_POLL_MS+import app.tellyscope.ui.TellyscopeViewModel+import app.tellyscope.ui.offerLauncher+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.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.Assert.assertTrue+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++private const val TV_HOME = "com.google.android.tvlauncher"+private const val PROJECTIVY = "com.spocky.projengmenu"+private const val FLAUNCHER = "me.efesser.flauncher"++private val store = AppInfo(PLAY_STORE, "Google Play Store", null, true, true, null, "1.0")+private val stock = AppInfo(TV_HOME, "Google TV Home", null, true, true, "this is your home screen", "1.0", home = true)++/** One online TV whose Play Store answers from a script. */+private class StoreTv : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {+ var opens = true+ val opened = mutableListOf<String>()+ var states = ArrayDeque<StoreState>()+ var installed = false+ var hidden = false+ val switched = mutableListOf<Pair<String, Boolean>>()++ 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 suggestions(deviceId: String) = Suggestions.Unavailable+ override suspend fun history(deviceId: String) = emptyList<HistoryEntry>()++ override suspend fun apps(deviceId: String) = listOf(store, stock) ++ if (installed) listOf(AppInfo(PROJECTIVY, "Projectivy Launcher", null, false, true, null, "1.0", homeInstead = TV_HOME, homeService = true)) else emptyList()++ override suspend fun openStore(deviceId: String, packageName: String): Boolean {+ opened += packageName+ return opens+ }++ override suspend fun storeState(deviceId: String, packageName: String): StoreState {+ val s = states.removeFirstOrNull() ?: StoreState.InStore+ if (s == StoreState.Installed) installed = true+ return s+ }++ override suspend fun launcherCardHidden(deviceId: String) = hidden++ override suspend fun hideLauncherCard(deviceId: String) {+ hidden = true+ }++ override suspend fun makeHome(deviceId: String, packageName: String, service: Boolean): HistoryEntry {+ switched += packageName to service+ return HistoryEntry(1, deviceId, 0L, app.tellyscope.data.Action.Home, packageName, "Projectivy Launcher", app.tellyscope.data.Action.Home, null)+ }+}++/** Install a home screen: the Store wait, its dead ends, and the card's Not now. */+@OptIn(ExperimentalCoroutinesApi::class)+class LauncherFlowTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private val source = StoreTv()+ private lateinit var vm: TellyscopeViewModel++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ vm.viewModelScope.cancel()+ Dispatchers.resetMain()+ }++ private fun TestScope.started(): TellyscopeViewModel {+ vm = TellyscopeViewModel(source, clock = { 0L })+ runCurrent()+ vm.openLauncherFlow()+ return vm+ }++ private val step get() = vm.state.value.device.launcher?.step++ @Test fun itWaitsForTheInstallThenOffersTheSwitch() = with(test) {+ source.states = ArrayDeque(listOf(StoreState.InStore, StoreState.Installed))+ started().installLauncher(PROJECTIVY)+ runCurrent()+ assertEquals(listOf(PROJECTIVY), source.opened)+ assertEquals(LauncherFlow.Step.Waiting, step)+ advanceTimeBy(STORE_POLL_MS + 1)+ assertEquals(LauncherFlow.Step.Waiting, step)+ advanceTimeBy(STORE_POLL_MS)+ assertEquals(LauncherFlow.Step.Installed, step)+ assertTrue(vm.state.value.device.apps.any { it.packageName == PROJECTIVY })++ vm.switchToLauncher(service = false)+ runCurrent()+ assertNull(step)+ assertEquals(listOf(PROJECTIVY to false), source.switched)+ }++ @Test fun aStoreThatClosesWithoutTheInstallSaysSo() = with(test) {+ source.states = ArrayDeque(listOf(StoreState.InStore, StoreState.Elsewhere))+ started().installLauncher(PROJECTIVY)+ advanceTimeBy(2 * STORE_POLL_MS + 1)+ assertEquals(LauncherFlow.Step.Left, step)+ advanceTimeBy(10 * STORE_POLL_MS)+ assertEquals(LauncherFlow.Step.Left, step) // stopped checking+ }++ @Test fun aStoreThatDidntOpenSaysSoAndStillCatchesAnInstallByHand() = with(test) {+ source.opens = false+ source.states = ArrayDeque(listOf(StoreState.Elsewhere, StoreState.Installed))+ started().installLauncher(PROJECTIVY)+ runCurrent()+ assertEquals(LauncherFlow.Step.NoStore, step)+ advanceTimeBy(STORE_POLL_MS + 1)+ assertEquals(LauncherFlow.Step.NoStore, step) // never on screen, so not "closed"+ advanceTimeBy(STORE_POLL_MS)+ assertEquals(LauncherFlow.Step.Installed, step)+ }++ @Test fun notNowAfterTheInstallSaysWhereToSwitchLater() = with(test) {+ source.states = ArrayDeque(listOf(StoreState.Installed))+ started().installLauncher(PROJECTIVY)+ advanceTimeBy(STORE_POLL_MS + 1)+ vm.launcherLater()+ assertNull(step)+ assertEquals(Copy.launcherLater("Projectivy Launcher"), vm.notice.value)+ assertTrue(source.switched.isEmpty())+ }++ @Test fun closingStopsTheWait() = with(test) {+ started().installLauncher(PROJECTIVY)+ runCurrent()+ vm.closeLauncherFlow()+ source.states = ArrayDeque(listOf(StoreState.Installed))+ advanceTimeBy(5 * STORE_POLL_MS)+ assertNull(step)+ assertFalse(source.installed)+ }++ @Test fun notNowPutsTheCardAwayForThatTv() = with(test) {+ vm = TellyscopeViewModel(source, clock = { 0L })+ runCurrent()+ assertFalse(vm.state.value.device.launcherCardHidden)+ vm.hideLauncherCard()+ runCurrent()+ assertTrue(vm.state.value.device.launcherCardHidden)+ assertTrue(source.hidden)+ }+}++/** What the screens offer at each step. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class LauncherScreenTest {+ @get:Rule val compose = createComposeRule()++ private val tv = Device("tv", ScanHit("tv", 5555, ScanKind.Classic, "tv", null), DeviceState.Online, null, null, null, 0L)++ @Test fun theCardShowsOnlyWithAStoreAndNoSecondLauncher() {+ assertTrue(offerLauncher(listOf(store, stock), hidden = false))+ assertFalse(offerLauncher(listOf(store, stock), hidden = true))+ assertFalse(offerLauncher(listOf(stock), hidden = false)) // Fire TV: no Play Store+ val other = AppInfo(PROJECTIVY, "Projectivy Launcher", null, false, true, null, "1.0", homeInstead = TV_HOME)+ assertFalse(offerLauncher(listOf(store, stock, other), hidden = false))+ }++ @Test fun theCardsTwoButtons() {+ var notNow = false+ var chose = false+ compose.setContent { LauncherCard("Google TV Home", onNotNow = { notNow = true }, onChoose = { chose = true }) }+ compose.onNodeWithText(Copy.NOT_NOW).performClick()+ compose.onNodeWithText(Copy.CHOOSE_ONE).performClick()+ assertTrue(notNow && chose)+ }++ @Test fun thePickedLauncherIsTheOneInstalled() {+ val installs = mutableListOf<String>()+ compose.setContent { LauncherScreen(tv, LauncherFlow(), listOf(store, stock), LauncherActions(install = { installs += it })) }+ compose.onNodeWithText("FLauncher").performClick()+ compose.onNodeWithText(Copy.OPEN_IN_STORE).performClick()+ assertEquals(listOf(FLAUNCHER), installs)+ }++ @Test fun theStoreDidntOpenOffersAnotherOrARetry() {+ val installs = mutableListOf<String>()+ val picks = mutableListOf<String>()+ compose.setContent {+ LauncherScreen(tv, LauncherFlow(LauncherFlow.Step.NoStore, PROJECTIVY), listOf(store, stock), LauncherActions(install = { installs += it }, chooseAnother = { picks += it }))+ }+ compose.onNodeWithText(Copy.NO_STORE).assertExists()+ compose.onNodeWithText(Copy.TRY_AGAIN).performClick()+ compose.onNodeWithText(Copy.CHOOSE_ANOTHER).performClick()+ assertEquals(listOf(PROJECTIVY), installs)+ assertEquals(listOf(PROJECTIVY), picks)+ }++ @Test fun yesOnAServiceLauncherAsksAboutTheService() {+ val switches = mutableListOf<Boolean>()+ val projectivy = AppInfo(PROJECTIVY, "Projectivy Launcher", null, false, true, null, "1.0", homeInstead = TV_HOME, homeService = true)+ compose.setContent {+ LauncherScreen(tv, LauncherFlow(LauncherFlow.Step.Installed, PROJECTIVY), listOf(store, stock, projectivy), LauncherActions(switch = { switches += it }))+ }+ compose.onNodeWithText(Copy.MAKE_IT_HOME).assertExists()+ compose.onNodeWithText(Copy.confirm(app.tellyscope.data.Action.Home)).performClick()+ compose.onNodeWithText(Copy.serviceTitle("Projectivy Launcher")).assertExists()+ compose.onNodeWithText(Copy.TURN_IT_ON).performClick()+ assertEquals(listOf(true), switches)+ }+}diff --git a/app/src/test/java/app/tellyscope/LaunchersTest.kt b/app/src/test/java/app/tellyscope/LaunchersTest.ktindex d8e592e..e7ff4da 100644--- a/app/src/test/java/app/tellyscope/LaunchersTest.kt+++ b/app/src/test/java/app/tellyscope/LaunchersTest.kt@@ -4,6 +4,7 @@ package app.tellyscopeimport app.tellyscope.data.KnownLauncherimport app.tellyscope.data.parseLaunchers+import app.tellyscope.ui.RECOMMENDEDimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Test@@ -27,6 +28,15 @@ class LaunchersTest {)}+ @Test fun theRecommendedOnesAreOnTheBundledListAsItSaysThem() {+ val known = parseLaunchers(File("src/main/assets/launchers.json").readText()).associateBy { it.pkg }+ RECOMMENDED.forEach { r ->+ val k = known[r.pkg] ?: error("${r.pkg} isn't in launchers.json")+ assertEquals(r.pkg, k.accessibility, r.accessibility)+ assertEquals(k.name, r.name)+ }+ }+@Test fun badEntriesAreDroppedAndOnlySchemaOneCounts() {val text = """{"schema":1,"launchers":[{"package":"com.good.launcher","name":"Good","accessibility":true},