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.

Home switch: only the TV's own launcher goes off

jesse-agent-232fa2b0bde5bea
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
index 73fa789..e55905b 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt
@@ -15,10 +15,11 @@ sealed interface ActionResult {
/**
* What [Actions.makeHome] did. [from] and [to] are the old and new home activities, for Undo;
- * [from] is null when the TV had no default home and no launcher of its own to replace.
+ * [from] is null when the TV had no default home and no launcher of its own to replace. [kept]:
+ * the old launcher was one the user added, so it stayed on.
*/
sealed interface HomeResult {
- data class Switched(val from: String?, val to: String) : HomeResult
+ data class Switched(val from: String?, val to: String, val kept: Boolean = false) : HomeResult
data class Refused(val reason: ProtectedReason) : HomeResult
data class Failed(val output: String) : HomeResult
}
@@ -93,7 +94,8 @@ class Actions(private val shell: AdbShell) {
/**
* Makes [pkg] the home screen in place of the current one, then disables the old launcher so
- * the TV can't switch back by itself. Home is checked to open [pkg] before anything is
+ * the TV can't switch back by itself. Only a launcher the TV came with is ever disabled: one
+ * the user added stays on, and the switch only moves Home. Home is checked to open [pkg] before anything is
* disabled; if it doesn't, the old home is set back and nothing is turned off. The one
* exception: Android skips the default while a launcher with a higher Home priority is on, as
* Android TV Home is. Such an old launcher is turned off first, and turned back on and made
@@ -104,12 +106,18 @@ class Actions(private val shell: AdbShell) {
// With no default home, the TV's own launcher is the one being replaced; with none on, nothing is.
val from = currentHome() ?: stockHome() ?: return firstHome(pkg)
val old = from.substringBefore('/')
- if (old == pkg) return HomeResult.Failed("it's already the home screen")
+ // With no default home, the TV's own launcher can be made the default too.
+ if (old == pkg) return if (currentHome() == null) firstHome(pkg) else HomeResult.Failed("it's already the home screen")
val homes = shell.shell(Commands.HOME_ACTIVITIES).output
val to = launchersIn(homes)[pkg] ?: return HomeResult.Failed("it has no home screen")
// The old launcher is protected as the home screen and by name; once it isn't Home, that
// guard has done its job. Any other reason still stands.
Protected.reason(old)?.takeIf { it != ProtectedReason.HOME_SCREEN }?.let { return HomeResult.Refused(it) }
+ if (old in userPackages()) {
+ if (setHome(to)) return HomeResult.Switched(from, to, kept = true)
+ setHome(from)
+ return HomeResult.Failed("the TV kept the home screen it has")
+ }
val checked = setHome(to)
val priority = prioritiesIn(homes)
if (!checked && (priority[old] ?: 0) <= (priority[pkg] ?: 0)) {
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt
index b487015..1ed1e28 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt
@@ -95,6 +95,26 @@ class ActionsTest {
assertEquals("com.spocky.projengmenu/.ui.home.MainActivity", Actions(sh).currentHome())
}
+ @Test fun aSwitchBetweenTheUsersLaunchersTurnsNeitherOff() = runTest {
+ val sh = stockOff("com.spocky.projengmenu", "me.efesser.flauncher")
+ Actions(sh).makeHome("com.spocky.projengmenu")
+ assertEquals(
+ HomeResult.Switched("com.spocky.projengmenu/.ui.home.MainActivity", "me.efesser.flauncher/.MainActivity", kept = true),
+ Actions(sh).makeHome("me.efesser.flauncher"),
+ )
+ assertTrue(sh.ran.none { it.startsWith("pm disable") || it.startsWith("pm enable") })
+ assertEquals("me.efesser.flauncher/.MainActivity", Actions(sh).currentHome())
+ }
+
+ @Test fun aSwitchBetweenTheUsersLaunchersThatDoesNotTakePutsHomeBack() = runTest {
+ val sh = stockOff("com.spocky.projengmenu", "me.efesser.flauncher")
+ Actions(sh).makeHome("com.spocky.projengmenu")
+ sh.answer.let { prev -> sh.answer = { if (it.startsWith("cmd package set-home-activity --user 0 'me.")) ok("Success\n") else prev(it) } }
+ assertEquals(HomeResult.Failed("the TV kept the home screen it has"), Actions(sh).makeHome("me.efesser.flauncher"))
+ assertEquals("com.spocky.projengmenu/.ui.home.MainActivity", Actions(sh).currentHome())
+ assertTrue(sh.ran.none { it.startsWith("pm ") && !it.startsWith("pm list") })
+ }
+
@Test fun stockOffAndOneOfTheUsersLaunchersKeepsItLocked() = runTest {
// The only launcher left: without it the TV would have no home screen.
val sh = stockOff("com.spocky.projengmenu")
@@ -275,6 +295,29 @@ class ActionsTest {
assertTrue("pm disable-user --user 0 com.google.android.tvlauncher 2>&1" in sh.ran)
}
+ @Test fun noDefaultHomeMakesTheTvsOwnTheDefault() = runTest {
+ var home = "android/com.android.internal.app.ResolverActivity"
+ val sh = FakeShell(mapOf(
+ "cmd package query-activities" to ok("com.google.android.tvlauncher/.MainActivity\ncom.spocky.projengmenu/.ui.home.MainActivity\n"),
+ "pm list packages -3" to ok("package:com.spocky.projengmenu\n"),
+ )).apply {
+ answer = { cmd ->
+ when {
+ cmd.startsWith("cmd package resolve-activity") -> ok("priority=0\n$home\n")
+ cmd.startsWith("cmd package set-home-activity") -> {
+ home = cmd.substringAfter("'").substringBefore("'")
+ ok("Success\n")
+ }
+ else -> null
+ }
+ }
+ }
+ assertEquals(HomeResult.Switched(null, "com.google.android.tvlauncher/.MainActivity"), Actions(sh).makeHome("com.google.android.tvlauncher"))
+ assertTrue(sh.ran.none { it.startsWith("pm disable") || it.startsWith("pm enable") })
+ // Once it's the default, it's Home: asking again changes nothing.
+ assertTrue(Actions(sh).makeHome("com.google.android.tvlauncher") is HomeResult.Failed)
+ }
+
@Test fun makeHomeSwitchesChecksThenDisables() = runTest {
val sh = twoLaunchers()
assertEquals(
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index c24dfab..bedb1e1 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -510,9 +510,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
is ActionResult.Done -> {
// Undoing a home switch: the old launcher is on again, now make it Home again too.
val switch = undoing?.let { id -> book.entries(key).firstOrNull { it.id == id && it.action == Action.Home } }
- val back = switch?.previous?.get("from")?.let { Actions(shell).setHome(it) }
- // The service the switch turned on was only there to hold Home.
- switch?.previous?.get("service")?.let { Actions(shell).setService(it, false) }
+ val back = switch?.let { undoHomeSwitch(Actions(shell), it) }
book.record(
deviceId = key,
at = System.currentTimeMillis(),
@@ -533,34 +531,16 @@ class AdbDeviceSource(context: Context) : DeviceSource {
private suspend fun switchHome(deviceId: String, packageName: String, undoing: Long?, withService: Boolean): HistoryEntry {
fireHomes -= deviceId
val key = key(deviceId)
- val actions = Actions(session(deviceId))
- return when (val r = actions.makeHome(packageName)) {
- is HomeResult.Switched -> {
- // Where the TV sends Home to its own launcher, the new one holds it with this service.
- val service = packageName.takeIf { withService && it in serviceLaunchers }?.let { actions.homeService(it) }?.takeUnless { actions.serviceOn(it) }
- val on = service?.let { actions.setService(it, true) }
- val label = labels[packageName] ?: AppNames.fallback(packageName)
- book.record(
- deviceId = key,
- at = System.currentTimeMillis(),
- action = Action.Home,
- // With no launcher of the TV's own to replace, nothing was turned off: Undo is for the service alone.
- packageName = r.from?.substringBefore('/') ?: packageName,
- label = label,
- undo = Action.Enable.takeIf { r.from != null || on == true },
- undoing = undoing,
- // "service" only when this switch turned it on, so Undo turns off no more than that.
- previous = listOfNotNull(r.from?.let { "from" to it }, "to" to r.to, service?.takeIf { on == true }?.let { "service" to it }).toMap(),
- ).also { if (on == false) throw IllegalStateException(serviceNotOn(label)) }
- }
- is HomeResult.Refused -> throw IllegalStateException(reasonText(r.reason))
- is HomeResult.Failed -> throw IllegalStateException(r.output.ifEmpty { "the TV refused" })
+ return switchHome(Actions(session(deviceId)), packageName, withService, serviceLaunchers, ::labelOf, ::reasonText) { pkg, undo, previous ->
+ book.record(key, System.currentTimeMillis(), Action.Home, pkg, labelOf(packageName), undo, undoing, previous)
}
}
+ private fun labelOf(pkg: String) = labels[pkg] ?: AppNames.fallback(pkg)
+
/** Undo of a first home: [launcher] stays Home, as there's none to go back to; its [service] goes off. */
private suspend fun firstHomeServiceOff(deviceId: String, launcher: String, service: String, undoing: Long): HistoryEntry {
- val label = labels[launcher] ?: AppNames.fallback(launcher)
+ val label = labelOf(launcher)
if (!Actions(session(deviceId)).setService(service, false)) throw IllegalStateException(serviceStillOn(label))
return book.record(
deviceId = key(deviceId),
@@ -921,12 +901,6 @@ class AdbDeviceSource(context: Context) : DeviceSource {
else -> "closing"
}
- private fun serviceNotOn(app: String) =
- "$app is Home now, but its accessibility service didn't turn on, so the TV's Home button may still open its own launcher"
-
- private fun serviceNotOff(app: String) =
- "switched back, but $app's accessibility service is still on. Turn it off in the TV's Settings → Accessibility"
-
private fun serviceStillOn(app: String) =
"$app's accessibility service is still on. Turn it off in the TV's Settings → Accessibility"
@@ -948,6 +922,65 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
}
+/**
+ * Makes [pkg] Home and hands [record] the entry's package, its Undo and what Undo reverses. Only
+ * a launcher the TV came with is ever turned off ([Actions.makeHome]). With [withService], a
+ * launcher in [serviceLaunchers] gets its accessibility service on to hold Home. A launcher the
+ * user added that was Home stays on, and its service goes off, or it would take Home straight
+ * back. The entry is recorded before a service step that didn't take throws, so Undo still works.
+ */
+internal suspend fun switchHome(
+ actions: Actions,
+ pkg: String,
+ withService: Boolean,
+ serviceLaunchers: Set<String>,
+ label: (String) -> String,
+ reason: (ProtectedReason) -> String,
+ record: (packageName: String, undo: Action?, previous: Map<String, String?>) -> HistoryEntry,
+): HistoryEntry = when (val r = actions.makeHome(pkg)) {
+ is HomeResult.Switched -> {
+ // Where the TV sends Home to its own launcher, the new one holds it with this service.
+ val service = pkg.takeIf { withService && it in serviceLaunchers }?.let { actions.homeService(it) }?.takeUnless { actions.serviceOn(it) }
+ val on = service?.let { actions.setService(it, true) }
+ val was = r.from?.substringBefore('/')?.takeIf { r.kept }
+ val old = was?.takeIf { it in serviceLaunchers }?.let { actions.homeService(it) }?.takeIf { actions.serviceOn(it) }
+ val off = old?.let { actions.setService(it, false) }
+ record(
+ // With no launcher to replace, nothing was turned off: Undo is only for a service it turned on.
+ r.from?.substringBefore('/') ?: pkg,
+ Action.Enable.takeIf { r.from != null || on == true },
+ // "service" only when this switch turned it on, and "fromService" only when it turned the
+ // old one's off, so Undo reverses no more than that. "kept": the old launcher stayed on.
+ listOfNotNull(
+ r.from?.let { "from" to it }, "to" to r.to, service?.takeIf { on == true }?.let { "service" to it },
+ ("kept" to "true").takeIf { r.kept }, old?.takeIf { off == true }?.let { "fromService" to it },
+ ).toMap(),
+ ).also {
+ if (on == false) throw IllegalStateException(serviceNotOn(label(pkg)))
+ if (off == false) throw IllegalStateException(serviceNotOff(label(was!!)))
+ }
+ }
+ is HomeResult.Refused -> throw IllegalStateException(reason(r.reason))
+ is HomeResult.Failed -> throw IllegalStateException(r.output.ifEmpty { "the TV refused" })
+}
+
+/**
+ * The rest of [switch]'s Undo once its old launcher is on again: Home back to that launcher, the
+ * service the switch turned on off, and the old one's back on. False when Home didn't go back.
+ */
+internal suspend fun undoHomeSwitch(actions: Actions, switch: HistoryEntry): Boolean {
+ val back = switch.previous?.get("from")?.let { actions.setHome(it) }
+ switch.previous?.get("service")?.let { actions.setService(it, false) }
+ switch.previous?.get("fromService")?.let { actions.setService(it, true) }
+ return back != false
+}
+
+private fun serviceNotOn(app: String) =
+ "$app is Home now, but its accessibility service didn't turn on, so the TV's Home button may still open its own launcher"
+
+private fun serviceNotOff(app: String) =
+ "switched back, but $app's accessibility service is still on. Turn it off in the TV's Settings → Accessibility"
+
/**
* Writes [values] and hands [record] the label and the old values for History. Strict Private DNS
* fails closed: a provider the network can't reach takes the TV offline, so it's put back on the
diff --git a/app/src/main/java/app/tellyscope/data/HistoryBook.kt b/app/src/main/java/app/tellyscope/data/HistoryBook.kt
index 95bec8f..14ea408 100644
--- a/app/src/main/java/app/tellyscope/data/HistoryBook.kt
+++ b/app/src/main/java/app/tellyscope/data/HistoryBook.kt
@@ -194,10 +194,12 @@ fun homeBackTarget(current: String, history: List<HistoryEntry>, builtIns: List<
}
/**
- * A home switch disables the old launcher, unless there was none to replace: then it offers no
- * undo, or one for its service only.
+ * A home switch disables the old launcher, unless there was none to replace (then it offers no
+ * undo, or one for its service only) or the old one was a launcher the user added, which stays
+ * on ("kept").
*/
-private val HistoryEntry.disables get() = action == Action.Disable || (action == Action.Home && undo != null && firstHomeService == null)
+private val HistoryEntry.disables get() =
+ action == Action.Disable || (action == Action.Home && undo != null && firstHomeService == null && previous?.get("kept") == null)
/** The service a switch with no launcher to replace turned on: its Undo turns that off, and nothing else. */
val HistoryEntry.firstHomeService: String?
diff --git a/app/src/test/java/app/tellyscope/HomeSwitchTest.kt b/app/src/test/java/app/tellyscope/HomeSwitchTest.kt
new file mode 100644
index 0000000..b8cb04b
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/HomeSwitchTest.kt
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import app.tellyscope.adb.Action as AdbAction
+import app.tellyscope.adb.Actions
+import app.tellyscope.adb.AdbPipe
+import app.tellyscope.adb.AdbSession
+import app.tellyscope.adb.RemoteEntry
+import app.tellyscope.adb.ShellResult
+import app.tellyscope.data.Action
+import app.tellyscope.data.HistoryBook
+import app.tellyscope.data.HistoryEntry
+import app.tellyscope.data.switchHome
+import app.tellyscope.data.undoHomeSwitch
+import java.io.File
+import java.io.IOException
+import kotlinx.coroutines.test.runTest
+import okio.Sink
+import okio.Source
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+private const val TV_HOME = "com.google.android.tvlauncher"
+private const val PROJECTIVY = "com.spocky.projengmenu"
+private const val FLAUNCHER = "me.efesser.flauncher"
+private const val PROJECTIVY_SERVICE = "$PROJECTIVY/.HomeService"
+
+/** A TV with its own launcher and two the user added; Projectivy has an accessibility service. */
+private class LauncherTv(var home: String?) : AdbSession {
+ val activities = mapOf(TV_HOME to "$TV_HOME/.MainActivity", PROJECTIVY to "$PROJECTIVY/.Main", FLAUNCHER to "$FLAUNCHER/.MainActivity")
+ val enabled = activities.keys.toMutableSet()
+ val user = setOf(PROJECTIVY, FLAUNCHER)
+ val services = mutableListOf<String>()
+
+ override suspend fun shell(command: String): ShellResult {
+ val pkg = command.substringAfter("--user 0 ").substringBefore(' ')
+ val quoted = command.substringAfter("'").substringBefore("'")
+ return when {
+ command.startsWith("cmd package resolve-activity") -> ok("priority=0\n${home?.let(activities::getValue) ?: "android/com.android.internal.app.ResolverActivity"}\n")
+ command.startsWith("cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME") -> ok(activities.filterKeys { it in enabled }.values.joinToString("") { "priority=0\n$it\n" })
+ command.startsWith("cmd package set-home-activity") -> ok("Success\n").also { quoted.substringBefore('/').takeIf { it in enabled }?.let { home = it } }
+ command.startsWith("pm list packages -3") -> ok(user.joinToString("") { "package:$it\n" })
+ command.startsWith("pm disable-user") -> ok("Package $pkg new state: disabled-user\n").also { enabled -= pkg }
+ command.startsWith("pm enable") -> ok("Package $pkg new state: enabled\n").also { enabled += pkg }
+ command.startsWith("cmd package query-services") -> ok("$PROJECTIVY_SERVICE\n")
+ command.startsWith("settings get secure enabled_accessibility_services") -> ok(services.joinToString(":").ifEmpty { "null" } + "\n")
+ command.startsWith("settings put secure enabled_accessibility_services") -> ok("").also { services.clear(); services += quoted.split(':') }
+ command.startsWith("settings delete secure enabled_accessibility_services") -> ok("").also { services.clear() }
+ else -> ok("")
+ }
+ }
+
+ private fun ok(out: String) = ShellResult(out, 0)
+
+ override suspend fun push(bytes: ByteArray, remotePath: String) = Unit
+ override suspend fun reboot() = Unit
+ override suspend fun exec(command: String): AdbPipe = throw IOException("no exec")
+ override fun install(source: Source, size: Long, vararg options: String) = Unit
+ override fun installMultiple(apks: List<File>, vararg options: String) = Unit
+ override fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) = Unit
+ override fun pull(sink: Sink, remotePath: String) = Unit
+ override fun list(remoteDir: String) = emptyList<RemoteEntry>()
+ override fun close() = Unit
+}
+
+/** The switch rule: only the TV's own launcher goes off, and Undo reverses exactly what the switch did. */
+class HomeSwitchTest {
+ private val book = HistoryBook()
+
+ private suspend fun switch(tv: LauncherTv, pkg: String, withService: Boolean = true): HistoryEntry =
+ switchHome(Actions(tv), pkg, withService, setOf(PROJECTIVY), { it }, { it.name }) { from, undo, previous ->
+ book.record("tv", 0, Action.Home, from, pkg, undo, previous = previous)
+ }
+
+ /** What Undo in History runs for a switch: its old launcher on again, then the rest. */
+ private suspend fun undo(tv: LauncherTv, entry: HistoryEntry) {
+ Actions(tv).run(AdbAction.ENABLE, entry.packageName)
+ assertTrue(undoHomeSwitch(Actions(tv), entry))
+ }
+
+ @Test fun theTvsOwnLauncherIsTurnedOffAndUndoTurnsItBackOn() = runTest {
+ val tv = LauncherTv(home = TV_HOME)
+ val entry = switch(tv, FLAUNCHER)
+ assertEquals(FLAUNCHER, tv.home)
+ assertFalse(TV_HOME in tv.enabled)
+ assertEquals(listOf(TV_HOME), HistoryBook.leftDisabled(book.entries("tv")))
+ undo(tv, entry)
+ assertEquals(TV_HOME, tv.home)
+ assertTrue(TV_HOME in tv.enabled)
+ }
+
+ @Test fun aLauncherTheUserAddedStaysOnAndUndoMakesItHomeAgain() = runTest {
+ val tv = LauncherTv(home = FLAUNCHER)
+ val entry = switch(tv, PROJECTIVY, withService = false)
+ assertEquals(PROJECTIVY, tv.home)
+ assertTrue(FLAUNCHER in tv.enabled)
+ // Nothing went off, so Restore has nothing to turn on.
+ assertEquals(emptyList<String>(), HistoryBook.leftDisabled(book.entries("tv")))
+ undo(tv, entry)
+ assertEquals(FLAUNCHER, tv.home)
+ }
+
+ @Test fun switchingAwayFromAServiceLauncherTurnsItsServiceOffAndUndoBackOn() = runTest {
+ val tv = LauncherTv(home = PROJECTIVY).apply { services += PROJECTIVY_SERVICE }
+ val entry = switch(tv, FLAUNCHER)
+ assertEquals(FLAUNCHER, tv.home)
+ assertTrue(PROJECTIVY in tv.enabled)
+ assertTrue(tv.services.isEmpty())
+ undo(tv, entry)
+ assertEquals(PROJECTIVY, tv.home)
+ assertEquals(listOf(PROJECTIVY_SERVICE), tv.services)
+ }
+
+ @Test fun switchingToAServiceLauncherTurnsItsServiceOnAndUndoOff() = runTest {
+ val tv = LauncherTv(home = TV_HOME)
+ val entry = switch(tv, PROJECTIVY)
+ assertEquals(listOf(PROJECTIVY_SERVICE), tv.services)
+ undo(tv, entry)
+ assertEquals(TV_HOME, tv.home)
+ assertTrue(tv.services.isEmpty())
+ }
+
+ @Test fun withNoDefaultTheTvsOwnLauncherBecomesTheDefaultWithNothingTurnedOff() = runTest {
+ val tv = LauncherTv(home = null)
+ val entry = switch(tv, TV_HOME)
+ assertEquals(TV_HOME, tv.home)
+ assertEquals(setOf(TV_HOME, PROJECTIVY, FLAUNCHER), tv.enabled)
+ // Nothing to reverse: no launcher went off and no service came on.
+ assertNull(entry.undo)
+ }
+}