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.
Fire OS: install Projectivy from its GitHub release
jesse-agent-232d9a8ba16eb74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2d3f68..158acfd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,8 @@ until this file has a section for its version.- **Fixed:** A Remote button's tap ripple stays inside the button. [#228](../../pull/228)- **Improved:** The Remote buttons list has more room at its sides. [#228](../../pull/228)- **Improved:** While you type on the Remote, back, home and menu shrink to give the D-pad room. [#229](../../pull/229)+- **New:** On Fire TV, Install a home screen downloads and installs Projectivy for you. [#232](../../pull/232)+ - It comes from Projectivy's GitHub releases, and is checked against its developer's signature first.## 0.13.0 — 2026-10-29diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0e7bb6c..8166529 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -32,7 +32,7 @@ You don't have to trust ours. Fork tellyscope-devices, edit the lists in your foThese lists live in tellyscope-devices too, next to the debloat lists, and the app downloads them from the same source: change one there with a pull request and it reaches people without an app release. A fork's source supplies them as well. File formats and checks are in that repo's README.-- `lists/launchers.json`: the third-party launchers Tellyscope knows. One with an `"about"` line is offered in **Install a home screen**, in the file's order.+- `lists/launchers.json`: the third-party launchers Tellyscope knows. One with an `"about"` line is offered in **Install a home screen**, in the file's order. On Fire OS, which has no Play Store, only Projectivy is offered, while it's on the list: Tellyscope downloads it from its developer's GitHub releases and installs only an APK signed with the certificate pinned in [`LauncherDownload.kt`](app/src/main/java/app/tellyscope/data/LauncherDownload.kt).- `lists/labels.json`: names shown for common TV apps when the TV can't tell us.- `lists/streaming.json` and `logos/`: the streaming services the Remote can have a button for, with their logos.diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex aa28f3e..75a8d8e 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -42,6 +42,7 @@ import app.tellyscope.adb.AppFactsimport app.tellyscope.adb.Connectorimport app.tellyscope.adb.StatsProfileimport app.tellyscope.data.AdbDeviceSource+import app.tellyscope.data.AndroidLauncherDownloadimport app.tellyscope.data.AndroidPhoneStorageimport app.tellyscope.data.Deviceimport app.tellyscope.data.DeviceState@@ -126,6 +127,7 @@ class MainActivity : ComponentActivity() {gates = FoldBook(File(filesDir, "gates.properties")),historySeen = SeenBook(File(filesDir, "history-seen.properties")),appFacts = AppFacts(installedVersion(), "${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE}"),+ launcherDownload = if (scenario != null) null else AndroidLauncherDownload(applicationContext),)}},@@ -339,6 +341,9 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {makeHome = vm::makeHome,open = vm::openLauncher,later = vm::launcherLater,+ fireCheck = vm::checkProjectivy,+ fireInstall = vm::installProjectivy,+ fireDismiss = vm::dismissProjectivy,),snackbar = snackbar,)diff --git a/app/src/main/java/app/tellyscope/data/DeviceKind.kt b/app/src/main/java/app/tellyscope/data/DeviceKind.ktindex 6ee00fc..0242381 100644--- a/app/src/main/java/app/tellyscope/data/DeviceKind.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceKind.kt@@ -17,6 +17,12 @@ private val STICK = Regex("chromecast|stick|streamer|shield", RegexOption.IGNORE/** Projector makers or "projector" in a name, then Amazon, then other sticks and boxes; anything else is a TV. */fun deviceKind(d: Device): DeviceKind = kindOf(listOfNotNull(d.manufacturer, d.hit.maker), listOfNotNull(d.model, d.hit.hostname))+/** Amazon's launcher, on every Fire OS device: Fire TV Edition TVs too, whose maker may not say Amazon. */+const val FIRE_TV_LAUNCHER = "com.amazon.tv.launcher"++/** Fire OS: a Fire TV by name, or any TV with Amazon's launcher. No Play Store there. */+fun isFireOs(d: Device, apps: List<AppInfo>) = deviceKind(d) == DeviceKind.FireTv || apps.any { it.packageName == FIRE_TV_LAUNCHER }+/** The same guess for a debloat list, from its maker (see [listMakers]) and model name. */fun listKind(e: ListEntry, maker: String): DeviceKind = kindOf(listOf(maker), listOf(e.name))diff --git a/app/src/main/java/app/tellyscope/data/LauncherDownload.kt b/app/src/main/java/app/tellyscope/data/LauncherDownload.ktnew file mode 100644index 0000000..33285d1--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/LauncherDownload.kt@@ -0,0 +1,138 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import androidx.core.content.pm.PackageInfoCompat+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.Progress+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ensureActive+import kotlinx.coroutines.withContext+import org.json.JSONObject+import java.io.File+import java.io.IOException+import java.net.HttpURLConnection+import java.net.URL+import java.security.MessageDigest++const val PROJECTIVY = "com.spocky.projengmenu"++/** Where Projectivy's developer publishes its APKs. Not open source: the repo holds only releases and themes. */+const val PROJECTIVY_RELEASES = "https://github.com/spocky/miproja1/releases"+private const val PROJECTIVY_LATEST = "https://api.github.com/repos/spocky/miproja1/releases/latest"++/**+ * SHA-256 of the certificate Projectivy's GitHub APKs are signed with (APK Signature Scheme v2),+ * the same on 4.70 and 4.72. A download signed with anything else is never sent to the TV.+ */+val PROJECTIVY_SIGNERS = setOf("f6697bf4082ee97511e4de07863193884a015b7ab5860430321bda1042b0aadd")++/** Projectivy is about 11 MB; anything far past that isn't it. */+private const val MAX_APK_BYTES = 64L shl 20++/** Projectivy's latest release: [page] is shown before anything downloads, [apk] is its one APK. */+data class LauncherRelease(val version: String, val page: String, val apk: String, val size: Long)++/**+ * The latest release from GitHub's API, or null unless it is a full release on Projectivy's own+ * repo with exactly one APK, served from that release.+ */+fun parseRelease(json: String): LauncherRelease? = runCatching {+ val r = JSONObject(json)+ val tag = r.getString("tag_name")+ val assets = r.getJSONArray("assets")+ val apk = (0 until assets.length()).map(assets::getJSONObject).singleOrNull { it.getString("name").endsWith(".apk") }+ val url = apk?.getString("browser_download_url")+ val size = apk?.getLong("size") ?: 0L+ LauncherRelease(tag, r.getString("html_url"), url.orEmpty(), size).takeIf {+ !r.optBoolean("draft") && !r.optBoolean("prerelease") &&+ it.page == "$PROJECTIVY_RELEASES/tag/$tag" &&+ it.apk.startsWith("$PROJECTIVY_RELEASES/download/$tag/") &&+ size in 1..MAX_APK_BYTES+ }+}.getOrNull()++/** Projectivy, signed only by its developer: [signers] are the SHA-256s of the APK's certificates. */+fun isProjectivy(packageName: String, signers: Set<String>) =+ packageName == PROJECTIVY && signers.isNotEmpty() && PROJECTIVY_SIGNERS.containsAll(signers)++/** The download isn't Projectivy, or isn't signed by its developer. */+class NotProjectivy : IOException("not Projectivy")++/** Fire OS's way to Projectivy: there's no Play Store, so Tellyscope fetches it from its developer. Faked in tests. */+interface LauncherDownload {+ /** Throws on no network or a release that doesn't parse. */+ suspend fun latest(): LauncherRelease++ /** Downloads [release]'s APK and checks it. Throws [NotProjectivy], or IOException on a failed download. */+ suspend fun fetch(release: LauncherRelease, onProgress: (Progress) -> Unit): PickedApp+}++class AndroidLauncherDownload(context: Context) : LauncherDownload {+ private val ctx = context.applicationContext+ private val dir get() = File(ctx.cacheDir, "launcher")++ override suspend fun latest(): LauncherRelease =+ parseRelease(download(PROJECTIVY_LATEST).decodeToString()) ?: throw IOException("no Projectivy release")++ override suspend fun fetch(release: LauncherRelease, onProgress: (Progress) -> Unit): PickedApp = withContext(Dispatchers.IO) {+ dir.deleteRecursively()+ dir.mkdirs()+ val file = File(dir, "projectivy.apk")+ val c = URL(release.apk).openConnection() as HttpURLConnection+ c.connectTimeout = 10_000+ c.readTimeout = 30_000+ try {+ if (c.responseCode != 200) throw IOException("HTTP ${c.responseCode}")+ c.inputStream.use { input ->+ file.outputStream().use { out ->+ val buf = ByteArray(64 * 1024)+ var done = 0L+ while (true) {+ ensureActive()+ val n = input.read(buf).takeIf { it >= 0 } ?: break+ done += n+ if (done > release.size) throw IOException("larger than the release says")+ out.write(buf, 0, n)+ onProgress(Progress(done, release.size))+ }+ if (done != release.size) throw IOException("download cut short")+ }+ }+ } finally {+ c.disconnect()+ }+ read(file)+ }++ /** The package manager checks the APK's signature while it reads the certificates. */+ private fun read(file: File): PickedApp {+ val pm = ctx.packageManager+ val pkg = if (Build.VERSION.SDK_INT >= 28) {+ @Suppress("DEPRECATION") // the flags overload is API 33++ pm.getPackageArchiveInfo(file.path, PackageManager.GET_SIGNING_CERTIFICATES)+ } else {+ @Suppress("DEPRECATION")+ pm.getPackageArchiveInfo(file.path, PackageManager.GET_SIGNATURES)+ } ?: throw NotProjectivy()+ val certs = if (Build.VERSION.SDK_INT >= 28) {+ // A rotated key lists its past certificates first; the current one signs.+ pkg.signingInfo?.let { if (it.hasMultipleSigners()) it.apkContentsSigners.toList() else it.signingCertificateHistory.takeLast(1) }+ } else {+ @Suppress("DEPRECATION")+ pkg.signatures?.toList()+ }+ val signers = certs.orEmpty().map { sha256(it.toByteArray()) }.toSet()+ if (!isProjectivy(pkg.packageName, signers)) throw NotProjectivy()+ return PickedApp(+ files = listOf(file),+ info = ApkInfo(pkg.packageName, PackageInfoCompat.getLongVersionCode(pkg), pkg.versionName),+ label = "Projectivy Launcher",+ )+ }+}++private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex 7e9400f..4675efa 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -98,6 +98,7 @@ object Copy {const val MAKE_HOME = "Make Home"const val GET_LAUNCHER = "Get another launcher"const val GET_LAUNCHER_TEXT = "Install one from the Play Store, like Projectivy or FLauncher. Switch back any time."+ const val GET_PROJECTIVY_TEXT = "Install Projectivy. Switch back any time."/** The Apps tab's launcher rows: switching lives in the card, this opens it. */const val HOME_SETTINGS = "Home screen settings"@@ -168,10 +169,13 @@ object Copy {/** 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."+ /** [fire]: Fire OS, where there's no Play Store and Tellyscope installs it. */+ fun betterHomeText(current: String?, fire: Boolean = false) =+ "Swap ${current ?: "the TV's home screen"} for a launcher without ads" ++ if (fire) "; switch back any time." else ". Free on the Play Store; switch back any time."const val CHOOSE_ONE = "Choose one"+ const val INSTALL_ONE = "Install it"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 NO_LAUNCHER_LIST = "Couldn't load the list of home screens. Check the phone's internet and try again."@@ -221,6 +225,29 @@ object Copy {/** The Store closed without an install: back on the picker, still chosen. */fun wasntInstalled(name: String) = "$name wasn't installed"+ /** Install Projectivy on Fire OS: Tellyscope downloads it from its developer's GitHub and installs it over adb. */+ const val INSTALL_PROJECTIVY = "Install Projectivy"+ const val FIRE_INSTALL_TEXT = "A home screen without ads. Tellyscope installs it on the TV for you; there's nothing to do on the TV."++ fun installProjectivyOn(tv: String) = "Install Projectivy on $tv?"++ fun downloadsFrom(name: String, version: String, size: Long) = "Tellyscope downloads $name $version (${bytes(size)}) from:"++ const val SIGNED_CHECK =+ "and checks it's signed by Projectivy's developer before installing it on the TV. Tellyscope isn't affiliated with Projectivy."+ const val DOWNLOAD_AND_INSTALL = "Download and install"++ fun downloading(percent: Int) = "Downloading · $percent%"++ fun installingOn(tv: String) = "Installing on $tv…"++ const val NOT_PROJECTIVY = "That download isn't Projectivy"+ const val NOT_PROJECTIVY_TEXT =+ "The file from GitHub didn't match Projectivy's package name or its developer's signature, so Tellyscope installed nothing on the TV."+ const val NO_DOWNLOAD = "Couldn't download Projectivy"+ const val NO_DOWNLOAD_TEXT = "Check the phone's internet, then try again. Or download it yourself from Projectivy's release page."+ const val OPEN_DOWNLOAD_PAGE = "Open the download page"+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."diff --git a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt b/app/src/main/java/app/tellyscope/ui/DeviceTabs.ktindex 3a9b75c..e41ae26 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt@@ -156,6 +156,7 @@ fun DeviceTabsScreen() {val device = state.selected ?: returnval ui = state.device+ val fire = fireInstall(device, ui.apps)var tab by rememberSaveable { mutableStateOf(startTab) }LaunchedEffect(tab) { onTab(tab) }var searching by rememberSaveable { mutableStateOf(false) }@@ -192,7 +193,7 @@ fun DeviceTabsScreen(val toApps = { gate = false; tab = TvTab.Apps }DebloatGate(// Only where the picker can install one: the Play Store is on and no launcher was added yet.- launcher = offerChoose(ui.apps),+ launcher = offerChoose(ui.apps, fire),onChoose = { gate = false; actions.installLauncher() },onApps = toApps,onNeverAgain = { actions.debloatGateOff(); toApps() },@@ -360,8 +361,8 @@ 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)+ if (!offline && offerLauncher(ui.apps, ui.launcherCardHidden, fire)) item(key = "launcherCard") {+ LauncherCard(ui.apps.firstOrNull { it.home }?.label, onNotNow = actions.hideLauncherCard, onChoose = actions.installLauncher, fire = fire)}if (split != null) {if (split.apps.isEmpty() && split.system.isEmpty()) item {@@ -404,7 +405,7 @@ fun DeviceTabsScreen(TvTab.Tweaks -> {if (offline) item { Muted("Connect to the TV to change its settings.") }else {- if (homeLaunchers(ui.apps).isNotEmpty()) item { Panel(Copy.HOME_SCREEN) { HomeScreenBlock(ui, actions) } }+ if (homeLaunchers(ui.apps).isNotEmpty()) item { Panel(Copy.HOME_SCREEN) { HomeScreenBlock(ui, actions, fire) } }item { Panel(Copy.TWEAKS) { TweaksBlock(ui, actions) } }}}diff --git a/app/src/main/java/app/tellyscope/ui/HomeScreenCard.kt b/app/src/main/java/app/tellyscope/ui/HomeScreenCard.ktindex f4fbdb2..5457789 100644--- a/app/src/main/java/app/tellyscope/ui/HomeScreenCard.kt+++ b/app/src/main/java/app/tellyscope/ui/HomeScreenCard.kt@@ -62,9 +62,10 @@ internal fun homeMove(app: AppInfo, current: AppInfo?): Action? = when {/*** The Home screen card at the top of Tweaks: every launcher on the TV, which one Home opens, and* the one place to change it. Make Home asks first; only the TV's own launcher is ever turned off.+ * [fire]: Fire OS ([fireInstall]), where Get another launcher installs Projectivy without a Play Store.*/@Composable-fun HomeScreenBlock(ui: DeviceUi, actions: DeviceActions) {+fun HomeScreenBlock(ui: DeviceUi, actions: DeviceActions, fire: Boolean = false) {val launchers = homeLaunchers(ui.apps)val current = launchers.firstOrNull { it.home }val locked = ui.busy != null@@ -85,10 +86,10 @@ fun HomeScreenBlock(ui: DeviceUi, actions: DeviceActions) {}}// Only before a launcher was added: after that, the rows above are the way to switch.- if (launchers.none { !it.system } && hasPlayStore(ui.apps)) {+ if (launchers.none { !it.system } && (hasPlayStore(ui.apps) || fire)) {Column(Modifier.fillMaxWidth().padding(top = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {Text(Copy.GET_LAUNCHER, style = MaterialTheme.typography.bodyLarge)- Text(Copy.GET_LAUNCHER_TEXT, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(if (fire) Copy.GET_PROJECTIVY_TEXT else Copy.GET_LAUNCHER_TEXT, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)FilledTonalButton(onClick = actions.installLauncher, enabled = !locked) { Text(Copy.GET_LAUNCHER) }}}diff --git a/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.ktindex 8288c0b..eb40ccd 100644--- a/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt+++ b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt@@ -6,6 +6,7 @@ package app.tellyscope.uiimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background+import androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -29,13 +30,16 @@ import androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Checkimport androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.Warningimport androidx.compose.material.icons.outlined.Home+import androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.ExperimentalMaterial3ExpressiveApiimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton+import androidx.compose.material3.LinearWavyProgressIndicatorimport androidx.compose.material3.LoadingIndicatorimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.RadioButton@@ -59,18 +63,24 @@ import androidx.compose.ui.graphics.PathFillTypeimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.graphics.vector.PathParser+import androidx.compose.ui.platform.LocalUriHandlerimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.text.AnnotatedStringimport androidx.compose.ui.text.SpanStyleimport androidx.compose.ui.text.buildAnnotatedStringimport androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextDecorationimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.dpimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfoimport app.tellyscope.data.Device+import app.tellyscope.data.PROJECTIVY+import app.tellyscope.data.PROJECTIVY_RELEASES+import app.tellyscope.data.isFireOs+import app.tellyscope.ui.theme.SmallNumber-/** The Play Store's package: a TV without it (Fire TV) gets no card and no Tweaks row. */+/** The Play Store's package: a TV without it gets no card and no Tweaks row, unless it runs Fire OS ([fireInstall]). */const val PLAY_STORE = "com.android.vending"/**@@ -83,10 +93,18 @@ internal fun hasPlayStore(apps: List<AppInfo>) = apps.any { it.packageName == PL/** A launcher someone added is on the TV, Home or not: one on `launchers.json`, or one they installed that answers Home. */internal fun hasAddedLauncher(apps: List<AppInfo>) = apps.any { it.listedLauncher || (it.removable && (it.home || it.answersHome)) }-internal fun offerChoose(apps: List<AppInfo>) = hasPlayStore(apps) && !hasAddedLauncher(apps)+/**+ * Fire OS has no Play Store, so Install a home screen offers only Projectivy there, which Tellyscope downloads+ * from its developer and installs itself. Only while the launcher list ([recommended]) has Projectivy; without it, nothing is offered.+ */+internal fun fireInstall(device: Device, apps: List<AppInfo>, recommended: List<Recommended> = RECOMMENDED) =+ isFireOs(device, apps) && recommended.any { it.pkg == PROJECTIVY }++/** [fire]: [fireInstall] holds, so the Play Store isn't needed. */+internal fun offerChoose(apps: List<AppInfo>, fire: Boolean = false) = (hasPlayStore(apps) || fire) && !hasAddedLauncher(apps)-internal fun offerLauncher(apps: List<AppInfo>, hidden: Boolean) =- !hidden && offerChoose(apps) && apps.none { it.homeInstead != null || it.homeBack != null }+internal fun offerLauncher(apps: List<AppInfo>, hidden: Boolean, fire: Boolean = false) =+ !hidden && offerChoose(apps, fire) && apps.none { it.homeInstead != null || it.homeBack != null }/** [pkg] on the TV and on, so the picker offers Make Home or Open on it rather than the Store. */internal fun installedLauncher(apps: List<AppInfo>, pkg: String) = apps.firstOrNull { it.packageName == pkg && it.enabled }@@ -108,12 +126,21 @@ data class LauncherActions(/** Open in the picker: shows that launcher on the TV. */val open: (String) -> Unit = {},val later: () -> Unit = {},+ /** Fire OS: Install Projectivy, which reads the latest release for the confirm dialog. Try again does the same. */+ val fireCheck: () -> Unit = {},+ /** Fire OS: Download and install in the confirm dialog. */+ val fireInstall: () -> Unit = {},+ /** Fire OS: Cancel, Close or OK in a dialog. */+ val fireDismiss: () -> Unit = {},)-/** The Apps tab's card: a launcher without ads, from the Play Store. Not now puts it away on this TV. */+/** The Apps tab's card: a launcher without ads, from the Play Store ([fire]: Projectivy, installed by Tellyscope). 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)+fun LauncherCard(current: String?, onNotNow: () -> Unit, onChoose: () -> Unit, fire: Boolean = false) {+ HomeNoteCard(+ Icons.Outlined.Home, Copy.BETTER_HOME, Copy.betterHomeText(current, fire), Copy.NOT_NOW, onNotNow,+ if (fire) Copy.INSTALL_ONE else Copy.CHOOSE_ONE, onChoose,+ )}/**@@ -121,6 +148,7 @@ fun LauncherCard(current: String?, onNotNow: () -> Unit, onChoose: () -> Unit) {* Play Store, then the switch, which ends in the same yes for the accessibility service as Set as* default. A launcher already on the TV skips the Store: the picker offers Make Home or Open on it.* A TV that didn't open the Store says so; a Store closed without installing goes back to the picker.+ * On Fire OS ([LauncherFlow.fire]) the picker is Projectivy alone, which Tellyscope downloads and installs.*/@OptIn(ExperimentalMaterial3Api::class)@Composable@@ -138,6 +166,7 @@ fun LauncherScreen(val app = apps.firstOrNull { it.packageName == if (picking) chosen else flow.pkg }val current = app?.let { homeLabel(apps, it) }val switch = { service: Boolean -> if (picking) actions.makeHome(chosen, service) else actions.switch(service) }+ flow.fire?.let { FireDialog(it, device, actions) }if (askService && app != null && current != null) {ServiceDialog(app.label, current,@@ -149,7 +178,15 @@ fun LauncherScreen(snackbarHost = { SnackbarHost(snackbar) },topBar = {TopAppBar(- title = { Text(if (flow.step == LauncherFlow.Step.Pick) Copy.CHOOSE_HOME else Copy.INSTALL_HOME) },+ title = {+ Text(+ when {+ flow.fire != null -> Copy.INSTALL_PROJECTIVY+ flow.step == LauncherFlow.Step.Pick -> Copy.CHOOSE_HOME+ else -> Copy.INSTALL_HOME+ },+ )+ },navigationIcon = { IconButton(onClick = actions.close) { Icon(Icons.Default.Close, contentDescription = "Close") } },)},@@ -160,7 +197,9 @@ fun LauncherScreen(verticalAlignment = Alignment.CenterVertically,) {when (flow.step) {- LauncherFlow.Step.Pick -> {+ LauncherFlow.Step.Pick -> if (flow.fire != null) {+ IconButtonText(LauncherIcons.Download, Copy.INSTALL_PROJECTIVY, enabled = flow.fire.step == null) { actions.fireCheck() }+ } else {val have = installedLauncher(apps, chosen)when {have == null -> IconButtonText(OpenInNew, Copy.OPEN_IN_STORE) { actions.install(chosen) }@@ -201,7 +240,7 @@ fun LauncherScreen(}val c = MaterialTheme.colorSchemewhen (flow.step) {- LauncherFlow.Step.Pick -> Picker(chosen, apps) { chosen = it }+ LauncherFlow.Step.Pick -> if (flow.fire != null) FirePick() else Picker(chosen, apps) { chosen = it }LauncherFlow.Step.Waiting -> {Hero(LauncherIcons.Download, c.secondaryContainer, c.onSecondaryContainer)Headed(Copy.INSTALL_IT, bold(Copy.installItText(label), label, "Install"))@@ -242,8 +281,8 @@ fun LauncherScreen(}@Composable-private fun IconButtonText(icon: ImageVector, text: String, onClick: () -> Unit) {- Button(onClick = onClick, contentPadding = ButtonDefaults.ButtonWithIconContentPadding) {+private fun IconButtonText(icon: ImageVector, text: String, enabled: Boolean = true, onClick: () -> Unit) {+ Button(onClick = onClick, enabled = enabled, contentPadding = ButtonDefaults.ButtonWithIconContentPadding) {Icon(icon, contentDescription = null, Modifier.size(18.dp))Spacer(Modifier.width(8.dp))Text(text)@@ -287,6 +326,112 @@ private fun Picker(chosen: String, apps: List<AppInfo>, onChoose: (String) -> Un}}+/** Fire OS's picker: Projectivy alone, about it as the picker says it, and nothing to do on the TV. */+@Composable+private fun FirePick() {+ val c = MaterialTheme.colorScheme+ Text(Copy.FIRE_INSTALL_TEXT, style = MaterialTheme.typography.bodyLarge, color = c.onSurfaceVariant)+ val l = RECOMMENDED.firstOrNull { it.pkg == PROJECTIVY } ?: return+ Surface(shape = MaterialTheme.shapes.large, color = c.surfaceContainer, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp)) {+ 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)+ }+ }+ }+}++/**+ * Fire OS's install, one dialog per [FireInstall.Step]: where it downloads from, the link opening that release+ * page on the phone, then the download and the install with no way out, then what went wrong.+ */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+private fun FireDialog(f: FireInstall, device: Device, actions: LauncherActions) {+ val step = f.step?.takeIf { it != FireInstall.Step.Checking } ?: return+ val c = MaterialTheme.colorScheme+ val uri = LocalUriHandler.current+ val label = launcherName(PROJECTIVY)+ val release = f.release+ val failed = step == FireInstall.Step.NotProjectivy || step == FireInstall.Step.NoDownload || step == FireInstall.Step.Refused+ AlertDialog(+ onDismissRequest = {},+ properties = Sticky,+ icon = if (failed) ({ Icon(Icons.Default.Warning, null) }) else null,+ title = {+ Text(+ when (step) {+ FireInstall.Step.Confirm -> Copy.installProjectivyOn(name(device))+ FireInstall.Step.NotProjectivy -> Copy.NOT_PROJECTIVY+ FireInstall.Step.NoDownload -> Copy.NO_DOWNLOAD+ FireInstall.Step.Refused -> "Couldn't install $label"+ else -> label+ },+ )+ },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ when (step) {+ FireInstall.Step.Confirm -> if (release != null) {+ Text(Copy.downloadsFrom(label, release.version, release.size), style = MaterialTheme.typography.bodyMedium)+ Row(Modifier.clickable(role = Role.Button) { uri.openUri(release.page) }, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ Icon(OpenInNew, null, Modifier.size(18.dp), tint = c.primary)+ Text(+ release.page.removePrefix("https://"),+ style = MaterialTheme.typography.bodyMedium.copy(textDecoration = TextDecoration.Underline),+ color = c.primary,+ )+ }+ Text(Copy.SIGNED_CHECK, style = MaterialTheme.typography.bodyMedium)+ }+ FireInstall.Step.Downloading, FireInstall.Step.Installing -> {+ Column {+ Text(PROJECTIVY, style = SmallNumber, color = c.onSurfaceVariant)+ release?.let { Text("Version ${it.version} · ${Copy.bytes(it.size)}", style = SmallNumber, color = c.onSurfaceVariant) }+ Text("from " + PROJECTIVY_RELEASES.removePrefix("https://").removeSuffix("/releases"), style = SmallNumber, color = c.onSurfaceVariant)+ }+ val p = f.progress?.fraction+ // Past the last byte the TV is still unpacking: no bar stuck at 100%.+ if (p != null && p < 1f) LinearWavyProgressIndicator(progress = { p }, Modifier.fillMaxWidth())+ else LinearWavyProgressIndicator(Modifier.fillMaxWidth())+ Text(+ if (step == FireInstall.Step.Downloading) Copy.downloading(((p ?: 0f) * 100).toInt()) else Copy.installingOn(name(device)),+ style = MaterialTheme.typography.bodyMedium,+ )+ Text(Copy.INSTALL_KEEP_OPEN, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ }+ FireInstall.Step.NotProjectivy -> Text(Copy.NOT_PROJECTIVY_TEXT, style = MaterialTheme.typography.bodyMedium)+ FireInstall.Step.NoDownload -> Text(Copy.NO_DOWNLOAD_TEXT, style = MaterialTheme.typography.bodyMedium)+ FireInstall.Step.Refused -> Text(f.error.orEmpty(), style = MaterialTheme.typography.bodyMedium)+ FireInstall.Step.Checking -> Unit+ }+ }+ },+ confirmButton = {+ when (step) {+ FireInstall.Step.Confirm -> Button(onClick = actions.fireInstall) { Text(Copy.DOWNLOAD_AND_INSTALL) }+ FireInstall.Step.NotProjectivy, FireInstall.Step.NoDownload -> Button(onClick = actions.fireCheck) { Text(Copy.TRY_AGAIN) }+ FireInstall.Step.Refused -> Button(onClick = actions.fireDismiss) { Text("OK") }+ else -> Unit+ }+ },+ dismissButton = {+ when (step) {+ FireInstall.Step.Confirm -> TextButton(onClick = actions.fireDismiss) { Text("Cancel") }+ FireInstall.Step.NotProjectivy -> TextButton(onClick = actions.fireDismiss) { Text("Close") }+ FireInstall.Step.NoDownload -> TextButton(onClick = { actions.fireDismiss(); uri.openUri(release?.page ?: PROJECTIVY_RELEASES) }) {+ Text(Copy.OPEN_DOWNLOAD_PAGE)+ }+ else -> Unit+ }+ },+ )+}+/** Row [i] of a segmented list ending at [last]: the ends rounded, the joins tight. */private fun segment(i: Int, last: Int): RoundedCornerShape {val top = if (i == 0) 16.dp else 4.dpdiff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 88ffd3e..c505fdd 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -32,8 +32,12 @@ import app.tellyscope.data.Dockimport app.tellyscope.data.Dockedimport app.tellyscope.data.HistoryEntryimport app.tellyscope.data.KeyHaptics+import app.tellyscope.data.LauncherDownload+import app.tellyscope.data.LauncherReleaseimport app.tellyscope.data.NetworkInfoimport app.tellyscope.data.NotAnApp+import app.tellyscope.data.NotProjectivy+import app.tellyscope.data.PROJECTIVYimport app.tellyscope.data.PhoneStorageimport app.tellyscope.data.PickedAppimport app.tellyscope.data.RemoteButtons@@ -166,10 +170,25 @@ data class ResetUi(* 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) {+data class LauncherFlow(val step: Step = Step.Pick, val pkg: String = RECOMMENDED.first().pkg, val fire: FireInstall? = null) {enum class Step { Pick, Waiting, NoStore, Left, Installed }}+/**+ * Install Projectivy on Fire OS ([fireInstall]), on [LauncherFlow.Step.Pick] in place of the picker: there's no+ * Play Store, so Tellyscope reads the latest release ([Step.Checking]), asks ([Step.Confirm]), downloads and+ * checks it ([Step.Downloading]), installs it over adb ([Step.Installing]), then moves to [LauncherFlow.Step.Installed].+ * A null [step] is the screen with no dialog. [error] is the TV's refusal, for [Step.Refused].+ */+data class FireInstall(+ val step: Step? = null,+ val release: LauncherRelease? = null,+ val progress: Progress? = null,+ val error: String? = null,+) {+ enum class Step { Checking, Confirm, Downloading, Installing, NotProjectivy, NoDownload, Refused }+}+/*** "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@@ -349,6 +368,8 @@ class TellyscopeViewModel(private val historySeen: SeenBook? = null,/** This build and phone, for reports. */private val appFacts: AppFacts = AppFacts("unknown", "unknown phone"),+ /** Projectivy from its developer's GitHub, for Fire OS. */+ private val launcherDownload: LauncherDownload? = null,) : ViewModel() {private val _state = MutableStateFlow(UiState(now = clock()))@@ -792,6 +813,10 @@ class TellyscopeViewModel(/** Opens Install a home screen on its picker; not before the launcher list has been downloaded once. */fun openLauncherFlow() {val id = _state.value.selectedId ?: return+ if (_state.value.selected?.let { fireInstall(it, _state.value.device.apps) } == true) {+ updateDevice(id) { it.copy(launcher = LauncherFlow(pkg = PROJECTIVY, fire = FireInstall())) }+ return+ }if (RECOMMENDED.isEmpty()) {_notice.value = Copy.NO_LAUNCHER_LISTreturn@@ -799,6 +824,74 @@ class TellyscopeViewModel(updateDevice(id) { it.copy(launcher = LauncherFlow()) }}+ private fun setFire(id: String, f: (FireInstall) -> FireInstall) =+ updateDevice(id) { d -> d.copy(launcher = d.launcher?.let { l -> l.fire?.let { l.copy(fire = f(it)) } }) }++ /** Install Projectivy on Fire OS: reads the latest release, for the confirm dialog to show where it comes from. */+ fun checkProjectivy() {+ val id = _state.value.selectedId ?: return+ val download = launcherDownload ?: return+ launcherJob?.cancel()+ setFire(id) { FireInstall(FireInstall.Step.Checking) }+ launcherJob = viewModelScope.launch {+ val release = try {+ download.latest()+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ return@launch setFire(id) { FireInstall(FireInstall.Step.NoDownload) }+ }+ setFire(id) { FireInstall(FireInstall.Step.Confirm, release) }+ }+ }++ /**+ * Download and install: fetches the APK, which must be Projectivy signed by its developer, then installs it+ * over adb like any sideload. Nothing reaches the TV unless the check passes.+ */+ fun installProjectivy() {+ val id = _state.value.selectedId ?: return+ val download = launcherDownload ?: return+ val release = _state.value.device.launcher?.fire?.takeIf { it.step == FireInstall.Step.Confirm }?.release ?: return+ launcherJob?.cancel()+ setFire(id) { it.copy(step = FireInstall.Step.Downloading, progress = null) }+ launcherJob = viewModelScope.launch {+ val app = try {+ download.fetch(release) { p -> setFire(id) { it.copy(progress = p) } }+ } catch (e: CancellationException) {+ throw e+ } catch (_: NotProjectivy) {+ return@launch setFire(id) { it.copy(step = FireInstall.Step.NotProjectivy) }+ } catch (_: Exception) {+ return@launch setFire(id) { it.copy(step = FireInstall.Step.NoDownload) }+ }+ setFire(id) { it.copy(step = FireInstall.Step.Installing, progress = null) }+ val result = try {+ source.install(id, app.files, app.info, allowDowngrade = false) { p -> setFire(id) { it.copy(progress = p) } }+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ return@launch setFire(id) { it.copy(step = FireInstall.Step.Refused, error = Copy.SIDELOAD_LOST) }+ }+ when (result) {+ InstallResult.Done -> launcherInstalled(id, PROJECTIVY) { step ->+ updateDevice(id) { it.copy(launcher = it.launcher?.copy(step = step)) }+ }+ is InstallResult.Refused -> setFire(id) {+ it.copy(step = FireInstall.Step.Refused, error = Copy.installRefused(result.reason, launcherName(PROJECTIVY)))+ }+ }+ }+ }++ /** Cancel, Close or OK on a Fire OS dialog: back to the screen. Not while the install runs. */+ fun dismissProjectivy() {+ val id = _state.value.selectedId ?: return+ if (_state.value.device.launcher?.fire?.step == FireInstall.Step.Installing) return+ launcherJob?.cancel()+ setFire(id) { FireInstall() }+ }+/** 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@@ -815,6 +908,8 @@ class TellyscopeViewModel(fun closeLauncherFlow() {val id = _state.value.selectedId ?: return+ // An install under way finishes; cutting it off could leave the TV half done.+ if (_state.value.device.launcher?.fire?.step == FireInstall.Step.Installing) returnlauncherJob?.cancel()updateDevice(id) { it.copy(launcher = null) }}@@ -864,24 +959,7 @@ class TellyscopeViewModel(return@repeat // 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.Installed -> return@launch launcherInstalled(id, pkg, step)StoreState.InStore -> seen = trueStoreState.Elsewhere -> if (seen) {// The Store closed without it: back to the picker, still chosen, and the snackbar says so.@@ -895,6 +973,25 @@ class TellyscopeViewModel(}}+ /** [pkg] is now on the TV: rereads the apps, then on to Make it the home screen. */+ private suspend fun launcherInstalled(id: String, pkg: String, step: (LauncherFlow.Step) -> Unit) {+ 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)+ }+ }+/** Yes on the installed launcher, with its accessibility service or without; the flow closes and the switch runs. */fun switchToLauncher(service: Boolean) {makeHome(_state.value.device.launcher?.pkg ?: return, service)diff --git a/app/src/main/java/app/tellyscope/ui/Transfers.kt b/app/src/main/java/app/tellyscope/ui/Transfers.ktindex f201b17..1538533 100644--- a/app/src/main/java/app/tellyscope/ui/Transfers.kt+++ b/app/src/main/java/app/tellyscope/ui/Transfers.kt@@ -55,7 +55,7 @@ import app.tellyscope.ui.theme.SmallNumber* Both dialogs here close only through their own buttons: a tap outside or Back would otherwise* drop an install halfway through its questions, or look like it cancelled a copy.*/-private val Sticky = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)+internal val Sticky = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)/*** The three things people come to a TV's page for, as big tiles under the system widget.diff --git a/app/src/test/java/app/tellyscope/FireOsTest.kt b/app/src/test/java/app/tellyscope/FireOsTest.ktnew file mode 100644index 0000000..fb44c4d--- /dev/null+++ b/app/src/test/java/app/tellyscope/FireOsTest.kt@@ -0,0 +1,226 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.lifecycle.viewModelScope+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.InstallResult+import app.tellyscope.adb.Progress+import app.tellyscope.data.AppInfo+import app.tellyscope.data.Device+import app.tellyscope.data.DeviceSource+import app.tellyscope.data.DeviceState+import app.tellyscope.data.FIRE_TV_LAUNCHER+import app.tellyscope.data.FakeDeviceSource+import app.tellyscope.data.HistoryEntry+import app.tellyscope.data.LauncherDownload+import app.tellyscope.data.LauncherRelease+import app.tellyscope.data.NotProjectivy+import app.tellyscope.data.PROJECTIVY+import app.tellyscope.data.PROJECTIVY_SIGNERS+import app.tellyscope.data.PickedApp+import app.tellyscope.data.ScanHit+import app.tellyscope.data.ScanKind+import app.tellyscope.data.Snapshot+import app.tellyscope.data.Suggestions+import app.tellyscope.data.isFireOs+import app.tellyscope.data.isProjectivy+import app.tellyscope.data.parseRelease+import app.tellyscope.ui.FireInstall+import app.tellyscope.ui.LauncherFlow+import app.tellyscope.ui.PLAY_STORE+import app.tellyscope.ui.RECOMMENDED+import app.tellyscope.ui.TellyscopeViewModel+import app.tellyscope.ui.fireInstall+import app.tellyscope.ui.offerChoose+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.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.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++// Fixtures from Amazon's developer docs, not from a TV: Fire TV devices report Build.MANUFACTURER "Amazon" and an+// AFT model (AFTKRT is the Fire TV Stick 4K Max, 2nd gen); Fire OS's home screen is com.amazon.tv.launcher, also on+// Fire TV Edition sets made by others.+private fun tv(manufacturer: String?, model: String?) =+ Device("tv", ScanHit("tv", 5555, ScanKind.Classic, null, null), DeviceState.Online, model, manufacturer, "11", 0L)++private val amazon = tv("Amazon", "AFTKRT")+private val insignia = tv("Insignia", "NS-43F301NA22")+private val androidTv = tv("Google", "Chromecast")++private val fireHome = AppInfo(FIRE_TV_LAUNCHER, "Fire TV Home", null, true, true, "this is your home screen", "1.0", home = true)+private val store = AppInfo(PLAY_STORE, "Google Play Store", null, true, true, null, "1.0")+private val tvHome = AppInfo("com.google.android.tvlauncher", "Google TV Home", null, true, true, "this is your home screen", "1.0", home = true)++private const val TAG = "4.72"+private const val PAGE = "https://github.com/spocky/miproja1/releases/tag/$TAG"+private const val APK = "https://github.com/spocky/miproja1/releases/download/$TAG/ProjectivyLauncher-4.72-c97-xda-release.apk"++/** GitHub's releases/latest, cut to the fields read. */+private fun release(+ tag: String = TAG,+ page: String = PAGE,+ assets: List<Pair<String, String>> = listOf("ProjectivyLauncher-4.72-c97-xda-release.apk" to APK),+ prerelease: Boolean = false,+ size: Long = 11432750,+) = """{"tag_name": "$tag", "html_url": "$page", "draft": false, "prerelease": $prerelease, "assets": [${+ assets.joinToString { (name, url) -> """{"name": "$name", "browser_download_url": "$url", "size": $size}""" }+}]}"""++/** A Fire TV with no Play Store, which takes whatever Tellyscope installs. */+private class FireTv : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {+ val installs = mutableListOf<ApkInfo>()+ var refuse: InstallResult? = null++ override suspend fun known() = listOf(amazon)+ override fun live(deviceId: String): Flow<Snapshot> = emptyFlow()+ override suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>) = Suggestions.Unavailable+ override suspend fun history(deviceId: String) = emptyList<HistoryEntry>()+ override suspend fun apps(deviceId: String) = listOf(fireHome) ++ if (installs.isEmpty()) emptyList() else listOf(AppInfo(PROJECTIVY, "Projectivy Launcher", null, false, true, null, "1.0", homeInstead = FIRE_TV_LAUNCHER, homeService = true))++ override suspend fun install(deviceId: String, apks: List<File>, apk: ApkInfo, allowDowngrade: Boolean, onProgress: (Progress) -> Unit): InstallResult {+ refuse?.let { return it }+ installs += apk+ return InstallResult.Done+ }+}++private class FakeDownload(var signedByDeveloper: Boolean = true) : LauncherDownload {+ var fetched = 0+ override suspend fun latest() = parseRelease(release())!!+ override suspend fun fetch(release: LauncherRelease, onProgress: (Progress) -> Unit): PickedApp {+ fetched+++ if (!signedByDeveloper) throw NotProjectivy()+ return PickedApp(listOf(File("projectivy.apk")), ApkInfo(PROJECTIVY, 97, release.version), "Projectivy Launcher")+ }+}++/** Install a home screen on Fire OS: who gets it, the release and signature checks, and the install. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class FireOsTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private val source = FireTv()+ private val download = FakeDownload()+ private var vm: TellyscopeViewModel? = null++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ vm?.viewModelScope?.cancel()+ Dispatchers.resetMain()+ }++ @Test fun anAmazonDeviceIsFireOs() {+ assertTrue(isFireOs(amazon, emptyList()))+ assertTrue(fireInstall(amazon, listOf(fireHome)))+ }++ @Test fun anotherMakersTvWithAmazonsLauncherIsFireOs() {+ assertTrue(isFireOs(insignia, listOf(fireHome)))+ assertFalse(isFireOs(insignia, emptyList()))+ }++ @Test fun plainAndroidTvKeepsThePlayStore() {+ assertFalse(isFireOs(androidTv, listOf(store, tvHome)))+ assertFalse(fireInstall(androidTv, listOf(store, tvHome)))+ }++ @Test fun fireOsGetsTheCardWithoutAPlayStore() {+ val fire = fireInstall(amazon, listOf(fireHome))+ assertTrue(offerChoose(listOf(fireHome), fire))+ assertTrue(offerLauncher(listOf(fireHome), hidden = false, fire = fire))+ assertFalse(offerLauncher(listOf(fireHome), hidden = false))+ }++ @Test fun aListWithoutProjectivyLeavesFireOsAsToday() {+ val without = RECOMMENDED.filter { it.pkg != PROJECTIVY }+ assertTrue(without.isNotEmpty())+ val fire = fireInstall(amazon, listOf(fireHome), without)+ assertFalse(fire)+ assertFalse(offerChoose(listOf(fireHome), fire))+ assertFalse(offerLauncher(listOf(fireHome), hidden = false, fire = fire))+ }++ @Test fun theLatestReleaseFromProjectivysRepo() {+ assertEquals(LauncherRelease(TAG, PAGE, APK, 11432750), parseRelease(release()))+ }++ @Test fun releasesThatArentProjectivysOwnAreRefused() {+ assertNull(parseRelease(release(prerelease = true)))+ assertNull(parseRelease(release(page = "https://github.com/someone/miproja1/releases/tag/$TAG")))+ assertNull(parseRelease(release(assets = listOf("a.apk" to APK, "b.apk" to APK))))+ assertNull(parseRelease(release(assets = listOf("p.apk" to "https://example.com/$TAG/p.apk"))))+ assertNull(parseRelease(release(assets = listOf("p.apk" to APK.replace("/$TAG/", "/4.70/")))))+ assertNull(parseRelease(release(size = 0)))+ assertNull(parseRelease(release(size = 200L shl 20)))+ assertNull(parseRelease("not json"))+ }++ @Test fun onlyProjectivySignedByItsDeveloper() {+ assertTrue(isProjectivy(PROJECTIVY, PROJECTIVY_SIGNERS))+ assertFalse(isProjectivy(PROJECTIVY, setOf("0".repeat(64))))+ assertFalse(isProjectivy(PROJECTIVY, PROJECTIVY_SIGNERS + "0".repeat(64)))+ assertFalse(isProjectivy(PROJECTIVY, emptySet()))+ assertFalse(isProjectivy("com.example.launcher", PROJECTIVY_SIGNERS))+ }++ private fun TestScope.opened(): TellyscopeViewModel {+ val v = TellyscopeViewModel(source, clock = { 0L }, launcherDownload = download)+ vm = v+ runCurrent()+ v.openLauncherFlow()+ return v+ }++ @Test fun itDownloadsChecksAndInstallsThenOffersTheSwitch() = with(test) {+ val v = opened()+ val flow = v.state.value.device.launcher!!+ assertEquals(PROJECTIVY, flow.pkg)+ assertEquals(FireInstall(), flow.fire)++ v.checkProjectivy()+ runCurrent()+ assertEquals(FireInstall.Step.Confirm, v.state.value.device.launcher?.fire?.step)+ assertEquals(PAGE, v.state.value.device.launcher?.fire?.release?.page)++ v.installProjectivy()+ runCurrent()+ assertEquals(listOf(PROJECTIVY), source.installs.map { it.packageName })+ assertEquals(LauncherFlow.Step.Installed, v.state.value.device.launcher?.step)+ }++ @Test fun aWrongSignatureInstallsNothing() = with(test) {+ download.signedByDeveloper = false+ val v = opened()+ v.checkProjectivy()+ runCurrent()+ v.installProjectivy()+ runCurrent()+ assertEquals(1, download.fetched)+ assertTrue(source.installs.isEmpty())+ assertEquals(FireInstall.Step.NotProjectivy, v.state.value.device.launcher?.fire?.step)+ assertEquals(LauncherFlow.Step.Pick, v.state.value.device.launcher?.step)+ }+}