Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

Check PowerShell native command failures and recover failed Home handovers

am-tmac32e0696b17d9
diff --git a/launcher/build-and-install.ps1 b/launcher/build-and-install.ps1
index 6a094d027..df940f294 100644
--- a/launcher/build-and-install.ps1
+++ b/launcher/build-and-install.ps1
@@ -50,6 +50,7 @@ if (-not $StockLauncher) {
# Android's chooser: launchers tie and no default is set (a restore followed by a re-applied list
# ends here). Take the one known stock launcher among the HOME claimants, if there is exactly one.
$claimants = (& $py -I ..\tools\tv.py 'cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME') -join "`n"
+ if ($LASTEXITCODE -ne 0) { throw 'could not query Home claimants; stock launcher was left untouched' }
$found = @($knownStock | Where-Object { $claimants -match ([regex]::Escape($_) + '/') })
if ($found.Count -eq 1) { $StockLauncher = $found[0]; Write-Host "Home is Android's chooser; the stock launcher among the candidates is $StockLauncher." }
else { throw "Home is Android's launcher chooser and $($found.Count) known stock launchers claim Home: pick a default on the TV first, or run again with -StockLauncher <package to disable> or -StockLauncher none." }
@@ -64,7 +65,7 @@ $apk = 'app\build\outputs\apk\release\app-release.apk'
if ($LASTEXITCODE -ne 0) { throw 'APK upload failed' }
$out = & $py -I ..\tools\tv.py 'pm install -r /data/local/tmp/tvhome.apk; rm -f /data/local/tmp/tvhome.apk'
Write-Host $out
-if ("$out" -notmatch 'Success') { throw 'pm install failed; the stock launcher was left untouched' }
+if ($LASTEXITCODE -ne 0 -or "$out" -notmatch 'Success') { throw 'pm install failed; the stock launcher was left untouched' }
# Stop the instance Android restarted mid-update, which can come up non-occluding (see build-and-install.sh,
# #1101), and write back a key helper the force stop took off the list. Through stdin: Windows PowerShell 5.1
# drops the inner double quotes from a native argument.
@@ -73,28 +74,69 @@ if ("$out" -notmatch 'Success') { throw 'pm install failed; the stock launcher w
# Android 9 only accepts a component here; Android 10+ also takes a bare package name.
$out = & $py -I ..\tools\tv.py 'cmd package set-home-activity --user 0 com.gathin.tvhome/.MainActivity'
Write-Host $out
-if ("$out" -match 'Error') { throw 'could not set the new launcher as home; the stock launcher was left untouched' }
+if ($LASTEXITCODE -ne 0 -or "$out" -match 'Error') { throw 'could not set the new launcher as home; the stock launcher was left untouched' }
# Start the launcher on its own, before the stock Home is touched (see build-and-install.sh, #239):
# in the batch a failed start only prints an Error line and the stock launcher would be disabled anyway.
$start = (& $py -I ..\tools\tv.py 'am start -W -a android.intent.action.MAIN -c android.intent.category.HOME -n com.gathin.tvhome/.MainActivity') -join "`n"
Write-Host $start
-if ($start -notmatch 'Status: ok' -or $start -match '(?m)^Error') { throw "the new launcher did not start (see above); $StockLauncher was left enabled" }
+if ($LASTEXITCODE -ne 0 -or $start -notmatch 'Status: ok' -or $start -match '(?m)^Error') { throw "the new launcher did not start (see above); $StockLauncher was left enabled" }
@(
'pm grant com.gathin.tvhome android.permission.ACCESS_FINE_LOCATION 2>/dev/null; echo location-granted',
'cmd package compile -m speed -f com.gathin.tvhome',
$disableStock,
'cmd package set-home-activity --user 0 com.gathin.tvhome/.MainActivity'
) | & $py -I ..\tools\tv.py --batch
+# A failed batch is not fatal here: the stock launcher may already be disabled, so fall through to the
+# Home check, which rolls back when Home is not ours.
+if ($LASTEXITCODE -ne 0) { Write-Warning "tv.py --batch failed (exit code $LASTEXITCODE); checking where Home ended up" }
+
+$homeQuery = 'cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME'
+# Home's owner, or '' when the TV cannot be reached: $null.Trim() would throw past the rollback.
+function Get-HomeNow {
+ $ErrorActionPreference = 'Continue'
+ $line = @(& $py -I ..\tools\tv.py $homeQuery 2>$null) | Where-Object { $_ -match '\S' } | Select-Object -Last 1
+ if ($LASTEXITCODE -ne 0) { return '' }
+ "$line".Trim()
+}
+# Put the stock launcher back and check that it took. A TV whose new Home does not start can only be
+# rescued over ADB, so the commands also go into a local file (build-and-install.sh does the same).
+function Undo-Handover {
+ if ($StockLauncher -eq 'none') {
+ Write-Warning 'Home is not the new launcher, and no stock launcher was disabled; nothing to roll back.'
+ return $false
+ }
+ $ErrorActionPreference = 'Continue'
+ & $py -I ..\tools\tv.py "pm enable --user 0 $StockLauncher" 2>$null | Out-Null
+ $enableExit = $LASTEXITCODE
+ if ($enableExit -ne 0) { Write-Warning "stock launcher enable failed (exit code $enableExit); checking recovery" }
+ # set-home-activity needs pkg/activity on Android 9, so resolve the stock component on the TV.
+ & $py -I ..\tools\tv.py "cmd package set-home-activity --user 0 `$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME $StockLauncher | tail -n 1)" 2>$null | Out-Null
+ $setHomeExit = $LASTEXITCODE
+ if ($setHomeExit -ne 0) { Write-Warning "stock Home restore failed (exit code $setHomeExit); checking recovery" }
+ $back = Get-HomeNow
+ if ($enableExit -eq 0 -and $setHomeExit -eq 0 -and $back -like "$StockLauncher/*") { Write-Warning "$StockLauncher owns Home again."; return $true }
+ $homeDir = if ($env:USERPROFILE) { $env:USERPROFILE } elseif ($env:HOME) { $env:HOME } else { (Get-Location).Path }
+ $rec = Join-Path $homeDir ("cleanyourtv-handover-" + ($TvHost -replace '[^A-Za-z0-9._-]', '_') + '.txt')
+ $lines = @(
+ "# cleanyourtv: the launcher handover on $TvHost did not finish. From the repo root:",
+ "tools\venv\Scripts\python.exe tools\tv.py 'pm enable --user 0 $StockLauncher' # with `$env:TV_HOST='$TvHost'",
+ "tools\venv\Scripts\python.exe tools\tv.py 'cmd package set-home-activity --user 0 `$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME $StockLauncher | tail -n 1)'",
+ "# then check: tools\venv\Scripts\python.exe tools\tv.py '$homeQuery'"
+ )
+ try { $lines | Out-File -Encoding ascii $rec } catch { $rec = '' }
+ Write-Warning "recovery is incomplete; Home still resolves to '$(if ($back) { $back } else { 'nothing' })'."
+ if ($rec) { Write-Warning "The commands that finish it are in $rec; the TV still needs ADB for them." }
+ else { Write-Warning "Re-run once the TV answers: pm enable --user 0 $StockLauncher, then set its Home activity." }
+ return $false
+}
# Order matters, see build-and-install.sh: start the new launcher, disable the stock one, set the
# preference last, then check where Home ended up and put the stock launcher back if it is not ours.
-$homeNow = (& $py -I ..\tools\tv.py 'cmd package resolve-activity --brief -c android.intent.category.HOME -a android.intent.action.MAIN' | Select-Object -Last 1).Trim()
+$homeNow = Get-HomeNow
if ($homeNow -notlike 'com.gathin.tvhome/*') {
- if ($StockLauncher -ne 'none') {
- & $py -I ..\tools\tv.py "pm enable --user 0 $StockLauncher" | Out-Null
- # set-home-activity needs pkg/activity on Android 9, so resolve the stock component on the TV.
- & $py -I ..\tools\tv.py "cmd package set-home-activity --user 0 `$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME $StockLauncher | tail -n 1)" | Out-Null
- }
- throw "Home resolves to '$homeNow', not to the new launcher; $StockLauncher was re-enabled. On Google TV this usually means com.google.android.tungsten.setupwraith also claims Home: add it to your debloat list (see README, Troubleshooting), apply it, then run this script again."
+ $reason = if ($homeNow) { "Home resolves to '$homeNow', not to the new launcher" } else { 'the TV stopped answering while Home was being switched, so the outcome is unknown' }
+ $restored = Undo-Handover
+ $hint = if ($homeNow) { ' On Google TV this usually means com.google.android.tungsten.setupwraith also claims Home: add it to your debloat list (see README, Troubleshooting), apply it, then run this script again.' } else { '' }
+ throw "$reason; $(if ($restored) { "$StockLauncher was re-enabled." } else { 'recovery is incomplete (see above).' })$hint"
}
Write-Host "Home now resolves to $homeNow"
# Optional accessibility services, appended to enabled_accessibility_services without dropping others.
@@ -105,6 +147,7 @@ function Enable-Service([string]$Name) {
# TCL names the op AUTO_START or APP_AUTO_START; without write-settings the grant is lost at the next reboot.
('cmd appops set com.gathin.tvhome AUTO_START allow 2>/dev/null; cmd appops set com.gathin.tvhome APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; s=$(settings get secure enabled_accessibility_services); case "$s" in *' + $Name + '*) settings put secure enabled_accessibility_services ""; settings put secure accessibility_enabled 0; sleep 1; settings put secure enabled_accessibility_services "$s" ;; null|"") settings put secure enabled_accessibility_services ' + $svc + ' ;; *) settings put secure enabled_accessibility_services "$s:' + $svc + '" ;; esac; settings put secure accessibility_enabled 1; echo ' + $Name + ' enabled') |
& $py -I ..\tools\tv.py --batch
+ if ($LASTEXITCODE -ne 0) { throw "could not enable $Name (tv.py exit code $LASTEXITCODE); Home is already the new launcher" }
}
if ($InputKeyService) { Enable-Service 'InputKeyService' }
if ($HomeKeyService) { Enable-Service 'HomeKeyService' }
diff --git a/tests/test_theme_push_ownership.py b/tests/test_theme_push_ownership.py
index 0a6c33e83..2637d0921 100644
--- a/tests/test_theme_push_ownership.py
+++ b/tests/test_theme_push_ownership.py
@@ -323,7 +323,7 @@ class ThemePushTest(unittest.TestCase):
def test_the_windows_script_clears_the_collection_on_reset(self):
"""theme.ps1 cannot run here, so the -Reset branch is pinned as text against theme.sh."""
script = (TOOLS / "theme.ps1").read_text(encoding="utf-8")
- reset = next(line for line in script.splitlines() if line.strip().startswith("& $py -I tv.py \"mkdir -p $dir"))
+ reset = next(line for line in script.splitlines() if line.strip().startswith("Invoke-Tv tv.py \"mkdir -p $dir"))
self.assertIn("$(Drop 'wallpapers/captions.txt')", reset)
self.assertIn("$clearWallpapers", reset, "one shared clear, as in theme.sh")
clear = next(line for line in script.splitlines() if line.startswith("$clearWallpapers = "))
diff --git a/tools/disable.ps1 b/tools/disable.ps1
index 2b3457f5d..d7d1955aa 100644
--- a/tools/disable.ps1
+++ b/tools/disable.ps1
@@ -205,7 +205,10 @@ if ($LASTEXITCODE -ne 0) { throw 'no recovery record was written, so nothing was
$cmds = @($pkgs | ForEach-Object { "pm disable-user --user 0 $_" }) + 'pm list packages -d'
$cmds | & $py -I (Join-Path $repo 'tools\tv.py') --batch
+$batchExit = $LASTEXITCODE
if ($adbSecure -eq '0') {
Write-Warning "This TV reports ro.adb.secure=0, so network ADB on port 5555 accepts any device on your network without the `"Allow`" prompt. When you are done, turn USB debugging and Network/ADB debugging off on the TV and reboot it (README: `"Isn't ADB access a security hole?`")."
}
+if ($batchExit -ne 0) { throw "tv.py --batch failed (exit code $batchExit): the list may be only partly applied; run it again once the TV answers" }
+
diff --git a/tools/restore.ps1 b/tools/restore.ps1
index 4ec964f3d..4ac7b7dac 100644
--- a/tools/restore.ps1
+++ b/tools/restore.ps1
@@ -24,3 +24,4 @@ $env:TV_HOST = $TvHost
$cmds = & $py -I (Join-Path $repo 'tools\recovery.py') --commands $List $Stock
if ($LASTEXITCODE -ne 0) { throw 'no restore plan was built, the TV was not changed' }
$cmds | & $py -I (Join-Path $repo 'tools\tv.py') --batch
+if ($LASTEXITCODE -ne 0) { throw "tv.py --batch failed (exit code $LASTEXITCODE): the restore may be only partly applied; run it again once the TV answers" }
diff --git a/tools/theme.ps1 b/tools/theme.ps1
index 3022679cf..e32900567 100644
--- a/tools/theme.ps1
+++ b/tools/theme.ps1
@@ -18,6 +18,13 @@ Set-Location $PSScriptRoot
$py = 'venv\Scripts\python.exe'
if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
$pkg = 'com.gathin.tvhome'
+# Runs tools\tv.py or b64push.py and stops on a non-zero exit: 'Stop' only covers cmdlets, so a failed
+# native call would otherwise fall through to "Theme ... is on the TV".
+function Invoke-Tv {
+ $out = & $py -I @args
+ if ($LASTEXITCODE -ne 0) { throw "$($args[0]) $($args[1]) failed (exit code $LASTEXITCODE); the theme was not fully applied" }
+ $out
+}
$dir = "/sdcard/Android/data/$pkg/files"
$revision = [guid]::NewGuid().ToString('N')
# Restart Home so it rereads the theme. Android drops a force-stopped app's accessibility services from the
@@ -56,7 +63,7 @@ function Drop($name) { "rm -f $dir/$name 2>/dev/null; content delete --uri $uri/
$clearWallpapers = "mkdir -p $dir/wallpapers 2>/dev/null; rm -f $dir/wallpapers/*.jpg $dir/wallpapers/*.jpeg $dir/wallpapers/*.png $dir/wallpapers/*.webp $dir/wallpapers/*.JPG $dir/wallpapers/*.JPEG $dir/wallpapers/*.PNG $dir/wallpapers/*.WEBP 2>/dev/null; content delete --uri $uri/wallpapers 2>/dev/null"
if ($Reset) {
- & $py -I tv.py "mkdir -p $dir 2>/dev/null; $(Drop 'config.json'); $(Drop 'wallpaper.jpg'); $(Drop 'wallpapers/captions.txt'); $clearWallpapers; printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision'); $restart; echo reset"
+ Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; $(Drop 'config.json'); $(Drop 'wallpaper.jpg'); $(Drop 'wallpapers/captions.txt'); $clearWallpapers; printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision'); $restart; echo reset"
exit 0
}
if (-not $Theme) { throw 'usage: theme.ps1 <theme folder> | -Reset' }
@@ -64,28 +71,29 @@ $config = Join-Path $Theme 'config.json'
if (-not (Test-Path $config)) { throw "no config.json in $Theme" }
try { Get-Content $config -Raw | ConvertFrom-Json | Out-Null } catch { throw "$config is not valid JSON" }
-& $py -I tv.py "mkdir -p $dir 2>/dev/null" | Out-Null
-& $py -I tv.py --push $config "$tmp-config.json" | Out-Null
-& $py -I tv.py (Put 'config.json')
+# Tolerated, as in theme.sh: a TV that locks Android/data still takes the files through ThemeProvider.
+Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; true" | Out-Null
+Invoke-Tv tv.py --push $config "$tmp-config.json" | Out-Null
+Invoke-Tv tv.py (Put 'config.json')
$wall = Join-Path $Theme 'wallpaper.jpg'
-if (Test-Path $wall) { & $py -I b64push.py $wall "$tmp-wallpaper.jpg"; & $py -I tv.py (Put 'wallpaper.jpg') } else { & $py -I tv.py (Drop 'wallpaper.jpg') | Out-Null }
-& $py -I tv.py $clearWallpapers | Out-Null
+if (Test-Path $wall) { Invoke-Tv b64push.py $wall "$tmp-wallpaper.jpg"; Invoke-Tv tv.py (Put 'wallpaper.jpg') } else { Invoke-Tv tv.py (Drop 'wallpaper.jpg') | Out-Null }
+Invoke-Tv tv.py $clearWallpapers | Out-Null
$wallpapers = Join-Path $Theme 'wallpapers'
if (Test-Path $wallpapers -PathType Container) {
Get-ChildItem $wallpapers -File | Where-Object { $_.Extension -match '^\.(jpg|jpeg|png|webp)$' } | ForEach-Object {
if ($_.Name -notmatch '^[A-Za-z0-9_.-]+$') { throw "unsupported wallpaper filename: $($_.Name)" }
- & $py -I b64push.py $_.FullName (Stage "wallpapers/$($_.Name)")
- & $py -I tv.py (Put "wallpapers/$($_.Name)") | Out-Null
+ Invoke-Tv b64push.py $_.FullName (Stage "wallpapers/$($_.Name)")
+ Invoke-Tv tv.py (Put "wallpapers/$($_.Name)") | Out-Null
}
}
# The collection's names (wallpaper_captions); a theme without them leaves no stale names behind.
$captions = Join-Path $Theme 'wallpapers\captions.txt'
if (Test-Path $captions -PathType Leaf) {
- & $py -I b64push.py $captions (Stage 'wallpapers/captions.txt')
- & $py -I tv.py (Put 'wallpapers/captions.txt') | Out-Null
+ Invoke-Tv b64push.py $captions (Stage 'wallpapers/captions.txt')
+ Invoke-Tv tv.py (Put 'wallpapers/captions.txt') | Out-Null
} else {
- & $py -I tv.py (Drop 'wallpapers/captions.txt') | Out-Null
+ Invoke-Tv tv.py (Drop 'wallpapers/captions.txt') | Out-Null
}
-& $py -I tv.py "printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision')" | Out-Null
-& $py -I tv.py "$restart; echo applied"
+Invoke-Tv tv.py "printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision')" | Out-Null
+Invoke-Tv tv.py "$restart; echo applied"
Write-Host "Theme $(Split-Path $Theme -Leaf) is on the TV. Undo with: tools\theme.ps1 -TvHost $TvHost -Reset"