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.
Make home: close the old launcher and open the new one
jesse-agent-8216ccd9ef3ecc8
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.ktindex 23d3164..1aedad9 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt@@ -16,11 +16,12 @@ 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. [kept]:- * the old launcher was one the user added, so it stayed on. A [Failed.output] is one plain line;- * [Failed.details] keeps what the TV printed, for a problem report.+ * the old launcher was one the user added, so it stayed on. [left]: Home moved, but the old+ * launcher didn't close or the new one didn't open; null when both did. A [Failed.output] is one+ * plain line; [Failed.details] keeps what the TV printed, for a problem report.*/sealed interface HomeResult {- data class Switched(val from: String?, val to: String, val kept: Boolean = false) : HomeResult+ data class Switched(val from: String?, val to: String, val kept: Boolean = false, val left: String? = null) : HomeResultdata class Refused(val reason: ProtectedReason) : HomeResultdata class Failed(val output: String, val details: String = output) : HomeResult}@@ -101,7 +102,7 @@ class Actions(private val shell: AdbShell) {* 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- * Home again if Home still doesn't open [pkg].+ * Home again if Home still doesn't open [pkg]. Once switched, the TV goes to [pkg] ([handOff]).*/suspend fun makeHome(pkg: String): HomeResult {require(PACKAGE.matches(pkg)) { "not a package name: $pkg" }@@ -116,7 +117,7 @@ class Actions(private val shell: AdbShell) {// 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)+ if (setHome(to)) return HomeResult.Switched(from, to, kept = true, left = handOff(old, to))setHome(from)return HomeResult.Failed("the TV kept the home screen it has")}@@ -131,7 +132,8 @@ class Actions(private val shell: AdbShell) {setHome(from)return HomeResult.Failed("the TV wouldn't turn the old home screen off, so nothing changed", off.output)}- if (checked || setHome(to)) return HomeResult.Switched(from, to)+ // Turning it off closed it too: only the new one is left to open.+ if (checked || setHome(to)) return HomeResult.Switched(from, to, left = handOff(null, to))val on = exec("pm enable --user 0 $old", undo = null) { "enabled" in it }setHome(from)if (on is ActionResult.Failed) {@@ -143,7 +145,8 @@ class Actions(private val shell: AdbShell) {/*** Makes [pkg] Home again after another launcher took over: turns it on if it's off, then sets* [activity], the one the switch away from it saved, or else its own home activity. The- * launcher that was Home stays on, so it can be made Home again or uninstalled.+ * launcher that was Home stays on, so it can be made Home again or uninstalled; it's closed,+ * and the TV goes to [pkg] ([handOff]).*/suspend fun homeBack(pkg: String, activity: String? = null): HomeResult {require(PACKAGE.matches(pkg)) { "not a package name: $pkg" }@@ -157,7 +160,7 @@ class Actions(private val shell: AdbShell) {setHome(from)return HomeResult.Failed("the TV kept the home screen it has")}- return HomeResult.Switched(from, to)+ return HomeResult.Switched(from, to, left = handOff(from.substringBefore('/'), to))}/** Makes [activity] (`package/class`) the default home, then checks that Home opens it. */@@ -225,7 +228,22 @@ class Actions(private val shell: AdbShell) {private suspend fun firstHome(pkg: String): HomeResult {val to = launchers()[pkg] ?: return HomeResult.Refused(ProtectedReason.UNKNOWN_HOME)if (!setHome(to)) return HomeResult.Failed("the TV still asks which home screen to use")- return HomeResult.Switched(null, to)+ return HomeResult.Switched(null, to, left = handOff(null, to))+ }++ /**+ * After a switch, so the TV shows the new home screen without a Home press: closes [old], the+ * launcher that was Home if it's still on, then opens [to]. Home has moved either way, so a+ * step that fails is only reported. Null when both took.+ */+ private suspend fun handOff(old: String?, to: String): String? {+ val stop = old?.takeIf { it != to.substringBefore('/') }?.let { exec("am force-stop $it", undo = null) }+ val open = shell.shell("${Commands.OPEN_HOME} '$to' 2>&1")+ return when {+ open.exitCode != 0 || "Error" in open.output -> "it didn't open (${open.output.trim()}), so press Home on the remote to go there"+ stop is ActionResult.Failed -> "the old home screen didn't close (${stop.output})"+ else -> null+ }}/** With no default home, the TV's own launcher that is on: the built-in one Home ranks highest. */diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt b/adb/src/main/kotlin/app/tellyscope/adb/Commands.ktindex 5bf2fc8..f958d4c 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Commands.kt@@ -46,6 +46,8 @@ internal object Commands {const val SYSTEM_PACKAGES = "pm list packages -s"const val HOME_ACTIVITY = "cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME"const val SET_HOME = "cmd package set-home-activity --user 0"+ /** Opens a launcher's home activity, named after `-n`; Fire TV's Home key won't reach anything but Amazon's. */+ const val OPEN_HOME = "am start -a android.intent.action.MAIN -c android.intent.category.HOME -n"const val HOME_ACTIVITIES = "cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME"/** Apps with an icon on a TV home screen. */const val TV_LAUNCHABLE = "cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LEANBACK_LAUNCHER"diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt b/adb/src/main/kotlin/app/tellyscope/adb/Remote.ktindex 6baee33..4c9017f 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt@@ -40,7 +40,7 @@ class Remote(private val session: AdbSession, private val keys: KeyHelper? = nul*/suspend fun home(launcher: String?): Boolean {if (launcher != null && COMPONENT.matches(launcher)) {- val r = session.shell("am start -a android.intent.action.MAIN -c android.intent.category.HOME -n '$launcher' 2>&1")+ val r = session.shell("${Commands.OPEN_HOME} '$launcher' 2>&1")if (r.exitCode == 0 && "Error" !in r.output) return true}return press(RemoteKey.HOME)diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.ktindex dd18edc..461e44c 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/ActionsTest.kt@@ -484,4 +484,54 @@ class ActionsTest {val sh = FakeShell(mapOf("dumpsys package packages" to ok(dump)))assertEquals(setOf("com.android.nfc", "com.oem.lazy"), Actions(sh).disabledByTv())}++ @Test fun aSwitchFromTheUsersLauncherStopsItThenOpensTheNewOne() = runTest {+ val sh = stockOff("com.spocky.projengmenu", "me.efesser.flauncher")+ Actions(sh).makeHome("com.spocky.projengmenu")+ sh.ran.clear()+ Actions(sh).makeHome("me.efesser.flauncher")+ val set = sh.ran.indexOf("cmd package set-home-activity --user 0 'me.efesser.flauncher/.MainActivity' 2>&1")+ val stop = sh.ran.indexOf("am force-stop com.spocky.projengmenu 2>&1")+ val open = sh.ran.indexOf("am start -a android.intent.action.MAIN -c android.intent.category.HOME -n 'me.efesser.flauncher/.MainActivity' 2>&1")+ assertTrue(set >= 0 && stop > set && open > stop, sh.ran.toString())+ assertTrue(sh.ran.none { it == "am force-stop me.efesser.flauncher 2>&1" })+ }++ @Test fun aSwitchFromTheTvsOwnOpensTheNewOneAndStopsNothing() = runTest {+ // Turning the TV's own launcher off closes it already.+ val sh = twoLaunchers()+ Actions(sh).makeHome("com.spocky.projengmenu")+ val off = sh.ran.indexOf("pm disable-user --user 0 com.google.android.tvlauncher 2>&1")+ val open = sh.ran.indexOf("am start -a android.intent.action.MAIN -c android.intent.category.HOME -n 'com.spocky.projengmenu/.ui.home.MainActivity' 2>&1")+ assertTrue(off >= 0 && open > off, sh.ran.toString())+ assertTrue(sh.ran.none { it.startsWith("am force-stop") })+ }++ @Test fun aHomeThatDoesNotOpenKeepsTheSwitch() = runTest {+ val sh = twoLaunchers()+ sh.answer.let { prev -> sh.answer = { if (it.startsWith("am start")) ok("Error: Activity not started\n") else prev(it) } }+ val r = Actions(sh).makeHome("com.spocky.projengmenu") as HomeResult.Switched+ assertTrue(r.left.orEmpty().startsWith("it didn't open"), r.left)+ assertEquals("com.spocky.projengmenu", Actions(sh).homeOptions()?.current)+ assertTrue(sh.ran.none { it.startsWith("pm enable") })+ }++ @Test fun anOldHomeThatDoesNotStopKeepsTheSwitch() = 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("am force-stop")) ShellResult("Error: denied\n", 1) else prev(it) } }+ val r = Actions(sh).makeHome("me.efesser.flauncher") as HomeResult.Switched+ assertEquals("the old home screen didn't close (Error: denied)", r.left)+ assertEquals("me.efesser.flauncher/.MainActivity", Actions(sh).currentHome())+ }++ @Test fun homeBackStopsTheLauncherItLeavesAndOpensTheTvsOwn() = runTest {+ val sh = twoLaunchers()+ Actions(sh).makeHome("com.spocky.projengmenu")+ sh.ran.clear()+ Actions(sh).homeBack("com.google.android.tvlauncher", "com.google.android.tvlauncher/.MainActivity")+ val stop = sh.ran.indexOf("am force-stop com.spocky.projengmenu 2>&1")+ val open = sh.ran.indexOf("am start -a android.intent.action.MAIN -c android.intent.category.HOME -n 'com.google.android.tvlauncher/.MainActivity' 2>&1")+ assertTrue(stop >= 0 && open > stop, sh.ran.toString())+ }}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex d77d9ce..c58e3a4 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -605,7 +605,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {// The switch away from it is reversed now, so Restore leaves it alone.undoing = undoing ?: target.reverses,previous = listOfNotNull(r.from?.let { "from" to it }, "to" to r.to, service?.takeIf { off == true }?.let { "service" to it }).toMap(),- ).also { if (off == false) throw IllegalStateException(serviceNotOff(labels[added] ?: AppNames.fallback(added))) }+ ).also {+ if (off == false) throw IllegalStateException(serviceNotOff(labels[added] ?: AppNames.fallback(added)))+ r.left?.let { throw IllegalStateException(notShown(labels[target.pkg] ?: AppNames.fallback(target.pkg), it)) }+ }}is HomeResult.Refused -> throw IllegalStateException(reasonText(r.reason))is HomeResult.Failed -> throw ActionFailed(r.output.ifEmpty { "the TV refused" }, r.details)@@ -699,7 +702,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {onProgress(ResetProgress(ResetPart.Home, 0, 1))try {val (moved, stuck) = resetHome(Actions(shell), h)- // Home moved but the service stayed on: Undo still needs the move.+ // Home moved but the service stayed on, or the hand-off to it didn't finish: Undo still needs the move.if (stuck != null) failed += ResetFailure(ResetPart.Home, ResetApp(h.from, h.fromLabel), stuck)moved} catch (e: CancellationException) {@@ -721,21 +724,25 @@ class AdbDeviceSource(context: Context) : DeviceSource {/*** Home back to [home]'s TV's own launcher, the added one's accessibility service off with it:- * it would keep sending Home there. Returns what Undo needs, and why the service stayed on if- * it did; throws when Home didn't move. On Try again Home may have moved already: then only- * the service is left to do, and the entry already holds the move.+ * it would keep sending Home there. Returns what Undo needs, and why the service stayed on or+ * the hand-off to the new home screen didn't finish, if so; throws when Home didn't move. On Try again Home+ * may have moved already: then only the service is left to do, and the entry already holds the move.*/private suspend fun resetHome(actions: Actions, home: ResetHome): Pair<Map<String, String?>, String?> {+ var left: String? = nullval moved: Map<String, String?> = if (actions.currentHome()?.substringBefore('/') == home.to) emptyMap()else when (val r = actions.homeBack(home.to)) {- is HomeResult.Switched -> listOfNotNull(ResetRecord.FROM to r.from, ResetRecord.TO to r.to).toMap()+ is HomeResult.Switched -> {+ left = r.left?.let { notShown(home.toLabel, it) }+ listOfNotNull(ResetRecord.FROM to r.from, ResetRecord.TO to r.to).toMap()+ }is HomeResult.Refused -> throw IllegalStateException(reasonText(r.reason))is HomeResult.Failed -> throw IllegalStateException(r.output.ifEmpty { "the TV refused" })}val service = home.from.takeIf { it in serviceLaunchers }?.let { actions.homeService(it) }?.takeIf { actions.serviceOn(it) }- ?: return moved to null+ ?: return moved to left// Recorded only once it's off: Undo turns back on what Reset turned off, nothing more.- return if (actions.setService(service, false)) moved + (ResetRecord.SERVICE to service) to null+ return if (actions.setService(service, false)) moved + (ResetRecord.SERVICE to service) to leftelse moved to serviceNotOff(home.fromLabel)}@@ -1126,6 +1133,7 @@ internal suspend fun switchHome().also {if (on == false) throw IllegalStateException(serviceNotOn(label(pkg)))if (off == false) throw IllegalStateException(serviceNotOff(label(was!!)))+ r.left?.let { throw IllegalStateException(notShown(label(pkg), it)) }}}is HomeResult.Refused -> throw IllegalStateException(reason(r.reason))@@ -1149,6 +1157,9 @@ internal const val RESET = "reset"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"+/** Home moved, but the old launcher didn't close or [app] didn't open: [why], from [HomeResult.Switched.left]. */+private fun notShown(app: String, why: String) = "$app is Home now, but $why"+private fun serviceNotOff(app: String) ="switched back, but $app's accessibility service is still on. Turn it off in the TV's Settings → Accessibility"diff --git a/app/src/test/java/app/tellyscope/HomeSwitchTest.kt b/app/src/test/java/app/tellyscope/HomeSwitchTest.ktindex b8cb04b..1b9a4ca 100644--- a/app/src/test/java/app/tellyscope/HomeSwitchTest.kt+++ b/app/src/test/java/app/tellyscope/HomeSwitchTest.kt@@ -35,6 +35,8 @@ private class LauncherTv(var home: String?) : AdbSession {val enabled = activities.keys.toMutableSet()val user = setOf(PROJECTIVY, FLAUNCHER)val services = mutableListOf<String>()+ /** False: `am start` can't open a home screen, as on a TV that refuses it. */+ var opens = trueoverride suspend fun shell(command: String): ShellResult {val pkg = command.substringAfter("--user 0 ").substringBefore(' ')@@ -50,6 +52,7 @@ private class LauncherTv(var home: String?) : AdbSession {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() }+ command.startsWith("am start") && !opens -> ok("Error: Activity not started\n")else -> ok("")}}@@ -132,4 +135,12 @@ class HomeSwitchTest {// Nothing to reverse: no launcher went off and no service came on.assertNull(entry.undo)}++ @Test fun aHomeThatDoesNotOpenStillSwitchesAndIsRecordedBeforeItSays() = runTest {+ val tv = LauncherTv(TV_HOME).apply { opens = false }+ val e = runCatching { switch(tv, FLAUNCHER) }.exceptionOrNull()+ assertTrue(e?.message.orEmpty(), e is IllegalStateException && e.message!!.startsWith("$FLAUNCHER is Home now, but it didn't open"))+ assertEquals(FLAUNCHER, tv.home)+ assertEquals(TV_HOME, book.entries("tv").single().packageName)+ }}