Modern Apps git

← Modern-Apps.git

code reorganization

Commit
c879ca33e8de45146e2b8c17a264ab0c49b2d663
Author
vayun-mathur <[email protected]>
When
2026-09-12 22:57 UTC (2 months ago)
Parents
8ff4fcb

Diff

appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 593020e750..085000503f 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -29,6 +29,9 @@ import com.vayunmathur.appstore.ui.TrustPage import com.vayunmathur.appstore.ui.UpdatesPage import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.AppStoreViewModelFactory+import com.vayunmathur.appstore.util.clearSelection+import com.vayunmathur.appstore.util.selectApp+import com.vayunmathur.appstore.util.selectPackage import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.DynamicTheme
appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.ktindex 0f80e4a07f..36b03124e7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt@@ -11,8 +11,6 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width@@ -25,10 +23,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale-import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp@@ -38,14 +34,11 @@ import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.library.image.compose.AsyncImage-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconStar import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.util.sharedContainer import com.vayunmathur.library.util.sharedCrop import java.util.Locale @@ -222,71 +215,6 @@ fun AppRow(     } } -/**- * A carousel tile: icon over name over rating, in a fixed-width column.- *- * Fixed width rather than intrinsic so that the tiles in a row line up regardless of how- * long each app's name is — a carousel of ragged columns reads as broken.- */-@Composable-fun AppTile(-    app: UnifiedApp,-    modifier: Modifier = Modifier,-    isInstalled: Boolean = false,-    stage: InstallStage? = null,-    installedIcon: Drawable? = null,-    /** As [AppRow]: null for a tile whose app is already an origin elsewhere on screen. */-    sharedKey: Any? = null,-    onClick: () -> Unit = {},-) {-    Column(-        modifier-            // Deliberately [sharedContainer] where [AppRow] uses [sharedCrop]: a tile centres its-            // icon in 96dp and the detail header puts it hard left in a full-width row, so the two-            // ends are not congruent at their top-left and a crop would jump the icon across. A-            // reflow absorbs that. Do not "tidy" this into matching AppRow.-            .then(if (sharedKey == null) Modifier else Modifier.sharedContainer(sharedKey))-            .width(96.dp)-            .clip(RoundedCornerShape(12.dp))-            .clickable(onClick = onClick)-            .padding(vertical = 4.dp),-        horizontalAlignment = Alignment.CenterHorizontally,-    ) {-        AppIcon(app, installedIcon, size = 72.dp, corner = 18.dp)-        Spacer(Modifier.height(8.dp))-        Text(-            app.name,-            style = MaterialTheme.typography.labelMedium,-            textAlign = TextAlign.Center,-            maxLines = 2,-            overflow = TextOverflow.Ellipsis,-            // Two lines' worth whatever the name's length, so tiles stay aligned.-            modifier = Modifier.heightIn(min = 32.dp),-        )-        // An in-flight install replaces the rating line rather than adding a third one, so a-        // tile mid-install stays roughly the height of its neighbours. The slot holds a label-        // line even when it has nothing to say, because most catalogue entries carry no rating-        // and RatingLabel then draws nothing at all — an installed tile would be a whole line-        // taller than the ones either side of it, and a LazyRow takes the height of its tallest-        // visible child, so the carousel and everything below it would move as those tiles-        // scrolled in.-        val statusHeight = with(LocalDensity.current) {-            MaterialTheme.typography.labelSmall.lineHeight.toDp()-        }-        Box(Modifier.heightIn(min = statusHeight), contentAlignment = Alignment.Center) {-            when {-                stage != null -> StageProgress(stage)-                isInstalled -> Text(-                    stringResource(R.string.installed),-                    style = MaterialTheme.typography.labelSmall,-                    color = MaterialTheme.colorScheme.primary,-                )-                else -> RatingLabel(app)-            }-        }-    }-}- /** Heading above a section of the home screen. */ @Composable fun SectionHeader(title: String, subtitle: String?, modifier: Modifier = Modifier) {@@ -372,70 +300,3 @@ fun stageLabel(stage: InstallStage): String = when (stage) {     InstallStage.Installing -> stringResource(R.string.stage_installing)     is InstallStage.Failed -> stringResource(R.string.stage_failed, stage.reason) }--/** A labelled value in the facts grid on the detail page. */-@Composable-fun StatCell(label: String, value: String, modifier: Modifier = Modifier) {-    Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) {-        Text(-            value,-            style = MaterialTheme.typography.titleSmall,-            fontWeight = FontWeight.SemiBold,-            maxLines = 1,-        )-        Text(-            label,-            style = MaterialTheme.typography.labelSmall,-            color = MaterialTheme.colorScheme.onSurfaceVariant,-            maxLines = 1,-        )-    }-}--/** A read-only chip, for categories and anti-features. */-@Composable-fun InfoChip(-    text: String,-    modifier: Modifier = Modifier,-    emphasise: Boolean = false,-) {-    Card(-        modifier = modifier,-        colors = CardDefaults.cardColors(-            containerColor = if (emphasise) {-                MaterialTheme.colorScheme.errorContainer-            } else {-                MaterialTheme.colorScheme.surfaceVariant-            },-            contentColor = if (emphasise) {-                MaterialTheme.colorScheme.onErrorContainer-            } else {-                MaterialTheme.colorScheme.onSurfaceVariant-            },-        ),-    ) {-        Text(-            text,-            style = MaterialTheme.typography.labelSmall,-            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),-        )-    }-}--/** "12 MB", "980 kB" — SI units, because that is what stores quote. */-fun formatSize(bytes: Long): String = when {-    bytes <= 0L -> ""-    bytes < 1_000L -> "$bytes B"-    bytes < 1_000_000L -> String.format(Locale.US, "%.0f kB", bytes / 1_000.0)-    bytes < 1_000_000_000L -> String.format(Locale.US, "%.1f MB", bytes / 1_000_000.0)-    else -> String.format(Locale.US, "%.2f GB", bytes / 1_000_000_000.0)-}--/** "1.2M+", "50K+" — the rounded form an install count is meaningful at. */-fun formatCount(count: Long): String = when {-    count <= 0L -> ""-    count < 1_000L -> count.toString()-    count < 1_000_000L -> "${count / 1_000}K+"-    count < 1_000_000_000L -> String.format(Locale.US, "%.1fM+", count / 1_000_000.0)-    else -> String.format(Locale.US, "%.1fB+", count / 1_000_000_000.0)-}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.ktnew file mode 100644index 0000000000..49d4c4cd7d--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailHeader.kt@@ -0,0 +1,235 @@+package com.vayunmathur.appstore.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.util.AppDetailUiState+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.compose.AsyncImageState+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.IconKeyboardArrowUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.sharedCrop++@Composable+internal fun AppDetailHeader(state: AppDetailUiState) {+    val app = state.app ?: return+    Row(+        Modifier+            .sharedCrop("appstore-app-${app.packageName}")+            .fillMaxWidth()+            .padding(start = 16.dp, end = 16.dp, top = 8.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        AppIcon(app, state.installedIcon, size = 80.dp, corner = 20.dp)+        Spacer(Modifier.width(16.dp))+        Column(Modifier.weight(1f)) {+            Text(+                app.name,+                style = MaterialTheme.typography.headlineSmall,+                fontWeight = FontWeight.Bold,+            )+            app.author?.let {+                Text(+                    it,+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.primary,+                )+            }+            Row(+                Modifier.padding(top = 6.dp),+                horizontalArrangement = Arrangement.spacedBy(6.dp),+                verticalAlignment = Alignment.CenterVertically,+            ) {+                SourceChip(app.source)+                if (state.isLoadingDetails) CircularProgressIndicator(Modifier.size(12.dp))+            }+        }+    }+}++/**+ * Rating, installs, size and age rating, in whatever subset the source published.+ *+ * F-Droid publishes none of the first three, so the row collapses to just the size for an+ * F-Droid app rather than showing four empty cells.+ */+@Composable+internal fun AppDetailFacts(app: UnifiedApp) {+    val cells = buildList<Pair<String, String>> {+        app.rating?.let {+            add(stringResource(R.string.fact_rating) to String.format(java.util.Locale.US, "%.1f★", it))+        }+        if (app.installs > 0) add(stringResource(R.string.fact_installs) to formatCount(app.installs))+        if (app.sizeBytes > 0) add(stringResource(R.string.fact_size) to formatSize(app.sizeBytes))+        app.contentRating?.let { add(stringResource(R.string.fact_rated) to it) }+        app.versionName?.let { add(stringResource(R.string.fact_version) to it) }+    }+    if (cells.isEmpty()) return+    Row(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        horizontalArrangement = Arrangement.SpaceEvenly,+    ) {+        cells.take(4).forEachIndexed { index, (label, value) ->+            if (index > 0) {+                Box(+                    Modifier+                        .width(1.dp)+                        .height(32.dp)+                        .background(MaterialTheme.colorScheme.outlineVariant)+                )+            }+            StatCell(label, value, Modifier.weight(1f))+        }+    }+}++/** Screenshots, at a fixed height so mixed aspect ratios still scroll as one strip. */+@Composable+internal fun AppScreenshotStrip(urls: List<String>) {+    LazyRow(+        Modifier.fillMaxWidth(),+        contentPadding = PaddingValues(horizontal = 16.dp),+        horizontalArrangement = Arrangement.spacedBy(10.dp),+    ) {+        items(urls, key = { it }) { url ->+            // The width has to be stated. AsyncImage draws its bitmap with matchParentSize, which+            // contributes nothing to the measure pass, so an image given only a height resolves to+            // zero wide and the strip is 220dp of nothing. Start at a phone screenshot's shape and+            // switch to the real one once the bitmap has been decoded.+            var ratio by remember(url) { mutableFloatStateOf(PORTRAIT_SCREENSHOT_RATIO) }+            AsyncImage(+                model = url,+                contentDescription = null,+                modifier = Modifier+                    .height(220.dp)+                    .aspectRatio(ratio)+                    .clip(RoundedCornerShape(12.dp))+                    .background(MaterialTheme.colorScheme.surfaceVariant),+                contentScale = ContentScale.Fit,+                onState = { state ->+                    val size = (state as? AsyncImageState.Success)?.painter?.intrinsicSize+                    if (size != null && size.width > 0f && size.height > 0f) {+                        ratio = size.width / size.height+                    }+                },+            )+        }+    }+}++/** 9:16, the shape a phone screenshot is until its own is known. */+private const val PORTRAIT_SCREENSHOT_RATIO = 9f / 16f++/** Summary always, full description behind a toggle — most of them are very long. */+@Composable+internal fun AppDetailDescription(app: UnifiedApp) {+    if (app.summary.isBlank() && app.description.isBlank()) return+    var expanded by remember(app.packageName) { mutableStateOf(false) }+    Column(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        verticalArrangement = Arrangement.spacedBy(6.dp),+    ) {+        if (app.summary.isNotBlank()) {+            Text(+                app.summary,+                style = MaterialTheme.typography.bodyLarge,+                fontWeight = FontWeight.Medium,+            )+        }+        if (app.description.isNotBlank() && app.description != app.summary) {+            Text(+                app.description,+                style = MaterialTheme.typography.bodyMedium,+                maxLines = if (expanded) Int.MAX_VALUE else 5,+                overflow = TextOverflow.Ellipsis,+            )+            TextButton(onClick = { expanded = !expanded }) {+                Text(+                    stringResource(+                        if (expanded) R.string.action_show_less else R.string.action_read_more+                    )+                )+                Spacer(Modifier.width(4.dp))+                if (expanded) IconKeyboardArrowUp() else IconKeyboardArrowDown()+            }+        }+    }+}++@Composable+internal fun AppDetailWhatsNew(app: UnifiedApp) {+    val notes = app.whatsNew?.takeIf { it.isNotBlank() } ?: return+    Column(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        verticalArrangement = Arrangement.spacedBy(4.dp),+    ) {+        Text(+            stringResource(R.string.detail_whats_new),+            style = MaterialTheme.typography.titleSmall,+            fontWeight = FontWeight.SemiBold,+        )+        app.updatedOn?.let {+            Text(+                it,+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        Text(notes, style = MaterialTheme.typography.bodyMedium)+    }+}++@Composable+internal fun AppDetailChips(app: UnifiedApp) {+    if (app.categories.isEmpty() && app.antiFeatures.isEmpty() && !app.containsAds && !app.reproducible) return+    LazyRow(+        Modifier.fillMaxWidth(),+        contentPadding = PaddingValues(horizontal = 16.dp),+        horizontalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        // F-Droid versions the verification server rebuilt bit-for-bit earn a positive badge.+        if (app.reproducible) {+            item("reproducible") { InfoChip(stringResource(R.string.chip_reproducible)) }+        }+        items(app.categories, key = { "cat-$it" }) { InfoChip(it) }+        if (app.containsAds) {+            item("ads") { InfoChip(stringResource(R.string.chip_contains_ads), emphasise = true) }+        }+        // F-Droid's anti-feature labels are the honest part of its listings and there is+        // no reason to bury them; they are flagged rather than hidden.+        items(app.antiFeatures, key = { "af-$it" }) { InfoChip(it, emphasise = true) }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.ktindex 81290123e3..d6cbb4837c 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt@@ -1,72 +1,33 @@ package com.vayunmathur.appstore.ui -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.lazy.LazyRow-import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.appstore.R-import com.vayunmathur.appstore.data.AppSource-import com.vayunmathur.appstore.data.UnifiedApp-import com.vayunmathur.appstore.data.installer.InstallStage-import com.vayunmathur.appstore.data.security.TrustProfile-import com.vayunmathur.appstore.data.security.VerificationResult import com.vayunmathur.appstore.util.AppDetailActions import com.vayunmathur.appstore.util.AppDetailUiState import com.vayunmathur.appstore.util.AppStoreViewModel-import com.vayunmathur.library.image.compose.AsyncImage-import com.vayunmathur.library.image.compose.AsyncImageState import com.vayunmathur.library.ui.AppBarAlignment import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ConfirmDialog-import com.vayunmathur.library.ui.FilledTonalButton-import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconDownload-import com.vayunmathur.library.ui.IconGlobe-import com.vayunmathur.library.ui.IconKeyboardArrowDown-import com.vayunmathur.library.ui.IconKeyboardArrowUp import com.vayunmathur.library.ui.IconShare-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.util.sharedCrop  /** Binds [AppStoreViewModel] to the stateless [AppDetailScreen]. */ @Composable@@ -116,16 +77,16 @@ fun AppDetailScreen(                 .padding(bottom = 32.dp),             verticalArrangement = Arrangement.spacedBy(16.dp),         ) {-            Header(state)-            InstallActions(state, actions, onUninstall = { showUninstallConfirm = true })-            if (app.screenshots.isNotEmpty()) ScreenshotStrip(app.screenshots)-            Facts(app)-            Description(app)-            WhatsNew(app)-            Chips(app)-            TrustCard(app.source, state.verification, onOpenTrust)-            Links(app, actions)-            Details(app)+            AppDetailHeader(state)+            AppInstallActions(state, actions, onUninstall = { showUninstallConfirm = true })+            if (app.screenshots.isNotEmpty()) AppScreenshotStrip(app.screenshots)+            AppDetailFacts(app)+            AppDetailDescription(app)+            AppDetailWhatsNew(app)+            AppDetailChips(app)+            AppTrustCard(app.source, state.verification, onOpenTrust)+            AppDetailLinks(app, actions)+            AppDetailDetails(app)         }     } @@ -141,388 +102,3 @@ fun AppDetailScreen(         )     } }--@Composable-private fun Header(state: AppDetailUiState) {-    val app = state.app ?: return-    Row(-        Modifier-            .sharedCrop("appstore-app-${app.packageName}")-            .fillMaxWidth()-            .padding(start = 16.dp, end = 16.dp, top = 8.dp),-        verticalAlignment = Alignment.CenterVertically,-    ) {-        AppIcon(app, state.installedIcon, size = 80.dp, corner = 20.dp)-        Spacer(Modifier.width(16.dp))-        Column(Modifier.weight(1f)) {-            Text(-                app.name,-                style = MaterialTheme.typography.headlineSmall,-                fontWeight = FontWeight.Bold,-            )-            app.author?.let {-                Text(-                    it,-                    style = MaterialTheme.typography.bodyMedium,-                    color = MaterialTheme.colorScheme.primary,-                )-            }-            Row(-                Modifier.padding(top = 6.dp),-                horizontalArrangement = Arrangement.spacedBy(6.dp),-                verticalAlignment = Alignment.CenterVertically,-            ) {-                SourceChip(app.source)-                if (state.isLoadingDetails) CircularProgressIndicator(Modifier.size(12.dp))-            }-        }-    }-}--/**- * Rating, installs, size and age rating, in whatever subset the source published.- *- * F-Droid publishes none of the first three, so the row collapses to just the size for an- * F-Droid app rather than showing four empty cells.- */-@Composable-private fun Facts(app: UnifiedApp) {-    val cells = buildList<Pair<String, String>> {-        app.rating?.let {-            add(stringResource(R.string.fact_rating) to String.format(java.util.Locale.US, "%.1f★", it))-        }-        if (app.installs > 0) add(stringResource(R.string.fact_installs) to formatCount(app.installs))-        if (app.sizeBytes > 0) add(stringResource(R.string.fact_size) to formatSize(app.sizeBytes))-        app.contentRating?.let { add(stringResource(R.string.fact_rated) to it) }-        app.versionName?.let { add(stringResource(R.string.fact_version) to it) }-    }-    if (cells.isEmpty()) return-    Row(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        horizontalArrangement = Arrangement.SpaceEvenly,-    ) {-        cells.take(4).forEachIndexed { index, (label, value) ->-            if (index > 0) {-                Box(-                    Modifier-                        .width(1.dp)-                        .height(32.dp)-                        .background(MaterialTheme.colorScheme.outlineVariant)-                )-            }-            StatCell(label, value, Modifier.weight(1f))-        }-    }-}--/**- * The primary action.- *- * There is exactly one full-width button and it always says what tapping it will do —- * including mid-install, where it reports the stage instead of going dead and leaving a- * separate progress bar to explain itself.- */-@Composable-private fun InstallActions(-    state: AppDetailUiState,-    actions: AppDetailActions,-    onUninstall: () -> Unit,-) {-    val app = state.app ?: return-    val stage = state.stage-    val busy = stage != null && stage !is InstallStage.Failed--    Column(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        verticalArrangement = Arrangement.spacedBy(8.dp),-    ) {-        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-            when {-                busy -> Button(onClick = {}, enabled = false, modifier = Modifier.weight(1f)) {-                    Text(stageLabel(stage))-                }--                state.hasUpdate -> {-                    Button(onClick = { actions.install(app) }, modifier = Modifier.weight(1f)) {-                        IconDownload()-                        Spacer(Modifier.width(8.dp))-                        Text(stringResource(R.string.action_update))-                    }-                    FilledTonalButton(onClick = { actions.openApp(app.packageName) }) {-                        Text(stringResource(R.string.open))-                    }-                }--                state.isInstalled -> {-                    FilledTonalButton(-                        onClick = { actions.openApp(app.packageName) },-                        modifier = Modifier.weight(1f),-                    ) {-                        Text(stringResource(R.string.open))-                    }-                    OutlinedButton(onClick = onUninstall) { IconDelete() }-                }--                else -> Button(-                    onClick = { actions.install(app) },-                    modifier = Modifier.weight(1f),-                ) {-                    IconDownload()-                    Spacer(Modifier.width(8.dp))-                    Text(stringResource(R.string.action_install))-                }-            }-        }--        if (state.isInstalled && state.installedInfo?.versionName != null && !state.hasUpdate) {-            Text(-                stringResource(R.string.installed_2, state.installedInfo.versionName),-                style = MaterialTheme.typography.labelSmall,-                color = MaterialTheme.colorScheme.onSurfaceVariant,-            )-        }--        StageProgress(stage)-        if (stage is InstallStage.Failed) {-            TextButton(onClick = { actions.dismissInstallFailure(app.packageName) }) {-                Text(stringResource(R.string.action_dismiss))-            }-        }-    }-}--/** Screenshots, at a fixed height so mixed aspect ratios still scroll as one strip. */-@Composable-private fun ScreenshotStrip(urls: List<String>) {-    LazyRow(-        Modifier.fillMaxWidth(),-        contentPadding = PaddingValues(horizontal = 16.dp),-        horizontalArrangement = Arrangement.spacedBy(10.dp),-    ) {-        items(urls, key = { it }) { url ->-            // The width has to be stated. AsyncImage draws its bitmap with matchParentSize, which-            // contributes nothing to the measure pass, so an image given only a height resolves to-            // zero wide and the strip is 220dp of nothing. Start at a phone screenshot's shape and-            // switch to the real one once the bitmap has been decoded.-            var ratio by remember(url) { mutableFloatStateOf(PORTRAIT_SCREENSHOT_RATIO) }-            AsyncImage(-                model = url,-                contentDescription = null,-                modifier = Modifier-                    .height(220.dp)-                    .aspectRatio(ratio)-                    .clip(RoundedCornerShape(12.dp))-                    .background(MaterialTheme.colorScheme.surfaceVariant),-                contentScale = ContentScale.Fit,-                onState = { state ->-                    val size = (state as? AsyncImageState.Success)?.painter?.intrinsicSize-                    if (size != null && size.width > 0f && size.height > 0f) {-                        ratio = size.width / size.height-                    }-                },-            )-        }-    }-}--/** 9:16, the shape a phone screenshot is until its own is known. */-private const val PORTRAIT_SCREENSHOT_RATIO = 9f / 16f--/** Summary always, full description behind a toggle — most of them are very long. */-@Composable-private fun Description(app: UnifiedApp) {-    if (app.summary.isBlank() && app.description.isBlank()) return-    var expanded by remember(app.packageName) { mutableStateOf(false) }-    Column(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        verticalArrangement = Arrangement.spacedBy(6.dp),-    ) {-        if (app.summary.isNotBlank()) {-            Text(-                app.summary,-                style = MaterialTheme.typography.bodyLarge,-                fontWeight = FontWeight.Medium,-            )-        }-        if (app.description.isNotBlank() && app.description != app.summary) {-            Text(-                app.description,-                style = MaterialTheme.typography.bodyMedium,-                maxLines = if (expanded) Int.MAX_VALUE else 5,-                overflow = TextOverflow.Ellipsis,-            )-            TextButton(onClick = { expanded = !expanded }) {-                Text(-                    stringResource(-                        if (expanded) R.string.action_show_less else R.string.action_read_more-                    )-                )-                Spacer(Modifier.width(4.dp))-                if (expanded) IconKeyboardArrowUp() else IconKeyboardArrowDown()-            }-        }-    }-}--@Composable-private fun WhatsNew(app: UnifiedApp) {-    val notes = app.whatsNew?.takeIf { it.isNotBlank() } ?: return-    Column(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        verticalArrangement = Arrangement.spacedBy(4.dp),-    ) {-        Text(-            stringResource(R.string.detail_whats_new),-            style = MaterialTheme.typography.titleSmall,-            fontWeight = FontWeight.SemiBold,-        )-        app.updatedOn?.let {-            Text(-                it,-                style = MaterialTheme.typography.labelSmall,-                color = MaterialTheme.colorScheme.onSurfaceVariant,-            )-        }-        Text(notes, style = MaterialTheme.typography.bodyMedium)-    }-}--@Composable-private fun Chips(app: UnifiedApp) {-    if (app.categories.isEmpty() && app.antiFeatures.isEmpty() && !app.containsAds && !app.reproducible) return-    LazyRow(-        Modifier.fillMaxWidth(),-        contentPadding = PaddingValues(horizontal = 16.dp),-        horizontalArrangement = Arrangement.spacedBy(8.dp),-    ) {-        // F-Droid versions the verification server rebuilt bit-for-bit earn a positive badge.-        if (app.reproducible) {-            item("reproducible") { InfoChip(stringResource(R.string.chip_reproducible)) }-        }-        items(app.categories, key = { "cat-$it" }) { InfoChip(it) }-        if (app.containsAds) {-            item("ads") { InfoChip(stringResource(R.string.chip_contains_ads), emphasise = true) }-        }-        // F-Droid's anti-feature labels are the honest part of its listings and there is-        // no reason to bury them; they are flagged rather than hidden.-        items(app.antiFeatures, key = { "af-$it" }) { InfoChip(it, emphasise = true) }-    }-}--/**- * What can be checked about this app's download, and what the last install proved.- *- * Neutral by design: the card describes the source's own practices and this app's checks,- * and does not claim one source is safer than another. Tapping opens the full comparison.- */-@Composable-private fun TrustCard(-    source: AppSource,-    verification: VerificationResult?,-    onOpenTrust: () -> Unit,-) {-    val profile = TrustProfile.of(source)-    Card(-        onClick = onOpenTrust,-        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),-    ) {-        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {-            Text(-                stringResource(profile.title),-                style = MaterialTheme.typography.titleSmall,-                fontWeight = FontWeight.SemiBold,-            )-            Text(stringResource(profile.summary), style = MaterialTheme.typography.bodySmall)-            when (verification) {-                is VerificationResult.Rejected -> Text(-                    stringResource(R.string.detail_install_blocked, verification.reason),-                    style = MaterialTheme.typography.labelSmall,-                    color = MaterialTheme.colorScheme.error,-                )-                is VerificationResult.Verified -> Text(-                    stringResource(R.string.detail_checked_on_install, verification.detail),-                    style = MaterialTheme.typography.labelSmall,-                    color = MaterialTheme.colorScheme.primary,-                )-                is VerificationResult.Unverified -> Text(-                    stringResource(R.string.detail_installed_unverified, verification.reason),-                    style = MaterialTheme.typography.labelSmall,-                    color = MaterialTheme.colorScheme.error,-                )-                null -> Text(-                    stringResource(R.string.detail_tap_for_trust),-                    style = MaterialTheme.typography.labelSmall,-                    color = MaterialTheme.colorScheme.onSurfaceVariant,-                )-            }-        }-    }-}--@Composable-private fun Links(app: UnifiedApp, actions: AppDetailActions) {-    val links = buildList<Pair<Int, String>> {-        app.website?.let { add(R.string.link_website to it) }-        app.sourceCode?.let { add(R.string.link_source to it) }-        app.privacyPolicyUrl?.let { add(R.string.link_privacy to it) }-    }-    if (links.isEmpty() && app.source != AppSource.PLAYSTORE) return-    Column(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        verticalArrangement = Arrangement.spacedBy(8.dp),-    ) {-        links.forEach { (label, url) ->-            OutlinedButton(-                onClick = { actions.openInBrowser(url) },-                modifier = Modifier.fillMaxWidth(),-            ) {-                IconGlobe()-                Spacer(Modifier.width(8.dp))-                Text(stringResource(label))-            }-        }-        if (app.source == AppSource.PLAYSTORE) {-            OutlinedButton(-                onClick = { actions.openInPlayStore(app.packageName) },-                modifier = Modifier.fillMaxWidth(),-            ) {-                Text(stringResource(R.string.view_in_play_store))-            }-        }-    }-}--/** The remaining facts, as a plain table — deliberately last. */-@Composable-private fun Details(app: UnifiedApp) {-    Column(-        Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        verticalArrangement = Arrangement.spacedBy(6.dp),-    ) {-        HorizontalDivider()-        DetailRow(stringResource(R.string.detail_package), app.packageName)-        app.license?.let { DetailRow(stringResource(R.string.detail_license), it) }-        app.targetSdk?.let { DetailRow(stringResource(R.string.detail_target_sdk), it.toString()) }-        if (app.ratingCount > 0) {-            DetailRow(stringResource(R.string.detail_rating_count), formatCount(app.ratingCount))-        }-        if (app.permissions.isNotEmpty()) {-            DetailRow(-                stringResource(R.string.detail_permissions),-                app.permissions.joinToString("\n") { it.substringAfterLast('.') },-            )-        }-    }-}--@Composable-private fun DetailRow(label: String, value: String) {-    Column(Modifier.fillMaxWidth()) {-        Text(-            label,-            style = MaterialTheme.typography.labelSmall,-            color = MaterialTheme.colorScheme.onSurfaceVariant,-        )-        Text(value, style = MaterialTheme.typography.bodySmall)-    }-}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.ktnew file mode 100644index 0000000000..fb20942623--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt@@ -0,0 +1,228 @@+package com.vayunmathur.appstore.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.appstore.data.security.TrustProfile+import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.appstore.util.AppDetailActions+import com.vayunmathur.appstore.util.AppDetailUiState+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconDownload+import com.vayunmathur.library.ui.IconGlobe+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * The primary action.+ *+ * There is exactly one full-width button and it always says what tapping it will do —+ * including mid-install, where it reports the stage instead of going dead and leaving a+ * separate progress bar to explain itself.+ */+@Composable+internal fun AppInstallActions(+    state: AppDetailUiState,+    actions: AppDetailActions,+    onUninstall: () -> Unit,+) {+    val app = state.app ?: return+    val stage = state.stage+    val busy = stage != null && stage !is InstallStage.Failed++    Column(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+            when {+                busy -> Button(onClick = {}, enabled = false, modifier = Modifier.weight(1f)) {+                    Text(stageLabel(stage))+                }++                state.hasUpdate -> {+                    Button(onClick = { actions.install(app) }, modifier = Modifier.weight(1f)) {+                        IconDownload()+                        Spacer(Modifier.width(8.dp))+                        Text(stringResource(R.string.action_update))+                    }+                    FilledTonalButton(onClick = { actions.openApp(app.packageName) }) {+                        Text(stringResource(R.string.open))+                    }+                }++                state.isInstalled -> {+                    FilledTonalButton(+                        onClick = { actions.openApp(app.packageName) },+                        modifier = Modifier.weight(1f),+                    ) {+                        Text(stringResource(R.string.open))+                    }+                    OutlinedButton(onClick = onUninstall) { IconDelete() }+                }++                else -> Button(+                    onClick = { actions.install(app) },+                    modifier = Modifier.weight(1f),+                ) {+                    IconDownload()+                    Spacer(Modifier.width(8.dp))+                    Text(stringResource(R.string.action_install))+                }+            }+        }++        if (state.isInstalled && state.installedInfo?.versionName != null && !state.hasUpdate) {+            Text(+                stringResource(R.string.installed_2, state.installedInfo.versionName),+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }++        StageProgress(stage)+        if (stage is InstallStage.Failed) {+            TextButton(onClick = { actions.dismissInstallFailure(app.packageName) }) {+                Text(stringResource(R.string.action_dismiss))+            }+        }+    }+}++/**+ * What can be checked about this app's download, and what the last install proved.+ *+ * Neutral by design: the card describes the source's own practices and this app's checks,+ * and does not claim one source is safer than another. Tapping opens the full comparison.+ */+@Composable+internal fun AppTrustCard(+    source: AppSource,+    verification: VerificationResult?,+    onOpenTrust: () -> Unit,+) {+    val profile = TrustProfile.of(source)+    Card(+        onClick = onOpenTrust,+        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+    ) {+        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            Text(+                stringResource(profile.title),+                style = MaterialTheme.typography.titleSmall,+                fontWeight = FontWeight.SemiBold,+            )+            Text(stringResource(profile.summary), style = MaterialTheme.typography.bodySmall)+            when (verification) {+                is VerificationResult.Rejected -> Text(+                    stringResource(R.string.detail_install_blocked, verification.reason),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.error,+                )+                is VerificationResult.Verified -> Text(+                    stringResource(R.string.detail_checked_on_install, verification.detail),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.primary,+                )+                is VerificationResult.Unverified -> Text(+                    stringResource(R.string.detail_installed_unverified, verification.reason),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.error,+                )+                null -> Text(+                    stringResource(R.string.detail_tap_for_trust),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+        }+    }+}++@Composable+internal fun AppDetailLinks(app: UnifiedApp, actions: AppDetailActions) {+    val links = buildList<Pair<Int, String>> {+        app.website?.let { add(R.string.link_website to it) }+        app.sourceCode?.let { add(R.string.link_source to it) }+        app.privacyPolicyUrl?.let { add(R.string.link_privacy to it) }+    }+    if (links.isEmpty() && app.source != AppSource.PLAYSTORE) return+    Column(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        links.forEach { (label, url) ->+            OutlinedButton(+                onClick = { actions.openInBrowser(url) },+                modifier = Modifier.fillMaxWidth(),+            ) {+                IconGlobe()+                Spacer(Modifier.width(8.dp))+                Text(stringResource(label))+            }+        }+        if (app.source == AppSource.PLAYSTORE) {+            OutlinedButton(+                onClick = { actions.openInPlayStore(app.packageName) },+                modifier = Modifier.fillMaxWidth(),+            ) {+                Text(stringResource(R.string.view_in_play_store))+            }+        }+    }+}++/** The remaining facts, as a plain table — deliberately last. */+@Composable+internal fun AppDetailDetails(app: UnifiedApp) {+    Column(+        Modifier.fillMaxWidth().padding(horizontal = 16.dp),+        verticalArrangement = Arrangement.spacedBy(6.dp),+    ) {+        HorizontalDivider()+        DetailRow(stringResource(R.string.detail_package), app.packageName)+        app.license?.let { DetailRow(stringResource(R.string.detail_license), it) }+        app.targetSdk?.let { DetailRow(stringResource(R.string.detail_target_sdk), it.toString()) }+        if (app.ratingCount > 0) {+            DetailRow(stringResource(R.string.detail_rating_count), formatCount(app.ratingCount))+        }+        if (app.permissions.isNotEmpty()) {+            DetailRow(+                stringResource(R.string.detail_permissions),+                app.permissions.joinToString("\n") { it.substringAfterLast('.') },+            )+        }+    }+}++@Composable+internal fun DetailRow(label: String, value: String) {+    Column(Modifier.fillMaxWidth()) {+        Text(+            label,+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Text(value, style = MaterialTheme.typography.bodySmall)+    }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppMeta.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppMeta.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppMeta.ktnew file mode 100644index 0000000000..a13cfe0d0b--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppMeta.kt@@ -0,0 +1,80 @@+package com.vayunmathur.appstore.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import java.util.Locale++/** A labelled value in the facts grid on the detail page. */+@Composable+fun StatCell(label: String, value: String, modifier: Modifier = Modifier) {+    Column(modifier, horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally) {+        Text(+            value,+            style = MaterialTheme.typography.titleSmall,+            fontWeight = FontWeight.SemiBold,+            maxLines = 1,+        )+        Text(+            label,+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            maxLines = 1,+        )+    }+}++/** A read-only chip, for categories and anti-features. */+@Composable+fun InfoChip(+    text: String,+    modifier: Modifier = Modifier,+    emphasise: Boolean = false,+) {+    Card(+        modifier = modifier,+        colors = CardDefaults.cardColors(+            containerColor = if (emphasise) {+                MaterialTheme.colorScheme.errorContainer+            } else {+                MaterialTheme.colorScheme.surfaceVariant+            },+            contentColor = if (emphasise) {+                MaterialTheme.colorScheme.onErrorContainer+            } else {+                MaterialTheme.colorScheme.onSurfaceVariant+            },+        ),+    ) {+        Text(+            text,+            style = MaterialTheme.typography.labelSmall,+            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),+        )+    }+}++/** "12 MB", "980 kB" — SI units, because that is what stores quote. */+fun formatSize(bytes: Long): String = when {+    bytes <= 0L -> ""+    bytes < 1_000L -> "$bytes B"+    bytes < 1_000_000L -> String.format(Locale.US, "%.0f kB", bytes / 1_000.0)+    bytes < 1_000_000_000L -> String.format(Locale.US, "%.1f MB", bytes / 1_000_000.0)+    else -> String.format(Locale.US, "%.2f GB", bytes / 1_000_000_000.0)+}++/** "1.2M+", "50K+" — the rounded form an install count is meaningful at. */+fun formatCount(count: Long): String = when {+    count <= 0L -> ""+    count < 1_000L -> count.toString()+    count < 1_000_000L -> "${count / 1_000}K+"+    count < 1_000_000_000L -> String.format(Locale.US, "%.1fM+", count / 1_000_000.0)+    else -> String.format(Locale.US, "%.1fB+", count / 1_000_000_000.0)+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppTile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppTile.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppTile.ktnew file mode 100644index 0000000000..9f56f01081--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppTile.kt@@ -0,0 +1,94 @@+package com.vayunmathur.appstore.ui++import android.graphics.drawable.Drawable+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.sharedContainer++/**+ * A carousel tile: icon over name over rating, in a fixed-width column.+ *+ * Fixed width rather than intrinsic so that the tiles in a row line up regardless of how+ * long each app's name is — a carousel of ragged columns reads as broken.+ */+@Composable+fun AppTile(+    app: UnifiedApp,+    modifier: Modifier = Modifier,+    isInstalled: Boolean = false,+    stage: InstallStage? = null,+    installedIcon: Drawable? = null,+    /** As [AppRow]: null for a tile whose app is already an origin elsewhere on screen. */+    sharedKey: Any? = null,+    onClick: () -> Unit = {},+) {+    Column(+        modifier+            // Deliberately [sharedContainer] where [AppRow] uses [sharedCrop]: a tile centres its+            // icon in 96dp and the detail header puts it hard left in a full-width row, so the two+            // ends are not congruent at their top-left and a crop would jump the icon across. A+            // reflow absorbs that. Do not "tidy" this into matching AppRow.+            .then(if (sharedKey == null) Modifier else Modifier.sharedContainer(sharedKey))+            .width(96.dp)+            .clip(RoundedCornerShape(12.dp))+            .clickable(onClick = onClick)+            .padding(vertical = 4.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        AppIcon(app, installedIcon, size = 72.dp, corner = 18.dp)+        Spacer(Modifier.height(8.dp))+        Text(+            app.name,+            style = MaterialTheme.typography.labelMedium,+            textAlign = TextAlign.Center,+            maxLines = 2,+            overflow = TextOverflow.Ellipsis,+            // Two lines' worth whatever the name's length, so tiles stay aligned.+            modifier = Modifier.heightIn(min = 32.dp),+        )+        // An in-flight install replaces the rating line rather than adding a third one, so a+        // tile mid-install stays roughly the height of its neighbours. The slot holds a label+        // line even when it has nothing to say, because most catalogue entries carry no rating+        // and RatingLabel then draws nothing at all — an installed tile would be a whole line+        // taller than the ones either side of it, and a LazyRow takes the height of its tallest+        // visible child, so the carousel and everything below it would move as those tiles+        // scrolled in.+        val statusHeight = with(LocalDensity.current) {+            MaterialTheme.typography.labelSmall.lineHeight.toDp()+        }+        Box(Modifier.heightIn(min = statusHeight), contentAlignment = Alignment.Center) {+            when {+                stage != null -> StageProgress(stage)+                isInstalled -> Text(+                    stringResource(R.string.installed),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.primary,+                )+                else -> RatingLabel(app)+            }+        }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.ktindex 2099935146..9549fb57b7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt@@ -23,6 +23,9 @@ import com.vayunmathur.appstore.data.ModernAppsRepo import com.vayunmathur.appstore.data.accrescent.AccrescentRepo import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.util.AppStoreViewModel+import com.vayunmathur.appstore.util.setAutoInstallUpdates+import com.vayunmathur.appstore.util.setSourceEnabled+import com.vayunmathur.appstore.util.syncSources import com.vayunmathur.library.ui.AppBarAlignment import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreActionOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreActionOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreActionOps.ktnew file mode 100644index 0000000000..96f9225f40--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreActionOps.kt@@ -0,0 +1,94 @@+package com.vayunmathur.appstore.util++import android.content.Intent+import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.PlayStoreLinks+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++// ---- Actions ----+// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.++internal fun AppStoreViewModel.installImpl(app: UnifiedApp) {+    viewModelScope.launch {+        val outcome = installer.install(app)+        AppMessages.show(+            when (val v = outcome.verification) {+                is VerificationResult.Rejected ->+                    context.getString(R.string.install_blocked, app.name, v.reason)+                is VerificationResult.Unverified ->+                    if (outcome.started) context.getString(R.string.install_started_unverified, app.name)+                    else context.getString(R.string.install_failed, app.name)+                is VerificationResult.Verified ->+                    if (outcome.started) context.getString(R.string.install_started, app.name)+                    else context.getString(R.string.install_failed, app.name)+            }+        )+        if (outcome.started) {+            // PackageInstaller commits asynchronously; give it a moment before the+            // installed list is re-read, or the row still shows the old version.+            delay(INSTALL_SETTLE_MS)+            installedRepo.refresh()+        }+    }+}++/**+ * Install the Sandboxed Google Play bundle in dependency order.+ *+ * Sequential and awaited, like [updateAll]: Play Services provides the provider Vending+ * talks to, so it must land first, and each first-time install shows its own+ * PackageInstaller confirmation - firing them at once would bury the user in prompts and+ * let the store client install before the services it needs.+ */+internal fun AppStoreViewModel.installSandboxedGooglePlayImpl() {+    viewModelScope.launch {+        for (app in _sandboxedGooglePlay.value) {+            installer.install(app)+        }+        delay(INSTALL_SETTLE_MS)+        installedRepo.refresh()+    }+}++internal fun AppStoreViewModel.openAppImpl(packageName: String) {+    val launchIntent = runCatching {+        context.packageManager.getLaunchIntentForPackage(packageName)+    }.getOrNull()+    if (launchIntent == null) {+        openInPlayStoreImpl(packageName)+        return+    }+    startActivity(launchIntent)+}++internal fun AppStoreViewModel.uninstallAppImpl(packageName: String) {+    val started = startActivity(+        Intent(Intent.ACTION_DELETE, "package:$packageName".toUri())+            .putExtra(Intent.EXTRA_RETURN_RESULT, true)+    )+    if (!started) AppMessages.show(context.getString(R.string.uninstaller_unavailable))+}++internal fun AppStoreViewModel.openInPlayStoreImpl(packageName: String) {+    if (startActivity(Intent(Intent.ACTION_VIEW, "market://details?id=$packageName".toUri()))) return+    startActivity(Intent(Intent.ACTION_VIEW, PlayStoreLinks.playStoreUrl(packageName).toUri()))+}++internal fun AppStoreViewModel.openInBrowserImpl(url: String) {+    if (url.isBlank()) return+    startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))+}++internal fun AppStoreViewModel.shareAppImpl(app: UnifiedApp) {+    val link = app.website ?: PlayStoreLinks.playStoreUrl(app.packageName)+    val share = Intent(Intent.ACTION_SEND).apply {+        type = "text/plain"+        putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_app_text, app.name, link))+    }+    startActivity(Intent.createChooser(share, null))+}
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.ktnew file mode 100644index 0000000000..cf1641708b--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreDetailOps.kt@@ -0,0 +1,94 @@+package com.vayunmathur.appstore.util++import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import kotlinx.coroutines.launch++// ---- Detail ----+// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.++fun AppStoreViewModel.selectApp(app: UnifiedApp) {+    detailJob?.cancel()+    _selectedApp.value = app+    detailJob = viewModelScope.launch {+        // Play lists the Sandboxed Google Play components too, so a search hit for one can+        // arrive carrying AppSource.PLAYSTORE. Describe it from GrapheneOS regardless: that+        // is the row an install would actually use, and the Play build is the wrong+        // artifact for the device even though Play would happily deliver it.+        sandboxedGooglePlayRow(app.packageName)?.let { sandboxed ->+            _selectedApp.value = sandboxed+            return@launch+        }+        // The catalogue row wins whenever there is one, even if the user tapped a Play+        // tile for the same package. It is the row an install would actually use — it+        // carries the signer and hash an authenticated index published — so showing+        // the Play listing here would describe a download this store is not going to+        // make. Only F-Droid and Modern Apps rows are ever cached, so this never+        // replaces one Play listing with another.+        val cached = catalog.byPackage(app.packageName)+        if (cached != null) {+            _selectedApp.value = cached+            return@launch+        }+        // Accrescent listings from the home carousel are shells (no version code, no signer+        // yet); fetch the full listing + package info + trust anchor before the page settles.+        if (app.source == AppSource.ACCRESCENT) {+            _isLoadingDetails.value = true+            val details = accrescent.details(app.packageName)+            if (details != null) _selectedApp.value = details+            _isLoadingDetails.value = false+            return@launch+        }+        // Play listings from a cluster are shells: no description, no+        // screenshots, no version code. Fill them in before the page settles.+        if (app.source == AppSource.PLAYSTORE && app.screenshots.isEmpty() &&+            AppSource.PLAYSTORE in enabledSources.value+        ) {+            _isLoadingDetails.value = true+            val details = play.details(app.packageName)+            if (details != null) _selectedApp.value = details+            _isLoadingDetails.value = false+        }+    }+}++/** Open a package the store only knows by name, e.g. from a `market://` link. */+fun AppStoreViewModel.selectPackage(packageName: String) {+    viewModelScope.launch {+        sandboxedGooglePlayRow(packageName)?.let {+            selectApp(it)+            return@launch+        }+        val known = catalog.byPackage(packageName)+        if (known != null) {+            selectApp(known)+            return@launch+        }+        _isLoadingDetails.value = true+        _selectedApp.value = UnifiedApp(+            packageName = packageName,+            source = AppSource.PLAYSTORE,+            name = packageName.substringAfterLast('.'),+        )+        if (AppSource.PLAYSTORE in enabledSources.value) {+            val details = play.details(packageName)+            if (details != null) _selectedApp.value = details+        }+        _isLoadingDetails.value = false+    }+}++fun AppStoreViewModel.clearSelection() {+    detailJob?.cancel()+    _selectedApp.value = null+}++/**+ * The GrapheneOS row for a Sandboxed Google Play component, or null for any other package.+ *+ * Carries whatever [loadHome] enriched the stand-in with, so this is the best row the store+ * holds for GSF, GMS or Vending.+ */+internal fun AppStoreViewModel.sandboxedGooglePlayRow(packageName: String): UnifiedApp? =+    _sandboxedGooglePlay.value.firstOrNull { it.packageName == packageName }
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.ktnew file mode 100644index 0000000000..f53a667f44--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt@@ -0,0 +1,193 @@+package com.vayunmathur.appstore.util++import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.DefaultRepos+import com.vayunmathur.appstore.data.SandboxedGooglePlay+import com.vayunmathur.appstore.data.SyncStep+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.grapheneos.toUnifiedApp+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.launch++// ---- Home ----+// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.++/**+ * Fill the home screen.+ *+ * The offline rows come straight from Room and are already on screen by the time this+ * runs; what it adds is Play's editorial clusters and top chart, which need an+ * anonymous account. Those failing is normal — no network, no account — and leaves the+ * offline rows exactly as they were rather than emptying the screen.+ */+internal suspend fun AppStoreViewModel.loadHome(enabled: Set<AppSource> = enabledSources.value) {+    _isLoadingHome.value = true+    _recentlyUpdated.value = catalog.recentlyUpdated(RECENT_LIMIT)++    // The Sandboxed Google Play components come from GrapheneOS's release server, not+    // Play. Refreshing its signed index is what turns the stand-ins into installable+    // rows: the version, file list, signer digests and per-APK hashes all come from+    // there. A failed refresh leaves the stand-ins, and the section, exactly as they were.+    if (_sandboxedGooglePlay.value.isNotEmpty()) {+        grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull()?.let { packages ->+            val byPackage = packages.associateBy { it.packageName }+            _sandboxedGooglePlay.value = _sandboxedGooglePlay.value.map { row ->+                byPackage[row.packageName]?.toUnifiedApp() ?: row+            }+        }+    }++    if (AppSource.PLAYSTORE !in enabled) {+        _isLoadingHome.value = false+        return+    }++    val clusters = play.homeClusters()+    _playSections.value = clusters+        .filter { it.apps.isNotEmpty() }+        .take(PLAY_CLUSTER_LIMIT)+        .map { AppSection("play-${it.title}", it.title, it.apps.take(CAROUSEL_LIMIT)) }++    if (_playSections.value.isEmpty()) {+        // No account, or Play changed its stream shape. A top chart is one request and+        // still gives the screen something beyond this repo's own dozen apps.+        val chart = play.topChart()+        if (chart.isNotEmpty()) {+            _playSections.value = listOf(+                AppSection(+                    id = "play-top",+                    title = context.getString(R.string.section_play_top_charts),+                    apps = chart.take(CAROUSEL_LIMIT),+                )+            )+        }+    }+    _isLoadingHome.value = false+}++internal fun AppStoreViewModel.buildSections(+    modern: List<UnifiedApp>,+    playSections: List<AppSection>,+    recent: List<UnifiedApp>,+    sandboxed: List<UnifiedApp>,+    accrescent: List<UnifiedApp>,+    categoryApps: List<UnifiedApp>,+    category: String?,+): List<AppSection> = buildList {+    // A chosen category replaces the browsing rows: the user asked a narrow question+    // and a wall of unrelated carousels underneath it is just noise.+    if (category != null) {+        add(+            AppSection(+                id = "category",+                title = category,+                apps = categoryApps,+                layout = SectionLayout.LIST,+                subtitle = context.getString(R.string.section_category_subtitle),+            )+        )+        return@buildList+    }+    if (modern.isNotEmpty()) {+        add(+            AppSection(+                id = "modern",+                title = context.getString(R.string.section_modern_apps),+                apps = modern,+                subtitle = context.getString(R.string.section_modern_apps_subtitle),+            )+        )+    }+    if (sandboxed.isNotEmpty()) {+        add(+            AppSection(+                id = SandboxedGooglePlay.SECTION_ID,+                title = context.getString(R.string.section_sandboxed_google_play),+                apps = sandboxed,+                subtitle = context.getString(R.string.section_sandboxed_google_play_subtitle),+            )+        )+    }+    addAll(playSections)+    if (accrescent.isNotEmpty()) {+        add(+            AppSection(+                id = "accrescent",+                title = context.getString(R.string.section_accrescent),+                apps = accrescent,+                subtitle = context.getString(R.string.section_accrescent_subtitle),+            )+        )+    }+    if (recent.isNotEmpty()) {+        add(+            AppSection(+                id = "recent",+                title = context.getString(R.string.section_recently_updated),+                apps = recent,+                subtitle = context.getString(R.string.section_recently_updated_subtitle),+            )+        )+    }+}++/**+ * Populate the offline catalogues the first time the store is opened.+ *+ * Nothing else fetches them on startup: [loadHome] only refreshes GrapheneOS's index, and+ * the periodic [com.vayunmathur.appstore.work.UpdateCheckWorker] may be hours away. That+ * left a fresh install showing an empty store until the user thought to pull to refresh.+ *+ * Keyed off the catalogue being empty rather than a "first run" flag, so it also recovers+ * a store whose first sync failed or whose data was cleared - and so it stays quiet on+ * every later launch, when re-fetching two full catalogues on the user's connection would+ * be a poor trade for data that is at most a few hours stale.+ */+internal fun AppStoreViewModel.syncIfNeverSynced(enabled: Set<AppSource>) {+    if (_recentlyUpdated.value.isNotEmpty()) return+    // Nothing to fetch if both offline sources are switched off; syncSources() would only+    // report "all sources off" at someone who never asked for a sync.+    val offlineSources = setOf(DefaultRepos.FDROID.source, DefaultRepos.MODERN_APPS.source)+    if (enabled.intersect(offlineSources).isEmpty()) return+    syncSources()+}++/** Re-download both offline catalogues, then reload the home rows from them. */+fun AppStoreViewModel.syncSources() {+    if (_isSyncing.value) return+    viewModelScope.launch {+        val enabled = enabledSources.value+        _isSyncing.value = true+        val report = catalog.sync(enabled) { step ->+            _statusMessage.value = context.getString(+                when (step) {+                    SyncStep.FDROID -> R.string.sync_step_fdroid+                    SyncStep.MODERN_APPS -> R.string.sync_step_modern_apps+                }+            )+        }+        _statusMessage.value = ""+        _isSyncing.value = false++        AppMessages.show(+            when {+                report.allSkipped -> context.getString(R.string.sync_all_sources_off)+                !report.anyFailed -> context.getString(+                    R.string.sync_done,+                    (report.fdroidCount ?: 0) + (report.modernCount ?: 0),+                )+                report.fdroidCount == null && report.modernCount == null ->+                    context.getString(R.string.sync_failed_all)+                report.fdroidCount == null -> context.getString(R.string.sync_failed_fdroid)+                else -> context.getString(R.string.sync_failed_modern_apps)+            }+        )++        _categories.value = catalog.categories()+        loadHome(enabled)+        loadAccrescent(enabled)+        installedRepo.refresh()+    }+}
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreSearchOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreSearchOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreSearchOps.ktnew file mode 100644index 0000000000..b468bb8350--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreSearchOps.kt@@ -0,0 +1,63 @@+package com.vayunmathur.appstore.util++import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.priority+import com.vayunmathur.appstore.data.searchCandidate+import com.vayunmathur.appstore.domain.SearchRanking+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++// ---- Search ----+// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.++internal fun AppStoreViewModel.setSearchImpl(query: String) {+    _query.value = query+    searchJob?.cancel()+    if (query.isBlank()) {+        _searchResults.value = emptyList()+        _hasSearched.value = false+        _isSearching.value = false+        return+    }+    searchJob = viewModelScope.launch {+        delay(SEARCH_DEBOUNCE_MS)+        _isSearching.value = true+        val enabled = enabledSources.value++        // Local first and published immediately: the F-Droid catalogue is on disk, so+        // there is no reason to make the user wait on Play before seeing anything.+        val local = catalog.searchLocal(query)+        _searchResults.value = rank(local, query)++        // Accrescent search is client-side over the listings already cached from the home+        // carousel (its API has no search RPC), so it adds no network round-trip here.+        val accrescentResults =+            if (AppSource.ACCRESCENT in enabled) accrescent.search(query) else emptyList()+        val remote = if (AppSource.PLAYSTORE in enabled) play.search(query) else emptyList()+        _searchResults.value = rank(merge(local, remote, accrescentResults), query)+        _isSearching.value = false+        _hasSearched.value = true+    }+}++/**+ * Combine catalogue, Play and Accrescent hits, one row per package.+ *+ * Where several sources offer a package, [AppSource.PRIORITY] decides which row survives —+ * notably keeping the GrapheneOS row for the Sandboxed Google Play components rather than+ * Play's listing of the same three packages. Sorting is stable, so each source's own+ * relevance ordering is preserved within its rank, and [rank] re-sorts the result anyway.+ */+internal fun AppStoreViewModel.merge(vararg lists: List<UnifiedApp>): List<UnifiedApp> =+    lists.asSequence()+        .flatten()+        .sortedBy { it.source.priority }+        .distinctBy { it.packageName }+        .toList()++/** See [SearchRanking]: exact and prefix hits first, and nothing that answers no word. */+internal fun AppStoreViewModel.rank(apps: List<UnifiedApp>, query: String): List<UnifiedApp> =+    SearchRanking.rank(apps, query) { it.searchCandidate() }
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUpdateOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUpdateOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUpdateOps.ktnew file mode 100644index 0000000000..dcbec74a3b--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUpdateOps.kt@@ -0,0 +1,185 @@+package com.vayunmathur.appstore.util++import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.SandboxedGooglePlay+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.grapheneos.toUnifiedApp+import com.vayunmathur.appstore.data.installer.InstallFailureBatch+import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++// ---- Updates ----+// Moved from AppStoreViewModel.kt (FileLength split); behavior identical.++internal fun AppStoreViewModel.checkForUpdatesImpl() {+    if (_isCheckingUpdates.value) return+    viewModelScope.launch {+        val enabled = enabledSources.value+        _isCheckingUpdates.value = true+        _statusMessage.value = context.getString(R.string.updates_checking)++        installedRepo.refresh()+        _catalogUpdates.value = catalog.updatesFor(installedRepo.updatable.value)++        // Only ask Play about packages neither offline source lists — for the rest the+        // catalogue already answered, and Play would just re-answer it over the network.+        // The Sandboxed Google Play components are held back too: Play hosts newer builds+        // of all three, but only GrapheneOS's are the ones this device can use, so their+        // updates come from its signed index below instead.+        val index = catalog.packageIndex.value+        val installed = installedRepo.updatable.value+        if (AppSource.PLAYSTORE in enabled) {+            val playCandidates = installed+                .filter {+                    it.packageName !in index &&+                        it.packageName !in SandboxedGooglePlay.PACKAGES+                }+                .map { it.packageName }++            val remote = play.details(playCandidates).associateBy { it.packageName }+            _playUpdates.value = installed.mapNotNull { inst ->+                remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }+            }+            // The same response tells us which of these packages Play actually hosts, which+            // the library uses to tell a genuine Play app from a sideloaded one.+            if (remote.isNotEmpty()) _playInstalledPackages.value = remote.keys.toSet()+        }++        // Accrescent: refresh the signed allowlist, then ask its API for a newer build of+        // each installed package it vouches for.+        if (AppSource.ACCRESCENT in enabled) {+            accrescent.refreshRepoData()+            val accrescentIds = accrescent.appIds()+            if (accrescentIds.isNotEmpty()) _accrescentPackages.value = accrescentIds+            _accrescentUpdates.value = installed+                .filter { it.packageName in accrescentIds }+                .mapNotNull { inst -> accrescentUpdate(inst.packageName, inst.versionCode) }+        }++        // GrapheneOS: its signed index is the only place a Sandboxed Google Play update+        // can come from, which is why the three are held back from the Play list above.+        _grapheneOSUpdates.value = grapheneOS.packages.mapNotNull { entry ->+            val current = installed.firstOrNull { it.packageName == entry.packageName }+                ?: return@mapNotNull null+            entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }+        }++        _lastUpdateCheck.value = System.currentTimeMillis()+        _statusMessage.value = ""+        _isCheckingUpdates.value = false+    }+}++/**+ * Update everything, and report the run once when it is over.+ *+ * Sequential on purpose: updates this store isn't the update owner of still get a+ * system confirmation dialog, and firing them concurrently buries the user in prompts.+ *+ * The reporting is the other half of issue #630. A run used to say nothing itself and+ * let each app's failure raise its own snackbar, so a phone whose updates were all+ * failing the same way — Play refusing the lot for going too fast, typically — showed+ * the user the same error once per app. Now the failures are collected and summarised,+ * and a reason that keeps coming back ends the run rather than being demonstrated+ * another dozen times.+ */+internal fun AppStoreViewModel.updateAllImpl() {+    if (updateAllJob?.isActive == true) return+    updateAllJob = viewModelScope.launch {+        val batch = updates.value+        if (batch.isEmpty()) return@launch+        val failures = mutableListOf<String>()+        var started = 0+        var repeats = 0+        var previousReason: String? = null+        InstallFailureBatch.begin()+        try {+            for ((index, app) in batch.withIndex()) {+                _statusMessage.value = context.getString(+                    R.string.updates_progress, app.name, index + 1, batch.size+                )+                val outcome = installer.install(app)+                if (outcome.started) {+                    started+++                    previousReason = null+                    repeats = 0+                    continue+                }+                val reason = outcome.verification.reason()+                failures += reason+                repeats = if (reason == previousReason) repeats + 1 else 1+                previousReason = reason+                if (repeats >= REPEATED_FAILURE_LIMIT) break+            }+            // PackageInstaller commits asynchronously, so the last app's real verdict+            // is still on its way. Wait for it before summarising, or it lands on its+            // own afterwards — which is the repetition this is here to stop.+            delay(INSTALL_SETTLE_MS)+        } finally {+            _statusMessage.value = ""+            failures += InstallFailureBatch.end()+        }++        AppMessages.show(+            if (failures.isEmpty()) {+                context.resources.getQuantityString(+                    R.plurals.updates_batch_installed, started, started+                )+            } else {+                context.getString(+                    R.string.updates_batch_partial,+                    started,+                    batch.size,+                    failures.first(),+                )+            },+            duration = if (failures.isEmpty()) {+                AppMessages.Duration.Short+            } else {+                AppMessages.Duration.Long+            },+        )+        installedRepo.refresh()+    }+}++/** What to tell the user a failed install went wrong with. */+internal fun AppStoreViewModel.reason(verification: VerificationResult): String = when (verification) {+    is VerificationResult.Rejected -> verification.reason+    is VerificationResult.Unverified -> verification.reason+    is VerificationResult.Verified -> context.getString(R.string.install_failure_unknown)+}++/**+ * The available Accrescent update for [packageName] as an installable listing, or null when+ * there is none. The version code is the update's, so the [updates] filter keeps it only+ * while it is genuinely newer than what is installed.+ */+internal suspend fun AppStoreViewModel.accrescentUpdate(packageName: String, currentVersionCode: Long): UnifiedApp? {+    val update = runCatching {+        accrescent.updateInfo(packageName, currentVersionCode)+    }.getOrNull() ?: return null+    val details = accrescent.details(packageName) ?: UnifiedApp(+        packageName = packageName,+        source = AppSource.ACCRESCENT,+        name = packageName.substringAfterLast('.'),+    )+    return details.copy(versionCode = update.versionCode, versionName = update.versionName)+}++/**+ * Refresh Accrescent's signed allowlist and its home listings. Both fail soft: a network+ * blip leaves the previous rows and attribution set in place rather than emptying them.+ */+internal suspend fun AppStoreViewModel.loadAccrescent(enabled: Set<AppSource> = enabledSources.value) {+    if (AppSource.ACCRESCENT !in enabled) return+    accrescent.refreshRepoData()+    val ids = accrescent.appIds()+    if (ids.isNotEmpty()) _accrescentPackages.value = ids+    val page = accrescent.listApps()+    if (page.apps.isNotEmpty()) _accrescentApps.value = page.apps.take(CAROUSEL_LIMIT)+}
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex 0fdabc7e98..0e98fbe13a 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -55,17 +55,17 @@ import kotlinx.coroutines.launch  * their flows into per-screen state and turning taps into calls.  */ class AppStoreViewModel(-    private val context: Application,+    internal val context: Application,     db: AppDatabase, ) : ViewModel(), HomeActions, SearchActions, AppDetailActions, UpdatesActions, LibraryActions { -    private val catalog = CatalogRepository(context, db, viewModelScope)-    private val play = PlayRepository(context)-    private val accrescent = AccrescentRepository(context, db)-    private val grapheneOS = GrapheneOSRepository(context)-    private val installedRepo = InstalledAppsRepository(context)-    private val settings = SettingsRepository(context, viewModelScope)-    private val installer =+    internal val catalog = CatalogRepository(context, db, viewModelScope)+    internal val play = PlayRepository(context)+    internal val accrescent = AccrescentRepository(context, db)+    internal val grapheneOS = GrapheneOSRepository(context)+    internal val installedRepo = InstalledAppsRepository(context)+    internal val settings = SettingsRepository(context, viewModelScope)+    internal val installer =         InstallCoordinator(context, db, play, accrescent, grapheneOS) { ownSigningCertificates }      /** Off-by-default: the periodic check may also download and install updates unattended. */@@ -81,26 +81,26 @@ class AppStoreViewModel(      // --- Raw state ------------------------------------------------------------------ -    private val _statusMessage = MutableStateFlow("")+    internal val _statusMessage = MutableStateFlow("")      /** Kept apart from [_statusMessage] so a transient sync line can't erase it. */     private val _playError = MutableStateFlow("")-    private val _isSyncing = MutableStateFlow(false)-    private val _isLoadingHome = MutableStateFlow(false)-    private val _isCheckingUpdates = MutableStateFlow(false)-    private val _lastUpdateCheck = MutableStateFlow(0L)+    internal val _isSyncing = MutableStateFlow(false)+    internal val _isLoadingHome = MutableStateFlow(false)+    internal val _isCheckingUpdates = MutableStateFlow(false)+    internal val _lastUpdateCheck = MutableStateFlow(0L) -    private val _playSections = MutableStateFlow<List<AppSection>>(emptyList())-    private val _recentlyUpdated = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _playSections = MutableStateFlow<List<AppSection>>(emptyList())+    internal val _recentlyUpdated = MutableStateFlow<List<UnifiedApp>>(emptyList())      /** Accrescent listings for the home carousel, from the gRPC listing API. */-    private val _accrescentApps = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _accrescentApps = MutableStateFlow<List<UnifiedApp>>(emptyList())      /**      * App ids Accrescent's signed allowlist vouches for. Drives library attribution for an      * installed Accrescent app. Empty until the first repodata refresh populates it.      */-    private val _accrescentPackages = MutableStateFlow<Set<String>>(emptySet())+    internal val _accrescentPackages = MutableStateFlow<Set<String>>(emptySet())      /**      * The Sandboxed Google Play bundle rows. Seeded with stand-ins so the section is on@@ -112,27 +112,27 @@ class AppStoreViewModel(      * is part of the OS, so on a device without it the section would offer three installs      * that cannot function.      */-    private val _sandboxedGooglePlay = MutableStateFlow(+    internal val _sandboxedGooglePlay = MutableStateFlow(         if (RestrictedPackages.isGrapheneOS(context)) SandboxedGooglePlay.placeholders()         else emptyList()     )-    private val _categories = MutableStateFlow<List<String>>(emptyList())-    private val _selectedCategory = MutableStateFlow<String?>(null)-    private val _categoryApps = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _categories = MutableStateFlow<List<String>>(emptyList())+    internal val _selectedCategory = MutableStateFlow<String?>(null)+    internal val _categoryApps = MutableStateFlow<List<UnifiedApp>>(emptyList()) -    private val _query = MutableStateFlow("")-    private val _searchResults = MutableStateFlow<List<UnifiedApp>>(emptyList())-    private val _searchFilter = MutableStateFlow(SourceFilter.ALL)-    private val _isSearching = MutableStateFlow(false)-    private val _hasSearched = MutableStateFlow(false)+    internal val _query = MutableStateFlow("")+    internal val _searchResults = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _searchFilter = MutableStateFlow(SourceFilter.ALL)+    internal val _isSearching = MutableStateFlow(false)+    internal val _hasSearched = MutableStateFlow(false) -    private val _selectedApp = MutableStateFlow<UnifiedApp?>(null)-    private val _isLoadingDetails = MutableStateFlow(false)+    internal val _selectedApp = MutableStateFlow<UnifiedApp?>(null)+    internal val _isLoadingDetails = MutableStateFlow(false) -    private val _catalogUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())-    private val _playUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())-    private val _accrescentUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())-    private val _grapheneOSUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _catalogUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _playUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _accrescentUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+    internal val _grapheneOSUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())      private val _libraryFilter = MutableStateFlow(SourceFilter.ALL) @@ -144,11 +144,11 @@ class AppStoreViewModel(      * stays out of the library until Play vouches for it. A failed lookup leaves the      * previous answer in place rather than emptying it — see [refreshPlayInstalledPackages].      */-    private val _playInstalledPackages = MutableStateFlow<Set<String>>(emptySet())+    internal val _playInstalledPackages = MutableStateFlow<Set<String>>(emptySet()) -    private var searchJob: Job? = null-    private var detailJob: Job? = null-    private var updateAllJob: Job? = null+    internal var searchJob: Job? = null+    internal var detailJob: Job? = null+    internal var updateAllJob: Job? = null      // --- Derived state ---------------------------------------------------------------- @@ -408,156 +408,10 @@ class AppStoreViewModel(         if (available.isNotEmpty()) _playInstalledPackages.value = available     } -    /**-     * Refresh Accrescent's signed allowlist and its home listings. Both fail soft: a network-     * blip leaves the previous rows and attribution set in place rather than emptying them.-     */-    private suspend fun loadAccrescent(enabled: Set<AppSource> = enabledSources.value) {-        if (AppSource.ACCRESCENT !in enabled) return-        accrescent.refreshRepoData()-        val ids = accrescent.appIds()-        if (ids.isNotEmpty()) _accrescentPackages.value = ids-        val page = accrescent.listApps()-        if (page.apps.isNotEmpty()) _accrescentApps.value = page.apps.take(CAROUSEL_LIMIT)-    }--    /**-     * The available Accrescent update for [packageName] as an installable listing, or null when-     * there is none. The version code is the update's, so the [updates] filter keeps it only-     * while it is genuinely newer than what is installed.-     */-    private suspend fun accrescentUpdate(packageName: String, currentVersionCode: Long): UnifiedApp? {-        val update = runCatching {-            accrescent.updateInfo(packageName, currentVersionCode)-        }.getOrNull() ?: return null-        val details = accrescent.details(packageName) ?: UnifiedApp(-            packageName = packageName,-            source = AppSource.ACCRESCENT,-            name = packageName.substringAfterLast('.'),-        )-        return details.copy(versionCode = update.versionCode, versionName = update.versionName)-    }+    // (loadAccrescent/accrescentUpdate live in AppStoreUpdateOps.kt.)      // --- Home -----------------------------------------------------------------------    /**-     * Fill the home screen.-     *-     * The offline rows come straight from Room and are already on screen by the time this-     * runs; what it adds is Play's editorial clusters and top chart, which need an-     * anonymous account. Those failing is normal — no network, no account — and leaves the-     * offline rows exactly as they were rather than emptying the screen.-     */-    private suspend fun loadHome(enabled: Set<AppSource> = enabledSources.value) {-        _isLoadingHome.value = true-        _recentlyUpdated.value = catalog.recentlyUpdated(RECENT_LIMIT)--        // The Sandboxed Google Play components come from GrapheneOS's release server, not-        // Play. Refreshing its signed index is what turns the stand-ins into installable-        // rows: the version, file list, signer digests and per-APK hashes all come from-        // there. A failed refresh leaves the stand-ins, and the section, exactly as they were.-        if (_sandboxedGooglePlay.value.isNotEmpty()) {-            grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull()?.let { packages ->-                val byPackage = packages.associateBy { it.packageName }-                _sandboxedGooglePlay.value = _sandboxedGooglePlay.value.map { row ->-                    byPackage[row.packageName]?.toUnifiedApp() ?: row-                }-            }-        }--        if (AppSource.PLAYSTORE !in enabled) {-            _isLoadingHome.value = false-            return-        }--        val clusters = play.homeClusters()-        _playSections.value = clusters-            .filter { it.apps.isNotEmpty() }-            .take(PLAY_CLUSTER_LIMIT)-            .map { AppSection("play-${it.title}", it.title, it.apps.take(CAROUSEL_LIMIT)) }--        if (_playSections.value.isEmpty()) {-            // No account, or Play changed its stream shape. A top chart is one request and-            // still gives the screen something beyond this repo's own dozen apps.-            val chart = play.topChart()-            if (chart.isNotEmpty()) {-                _playSections.value = listOf(-                    AppSection(-                        id = "play-top",-                        title = context.getString(R.string.section_play_top_charts),-                        apps = chart.take(CAROUSEL_LIMIT),-                    )-                )-            }-        }-        _isLoadingHome.value = false-    }--    private fun buildSections(-        modern: List<UnifiedApp>,-        playSections: List<AppSection>,-        recent: List<UnifiedApp>,-        sandboxed: List<UnifiedApp>,-        accrescent: List<UnifiedApp>,-        categoryApps: List<UnifiedApp>,-        category: String?,-    ): List<AppSection> = buildList {-        // A chosen category replaces the browsing rows: the user asked a narrow question-        // and a wall of unrelated carousels underneath it is just noise.-        if (category != null) {-            add(-                AppSection(-                    id = "category",-                    title = category,-                    apps = categoryApps,-                    layout = SectionLayout.LIST,-                    subtitle = context.getString(R.string.section_category_subtitle),-                )-            )-            return@buildList-        }-        if (modern.isNotEmpty()) {-            add(-                AppSection(-                    id = "modern",-                    title = context.getString(R.string.section_modern_apps),-                    apps = modern,-                    subtitle = context.getString(R.string.section_modern_apps_subtitle),-                )-            )-        }-        if (sandboxed.isNotEmpty()) {-            add(-                AppSection(-                    id = SandboxedGooglePlay.SECTION_ID,-                    title = context.getString(R.string.section_sandboxed_google_play),-                    apps = sandboxed,-                    subtitle = context.getString(R.string.section_sandboxed_google_play_subtitle),-                )-            )-        }-        addAll(playSections)-        if (accrescent.isNotEmpty()) {-            add(-                AppSection(-                    id = "accrescent",-                    title = context.getString(R.string.section_accrescent),-                    apps = accrescent,-                    subtitle = context.getString(R.string.section_accrescent_subtitle),-                )-            )-        }-        if (recent.isNotEmpty()) {-            add(-                AppSection(-                    id = "recent",-                    title = context.getString(R.string.section_recently_updated),-                    apps = recent,-                    subtitle = context.getString(R.string.section_recently_updated_subtitle),-                )-            )-        }-    }+    // Implementations live in AppStoreHomeOps.kt.      override fun selectCategory(category: String?) {         _selectedCategory.value = category@@ -568,64 +422,8 @@ class AppStoreViewModel(      override fun refresh() = syncSources() -    /**-     * Populate the offline catalogues the first time the store is opened.-     *-     * Nothing else fetches them on startup: [loadHome] only refreshes GrapheneOS's index, and-     * the periodic [com.vayunmathur.appstore.work.UpdateCheckWorker] may be hours away. That-     * left a fresh install showing an empty store until the user thought to pull to refresh.-     *-     * Keyed off the catalogue being empty rather than a "first run" flag, so it also recovers-     * a store whose first sync failed or whose data was cleared - and so it stays quiet on-     * every later launch, when re-fetching two full catalogues on the user's connection would-     * be a poor trade for data that is at most a few hours stale.-     */-    private fun syncIfNeverSynced(enabled: Set<AppSource>) {-        if (_recentlyUpdated.value.isNotEmpty()) return-        // Nothing to fetch if both offline sources are switched off; syncSources() would only-        // report "all sources off" at someone who never asked for a sync.-        val offlineSources = setOf(DefaultRepos.FDROID.source, DefaultRepos.MODERN_APPS.source)-        if (enabled.intersect(offlineSources).isEmpty()) return-        syncSources()-    }-     /** Re-download both offline catalogues, then reload the home rows from them. */-    fun syncSources() {-        if (_isSyncing.value) return-        viewModelScope.launch {-            val enabled = enabledSources.value-            _isSyncing.value = true-            val report = catalog.sync(enabled) { step ->-                _statusMessage.value = context.getString(-                    when (step) {-                        SyncStep.FDROID -> R.string.sync_step_fdroid-                        SyncStep.MODERN_APPS -> R.string.sync_step_modern_apps-                    }-                )-            }-            _statusMessage.value = ""-            _isSyncing.value = false--            AppMessages.show(-                when {-                    report.allSkipped -> context.getString(R.string.sync_all_sources_off)-                    !report.anyFailed -> context.getString(-                        R.string.sync_done,-                        (report.fdroidCount ?: 0) + (report.modernCount ?: 0),-                    )-                    report.fdroidCount == null && report.modernCount == null ->-                        context.getString(R.string.sync_failed_all)-                    report.fdroidCount == null -> context.getString(R.string.sync_failed_fdroid)-                    else -> context.getString(R.string.sync_failed_modern_apps)-                }-            )--            _categories.value = catalog.categories()-            loadHome(enabled)-            loadAccrescent(enabled)-            installedRepo.refresh()-        }-    }+    // Implemented in AppStoreHomeOps.kt as a public extension (called from SourcesPage).      /**      * Turn a source on or off, and make the rest of the store agree immediately.@@ -671,172 +469,22 @@ class AppStoreViewModel(     }      // --- Search -----------------------------------------------------------------------+    // Bodies live in AppStoreSearchOps.kt; these overrides keep interface conformance. -    override fun setSearch(query: String) {-        _query.value = query-        searchJob?.cancel()-        if (query.isBlank()) {-            _searchResults.value = emptyList()-            _hasSearched.value = false-            _isSearching.value = false-            return-        }-        searchJob = viewModelScope.launch {-            delay(SEARCH_DEBOUNCE_MS)-            _isSearching.value = true-            val enabled = enabledSources.value--            // Local first and published immediately: the F-Droid catalogue is on disk, so-            // there is no reason to make the user wait on Play before seeing anything.-            val local = catalog.searchLocal(query)-            _searchResults.value = rank(local, query)--            // Accrescent search is client-side over the listings already cached from the home-            // carousel (its API has no search RPC), so it adds no network round-trip here.-            val accrescentResults =-                if (AppSource.ACCRESCENT in enabled) accrescent.search(query) else emptyList()-            val remote = if (AppSource.PLAYSTORE in enabled) play.search(query) else emptyList()-            _searchResults.value = rank(merge(local, remote, accrescentResults), query)-            _isSearching.value = false-            _hasSearched.value = true-        }-    }+    override fun setSearch(query: String) = setSearchImpl(query)      override fun setSearchFilter(filter: SourceFilter) {         _searchFilter.value = filter     } -    /**-     * Combine catalogue, Play and Accrescent hits, one row per package.-     *-     * Where several sources offer a package, [AppSource.PRIORITY] decides which row survives —-     * notably keeping the GrapheneOS row for the Sandboxed Google Play components rather than-     * Play's listing of the same three packages. Sorting is stable, so each source's own-     * relevance ordering is preserved within its rank, and [rank] re-sorts the result anyway.-     */-    private fun merge(vararg lists: List<UnifiedApp>): List<UnifiedApp> =-        lists.asSequence()-            .flatten()-            .sortedBy { it.source.priority }-            .distinctBy { it.packageName }-            .toList()--    /** See [SearchRanking]: exact and prefix hits first, and nothing that answers no word. */-    private fun rank(apps: List<UnifiedApp>, query: String): List<UnifiedApp> =-        SearchRanking.rank(apps, query) { it.searchCandidate() }-     // --- Detail -------------------------------------------------------------------------    fun selectApp(app: UnifiedApp) {-        detailJob?.cancel()-        _selectedApp.value = app-        detailJob = viewModelScope.launch {-            // Play lists the Sandboxed Google Play components too, so a search hit for one can-            // arrive carrying AppSource.PLAYSTORE. Describe it from GrapheneOS regardless: that-            // is the row an install would actually use, and the Play build is the wrong-            // artifact for the device even though Play would happily deliver it.-            sandboxedGooglePlayRow(app.packageName)?.let { sandboxed ->-                _selectedApp.value = sandboxed-                return@launch-            }-            // The catalogue row wins whenever there is one, even if the user tapped a Play-            // tile for the same package. It is the row an install would actually use — it-            // carries the signer and hash an authenticated index published — so showing-            // the Play listing here would describe a download this store is not going to-            // make. Only F-Droid and Modern Apps rows are ever cached, so this never-            // replaces one Play listing with another.-            val cached = catalog.byPackage(app.packageName)-            if (cached != null) {-                _selectedApp.value = cached-                return@launch-            }-            // Accrescent listings from the home carousel are shells (no version code, no signer-            // yet); fetch the full listing + package info + trust anchor before the page settles.-            if (app.source == AppSource.ACCRESCENT) {-                _isLoadingDetails.value = true-                val details = accrescent.details(app.packageName)-                if (details != null) _selectedApp.value = details-                _isLoadingDetails.value = false-                return@launch-            }-            // Play listings from a cluster are shells: no description, no-            // screenshots, no version code. Fill them in before the page settles.-            if (app.source == AppSource.PLAYSTORE && app.screenshots.isEmpty() &&-                AppSource.PLAYSTORE in enabledSources.value-            ) {-                _isLoadingDetails.value = true-                val details = play.details(app.packageName)-                if (details != null) _selectedApp.value = details-                _isLoadingDetails.value = false-            }-        }-    }--    /** Open a package the store only knows by name, e.g. from a `market://` link. */-    fun selectPackage(packageName: String) {-        viewModelScope.launch {-            sandboxedGooglePlayRow(packageName)?.let {-                selectApp(it)-                return@launch-            }-            val known = catalog.byPackage(packageName)-            if (known != null) {-                selectApp(known)-                return@launch-            }-            _isLoadingDetails.value = true-            _selectedApp.value = UnifiedApp(-                packageName = packageName,-                source = AppSource.PLAYSTORE,-                name = packageName.substringAfterLast('.'),-            )-            if (AppSource.PLAYSTORE in enabledSources.value) {-                val details = play.details(packageName)-                if (details != null) _selectedApp.value = details-            }-            _isLoadingDetails.value = false-        }-    }--    fun clearSelection() {-        detailJob?.cancel()-        _selectedApp.value = null-    }--    /**-     * The GrapheneOS row for a Sandboxed Google Play component, or null for any other package.-     *-     * Carries whatever [loadHome] enriched the stand-in with, so this is the best row the store-     * holds for GSF, GMS or Vending.-     */-    private fun sandboxedGooglePlayRow(packageName: String): UnifiedApp? =-        _sandboxedGooglePlay.value.firstOrNull { it.packageName == packageName }+    // Bodies live in AppStoreDetailOps.kt as public extensions+    // (called from MainActivity + AppDetailPage via the concrete class).      // --- Actions ----------------------------------------------------------------------+    // Bodies live in AppStoreActionOps.kt; these overrides keep interface conformance. -    override fun install(app: UnifiedApp) {-        viewModelScope.launch {-            val outcome = installer.install(app)-            AppMessages.show(-                when (val v = outcome.verification) {-                    is VerificationResult.Rejected ->-                        context.getString(R.string.install_blocked, app.name, v.reason)-                    is VerificationResult.Unverified ->-                        if (outcome.started) context.getString(R.string.install_started_unverified, app.name)-                        else context.getString(R.string.install_failed, app.name)-                    is VerificationResult.Verified ->-                        if (outcome.started) context.getString(R.string.install_started, app.name)-                        else context.getString(R.string.install_failed, app.name)-                }-            )-            if (outcome.started) {-                // PackageInstaller commits asynchronously; give it a moment before the-                // installed list is re-read, or the row still shows the old version.-                delay(INSTALL_SETTLE_MS)-                installedRepo.refresh()-            }-        }-    }+    override fun install(app: UnifiedApp) = installImpl(app)      override fun dismissInstallFailure(packageName: String) = installer.dismissFailure(packageName) @@ -848,114 +496,22 @@ class AppStoreViewModel(      * PackageInstaller confirmation - firing them at once would bury the user in prompts and      * let the store client install before the services it needs.      */-    override fun installSandboxedGooglePlay() {-        viewModelScope.launch {-            for (app in _sandboxedGooglePlay.value) {-                installer.install(app)-            }-            delay(INSTALL_SETTLE_MS)-            installedRepo.refresh()-        }-    }+    override fun installSandboxedGooglePlay() = installSandboxedGooglePlayImpl() -    override fun openApp(packageName: String) {-        val launchIntent = runCatching {-            context.packageManager.getLaunchIntentForPackage(packageName)-        }.getOrNull()-        if (launchIntent == null) {-            openInPlayStore(packageName)-            return-        }-        startActivity(launchIntent)-    }+    override fun openApp(packageName: String) = openAppImpl(packageName) -    override fun uninstallApp(packageName: String) {-        val started = startActivity(-            Intent(Intent.ACTION_DELETE, "package:$packageName".toUri())-                .putExtra(Intent.EXTRA_RETURN_RESULT, true)-        )-        if (!started) AppMessages.show(context.getString(R.string.uninstaller_unavailable))-    }+    override fun uninstallApp(packageName: String) = uninstallAppImpl(packageName) -    override fun openInPlayStore(packageName: String) {-        if (startActivity(Intent(Intent.ACTION_VIEW, "market://details?id=$packageName".toUri()))) return-        startActivity(Intent(Intent.ACTION_VIEW, PlayStoreLinks.playStoreUrl(packageName).toUri()))-    }+    override fun openInPlayStore(packageName: String) = openInPlayStoreImpl(packageName) -    override fun openInBrowser(url: String) {-        if (url.isBlank()) return-        startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))-    }+    override fun openInBrowser(url: String) = openInBrowserImpl(url) -    override fun shareApp(app: UnifiedApp) {-        val link = app.website ?: PlayStoreLinks.playStoreUrl(app.packageName)-        val share = Intent(Intent.ACTION_SEND).apply {-            type = "text/plain"-            putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_app_text, app.name, link))-        }-        startActivity(Intent.createChooser(share, null))-    }+    override fun shareApp(app: UnifiedApp) = shareAppImpl(app)      // --- Updates ----------------------------------------------------------------------+    // Bodies live in AppStoreUpdateOps.kt; these overrides keep interface conformance. -    override fun checkForUpdates() {-        if (_isCheckingUpdates.value) return-        viewModelScope.launch {-            val enabled = enabledSources.value-            _isCheckingUpdates.value = true-            _statusMessage.value = context.getString(R.string.updates_checking)--            installedRepo.refresh()-            _catalogUpdates.value = catalog.updatesFor(installedRepo.updatable.value)--            // Only ask Play about packages neither offline source lists — for the rest the-            // catalogue already answered, and Play would just re-answer it over the network.-            // The Sandboxed Google Play components are held back too: Play hosts newer builds-            // of all three, but only GrapheneOS's are the ones this device can use, so their-            // updates come from its signed index below instead.-            val index = catalog.packageIndex.value-            val installed = installedRepo.updatable.value-            if (AppSource.PLAYSTORE in enabled) {-                val playCandidates = installed-                    .filter {-                        it.packageName !in index &&-                            it.packageName !in SandboxedGooglePlay.PACKAGES-                    }-                    .map { it.packageName }--                val remote = play.details(playCandidates).associateBy { it.packageName }-                _playUpdates.value = installed.mapNotNull { inst ->-                    remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }-                }-                // The same response tells us which of these packages Play actually hosts, which-                // the library uses to tell a genuine Play app from a sideloaded one.-                if (remote.isNotEmpty()) _playInstalledPackages.value = remote.keys.toSet()-            }--            // Accrescent: refresh the signed allowlist, then ask its API for a newer build of-            // each installed package it vouches for.-            if (AppSource.ACCRESCENT in enabled) {-                accrescent.refreshRepoData()-                val accrescentIds = accrescent.appIds()-                if (accrescentIds.isNotEmpty()) _accrescentPackages.value = accrescentIds-                _accrescentUpdates.value = installed-                    .filter { it.packageName in accrescentIds }-                    .mapNotNull { inst -> accrescentUpdate(inst.packageName, inst.versionCode) }-            }--            // GrapheneOS: its signed index is the only place a Sandboxed Google Play update-            // can come from, which is why the three are held back from the Play list above.-            _grapheneOSUpdates.value = grapheneOS.packages.mapNotNull { entry ->-                val current = installed.firstOrNull { it.packageName == entry.packageName }-                    ?: return@mapNotNull null-                entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }-            }--            _lastUpdateCheck.value = System.currentTimeMillis()-            _statusMessage.value = ""-            _isCheckingUpdates.value = false-        }-    }+    override fun checkForUpdates() = checkForUpdatesImpl()      /**      * Update everything, and report the run once when it is over.@@ -970,72 +526,7 @@ class AppStoreViewModel(      * and a reason that keeps coming back ends the run rather than being demonstrated      * another dozen times.      */-    override fun updateAll() {-        if (updateAllJob?.isActive == true) return-        updateAllJob = viewModelScope.launch {-            val batch = updates.value-            if (batch.isEmpty()) return@launch-            val failures = mutableListOf<String>()-            var started = 0-            var repeats = 0-            var previousReason: String? = null-            InstallFailureBatch.begin()-            try {-                for ((index, app) in batch.withIndex()) {-                    _statusMessage.value = context.getString(-                        R.string.updates_progress, app.name, index + 1, batch.size-                    )-                    val outcome = installer.install(app)-                    if (outcome.started) {-                        started++-                        previousReason = null-                        repeats = 0-                        continue-                    }-                    val reason = outcome.verification.reason()-                    failures += reason-                    repeats = if (reason == previousReason) repeats + 1 else 1-                    previousReason = reason-                    if (repeats >= REPEATED_FAILURE_LIMIT) break-                }-                // PackageInstaller commits asynchronously, so the last app's real verdict-                // is still on its way. Wait for it before summarising, or it lands on its-                // own afterwards — which is the repetition this is here to stop.-                delay(INSTALL_SETTLE_MS)-            } finally {-                _statusMessage.value = ""-                failures += InstallFailureBatch.end()-            }--            AppMessages.show(-                if (failures.isEmpty()) {-                    context.resources.getQuantityString(-                        R.plurals.updates_batch_installed, started, started-                    )-                } else {-                    context.getString(-                        R.string.updates_batch_partial,-                        started,-                        batch.size,-                        failures.first(),-                    )-                },-                duration = if (failures.isEmpty()) {-                    AppMessages.Duration.Short-                } else {-                    AppMessages.Duration.Long-                },-            )-            installedRepo.refresh()-        }-    }--    /** What to tell the user a failed install went wrong with. */-    private fun VerificationResult.reason(): String = when (this) {-        is VerificationResult.Rejected -> reason-        is VerificationResult.Unverified -> reason-        is VerificationResult.Verified -> context.getString(R.string.install_failure_unknown)-    }+    override fun updateAll() = updateAllImpl()      /** Turn fully unattended (no-tap) background update installation on or off. */     fun setAutoInstallUpdates(enabled: Boolean) {@@ -1083,18 +574,18 @@ class AppStoreViewModel(         val message: String,     ) -    private companion object {-        const val SEARCH_DEBOUNCE_MS = 350L-        const val INSTALL_SETTLE_MS = 1_500L-        const val RECENT_LIMIT = 30-        const val CAROUSEL_LIMIT = 20-        const val PLAY_CLUSTER_LIMIT = 4+    internal companion object {+        internal const val SEARCH_DEBOUNCE_MS = 350L+        internal const val INSTALL_SETTLE_MS = 1_500L+        internal const val RECENT_LIMIT = 30+        internal const val CAROUSEL_LIMIT = 20+        internal const val PLAY_CLUSTER_LIMIT = 4          /**          * How many times in a row an update may fail for the same reason before the rest          * of the run is abandoned. Three is enough to tell a bad app from a bad afternoon.          */-        const val REPEATED_FAILURE_LIMIT = 3+    internal const val REPEATED_FAILURE_LIMIT = 3     } } 
astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.ktindex 362f78449c..c2b535cff6 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt@@ -27,7 +27,9 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod      val detail = remember(objectId, visibleSky) { resolveDetail(objectId, visibleSky, viewModel) } -    Box(Modifier.fillMaxSize()) {+    // Dialog detail: already correct metadata, just letterbox the column on+    // expanded windows so it keeps a readable measure on desktop.+    DesktopMaxWidthContainer {         Column(Modifier.fillMaxSize().statusBarsPadding().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {             if (detail == null) {                 Text(stringResource(R.string.object_not_found, objectId))
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.ktindex fce91e692d..e20693c2f8 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt@@ -40,7 +40,9 @@ fun SearchScreen(     var query by remember { mutableStateOf(initialQuery) }     var results by remember { mutableStateOf(actions.search(initialQuery)) } -    Box(Modifier.fillMaxSize()) {+    // Letterbox the single results column on expanded windows; the sky map+    // itself stays full-bleed by design.+    DesktopMaxWidthContainer {         Column(Modifier.fillMaxSize().statusBarsPadding().padding(top = 56.dp).padding(12.dp)) {             OutlinedTextField(value = query, onValueChange = { query = it; results = actions.search(it) }, label = { Text(stringResource(R.string.search_stars_planets_messier)) }, modifier = Modifier.fillMaxWidth())             Spacer(Modifier.height(8.dp))
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.ktindex 9594510695..42b0bd29db 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt@@ -65,7 +65,9 @@ fun SettingsScreen(backStack: NavBackStack<Route>, state: SettingsUiState, actio     val linesArtLabel = stringResource(R.string.lines_art)      AppScaffold(title = stringResource(R.string.settings), onNavigateBack = { backStack.pop() }, scrollBehavior = appBarScrollBehavior()) { padding ->-        Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState())) {+        // Letterboxed on expanded windows so the form keeps a readable measure.+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+        Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {             SettingsSection(title = stringResource(R.string.display)) {                 SettingsSelectRow(                     title = stringResource(R.string.constellations),@@ -118,6 +120,7 @@ fun SettingsScreen(backStack: NavBackStack<Route>, state: SettingsUiState, actio                 Text(stringResource(R.string.catalog_stars_constellations_dso, state.starCount, state.constellationCount, state.deepSkyCount), style = MaterialTheme.typography.labelSmall)             }         }+        }     } } 
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyArt.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyArt.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyArt.ktnew file mode 100644index 0000000000..eca1643b14--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyArt.kt@@ -0,0 +1,115 @@+package com.vayunmathur.astronomy.ui++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.nativeCanvas+import com.vayunmathur.astronomy.domain.engine.AltAz+import com.vayunmathur.astronomy.domain.projection.StereographicProjection+import com.vayunmathur.astronomy.platform.VisibleArt+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.asin+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++internal const val ART_MESH = 12++/**+ * Draw a constellation figure so it lies on the celestial sphere. The 3 anchors+ * define an affine map from image pixels to 3D sky direction; a subdivided mesh+ * of that map is then run through the real sphere projection, so the artwork+ * curves and tracks with the stars instead of being a flat plane.+ */+internal fun DrawScope.drawConstellationArt(+    projection: StereographicProjection,+    bmp: android.graphics.Bitmap,+    art: VisibleArt,+    paint: android.graphics.Paint+) {+    val a0 = art.anchors[0]; val a1 = art.anchors[1]; val a2 = art.anchors[2]+    val v0 = altAzToVec(a0.altAz); val v1 = altAzToVec(a1.altAz); val v2 = altAzToVec(a2.altAz)+    val inv = invert3x3(+        a0.srcX.toDouble(), a0.srcY.toDouble(), 1.0,+        a1.srcX.toDouble(), a1.srcY.toDouble(), 1.0,+        a2.srcX.toDouble(), a2.srcY.toDouble(), 1.0+    ) ?: return+    // Per-component coefficients (a,b,c) with comp(px,py) = a*px + b*py + c.+    fun coef(c0: Double, c1: Double, c2: Double) = doubleArrayOf(+        inv[0]*c0 + inv[1]*c1 + inv[2]*c2,+        inv[3]*c0 + inv[4]*c1 + inv[5]*c2,+        inv[6]*c0 + inv[7]*c1 + inv[8]*c2+    )+    val cx = coef(v0[0], v1[0], v2[0])+    val cy = coef(v0[1], v1[1], v2[1])+    val cz = coef(v0[2], v1[2], v2[2])++    val bw = bmp.width.toFloat(); val bh = bmp.height.toFloat()+    val n = ART_MESH+    val verts = FloatArray((n + 1) * (n + 1) * 2)+    var k = 0+    for (j in 0..n) {+        val py = bh * j / n+        for (i in 0..n) {+            val px = bw * i / n+            var vx = cx[0]*px + cx[1]*py + cx[2]+            var vy = cy[0]*px + cy[1]*py + cy[2]+            var vz = cz[0]*px + cz[1]*py + cz[2]+            val len = sqrt(vx*vx + vy*vy + vz*vz)+            if (len < 1e-9) return+            vx /= len; vy /= len; vz /= len+            val alt = asin(vz.coerceIn(-1.0, 1.0))+            val az = atan2(vx, vy).let { if (it < 0) it + 2*PI else it }+            val off = projection.projectMesh(AltAz(az, alt)) ?: return+            verts[k++] = off.x; verts[k++] = off.y+        }+    }+    drawIntoCanvas { canvas ->+        canvas.nativeCanvas.drawBitmapMesh(bmp, n, n, verts, 0, null, 0, paint)+    }+}++internal fun altAzToVec(a: AltAz): DoubleArray {+    val ca = cos(a.altRad)+    return doubleArrayOf(ca * sin(a.azRad), ca * cos(a.azRad), sin(a.altRad))+}++internal fun invert3x3(+    m0: Double, m1: Double, m2: Double,+    m3: Double, m4: Double, m5: Double,+    m6: Double, m7: Double, m8: Double+): DoubleArray? {+    val det = m0*(m4*m8 - m5*m7) - m1*(m3*m8 - m5*m6) + m2*(m3*m7 - m4*m6)+    if (abs(det) < 1e-12) return null+    val id = 1.0 / det+    return doubleArrayOf(+        (m4*m8 - m5*m7)*id, (m2*m7 - m1*m8)*id, (m1*m5 - m2*m4)*id,+        (m5*m6 - m3*m8)*id, (m0*m8 - m2*m6)*id, (m2*m3 - m0*m5)*id,+        (m3*m7 - m4*m6)*id, (m1*m6 - m0*m7)*id, (m0*m4 - m1*m3)*id+    )+}++internal fun starRadius(mag: Double): Float = (4.2 - mag * 0.55).toFloat().coerceIn(0.9f, 5.5f)++internal fun bvToColor(bv: Double): Color = when {+    bv < -0.2 -> Color(0xFF9BB0FF)+    bv < 0.0 -> Color(0xFFC6D2FF)+    bv < 0.3 -> Color.White+    bv < 0.6 -> Color(0xFFFFFFE0)+    bv < 1.0 -> Color(0xFFFFE4B5)+    bv < 1.4 -> Color(0xFFFFA500)+    else -> Color(0xFFFF6347)+}++internal fun planetColor(id: String): Color = when (id) {+    "MERCURY" -> Color(0xFFA9A9A9)+    "VENUS" -> Color(0xFFFFE0B0)+    "MARS" -> Color(0xFFFF4500)+    "JUPITER" -> Color(0xFFDEB887)+    "SATURN" -> Color(0xFFF0E68C)+    "URANUS" -> Color(0xFFADD8E6)+    "NEPTUNE" -> Color(0xFF4169E1)+    else -> Color.White+}
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.ktindex b51b86639f..3ace67c558 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt@@ -9,22 +9,17 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path-import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.graphics.drawscope.drawIntoCanvas-import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.sp-import com.vayunmathur.astronomy.domain.engine.AltAz import com.vayunmathur.astronomy.domain.projection.StereographicProjection import com.vayunmathur.astronomy.domain.projection.ViewState import com.vayunmathur.astronomy.domain.projection.projectAll import com.vayunmathur.astronomy.platform.TrajectoryPoint-import com.vayunmathur.astronomy.platform.VisibleArt import com.vayunmathur.astronomy.platform.VisibleSky import kotlin.math.* @@ -256,184 +251,3 @@ fun SkyCanvas(         if (viewState.centerAltRad < Math.toRadians(60.0)) drawCardinalLabels(projection, viewSta

Diff truncated.