various fixes
- Commit
dfe073c49859b2eee8799d8eb87e68eedcaf2819- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-23 16:35 UTC (1 month ago)
- Parents
270805b
Diff
.gitignore
diff --git a/.gitignore b/.gitignoreindex ad4087af94..ed02238766 100644--- a/.gitignore+++ b/.gitignore@@ -64,11 +64,11 @@ health/src/main/assets/catalog.db health/src/main/assets/catalog.db.br health/src/main/assets/catalog.db.meta.json -# Built by scripts/generate_places_db.py from GeoNames cities1000. Same deal-# as the health catalogue: generated at build time, never committed.+# Built by scripts/generate_places_db.py from GeoNames cities1000. The+# compressed asset + metadata ARE committed (search must work on a clean+# checkout with no generator run); only the uncompressed staging file is+# ignored. weather/src/main/assets/places.db-weather/src/main/assets/places.db.br-weather/src/main/assets/places.db.meta.json # Compose preview screenshot rendering (common-conventions-preview-metadata). These PNGs # are an intermediate: the `metadata` task copies them into metadata_data/photos/<module>,
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 cf4cae3e82..2e055bfe87 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -17,15 +17,18 @@ import com.vayunmathur.appstore.data.AppStoreDatabaseRepository import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.UpdateCheckWorker import com.vayunmathur.appstore.ui.AppDetailPage+import com.vayunmathur.appstore.ui.BrowsePage import com.vayunmathur.appstore.ui.HomePage import com.vayunmathur.appstore.ui.LibraryPage import com.vayunmathur.appstore.ui.SearchPage import com.vayunmathur.appstore.ui.SourcesPage import com.vayunmathur.appstore.ui.TrustPage import com.vayunmathur.appstore.ui.UpdatesPage+import com.vayunmathur.appstore.util.AppSection import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.AppStoreViewModelFactory import com.vayunmathur.appstore.util.clearSelection+import com.vayunmathur.appstore.util.openBrowse import com.vayunmathur.appstore.util.selectApp import com.vayunmathur.appstore.util.selectPackage import com.vayunmathur.library.network.NetworkClient@@ -113,6 +116,7 @@ sealed interface Route : NavKey { @Serializable data object Main : Route @Serializable data object Trust : Route @Serializable data object Detail : Route+ @Serializable data class Browse(val sectionId: String) : Route } /**@@ -143,12 +147,25 @@ private fun AppRoot( if (backStack.last() !is Route.Detail) backStack.add(Route.Detail) } + fun openBrowse(section: AppSection) {+ viewModel.openBrowse(section)+ backStack.add(Route.Browse(section.id))+ }+ MainNavigation(backStack) { entry<Route.Main> { AppTabs( viewModel = viewModel, onAppClick = ::openDetail, onOpenTrust = { backStack.add(Route.Trust) },+ onOpenBrowse = ::openBrowse,+ )+ }+ entry<Route.Browse> {+ BrowsePage(+ viewModel = viewModel,+ onAppClick = ::openDetail,+ onBack = { backStack.pop() }, ) } entry<Route.Trust> {@@ -179,6 +196,7 @@ private fun AppTabs( viewModel: AppStoreViewModel, onAppClick: (UnifiedApp) -> Unit, onOpenTrust: () -> Unit,+ onOpenBrowse: (AppSection) -> Unit, ) { val pagerState = rememberPagerState(pageCount = { 5 }) val scope = rememberCoroutineScope()@@ -188,6 +206,7 @@ private fun AppTabs( viewModel = viewModel, onAppClick = onAppClick, onOpenUpdates = { scope.launch { pagerState.animateScrollToPage(PAGE_UPDATES) } },+ onOpenBrowse = onOpenBrowse, ) }, PagerTab(stringResource(R.string.nav_search), { IconSearch() }) {
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex f01de06ed3..40ae8813cb 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -271,6 +271,15 @@ interface CachedAppDao { @Query("SELECT * FROM CachedAppEntity WHERE source = :source ORDER BY name ASC") fun bySourceFlow(source: String): Flow<List<CachedAppEntity>> + @Query("SELECT * FROM CachedAppEntity WHERE source = :source ORDER BY name ASC")+ suspend fun bySourceAll(source: String): List<CachedAppEntity>++ @Query(+ "SELECT * FROM CachedAppEntity WHERE ',' || categories || ',' LIKE '%,' || :category || ',%' " ++ "ORDER BY name ASC"+ )+ suspend fun byCategoryAll(category: String): List<CachedAppEntity>+ /** * Newest builds from one offline source only. Each repo gets its own home * row, so the catalogue is never asked for a cross-source "recent" mix.
appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.ktindex ba034d1563..d2c96fd82a 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt@@ -105,6 +105,27 @@ class CatalogRepository( .getOrDefault(emptyList()).filterTv() } + /**+ * Every cached row for one offline source, A→Z. Backs the Browse page, which+ * lists the whole repo rather than the home carousel's recent slice.+ */+ suspend fun allBySource(source: AppSource): List<UnifiedApp> =+ withContext(Dispatchers.IO) {+ runCatching {+ db.cachedAppDao().bySourceAll(source.name).map { it.toUnifiedApp() }+ }.getOrDefault(emptyList()).filterTv()+ }++ /**+ * Every cached row in a category, A→Z. The home row caps at 60; Browse does not.+ */+ suspend fun allByCategory(category: String): List<UnifiedApp> =+ withContext(Dispatchers.IO) {+ runCatching {+ db.cachedAppDao().byCategoryAll(category).map { it.toUnifiedApp() }+ }.getOrDefault(emptyList()).filterTv()+ }+ /** Categories present in the catalogue, most-populated first. */ suspend fun categories(): List<String> = withContext(Dispatchers.IO) { runCatching {
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.ktindex ea42add94d..20a2557cf0 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt@@ -101,6 +101,18 @@ class AccrescentRepository( } } + /**+ * The whole listing catalogue, A–Z. Backs the Browse page, which lists every+ * Accrescent app rather than the home carousel's first page.+ *+ * Fail-soft like everything else here: an interrupted pagination returns whatever+ * listings are cached rather than an error.+ */+ suspend fun allListings(): List<UnifiedApp> {+ runCatching { ensureAllListingsLoaded() }+ return listingsCache.values.sortedBy { it.name.lowercase() }+ }+ /** * Client-side search over the full catalogue. Accrescent's API has no search RPC, so this * pages every listing into memory once (mirroring Accrescent's own client) and then matches
appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.ktnew file mode 100644index 0000000000..2e1cd70921--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt@@ -0,0 +1,102 @@+package com.vayunmathur.appstore.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.util.AppStoreViewModel+import com.vayunmathur.appstore.util.BrowseUiState+import com.vayunmathur.library.ui.AppBarAlignment+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.appBarScrollBehavior++/** Binds [AppStoreViewModel] to the stateless [BrowseScreen]. */+@Composable+fun BrowsePage(+ viewModel: AppStoreViewModel,+ onAppClick: (UnifiedApp) -> Unit,+ onBack: () -> Unit,+) {+ val state by viewModel.browse.collectAsState()+ BrowseScreen(+ state = state,+ onAppClick = onAppClick,+ onBack = onBack,+ )+}++/**+ * One home section's full catalogue as a vertical list.+ *+ * A home carousel shows a capped slice — the 20 newest builds, the first 20 tiles.+ * This page lists literally every app behind that section, A–Z, in the same+ * [AppRow] the search page uses.+ *+ * Stateless so it can be rendered from a `@Preview` — see `src/screenshotTest`,+ * which is where the store listing images come from.+ */+@Composable+fun BrowseScreen(+ state: BrowseUiState,+ onAppClick: (UnifiedApp) -> Unit = {},+ onBack: () -> Unit = {},+) {+ AppScaffold(+ title = state.title,+ onNavigateBack = onBack,+ alignment = AppBarAlignment.Start,+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ when {+ state.isLoading && state.apps.isEmpty() -> Box(+ Modifier.fillMaxSize().padding(padding),+ contentAlignment = Alignment.Center,+ ) {+ CircularProgressIndicator()+ }++ state.apps.isEmpty() -> EmptyState(+ title = stringResource(R.string.browse_empty_title),+ message = stringResource(R.string.browse_empty_message),+ icon = { IconSearch() },+ modifier = Modifier.padding(padding),+ )++ else -> LazyColumn(+ Modifier.fillMaxSize().padding(padding),+ contentPadding = PaddingValues(bottom = 24.dp),+ ) {+ // Morph ownership mirrors the home screen: the browse page and home are+ // never composed at the same time (pushed route), so this list owns the+ // morph for every app while it is on screen.+ items(+ state.apps,+ key = { it.packageName },+ ) { app ->+ AppRow(+ app = app,+ isInstalled = app.packageName in state.installedPackages,+ stage = state.stages[app.packageName],+ installedIcon = state.installedIcons[app.packageName],+ onClick = { onAppClick(app) },+ sharedKey = "appstore-app-${app.packageName}",+ )+ }+ }+ }+ }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/HomePage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/HomePage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/HomePage.ktindex 38912b1d16..c24680cf24 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/HomePage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/HomePage.kt@@ -51,6 +51,7 @@ fun HomePage( viewModel: AppStoreViewModel, onAppClick: (UnifiedApp) -> Unit, onOpenUpdates: () -> Unit,+ onOpenBrowse: (AppSection) -> Unit, ) { val state by viewModel.home.collectAsState() // The updates banner counts every source, but the Play half of the update check only@@ -64,6 +65,7 @@ fun HomePage( actions = viewModel, onAppClick = onAppClick, onOpenUpdates = onOpenUpdates,+ onOpenBrowse = onOpenBrowse, ) } @@ -84,6 +86,7 @@ fun HomeScreen( actions: HomeActions, onAppClick: (UnifiedApp) -> Unit = {}, onOpenUpdates: () -> Unit = {},+ onOpenBrowse: (AppSection) -> Unit = {}, ) { Scaffold { padding -> AppPullToRefreshBox(@@ -152,28 +155,12 @@ fun HomeScreen( SectionHeader( title = section.title, subtitle = section.subtitle,- actionLabel = browseLabel(section.id == state.expandedSectionId),- onAction = { actions.toggleSection(section.id) },+ actionLabel = stringResource(R.string.action_browse),+ onAction = { onOpenBrowse(section) }, ) }- val expanded = section.id == state.expandedSectionId- when {- // Browse (issue #669): the carousel's apps as a full vertical list of- // the same search-style rows, replacing the carousel while expanded.- expanded -> items(- section.apps,- key = { "${section.id}-${it.packageName}" },- ) { app ->- AppRow(- app = app,- isInstalled = app.packageName in state.installedPackages,- stage = state.stages[app.packageName],- installedIcon = state.installedIcons[app.packageName],- onClick = { onAppClick(app) },- sharedKey = sharedKeyFor(section, app),- )- }- section.layout == SectionLayout.CAROUSEL -> item("${section.id}-body") {+ if (section.layout == SectionLayout.CAROUSEL) {+ item("${section.id}-body") { AppCarousel( apps = section.apps, installedPackages = state.installedPackages,@@ -183,7 +170,8 @@ fun HomeScreen( sharedKey = { sharedKeyFor(section, it) }, ) }- else -> items(+ } else {+ items( section.apps, key = { "${section.id}-${it.packageName}" }, ) { app ->@@ -253,12 +241,6 @@ private fun UpdatesBanner(count: Int, onClick: () -> Unit) { } } -/** Browse/Show-less label for a section header, resolved here so previews stay literal. */-@Composable-private fun browseLabel(expanded: Boolean): String = stringResource(- if (expanded) R.string.action_show_less else R.string.action_browse-)- @Composable private fun CategoryRow( categories: List<String>,
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.ktindex 9e12452629..6998767975 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt@@ -58,6 +58,10 @@ internal suspend fun AppStoreViewModel.loadHome(enabled: Set<AppSource> = enable } val clusters = play.homeClusters()+ playFullClustersFlow.value = clusters+ .filter { it.apps.isNotEmpty() }+ .take(PLAY_CLUSTER_LIMIT)+ .associate { "play-${it.title}" to it.apps } playSectionsFlow.value = clusters .filter { it.apps.isNotEmpty() } .take(PLAY_CLUSTER_LIMIT)@@ -68,6 +72,9 @@ internal suspend fun AppStoreViewModel.loadHome(enabled: Set<AppSource> = enable // still gives the screen something beyond this repo's own dozen apps. val chart = play.topChart() if (chart.isNotEmpty()) {+ playFullClustersFlow.value = mapOf(+ "play-top" to chart,+ ) playSectionsFlow.value = listOf( AppSection( id = "play-top",@@ -181,6 +188,42 @@ internal fun AppStoreViewModel.syncIfNeverSynced(enabled: Set<AppSource>) { syncSources() } +/**+ * Fill the Browse page with one home section's full catalogue.+ *+ * Each home carousel is a capped slice — the 20 newest builds, the first 20 tiles.+ * Browse lists literally every app behind that section, A–Z: the whole offline repo+ * for an offline row, the whole paged catalogue for Accrescent, the uncapped cluster+ * for a Play row. The rows use the same [AppRow] as search.+ */+fun AppStoreViewModel.openBrowse(section: AppSection) {+ browseJob?.cancel()+ browseSectionFlow.value = section.id+ browseTitleFlow.value = section.title+ browseAppsFlow.value = emptyList()+ isLoadingBrowseFlow.value = true+ browseJob = viewModelScope.launch {+ val apps = when {+ section.id == "category" ->+ catalog.allByCategory(section.title)+ section.id == "modern" || section.id == "modern-recent" ->+ catalog.allBySource(AppSource.MODERN_APPS)+ section.id == "proprietary-recent" ->+ catalog.allBySource(AppSource.PROPRIETARY)+ section.id == "fdroid-recent" ->+ catalog.allBySource(AppSource.FDROID)+ section.id == "accrescent" ->+ accrescent.allListings()+ else ->+ playFullClustersFlow.value[section.id] ?: section.apps+ }+ // A section tapped twice in a row re-resolves: the visible row may predate a+ // sync, and stale full lists are worse than a re-read.+ browseAppsFlow.value = apps.sortedBy { it.name.lowercase() }+ isLoadingBrowseFlow.value = false+ }+}+ /** Re-download both offline catalogues, then reload the home rows from them. */ fun AppStoreViewModel.syncSources() { if (isSyncingFlow.value) return
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.ktindex 5f7315184b..8c29e0f441 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt@@ -54,8 +54,6 @@ data class HomeUiState( val sections: List<AppSection> = emptyList(), val categories: List<String> = emptyList(), val selectedCategory: String? = null,- /** Section id expanded into a full list via its Browse button, or null for carousels. */- val expandedSectionId: String? = null, val updateCount: Int = 0, val installedPackages: Set<String> = emptySet(), val installedIcons: Map<String, Drawable> = emptyMap(),@@ -66,6 +64,17 @@ data class HomeUiState( val statusMessage: String = "", ) +/** Everything the browse screen draws: one home section's full catalogue. */+data class BrowseUiState(+ val sectionId: String = "",+ val title: String = "",+ val apps: List<UnifiedApp> = emptyList(),+ val isLoading: Boolean = false,+ val installedPackages: Set<String> = emptySet(),+ val installedIcons: Map<String, Drawable> = emptyMap(),+ val stages: Map<String, InstallStage> = emptyMap(),+)+ /** Everything the search screen draws. */ data class SearchUiState( val query: String = "",@@ -143,12 +152,6 @@ interface HomeActions : AppActions { fun selectCategory(category: String?) {} fun refresh() {} - /**- * Expand a carousel section into its full vertical list, or collapse it back.- * One section at a time — an expanded section owns the screen below its header.- */- fun toggleSection(sectionId: String) {}- companion object { val Noop: HomeActions = object : HomeActions {} }
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 0d1debed50..ffa8de598d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -87,6 +87,8 @@ class AppStoreViewModel( internal val lastUpdateCheckFlow = MutableStateFlow(0L) internal val playSectionsFlow = MutableStateFlow<List<AppSection>>(emptyList())+ /** Uncapped Play cluster apps per section id — Browse shows the whole cluster. */+ internal val playFullClustersFlow = MutableStateFlow<Map<String, List<UnifiedApp>>>(emptyMap()) internal val recentlyUpdatedFlow = MutableStateFlow<List<UnifiedApp>>(emptyList()) /** Newest builds per offline repo: each one gets its own home row. */@@ -106,8 +108,10 @@ class AppStoreViewModel( internal val categoriesFlow = MutableStateFlow<List<String>>(emptyList()) internal val selectedCategoryFlow = MutableStateFlow<String?>(null) internal val categoryAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())- /** Section id expanded via its Browse button (issue #669), or null for carousels. */- internal val expandedSectionFlow = MutableStateFlow<String?>(null)+ internal val browseSectionFlow = MutableStateFlow<String?>(null)+ internal val browseTitleFlow = MutableStateFlow("")+ internal val browseAppsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())+ internal val isLoadingBrowseFlow = MutableStateFlow(false) internal val queryFlow = MutableStateFlow("") internal val searchResultsFlow = MutableStateFlow<List<UnifiedApp>>(emptyList())@@ -139,6 +143,7 @@ class AppStoreViewModel( internal var searchJob: Job? = null internal var detailJob: Job? = null internal var updateAllJob: Job? = null+ internal var browseJob: Job? = null // --- Derived state ---------------------------------------------------------------- @@ -223,9 +228,7 @@ class AppStoreViewModel( val home: StateFlow<HomeUiState> = combine( sections, categoriesFlow,- combine(selectedCategoryFlow, expandedSectionFlow) { category, expanded ->- category to expanded- },+ selectedCategoryFlow, chrome, combine( updates,@@ -236,12 +239,11 @@ class AppStoreViewModel( ) { u, syncing, loading, msg, playError -> HomeChrome(u.size, syncing, loading, msg.ifBlank { playError }) },- ) { built, categories, (category, expandedSectionId), rows, homeChrome ->+ ) { built, categories, category, rows, homeChrome -> HomeUiState( sections = built, categories = categories, selectedCategory = category,- expandedSectionId = expandedSectionId, updateCount = homeChrome.updateCount, installedPackages = rows.installedPackages, installedIcons = rows.icons,@@ -252,6 +254,24 @@ class AppStoreViewModel( ) }.stateIn(viewModelScope, SharingStarted.Eagerly, HomeUiState()) + val browse: StateFlow<BrowseUiState> = combine(+ browseSectionFlow,+ browseTitleFlow,+ browseAppsFlow,+ isLoadingBrowseFlow,+ chrome,+ ) { sectionId, title, apps, loading, rows ->+ BrowseUiState(+ sectionId = sectionId.orEmpty(),+ title = title,+ apps = apps,+ isLoading = loading,+ installedPackages = rows.installedPackages,+ installedIcons = rows.icons,+ stages = rows.stages,+ )+ }.stateIn(viewModelScope, SharingStarted.Eagerly, BrowseUiState())+ val search: StateFlow<SearchUiState> = combine( queryFlow, combine(searchResultsFlow, searchFilterFlow) { results, filter ->@@ -462,15 +482,6 @@ class AppStoreViewModel( } } - /**- * Expand a carousel section into its full vertical list, or collapse it.- * One section at a time (issue #669); expanding another moves, not stacks.- */- override fun toggleSection(sectionId: String) {- expandedSectionFlow.value =- if (expandedSectionFlow.value == sectionId) null else sectionId- }- override fun refresh() = syncSources() /** Re-download both offline catalogues, then reload the home rows from them. */@@ -505,6 +516,7 @@ class AppStoreViewModel( when (source) { AppSource.PLAYSTORE -> { playSectionsFlow.value = emptyList()+ playFullClustersFlow.value = emptyMap() playUpdatesFlow.value = emptyList() playInstalledPackagesFlow.value = emptySet() }
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex 5e67974a5f..2f127c0c2e 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -32,6 +32,9 @@ <!-- Home. --> <string name="action_browse">Browse</string>+ <!-- Browse page: the section's full catalogue came back empty. -->+ <string name="browse_empty_title">Nothing here yet</string>+ <string name="browse_empty_message">Sync your sources to fill this up, or search for an app by name.</string> <string name="section_modern_apps">From Modern Apps</string> <string name="section_modern_apps_subtitle">Built in this repo and signed with the same key as this store</string> <string name="section_play_top_charts">Top on the Play Store</string>
calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Units.ktindex f3ad977629..3e947bbe2c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt@@ -36,6 +36,20 @@ object UnitRegistry { private const val METRES_PER_FOOT = 0.3048 private const val METRES_PER_INCH = 0.0254 private const val METRES_PER_NAUTICAL_MILE = 1852.0+ private const val METRES_PER_LIGHT_NANOSECOND = 0.299792458+ private const val METRES_PER_LIGHT_MICROSECOND = 299.792458+ private const val METRES_PER_LIGHT_MILLISECOND = 299792.458+ private const val METRES_PER_LIGHT_SECOND = 299792458.0+ private const val METRES_PER_LIGHT_MINUTE = 17987547480.0+ private const val METRES_PER_LIGHT_HOUR = 1079252848800.0+ private const val METRES_PER_LIGHT_DAY = 25902068371200.0+ private const val METRES_PER_LIGHT_WEEK = 181314478598400.0+ private const val METRES_PER_LIGHT_YEAR = 9.4607304725808e15+ private const val METRES_PER_AU = 1.495978707e11+ private const val METRES_PER_PARSEC = 3.08567758149137e16+ private const val METRES_PER_KILOPARSEC = 3.08567758149137e19+ private const val METRES_PER_MEGAPARSEC = 3.08567758149137e22+ private const val METRES_PER_GIGAPARSEC = 3.08567758149137e25 // Mass (kilograms). private const val KG_PER_TONNE = 1000.0@@ -337,6 +351,127 @@ object UnitRegistry { UnitDef("ft", "ft", "Foot", d.LENGTH, METRES_PER_FOOT), UnitDef("in", "in", "Inch", d.LENGTH, METRES_PER_INCH), UnitDef("nmi", "nmi", "Nautical mile", d.LENGTH, METRES_PER_NAUTICAL_MILE),+ UnitDef(+ "Gpc",+ "Gpc",+ "Gigaparsec",+ d.LENGTH,+ METRES_PER_GIGAPARSEC,+ aliases = listOf("gpc", "gigaparsec", "gigaparsecs"),+ ),+ UnitDef(+ "Mpc",+ "Mpc",+ "Megaparsec",+ d.LENGTH,+ METRES_PER_MEGAPARSEC,+ aliases = listOf("mpc", "megaparsec", "megaparsecs"),+ ),+ UnitDef(+ "kpc",+ "kpc",+ "Kiloparsec",+ d.LENGTH,+ METRES_PER_KILOPARSEC,+ aliases = listOf("kiloparsec", "kiloparsecs"),+ ),+ UnitDef(+ "pc",+ "pc",+ "Parsec",+ d.LENGTH,+ METRES_PER_PARSEC,+ aliases = listOf("parsec", "parsecs"),+ ),+ UnitDef(+ "ly",+ "ly",+ "Light-year",+ d.LENGTH,+ METRES_PER_LIGHT_YEAR,+ aliases = listOf("lightyear", "lightyears"),+ ),+ UnitDef(+ "lw",+ "lw",+ "Light-week",+ d.LENGTH,+ METRES_PER_LIGHT_WEEK,+ aliases = listOf("lwk", "lightweek", "lightweeks"),+ ),+ UnitDef(+ "ld",+ "ld",+ "Light-day",+ d.LENGTH,+ METRES_PER_LIGHT_DAY,+ aliases = listOf("lday", "lightday", "lightdays"),+ ),+ UnitDef(+ "lh",+ "lh",+ "Light-hour",+ d.LENGTH,+ METRES_PER_LIGHT_HOUR,+ aliases = listOf("lighthour", "lighthours"),+ ),+ UnitDef(+ "lmin",+ "lmin",+ "Light-minute",+ d.LENGTH,+ METRES_PER_LIGHT_MINUTE,+ aliases = listOf("lightminute", "lightminutes"),+ ),+ UnitDef(+ "ls",+ "ls",+ "Light-second",+ d.LENGTH,+ METRES_PER_LIGHT_SECOND,+ aliases = listOf("lightsecond", "lightseconds"),+ ),+ UnitDef(+ "lms",+ "lms",+ "Light-millisecond",+ d.LENGTH,+ METRES_PER_LIGHT_MILLISECOND,+ aliases = listOf(+ "lightmillisecond",+ "lightmilliseconds",+ ),+ ),+ UnitDef(+ "lus",+ "lµs",+ "Light-microsecond",+ d.LENGTH,+ METRES_PER_LIGHT_MICROSECOND,+ aliases = listOf(+ "lightmicrosecond",+ "lightmicroseconds",+ ),+ ),+ UnitDef(+ "lns",+ "lns",+ "Light-nanosecond",+ d.LENGTH,+ METRES_PER_LIGHT_NANOSECOND,+ aliases = listOf(+ "lightnanosecond",+ "lightnanoseconds",+ ),+ ),+ UnitDef(+ "AU",+ "AU",+ "Astronomical unit",+ d.LENGTH,+ METRES_PER_AU,+ aliases = listOf("au", "astronomicalunit", "astronomicalunits"),+ ), ), ) }
calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.ktindex 6629675197..a423632f02 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/FormattingEdgeTest.kt@@ -52,7 +52,7 @@ class FormattingEdgeTest { @Test fun tokenFormUsesPlainSpaceForRoundTrips() { val q = Expression.parse("5m").evalQuantity()- XX(q, unit("m"), useToken = true))+ assertEquals("5 m", formatQuantity(q, unit("m"), useToken = true)) } @Test
calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.ktindex db2c73fb68..1781f5fa90 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt@@ -61,6 +61,34 @@ class UnitsTest { assertClose(3600.0, q("1h").value) } + @Test+ fun lightUnitsConvertBySpeedOfLight() {+ assertEquals(Dimension.LENGTH, q("1ly").dimension)+ assertClose(9.4607304725808e15, q("1ly").value, tolerance = 1e3)+ assertClose(299792458.0, q("1ls").value, tolerance = 1e-3)+ assertClose(0.299792458, q("1lns").value, tolerance = 1e-12)+ // Aliases resolve to the same units.+ assertClose(q("1ly").value, q("1lightyear").value, tolerance = 1.0)+ assertClose(1.0, unit("ly").fromBase(q("1lightyear").value))+ assertClose(9.4607304725808e12, unit("km").fromBase(q("1ly").value), tolerance = 1e3)+ assertTrue(UnitRegistry.unitsFor(Dimension.LENGTH).any { it.token == "ly" })+ }++ @Test+ fun astronomicalUnitsAndParsecs() {+ assertEquals(Dimension.LENGTH, q("1AU").dimension)+ assertClose(1.495978707e11, q("1AU").value, tolerance = 1.0)+ assertClose(q("1AU").value, q("1au").value, tolerance = 1.0)+ assertEquals(Dimension.LENGTH, q("1pc").dimension)+ assertClose(3.08567758149137e16, q("1pc").value, tolerance = 1e4)+ assertClose(3.26156, unit("ly").fromBase(q("1pc").value), tolerance = 1e-4)+ assertClose(1000.0, unit("pc").fromBase(q("1kpc").value), tolerance = 1e-9)+ assertClose(1.0, unit("pc").fromBase(q("1parsec").value), tolerance = 1e-12)+ assertClose(206264.806, unit("AU").fromBase(q("1pc").value), tolerance = 1e-3)+ assertTrue(UnitRegistry.unitsFor(Dimension.LENGTH).any { it.token == "AU" })+ assertTrue(UnitRegistry.unitsFor(Dimension.LENGTH).any { it.token == "pc" })+ }+ @Test fun areaVolumeSpeedDataEnergyPressureForceSamples() { assertEquals(Dimension.AREA, q("5m^2").dimension)
calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.ktindex 5e31bd807f..879c150847 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt@@ -1,6 +1,7 @@ package com.vayunmathur.calendar import android.Manifest+import android.content.Context import android.content.Intent import android.os.Build import android.provider.CalendarContract@@ -17,6 +18,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.lifecycleScope@@ -44,6 +46,7 @@ import com.vayunmathur.calendar.ui.dialogs.SettingsRenameCalendarDialog import com.vayunmathur.calendar.ui.dialogs.TimezonePickerDialog import com.vayunmathur.calendar.util.CalendarViewModel import com.vayunmathur.calendar.util.RecurrenceParams+import com.vayunmathur.calendar.util.ReminderScheduler import com.vayunmathur.library.ui.AppPermissionsGate import com.vayunmathur.library.ui.AppPermissionsSpec import com.vayunmathur.library.ui.DynamicTheme@@ -76,6 +79,7 @@ import kotlinx.serialization.json.Json class MainActivity : MaActivity() { private val importUris = mutableStateOf<List<String>>(emptyList()) private val pendingRoute = mutableStateOf<Route?>(null)+ private val pendingReminderFallback = mutableStateOf<ReminderFallback?>(null) private val pendingDate = mutableStateOf<LocalDate?>(null) override fun onCreateBeforeContent() {@@ -110,6 +114,7 @@ class MainActivity : MaActivity() { activityIntent = intent, importUris = importUris, pendingRoute = pendingRoute,+ pendingReminderFallback = pendingReminderFallback, pendingDate = pendingDate, ) }@@ -152,12 +157,45 @@ class MainActivity : MaActivity() { /** * Handles an instance deep-link extra. Returns true when the intent carried no * stream data, so it must not fall into ICS handling.+ *+ * Notification taps arrive with the full Instance JSON when the provider+ * was readable at fire time (same key the agenda widget uses); pre-unlock+ * alarms only carry the lightweight event id + start/end extras (see+ * ReminderReceiver), which are stashed as a [ReminderFallback] and resolved+ * against the provider once the app is open. */ private fun consumeInstanceLink(it: Intent): Boolean {- if (!it.hasExtra("instance")) return false- it.getStringExtra("instance")?.let { raw ->+ it.getStringExtra(ReminderScheduler.EXTRA_INSTANCE)?.let { raw -> runCatching { Json.decodeFromString<Instance>(raw) }.getOrNull()- }?.let { instance -> pendingRoute.value = Route.Event(instance) }+ }?.let { instance ->+ pendingRoute.value = Route.Event(instance)+ pendingReminderFallback.value = null+ return finishInstanceLink(it)+ }+ if (it.hasExtra(ReminderScheduler.EXTRA_EVENT_ID) &&+ it.hasExtra(ReminderScheduler.EXTRA_INSTANCE_START)+ ) {+ val eventId = it.getLongExtra(ReminderScheduler.EXTRA_EVENT_ID, -1L)+ val start = it.getLongExtra(ReminderScheduler.EXTRA_INSTANCE_START, 0L)+ val end = it.getLongExtra(ReminderScheduler.EXTRA_INSTANCE_END, 0L)+ if (eventId != -1L && start != 0L) {+ pendingRoute.value = null+ pendingReminderFallback.value = ReminderFallback(eventId, start, end)+ return finishInstanceLink(it)+ }+ }+ if (!it.hasExtra(ReminderScheduler.EXTRA_INSTANCE) &&+ !it.hasExtra(ReminderScheduler.EXTRA_EVENT_ID)+ ) {+ return false+ }+ // Malformed deep-link (exported activity): fall back to home, never crash.+ pendingRoute.value = null+ pendingReminderFallback.value = null+ return finishInstanceLink(it)+ }++ private fun finishInstanceLink(it: Intent): Boolean { // Instance intents carry no stream data; avoid falling into ICS handling. return it.data == null && IntentHelper.getUrisFromIntent(it).isEmpty() }@@ -170,6 +208,7 @@ class MainActivity : MaActivity() { return false } pendingRoute.value = editEventFromIntent(it)+ pendingReminderFallback.value = null return true } @@ -230,6 +269,12 @@ private fun editEventFromIntent(it: Intent): Route.EditEvent { private const val NO_TIME_MILLIS = -1L +/**+ * Lightweight deep-link for a reminder tap when the full Instance JSON was+ * unavailable (pre-unlock alarm). Resolved against the provider once readable.+ */+data class ReminderFallback(val eventId: Long, val instanceStart: Long, val instanceEnd: Long)+ /** * The activity's content, extracted from [MainActivity.onCreate] so the activity * method stays under the LongMethod/CyclomaticComplexMethod limits.@@ -239,6 +284,7 @@ private fun MainActivity.CalendarAppContent( activityIntent: Intent?, importUris: MutableState<List<String>>, pendingRoute: MutableState<Route?>,+ pendingReminderFallback: MutableState<ReminderFallback?>, pendingDate: MutableState<LocalDate?>, ) { AppPermissionsGate(@@ -264,7 +310,23 @@ private fun MainActivity.CalendarAppContent( val uris by importUris val pending by pendingRoute- val initialRoute = resolveInitialRoute(activityIntent, uris, pending)+ val fallback by pendingReminderFallback+ val initialRoute = resolveInitialRoute(activityIntent, uris, pending, fallback)+ val context = LocalContext.current+ LaunchedEffect(fallback, pending) {+ // Stashed fallback (no full Instance yet): resolve it against the+ // provider now that permissions are granted and the app is open.+ // Provider query goes on IO — never block composition.+ val fb = fallback+ if (pending == null && fb != null) {+ val appContext = context.applicationContext+ val instance = withContext(Dispatchers.IO) {+ resolveReminderFallback(appContext, fb)+ }+ instance?.let { pendingRoute.value = Route.Event(it) }+ pendingReminderFallback.value = null+ }+ } Box( Modifier.fillMaxSize().onFileDrop { dropped -> importUris.value = dropped.map { it.toString() }@@ -324,21 +386,37 @@ private fun Long.toJumpDate(): LocalDate? { }.getOrNull() } +/**+ * Resolves a pre-unlock notification tap ([ReminderFallback]) against the+ * calendar provider. Null when the event is gone or the provider is still+ * unreadable — the caller then leaves the user on home (old behavior).+ */+private fun resolveReminderFallback(context: Context, fb: ReminderFallback): Instance? {+ return Instance.findForReminder(context, fb.eventId, fb.instanceStart, fb.instanceEnd)+}+ /** * Resolves which route the app opens on: an ICS import, a pending deep-link, an- * instance extra, or an ACTION_INSERT — else the calendar home (null).- * Exported activity: malformed "instance" extras fall back to no route instead- * of crashing.+ * instance extra (widget or notification tap), a lightweight reminder fallback,+ * or an ACTION_INSERT — else the calendar home (null).+ * Exported activity: malformed extras fall back to no route instead of crashing. */ private fun resolveInitialRoute( activityIntent: Intent?, uris: List<String>, pending: Route?,+ fallback: ReminderFallback? = null, ): Route? { if (uris.isNotEmpty()) return Route.Settings.ImportIcs(uris) if (pending != null) return pending+ if (fallback != null) {+ // Pre-unlock notification tap stashed before composition: resolved+ // against the provider by the LaunchedEffect in CalendarAppContent.+ // Return of null here is temporary until that resolution lands.+ return null+ } if (activityIntent == null) return null- activityIntent.getStringExtra("instance")?.let { raw ->+ activityIntent.getStringExtra(ReminderScheduler.EXTRA_INSTANCE)?.let { raw -> runCatching { Json.decodeFromString<Instance>(raw) }.getOrNull() }?.let { return Route.Event(it) } if (activityIntent.action == Intent.ACTION_INSERT &&
calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt b/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.ktindex ad61624f85..cd9f37a25d 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt@@ -55,6 +55,23 @@ data class Instance( companion object {+ /**+ * Best-match [Instance] for a reminder tap: exact begin match first, then+ * any instance of the event in a tight window around it (covers a+ * recurrence shift or clock skew). Null when the provider is unreadable+ * (locked boot, missing permission) or the event is gone.+ */+ fun findForReminder(context: Context, eventId: Long, begin: Long, end: Long): Instance? {+ return runCatching {+ val start = Instant.fromEpochMilliseconds((begin - 60_000L).coerceAtLeast(0L))+ val finish = Instant.fromEpochMilliseconds(+ if (end > begin) end + 60_000L else begin + 3_600_000L,+ )+ val window = getInstances(context, start, finish)+ window.firstOrNull { it.eventID == eventId && it.begin == begin }+ ?: window.firstOrNull { it.eventID == eventId }+ }.getOrNull()+ } /** Zone an instance's wall time displays in: UTC for all-day, system default otherwise. */ private fun displayZone(allDay: Boolean): TimeZone = if (allDay) TimeZone.UTC else TimeZone.currentSystemDefault()
calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.ktindex 5697c4e4ee..230df04eb1 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt@@ -115,7 +115,7 @@ fun CalendarScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>) override fun createEventOn(date: LocalDate) { viewModel.setLastViewedDate(dateViewing) // Pre-fill the pressed date at the current hour so the editor opens on a sensible- // timed slot; the editor derives a default end an hour later.+ // timed slot; the editor derives a default end half an hour later. val tz = TimeZone.currentSystemDefault() val nowTime = Clock.System.now().toLocalDateTime(tz).time val begin = date.atTime(nowTime.hour, 0).toInstant(tz).toEpochMilliseconds()
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventDescription.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventDescription.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventDescription.ktnew file mode 100644index 0000000000..375fed51d6--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventDescription.kt@@ -0,0 +1,62 @@+package com.vayunmathur.calendar.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+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.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.calendar.R+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OdfMarkdownEditorController+import com.vayunmathur.library.ui.OdfMarkdownEditorField+import com.vayunmathur.library.ui.Text++/**+ * The event description editor: an outlined box that sizes to its content (no minimum+ * height). The [R.string.label_description] label sits inline like an [OutlinedTextField]+ * hint when empty, and floats as a chip over the top border once there is text.+ */+@Composable+fun EditEventDescription(+ descriptionText: String,+ descriptionController: OdfMarkdownEditorController,+ modifier: Modifier = Modifier,+) {+ Box(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = 4.dp)+ .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp))+ .padding(12.dp),+ ) {+ if (descriptionText.isEmpty()) {+ Text(+ text = stringResource(R.string.label_description),+ style = MaterialTheme.typography.bodyLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } else {+ Text(+ text = stringResource(R.string.label_description),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier+ .align(Alignment.TopStart)+ .offset(y = (-21).dp)+ .background(MaterialTheme.colorScheme.surface)+ .padding(horizontal = 4.dp),+ )+ }+ OdfMarkdownEditorField(+ controller = descriptionController,+ modifier = Modifier.fillMaxWidth(),+ )+ }+}
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventReminders.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventReminders.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventReminders.ktindex 1c76dd8a45..4bda8067b4 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventReminders.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventReminders.kt@@ -1,20 +1,30 @@ package com.vayunmathur.calendar.ui import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.pager.PageSize+import androidx.compose.foundation.pager.VerticalPager+import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.vayunmathur.calendar.R import com.vayunmathur.library.ui.AlertDialog@@ -22,10 +32,10 @@ import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.IconSchedule-import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text-import androidx.compose.foundation.text.KeyboardOptions import com.vayunmathur.library.ui.R as UiR+import kotlinx.coroutines.launch @Composable internal fun EditEventReminders(@@ -88,54 +98,56 @@ private fun CustomReminderDialog( onDismiss: () -> Unit, onConfirm: (Int) -> Unit, ) {- var amountStr by remember { mutableStateOf("") }- var unitIndex by remember { mutableIntStateOf(1) }- val units = listOf(- stringResource(R.string.reminder_unit_minutes),- stringResource(R.string.reminder_unit_hours),- stringResource(R.string.reminder_unit_days),- stringResource(R.string.reminder_unit_weeks),- )- val minutes = amountStr.toLongOrNull()- ?.let { customReminderMinutes(it, REMINDER_UNIT_MULTIPLIERS[unitIndex]) }- var unitExpanded by remember { mutableStateOf(false) }+ val context = LocalContext.current+ var hours by remember { mutableIntStateOf(0) }+ var minutes by remember { mutableIntStateOf(15) }+ val totalMinutes = hours * 60 + minutes AlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.reminder_custom_title)) }, text = {- Column {- OutlinedTextField(- value = amountStr,- onValueChange = { amountStr = it.filter(Char::isDigit).take(9) },- label = { Text(stringResource(R.string.reminder_custom_amount)) },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),- )- Box(Modifier.fillMaxWidth().padding(top = 8.dp)) {- OutlinedTextField(- value = units[unitIndex],- onValueChange = {},- readOnly = true,- singleLine = true,- modifier = Modifier.fillMaxWidth().clickable { unitExpanded = true },- label = { Text(stringResource(R.string.reminder_custom_unit)) },- )- DropdownMenu(unitExpanded, { unitExpanded = false }) {- units.forEachIndexed { i, label ->- DropdownMenuItem(- text = { Text(label) },- onClick = {- unitIndex = i- unitExpanded = false- },- )- }+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.Top,+ ) {+ Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ stringResource(R.string.reminder_unit_hours),+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ WheelColumn(+ range = 0..99,+ value = hours,+ onValue = { hours = it },+ label = { it.toString() },+ )+ }+ Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ stringResource(R.string.reminder_unit_minutes),+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ WheelColumn(+ range = 0..59,+ value = minutes,+ onValue = { minutes = it },+ label = { "%02d".format(it) },+ ) } }+ Text(+ reminderLabel(context, totalMinutes),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ ) } }, confirmButton = {- Button(onClick = { minutes?.let(onConfirm) }, enabled = minutes != null) {+ Button(onClick = { onConfirm(totalMinutes) }, enabled = totalMinutes > 0) { Text(stringResource(UiR.string.add)) } },@@ -144,3 +156,52 @@ private fun CustomReminderDialog( }, ) }++/**+ * A spinning-wheel number column: a [VerticalPager] with a fixed page size so a fling+ * settles on a value, with the settled row emphasized. The vertical content padding keeps+ * the first and last values centerable. Reports the settled page via [onValue]; tapping a+ * visible row animates to it.+ */+@Composable+private fun WheelColumn(+ range: IntRange,+ value: Int,+ onValue: (Int) -> Unit,+ label: (Int) -> String,+ modifier: Modifier = Modifier,+) {+ val values = remember(range) { range.toList() }+ val pagerState = rememberPagerState(+ initialPage = values.indexOf(value).coerceAtLeast(0),+ ) { values.size }+ val scope = rememberCoroutineScope()+ LaunchedEffect(pagerState.settledPage) {+ val settled = values.getOrNull(pagerState.settledPage) ?: return@LaunchedEffect+ if (settled != value) onValue(settled)+ }+ VerticalPager(+ state = pagerState,+ pageSize = PageSize.Fixed(48.dp),+ contentPadding = PaddingValues(vertical = 48.dp),+ modifier = modifier.height(144.dp),+ ) { page ->+ val v = values[page]+ val selected = page == pagerState.currentPage+ Box(+ Modifier+ .fillMaxWidth()+ .height(48.dp)+ .clickable { scope.launch { pagerState.animateScrollToPage(page) } },+ contentAlignment = Alignment.Center,+ ) {+ Text(+ label(v),+ style = if (selected) MaterialTheme.typography.titleLarge else MaterialTheme.typography.bodyLarge,+ fontWeight = if (selected) FontWeight.Bold else null,+ color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ }+ }+}
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventRow.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventRow.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventRow.ktindex d185f7aa01..a378163bef 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventRow.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventRow.kt@@ -4,7 +4,7 @@ import android.content.Context import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row 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@@ -18,12 +18,12 @@ import com.vayunmathur.library.ui.ProvideTextStyle @Composable internal fun Item(icon: @Composable () -> Unit = {}, left: @Composable () -> Unit, right: @Composable () -> Unit = {}) {- Row(Modifier.padding(8.dp).padding(horizontal = 8.dp).height(32.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(Modifier.padding(horizontal = 8.dp, vertical = 4.dp).heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) { ProvideTextStyle(MaterialTheme.typography.bodyLarge) { Box(Modifier.size(24.dp)) { icon() }- Spacer(Modifier.width(24.dp))+ Spacer(Modifier.width(12.dp)) Box(Modifier.weight(1f)) { left() }@@ -35,20 +35,6 @@ internal fun Item(icon: @Composable () -> Unit = {}, left: @Composable () -> Uni /** Common reminder offsets, in minutes before the event start. */ val REMINDER_PRESETS = listOf(0, 5, 10, 15, 30, 60, 120, 1440) -/** Minute multipliers for the custom-reminder unit picker, in dropdown order. */-val REMINDER_UNIT_MULTIPLIERS = listOf(1, 60, 24 * 60, 7 * 24 * 60)--/**- * Minutes-before for a custom reminder of [amount] [unitMinutes]-minute units, or null when the- * amount is not positive or the total does not fit an Int.- */-fun customReminderMinutes(amount: Long, unitMinutes: Int): Int? {- if (amount < 1 || unitMinutes < 1) return null- // Divide before multiplying: amount * unitMinutes can overflow Long for huge amounts.- if (amount > Int.MAX_VALUE / unitMinutes) return null- return (amount * unitMinutes).toInt()-}- fun reminderLabel(context: Context, minutes: Int): String = when { minutes <= 0 -> context.getString(R.string.reminder_at_time_of_event) minutes % 1440 == 0 -> context.resources.getQuantityString(R.plurals.reminder_days_before, minutes / 1440, minutes / 1440)
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.ktindex a90d0ed722..3cb0d0ef64 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt@@ -3,24 +3,17 @@ package com.vayunmathur.calendar.ui import com.vayunmathur.library.ui.R as UiR import android.text.format.DateFormat import androidx.compose.foundation.background-import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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-import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.LabeledTextField-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.ProvideTextStyle import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text@@ -34,12 +27,10 @@ import androidx.compose.runtime.mutableLongStateOf 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.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.calendar.data.Event@@ -63,7 +54,7 @@ import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock import kotlin.time.Duration-import kotlin.time.Duration.Companion.hours+import kotlin.time.Duration.Companion.minutes import com.vayunmathur.library.ui.DateString import com.vayunmathur.library.ui.appBarScrollBehavior @@ -126,20 +117,27 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba val initialEndLdt = editRoute.endTime?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.currentSystemDefault()) } ?: initialBeginLdt?.let { val tz = TimeZone.currentSystemDefault()- it.toInstant(tz).plus(1.hours).toLocalDateTime(tz)+ it.toInstant(tz).plus(30.minutes).toLocalDateTime(tz) } var allDay by remember(event?.id) { mutableStateOf(event?.allDay ?: editRoute.allDay ?: false) } var startDate by remember(event?.id) { mutableStateOf(event?.startDateTimeDisplay?.date ?: initialBeginLdt?.date ?: today) }+ var startTime by remember(event?.id) { mutableStateOf(event?.startDateTimeDisplay?.time ?: initialBeginLdt?.time ?: now) }+ // A new event with no supplied end defaults to 30 minutes long (the old fallback reused+ // startTime, producing a 0-minute event). Rolls to the next day when past midnight.+ val defaultEndLdt = remember(event?.id) {+ if (event != null || initialEndLdt != null) null+ else (startDate.atTime(startTime).toInstant(TimeZone.currentSystemDefault()) + 30.minutes)+ .toLocalDateTime(TimeZone.currentSystemDefault())+ } // Stored all-day end is exclusive (midnight after the last day), so show the last covered day. var endDate by remember(event?.id) { mutableStateOf( event?.let { if (it.allDay) it.endDateTimeDisplay.date.minus(DatePeriod(days = 1)) else it.endDateTimeDisplay.date }- ?: initialEndLdt?.date ?: startDate+ ?: initialEndLdt?.date ?: defaultEndLdt?.date ?: startDate ) }- var startTime by remember(event?.id) { mutableStateOf(event?.startDateTimeDisplay?.time ?: initialBeginLdt?.time ?: now) }- var endTime by remember(event?.id) { mutableStateOf(event?.endDateTimeDisplay?.time ?: initialEndLdt?.time ?: startTime) }+ var endTime by remember(event?.id) { mutableStateOf(event?.endDateTimeDisplay?.time ?: initialEndLdt?.time ?: defaultEndLdt?.time ?: startTime) } // All-day events are stored in UTC as a provider/RFC 5545 artifact, not a real user zone. // Seed the picker with the device zone so switching to a timed event doesn't reinterpret the // wall-clock time in UTC (which the day/week/month views would then shift by the local offset).@@ -277,7 +275,7 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba value = title, onValueChange = { title = it }, label = stringResource(R.string.label_title),- modifier = Modifier.fillMaxWidth().padding(8.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), sharedTextKey = editRoute.instanceId?.let { "calendar-event-title-$it" }, ) @@ -290,22 +288,11 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba ) } - Text(- text = stringResource(R.string.label_description),- style = MaterialTheme.typography.labelMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),- )- com.vayunmathur.library.ui.OdfMarkdownEditorField(- controller = descriptionController,- modifier = Modifier- .fillMaxWidth()- .padding(8.dp)- .heightIn(min = 96.dp)- .border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp))- .padding(12.dp),+ EditEventDescription(+ descriptionText = descriptionText,+ descriptionController = descriptionController, )- HorizontalDivider(Modifier.padding(vertical = 16.dp))+ HorizontalDivider(Modifier.padding(vertical = 8.dp)) EditEventDateTimeSection( allDay = allDay, onAllDay = { allDay = it },@@ -327,11 +314,11 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba timezoneKey = KEY_TIMEZONE, ) - HorizontalDivider(Modifier.padding(vertical = 16.dp))+ HorizontalDivider(Modifier.padding(vertical = 8.dp)) EditEventReminders(reminders = reminders, onReminders = { reminders = it }) - HorizontalDivider(Modifier.padding(vertical = 16.dp))+ HorizontalDivider(Modifier.padding(vertical = 8.dp)) // The location line on the detail screen morphs into this field. sharedTextKey, not a // modifier: the editable line fills the field's width, so keying the field itself would // balloon the arriving text out to that width and snap it back on landing. Null for a new@@ -340,7 +327,7 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba value = location, onValueChange = { location = it }, label = stringResource(R.string.label_location),- modifier = Modifier.fillMaxWidth().padding(8.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), singleLine = false, sharedTextKey = editRoute.id?.let { "calendar-event-location-$it" }, )
calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.ktindex 1925634a7c..0803b82eb2 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt@@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.text.KeyboardOptions import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.DropdownMenu@@ -35,6 +36,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.calendar.util.MAX_RRULE_COUNT@@ -158,7 +160,7 @@ fun RecurrenceDialog( Button(onClick = { backStack.pop() }) { Text(stringResource(UiR.string.cancel)) } }, text = {- Column(Modifier.padding(8.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Column(Modifier.padding(8.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) { SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { SegmentedButton(!onDates, { onDates = false }, shape = SegmentedButtonDefaults.itemShape(0, 2)) {@@ -187,28 +189,45 @@ fun RecurrenceDialog( return@Column } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) { Text(stringResource(R.string.repeat)) var openDropdown by remember { mutableStateOf(false) } - OutlinedTextField(- intervalStr,- { intervalStr = it },- leadingIcon = {Text(stringResource(R.string.every))},- trailingIcon = {- Text(stringResource(R.string.dropdown_freq_format, freq), Modifier.clickable{- openDropdown = true- })- DropdownMenu(openDropdown, onDismissRequest = { openDropdown = false }) {- listOf("days", "weeks", "months", "years").forEach { f ->- DropdownMenuItem({ Text(f) }, onClick = {- freq = f- openDropdown = false- })- }+ Box(Modifier.weight(1f)) {+ OutlinedTextField(+ intervalStr,+ { intervalStr = it.filter { c -> c.isDigit() } },+ modifier = Modifier.fillMaxWidth(),+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+ prefix = {+ Text(+ stringResource(R.string.every),+ Modifier.padding(end = 8.dp)+ )+ },+ suffix = {+ Text(+ stringResource(R.string.dropdown_freq_format, freq),+ Modifier.padding(start = 8.dp).clickable {+ openDropdown = true+ }+ )+ }+ )+ DropdownMenu(openDropdown, onDismissRequest = { openDropdown = false }) {+ listOf("days", "weeks", "months", "years").forEach { f ->+ DropdownMenuItem({ Text(f) }, onClick = {+ freq = f+ openDropdown = false+ }) } }- )+ } } if (freq == "weeks") {
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.ktindex b09958e6d3..35f546231f 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt@@ -11,11 +11,13 @@ import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat import com.vayunmathur.calendar.MainActivity import com.vayunmathur.calendar.R+import com.vayunmathur.calendar.data.Instance import com.vayunmathur.library.util.ensureNotificationChannel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch+import kotlinx.serialization.json.Json import java.util.Date /**@@ -30,47 +32,59 @@ class ReminderReceiver : BroadcastReceiver() { ?.takeIf { it.isNotBlank() } ?: context.getString(R.string.reminder_notification_default_title) val instanceStart = intent.getLongExtra(ReminderScheduler.EXTRA_INSTANCE_START, 0L)+ val instanceEnd = intent.getLongExtra(ReminderScheduler.EXTRA_INSTANCE_END, 0L) - context.ensureNotificationChannel(- CHANNEL_ID,- context.getString(R.string.reminder_channel_name),- NotificationManager.IMPORTANCE_HIGH,- context.getString(R.string.reminder_channel_description),- )-- val openIntent = Intent(context, MainActivity::class.java).apply {- flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP- }- val contentIntent = PendingIntent.getActivity(- context,- eventId.toInt(),- openIntent,- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,- )-- val timeString = DateFormat.getTimeFormat(context).format(Date(instanceStart))- // Visibility is left at the platform default (VISIBILITY_PRIVATE) on purpose: that is- // what lets the system redact this on the lock screen when the user has asked for- // sensitive content to be hidden. Do not set VISIBILITY_PUBLIC.- val notification = NotificationCompat.Builder(context, CHANNEL_ID)- .setSmallIcon(R.drawable.ic_reminder_notification)- .setContentTitle(title)- .setContentText(context.getString(R.string.reminder_notification_text, timeString))- .setPriority(NotificationCompat.PRIORITY_HIGH)- .setCategory(NotificationCompat.CATEGORY_EVENT)- .setContentIntent(contentIntent)- .setAutoCancel(true)- .build()-- val notificationId = 31 * eventId.hashCode() + instanceStart.hashCode()- context.getSystemService(NotificationManager::class.java)- .notify(notificationId, notification)-- // Reschedule the following occurrence for recurring events. Runs in the- // background via goAsync() because it queries the calendar provider.+ // The Instance lookup below queries the calendar provider, so the whole+ // post runs off the main thread via goAsync(). val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {+ context.ensureNotificationChannel(+ CHANNEL_ID,+ context.getString(R.string.reminder_channel_name),+ NotificationManager.IMPORTANCE_HIGH,+ context.getString(R.string.reminder_channel_description),+ )++ // Deep-link the tap to the event detail, mirroring the agenda+ // widget's instance extra (see MainActivity.consumeInstanceLink).+ // The alarm only carries ids/times, so resolve the full Instance+ // from the provider here. On failure (locked boot, deleted+ // event) fall back to lightweight extras that MainActivity+ // resolves after unlock, else bare launch (old behavior).+ val instanceJson = lookupInstanceJson(context, eventId, instanceStart, instanceEnd)+ val notificationId = 31 * eventId.hashCode() + instanceStart.hashCode()+ val openIntent = Intent(context, MainActivity::class.java).apply {+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+ putExtra(ReminderScheduler.EXTRA_EVENT_ID, eventId)+ putExtra(ReminderScheduler.EXTRA_INSTANCE_START, instanceStart)+ putExtra(ReminderScheduler.EXTRA_INSTANCE_END, instanceEnd)+ if (instanceJson != null) putExtra(ReminderScheduler.EXTRA_INSTANCE, instanceJson)+ }+ val contentIntent = PendingIntent.getActivity(+ context,+ notificationId,+ openIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )++ val timeString = DateFormat.getTimeFormat(context).format(Date(instanceStart))+ // Visibility is left at the platform default (VISIBILITY_PRIVATE) on purpose: that is+ // what lets the system redact this on the lock screen when the user has asked for+ // sensitive content to be hidden. Do not set VISIBILITY_PUBLIC.+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_reminder_notification)+ .setContentTitle(title)+ .setContentText(context.getString(R.string.reminder_notification_text, timeString))+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .setCategory(NotificationCompat.CATEGORY_EVENT)+ .setContentIntent(contentIntent)+ .setAutoCancel(true)+ .build()+ context.getSystemService(NotificationManager::class.java)+ .notify(notificationId, notification)++ // Reschedule the following occurrence for recurring events. // Before the first unlock the provider is unreadable, so there is nothing to // reconcile against. The post-unlock BOOT_COMPLETED pass picks this up; the // cost is that a recurring reminder firing pre-unlock does not arm its next@@ -79,7 +93,7 @@ class ReminderReceiver : BroadcastReceiver() { ReminderScheduler.reconcileAll(context) } } catch (expected: Exception) {- Log.error(TAG, "could not reschedule after a reminder fired", expected)+ Log.error(TAG, "could not post reminder notification", expected) } finally { pendingResult.finish() }@@ -90,4 +104,15 @@ class ReminderReceiver : BroadcastReceiver() { const val CHANNEL_ID = "calendar_reminders" private const val TAG = "CalendarReminderReceiver" }++ /**+ * Serializes the reminder's [Instance] for the notification tap deep-link.+ * Null when the provider is unreadable (locked boot) or the event is gone.+ */+ private fun lookupInstanceJson(context: Context, eventId: Long, begin: Long, end: Long): String? {+ if (eventId == -1L || begin == 0L) return null+ return Instance.findForReminder(context, eventId, begin, end)?.let { instance ->+ runCatching { Json.encodeToString(instance) }.getOrNull()+ }+ } }
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.ktindex a6898936be..578efa468d 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt@@ -43,6 +43,11 @@ object ReminderScheduler { const val EXTRA_INSTANCE_START = "instance_start" const val EXTRA_INSTANCE_END = "instance_end" const val EXTRA_TITLE = "title"+ /**+ * Full Instance JSON for the notification tap deep-link. Same key the+ * agenda widget uses, read by MainActivity.consumeInstanceLink.+ */+ const val EXTRA_INSTANCE = "instance" private const val PREFS = "calendar_reminders" private const val KEY_SCHEDULED = "scheduled_request_codes"
calendar/src/main/res/values-et/strings.xml
diff --git a/calendar/src/main/res/values-et/strings.xml b/calendar/src/main/res/values-et/strings.xmlindex 6f32ea0a0b..2ccb5a51f8 100644--- a/calendar/src/main/res/values-et/strings.xml+++ b/calendar/src/main/res/values-et/strings.xml@@ -178,10 +178,6 @@ <string name="reminders">Meeldetuletused</string> <string name="reminder_custom">Sinu seadistatud</string> <string name="reminder_custom_title">Sinu koostatud meeldetuletus</string>- <string name="reminder_custom_amount">Kogus</string>- <string name="reminder_custom_unit">Ühik</string> <string name="reminder_unit_minutes">Minutid</string> <string name="reminder_unit_hours">Tunnid</string>- <string name="reminder_unit_days">Päevad</string>- <string name="reminder_unit_weeks">Nädalad</string> </resources>
calendar/src/main/res/values-pl/strings.xml
diff --git a/calendar/src/main/res/values-pl/strings.xml b/calendar/src/main/res/values-pl/strings.xmlindex d30395a467..42257c7dcd 100644--- a/calendar/src/main/res/values-pl/strings.xml+++ b/calendar/src/main/res/values-pl/strings.xml@@ -200,10 +200,6 @@ <string name="reminders">Przypomnienia</string> <string name="reminder_custom">Niestandardowy</string> <string name="reminder_custom_title">Niestandardowe przypomnienie</string>- <string name="reminder_custom_amount">Wartość</string>- <string name="reminder_custom_unit">Jednostka</string> <string name="reminder_unit_minutes">Minuty</string> <string name="reminder_unit_hours">Godziny</string>- <string name="reminder_unit_days">Dni</string>- <string name="reminder_unit_weeks">Tygodnie</string> </resources>
calendar/src/main/res/values-sv/strings.xml
diff --git a/calendar/src/main/res/values-sv/strings.xml b/calendar/src/main/res/values-sv/strings.xmlindex ed16c68039..4cab2418cd 100644--- a/calendar/src/main/res/values-sv/strings.xml+++ b/calendar/src/main/res/values-sv/strings.xml@@ -178,10 +178,6 @@ <string name="reminders">Påminnelser</string> <string name="reminder_custom">Anpassad</string> <string name="reminder_custom_title">Anpassad påminnelse</string>- <string name="reminder_custom_amount">Antal</string>- <string name="reminder_custom_unit">Enhet</string> <string name="reminder_unit_minutes">Minuter</string> <string name="reminder_unit_hours">Timmar</string>- <string name="reminder_unit_days">Dagar</string>- <string name="reminder_unit_weeks">Veckor</string> </resources>
calendar/src/main/res/values/strings.xml
diff --git a/calendar/src/main/res/values/strings.xml b/calendar/src/main/res/values/strings.xmlindex 0bd2f50bd3..862a0d5aa8 100644--- a/calendar/src/main/res/values/strings.xml+++ b/calendar/src/main/res/values/strings.xml@@ -310,18 +310,10 @@ <string name="reminder_custom">Custom</string> <!-- Custom reminder dialog: title. Noun phrase --> <string name="reminder_custom_title">Custom reminder</string>- <!-- Custom reminder dialog: label for the numeric amount field. Noun -->- <string name="reminder_custom_amount">Amount</string>- <!-- Custom reminder dialog: label for the time-unit dropdown. Noun -->- <string name="reminder_custom_unit">Unit</string>- <!-- Custom reminder dialog: time-unit options. Nouns, plural -->+ <!-- Custom reminder dialog: wheel column header for the hours wheel. Noun, plural --> <string name="reminder_unit_minutes">Minutes</string>- <!-- Custom reminder dialog: hours unit option -->+ <!-- Custom reminder dialog: wheel column header for the minutes wheel. Noun, plural --> <string name="reminder_unit_hours">Hours</string>- <!-- Custom reminder dialog: days unit option -->- <string name="reminder_unit_days">Days</string>- <!-- Custom reminder dialog: weeks unit option -->- <string name="reminder_unit_weeks">Weeks</string> <!-- Recurrence summary descriptions (RRule.describe): human-readable repeat rule --> <!-- Recurrence summary: event repeats daily -->
calendar/src/test/java/com/vayunmathur/calendar/ui/CustomReminderTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/CustomReminderTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/CustomReminderTest.ktdeleted file mode 100644index 5382eef764..0000000000--- a/calendar/src/test/java/com/vayunmathur/calendar/ui/CustomReminderTest.kt+++ /dev/null@@ -1,28 +0,0 @@-package com.vayunmathur.calendar.ui--import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertNull--class CustomReminderTest {-- @Test- fun eachUnitMultipliesToMinutes() {- assertEquals(45, customReminderMinutes(45, REMINDER_UNIT_MULTIPLIERS[0]))- assertEquals(120, customReminderMinutes(2, REMINDER_UNIT_MULTIPLIERS[1]))- assertEquals(4320, customReminderMinutes(3, REMINDER_UNIT_MULTIPLIERS[2]))- assertEquals(10080, customReminderMinutes(1, REMINDER_UNIT_MULTIPLIERS[3]))- }-- @Test- fun zeroOrNegativeAmountIsRejected() {- assertNull(customReminderMinutes(0, 1))- assertNull(customReminderMinutes(-3, 60))- }-- @Test- fun overflowIsRejected() {- assertNull(customReminderMinutes(Long.MAX_VALUE, 7 * 24 * 60))- assertNull(customReminderMinutes(Int.MAX_VALUE.toLong() + 1, 1))- }-}
camera/src/main/java/com/vayunmathur/camera/domain/QrClassification.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/QrClassification.kt b/camera/src/main/java/com/vayunmathur/camera/domain/QrClassification.ktnew file mode 100644index 0000000000..676d617129--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/QrClassification.kt@@ -0,0 +1,190 @@+package com.vayunmathur.camera.domain++/**+ * QR link classification for the camera scanner. Pure JVM (no Android+ * dependency) so it stays unit-testable.+ *+ * FIDO hybrid/caBLE QR codes (desktop sign-in via the passwords app) decode to+ * a `FIDO:/...` URI. Those get a standalone passkey action instead of the+ * generic open-URL row, so less-technical users know what it does.+ */++/** Which caBLE operation the desktop side is asking for. */+enum class FidoRequestType {+ /** `mc` (makeCredential): register a new passkey on this device. */+ CREATE,++ /** `ga` (getAssertion): sign in with an existing passkey. */+ SIGN_IN,++ /** No usable hint — the button falls back to a neutral label. */+ UNKNOWN,+}++/**+ * Whether [text] is a FIDO deep link (`FIDO:/...`, case-insensitive —+ * desktop Chrome renders it uppercase, which never matches an intent-filter+ * until the scheme is lowercased at fire time).+ */+fun isFidoDeepLink(text: String): Boolean =+ text.trim().startsWith("FIDO:", ignoreCase = true)++/**+ * Which operation a scanned FIDO [text] is asking for, read off the QR's+ * request-type hint (CBOR map key 5: `"ga"` = getAssertion/sign-in, `"mc"` =+ * makeCredential/create). Returns [FidoRequestType.UNKNOWN] when the payload+ * can't be decoded — the key is optional per the CTAP 2.2 hybrid-transport+ * spec, and some initiators omit it.+ */+fun fidoRequestType(text: String): FidoRequestType {+ val hint = fidoRequestTypeHint(text) ?: return FidoRequestType.UNKNOWN+ return when (hint) {+ "mc" -> FidoRequestType.CREATE+ "ga" -> FidoRequestType.SIGN_IN+ else -> FidoRequestType.UNKNOWN+ }+}++// --- caBLE v2 QR digit/CBOR decode (mirrors passwords' CableQrData) ---++/** bytes-in-partial-chunk -> number of decimal digits (index 1..6 valid). */+private val PARTIAL_CHUNK_DIGITS = intArrayOf(0, 3, 5, 8, 10, 13, 15, 0)+private const val CHUNK_BYTES = 7+private const val CHUNK_DIGITS = 17+private const val BYTE_MASK = 0xFF+private const val BYTE_SHIFT = 8++/** Reads CBOR map key 5 (request-type hint) from a FIDO URI, or null. */+private fun fidoRequestTypeHint(uri: String): String? {+ val trimmed = uri.trim()+ val body = when {+ trimmed.startsWith("FIDO:/") -> trimmed.removePrefix("FIDO:/")+ trimmed.startsWith("fido:/") -> trimmed.removePrefix("fido:/")+ trimmed.startsWith("FIDO:", ignoreCase = true) -> trimmed.substringAfter(':')+ else -> return null+ }.trim()+ if (body.isEmpty() || !body.all { it in '0'..'9' }) return null+ val cbor = try {+ digitDecode(body)+ } catch (_: IllegalArgumentException) {+ return null+ }+ return readRequestHint(cbor)+}++/** Decodes the compact base-10 digit encoding back into raw CBOR bytes. */+private fun digitDecode(digits: String): ByteArray {+ val out = ArrayList<Byte>(digits.length)+ var i = 0+ while (digits.length - i >= CHUNK_DIGITS) {+ appendLittleEndian(out, digits.substring(i, i + CHUNK_DIGITS).toLong(), CHUNK_BYTES)+ i += CHUNK_DIGITS+ }+ val remaining = digits.length - i+ if (remaining > 0) {+ val byteCount = PARTIAL_CHUNK_DIGITS.indexOf(remaining)+ require(byteCount in 1..6) { "Invalid trailing digit count: $remaining" }+ appendLittleEndian(out, digits.substring(i).toLong(), byteCount)+ }+ return out.toByteArray()+}++private fun appendLittleEndian(out: MutableList<Byte>, value: Long, byteCount: Int) {+ var v = value+ repeat(byteCount) {+ out.add((v and BYTE_MASK.toLong()).toByte())+ v = v ushr BYTE_SHIFT+ }+}++/**+ * Minimal CBOR scan for map key 5's text value. Walks the top-level map+ * without a full decoder — only unsigned-int keys, byte/text strings and+ * small ints are stepped over; anything else aborts to null.+ */+private fun readRequestHint(cbor: ByteArray): String? {+ val r = CborCursor(cbor) ?: return null+ // Top level must be a map; key 5 must be a text string.+ if (r.major() != 5) return null+ val entries = r.argument() ?: return null+ if (entries < 0 || entries > cbor.size) return null+ repeat(entries.toInt()) {+ val keyMajor = r.major() ?: return null+ val key = r.argument() ?: return null+ if (keyMajor == 0 && key == 5L) {+ if (r.major() != 3) return null+ val len = r.argument() ?: return null+ return r.text(len)+ }+ if (!r.skip()) return null+ }+ return null+}++/** Tiny CBOR cursor over definite-length items only. */+private class CborCursor(private val bytes: ByteArray) {+ var pos = 0++ fun major(): Int? {+ if (pos >= bytes.size) return null+ return (bytes[pos].toInt() and BYTE_MASK) ushr 5+ }++ /** Reads the initial byte's argument; null on indefinite lengths. */+ fun argument(): Long? {+ if (pos >= bytes.size) return null+ val minor = bytes[pos++].toInt() and 0x1F+ return when (minor) {+ in 0..23 -> minor.toLong()+ 24 -> byte().toLong() and BYTE_MASK.toLong()+ 25 -> uInt(2)+ 26 -> uInt(4)+ 27 -> uInt(8)+ else -> null+ }+ }++ fun text(len: Long): String? {+ if (len < 0 || len > Int.MAX_VALUE || pos + len > bytes.size) return null+ return String(bytes.copyOfRange(pos, (pos + len).toInt()), Charsets.UTF_8)+ .also { pos += len.toInt() }+ }++ /** Steps over one item; false when the shape is unsupported. */+ fun skip(): Boolean {+ val major = major() ?: return false+ val arg = argument() ?: return false+ return when (major) {+ 0, 1 -> true+ 2, 3 -> step(arg)+ 4 -> repeatOk(arg) { skip() }+ 5 -> repeatOk(arg * 2) { skip() }+ 7 -> true+ else -> false+ }+ }++ private fun repeatOk(n: Long, fn: () -> Boolean): Boolean {+ if (n < 0 || n > bytes.size) return false+ repeat(n.toInt()) { if (!fn()) return false }+ return true+ }++ private fun step(n: Long): Boolean {+ if (n < 0 || n > Int.MAX_VALUE || pos + n > bytes.size) return false+ pos += n.toInt()+ return true+ }++ private fun byte(): Byte {+ if (pos >= bytes.size) throw IndexOutOfBoundsException()+ return bytes[pos++]+ }++ private fun uInt(n: Int): Long? {+ if (pos + n > bytes.size) return null+ var v = 0L+ repeat(n) { v = (v shl BYTE_SHIFT) or (byte().toLong() and BYTE_MASK.toLong()) }+ return v+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraOverlays.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraOverlays.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraOverlays.ktindex 2adb857f26..a094d07ac5 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraOverlays.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraOverlays.kt@@ -32,11 +32,14 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.net.toUri import com.vayunmathur.camera.R+import com.vayunmathur.camera.domain.FidoRequestType+import com.vayunmathur.camera.domain.fidoRequestType import com.vayunmathur.library.intents.euicc.EsimLink import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.IconBedtime+import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Motion import com.vayunmathur.library.ui.Text@@ -143,11 +146,8 @@ internal fun QrResultOverlay(text: String, onDismiss: () -> Unit, context: Conte color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp) )- // Passkey (FIDO hybrid/caBLE) QR codes decode to a "FIDO:/..." URI. Treat it as an- // openable URL alongside normal web links. Intent-filter scheme matching is case-SENSITIVE,- // so the "FIDO" scheme must be lowercased (normalizeScheme) or nothing will handle it.- // eSIM activation codes are neither: they go to the platform LPA, not a browser.- val isFidoUri = text.startsWith("FIDO:", ignoreCase = true)+ // eSIM activation codes are neither URL nor FIDO: they go to the+ // platform LPA, not a browser. Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { if (isEsim) { Button(onClick = {@@ -174,10 +174,10 @@ internal fun QrResultOverlay(text: String, onDismiss: () -> Unit, context: Conte }) { Text(stringResource(R.string.add_esim)) }- } else if (isFidoUri || Patterns.WEB_URL.matcher(text).matches()) {+ } else if (Patterns.WEB_URL.matcher(text).matches()) { Button(onClick = {- val url = if (!isFidoUri && !text.startsWith("http")) "https://$text" else text- val uri = url.toUri().normalizeScheme()+ val url = if (!text.startsWith("http")) "https://$text" else text+ val uri = url.toUri() try { context.startActivity(Intent(Intent.ACTION_VIEW, uri)) } catch (e: ActivityNotFoundException) {@@ -201,6 +201,48 @@ internal fun QrResultOverlay(text: String, onDismiss: () -> Unit, context: Conte } } +/**+ * Standalone action for FIDO hybrid/caBLE QR codes (desktop "use a passkey+ * from another device"): a single passkey button with the dismiss X tucked+ * inside it. The label reflects the QR's request-type hint — "Create a+ * passkey" for registration (`mc`), "Sign in with a passkey" for assertion+ * (`ga`). Rendered in [CameraSettingsColumn] directly above the zoom bar —+ * not in the generic QR popup above, whose text preview and copy button are+ * meaningless for the FIDO digit blob.+ */+@Composable+internal fun FidoQrCard(text: String, onDismiss: () -> Unit, context: Context, modifier: Modifier = Modifier) {+ val labelRes = when (fidoRequestType(text)) {+ FidoRequestType.CREATE -> R.string.create_passkey+ FidoRequestType.SIGN_IN -> R.string.sign_in_with_passkey+ FidoRequestType.UNKNOWN -> R.string.use_passkey+ }+ Button(+ onClick = {+ // Intent-filter scheme matching is case-SENSITIVE, so the+ // "FIDO" scheme must be lowercased or nothing will handle it.+ val uri = text.toUri().normalizeScheme()+ try {+ context.startActivity(Intent(Intent.ACTION_VIEW, uri))+ onDismiss()+ } catch (e: ActivityNotFoundException) {+ Log.status("CameraOverlays", "No app to open FIDO link", e)+ AppMessages.show(context.getString(R.string.no_app_to_open_url))+ }+ },+ modifier = modifier.padding(16.dp)+ ) {+ Text(stringResource(labelRes))+ IconClose(+ modifier = Modifier+ .padding(start = 8.dp)+ .size(18.dp)+ .clickable(onClick = onDismiss),+ tint = MaterialTheme.colorScheme.onPrimary+ )+ }+}+ /** * Whether [text] is an SGP.22 eSIM activation code (`LPA:1$<smdp>$<matchingId>`, * prefix and trailing fields optional — see euicc's `parse_activation_code`).
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex 4df8ca7937..9675f8de00 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -49,6 +49,7 @@ import com.vayunmathur.camera.util.setBlurStrength import com.vayunmathur.camera.util.setExposureCompensation import com.vayunmathur.camera.util.setExposureTimeIndex import com.vayunmathur.camera.util.setManualIsoIndex+import com.vayunmathur.camera.util.setQrResult import com.vayunmathur.camera.util.setShadows import com.vayunmathur.camera.util.setWarmth import com.vayunmathur.camera.util.setZoomRatio@@ -281,6 +282,8 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( cameraMode = cameraMode, onSelectSetting = { state.activeSetting = it }, modifier = Modifier.align(Alignment.BottomCenter),+ qrResult = state.qrResult,+ onDismissQr = { viewModel.setQrResult(null) }, ) if ((cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE) && (state.panoSweeping || state.panoStitching)) {
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 1a8018ed79..db5b443e59 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -138,7 +138,8 @@ fun CameraScreen( onMicToggle = { viewModel.toggleMicMuted() }, onTimerCycle = { val next = when (state.timerDuration) {- TimerDuration.NONE -> TimerDuration.THREE+ TimerDuration.NONE -> TimerDuration.ONE+ TimerDuration.ONE -> TimerDuration.THREE TimerDuration.THREE -> TimerDuration.FIVE TimerDuration.FIVE -> TimerDuration.TEN TimerDuration.TEN -> TimerDuration.NONE
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.ktindex 07132cd621..a68b810c63 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt@@ -7,9 +7,11 @@ import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R+import com.vayunmathur.camera.domain.isFidoDeepLink import com.vayunmathur.camera.util.CameraMode import com.vayunmathur.library.ui.IconBlur import com.vayunmathur.library.ui.IconContrast@@ -42,6 +44,8 @@ internal fun CameraSettingsColumn( cameraMode: CameraMode, onSelectSetting: (CameraSetting?) -> Unit, modifier: Modifier = Modifier,+ qrResult: String? = null,+ onDismissQr: (() -> Unit)? = null, ) { Column( modifier = modifier@@ -50,6 +54,16 @@ internal fun CameraSettingsColumn( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp) ) {+ // FIDO hybrid/caBLE QR codes sit directly above the zoom bar: a single+ // "Create a passkey" button with the dismiss X inside it.+ val fidoQr = qrResult?.takeIf { isFidoDeepLink(it) }+ if (fidoQr != null && onDismissQr != null) {+ FidoQrCard(+ text = fidoQr,+ onDismiss = onDismissQr,+ context = LocalContext.current,+ )+ } when (activeSetting) { null -> { LensBar(
camera/src/main/java/com/vayunmathur/camera/ui/CameraStatusIndicators.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraStatusIndicators.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraStatusIndicators.ktindex 7312f2cd7a..1ec20442f4 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraStatusIndicators.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraStatusIndicators.kt@@ -17,6 +17,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.vayunmathur.camera.R+import com.vayunmathur.camera.domain.isFidoDeepLink import com.vayunmathur.library.ui.Text @Composable@@ -33,7 +34,9 @@ internal fun BoxScope.CameraStatusIndicators( focusLocked: Boolean, focusTopPadding: Dp, ) {- qrResult?.let { qr ->+ // FIDO deep links render in CameraSettingsColumn directly above the zoom+ // bar — never in the generic QR popup here.+ qrResult?.takeUnless { isFidoDeepLink(it) }?.let { qr -> QrResultOverlay( text = qr, onDismiss = onDismissQr,
camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.ktindex 2dd3a05eaf..87402274b1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt@@ -159,6 +159,7 @@ internal fun CameraTopBar( } else { val timerLabel = when (timerDuration) { TimerDuration.NONE -> ""+ TimerDuration.ONE -> "1" TimerDuration.THREE -> "3" TimerDuration.FIVE -> "5" TimerDuration.TEN -> "10"
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModelTypes.ktindex 0ca37020ab..a9994f8126 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModelTypes.kt@@ -13,11 +13,13 @@ enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, VIDEO, SLOW_MO, enum class FlashMode { ON, OFF, AUTO } /** Shutter-timer durations (seconds). */+private const val TIMER_ONE_SECOND = 1 private const val TIMER_THREE_SECONDS = 3 private const val TIMER_FIVE_SECONDS = 5 private const val TIMER_TEN_SECONDS = 10 enum class TimerDuration(val seconds: Int) { NONE(0),+ ONE(TIMER_ONE_SECOND), THREE(TIMER_THREE_SECONDS), FIVE(TIMER_FIVE_SECONDS), TEN(TIMER_TEN_SECONDS)
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex d5738917ad..8a7d91da27 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -100,6 +100,12 @@ <!-- QR code detection overlay --> <!-- QrResultOverlay: header title when QR code detected --> <string name="qr_result">QR Code</string>+ <!-- FidoQrCard: button to hand a FIDO registration QR to the passwords app. Verb. -->+ <string name="create_passkey">Create a passkey</string>+ <!-- FidoQrCard: button to hand a FIDO sign-in QR to the passwords app. Verb. -->+ <string name="sign_in_with_passkey">Sign in with a passkey</string>+ <!-- FidoQrCard: button when the FIDO QR carries no request-type hint. Verb. -->+ <string name="use_passkey">Use a passkey</string> <!-- QrResultOverlay: header title when an eSIM activation code QR is detected --> <string name="esim_qr_result">eSIM QR Code</string> <!-- QrResultOverlay: button to hand an eSIM activation code to the system LPA. Verb. -->
camera/src/main/rust/testdata/output.jpg
diff --git a/camera/src/main/rust/testdata/output.jpg b/camera/src/main/rust/testdata/output.jpgindex acfe24a5d4..0a1079e8dc 100644Binary files a/camera/src/main/rust/testdata/output.jpg and b/camera/src/main/rust/testdata/output.jpg differ
camera/src/test/java/com/vayunmathur/camera/domain/QrClassificationTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/QrClassificationTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/QrClassificationTest.ktnew file mode 100644index 0000000000..48625db09c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/QrClassificationTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Pure-domain checks for the FIDO classification: no Android needed. */+class QrClassificationTest {++ @Test+ fun fidoUppercaseMatches() {+ assertTrue(isFidoDeepLink("FIDO:/48219375120864391756028374659102847"))+ }++ @Test+ fun fidoLowercaseMatches() {+ assertTrue(isFidoDeepLink("fido:/48219375120864391756028374659102847"))+ }++ @Test+ fun fidoWithWhitespaceMatches() {+ assertTrue(isFidoDeepLink(" FIDO:/123 "))+ }++ @Test+ fun webUrlIsNotFido() {+ assertFalse(isFidoDeepLink("https://example.com"))+ assertFalse(isFidoDeepLink("example.com"))+ }++ @Test+ fun esimIsNotFido() {+ assertFalse(isFidoDeepLink("LPA:1\$smdp.example\$matching-id"))+ }++ @Test+ fun plainTextIsNotFido() {+ assertFalse(isFidoDeepLink("hello world"))+ assertFalse(isFidoDeepLink(""))+ }++ // --- request-type hint (CBOR map key 5) ---++ @Test+ fun mcHintMeansCreate() {+ assertEquals(FidoRequestType.CREATE, fidoRequestType(fidoUri(hint = "mc")))+ }++ @Test+ fun gaHintMeansSignIn() {+ assertEquals(FidoRequestType.SIGN_IN, fidoRequestType(fidoUri(hint = "ga")))+ }++ @Test+ fun missingHintIsUnknown() {+ assertEquals(FidoRequestType.UNKNOWN, fidoRequestType(fidoUri(hint = null)))+ }++ @Test+ fun garbageBodyIsUnknown() {+ assertEquals(FidoRequestType.UNKNOWN, fidoRequestType("FIDO:/not-digits!!"))+ assertEquals(FidoRequestType.UNKNOWN, fidoRequestType("FIDO:/"))+ assertEquals(FidoRequestType.UNKNOWN, fidoRequestType("https://example.com"))+ }++ /**+ * Builds a minimal `FIDO:/...` URI whose CBOR payload is a map with the+ * required keys 0 (33-byte key) and 1 (16-byte secret) plus an optional+ * key 5 [hint], using the same digit encoding as the real QR format.+ */+ private fun fidoUri(hint: String?): String {+ val cbor = buildCborMap(hint)+ return "FIDO:/" + digitEncode(cbor)+ }++ private fun buildCborMap(hint: String?): ByteArray {+ val out = mutableListOf<Byte>()+ val entries = if (hint == null) 2 else 3+ out.add((0xA0 or entries).toByte())+ // Key 0: 33 zero bytes.+ out.add(0x00.toByte())+ out.add(0x58.toByte())+ out.add(33.toByte())+ repeat(33) { out.add(0) }+ // Key 1: 16 zero bytes.+ out.add(0x01.toByte())+ out.add(0x50.toByte())+ repeat(16) { out.add(0) }+ // Key 5: text hint.+ if (hint != null) {+ out.add(0x05.toByte())+ val bytes = hint.encodeToByteArray()+ out.add((0x60 or bytes.size).toByte())+ bytes.forEach { out.add(it) }+ }+ return out.toByteArray()+ }++ private fun digitEncode(cbor: ByteArray): String {+ val sb = StringBuilder()+ var i = 0+ while (cbor.size - i >= 7) {+ var v = 0L+ for (b in 0 until 7) v = v or ((cbor[i + b].toLong() and 0xFF) shl (8 * b))+ sb.append(v.toString().padStart(17, '0'))+ i += 7+ }+ val remaining = cbor.size - i+ if (remaining > 0) {+ var v = 0L+ for (b in 0 until remaining) v = v or ((cbor[i + b].toLong() and 0xFF) shl (8 * b))+ val digits = intArrayOf(0, 3, 5, 8, 10, 13, 15, 0)[remaining]+ sb.append(v.toString().padStart(digits, '0'))+ }+ return sb.toString()+ }+}
clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmCard.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmCard.kt b/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmCard.ktindex c930f66e34..9b4e31a0ca 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmCard.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmCard.kt@@ -11,13 +11,17 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate+import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.clock.R@@ -111,10 +115,26 @@ fun AlarmCard( } if (expanded) { Spacer(Modifier.height(12.dp))+ // Local editing state keyed on the alarm: the field used to bind+ // straight to the Room-backed alarm.name, so every keystroke+ // round-tripped through the DB and the recomposed field reset+ // the cursor. Editing locally preserves cursor/selection; the+ // DB is still updated on each change.+ var labelState by remember(alarm.id) { mutableStateOf(TextFieldValue(alarm.name)) }+ var labelFocused by remember(alarm.id) { mutableStateOf(false) }+ // Adopt external changes (e.g. assistant intent) when not editing.+ LaunchedEffect(alarm.name, labelFocused) {+ if (!labelFocused && labelState.text != alarm.name) {+ labelState = TextFieldValue(alarm.name, TextRange(alarm.name.length))+ }+ } OutlinedTextField(- value = alarm.name,- onValueChange = { actions.setName(alarm, it) },- modifier = Modifier.fillMaxWidth(),+ value = labelState,+ onValueChange = {+ labelState = it+ if (it.text != alarm.name) actions.setName(alarm, it.text)+ },+ modifier = Modifier.fillMaxWidth().onFocusChanged { labelFocused = it.isFocused }, label = { Text(stringResource(R.string.field_label)) }, placeholder = { Text(stringResource(R.string.alarm_label_hint)) }, singleLine = true,
contacts/src/main/java/com/vayunmathur/contacts/data/CommPref.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/CommPref.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/CommPref.ktnew file mode 100644index 0000000000..ff4a764d00--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/CommPref.kt@@ -0,0 +1,57 @@+package com.vayunmathur.contacts.data++import android.content.Context+import kotlinx.serialization.Serializable++/**+ * Singleton per-contact preferred number + platform for the Call/Message/Video+ * header buttons, persisted as a custom MIME Data row like [Gender].+ * Persisted under a custom MIME type in DATA1 (number as stored) + DATA2+ * (platform storage key); never stored on SIM contacts.+ */+@Serializable+data class CommPref(+ override val id: Long,+ val number: String,+ val platform: CommPlatform = CommPlatform.SIM,+) : ContactDetail<CommPref> {+ override val type: Int = 0+ override val value: String+ get() = "${platform.storageKey};$number"++ override fun withType(type: Int) =+ throw UnsupportedOperationException("Cannot change type of comm pref")++ override fun withValue(value: String): CommPref {+ val key = value.substringBefore(";")+ val num = value.substringAfter(";", "")+ return copy(+ number = num,+ platform = CommPlatform.fromStorageKey(key) ?: CommPlatform.SIM,+ )+ }++ override fun withLabel(label: String): CommPref = this++ override fun typeString(context: Context) =+ throw UnsupportedOperationException("Comm pref doesn't have type")++ companion object {+ const val MIME_TYPE = "vnd.android.cursor.item/vnd.com.vayunmathur.contacts.comm_pref"+ }+}++/** Platform a [CommPref] can point at. Storage keys are stable; do not rename. */+@Serializable+enum class CommPlatform(val storageKey: String) {+ SIM("sim"),+ SIGNAL("signal"),+ WHATSAPP("whatsapp"),+ TELEGRAM("telegram"),+ MEET("meet");++ companion object {+ fun fromStorageKey(key: String): CommPlatform? =+ entries.firstOrNull { it.storageKey == key.trim().lowercase() }+ }+}
contacts/src/main/java/com/vayunmathur/contacts/data/CommPrefResolver.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/CommPrefResolver.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/CommPrefResolver.ktnew file mode 100644index 0000000000..0a04cb007e--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/CommPrefResolver.kt@@ -0,0 +1,80 @@+package com.vayunmathur.contacts.data++import com.vayunmathur.contacts.util.ContactPlatforms++/** Which header button is being resolved: call, message, or video. */+enum class CommAction { CALL, MESSAGE, VIDEO }++/**+ * Pure decision logic for the single shared [CommPref].+ * No Android dependencies so it stays unit-testable on the JVM.+ */+object CommPrefResolver {+ /**+ * Platforms the picker may offer for [action], in Signal > WhatsApp > SIM+ * priority order. SIM/system is always available for call and message;+ * video has no system option, so it lists only installed platforms.+ * Meet is video-only and only when installed.+ */+ fun availablePlatformsFor(+ action: CommAction,+ platforms: ContactPlatforms,+ isGoogleMeetInstalled: Boolean,+ ): List<CommPlatform> {+ val out = mutableListOf<CommPlatform>()+ when (action) {+ CommAction.CALL -> {+ if (platforms.signalCallId != null) out += CommPlatform.SIGNAL+ if (platforms.whatsAppCallId != null) out += CommPlatform.WHATSAPP+ if (platforms.telegramCallId != null) out += CommPlatform.TELEGRAM+ out += CommPlatform.SIM+ }+ CommAction.MESSAGE -> {+ if (platforms.signalMessageId != null) out += CommPlatform.SIGNAL+ if (platforms.whatsAppMessageId != null) out += CommPlatform.WHATSAPP+ if (platforms.telegramMessageId != null) out += CommPlatform.TELEGRAM+ out += CommPlatform.SIM+ }+ CommAction.VIDEO -> {+ if (isGoogleMeetInstalled) out += CommPlatform.MEET+ if (platforms.whatsAppVideoId != null) out += CommPlatform.WHATSAPP+ if (platforms.signalVideoId != null) out += CommPlatform.SIGNAL+ if (platforms.telegramVideoId != null) out += CommPlatform.TELEGRAM+ }+ }+ return out+ }++ /**+ * True when [pref] can be launched directly for [action]: its number still+ * exists on the contact (normalized compare) and its platform is offered+ * for [action] right now.+ */+ fun isPrefValidFor(+ pref: CommPref?,+ action: CommAction,+ phoneNumbers: List<PhoneNumber>,+ platforms: ContactPlatforms,+ isGoogleMeetInstalled: Boolean,+ ): Boolean {+ if (pref == null || pref.number.isBlank()) return false+ if (phoneNumbers.none { normalize(it.number) == normalize(pref.number) }) return false+ return availablePlatformsFor(action, platforms, isGoogleMeetInstalled)+ .contains(pref.platform)+ }++ /**+ * True when the platform picker can be skipped entirely: only SIM is+ * available, so there is nothing to choose (per request: if neither+ * WhatsApp nor Signal is available, just pick SIM).+ */+ fun isSimOnly(+ action: CommAction,+ platforms: ContactPlatforms,+ isGoogleMeetInstalled: Boolean,+ ): Boolean = availablePlatformsFor(action, platforms, isGoogleMeetInstalled) ==+ listOf(CommPlatform.SIM)++ internal fun normalize(raw: String): String =+ raw.filter { it.isDigit() || it == '+' }.trim()+}
contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.ktindex 01139773fd..a1fd6b5428 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt@@ -38,12 +38,18 @@ data class ContactDetails( val orgs: List<Organization>, val notes: List<Note>, val nicknames: List<Nickname>,- val groups: List<GroupMembership>+ val groups: List<GroupMembership>,+ val genders: List<Gender> = emptyList(),+ val commPrefs: List<CommPref> = emptyList(), ) { fun all(): List<ContactDetail<*>> {- return phoneNumbers + emails + addresses + dates + photos + names + orgs + notes + nicknames + groups+ return phoneNumbers + emails + addresses + dates + photos + names + orgs + notes + nicknames + groups + genders + commPrefs } + /** Single shared preferred number + platform; null means ask every time. */+ val commPref: CommPref?+ get() = commPrefs.firstOrNull()+ companion object { fun empty() = ContactDetails( emptyList(), emptyList(), emptyList(), emptyList(), emptyList(),@@ -251,6 +257,50 @@ data class GroupMembership(override val id: Long, val groupId: Long): ContactDet throw UnsupportedOperationException("Group membership doesn't have type") } +/**+ * Singleton gender detail (RFC 6350 §6.2.7 sex/gender value): [code] is one of+ * F/M/O/U, [text] carries the free-form value for O (and is otherwise blank).+ * Persisted under a custom MIME type in DATA1 (code) + DATA2 (text); never stored+ * on SIM contacts.+ */+@Serializable+data class Gender(+ override val id: Long,+ val code: String,+ val text: String = "",+) : ContactDetail<Gender> {+ override val type: Int = 0+ override val value: String+ get() = if (code == OTHER && text.isNotBlank()) "$code;$text" else code++ override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of gender")+ override fun withValue(value: String): Gender {+ val parts = value.split(";")+ return copy(code = parts.getOrNull(0).orEmpty(), text = parts.drop(1).joinToString(";"))+ }+ override fun withLabel(label: String): Gender = this++ override fun typeString(context: Context) =+ throw UnsupportedOperationException("Gender doesn't have type")++ companion object {+ const val FEMALE = "F"+ const val MALE = "M"+ const val OTHER = "O"+ const val UNSPECIFIED = "U"+ const val MIME_TYPE = "vnd.android.cursor.item/vnd.com.vayunmathur.contacts.gender"++ /** Canonical code for a raw string, or null when unrecognized. */+ fun canonicalCode(raw: String): String? = when (raw.trim().uppercase()) {+ FEMALE, "FEMALE", "W", "WOMAN", "GIRL" -> FEMALE+ MALE, "MALE", "MAN", "BOY" -> MALE+ OTHER, "OTHER", "X", "DIVERSE", "NONBINARY", "NON-BINARY" -> OTHER+ UNSPECIFIED, "UNSPECIFIED", "UNKNOWN", "" -> UNSPECIFIED+ else -> null+ }+ }+}+ @Serializable data class Contact( val id: Long,@@ -385,6 +435,8 @@ data class Contact( is Note -> completeNoteOperation(detail) is Nickname -> completeNicknameOperation(detail) is GroupMembership -> completeGroupMembershipOperation(detail)+ is Gender -> completeGenderOperation(detail)+ is CommPref -> completeCommPrefOperation(detail) else -> throw IllegalArgumentException("Unknown detail type") } }@@ -401,6 +453,8 @@ data class Contact( is Note -> CDKNote.CONTENT_ITEM_TYPE is Nickname -> CDKNickname.CONTENT_ITEM_TYPE is GroupMembership -> CDKGroupMembership.CONTENT_ITEM_TYPE+ is Gender -> Gender.MIME_TYPE+ is CommPref -> CommPref.MIME_TYPE else -> throw IllegalArgumentException("Unknown detail type") } @@ -431,7 +485,10 @@ data class Contact( private fun ContentProviderOperation.Builder.completeEventOperation( detail: Event ): ContentProviderOperation = this- .withValue(CDKEvent.START_DATE, detail.startDate.format(LocalDate.Formats.ISO))+ // Year-less dates go out as "--MM-DD" (the provider contract Google+ // Contacts and third-party readers parse); the internal 1604 sentinel+ // must never reach the provider. See toExternalDateString.+ .withValue(CDKEvent.START_DATE, detail.startDate.toExternalDateString()) .withValue(CDKEvent.TYPE, detail.type) .withValue(CDKEvent.LABEL, detail.label) .build()@@ -478,6 +535,20 @@ data class Contact( .withValue(CDKGroupMembership.GROUP_ROW_ID, detail.groupId) .build() + private fun ContentProviderOperation.Builder.completeGenderOperation(+ detail: Gender+ ): ContentProviderOperation = this+ .withValue(ContactsContract.Data.DATA1, detail.code)+ .withValue(ContactsContract.Data.DATA2, detail.text)+ .build()++ private fun ContentProviderOperation.Builder.completeCommPrefOperation(+ detail: CommPref+ ): ContentProviderOperation = this+ .withValue(ContactsContract.Data.DATA1, detail.number)+ .withValue(ContactsContract.Data.DATA2, detail.platform.storageKey)+ .build()+ companion object { private fun processDetails(details: ContactDetails, displayName: String?): ContactDetails? {
contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.ktindex 9182706262..eadc27832f 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/ContactDetailsQuery.kt@@ -85,6 +85,8 @@ private class DetailsAccumulator { val notesMap = mutableMapOf<Long, MutableList<Note>>() val nicknamesMap = mutableMapOf<Long, MutableList<Nickname>>() val groupsMap = mutableMapOf<Long, MutableList<GroupMembership>>()+ val gendersMap = mutableMapOf<Long, MutableList<Gender>>()+ val commPrefsMap = mutableMapOf<Long, MutableList<CommPref>>() val rawContactIds = mutableSetOf<Long>() fun toDetails(): Map<Long, ContactDetails> =@@ -99,7 +101,11 @@ private class DetailsAccumulator { orgsMap[rawId]?.distinct().orEmpty(), notesMap[rawId]?.distinct().orEmpty(), nicknamesMap[rawId]?.distinct().orEmpty(),- groupsMap[rawId]?.distinct().orEmpty()+ groupsMap[rawId]?.distinct().orEmpty(),+ gendersMap[rawId]?.distinct().orEmpty(),+ // Singleton in practice (one pref row per raw contact); last-wins+ // on duplicates from aggregated raws, matching gender handling.+ commPrefsMap[rawId]?.distinct().orEmpty() ) } }@@ -189,6 +195,8 @@ private fun accumulateDetailsRow( CDKNote.CONTENT_ITEM_TYPE -> accumulator.addNote(cursor, cols, rawId, dataId) CDKNickname.CONTENT_ITEM_TYPE -> accumulator.addNickname(cursor, cols, rawId, dataId) CDKGroupMembership.CONTENT_ITEM_TYPE -> accumulator.addGroup(cursor, cols, rawId, dataId)+ Gender.MIME_TYPE -> accumulator.addGender(cursor, cols, rawId, dataId)+ CommPref.MIME_TYPE -> accumulator.addCommPref(cursor, cols, rawId, dataId) } } @@ -339,3 +347,27 @@ private fun DetailsAccumulator.addGroup( val groupId = cursor.getLong(cols.d1Idx) groupsMap.getOrPut(rawId) { mutableListOf() }.add(GroupMembership(dataId, groupId)) }++private fun DetailsAccumulator.addGender(+ cursor: android.database.Cursor,+ cols: DetailsColumnIndexes,+ rawId: Long,+ dataId: Long,+) {+ val code = cursor.getStringOrNull(cols.d1Idx).orEmpty()+ val text = cursor.getStringOrNull(cols.d2Idx).orEmpty()+ gendersMap.getOrPut(rawId) { mutableListOf() }.add(Gender(dataId, code, text))+}++private fun DetailsAccumulator.addCommPref(+ cursor: android.database.Cursor,+ cols: DetailsColumnIndexes,+ rawId: Long,+ dataId: Long,+) {+ val number = cursor.getStringOrNull(cols.d1Idx).orEmpty()+ val platform = CommPlatform.fromStorageKey(cursor.getStringOrNull(cols.d2Idx).orEmpty())+ ?: return+ if (number.isBlank()) return+ commPrefsMap.getOrPut(rawId) { mutableListOf() }.add(CommPref(dataId, number, platform))+}
contacts/src/main/java/com/vayunmathur/contacts/data/EventExternalDate.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/EventExternalDate.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/EventExternalDate.ktnew file mode 100644index 0000000000..89afa87e14--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/EventExternalDate.kt@@ -0,0 +1,41 @@+package com.vayunmathur.contacts.data++import kotlinx.datetime.LocalDate+import kotlinx.datetime.format++/**+ * Portable string form of an event date for external stores: full ISO when the+ * year is known, "--MM-DD" when it isn't.+ *+ * Both the Android provider contract (Event.START_DATE, as read by Google+ * Contacts and third-party readers such as KashCal) and vCard BDAY/X-EVENT+ * expect the year-less "--MM-DD" form. Writing the internal 1604 sentinel year+ * instead (e.g. "1604-05-04") makes the birthday invisible to those readers,+ * even though our own read path accepts both forms.+ */+fun LocalDate.toExternalDateString(): String {+ if (hasYear) return format(LocalDate.Formats.ISO)+ // monthNumber/dayOfMonth: deprecated upstream, but the accessors used+ // across this module (see ContactDetailsFormat, EventDate
Diff truncated.