From fb5cb226ee723e1fd3dbbc9fc37047e159e0e2d9 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:27:51 +0100 Subject: [PATCH 01/17] feat(#303, #240): nudge sync adapters after writes, add Sync now to the drawer --- .../data/calendar/CalendarDataSource.kt | 17 +- .../data/calendar/CalendarRepository.kt | 9 + .../data/calendar/CalendarRepositoryImpl.kt | 73 ++++++- .../calendula/data/calendar/SyncRequester.kt | 57 ++++++ .../calendula/data/di/DataModule.kt | 8 + .../calendula/ui/CalendarHost.kt | 27 ++- .../calendula/ui/common/CalendarDrawer.kt | 28 ++- .../calendula/ui/common/SyncViewModel.kt | 82 ++++++++ app/src/main/res/values/strings.xml | 4 + .../calendula/TestRepositories.kt | 17 +- .../data/calendar/FakeCalendarDataSource.kt | 9 + .../calendula/data/calendar/SyncNudgeTest.kt | 190 ++++++++++++++++++ .../calendula/ui/common/SyncViewModelTest.kt | 87 ++++++++ docs/ARCHITECTURE.md | 6 + 14 files changed, 594 insertions(+), 20 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 7f96a33e..1cfd6f4b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -301,6 +301,12 @@ interface CalendarDataSource { */ fun deleteOccurrence(eventId: Long, beginMillis: Long) + /** The account [calendarId] belongs to; null when the row is gone or unreadable. */ + fun calendarAccount(calendarId: Long): SyncAccount? + + /** The calendar event [eventId] lives in; null when the row is gone or unreadable. */ + fun eventCalendarId(eventId: Long): Long? + fun registerChangeListener(listener: () -> Unit) fun unregisterChangeListener(listener: () -> Unit) } @@ -881,8 +887,7 @@ class AndroidCalendarDataSource @Inject constructor( return eventId } - /** The account a calendar belongs to, for scoping a `Colors` lookup. */ - private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query( + override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query( ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId), arrayOf( CalendarContract.Calendars.ACCOUNT_NAME, @@ -891,13 +896,17 @@ class AndroidCalendarDataSource @Inject constructor( null, null, null, )?.use { c -> if (c.moveToFirst()) { - CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty()) + SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty()) } else { null } } - private data class CalendarAccount(val name: String, val type: String) + override fun eventCalendarId(eventId: Long): Long? = resolver.query( + ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId), + arrayOf(CalendarContract.Events.CALENDAR_ID), + null, null, null, + )?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null } /** * The raw provider `MINUTES` to store for one of [form]'s reminders: an diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 3d1308c7..7f5f8204 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -134,6 +134,15 @@ interface CalendarRepository { /** Delete a recurring event from the occurrence at [beginMillis] onwards. */ suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) + + /** + * Ask every account behind a visible synced calendar to sync now (#240). + * Only a request: the adapter may still run it late, or fail. + */ + suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync + + /** Every provider notification and [refresh], including the app's own writes. */ + val providerChanges: Flow get() = emptyFlow() } class NoSuchEventException(eventId: Long) : diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 481ae7a4..b8c4da8e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -47,6 +47,7 @@ class CalendarRepositoryImpl @Inject constructor( private val prefs: CalendarPrefs, private val settingsPrefs: SettingsPrefs, @IoDispatcher private val io: CoroutineDispatcher, + private val syncRequester: SyncRequester, ) : CalendarRepository { /** The configured wall-clock fire time for all-day reminders, read per write. */ @@ -84,13 +85,63 @@ class CalendarRepositoryImpl @Inject constructor( onBufferOverflow = BufferOverflow.DROP_OLDEST, ) - /** Run a provider write on [io], then re-query whether or not it threw. */ - private suspend fun write(block: suspend () -> T): T = withContext(io) { + override val providerChanges: Flow get() = ticks + + /** + * Run a provider write on [io], then re-query whether or not it threw. The + * accounts behind [syncCalendars] (read before the write, which may delete + * the row) get one sync nudge each afterwards (#303) — once per write, so a + * multi-row save or a whole import asks once per account. + */ + private suspend fun write( + syncCalendars: suspend () -> Collection = { emptyList() }, + block: suspend () -> T, + ): T = withContext(io) { + val accounts = syncAccountsOf(syncCalendars) try { block() } finally { refresh() writes.tryEmit(Unit) + accounts.forEach { requestSync(it, userInitiated = false) } + } + } + + private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection): Set = + try { + calendarIds().filterNotNull().distinct() + .mapNotNull { dataSource.calendarAccount(it) } + .filterTo(linkedSetOf()) { it.isSyncable } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "No sync nudge: the calendar account could not be read", e) + emptySet() + } + + private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + syncRequester.requestSync(account, userInitiated) + } catch (e: Exception) { + Log.w(TAG, "Sync request failed", e) + false + } + + private fun eventCalendar(eventId: Long): suspend () -> Collection = + { listOf(dataSource.eventCalendarId(eventId)) } + + override suspend fun requestSync(): SyncRequestResult = withContext(io) { + val accounts = try { + dataSource.calendars().syncAccounts() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync request skipped: calendars unreadable", e) + return@withContext SyncRequestResult.Failed + } + when { + accounts.isEmpty() -> SyncRequestResult.NothingToSync + accounts.count { requestSync(it, userInitiated = true) } > 0 -> SyncRequestResult.Requested + else -> SyncRequestResult.Failed } } @@ -253,7 +304,7 @@ class CalendarRepositoryImpl @Inject constructor( override suspend fun importEvents( targetCalendarId: Long, events: List, - ): IcsImportSummary = write { + ): IcsImportSummary = write({ listOf(targetCalendarId) }) { val existing = dataSource.existingUids(targetCalendarId) // Both are per-calendar, not per-event: looking them up once keeps a // thousand-event restore to two extra queries. The palette is the @@ -304,7 +355,7 @@ class CalendarRepositoryImpl @Inject constructor( ) } - override suspend fun createEvent(form: EventForm): Long = write { + override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) { dataSource.insertEvent(form, allDayReminderTimeMinutes()) } @@ -312,11 +363,11 @@ class CalendarRepositoryImpl @Inject constructor( eventId: Long, original: EventForm, updated: EventForm, - ) = write { + ) = write({ listOf(dataSource.eventCalendarId(eventId), updated.calendarId) }) { dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes()) } - override suspend fun deleteEvent(eventId: Long) = write { + override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) { dataSource.deleteEvent(eventId) } @@ -325,7 +376,7 @@ class CalendarRepositoryImpl @Inject constructor( targetCalendarId: Long, original: EventForm, updated: EventForm, - ): Long = write { + ): Long = write({ listOf(dataSource.eventCalendarId(eventId), targetCalendarId) }) { dataSource.moveEvent( eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(), ) @@ -336,7 +387,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, form: EventForm, - ): Long = write { + ): Long = write(eventCalendar(eventId)) { dataSource.updateOccurrence( eventId, beginMillis, original, form, allDayReminderTimeMinutes(), ) @@ -347,7 +398,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, updated: EventForm, - ): Long = write { + ): Long = write(eventCalendar(eventId)) { dataSource.updateEventFromOccurrence( eventId, beginMillis, original, updated, allDayReminderTimeMinutes(), ) @@ -357,14 +408,14 @@ class CalendarRepositoryImpl @Inject constructor( override val seriesSplits: Flow = splits - override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write { + override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) { dataSource.deleteOccurrence(eventId, beginMillis) } override suspend fun deleteEventFromOccurrence( eventId: Long, beginMillis: Long, - ) = write { + ) = write(eventCalendar(eventId)) { dataSource.deleteEventFromOccurrence(eventId, beginMillis) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt new file mode 100644 index 00000000..52eb42eb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -0,0 +1,57 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import android.accounts.Account +import android.content.ContentResolver +import android.os.Bundle +import android.provider.CalendarContract +import android.util.Log +import de.jeanlucmakiola.calendula.domain.CalendarSource +import javax.inject.Inject +import javax.inject.Singleton + +/** The account behind a calendar row (`ACCOUNT_NAME` / `ACCOUNT_TYPE`). */ +data class SyncAccount(val name: String, val type: String) { + /** Whether a sync adapter can stand behind it: device-only calendars have none. */ + val isSyncable: Boolean + get() = name.isNotBlank() && type.isNotBlank() && type != CalendarContract.ACCOUNT_TYPE_LOCAL +} + +/** + * Asks the system to run a calendar sync adapter sooner (#303, #240). The sync + * itself stays the adapter's job; this only schedules it. + */ +interface SyncRequester { + /** + * Returns whether the request reached the system. [userInitiated] marks it + * manual, which also overrides master-sync-off — only for a user's tap. + */ + fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean +} + +@Singleton +class AndroidSyncRequester @Inject constructor() : SyncRequester { + override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + val extras = Bundle().apply { + putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) + if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) + } + ContentResolver.requestSync( + Account(account.name, account.type), + CalendarContract.AUTHORITY, + extras, + ) + true + } catch (e: Exception) { + Log.w("SyncRequester", "Sync request refused", e) + false + } +} + +/** The distinct accounts behind the visible, synced calendars — what a manual refresh asks. */ +fun List.syncAccounts(): Set = + filter { !it.isLocal && it.isVisibleInSystem } + .map { SyncAccount(it.accountName, it.accountType) } + .filterTo(linkedSetOf()) { it.isSyncable } + +/** Outcome of a user-triggered sync request (#240). */ +enum class SyncRequestResult { Requested, NothingToSync, Failed } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt index 3d5e5800..197715e5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt @@ -11,9 +11,11 @@ import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl +import de.jeanlucmakiola.calendula.data.calendar.SyncRequester import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource @@ -49,6 +51,12 @@ abstract class DataBindModule { impl: CalendarRepositoryImpl, ): CalendarRepository + @Binds + @Singleton + abstract fun bindSyncRequester( + impl: AndroidSyncRequester, + ): SyncRequester + @Binds @Singleton abstract fun bindReminderInstanceSource( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index d3b8bfb1..013b52ff 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -35,6 +35,7 @@ import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource import de.jeanlucmakiola.calendula.ui.common.rememberHeld import de.jeanlucmakiola.calendula.ui.common.screen import de.jeanlucmakiola.calendula.ui.common.ViewScreen @@ -52,6 +53,9 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip import de.jeanlucmakiola.calendula.ui.common.StayingPut import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer +import de.jeanlucmakiola.calendula.ui.common.DrawerSync +import de.jeanlucmakiola.calendula.ui.common.SyncViewModel +import de.jeanlucmakiola.calendula.ui.common.messageRes import de.jeanlucmakiola.calendula.ui.common.CalendarFab import de.jeanlucmakiola.calendula.ui.common.CalendarTopBar import de.jeanlucmakiola.calendula.ui.common.ChromeHost @@ -441,6 +445,13 @@ fun CalendarHost( val eventActions: EventActionsViewModel = hiltViewModel() val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle() val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() + // "Sync now" in the drawer (#240); its receipt shares the move chip. + val sync: SyncViewModel = hiltViewModel() + val syncAvailable by sync.available.collectAsStateWithLifecycle() + val syncInFlight by sync.inFlight.collectAsStateWithLifecycle() + val syncResult by sync.result.collectAsStateWithLifecycle() + val selectionFailureMessage = eventActionFailureMessage(selectionFailure) + val syncMessage = syncResult?.let { stringResource(it.messageRes()) } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -588,6 +599,13 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, + sync = DrawerSync( + inFlight = syncInFlight, + onSync = { + sync.requestSync() + switchScope.launch { drawerState.close() } + }, + ).takeIf { syncAvailable }, ) }, ) { @@ -613,10 +631,11 @@ fun CalendarHost( // A fresh event, like a duplicate from the detail screen (#52). openImportForm(form, ImportSource.Insert) }, - chipShown = moveOutcome != null || selectionFailure != null, + chipShown = moveOutcome != null || selectionFailure != null || syncResult != null, onDismissChip = { reschedule.consumeOutcome() eventActions.consumeFailure() + sync.consumeResult() }, ) CalendarFab(chromeHost, todayInToolbar, fabSelection) @@ -679,8 +698,10 @@ fun CalendarHost( EventMoveHost( reschedule, modifier = Modifier.fillMaxSize(), - actionFailure = eventActionFailureMessage(selectionFailure), - onActionFailureShown = eventActions::consumeFailure, + actionFailure = selectionFailureMessage ?: syncMessage, + onActionFailureShown = { + if (selectionFailureMessage != null) eventActions.consumeFailure() else sync.consumeResult() + }, ) // The delete prompt and failure chip of a selected event's actions (#141). diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index e2a1d028..b6f655bf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -20,8 +20,11 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Sync import androidx.compose.material3.DrawerState +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon +import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.Text @@ -61,6 +64,7 @@ import kotlinx.datetime.LocalDate * * [currentDate] seeds the jump-to-date picker (the visible day/week-start/month * anchor); [onJumpToDate] navigates the active view to the chosen day. + * [sync] adds "Sync now" beside it while there is a synced calendar (#240). */ @Composable fun CalendarDrawer( @@ -71,6 +75,7 @@ fun CalendarDrawer( onJumpToDate: (LocalDate) -> Unit, onSettings: () -> Unit, viewOrder: List = IMPLEMENTED_VIEWS, + sync: DrawerSync? = null, ) { var showDatePicker by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() @@ -103,11 +108,12 @@ fun CalendarDrawer( Spacer(Modifier.height(16.dp)) GroupedRow( title = stringResource(R.string.drawer_jump_to_date), - position = Position.Alone, + position = if (sync != null) Position.Top else Position.Alone, minHeight = 56.dp, leading = { DrawerLeadingIcon(Icons.Filled.DateRange) }, onClick = { showDatePicker = true }, ) + if (sync != null) SyncNowRow(sync) Spacer(Modifier.height(16.dp)) @@ -138,6 +144,26 @@ fun CalendarDrawer( } } +/** The drawer's "Sync now" state: [inFlight] shows progress and ignores taps. */ +data class DrawerSync(val inFlight: Boolean, val onSync: () -> Unit) + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun SyncNowRow(sync: DrawerSync) { + GroupedRow( + title = stringResource(R.string.drawer_sync_now), + position = Position.Bottom, + minHeight = 56.dp, + leading = { DrawerLeadingIcon(Icons.Filled.Sync) }, + trailing = if (sync.inFlight) { + { LoadingIndicator(Modifier.size(32.dp)) } + } else { + null + }, + onClick = { if (!sync.inFlight) sync.onSync() }, + ) +} + /** Leading slot for the drawer's plain icons: the same 40.dp footprint * [CalendarColorChip] takes, so every leading glyph shares one vertical axis. */ @Composable diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt new file mode 100644 index 00000000..6b45c1cb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -0,0 +1,82 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.annotation.StringRes +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.data.calendar.syncAccounts +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import javax.inject.Inject + +/** + * The drawer's "Sync now" (#240): asks the sync adapters of every visible synced + * calendar to run now. [inFlight] holds until the provider next reports a change + * or [SETTLE_MILLIS] pass — the request itself says nothing about when, or + * whether, the sync completes. + */ +@HiltViewModel +class SyncViewModel @Inject constructor( + private val repository: CalendarRepository, +) : ViewModel() { + + /** Whether any visible calendar has a sync adapter behind it. */ + val available: StateFlow = repository.calendars() + .map { it.syncAccounts().isNotEmpty() } + .catch { emit(false) } + .stateWhileSubscribed(scope = viewModelScope, initialValue = false) + + private val _inFlight = MutableStateFlow(false) + val inFlight: StateFlow = _inFlight.asStateFlow() + + private val _result = MutableStateFlow(null) + + /** The last request's outcome, until [consumeResult]. */ + val result: StateFlow = _result.asStateFlow() + + fun requestSync() { + if (_inFlight.value) return + _inFlight.value = true + viewModelScope.launch { + try { + // Listening before asking, so a sync that lands at once still counts. + val settled = async(start = CoroutineStart.UNDISPATCHED) { + withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.first() } + } + val outcome = repository.requestSync() + _result.value = outcome + if (outcome == SyncRequestResult.Requested) settled.await() else settled.cancel() + } finally { + _inFlight.value = false + } + } + } + + fun consumeResult() { + _result.value = null + } + + private companion object { + const val SETTLE_MILLIS = 15_000L + } +} + +/** The chip text for a sync request's outcome. */ +@StringRes +fun SyncRequestResult.messageRes(): Int = when (this) { + SyncRequestResult.Requested -> R.string.sync_requested + SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync + SyncRequestResult.Failed -> R.string.sync_request_failed +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 278cc7ca..20c67931 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -395,6 +395,10 @@ Jump to date + Sync now + Sync requested + Couldn\'t request a sync + No synced calendars to sync Today diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index 51de87a3..dc7809bc 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -5,6 +5,8 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncRequester import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import kotlinx.coroutines.CoroutineDispatcher @@ -43,7 +45,20 @@ fun testRepository( io: CoroutineDispatcher, prefs: CalendarPrefs = testPrefs(dir), settings: SettingsPrefs = testSettings(dir), -): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io) + syncRequester: SyncRequester = RecordingSyncRequester(), +): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester) + +/** Records every sync request; [accepts] false models the system refusing one. */ +class RecordingSyncRequester(var accepts: Boolean = true) : SyncRequester { + data class Request(val account: SyncAccount, val userInitiated: Boolean) + + val requests = mutableListOf() + + override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean { + requests += Request(account, userInitiated) + return accepts + } +} /** Installs [dispatcher] as `Dispatchers.Main` around each test. */ @OptIn(ExperimentalCoroutinesApi::class) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index e22ec492..493b2708 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -64,6 +64,15 @@ internal class FakeCalendarDataSource : CalendarDataSource { val updatedCalendars = mutableListOf() val deletedCalendarIds = mutableListOf() + /** eventId → calendarId, for [eventCalendarId]. */ + val eventCalendars = mutableMapOf() + + override fun calendarAccount(calendarId: Long): SyncAccount? = + calendarsResult.firstOrNull { it.id == calendarId } + ?.let { SyncAccount(it.accountName, it.accountType) } + + override fun eventCalendarId(eventId: Long): Long? = eventCalendars[eventId] + private val listeners = mutableListOf<() -> Unit>() /** How often [calendars] was queried — the repository shares one read per tick. */ diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt new file mode 100644 index 00000000..d307e6e1 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -0,0 +1,190 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.RecordingSyncRequester +import de.jeanlucmakiola.calendula.RecordingSyncRequester.Request +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.FormTime +import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent +import de.jeanlucmakiola.calendula.testRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.test.runTest +import kotlinx.datetime.LocalDate +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.LocalTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.time.Instant + +class SyncNudgeTest { + + private val dav = SyncAccount("me@dav", "bitfire.at.davdroid") + private val google = SyncAccount("me@gmail.com", "com.google") + + private fun cal(id: Long, account: SyncAccount, visible: Boolean = true) = CalendarSource( + id = id, + displayName = "Cal $id", + accountName = account.name, + accountType = account.type, + color = 0, + isVisibleInSystem = visible, + isLocal = account.type == "LOCAL", + ) + + private val local = SyncAccount("Calendula", "LOCAL") + + private fun fake() = FakeCalendarDataSource().apply { + calendarsResult = listOf(cal(1L, dav), cal(2L, dav), cal(3L, google), cal(4L, local)) + eventCalendars += mapOf(10L to 1L, 30L to 3L, 40L to 4L) + } + + private fun form(calendarId: Long) = EventForm( + calendarId = calendarId, + title = "Stand-up", + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))), + ) + + private fun auto(account: SyncAccount) = Request(account, userInitiated = false) + + @Test + fun `a write to a synced calendar nudges its account once, not manually`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `a write to a local calendar asks for no sync`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(4L)) + repo.deleteEvent(40L) + + assertThat(sync.requests).isEmpty() + } + + @Test + fun `event writes resolve the account from the event's calendar`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.updateEventFromOccurrence(10L, 0L, form(1L), form(1L)) + repo.deleteOccurrence(30L, 0L) + + assertThat(sync.requests).containsExactly(auto(dav), auto(google)).inOrder() + } + + @Test + fun `a move between accounts nudges both, each once`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 3L, form(1L), form(3L)) + + assertThat(sync.requests).containsExactly(auto(dav), auto(google)) + } + + @Test + fun `a move between calendars of one account nudges it once`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 2L, form(1L), form(2L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `an import nudges once at the end, however many events`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + val events = (1..5).map { + ParsedIcsEvent( + uid = "u$it", + summary = "E$it", + start = Instant.fromEpochMilliseconds(1_000_000_000L), + end = Instant.fromEpochMilliseconds(1_000_003_600L), + isAllDay = false, + zoneId = "UTC", + ) + } + + repo.importEvents(3L, events) + + assertThat(sync.requests).containsExactly(auto(google)) + } + + @Test + fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = fake().apply { writeError = IllegalStateException("boom") } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThrows { repo.deleteEvent(10L) } + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest { + val throwing = object : SyncRequester { + override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = + throw SecurityException("no") + } + val source = fake().apply { nextInsertId = 77L } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing) + + assertThat(repo.createEvent(form(1L))).isEqualTo(77L) + } + + @Test + fun `manual sync asks each visible synced account once, as manual`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = fake().apply { + calendarsResult = calendarsResult + cal(5L, SyncAccount("hidden@dav", "bitfire.at.davdroid"), visible = false) + } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) + } + + @Test + fun `manual sync with only local calendars has nothing to sync`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(4L, local)) } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync) + assertThat(sync.requests).isEmpty() + } + + @Test + fun `manual sync the system refuses reports a failure`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(accepts = false) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + } + + @Test + fun `syncAccounts skips local, invisible and blank accounts`() { + val calendars = listOf( + cal(1L, dav), + cal(2L, dav), + cal(3L, google, visible = false), + cal(4L, local), + cal(5L, SyncAccount("", "com.google")), + ) + + assertThat(calendars.syncAccounts()).containsExactly(dav) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt new file mode 100644 index 00000000..0aa294a4 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -0,0 +1,87 @@ +package de.jeanlucmakiola.calendula.ui.common + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.MainDispatcherExtension +import de.jeanlucmakiola.calendula.RecordingSyncRequester +import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.testRepository +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path + +@OptIn(ExperimentalCoroutinesApi::class) +class SyncViewModelTest { + + @JvmField @RegisterExtension + val mainDispatcher = MainDispatcherExtension(StandardTestDispatcher()) + private val dispatcher = mainDispatcher.dispatcher + + private val synced = CalendarSource(1L, "Work", "me@dav", "bitfire.at.davdroid", 0, true) + + private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()): + Pair { + val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) } + return SyncViewModel(testRepository(source, dir, dispatcher, syncRequester = sync)) to source + } + + @Test + fun `in flight until the provider next reports a change`(@TempDir dir: Path) = runTest(dispatcher) { + val (vm, source) = viewModel(dir) + + vm.requestSync() + runCurrent() + + assertThat(vm.inFlight.value).isTrue() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) + + source.tick() + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + } + + @Test + fun `in flight ends on its own when nothing changes`(@TempDir dir: Path) = runTest(dispatcher) { + val (vm, _) = viewModel(dir) + + vm.requestSync() + advanceTimeBy(15_001L) + + assertThat(vm.inFlight.value).isFalse() + } + + @Test + fun `a tap while in flight asks only once`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + vm.requestSync() + runCurrent() + + assertThat(sync.requests).hasSize(1) + } + + @Test + fun `a refused request stops at once and says so`(@TempDir dir: Path) = runTest(dispatcher) { + val (vm, _) = viewModel(dir, RecordingSyncRequester(accepts = false)) + + vm.requestSync() + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Failed) + + vm.consumeResult() + assertThat(vm.result.value).isNull() + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 771d9bd7..9a2d8327 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -10,6 +10,12 @@ the package list (recurring writes, save conflicts, reminder delivery). 1. **`CalendarContract` is the single source of truth.** No app database, no caching layer, no sync code. Reads query the provider; writes go straight back to it. Sync is DAVx5's / Google's / the system's job. + The app only *asks* for one through `ContentResolver.requestSync`: an + expedited nudge for the account after each of its own writes to a synced + calendar (#303, once per write, so a multi-row save or an import asks once + per account, and never `MANUAL`, which would override master-sync-off), and + a manual request from the drawer's "Sync now" (#240). Both go through + `SyncRequester`; whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 1dcbffd6f21c5552a96cd25b364adf798e0e58ad Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:35:03 +0100 Subject: [PATCH 02/17] fix(#303, #240): only ask accounts with a calendar sync adapter, review fixes --- .../data/calendar/CalendarRepository.kt | 4 ++ .../data/calendar/CalendarRepositoryImpl.kt | 44 ++++++++++++++----- .../calendula/data/calendar/SyncRequester.kt | 25 ++++++----- .../calendula/ui/CalendarHost.kt | 19 ++++---- .../calendula/ui/common/SyncViewModel.kt | 9 ++-- .../calendula/TestRepositories.kt | 17 +++++-- .../calendula/data/calendar/SyncNudgeTest.kt | 32 ++++++++++++-- .../calendula/ui/common/SyncViewModelTest.kt | 11 ++++- 8 files changed, 115 insertions(+), 46 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 7f5f8204..ddb71eb8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant interface CalendarRepository { @@ -141,6 +142,9 @@ interface CalendarRepository { */ suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync + /** Whether [requestSync] has anyone to ask: a visible calendar with a sync adapter behind it. */ + val canRequestSync: Flow get() = flowOf(false) + /** Every provider notification and [refresh], including the app's own writes. */ val providerChanges: Flow get() = emptyFlow() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index b8c4da8e..857ec5f6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -110,8 +110,8 @@ class CalendarRepositoryImpl @Inject constructor( private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection): Set = try { calendarIds().filterNotNull().distinct() - .mapNotNull { dataSource.calendarAccount(it) } - .filterTo(linkedSetOf()) { it.isSyncable } + .mapNotNull { accountOf(it) } + .filterTo(linkedSetOf()) { canSync(it) } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -119,19 +119,39 @@ class CalendarRepositoryImpl @Inject constructor( emptySet() } - private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { - syncRequester.requestSync(account, userInitiated) + /** From the shared per-tick read; a calendar newer than it is read on its own. */ + private suspend fun accountOf(calendarId: Long): SyncAccount? = + calendarsSnapshot().firstOrNull { it.id == calendarId } + ?.let { SyncAccount(it.accountName, it.accountType) } + ?: dataSource.calendarAccount(calendarId) + + private fun canSync(account: SyncAccount): Boolean = account.isSyncable && try { + syncRequester.hasAdapter(account.type) } catch (e: Exception) { - Log.w(TAG, "Sync request failed", e) + Log.w(TAG, "Sync adapters unreadable", e) false } - private fun eventCalendar(eventId: Long): suspend () -> Collection = - { listOf(dataSource.eventCalendarId(eventId)) } + private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + syncRequester.requestSync(account, userInitiated) + true + } catch (e: Exception) { + Log.w(TAG, "Sync request refused", e) + false + } + + private fun eventCalendar(eventId: Long, original: EventForm? = null): suspend () -> Collection = + { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId)) } + + private fun syncTargets(calendars: List): Set = + calendars.syncAccounts().filterTo(linkedSetOf(), ::canSync) + + override val canRequestSync: Flow + get() = calendars().map { syncTargets(it).isNotEmpty() }.distinctUntilChanged().flowOn(io) override suspend fun requestSync(): SyncRequestResult = withContext(io) { val accounts = try { - dataSource.calendars().syncAccounts() + syncTargets(calendars().first()) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -363,7 +383,7 @@ class CalendarRepositoryImpl @Inject constructor( eventId: Long, original: EventForm, updated: EventForm, - ) = write({ listOf(dataSource.eventCalendarId(eventId), updated.calendarId) }) { + ) = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), updated.calendarId) }) { dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes()) } @@ -376,7 +396,7 @@ class CalendarRepositoryImpl @Inject constructor( targetCalendarId: Long, original: EventForm, updated: EventForm, - ): Long = write({ listOf(dataSource.eventCalendarId(eventId), targetCalendarId) }) { + ): Long = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), targetCalendarId) }) { dataSource.moveEvent( eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(), ) @@ -387,7 +407,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, form: EventForm, - ): Long = write(eventCalendar(eventId)) { + ): Long = write(eventCalendar(eventId, original)) { dataSource.updateOccurrence( eventId, beginMillis, original, form, allDayReminderTimeMinutes(), ) @@ -398,7 +418,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, updated: EventForm, - ): Long = write(eventCalendar(eventId)) { + ): Long = write(eventCalendar(eventId, original)) { dataSource.updateEventFromOccurrence( eventId, beginMillis, original, updated, allDayReminderTimeMinutes(), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index 52eb42eb..e8654686 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -4,7 +4,6 @@ import android.accounts.Account import android.content.ContentResolver import android.os.Bundle import android.provider.CalendarContract -import android.util.Log import de.jeanlucmakiola.calendula.domain.CalendarSource import javax.inject.Inject import javax.inject.Singleton @@ -21,16 +20,24 @@ data class SyncAccount(val name: String, val type: String) { * itself stays the adapter's job; this only schedules it. */ interface SyncRequester { + /** Whether a calendar sync adapter is installed for [accountType]; without one a request does nothing. */ + fun hasAdapter(accountType: String): Boolean + /** - * Returns whether the request reached the system. [userInitiated] marks it - * manual, which also overrides master-sync-off — only for a user's tap. + * Schedule a sync of [account]; may throw if the system refuses. [userInitiated] + * marks it manual, which also overrides master-sync-off — only for a user's tap. */ - fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean + fun requestSync(account: SyncAccount, userInitiated: Boolean) } @Singleton class AndroidSyncRequester @Inject constructor() : SyncRequester { - override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + override fun hasAdapter(accountType: String): Boolean = + ContentResolver.getSyncAdapterTypes().any { + it.authority == CalendarContract.AUTHORITY && it.accountType == accountType + } + + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { val extras = Bundle().apply { putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) @@ -40,16 +47,12 @@ class AndroidSyncRequester @Inject constructor() : SyncRequester { CalendarContract.AUTHORITY, extras, ) - true - } catch (e: Exception) { - Log.w("SyncRequester", "Sync request refused", e) - false } } -/** The distinct accounts behind the visible, synced calendars — what a manual refresh asks. */ +/** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */ fun List.syncAccounts(): Set = - filter { !it.isLocal && it.isVisibleInSystem } + filter { it.isVisibleInSystem } .map { SyncAccount(it.accountName, it.accountType) } .filterTo(linkedSetOf()) { it.isSyncable } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 013b52ff..d8922ff9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -599,13 +599,15 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = DrawerSync( - inFlight = syncInFlight, - onSync = { - sync.requestSync() - switchScope.launch { drawerState.close() } - }, - ).takeIf { syncAvailable }, + sync = remember(syncAvailable, syncInFlight) { + DrawerSync( + inFlight = syncInFlight, + onSync = { + sync.requestSync() + switchScope.launch { drawerState.close() } + }, + ).takeIf { syncAvailable } + }, ) }, ) { @@ -635,7 +637,8 @@ fun CalendarHost( onDismissChip = { reschedule.consumeOutcome() eventActions.consumeFailure() - sync.consumeResult() + // Only the chip on show: a receipt queued behind it still gets its turn. + if (moveOutcome == null && selectionFailure == null) sync.consumeResult() }, ) CalendarFab(chromeHost, todayInToolbar, fabSelection) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 6b45c1cb..70e05048 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -7,7 +7,6 @@ import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult -import de.jeanlucmakiola.calendula.data.calendar.syncAccounts import de.jeanlucmakiola.floret.android.stateWhileSubscribed import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async @@ -15,8 +14,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject @@ -33,8 +31,7 @@ class SyncViewModel @Inject constructor( ) : ViewModel() { /** Whether any visible calendar has a sync adapter behind it. */ - val available: StateFlow = repository.calendars() - .map { it.syncAccounts().isNotEmpty() } + val available: StateFlow = repository.canRequestSync .catch { emit(false) } .stateWhileSubscribed(scope = viewModelScope, initialValue = false) @@ -53,7 +50,7 @@ class SyncViewModel @Inject constructor( try { // Listening before asking, so a sync that lands at once still counts. val settled = async(start = CoroutineStart.UNDISPATCHED) { - withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.first() } + withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.firstOrNull() } } val outcome = repository.requestSync() _result.value = outcome diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index dc7809bc..b3396f89 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -48,15 +48,24 @@ fun testRepository( syncRequester: SyncRequester = RecordingSyncRequester(), ): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester) -/** Records every sync request; [accepts] false models the system refusing one. */ -class RecordingSyncRequester(var accepts: Boolean = true) : SyncRequester { +/** + * Records every sync request; [accepts] false models the system refusing one, + * [adapterTypes] the installed calendar sync adapters (null: every type has one). + */ +class RecordingSyncRequester( + var accepts: Boolean = true, + var adapterTypes: Set? = null, +) : SyncRequester { data class Request(val account: SyncAccount, val userInitiated: Boolean) val requests = mutableListOf() - override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean { + override fun hasAdapter(accountType: String): Boolean = + adapterTypes?.contains(accountType) ?: true + + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { + if (!accepts) throw SecurityException("refused") requests += Request(account, userInitiated) - return accepts } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index d307e6e1..025609f5 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -9,6 +9,7 @@ import de.jeanlucmakiola.calendula.domain.FormTime import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.testRepository import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime @@ -135,10 +136,7 @@ class SyncNudgeTest { @Test fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest { - val throwing = object : SyncRequester { - override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = - throw SecurityException("no") - } + val throwing = RecordingSyncRequester(accepts = false) val source = fake().apply { nextInsertId = 77L } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing) @@ -187,4 +185,30 @@ class SyncNudgeTest { assertThat(calendars.syncAccounts()).containsExactly(dav) } + + @Test + fun `accounts without a calendar sync adapter are never asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(adapterTypes = setOf(dav.type)) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(3L)) + assertThat(sync.requests).isEmpty() + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true)) + } + + @Test + fun `canRequestSync needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(adapterTypes = setOf(google.type)) + val source = fake().apply { + calendarsResult = listOf(cal(1L, dav), cal(3L, google, visible = false), cal(4L, local)) + } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.canRequestSync.first()).isFalse() + + sync.adapterTypes = setOf(dav.type) + assertThat(repo.canRequestSync.first()).isTrue() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt index 0aa294a4..144b0659 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -6,7 +6,10 @@ import de.jeanlucmakiola.calendula.RecordingSyncRequester import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.testPrefs import de.jeanlucmakiola.calendula.testRepository +import de.jeanlucmakiola.calendula.testSettings +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceTimeBy @@ -29,7 +32,13 @@ class SyncViewModelTest { private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()): Pair { val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) } - return SyncViewModel(testRepository(source, dir, dispatcher, syncRequester = sync)) to source + val repo = testRepository( + source, dir, dispatcher, + prefs = testPrefs(dir, CoroutineScope(dispatcher)), + settings = testSettings(dir, CoroutineScope(dispatcher)), + syncRequester = sync, + ) + return SyncViewModel(repo) to source } @Test From d1c601a6e27a52d063a337a9de9baecedb523ff4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:44:49 +0100 Subject: [PATCH 03/17] fix(#303, #240): see sync adapters behind package visibility, review fixes --- app/src/main/AndroidManifest.xml | 4 ++ .../data/calendar/CalendarRepositoryImpl.kt | 43 ++++++++++++------- .../calendula/data/calendar/SyncRequester.kt | 15 ++++--- .../calendula/ui/CalendarHost.kt | 4 +- .../calendula/ui/common/CalendarDrawer.kt | 9 ++++ .../calendula/ui/common/EventMoveHost.kt | 14 +++--- .../calendula/ui/common/SyncViewModel.kt | 5 ++- app/src/main/res/values/strings.xml | 1 + .../calendula/TestRepositories.kt | 12 +++--- .../calendula/data/calendar/SyncNudgeTest.kt | 9 ++++ docs/ARCHITECTURE.md | 7 ++- 11 files changed, 84 insertions(+), 39 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b272d8e9..17ee1eb7 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -56,6 +56,10 @@ + + + + .withAdapter(): Set { + val candidates = filter { it.isSyncable } + if (candidates.isEmpty()) return emptySet() + val adapterTypes = try { + syncRequester.adapterAccountTypes() + } catch (e: Exception) { + Log.w(TAG, "Sync adapters unreadable", e) + return emptySet() + } + return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes } } private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { @@ -140,11 +146,16 @@ class CalendarRepositoryImpl @Inject constructor( false } - private fun eventCalendar(eventId: Long, original: EventForm? = null): suspend () -> Collection = - { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId)) } + /** The event's own calendar (from [original] when given, else read), plus [others]. */ + private fun eventCalendar( + eventId: Long, + original: EventForm? = null, + vararg others: Long?, + ): suspend () -> Collection = + { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) } private fun syncTargets(calendars: List): Set = - calendars.syncAccounts().filterTo(linkedSetOf(), ::canSync) + calendars.syncAccounts().withAdapter() override val canRequestSync: Flow get() = calendars().map { syncTargets(it).isNotEmpty() }.distinctUntilChanged().flowOn(io) @@ -158,10 +169,12 @@ class CalendarRepositoryImpl @Inject constructor( Log.w(TAG, "Sync request skipped: calendars unreadable", e) return@withContext SyncRequestResult.Failed } - when { - accounts.isEmpty() -> SyncRequestResult.NothingToSync - accounts.count { requestSync(it, userInitiated = true) } > 0 -> SyncRequestResult.Requested - else -> SyncRequestResult.Failed + if (accounts.isEmpty()) return@withContext SyncRequestResult.NothingToSync + val sent = accounts.count { requestSync(it, userInitiated = true) } + when (sent) { + accounts.size -> SyncRequestResult.Requested + 0 -> SyncRequestResult.Failed + else -> SyncRequestResult.PartlyFailed } } @@ -383,7 +396,7 @@ class CalendarRepositoryImpl @Inject constructor( eventId: Long, original: EventForm, updated: EventForm, - ) = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), updated.calendarId) }) { + ) = write(eventCalendar(eventId, original, updated.calendarId)) { dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes()) } @@ -396,7 +409,7 @@ class CalendarRepositoryImpl @Inject constructor( targetCalendarId: Long, original: EventForm, updated: EventForm, - ): Long = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), targetCalendarId) }) { + ): Long = write(eventCalendar(eventId, original, targetCalendarId)) { dataSource.moveEvent( eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index e8654686..ddcd20df 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -20,8 +20,8 @@ data class SyncAccount(val name: String, val type: String) { * itself stays the adapter's job; this only schedules it. */ interface SyncRequester { - /** Whether a calendar sync adapter is installed for [accountType]; without one a request does nothing. */ - fun hasAdapter(accountType: String): Boolean + /** Account types with a calendar sync adapter installed; for any other a request does nothing. */ + fun adapterAccountTypes(): Set /** * Schedule a sync of [account]; may throw if the system refuses. [userInitiated] @@ -32,10 +32,11 @@ interface SyncRequester { @Singleton class AndroidSyncRequester @Inject constructor() : SyncRequester { - override fun hasAdapter(accountType: String): Boolean = - ContentResolver.getSyncAdapterTypes().any { - it.authority == CalendarContract.AUTHORITY && it.accountType == accountType - } + // Lists only adapters in packages visible to the app — hence the SyncAdapter entry. + override fun adapterAccountTypes(): Set = + ContentResolver.getSyncAdapterTypes() + .filter { it.authority == CalendarContract.AUTHORITY } + .mapTo(mutableSetOf()) { it.accountType } override fun requestSync(account: SyncAccount, userInitiated: Boolean) { val extras = Bundle().apply { @@ -57,4 +58,4 @@ fun List.syncAccounts(): Set = .filterTo(linkedSetOf()) { it.isSyncable } /** Outcome of a user-triggered sync request (#240). */ -enum class SyncRequestResult { Requested, NothingToSync, Failed } +enum class SyncRequestResult { Requested, PartlyFailed, NothingToSync, Failed } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index d8922ff9..a84f8c68 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -701,8 +701,8 @@ fun CalendarHost( EventMoveHost( reschedule, modifier = Modifier.fillMaxSize(), - actionFailure = selectionFailureMessage ?: syncMessage, - onActionFailureShown = { + notice = selectionFailureMessage ?: syncMessage, + onNoticeShown = { if (selectionFailureMessage != null) eventActions.consumeFailure() else sync.consumeResult() }, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index b6f655bf..602bf99a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -41,6 +41,8 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.ui.filter.CalendarFilterList @@ -150,9 +152,16 @@ data class DrawerSync(val inFlight: Boolean, val onSync: () -> Unit) @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable private fun SyncNowRow(sync: DrawerSync) { + val inFlightText = stringResource(R.string.sync_requested) GroupedRow( title = stringResource(R.string.drawer_sync_now), position = Position.Bottom, + modifier = if (sync.inFlight) { + Modifier.semantics { stateDescription = inFlightText } + } else { + Modifier + }, + dimmed = sync.inFlight, minHeight = 56.dp, leading = { DrawerLeadingIcon(Icons.Filled.Sync) }, trailing = if (sync.inFlight) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt index 542222aa..2a0b539e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt @@ -51,8 +51,8 @@ private val FAB_BAND = 88.dp fun EventMoveHost( viewModel: RescheduleViewModel, modifier: Modifier = Modifier, - actionFailure: String? = null, - onActionFailureShown: () -> Unit = {}, + notice: String? = null, + onNoticeShown: () -> Unit = {}, ) { val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle() val outcome by viewModel.outcome.collectAsStateWithLifecycle() @@ -81,7 +81,7 @@ fun EventMoveHost( } // A failed selection action (#141) shares the chip rather than stacking on it. val message = when (outcome) { - null -> actionFailure + null -> notice is MoveOutcome.Moved -> if (resizedLabel != null) { stringResource(R.string.event_resize_done, resizedLabel) } else { @@ -116,10 +116,10 @@ fun EventMoveHost( viewModel.consumeOutcome() } // A failure waits for the chip to be free, then has its own turn. - LaunchedEffect(actionFailure, outcome == null) { - if (actionFailure == null || outcome != null) return@LaunchedEffect + LaunchedEffect(notice, outcome == null) { + if (notice == null || outcome != null) return@LaunchedEffect delay(CHIP_MILLIS) - onActionFailureShown() + onNoticeShown() } BoxWithConstraints(modifier = modifier.fillMaxSize()) { @@ -138,7 +138,7 @@ fun EventMoveHost( // write anyway, so offering it would be a button that does nothing. val undo = content.undo?.takeIf { !writeInFlight } SnackChip( - visible = outcome != null || actionFailure != null, + visible = outcome != null || notice != null, message = content.message, maxWidth = chipMaxWidth, actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 70e05048..b80a822a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -46,6 +46,8 @@ class SyncViewModel @Inject constructor( fun requestSync() { if (_inFlight.value) return _inFlight.value = true + // A repeat receipt must land as a new one, restarting the chip. + _result.value = null viewModelScope.launch { try { // Listening before asking, so a sync that lands at once still counts. @@ -54,7 +56,7 @@ class SyncViewModel @Inject constructor( } val outcome = repository.requestSync() _result.value = outcome - if (outcome == SyncRequestResult.Requested) settled.await() else settled.cancel() + if (outcome == SyncRequestResult.Requested || outcome == SyncRequestResult.PartlyFailed) settled.await() else settled.cancel() } finally { _inFlight.value = false } @@ -74,6 +76,7 @@ class SyncViewModel @Inject constructor( @StringRes fun SyncRequestResult.messageRes(): Int = when (this) { SyncRequestResult.Requested -> R.string.sync_requested + SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync SyncRequestResult.Failed -> R.string.sync_request_failed } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 20c67931..8d9d800b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -398,6 +398,7 @@ Sync now Sync requested Couldn\'t request a sync + Sync requested, but not for every account No synced calendars to sync diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index b3396f89..44eb1ae0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -49,22 +49,24 @@ fun testRepository( ): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester) /** - * Records every sync request; [accepts] false models the system refusing one, - * [adapterTypes] the installed calendar sync adapters (null: every type has one). + * Records every sync request; [accepts] false models the system refusing all, + * [refusedTypes] refusing those account types, [adapterTypes] the installed + * calendar sync adapters (null: a fixed set covering the test accounts). */ class RecordingSyncRequester( var accepts: Boolean = true, var adapterTypes: Set? = null, + var refusedTypes: Set = emptySet(), ) : SyncRequester { data class Request(val account: SyncAccount, val userInitiated: Boolean) val requests = mutableListOf() - override fun hasAdapter(accountType: String): Boolean = - adapterTypes?.contains(accountType) ?: true + override fun adapterAccountTypes(): Set = + adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL") override fun requestSync(account: SyncAccount, userInitiated: Boolean) { - if (!accepts) throw SecurityException("refused") + if (!accepts || account.type in refusedTypes) throw SecurityException("refused") requests += Request(account, userInitiated) } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 025609f5..8a347768 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -211,4 +211,13 @@ class SyncNudgeTest { sync.adapterTypes = setOf(dav.type) assertThat(repo.canRequestSync.first()).isTrue() } + + @Test + fun `manual sync refused for some accounts says so`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(refusedTypes = setOf(google.type)) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(sync.requests).containsExactly(Request(dav, true)) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9a2d8327..426ca7da 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -14,8 +14,11 @@ the package list (recurring writes, save conflicts, reminder delivery). expedited nudge for the account after each of its own writes to a synced calendar (#303, once per write, so a multi-row save or an import asks once per account, and never `MANUAL`, which would override master-sync-off), and - a manual request from the drawer's "Sync now" (#240). Both go through - `SyncRequester`; whether and when the adapter syncs stays its call. + a manual request from the drawer's "Sync now" (#240), which like the + system's own "Sync now" also runs for accounts whose auto-sync is off. Both + go through `SyncRequester` and only ask account types with a calendar sync + adapter (visible to the app via a `` entry); whether and when the + adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 55934664e2c8df68a8afaa1fb6ba49a18d13de4e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:52:42 +0100 Subject: [PATCH 04/17] fix(#303, #240): fall back to an account-less request for accounts the app can't see --- .../calendar/CalendarRepositorySmokeTest.kt | 1 + .../data/calendar/CalendarRepositoryImpl.kt | 38 +++++++++++++++---- .../calendula/data/calendar/SyncRequester.kt | 29 +++++++++++--- .../calendula/ui/common/CalendarDrawer.kt | 2 +- .../calendula/ui/common/SyncViewModel.kt | 2 - .../calendula/TestRepositories.kt | 13 +++++-- .../calendula/data/calendar/SyncNudgeTest.kt | 14 +++++++ docs/ARCHITECTURE.md | 6 ++- 8 files changed, 82 insertions(+), 23 deletions(-) diff --git a/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt index d6eea3f1..308ca955 100644 --- a/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt +++ b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt @@ -37,6 +37,7 @@ class CalendarRepositorySmokeTest { CalendarPrefs(store), SettingsPrefs(store), Dispatchers.IO, + AndroidSyncRequester(context), ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 8903e4b4..f760bc89 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -94,7 +94,7 @@ class CalendarRepositoryImpl @Inject constructor( * multi-row save or a whole import asks once per account. */ private suspend fun write( - syncCalendars: suspend () -> Collection = { emptyList() }, + syncCalendars: suspend () -> Collection, block: suspend () -> T, ): T = withContext(io) { val accounts = syncAccountsOf(syncCalendars) @@ -103,10 +103,12 @@ class CalendarRepositoryImpl @Inject constructor( } finally { refresh() writes.tryEmit(Unit) - accounts.forEach { requestSync(it, userInitiated = false) } + requestSyncs(accounts, userInitiated = false) } } + private val noSync: suspend () -> Collection = { emptyList() } + private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection): Set = try { calendarIds().filterNotNull().distinct() @@ -138,7 +140,26 @@ class CalendarRepositoryImpl @Inject constructor( return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes } } - private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + /** + * Ask each of [accounts] once; those the app can't name (see + * [SyncRequester.isAddressable]) share one request for every calendar + * account. Returns how many of [accounts] were asked. + */ + private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int { + val (direct, hidden) = accounts.partition { isAddressable(it) } + var sent = direct.count { requestSync(it, userInitiated) } + if (hidden.isNotEmpty() && requestSync(null, userInitiated)) sent += hidden.size + return sent + } + + private fun isAddressable(account: SyncAccount): Boolean = try { + syncRequester.isAddressable(account) + } catch (e: Exception) { + Log.w(TAG, "Account visibility unreadable", e) + false + } + + private fun requestSync(account: SyncAccount?, userInitiated: Boolean): Boolean = try { syncRequester.requestSync(account, userInitiated) true } catch (e: Exception) { @@ -170,7 +191,7 @@ class CalendarRepositoryImpl @Inject constructor( return@withContext SyncRequestResult.Failed } if (accounts.isEmpty()) return@withContext SyncRequestResult.NothingToSync - val sent = accounts.count { requestSync(it, userInitiated = true) } + val sent = requestSyncs(accounts, userInitiated = true) when (sent) { accounts.size -> SyncRequestResult.Requested 0 -> SyncRequestResult.Failed @@ -302,7 +323,7 @@ class CalendarRepositoryImpl @Inject constructor( displayName: String, color: Int, description: String?, - ): Long = write { + ): Long = write(noSync) { dataSource.createLocalCalendar(displayName, color, description) } @@ -311,13 +332,14 @@ class CalendarRepositoryImpl @Inject constructor( displayName: String, color: Int, description: String?, - ) = write { dataSource.updateCalendar(id, displayName, color, description) } + ) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) } override suspend fun deleteCalendar(id: Long) = - write { dataSource.deleteCalendar(id) } + write(noSync) { dataSource.deleteCalendar(id) } override suspend fun setCalendarsVisible(ids: Collection, visible: Boolean) = - write { + // VISIBLE is device-local: nothing for an adapter to upload. + write(noSync) { val canWrite = dataSource.canWriteCalendars() if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) } // Nothing of ours is left waiting for the provider once the write diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index ddcd20df..f010bbe6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -1,9 +1,13 @@ package de.jeanlucmakiola.calendula.data.calendar import android.accounts.Account +import android.accounts.AccountManager import android.content.ContentResolver +import android.content.Context +import android.os.Build import android.os.Bundle import android.provider.CalendarContract +import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.domain.CalendarSource import javax.inject.Inject import javax.inject.Singleton @@ -24,27 +28,40 @@ interface SyncRequester { fun adapterAccountTypes(): Set /** - * Schedule a sync of [account]; may throw if the system refuses. [userInitiated] - * marks it manual, which also overrides master-sync-off — only for a user's tap. + * Whether a request naming [account] reaches the system. From Android 13 one + * for an account the app can't see is dropped without a word. */ - fun requestSync(account: SyncAccount, userInitiated: Boolean) + fun isAddressable(account: SyncAccount): Boolean + + /** + * Schedule a sync of [account], or of every calendar account when null; may + * throw if the system refuses. [userInitiated] marks it manual, which also + * overrides master-sync-off — only for a user's tap. + */ + fun requestSync(account: SyncAccount?, userInitiated: Boolean) } @Singleton -class AndroidSyncRequester @Inject constructor() : SyncRequester { +class AndroidSyncRequester @Inject constructor( + @ApplicationContext private val context: Context, +) : SyncRequester { // Lists only adapters in packages visible to the app — hence the SyncAdapter entry. override fun adapterAccountTypes(): Set = ContentResolver.getSyncAdapterTypes() .filter { it.authority == CalendarContract.AUTHORITY } .mapTo(mutableSetOf()) { it.accountType } - override fun requestSync(account: SyncAccount, userInitiated: Boolean) { + override fun isAddressable(account: SyncAccount): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + AccountManager.get(context).getAccountsByType(account.type).any { it.name == account.name } + + override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { val extras = Bundle().apply { putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) } ContentResolver.requestSync( - Account(account.name, account.type), + account?.let { Account(it.name, it.type) }, CalendarContract.AUTHORITY, extras, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index 602bf99a..46de5fdf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -169,7 +169,7 @@ private fun SyncNowRow(sync: DrawerSync) { } else { null }, - onClick = { if (!sync.inFlight) sync.onSync() }, + onClick = sync.onSync.takeIf { !sync.inFlight }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index b80a822a..4c05144c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -46,8 +46,6 @@ class SyncViewModel @Inject constructor( fun requestSync() { if (_inFlight.value) return _inFlight.value = true - // A repeat receipt must land as a new one, restarting the chip. - _result.value = null viewModelScope.launch { try { // Listening before asking, so a sync that lands at once still counts. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index 44eb1ae0..b838d682 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -51,22 +51,27 @@ fun testRepository( /** * Records every sync request; [accepts] false models the system refusing all, * [refusedTypes] refusing those account types, [adapterTypes] the installed - * calendar sync adapters (null: a fixed set covering the test accounts). + * calendar sync adapters (null: a fixed set covering the test accounts), + * [hiddenTypes] account types the app can't address by name. */ class RecordingSyncRequester( var accepts: Boolean = true, var adapterTypes: Set? = null, var refusedTypes: Set = emptySet(), + var hiddenTypes: Set = emptySet(), ) : SyncRequester { - data class Request(val account: SyncAccount, val userInitiated: Boolean) + /** [account] null: one request for every calendar account. */ + data class Request(val account: SyncAccount?, val userInitiated: Boolean) val requests = mutableListOf() override fun adapterAccountTypes(): Set = adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL") - override fun requestSync(account: SyncAccount, userInitiated: Boolean) { - if (!accepts || account.type in refusedTypes) throw SecurityException("refused") + override fun isAddressable(account: SyncAccount): Boolean = account.type !in hiddenTypes + + override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { + if (!accepts || account?.type in refusedTypes) throw SecurityException("refused") requests += Request(account, userInitiated) } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 8a347768..f040b36e 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -220,4 +220,18 @@ class SyncNudgeTest { assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) assertThat(sync.requests).containsExactly(Request(dav, true)) } + + @Test + fun `accounts the app can't see share one request for every calendar account`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 3L, form(1L), form(3L)) + assertThat(sync.requests).containsExactly(Request(null, false)) + + sync.requests.clear() + sync.hiddenTypes = setOf(google.type) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true), Request(null, true)).inOrder() + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 426ca7da..e913d0bb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -17,8 +17,10 @@ the package list (recurring writes, save conflicts, reminder delivery). a manual request from the drawer's "Sync now" (#240), which like the system's own "Sync now" also runs for accounts whose auto-sync is off. Both go through `SyncRequester` and only ask account types with a calendar sync - adapter (visible to the app via a `` entry); whether and when the - adapter syncs stays its call. + adapter (visible to the app via a `` entry). From Android 13 a + request naming an account the app can't see is silently dropped, so those + accounts share one account-less request, which covers every calendar + account. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 1688b206a56865579709c732540a332ce5b8c5c8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:58:19 +0100 Subject: [PATCH 05/17] fix(#303, #240): one account-less request when any account is hidden, nudge only after a successful write --- .../data/calendar/CalendarRepositoryImpl.kt | 42 ++++++++++--------- .../calendula/data/calendar/SyncRequester.kt | 15 ++++--- .../calendula/TestRepositories.kt | 6 ++- .../calendula/data/calendar/SyncNudgeTest.kt | 12 ++++-- docs/ARCHITECTURE.md | 10 ++--- 5 files changed, 50 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index f760bc89..2a57b070 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -88,10 +88,10 @@ class CalendarRepositoryImpl @Inject constructor( override val providerChanges: Flow get() = ticks /** - * Run a provider write on [io], then re-query whether or not it threw. The - * accounts behind [syncCalendars] (read before the write, which may delete - * the row) get one sync nudge each afterwards (#303) — once per write, so a - * multi-row save or a whole import asks once per account. + * Run a provider write on [io], then re-query whether or not it threw. Once + * it succeeded, the accounts behind [syncCalendars] (read before the write, + * which may delete the row) get one sync nudge each (#303) — once per write, + * so a multi-row save or a whole import asks once per account. */ private suspend fun write( syncCalendars: suspend () -> Collection, @@ -99,11 +99,10 @@ class CalendarRepositoryImpl @Inject constructor( ): T = withContext(io) { val accounts = syncAccountsOf(syncCalendars) try { - block() + block().also { requestSyncs(accounts, userInitiated = false) } } finally { refresh() writes.tryEmit(Unit) - requestSyncs(accounts, userInitiated = false) } } @@ -141,22 +140,25 @@ class CalendarRepositoryImpl @Inject constructor( } /** - * Ask each of [accounts] once; those the app can't name (see - * [SyncRequester.isAddressable]) share one request for every calendar - * account. Returns how many of [accounts] were asked. + * Ask each of [accounts] once. If the app can't name one of them (see + * [SyncRequester.addressableAccounts]), a single account-less request for + * every calendar account goes out instead. Returns how many were asked. */ private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int { - val (direct, hidden) = accounts.partition { isAddressable(it) } - var sent = direct.count { requestSync(it, userInitiated) } - if (hidden.isNotEmpty() && requestSync(null, userInitiated)) sent += hidden.size - return sent - } - - private fun isAddressable(account: SyncAccount): Boolean = try { - syncRequester.isAddressable(account) - } catch (e: Exception) { - Log.w(TAG, "Account visibility unreadable", e) - false + if (accounts.isEmpty()) return 0 + val addressable = try { + syncRequester.addressableAccounts() + } catch (e: Exception) { + Log.w(TAG, "Account visibility unreadable", e) + emptySet() + } + return if (addressable == null || addressable.containsAll(accounts)) { + accounts.count { requestSync(it, userInitiated) } + } else if (requestSync(null, userInitiated)) { + accounts.size + } else { + 0 + } } private fun requestSync(account: SyncAccount?, userInitiated: Boolean): Boolean = try { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index f010bbe6..736b9035 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -28,10 +28,10 @@ interface SyncRequester { fun adapterAccountTypes(): Set /** - * Whether a request naming [account] reaches the system. From Android 13 one - * for an account the app can't see is dropped without a word. + * The accounts a request may name, or null when any may. From Android 13 a + * request for an account the app can't see is dropped without a word. */ - fun isAddressable(account: SyncAccount): Boolean + fun addressableAccounts(): Set? /** * Schedule a sync of [account], or of every calendar account when null; may @@ -51,9 +51,12 @@ class AndroidSyncRequester @Inject constructor( .filter { it.authority == CalendarContract.AUTHORITY } .mapTo(mutableSetOf()) { it.accountType } - override fun isAddressable(account: SyncAccount): Boolean = - Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || - AccountManager.get(context).getAccountsByType(account.type).any { it.name == account.name } + override fun addressableAccounts(): Set? = + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + null + } else { + AccountManager.get(context).accounts.mapTo(mutableSetOf()) { SyncAccount(it.name, it.type) } + } override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { val extras = Bundle().apply { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index b838d682..0b0db553 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -68,7 +68,11 @@ class RecordingSyncRequester( override fun adapterAccountTypes(): Set = adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL") - override fun isAddressable(account: SyncAccount): Boolean = account.type !in hiddenTypes + override fun addressableAccounts(): Set? = + if (hiddenTypes.isEmpty()) null else knownAccounts.filterTo(mutableSetOf()) { it.type !in hiddenTypes } + + /** The accounts on the "device", for [addressableAccounts]. */ + var knownAccounts: Set = emptySet() override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { if (!accepts || account?.type in refusedTypes) throw SecurityException("refused") diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index f040b36e..60fdc3af 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -124,14 +124,14 @@ class SyncNudgeTest { } @Test - fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest { + fun `a failed write asks for no sync`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester() val source = fake().apply { writeError = IllegalStateException("boom") } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) assertThrows { repo.deleteEvent(10L) } - assertThat(sync.requests).containsExactly(auto(dav)) + assertThat(sync.requests).isEmpty() } @Test @@ -224,6 +224,7 @@ class SyncNudgeTest { @Test fun `accounts the app can't see share one request for every calendar account`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + sync.knownAccounts = setOf(dav, google) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) repo.moveEvent(10L, 3L, form(1L), form(3L)) @@ -232,6 +233,11 @@ class SyncNudgeTest { sync.requests.clear() sync.hiddenTypes = setOf(google.type) assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) - assertThat(sync.requests).containsExactly(Request(dav, true), Request(null, true)).inOrder() + assertThat(sync.requests).containsExactly(Request(null, true)) + + sync.requests.clear() + sync.hiddenTypes = setOf("other") + repo.createEvent(form(1L)) + assertThat(sync.requests).containsExactly(auto(dav)) } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e913d0bb..2fed75c5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -11,16 +11,16 @@ the package list (recurring writes, save conflicts, reminder delivery). no caching layer, no sync code. Reads query the provider; writes go straight back to it. Sync is DAVx5's / Google's / the system's job. The app only *asks* for one through `ContentResolver.requestSync`: an - expedited nudge for the account after each of its own writes to a synced - calendar (#303, once per write, so a multi-row save or an import asks once + expedited nudge for the account after each of its own successful writes to + a synced calendar (#303, once per write, so a multi-row save or an import asks once per account, and never `MANUAL`, which would override master-sync-off), and a manual request from the drawer's "Sync now" (#240), which like the system's own "Sync now" also runs for accounts whose auto-sync is off. Both go through `SyncRequester` and only ask account types with a calendar sync adapter (visible to the app via a `` entry). From Android 13 a - request naming an account the app can't see is silently dropped, so those - accounts share one account-less request, which covers every calendar - account. Whether and when the adapter syncs stays its call. + request naming an account the app can't see is silently dropped, so when + any of them is hidden a single account-less request, which covers every + calendar account, goes out instead. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 8c31e0f6ee05184f3c8de23fd22c7e26bce95e38 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 19:04:07 +0100 Subject: [PATCH 06/17] fix(#303): nudge after failed writes again, per-type account visibility --- .../data/calendar/CalendarRepositoryImpl.kt | 14 ++++++----- .../calendula/data/calendar/SyncRequester.kt | 17 ++++++------- .../calendula/TestRepositories.kt | 13 ++++++++-- .../calendula/data/calendar/SyncNudgeTest.kt | 24 +++++++++++++++++-- docs/ARCHITECTURE.md | 4 ++-- 5 files changed, 52 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 2a57b070..14e34855 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -88,10 +88,11 @@ class CalendarRepositoryImpl @Inject constructor( override val providerChanges: Flow get() = ticks /** - * Run a provider write on [io], then re-query whether or not it threw. Once - * it succeeded, the accounts behind [syncCalendars] (read before the write, - * which may delete the row) get one sync nudge each (#303) — once per write, - * so a multi-row save or a whole import asks once per account. + * Run a provider write on [io], then re-query whether or not it threw. The + * accounts behind [syncCalendars] (read before the write, which may delete + * the row) then get one sync nudge each (#303), also after a failure, which + * may have landed part of a multi-row write. Once per write, so a multi-row + * save or a whole import asks once per account. */ private suspend fun write( syncCalendars: suspend () -> Collection, @@ -99,10 +100,11 @@ class CalendarRepositoryImpl @Inject constructor( ): T = withContext(io) { val accounts = syncAccountsOf(syncCalendars) try { - block().also { requestSyncs(accounts, userInitiated = false) } + block() } finally { refresh() writes.tryEmit(Unit) + requestSyncs(accounts, userInitiated = false) } } @@ -147,7 +149,7 @@ class CalendarRepositoryImpl @Inject constructor( private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int { if (accounts.isEmpty()) return 0 val addressable = try { - syncRequester.addressableAccounts() + syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type }) } catch (e: Exception) { Log.w(TAG, "Account visibility unreadable", e) emptySet() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index 736b9035..c57db9f7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -28,10 +28,10 @@ interface SyncRequester { fun adapterAccountTypes(): Set /** - * The accounts a request may name, or null when any may. From Android 13 a - * request for an account the app can't see is dropped without a word. + * The accounts of [types] a request may name, or null when any may. From + * Android 13 a request for an account the app can't see is dropped without a word. */ - fun addressableAccounts(): Set? + fun addressableAccounts(types: Set): Set? /** * Schedule a sync of [account], or of every calendar account when null; may @@ -51,12 +51,13 @@ class AndroidSyncRequester @Inject constructor( .filter { it.authority == CalendarContract.AUTHORITY } .mapTo(mutableSetOf()) { it.accountType } - override fun addressableAccounts(): Set? = - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { - null - } else { - AccountManager.get(context).accounts.mapTo(mutableSetOf()) { SyncAccount(it.name, it.type) } + override fun addressableAccounts(types: Set): Set? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null + val manager = AccountManager.get(context) + return types.flatMapTo(mutableSetOf()) { type -> + manager.getAccountsByType(type).map { SyncAccount(it.name, it.type) } } + } override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { val extras = Bundle().apply { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index 0b0db553..c5a602a9 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -68,8 +68,17 @@ class RecordingSyncRequester( override fun adapterAccountTypes(): Set = adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL") - override fun addressableAccounts(): Set? = - if (hiddenTypes.isEmpty()) null else knownAccounts.filterTo(mutableSetOf()) { it.type !in hiddenTypes } + override fun addressableAccounts(types: Set): Set? { + visibilityError?.let { throw it } + return if (hiddenTypes.isEmpty()) { + null + } else { + knownAccounts.filterTo(mutableSetOf()) { it.type in types && it.type !in hiddenTypes } + } + } + + /** Thrown by [addressableAccounts] when set. */ + var visibilityError: Exception? = null /** The accounts on the "device", for [addressableAccounts]. */ var knownAccounts: Set = emptySet() diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 60fdc3af..0a5b7673 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -124,14 +124,14 @@ class SyncNudgeTest { } @Test - fun `a failed write asks for no sync`(@TempDir dir: Path) = runTest { + fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester() val source = fake().apply { writeError = IllegalStateException("boom") } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) assertThrows { repo.deleteEvent(10L) } - assertThat(sync.requests).isEmpty() + assertThat(sync.requests).containsExactly(auto(dav)) } @Test @@ -240,4 +240,24 @@ class SyncNudgeTest { repo.createEvent(form(1L)) assertThat(sync.requests).containsExactly(auto(dav)) } + + @Test + fun `unreadable account visibility falls back to the account-less request`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf("other")) + sync.visibilityError = SecurityException("no") + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(Request(null, false)) + } + + @Test + fun `a refused account-less request reports a failure`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(accepts = false, hiddenTypes = setOf(dav.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2fed75c5..ff3e213a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -11,8 +11,8 @@ the package list (recurring writes, save conflicts, reminder delivery). no caching layer, no sync code. Reads query the provider; writes go straight back to it. Sync is DAVx5's / Google's / the system's job. The app only *asks* for one through `ContentResolver.requestSync`: an - expedited nudge for the account after each of its own successful writes to - a synced calendar (#303, once per write, so a multi-row save or an import asks once + expedited nudge for the account after each of its own writes to a synced + calendar (#303, once per write, so a multi-row save or an import asks once per account, and never `MANUAL`, which would override master-sync-off), and a manual request from the drawer's "Sync now" (#240), which like the system's own "Sync now" also runs for accounts whose auto-sync is off. Both From 88de8f42b0a783355ca8da1e02dac9c9ea94639b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 21:57:55 +0100 Subject: [PATCH 07/17] feat(#240, #303): grant account access for sync requests instead of an account-less fallback --- .../data/calendar/CalendarRepository.kt | 8 ++- .../data/calendar/CalendarRepositoryImpl.kt | 57 +++++++++-------- .../calendula/data/calendar/SyncRequester.kt | 37 +++++++++-- .../calendula/ui/CalendarHost.kt | 37 ++++++++++- .../calendula/ui/common/CalendarDrawer.kt | 44 ++++++++++--- .../calendula/ui/common/SyncViewModel.kt | 26 ++++++-- app/src/main/res/values/strings.xml | 3 + .../calendula/TestRepositories.kt | 7 +-- .../calendula/data/calendar/SyncNudgeTest.kt | 62 +++++++++++-------- .../calendula/ui/common/SyncViewModelTest.kt | 21 +++++++ docs/ARCHITECTURE.md | 11 +++- 11 files changed, 232 insertions(+), 81 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index ddb71eb8..6afb86d1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -142,8 +142,12 @@ interface CalendarRepository { */ suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync - /** Whether [requestSync] has anyone to ask: a visible calendar with a sync adapter behind it. */ - val canRequestSync: Flow get() = flowOf(false) + /** + * The accounts behind visible calendars with a sync adapter, split by + * whether [requestSync] can reach them yet. Re-reads account access on + * every collection, so a grant or revoke shows on the next one. + */ + val syncTargets: Flow get() = flowOf(SyncTargets.None) /** Every provider notification and [refresh], including the app's own writes. */ val providerChanges: Flow get() = emptyFlow() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 14e34855..09a2e8a4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -142,28 +142,29 @@ class CalendarRepositoryImpl @Inject constructor( } /** - * Ask each of [accounts] once. If the app can't name one of them (see - * [SyncRequester.addressableAccounts]), a single account-less request for - * every calendar account goes out instead. Returns how many were asked. + * Splits [accounts] by whether a request may name them (see + * [SyncRequester.addressableAccounts]). The rest wait for the user's grant: + * an account-less request would reach them, but also every other calendar + * account on the device, so none is sent. */ - private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int { - if (accounts.isEmpty()) return 0 + private fun reach(accounts: Set): SyncTargets { + if (accounts.isEmpty()) return SyncTargets.None val addressable = try { syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type }) } catch (e: Exception) { Log.w(TAG, "Account visibility unreadable", e) emptySet() } - return if (addressable == null || addressable.containsAll(accounts)) { - accounts.count { requestSync(it, userInitiated) } - } else if (requestSync(null, userInitiated)) { - accounts.size - } else { - 0 - } + if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet()) + val (reachable, hidden) = accounts.partition { it in addressable } + return SyncTargets(reachable.toSet(), hidden.toSet()) } - private fun requestSync(account: SyncAccount?, userInitiated: Boolean): Boolean = try { + /** Ask each reachable one of [accounts] once; returns how many were asked. */ + private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int = + reach(accounts).reachable.count { requestSync(it, userInitiated) } + + private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { syncRequester.requestSync(account, userInitiated) true } catch (e: Exception) { @@ -179,27 +180,33 @@ class CalendarRepositoryImpl @Inject constructor( ): suspend () -> Collection = { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) } - private fun syncTargets(calendars: List): Set = - calendars.syncAccounts().withAdapter() + private fun targetsOf(calendars: List): SyncTargets = + reach(calendars.syncAccounts().withAdapter()) - override val canRequestSync: Flow - get() = calendars().map { syncTargets(it).isNotEmpty() }.distinctUntilChanged().flowOn(io) + override val syncTargets: Flow + get() = calendars().map { targetsOf(it) }.flowOn(io) override suspend fun requestSync(): SyncRequestResult = withContext(io) { - val accounts = try { - syncTargets(calendars().first()) + val targets = try { + targetsOf(calendars().first()) } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.w(TAG, "Sync request skipped: calendars unreadable", e) return@withContext SyncRequestResult.Failed } - if (accounts.isEmpty()) return@withContext SyncRequestResult.NothingToSync - val sent = requestSyncs(accounts, userInitiated = true) - when (sent) { - accounts.size -> SyncRequestResult.Requested - 0 -> SyncRequestResult.Failed - else -> SyncRequestResult.PartlyFailed + if (targets.reachable.isEmpty()) { + return@withContext if (targets.needsAccess.isEmpty()) { + SyncRequestResult.NothingToSync + } else { + SyncRequestResult.Failed + } + } + val sent = targets.reachable.count { requestSync(it, userInitiated = true) } + when { + sent == 0 -> SyncRequestResult.Failed + sent < targets.reachable.size || targets.needsAccess.isNotEmpty() -> SyncRequestResult.PartlyFailed + else -> SyncRequestResult.Requested } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index c57db9f7..d81acafe 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -4,6 +4,7 @@ import android.accounts.Account import android.accounts.AccountManager import android.content.ContentResolver import android.content.Context +import android.content.Intent import android.os.Build import android.os.Bundle import android.provider.CalendarContract @@ -34,11 +35,10 @@ interface SyncRequester { fun addressableAccounts(types: Set): Set? /** - * Schedule a sync of [account], or of every calendar account when null; may - * throw if the system refuses. [userInitiated] marks it manual, which also - * overrides master-sync-off — only for a user's tap. + * Schedule a sync of [account]; may throw if the system refuses. [userInitiated] + * marks it manual, which also overrides master-sync-off — only for a user's tap. */ - fun requestSync(account: SyncAccount?, userInitiated: Boolean) + fun requestSync(account: SyncAccount, userInitiated: Boolean) } @Singleton @@ -59,13 +59,13 @@ class AndroidSyncRequester @Inject constructor( } } - override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { val extras = Bundle().apply { putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) } ContentResolver.requestSync( - account?.let { Account(it.name, it.type) }, + Account(account.name, account.type), CalendarContract.AUTHORITY, extras, ) @@ -78,5 +78,30 @@ fun List.syncAccounts(): Set = .map { SyncAccount(it.accountName, it.accountType) } .filterTo(linkedSetOf()) { it.isSyncable } +/** + * Who a sync request can go to: [reachable] by name, [needsAccess] only once the + * user lets the app see the account (Android 13+, see [accountAccessIntent]). + */ +data class SyncTargets(val reachable: Set, val needsAccess: Set) { + companion object { + val None = SyncTargets(emptySet(), emptySet()) + } +} + +/** + * The system account picker, limited to [accounts]: the one the user picks + * becomes visible to the app, so sync requests can name it. One account per pick. + */ +fun accountAccessIntent(accounts: Collection, description: String): Intent = + AccountManager.newChooseAccountIntent( + null, + accounts.map { Account(it.name, it.type) }, + accounts.map { it.type }.distinct().toTypedArray(), + description, + null, + null, + null, + ) + /** Outcome of a user-triggered sync request (#240). */ enum class SyncRequestResult { Requested, PartlyFailed, NothingToSync, Failed } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index a84f8c68..9cd7e5c1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -1,6 +1,10 @@ package de.jeanlucmakiola.calendula.ui +import android.content.ActivityNotFoundException +import android.util.Log import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.compose.PredictiveBackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility @@ -44,6 +48,7 @@ import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.time.currentDate import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance @@ -53,6 +58,8 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip import de.jeanlucmakiola.calendula.ui.common.StayingPut import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent import de.jeanlucmakiola.calendula.ui.common.DrawerSync import de.jeanlucmakiola.calendula.ui.common.SyncViewModel import de.jeanlucmakiola.calendula.ui.common.messageRes @@ -447,11 +454,24 @@ fun CalendarHost( val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() // "Sync now" in the drawer (#240); its receipt shares the move chip. val sync: SyncViewModel = hiltViewModel() - val syncAvailable by sync.available.collectAsStateWithLifecycle() + val syncTargets by sync.targets.collectAsStateWithLifecycle() val syncInFlight by sync.inFlight.collectAsStateWithLifecycle() val syncResult by sync.result.collectAsStateWithLifecycle() val selectionFailureMessage = eventActionFailureMessage(selectionFailure) val syncMessage = syncResult?.let { stringResource(it.messageRes()) } + // The system account picker grants access to one account per pick; whatever + // the outcome, access is re-read rather than trusted from the result. + val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + sync.refreshAccess() + } + val accessPickerDescription = stringResource(R.string.sync_access_picker_description) + val launchAccessPicker: (Set) -> Unit = { accounts -> + try { + accessPicker.launch(accountAccessIntent(accounts, accessPickerDescription)) + } catch (e: ActivityNotFoundException) { + Log.w("CalendarHost", "No account picker", e) + } + } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -549,6 +569,11 @@ fun CalendarHost( val stayingPut = remember { StayingPut() } val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) + // Account access can be granted or revoked outside the app; re-read it + // whenever the drawer that offers the grant opens. + LaunchedEffect(drawerState.targetValue) { + if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() + } val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -599,14 +624,20 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = remember(syncAvailable, syncInFlight) { + sync = remember(syncTargets, syncInFlight) { DrawerSync( + canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, + needsAccess = syncTargets.needsAccess.map { it.name }, onSync = { sync.requestSync() switchScope.launch { drawerState.close() } }, - ).takeIf { syncAvailable } + onGrantAccess = { + launchAccessPicker(syncTargets.needsAccess) + switchScope.launch { drawerState.close() } + }, + ) }, ) }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index 46de5fdf..2d5b567e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -20,6 +20,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.ManageAccounts import androidx.compose.material.icons.filled.Sync import androidx.compose.material3.DrawerState import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -66,7 +67,8 @@ import kotlinx.datetime.LocalDate * * [currentDate] seeds the jump-to-date picker (the visible day/week-start/month * anchor); [onJumpToDate] navigates the active view to the chosen day. - * [sync] adds "Sync now" beside it while there is a synced calendar (#240). + * [sync] adds "Sync now" beside it while there is a synced calendar (#240), + * and a row to grant account access while some account can't be reached yet. */ @Composable fun CalendarDrawer( @@ -110,12 +112,12 @@ fun CalendarDrawer( Spacer(Modifier.height(16.dp)) GroupedRow( title = stringResource(R.string.drawer_jump_to_date), - position = if (sync != null) Position.Top else Position.Alone, + position = if (sync?.hasRows == true) Position.Top else Position.Alone, minHeight = 56.dp, leading = { DrawerLeadingIcon(Icons.Filled.DateRange) }, onClick = { showDatePicker = true }, ) - if (sync != null) SyncNowRow(sync) + if (sync != null) SyncRows(sync) Spacer(Modifier.height(16.dp)) @@ -146,16 +148,44 @@ fun CalendarDrawer( } } -/** The drawer's "Sync now" state: [inFlight] shows progress and ignores taps. */ -data class DrawerSync(val inFlight: Boolean, val onSync: () -> Unit) +/** + * The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress + * and ignores taps), and a grant row naming the [needsAccess] accounts. + */ +data class DrawerSync( + val canSync: Boolean, + val inFlight: Boolean, + val needsAccess: List, + val onSync: () -> Unit, + val onGrantAccess: () -> Unit, +) { + val hasRows: Boolean get() = canSync || needsAccess.isNotEmpty() +} + +@Composable +private fun SyncRows(sync: DrawerSync) { + if (sync.canSync) { + SyncNowRow(sync, if (sync.needsAccess.isEmpty()) Position.Bottom else Position.Middle) + } + if (sync.needsAccess.isNotEmpty()) { + GroupedRow( + title = stringResource(R.string.drawer_sync_access), + summary = stringResource(R.string.drawer_sync_access_summary, sync.needsAccess.joinToString()), + position = Position.Bottom, + minHeight = 56.dp, + leading = { DrawerLeadingIcon(Icons.Filled.ManageAccounts) }, + onClick = sync.onGrantAccess, + ) + } +} @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -private fun SyncNowRow(sync: DrawerSync) { +private fun SyncNowRow(sync: DrawerSync, position: Position) { val inFlightText = stringResource(R.string.sync_requested) GroupedRow( title = stringResource(R.string.drawer_sync_now), - position = Position.Bottom, + position = position, modifier = if (sync.inFlight) { Modifier.semantics { stateDescription = inFlightText } } else { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 4c05144c..bf38193e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -7,14 +7,18 @@ import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import de.jeanlucmakiola.floret.android.stateWhileSubscribed import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.firstOrNull +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject @@ -30,10 +34,21 @@ class SyncViewModel @Inject constructor( private val repository: CalendarRepository, ) : ViewModel() { - /** Whether any visible calendar has a sync adapter behind it. */ - val available: StateFlow = repository.canRequestSync - .catch { emit(false) } - .stateWhileSubscribed(scope = viewModelScope, initialValue = false) + private val accessChecks = MutableStateFlow(0) + + /** + * Who "Sync now" can reach, and who first needs the user's grant. Account + * access isn't observable, so it is re-read on every [refreshAccess]. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val targets: StateFlow = accessChecks + .flatMapLatest { repository.syncTargets.catch { emit(SyncTargets.None) } } + .stateWhileSubscribed(scope = viewModelScope, initialValue = SyncTargets.None) + + /** Re-read account access: after the picker returns, and whenever the drawer opens. */ + fun refreshAccess() { + accessChecks.update { it + 1 } + } private val _inFlight = MutableStateFlow(false) val inFlight: StateFlow = _inFlight.asStateFlow() @@ -54,7 +69,8 @@ class SyncViewModel @Inject constructor( } val outcome = repository.requestSync() _result.value = outcome - if (outcome == SyncRequestResult.Requested || outcome == SyncRequestResult.PartlyFailed) settled.await() else settled.cancel() + val sent = outcome == SyncRequestResult.Requested || outcome == SyncRequestResult.PartlyFailed + if (sent) settled.await() else settled.cancel() } finally { _inFlight.value = false } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8d9d800b..c5504106 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -396,6 +396,9 @@ Jump to date Sync now + Allow sync requests + Calendula can\'t ask %1$s to sync yet + Choose an account Calendula may ask to sync your calendars Sync requested Couldn\'t request a sync Sync requested, but not for every account diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index c5a602a9..460a16f4 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -60,8 +60,7 @@ class RecordingSyncRequester( var refusedTypes: Set = emptySet(), var hiddenTypes: Set = emptySet(), ) : SyncRequester { - /** [account] null: one request for every calendar account. */ - data class Request(val account: SyncAccount?, val userInitiated: Boolean) + data class Request(val account: SyncAccount, val userInitiated: Boolean) val requests = mutableListOf() @@ -83,8 +82,8 @@ class RecordingSyncRequester( /** The accounts on the "device", for [addressableAccounts]. */ var knownAccounts: Set = emptySet() - override fun requestSync(account: SyncAccount?, userInitiated: Boolean) { - if (!accepts || account?.type in refusedTypes) throw SecurityException("refused") + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { + if (!accepts || account.type in refusedTypes) throw SecurityException("refused") requests += Request(account, userInitiated) } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 0a5b7673..a9ea68d9 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -199,17 +199,17 @@ class SyncNudgeTest { } @Test - fun `canRequestSync needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest { + fun `syncTargets needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester(adapterTypes = setOf(google.type)) val source = fake().apply { calendarsResult = listOf(cal(1L, dav), cal(3L, google, visible = false), cal(4L, local)) } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.canRequestSync.first()).isFalse() + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None) sync.adapterTypes = setOf(dav.type) - assertThat(repo.canRequestSync.first()).isTrue() + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet())) } @Test @@ -222,42 +222,52 @@ class SyncNudgeTest { } @Test - fun `accounts the app can't see share one request for every calendar account`(@TempDir dir: Path) = runTest { - val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + fun `accounts the app can't see wait for access instead of being asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) sync.knownAccounts = setOf(dav, google) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) repo.moveEvent(10L, 3L, form(1L), form(3L)) - assertThat(sync.requests).containsExactly(Request(null, false)) - - sync.requests.clear() - sync.hiddenTypes = setOf(google.type) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) - assertThat(sync.requests).containsExactly(Request(null, true)) - - sync.requests.clear() - sync.hiddenTypes = setOf("other") - repo.createEvent(form(1L)) assertThat(sync.requests).containsExactly(auto(dav)) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) + + sync.requests.clear() + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(sync.requests).containsExactly(Request(dav, true)) } @Test - fun `unreadable account visibility falls back to the account-less request`(@TempDir dir: Path) = runTest { + fun `once access is granted the account is asked by name`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + sync.hiddenTypes = setOf("other") + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav, google), emptySet())) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + } + + @Test + fun `only hidden accounts make manual sync fail without asking anyone`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + repo.createEvent(form(1L)) + assertThat(sync.requests).isEmpty() + } + + @Test + fun `unreadable account visibility asks no one`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester(hiddenTypes = setOf("other")) sync.visibilityError = SecurityException("no") val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) repo.createEvent(form(1L)) - assertThat(sync.requests).containsExactly(Request(null, false)) - } - - @Test - fun `a refused account-less request reports a failure`(@TempDir dir: Path) = runTest { - val sync = RecordingSyncRequester(accepts = false, hiddenTypes = setOf(dav.type)) - sync.knownAccounts = setOf(dav, google) - val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) - - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + assertThat(sync.requests).isEmpty() } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt index 144b0659..d755a9fc 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -4,7 +4,10 @@ import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.MainDispatcherExtension import de.jeanlucmakiola.calendula.RecordingSyncRequester import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets +import kotlinx.coroutines.launch import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.testPrefs import de.jeanlucmakiola.calendula.testRepository @@ -28,6 +31,7 @@ class SyncViewModelTest { private val dispatcher = mainDispatcher.dispatcher private val synced = CalendarSource(1L, "Work", "me@dav", "bitfire.at.davdroid", 0, true) + private val davAccount = SyncAccount("me@dav", "bitfire.at.davdroid") private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()): Pair { @@ -93,4 +97,21 @@ class SyncViewModelTest { vm.consumeResult() assertThat(vm.result.value).isNull() } + + @Test + fun `refreshAccess picks up a grant`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type)) + sync.knownAccounts = setOf(davAccount) + val (vm, _) = viewModel(dir, sync) + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), setOf(davAccount))) + + sync.hiddenTypes = setOf("other") + vm.refreshAccess() + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(setOf(davAccount), emptySet())) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ff3e213a..2f2f28e1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -18,9 +18,14 @@ the package list (recurring writes, save conflicts, reminder delivery). system's own "Sync now" also runs for accounts whose auto-sync is off. Both go through `SyncRequester` and only ask account types with a calendar sync adapter (visible to the app via a `` entry). From Android 13 a - request naming an account the app can't see is silently dropped, so when - any of them is hidden a single account-less request, which covers every - calendar account, goes out instead. Whether and when the adapter syncs stays its call. + request naming an account the app can't see is silently dropped, and + without `GET_ACCOUNTS` that is most of them. Such accounts are not asked at + all (an account-less request would sync every account on the device); the + drawer offers "Allow sync requests" instead, which opens the system account + picker (`AccountManager.newChooseAccountIntent`) — the picked account + becomes visible to the app. Access is re-read on every request and when + the drawer opens, so a revoke simply puts the account back behind the + grant row. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 67052352acbc532c26cc5a52f321df10c7bfef94 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 22:04:44 +0100 Subject: [PATCH 08/17] fix(#240): access re-read on resume, needs-access receipt, drawer stays open for the next grant --- .../data/calendar/CalendarRepositoryImpl.kt | 7 +++--- .../calendula/data/calendar/SyncRequester.kt | 2 +- .../calendula/ui/CalendarHost.kt | 23 ++++++++----------- .../calendula/ui/common/SyncViewModel.kt | 3 ++- app/src/main/res/values/strings.xml | 1 + .../calendula/data/calendar/SyncNudgeTest.kt | 10 ++++---- docs/ARCHITECTURE.md | 4 ++-- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 09a2e8a4..b3c614a8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -149,11 +149,12 @@ class CalendarRepositoryImpl @Inject constructor( */ private fun reach(accounts: Set): SyncTargets { if (accounts.isEmpty()) return SyncTargets.None + // Unreadable access counts as reachable: a grant can't fix a failing read. val addressable = try { syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type }) } catch (e: Exception) { Log.w(TAG, "Account visibility unreadable", e) - emptySet() + null } if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet()) val (reachable, hidden) = accounts.partition { it in addressable } @@ -199,13 +200,13 @@ class CalendarRepositoryImpl @Inject constructor( return@withContext if (targets.needsAccess.isEmpty()) { SyncRequestResult.NothingToSync } else { - SyncRequestResult.Failed + SyncRequestResult.NeedsAccess } } val sent = targets.reachable.count { requestSync(it, userInitiated = true) } when { sent == 0 -> SyncRequestResult.Failed - sent < targets.reachable.size || targets.needsAccess.isNotEmpty() -> SyncRequestResult.PartlyFailed + sent < targets.reachable.size -> SyncRequestResult.PartlyFailed else -> SyncRequestResult.Requested } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index d81acafe..94ed46ee 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -104,4 +104,4 @@ fun accountAccessIntent(accounts: Collection, description: String): ) /** Outcome of a user-triggered sync request (#240). */ -enum class SyncRequestResult { Requested, PartlyFailed, NothingToSync, Failed } +enum class SyncRequestResult { Requested, PartlyFailed, NeedsAccess, NothingToSync, Failed } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 9cd7e5c1..6576138f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -5,6 +5,8 @@ import android.util.Log import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.activity.compose.PredictiveBackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility @@ -461,9 +463,10 @@ fun CalendarHost( val syncMessage = syncResult?.let { stringResource(it.messageRes()) } // The system account picker grants access to one account per pick; whatever // the outcome, access is re-read rather than trusted from the result. - val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { - sync.refreshAccess() - } + // Access can also be granted or revoked in system settings: re-read on every + // resume, which covers the picker returning too. + val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {} + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } val accessPickerDescription = stringResource(R.string.sync_access_picker_description) val launchAccessPicker: (Set) -> Unit = { accounts -> try { @@ -569,11 +572,6 @@ fun CalendarHost( val stayingPut = remember { StayingPut() } val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) - // Account access can be granted or revoked outside the app; re-read it - // whenever the drawer that offers the grant opens. - LaunchedEffect(drawerState.targetValue) { - if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() - } val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -628,15 +626,14 @@ fun CalendarHost( DrawerSync( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, - needsAccess = syncTargets.needsAccess.map { it.name }, + needsAccess = syncTargets.needsAccess.map { it.name }.distinct(), onSync = { sync.requestSync() switchScope.launch { drawerState.close() } }, - onGrantAccess = { - launchAccessPicker(syncTargets.needsAccess) - switchScope.launch { drawerState.close() } - }, + // The drawer stays open: one pick grants one account, + // and the row is right there for the next. + onGrantAccess = { launchAccessPicker(syncTargets.needsAccess) }, ) }, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index bf38193e..4207019e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -45,7 +45,7 @@ class SyncViewModel @Inject constructor( .flatMapLatest { repository.syncTargets.catch { emit(SyncTargets.None) } } .stateWhileSubscribed(scope = viewModelScope, initialValue = SyncTargets.None) - /** Re-read account access: after the picker returns, and whenever the drawer opens. */ + /** Re-read account access: whenever the app resumes, which includes the picker returning. */ fun refreshAccess() { accessChecks.update { it + 1 } } @@ -91,6 +91,7 @@ class SyncViewModel @Inject constructor( fun SyncRequestResult.messageRes(): Int = when (this) { SyncRequestResult.Requested -> R.string.sync_requested SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed + SyncRequestResult.NeedsAccess -> R.string.sync_request_needs_access SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync SyncRequestResult.Failed -> R.string.sync_request_failed } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c5504106..62ea96d1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -401,6 +401,7 @@ Choose an account Calendula may ask to sync your calendars Sync requested Couldn\'t request a sync + Allow sync requests in the menu first Sync requested, but not for every account No synced calendars to sync diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index a9ea68d9..5f5b956f 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -233,7 +233,7 @@ class SyncNudgeTest { assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) sync.requests.clear() - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) assertThat(sync.requests).containsExactly(Request(dav, true)) } @@ -250,24 +250,24 @@ class SyncNudgeTest { } @Test - fun `only hidden accounts make manual sync fail without asking anyone`(@TempDir dir: Path) = runTest { + fun `only hidden accounts make manual sync ask for access, asking no one`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) sync.knownAccounts = setOf(dav, google) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NeedsAccess) repo.createEvent(form(1L)) assertThat(sync.requests).isEmpty() } @Test - fun `unreadable account visibility asks no one`(@TempDir dir: Path) = runTest { + fun `unreadable account visibility counts as reachable`(@TempDir dir: Path) = runTest { val sync = RecordingSyncRequester(hiddenTypes = setOf("other")) sync.visibilityError = SecurityException("no") val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) repo.createEvent(form(1L)) - assertThat(sync.requests).isEmpty() + assertThat(sync.requests).containsExactly(auto(dav)) } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2f2f28e1..5a839865 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -23,8 +23,8 @@ the package list (recurring writes, save conflicts, reminder delivery). all (an account-less request would sync every account on the device); the drawer offers "Allow sync requests" instead, which opens the system account picker (`AccountManager.newChooseAccountIntent`) — the picked account - becomes visible to the app. Access is re-read on every request and when - the drawer opens, so a revoke simply puts the account back behind the + becomes visible to the app. Access is re-read on every request and on + every resume, so a revoke simply puts the account back behind the grant row. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a From e88ad7f5339723d5b671417da76d61a4a48c68c1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 22:10:04 +0100 Subject: [PATCH 09/17] fix(#240): guard double picker launch, flag skipped accounts in the receipt, translatable grant summary --- .../data/calendar/CalendarRepositoryImpl.kt | 2 +- .../calendula/ui/CalendarHost.kt | 30 +++++++++++-------- .../calendula/ui/common/CalendarDrawer.kt | 12 ++++---- app/src/main/res/values/strings.xml | 2 +- .../calendula/data/calendar/SyncNudgeTest.kt | 2 +- docs/ARCHITECTURE.md | 2 +- 6 files changed, 27 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index b3c614a8..7c11eac9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -206,7 +206,7 @@ class CalendarRepositoryImpl @Inject constructor( val sent = targets.reachable.count { requestSync(it, userInitiated = true) } when { sent == 0 -> SyncRequestResult.Failed - sent < targets.reachable.size -> SyncRequestResult.PartlyFailed + sent < targets.reachable.size || targets.needsAccess.isNotEmpty() -> SyncRequestResult.PartlyFailed else -> SyncRequestResult.Requested } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 6576138f..cd6bbfa3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -461,18 +461,21 @@ fun CalendarHost( val syncResult by sync.result.collectAsStateWithLifecycle() val selectionFailureMessage = eventActionFailureMessage(selectionFailure) val syncMessage = syncResult?.let { stringResource(it.messageRes()) } - // The system account picker grants access to one account per pick; whatever - // the outcome, access is re-read rather than trusted from the result. - // Access can also be granted or revoked in system settings: re-read on every - // resume, which covers the picker returning too. - val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {} + // Access is re-read on resume (covering the picker's return), never trusted from the result. + var accessPickerOpen by remember { mutableStateOf(false) } + val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + accessPickerOpen = false + } LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } val accessPickerDescription = stringResource(R.string.sync_access_picker_description) val launchAccessPicker: (Set) -> Unit = { accounts -> - try { - accessPicker.launch(accountAccessIntent(accounts, accessPickerDescription)) - } catch (e: ActivityNotFoundException) { - Log.w("CalendarHost", "No account picker", e) + if (!accessPickerOpen) { + try { + accessPicker.launch(accountAccessIntent(accounts, accessPickerDescription)) + accessPickerOpen = true + } catch (e: ActivityNotFoundException) { + Log.w("CalendarHost", "No account picker", e) + } } } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } @@ -572,6 +575,9 @@ fun CalendarHost( val stayingPut = remember { StayingPut() } val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) + LaunchedEffect(drawerState.targetValue) { + if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() + } val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -622,17 +628,15 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = remember(syncTargets, syncInFlight) { + sync = remember(syncTargets, syncInFlight, accessPickerDescription) { DrawerSync( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, - needsAccess = syncTargets.needsAccess.map { it.name }.distinct(), + needsAccess = syncTargets.needsAccess.isNotEmpty(), onSync = { sync.requestSync() switchScope.launch { drawerState.close() } }, - // The drawer stays open: one pick grants one account, - // and the row is right there for the next. onGrantAccess = { launchAccessPicker(syncTargets.needsAccess) }, ) }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index 2d5b567e..d115d61b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -150,27 +150,27 @@ fun CalendarDrawer( /** * The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress - * and ignores taps), and a grant row naming the [needsAccess] accounts. + * and ignores taps), and a grant row while some account [needsAccess]. */ data class DrawerSync( val canSync: Boolean, val inFlight: Boolean, - val needsAccess: List, + val needsAccess: Boolean, val onSync: () -> Unit, val onGrantAccess: () -> Unit, ) { - val hasRows: Boolean get() = canSync || needsAccess.isNotEmpty() + val hasRows: Boolean get() = canSync || needsAccess } @Composable private fun SyncRows(sync: DrawerSync) { if (sync.canSync) { - SyncNowRow(sync, if (sync.needsAccess.isEmpty()) Position.Bottom else Position.Middle) + SyncNowRow(sync, if (sync.needsAccess) Position.Middle else Position.Bottom) } - if (sync.needsAccess.isNotEmpty()) { + if (sync.needsAccess) { GroupedRow( title = stringResource(R.string.drawer_sync_access), - summary = stringResource(R.string.drawer_sync_access_summary, sync.needsAccess.joinToString()), + summary = stringResource(R.string.drawer_sync_access_summary), position = Position.Bottom, minHeight = 56.dp, leading = { DrawerLeadingIcon(Icons.Filled.ManageAccounts) }, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 62ea96d1..5a27b757 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -397,7 +397,7 @@ Jump to date Sync now Allow sync requests - Calendula can\'t ask %1$s to sync yet + Pick each account Calendula may ask to sync Choose an account Calendula may ask to sync your calendars Sync requested Couldn\'t request a sync diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 5f5b956f..02cbb189 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -233,7 +233,7 @@ class SyncNudgeTest { assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) sync.requests.clear() - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) assertThat(sync.requests).containsExactly(Request(dav, true)) } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5a839865..759a1a4a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -24,7 +24,7 @@ the package list (recurring writes, save conflicts, reminder delivery). drawer offers "Allow sync requests" instead, which opens the system account picker (`AccountManager.newChooseAccountIntent`) — the picked account becomes visible to the app. Access is re-read on every request and on - every resume, so a revoke simply puts the account back behind the + every resume and drawer open, so a revoke simply puts the account back behind the grant row. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a From 14a0725b219ad7cfb480c41c95fd58e64bb394ea Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 22:18:09 +0100 Subject: [PATCH 10/17] refactor(#240): grant-flow state in its own helper, clearer receipt when accounts need access --- .../data/calendar/CalendarRepositoryImpl.kt | 10 ++-- .../calendula/data/calendar/SyncRequester.kt | 2 +- .../calendula/ui/CalendarHost.kt | 35 ++---------- .../calendula/ui/common/SyncAccessPicker.kt | 55 +++++++++++++++++++ .../calendula/ui/common/SyncViewModel.kt | 5 +- app/src/main/res/values/strings.xml | 1 + .../calendula/data/calendar/SyncNudgeTest.kt | 3 +- 7 files changed, 74 insertions(+), 37 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 7c11eac9..5179a433 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -161,9 +161,10 @@ class CalendarRepositoryImpl @Inject constructor( return SyncTargets(reachable.toSet(), hidden.toSet()) } - /** Ask each reachable one of [accounts] once; returns how many were asked. */ - private fun requestSyncs(accounts: Set, userInitiated: Boolean): Int = - reach(accounts).reachable.count { requestSync(it, userInitiated) } + /** Ask each reachable one of [accounts] once. */ + private fun requestSyncs(accounts: Set, userInitiated: Boolean) { + reach(accounts).reachable.forEach { requestSync(it, userInitiated) } + } private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { syncRequester.requestSync(account, userInitiated) @@ -206,7 +207,8 @@ class CalendarRepositoryImpl @Inject constructor( val sent = targets.reachable.count { requestSync(it, userInitiated = true) } when { sent == 0 -> SyncRequestResult.Failed - sent < targets.reachable.size || targets.needsAccess.isNotEmpty() -> SyncRequestResult.PartlyFailed + sent < targets.reachable.size -> SyncRequestResult.PartlyFailed + targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess else -> SyncRequestResult.Requested } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index 94ed46ee..e22146f8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -104,4 +104,4 @@ fun accountAccessIntent(accounts: Collection, description: String): ) /** Outcome of a user-triggered sync request (#240). */ -enum class SyncRequestResult { Requested, PartlyFailed, NeedsAccess, NothingToSync, Failed } +enum class SyncRequestResult { Requested, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index cd6bbfa3..e7eef1b1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -1,12 +1,6 @@ package de.jeanlucmakiola.calendula.ui -import android.content.ActivityNotFoundException -import android.util.Log import androidx.activity.compose.BackHandler -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.compose.LifecycleEventEffect import androidx.activity.compose.PredictiveBackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility @@ -50,7 +44,6 @@ import androidx.compose.ui.layout.positionInWindow import androidx.compose.ui.platform.LocalDensity import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle -import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.time.currentDate import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance @@ -60,10 +53,10 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip import de.jeanlucmakiola.calendula.ui.common.StayingPut import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer -import de.jeanlucmakiola.calendula.data.calendar.SyncAccount -import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent import de.jeanlucmakiola.calendula.ui.common.DrawerSync import de.jeanlucmakiola.calendula.ui.common.SyncViewModel +import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen +import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker import de.jeanlucmakiola.calendula.ui.common.messageRes import de.jeanlucmakiola.calendula.ui.common.CalendarFab import de.jeanlucmakiola.calendula.ui.common.CalendarTopBar @@ -461,23 +454,7 @@ fun CalendarHost( val syncResult by sync.result.collectAsStateWithLifecycle() val selectionFailureMessage = eventActionFailureMessage(selectionFailure) val syncMessage = syncResult?.let { stringResource(it.messageRes()) } - // Access is re-read on resume (covering the picker's return), never trusted from the result. - var accessPickerOpen by remember { mutableStateOf(false) } - val accessPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { - accessPickerOpen = false - } - LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } - val accessPickerDescription = stringResource(R.string.sync_access_picker_description) - val launchAccessPicker: (Set) -> Unit = { accounts -> - if (!accessPickerOpen) { - try { - accessPicker.launch(accountAccessIntent(accounts, accessPickerDescription)) - accessPickerOpen = true - } catch (e: ActivityNotFoundException) { - Log.w("CalendarHost", "No account picker", e) - } - } - } + val launchAccessPicker = rememberSyncAccessPicker(sync) val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -575,9 +552,7 @@ fun CalendarHost( val stayingPut = remember { StayingPut() } val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) - LaunchedEffect(drawerState.targetValue) { - if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() - } + RefreshSyncAccessOnOpen(drawerState, sync) val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -628,7 +603,7 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = remember(syncTargets, syncInFlight, accessPickerDescription) { + sync = remember(syncTargets, syncInFlight, launchAccessPicker) { DrawerSync( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt new file mode 100644 index 00000000..ef02bec6 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -0,0 +1,55 @@ +package de.jeanlucmakiola.calendula.ui.common + +import android.content.ActivityNotFoundException +import android.util.Log +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.DrawerState +import androidx.compose.material3.DrawerValue +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.res.stringResource +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent + +/** + * Launches the system account picker for accounts sync requests can't reach yet + * (#240), one launch at a time. Access is re-read on every resume, which covers + * the picker's return and grants or revokes made in system settings. + */ +@Composable +fun rememberSyncAccessPicker(sync: SyncViewModel): (Set) -> Unit { + var open by remember { mutableStateOf(false) } + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + open = false + } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } + val description = stringResource(R.string.sync_access_picker_description) + return remember(launcher, description) { + { accounts -> + if (!open) { + try { + launcher.launch(accountAccessIntent(accounts, description)) + open = true + } catch (e: ActivityNotFoundException) { + Log.w("SyncAccessPicker", "No account picker", e) + } + } + } + } +} + +/** Re-reads account access whenever [drawerState] opens; the app may stay resumed in multi-window. */ +@Composable +fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { + LaunchedEffect(drawerState.targetValue) { + if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 4207019e..ca8bf8ea 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -69,7 +69,9 @@ class SyncViewModel @Inject constructor( } val outcome = repository.requestSync() _result.value = outcome - val sent = outcome == SyncRequestResult.Requested || outcome == SyncRequestResult.PartlyFailed + val sent = outcome == SyncRequestResult.Requested || + outcome == SyncRequestResult.SomeNeedAccess || + outcome == SyncRequestResult.PartlyFailed if (sent) settled.await() else settled.cancel() } finally { _inFlight.value = false @@ -92,6 +94,7 @@ fun SyncRequestResult.messageRes(): Int = when (this) { SyncRequestResult.Requested -> R.string.sync_requested SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed SyncRequestResult.NeedsAccess -> R.string.sync_request_needs_access + SyncRequestResult.SomeNeedAccess -> R.string.sync_request_some_need_access SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync SyncRequestResult.Failed -> R.string.sync_request_failed } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5a27b757..9d96eac3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -401,6 +401,7 @@ Choose an account Calendula may ask to sync your calendars Sync requested Couldn\'t request a sync + Sync requested. Allow sync requests in the menu for the other accounts Allow sync requests in the menu first Sync requested, but not for every account No synced calendars to sync diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 02cbb189..849f41eb 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -233,7 +233,7 @@ class SyncNudgeTest { assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) sync.requests.clear() - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.SomeNeedAccess) assertThat(sync.requests).containsExactly(Request(dav, true)) } @@ -247,6 +247,7 @@ class SyncNudgeTest { assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav, google), emptySet())) assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) } @Test From a026f24bed9d7b34ef8e2844a04a1363f38ca616 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 00:51:00 +0100 Subject: [PATCH 11/17] feat(#240): per-account Don't ask for sync access, undone from the calendar manager --- .../data/calendar/CalendarRepository.kt | 6 +++ .../data/calendar/CalendarRepositoryImpl.kt | 15 +++++-- .../calendula/data/prefs/CalendarPrefs.kt | 23 ++++++++++ .../calendula/ui/CalendarHost.kt | 13 +++++- .../calendula/ui/calendars/CalendarsScreen.kt | 27 ++++++++++++ .../ui/calendars/CalendarsViewModel.kt | 12 +++++ .../calendula/ui/common/SyncAccessPicker.kt | 44 +++++++++++++++++++ .../calendula/ui/common/SyncViewModel.kt | 6 +++ app/src/main/res/values/strings.xml | 5 +++ .../calendula/data/calendar/SyncNudgeTest.kt | 39 ++++++++++++++++ .../calendula/data/prefs/CalendarPrefsTest.kt | 15 +++++++ docs/ARCHITECTURE.md | 4 +- 12 files changed, 203 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 6afb86d1..e4a5ebec 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -149,6 +149,12 @@ interface CalendarRepository { */ val syncTargets: Flow get() = flowOf(SyncTargets.None) + /** Accounts the user said not to be asked about granting access for. */ + val syncAccessDismissed: Flow> get() = flowOf(emptySet()) + + /** Stop or resume asking for [account]'s sync-request access. */ + suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {} + /** Every provider notification and [refresh], including the app's own writes. */ val providerChanges: Flow get() = emptyFlow() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 5179a433..c3e88c49 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -182,15 +182,22 @@ class CalendarRepositoryImpl @Inject constructor( ): suspend () -> Collection = { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) } - private fun targetsOf(calendars: List): SyncTargets = - reach(calendars.syncAccounts().withAdapter()) + private fun targetsOf(calendars: List, dismissed: Set): SyncTargets = + reach(calendars.syncAccounts().withAdapter()).let { + if (dismissed.isEmpty()) it else it.copy(needsAccess = it.needsAccess - dismissed) + } override val syncTargets: Flow - get() = calendars().map { targetsOf(it) }.flowOn(io) + get() = calendars().combine(prefs.syncAccessDismissed, ::targetsOf).flowOn(io) + + override val syncAccessDismissed: Flow> = prefs.syncAccessDismissed + + override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) = + prefs.setSyncAccessDismissed(account, dismissed) override suspend fun requestSync(): SyncRequestResult = withContext(io) { val targets = try { - targetsOf(calendars().first()) + targetsOf(calendars().first(), prefs.syncAccessDismissed.first()) } catch (e: CancellationException) { throw e } catch (e: Exception) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt index f75b69a4..6b1e676b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt @@ -7,6 +7,8 @@ import de.jeanlucmakiola.floret.prefs.PrefStore import de.jeanlucmakiola.floret.prefs.nullableBooleanPref import de.jeanlucmakiola.floret.prefs.nullableLongPref import de.jeanlucmakiola.floret.prefs.nullableStringPref +import de.jeanlucmakiola.floret.prefs.stringSetPref +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @@ -72,7 +74,28 @@ class CalendarPrefs @Inject constructor( suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id) + /** + * Synced accounts the user chose never to be asked to grant sync-request + * access for (#240): no grant row, no "other accounts" receipt. + */ + val syncAccessDismissed: Flow> = prefs.flow(SYNC_ACCESS_DISMISSED) + + suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) { + prefs.update(SYNC_ACCESS_DISMISSED) { if (dismissed) it + account else it - account } + } + private companion object { + val SYNC_ACCESS_DISMISSED = stringSetPref("sync_access_dismissed").map>( + { stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } }, + { accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } }, + ) + const val FIELD_SEPARATOR = '\u001F' + + fun String.toSyncAccount(): SyncAccount? { + val split = indexOf(FIELD_SEPARATOR) + return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split)) + } + val HIDDEN_IDS = idSetPref("hidden_calendar_ids") val DISABLED_IDS = idSetPref("disabled_calendar_ids") val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending") diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index e7eef1b1..1e0d935c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -56,6 +56,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer import de.jeanlucmakiola.calendula.ui.common.DrawerSync import de.jeanlucmakiola.calendula.ui.common.SyncViewModel import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen +import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker import de.jeanlucmakiola.calendula.ui.common.messageRes import de.jeanlucmakiola.calendula.ui.common.CalendarFab @@ -455,6 +456,7 @@ fun CalendarHost( val selectionFailureMessage = eventActionFailureMessage(selectionFailure) val syncMessage = syncResult?.let { stringResource(it.messageRes()) } val launchAccessPicker = rememberSyncAccessPicker(sync) + var showSyncAccess by remember { mutableStateOf(false) } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -612,7 +614,7 @@ fun CalendarHost( sync.requestSync() switchScope.launch { drawerState.close() } }, - onGrantAccess = { launchAccessPicker(syncTargets.needsAccess) }, + onGrantAccess = { showSyncAccess = true }, ) }, ) @@ -714,6 +716,15 @@ fun CalendarHost( }, ) + if (showSyncAccess) { + SyncAccessSheet( + accounts = syncTargets.needsAccess.toList(), + onGrant = { launchAccessPicker(setOf(it)) }, + onDismissAccount = { sync.setAccessDismissed(it, dismissed = true) }, + onDismiss = { showSyncAccess = false }, + ) + } + // The delete prompt and failure chip of a selected event's actions (#141). EventSelectionHost(host = chromeHost, viewModel = eventActions) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt index 5be7aacf..d215fa90 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt @@ -85,6 +85,9 @@ import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.ui.common.sourceAppName +import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.collapseExit @@ -130,6 +133,7 @@ fun CalendarsScreen( val calendars by viewModel.calendars.collectAsStateWithLifecycle() val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle() val error by viewModel.error.collectAsStateWithLifecycle() + val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle() // null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar. // [editorSession] bumps on every open so the editor's field state resets for @@ -174,6 +178,8 @@ fun CalendarsScreen( onEdit = { calendar -> editorSession++; editorId = calendar.id }, onSetVisible = viewModel::setCalendarVisible, onSetAccountVisible = viewModel::setAccountVisible, + syncAccessDismissed = syncAccessDismissed, + onAskSyncAccessAgain = viewModel::askSyncAccessAgain, ) } } @@ -191,6 +197,8 @@ private fun CalendarsList( onEdit: (CalendarSource) -> Unit, onSetVisible: (Long, Boolean) -> Unit, onSetAccountVisible: (Collection, Boolean) -> Unit, + syncAccessDismissed: List, + onAskSyncAccessAgain: (SyncAccount) -> Unit, ) { val context = LocalContext.current val snackbarHostState = remember { SnackbarHostState() } @@ -321,6 +329,25 @@ private fun CalendarsList( } } } + + if (syncAccessDismissed.isNotEmpty()) { + Spacer(Modifier.height(16.dp)) + GroupedSectionHeader(stringResource(R.string.calendars_sync_access_header)) + GroupedHint(stringResource(R.string.calendars_sync_access_hint), style = MaterialTheme.typography.bodySmall) + syncAccessDismissed.forEachIndexed { index, account -> + GroupedRow( + title = account.name, + summary = sourceAppName(account.type), + position = positionOf(index, syncAccessDismissed.size), + leading = { SourceLogo(account.type) }, + trailing = { + TextButton(onClick = { onAskSyncAccessAgain(account) }) { + Text(stringResource(R.string.calendars_sync_access_ask_again)) + } + }, + ) + } + } } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 861f4525..2a6f3f47 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -9,6 +9,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.BackupStatus import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -56,6 +57,17 @@ class CalendarsViewModel @Inject constructor( initialValue = emptyList(), ) + /** Accounts the drawer was told not to ask sync-request access for (#240). */ + val syncAccessDismissed: StateFlow> = + repository.syncAccessDismissed + .map { set -> set.sortedWith(compareBy({ it.name.lowercase() }, { it.type })) } + .catch { emit(emptyList()) } + .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) + + fun askSyncAccessAgain(account: SyncAccount) { + viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) } + } + /** * The Backup & restore screen's own view of that list, with the loading and * failure states [calendars] flattens away — it starts empty and catches to diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt index ef02bec6..bdd97be7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -4,7 +4,12 @@ import android.content.ActivityNotFoundException import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ManageAccounts import androidx.compose.material3.DrawerState +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.DrawerValue import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -12,12 +17,18 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LifecycleEventEffect import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.positionOf /** * Launches the system account picker for accounts sync requests can't reach yet @@ -53,3 +64,36 @@ fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() } } + +/** + * The accounts sync requests can't reach yet (#240), one row each: tapping one + * opens the system picker for just that account, "Don't ask" stops offering it. + * Closes itself once no account is left. + */ +@Composable +fun SyncAccessSheet( + accounts: List, + onGrant: (SyncAccount) -> Unit, + onDismissAccount: (SyncAccount) -> Unit, + onDismiss: () -> Unit, +) { + LaunchedEffect(accounts.isEmpty()) { if (accounts.isEmpty()) onDismiss() } + FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) { + GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp) + accounts.forEachIndexed { index, account -> + GroupedRow( + title = account.name, + summary = sourceAppName(account.type), + position = positionOf(index, accounts.size), + minHeight = 64.dp, + leading = { Icon(Icons.Filled.ManageAccounts, contentDescription = null) }, + trailing = { + TextButton(onClick = { onDismissAccount(account) }) { + Text(stringResource(R.string.sync_access_dont_ask)) + } + }, + onClick = { onGrant(account) }, + ) + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index ca8bf8ea..47322557 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import de.jeanlucmakiola.floret.android.stateWhileSubscribed @@ -79,6 +80,11 @@ class SyncViewModel @Inject constructor( } } + /** Stop asking for [account]'s access (#240); undone from the calendar manager. */ + fun setAccessDismissed(account: SyncAccount, dismissed: Boolean) { + viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed) } + } + fun consumeResult() { _result.value = null } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9d96eac3..7b603c08 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -398,6 +398,11 @@ Sync now Allow sync requests Pick each account Calendula may ask to sync + Android only lets Calendula ask an account to sync once you pick it here. Tap an account to allow it, or choose Don\'t ask to stop offering it. + Don\'t ask + Not asked to sync + Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu. + Ask again Choose an account Calendula may ask to sync your calendars Sync requested Couldn\'t request a sync diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 849f41eb..77208479 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -271,4 +271,43 @@ class SyncNudgeTest { assertThat(sync.requests).containsExactly(auto(dav)) } + + @Test + fun `a dismissed hidden account no longer needs access`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(google, dismissed = true) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet())) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + + repo.setSyncAccessDismissed(google, dismissed = false) + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) + } + + @Test + fun `with every hidden account dismissed there is nothing to sync or grant`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(dav, dismissed = true) + repo.setSyncAccessDismissed(google, dismissed = true) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None) + assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync) + } + + @Test + fun `a dismissed account that becomes visible is still asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(dav, dismissed = true) + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt index 9f0fb46b..8b0010b0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs import androidx.datastore.preferences.core.stringPreferencesKey import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.testDataStore import de.jeanlucmakiola.calendula.testPrefs import kotlinx.coroutines.flow.first @@ -108,4 +109,18 @@ class CalendarPrefsTest { prefs.setVisibilityNoticePending(false) assertThat(prefs.visibilityNoticePending.first()).isFalse() } + + @Test + fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest { + val prefs = testPrefs(tempDir) + val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid") + val google = SyncAccount("me@dav.example/cal, 1", "com.google") + + prefs.setSyncAccessDismissed(dav, dismissed = true) + prefs.setSyncAccessDismissed(google, dismissed = true) + assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google) + + prefs.setSyncAccessDismissed(dav, dismissed = false) + assertThat(prefs.syncAccessDismissed.first()).containsExactly(google) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 759a1a4a..7b9a9ac1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -25,7 +25,9 @@ the package list (recurring writes, save conflicts, reminder delivery). picker (`AccountManager.newChooseAccountIntent`) — the picked account becomes visible to the app. Access is re-read on every request and on every resume and drawer open, so a revoke simply puts the account back behind the - grant row. Whether and when the adapter syncs stays its call. + grant row. Per account the user can choose "Don't ask" instead + (`CalendarPrefs.syncAccessDismissed`); such accounts drop out of the grant + row and the receipts, and the calendar manager lists them to ask again. Whether and when the adapter syncs stays its call. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. From 34e8e8571c791a0d1af151bf4889acbc497c036a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 00:56:47 +0100 Subject: [PATCH 12/17] fix(#240): list only dismissals that still apply, keep the access sheet across recreation --- .../data/calendar/CalendarRepositoryImpl.kt | 6 ++++- .../calendula/data/calendar/SyncRequester.kt | 17 +++++++++----- .../calendula/ui/CalendarHost.kt | 8 +++---- .../ui/calendars/CalendarsViewModel.kt | 9 +++++--- .../calendula/ui/common/SyncAccessPicker.kt | 23 ++++++++++--------- .../calendula/ui/common/SyncViewModel.kt | 4 ++-- app/src/main/res/values/strings.xml | 2 +- .../calendula/data/calendar/SyncNudgeTest.kt | 5 ++-- 8 files changed, 44 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index c3e88c49..98872219 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -184,7 +184,11 @@ class CalendarRepositoryImpl @Inject constructor( private fun targetsOf(calendars: List, dismissed: Set): SyncTargets = reach(calendars.syncAccounts().withAdapter()).let { - if (dismissed.isEmpty()) it else it.copy(needsAccess = it.needsAccess - dismissed) + if (dismissed.isEmpty()) { + it + } else { + it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed) + } } override val syncTargets: Flow diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index e22146f8..db44e688 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -81,22 +81,27 @@ fun List.syncAccounts(): Set = /** * Who a sync request can go to: [reachable] by name, [needsAccess] only once the * user lets the app see the account (Android 13+, see [accountAccessIntent]). + * [dismissed] are hidden accounts the user said not to ask about. */ -data class SyncTargets(val reachable: Set, val needsAccess: Set) { +data class SyncTargets( + val reachable: Set, + val needsAccess: Set, + val dismissed: Set = emptySet(), +) { companion object { val None = SyncTargets(emptySet(), emptySet()) } } /** - * The system account picker, limited to [accounts]: the one the user picks - * becomes visible to the app, so sync requests can name it. One account per pick. + * The system account picker, limited to [account]: once picked it becomes + * visible to the app, so sync requests can name it. */ -fun accountAccessIntent(accounts: Collection, description: String): Intent = +fun accountAccessIntent(account: SyncAccount, description: String): Intent = AccountManager.newChooseAccountIntent( null, - accounts.map { Account(it.name, it.type) }, - accounts.map { it.type }.distinct().toTypedArray(), + listOf(Account(account.name, account.type)), + arrayOf(account.type), description, null, null, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 1e0d935c..22b75422 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -456,7 +456,7 @@ fun CalendarHost( val selectionFailureMessage = eventActionFailureMessage(selectionFailure) val syncMessage = syncResult?.let { stringResource(it.messageRes()) } val launchAccessPicker = rememberSyncAccessPicker(sync) - var showSyncAccess by remember { mutableStateOf(false) } + var showSyncAccess by rememberSaveable { mutableStateOf(false) } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -605,7 +605,7 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = remember(syncTargets, syncInFlight, launchAccessPicker) { + sync = remember(syncTargets, syncInFlight) { DrawerSync( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, @@ -719,8 +719,8 @@ fun CalendarHost( if (showSyncAccess) { SyncAccessSheet( accounts = syncTargets.needsAccess.toList(), - onGrant = { launchAccessPicker(setOf(it)) }, - onDismissAccount = { sync.setAccessDismissed(it, dismissed = true) }, + onGrant = launchAccessPicker, + onDismissAccount = sync::dismissAccess, onDismiss = { showSyncAccess = false }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 2a6f3f47..131fd970 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -57,10 +57,13 @@ class CalendarsViewModel @Inject constructor( initialValue = emptyList(), ) - /** Accounts the drawer was told not to ask sync-request access for (#240). */ + /** + * Accounts the drawer was told not to ask sync-request access for (#240), + * limited to those still behind a visible calendar and still unreachable. + */ val syncAccessDismissed: StateFlow> = - repository.syncAccessDismissed - .map { set -> set.sortedWith(compareBy({ it.name.lowercase() }, { it.type })) } + repository.syncTargets + .map { targets -> targets.dismissed.sortedWith(compareBy({ it.name.lowercase() }, { it.type })) } .catch { emit(emptyList()) } .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt index bdd97be7..db705450 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -4,10 +4,7 @@ import android.content.ActivityNotFoundException import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ManageAccounts import androidx.compose.material3.DrawerState -import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.DrawerValue @@ -16,8 +13,8 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle @@ -31,12 +28,12 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.positionOf /** - * Launches the system account picker for accounts sync requests can't reach yet - * (#240), one launch at a time. Access is re-read on every resume, which covers + * Launches the system account picker for an account sync requests can't reach + * yet (#240), one launch at a time. Access is re-read on every resume, which covers * the picker's return and grants or revokes made in system settings. */ @Composable -fun rememberSyncAccessPicker(sync: SyncViewModel): (Set) -> Unit { +fun rememberSyncAccessPicker(sync: SyncViewModel): (SyncAccount) -> Unit { var open by remember { mutableStateOf(false) } val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { open = false @@ -44,10 +41,10 @@ fun rememberSyncAccessPicker(sync: SyncViewModel): (Set) -> Unit { LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } val description = stringResource(R.string.sync_access_picker_description) return remember(launcher, description) { - { accounts -> + { account -> if (!open) { try { - launcher.launch(accountAccessIntent(accounts, description)) + launcher.launch(accountAccessIntent(account, description)) open = true } catch (e: ActivityNotFoundException) { Log.w("SyncAccessPicker", "No account picker", e) @@ -77,7 +74,11 @@ fun SyncAccessSheet( onDismissAccount: (SyncAccount) -> Unit, onDismiss: () -> Unit, ) { - LaunchedEffect(accounts.isEmpty()) { if (accounts.isEmpty()) onDismiss() } + // Closes once the last account is granted or dismissed, not while the first read is pending. + var hadAccounts by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(accounts.isEmpty()) { + if (accounts.isNotEmpty()) hadAccounts = true else if (hadAccounts) onDismiss() + } FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) { GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp) accounts.forEachIndexed { index, account -> @@ -86,7 +87,7 @@ fun SyncAccessSheet( summary = sourceAppName(account.type), position = positionOf(index, accounts.size), minHeight = 64.dp, - leading = { Icon(Icons.Filled.ManageAccounts, contentDescription = null) }, + leading = { SourceLogo(account.type) }, trailing = { TextButton(onClick = { onDismissAccount(account) }) { Text(stringResource(R.string.sync_access_dont_ask)) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 47322557..f3ff3f0e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -81,8 +81,8 @@ class SyncViewModel @Inject constructor( } /** Stop asking for [account]'s access (#240); undone from the calendar manager. */ - fun setAccessDismissed(account: SyncAccount, dismissed: Boolean) { - viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed) } + fun dismissAccess(account: SyncAccount) { + viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = true) } } fun consumeResult() { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7b603c08..5c40047e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -400,7 +400,7 @@ Pick each account Calendula may ask to sync Android only lets Calendula ask an account to sync once you pick it here. Tap an account to allow it, or choose Don\'t ask to stop offering it. Don\'t ask - Not asked to sync + Not asked for sync access Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu. Ask again Choose an account Calendula may ask to sync your calendars diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 77208479..1fb3be7a 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -280,7 +280,7 @@ class SyncNudgeTest { repo.setSyncAccessDismissed(google, dismissed = true) - assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet())) + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet(), dismissed = setOf(google))) assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) repo.setSyncAccessDismissed(google, dismissed = false) @@ -296,7 +296,7 @@ class SyncNudgeTest { repo.setSyncAccessDismissed(dav, dismissed = true) repo.setSyncAccessDismissed(google, dismissed = true) - assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None) + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(dav, google))) assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync) } @@ -309,5 +309,6 @@ class SyncNudgeTest { repo.createEvent(form(1L)) assertThat(sync.requests).containsExactly(auto(dav)) + assertThat(repo.syncTargets.first().dismissed).isEmpty() } } From 6161efab406284751bd2cd49c1cc444e2c6401fa Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:02:58 +0100 Subject: [PATCH 13/17] fix(#240): access sheet waits for the first read, manager re-reads access, shared account row --- .../data/calendar/CalendarRepositoryImpl.kt | 17 +++++-- .../calendula/ui/CalendarHost.kt | 6 ++- .../calendula/ui/calendars/CalendarsScreen.kt | 18 ++++--- .../ui/calendars/CalendarsViewModel.kt | 19 +++++++- .../calendula/ui/common/SyncAccessPicker.kt | 48 +++++++++++-------- .../calendula/ui/common/SyncViewModel.kt | 9 ++-- 6 files changed, 77 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 98872219..846b1f96 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -183,7 +183,11 @@ class CalendarRepositoryImpl @Inject constructor( { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) } private fun targetsOf(calendars: List, dismissed: Set): SyncTargets = - reach(calendars.syncAccounts().withAdapter()).let { + reach( + calendars.syncAccounts().withAdapter() + .sortedWith(compareBy({ it.name.lowercase() }, { it.type })) + .toSet(), + ).let { if (dismissed.isEmpty()) { it } else { @@ -196,8 +200,15 @@ class CalendarRepositoryImpl @Inject constructor( override val syncAccessDismissed: Flow> = prefs.syncAccessDismissed - override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) = - prefs.setSyncAccessDismissed(account, dismissed) + override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) { + try { + prefs.setSyncAccessDismissed(account, dismissed) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync access dismissal not saved", e) + } + } override suspend fun requestSync(): SyncRequestResult = withContext(io) { val targets = try { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 22b75422..230881e2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -57,6 +57,7 @@ import de.jeanlucmakiola.calendula.ui.common.DrawerSync import de.jeanlucmakiola.calendula.ui.common.SyncViewModel import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker import de.jeanlucmakiola.calendula.ui.common.messageRes import de.jeanlucmakiola.calendula.ui.common.CalendarFab @@ -450,7 +451,8 @@ fun CalendarHost( val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() // "Sync now" in the drawer (#240); its receipt shares the move chip. val sync: SyncViewModel = hiltViewModel() - val syncTargets by sync.targets.collectAsStateWithLifecycle() + val loadedSyncTargets by sync.targets.collectAsStateWithLifecycle() + val syncTargets = loadedSyncTargets ?: SyncTargets.None val syncInFlight by sync.inFlight.collectAsStateWithLifecycle() val syncResult by sync.result.collectAsStateWithLifecycle() val selectionFailureMessage = eventActionFailureMessage(selectionFailure) @@ -718,7 +720,7 @@ fun CalendarHost( if (showSyncAccess) { SyncAccessSheet( - accounts = syncTargets.needsAccess.toList(), + accounts = loadedSyncTargets?.needsAccess?.toList(), onGrant = launchAccessPicker, onDismissAccount = sync::dismissAccess, onDismiss = { showSyncAccess = false }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt index d215fa90..e02ccfdb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt @@ -86,7 +86,9 @@ import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.calendula.data.calendar.SyncAccount -import de.jeanlucmakiola.calendula.ui.common.sourceAppName +import de.jeanlucmakiola.calendula.ui.common.SyncAccountRow +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme @@ -134,6 +136,7 @@ fun CalendarsScreen( val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle() val error by viewModel.error.collectAsStateWithLifecycle() val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle() + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.refreshAccess() } // null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar. // [editorSession] bumps on every open so the editor's field state resets for @@ -335,16 +338,11 @@ private fun CalendarsList( GroupedSectionHeader(stringResource(R.string.calendars_sync_access_header)) GroupedHint(stringResource(R.string.calendars_sync_access_hint), style = MaterialTheme.typography.bodySmall) syncAccessDismissed.forEachIndexed { index, account -> - GroupedRow( - title = account.name, - summary = sourceAppName(account.type), + SyncAccountRow( + account = account, position = positionOf(index, syncAccessDismissed.size), - leading = { SourceLogo(account.type) }, - trailing = { - TextButton(onClick = { onAskSyncAccessAgain(account) }) { - Text(stringResource(R.string.calendars_sync_access_ask_again)) - } - }, + actionLabel = stringResource(R.string.calendars_sync_access_ask_again), + onAction = { onAskSyncAccessAgain(account) }, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 131fd970..2f4ab300 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -9,6 +9,10 @@ import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.ExperimentalCoroutinesApi import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.BackupStatus @@ -57,16 +61,27 @@ class CalendarsViewModel @Inject constructor( initialValue = emptyList(), ) + private val accessChecks = MutableStateFlow(0) + /** * Accounts the drawer was told not to ask sync-request access for (#240), * limited to those still behind a visible calendar and still unreachable. */ + @OptIn(ExperimentalCoroutinesApi::class) val syncAccessDismissed: StateFlow> = - repository.syncTargets - .map { targets -> targets.dismissed.sortedWith(compareBy({ it.name.lowercase() }, { it.type })) } + combine(repository.syncAccessDismissed, accessChecks) { stored, _ -> stored } + .flatMapLatest { stored -> + if (stored.isEmpty()) flowOf(emptyList()) + else repository.syncTargets.map { it.dismissed.toList() } + } .catch { emit(emptyList()) } .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) + /** Re-read account access, which can change outside the app; called on resume. */ + fun refreshAccess() { + accessChecks.update { it + 1 } + } + fun askSyncAccessAgain(account: SyncAccount) { viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt index db705450..eb3f82b4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -13,7 +13,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -25,6 +24,7 @@ import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf /** @@ -69,32 +69,42 @@ fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { */ @Composable fun SyncAccessSheet( - accounts: List, + accounts: List?, onGrant: (SyncAccount) -> Unit, onDismissAccount: (SyncAccount) -> Unit, onDismiss: () -> Unit, ) { - // Closes once the last account is granted or dismissed, not while the first read is pending. - var hadAccounts by rememberSaveable { mutableStateOf(false) } - LaunchedEffect(accounts.isEmpty()) { - if (accounts.isNotEmpty()) hadAccounts = true else if (hadAccounts) onDismiss() - } + LaunchedEffect(accounts?.isEmpty()) { if (accounts?.isEmpty() == true) onDismiss() } FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) { GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp) - accounts.forEachIndexed { index, account -> - GroupedRow( - title = account.name, - summary = sourceAppName(account.type), - position = positionOf(index, accounts.size), - minHeight = 64.dp, - leading = { SourceLogo(account.type) }, - trailing = { - TextButton(onClick = { onDismissAccount(account) }) { - Text(stringResource(R.string.sync_access_dont_ask)) - } - }, + accounts.orEmpty().forEachIndexed { index, account -> + SyncAccountRow( + account = account, + position = positionOf(index, accounts.orEmpty().size), + actionLabel = stringResource(R.string.sync_access_dont_ask), + onAction = { onDismissAccount(account) }, onClick = { onGrant(account) }, ) } } } + +/** One synced account with a text action, as the access sheet and the calendar manager list them. */ +@Composable +fun SyncAccountRow( + account: SyncAccount, + position: Position, + actionLabel: String, + onAction: () -> Unit, + onClick: (() -> Unit)? = null, +) { + GroupedRow( + title = account.name, + summary = sourceAppName(account.type), + position = position, + minHeight = 64.dp, + leading = { SourceLogo(account.type) }, + trailing = { TextButton(onClick = onAction) { Text(actionLabel) } }, + onClick = onClick, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index f3ff3f0e..00b2f3b1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -38,13 +38,14 @@ class SyncViewModel @Inject constructor( private val accessChecks = MutableStateFlow(0) /** - * Who "Sync now" can reach, and who first needs the user's grant. Account - * access isn't observable, so it is re-read on every [refreshAccess]. + * Who "Sync now" can reach, and who first needs the user's grant; null until + * first read. Account access isn't observable, so it is re-read on every + * [refreshAccess]. */ @OptIn(ExperimentalCoroutinesApi::class) - val targets: StateFlow = accessChecks + val targets: StateFlow = accessChecks .flatMapLatest { repository.syncTargets.catch { emit(SyncTargets.None) } } - .stateWhileSubscribed(scope = viewModelScope, initialValue = SyncTargets.None) + .stateWhileSubscribed(scope = viewModelScope, initialValue = null) /** Re-read account access: whenever the app resumes, which includes the picker returning. */ fun refreshAccess() { From 145ef6c6bfef153b2611a8dc7fd19391700ab501 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:09:00 +0100 Subject: [PATCH 14/17] refactor(#240): one access refresh in the repository, loading state in the access sheet --- .../data/calendar/CalendarRepository.kt | 8 +++---- .../data/calendar/CalendarRepositoryImpl.kt | 14 +++++++++--- .../ui/calendars/CalendarsViewModel.kt | 18 +++------------ .../calendula/ui/common/SyncAccessPicker.kt | 11 ++++++++++ .../calendula/ui/common/SyncViewModel.kt | 22 +++++-------------- .../calendula/ui/common/SyncViewModelTest.kt | 15 +++++++++++++ 6 files changed, 49 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index e4a5ebec..28309da2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -144,13 +144,13 @@ interface CalendarRepository { /** * The accounts behind visible calendars with a sync adapter, split by - * whether [requestSync] can reach them yet. Re-reads account access on - * every collection, so a grant or revoke shows on the next one. + * whether [requestSync] can reach them yet. Account access isn't observable: + * it is re-read on each collection and on every [refreshSyncAccess]. */ val syncTargets: Flow get() = flowOf(SyncTargets.None) - /** Accounts the user said not to be asked about granting access for. */ - val syncAccessDismissed: Flow> get() = flowOf(emptySet()) + /** Re-read account access for every [syncTargets] collector; it can change outside the app. */ + fun refreshSyncAccess() {} /** Stop or resume asking for [account]'s sync-request access. */ suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 846b1f96..947a4432 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -18,6 +18,8 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop @@ -195,10 +197,16 @@ class CalendarRepositoryImpl @Inject constructor( } } - override val syncTargets: Flow - get() = calendars().combine(prefs.syncAccessDismissed, ::targetsOf).flowOn(io) + private val accessChecks = MutableStateFlow(0) - override val syncAccessDismissed: Flow> = prefs.syncAccessDismissed + override val syncTargets: Flow + get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ -> + targetsOf(calendars, dismissed) + }.flowOn(io) + + override fun refreshSyncAccess() { + accessChecks.update { it + 1 } + } override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) { try { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 2f4ab300..7fa95c38 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -9,10 +9,6 @@ import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.ExperimentalCoroutinesApi import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.BackupStatus @@ -61,26 +57,18 @@ class CalendarsViewModel @Inject constructor( initialValue = emptyList(), ) - private val accessChecks = MutableStateFlow(0) - /** * Accounts the drawer was told not to ask sync-request access for (#240), * limited to those still behind a visible calendar and still unreachable. */ - @OptIn(ExperimentalCoroutinesApi::class) val syncAccessDismissed: StateFlow> = - combine(repository.syncAccessDismissed, accessChecks) { stored, _ -> stored } - .flatMapLatest { stored -> - if (stored.isEmpty()) flowOf(emptyList()) - else repository.syncTargets.map { it.dismissed.toList() } - } + repository.syncTargets + .map { it.dismissed.toList() } .catch { emit(emptyList()) } .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) /** Re-read account access, which can change outside the app; called on resume. */ - fun refreshAccess() { - accessChecks.update { it + 1 } - } + fun refreshAccess() = repository.refreshSyncAccess() fun askSyncAccessAgain(account: SyncAccount) { viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt index eb3f82b4..f2fd2639 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -4,7 +4,12 @@ import android.content.ActivityNotFoundException import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding import androidx.compose.material3.DrawerState +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.DrawerValue @@ -14,6 +19,8 @@ import androidx.compose.runtime.getValue 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.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle @@ -67,6 +74,7 @@ fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { * opens the system picker for just that account, "Don't ask" stops offering it. * Closes itself once no account is left. */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable fun SyncAccessSheet( accounts: List?, @@ -77,6 +85,9 @@ fun SyncAccessSheet( LaunchedEffect(accounts?.isEmpty()) { if (accounts?.isEmpty() == true) onDismiss() } FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) { GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp) + if (accounts == null) { + Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { LoadingIndicator() } + } accounts.orEmpty().forEachIndexed { index, account -> SyncAccountRow( account = account, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 00b2f3b1..8b16f10e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -11,15 +11,12 @@ import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import de.jeanlucmakiola.floret.android.stateWhileSubscribed import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.firstOrNull -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject @@ -35,22 +32,13 @@ class SyncViewModel @Inject constructor( private val repository: CalendarRepository, ) : ViewModel() { - private val accessChecks = MutableStateFlow(0) - - /** - * Who "Sync now" can reach, and who first needs the user's grant; null until - * first read. Account access isn't observable, so it is re-read on every - * [refreshAccess]. - */ - @OptIn(ExperimentalCoroutinesApi::class) - val targets: StateFlow = accessChecks - .flatMapLatest { repository.syncTargets.catch { emit(SyncTargets.None) } } + /** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */ + val targets: StateFlow = repository.syncTargets + .catch { emit(SyncTargets.None) } .stateWhileSubscribed(scope = viewModelScope, initialValue = null) - /** Re-read account access: whenever the app resumes, which includes the picker returning. */ - fun refreshAccess() { - accessChecks.update { it + 1 } - } + /** Re-read account access: on resume (which includes the picker returning) and drawer open. */ + fun refreshAccess() = repository.refreshSyncAccess() private val _inFlight = MutableStateFlow(false) val inFlight: StateFlow = _inFlight.asStateFlow() diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt index d755a9fc..803c9586 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -114,4 +114,19 @@ class SyncViewModelTest { assertThat(vm.targets.value).isEqualTo(SyncTargets(setOf(davAccount), emptySet())) } + + @Test + fun `dismissing a hidden account takes it out of the grant list`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type)) + sync.knownAccounts = setOf(davAccount) + val (vm, _) = viewModel(dir, sync) + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + assertThat(vm.targets.value?.needsAccess).containsExactly(davAccount) + + vm.dismissAccess(davAccount) + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(davAccount))) + } } From 5e03916d1290006de5231908f6e45a2afb9c73b4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 20:03:33 +0100 Subject: [PATCH 15/17] fix(#240): keep the drawer open after Sync now --- .../java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index 230881e2..bfb9dda8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -612,10 +612,8 @@ fun CalendarHost( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, needsAccess = syncTargets.needsAccess.isNotEmpty(), - onSync = { - sync.requestSync() - switchScope.launch { drawerState.close() } - }, + // Stays open, so the row's progress and the result are seen. + onSync = { sync.requestSync() }, onGrantAccess = { showSyncAccess = true }, ) }, From 1bd055a0b76ac73f97a9d644ef674caf9f6a3468 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 20:20:30 +0100 Subject: [PATCH 16/17] fix(#240): Sync now shows the real sync state in the drawer, chip only when closed --- app/src/main/AndroidManifest.xml | 3 + .../data/calendar/CalendarRepository.kt | 5 +- .../data/calendar/CalendarRepositoryImpl.kt | 24 ++-- .../calendula/data/calendar/SyncRequester.kt | 107 +++++++++++++++++- .../calendula/ui/CalendarHost.kt | 19 ++-- .../calendula/ui/common/CalendarDrawer.kt | 7 +- .../calendula/ui/common/SyncAccessPicker.kt | 32 ++++++ .../calendula/ui/common/SyncViewModel.kt | 39 ++++--- app/src/main/res/values/strings.xml | 2 + .../calendula/TestRepositories.kt | 13 +++ .../calendula/data/calendar/SyncNudgeTest.kt | 20 ++-- .../calendula/ui/common/SyncViewModelTest.kt | 75 ++++++++++-- docs/ARCHITECTURE.md | 8 ++ docs/PRIVACY.md | 1 + 14 files changed, 297 insertions(+), 58 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 17ee1eb7..0fdccaa9 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,6 +41,9 @@ --> + + + diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 28309da2..f426224b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -140,7 +140,10 @@ interface CalendarRepository { * Ask every account behind a visible synced calendar to sync now (#240). * Only a request: the adapter may still run it late, or fail. */ - suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync + suspend fun requestSync(): SyncRequest = SyncRequest(SyncRequestResult.NothingToSync) + + /** Wait for the syncs a [requestSync] reached to run, see [awaitSyncs]. */ + suspend fun awaitSyncs(accounts: Set): SyncWait = SyncWait.Unconfirmed /** * The accounts behind visible calendars with a sync adapter, split by diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 947a4432..648a85b4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -218,31 +218,33 @@ class CalendarRepositoryImpl @Inject constructor( } } - override suspend fun requestSync(): SyncRequestResult = withContext(io) { + override suspend fun requestSync(): SyncRequest = withContext(io) { val targets = try { targetsOf(calendars().first(), prefs.syncAccessDismissed.first()) } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.w(TAG, "Sync request skipped: calendars unreadable", e) - return@withContext SyncRequestResult.Failed + return@withContext SyncRequest(SyncRequestResult.Failed) } if (targets.reachable.isEmpty()) { - return@withContext if (targets.needsAccess.isEmpty()) { - SyncRequestResult.NothingToSync - } else { - SyncRequestResult.NeedsAccess - } + return@withContext SyncRequest( + if (targets.needsAccess.isEmpty()) SyncRequestResult.NothingToSync else SyncRequestResult.NeedsAccess, + ) } - val sent = targets.reachable.count { requestSync(it, userInitiated = true) } - when { - sent == 0 -> SyncRequestResult.Failed - sent < targets.reachable.size -> SyncRequestResult.PartlyFailed + val sent = targets.reachable.filterTo(linkedSetOf()) { requestSync(it, userInitiated = true) } + val result = when { + sent.isEmpty() -> SyncRequestResult.Failed + sent.size < targets.reachable.size -> SyncRequestResult.PartlyFailed targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess else -> SyncRequestResult.Requested } + SyncRequest(result, sent) } + override suspend fun awaitSyncs(accounts: Set): SyncWait = + withContext(io) { syncRequester.awaitSyncs(accounts) } + override val localChanges: Flow = merge( writes, prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {}, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt index db44e688..e6479672 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -10,6 +10,18 @@ import android.os.Bundle import android.provider.CalendarContract import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.domain.CalendarSource +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import javax.inject.Singleton @@ -39,8 +51,71 @@ interface SyncRequester { * marks it manual, which also overrides master-sync-off — only for a user's tap. */ fun requestSync(account: SyncAccount, userInitiated: Boolean) + + /** Where [account]'s calendar sync stands, or null when the system won't say. */ + fun syncActivity(account: SyncAccount): SyncActivity? + + /** Fires whenever any sync on the device becomes pending, starts or ends. */ + fun syncActivityChanges(): Flow } +/** A calendar sync adapter's state for one account, from `READ_SYNC_STATS`. */ +enum class SyncActivity { Idle, Pending, Active } + +/** How waiting on requested syncs ended: seen through, or not confirmed in time. */ +enum class SyncWait { Completed, Unconfirmed } + +/** + * Waits until the syncs of [accounts] have run (#240): each account must have + * been seen pending or active and be idle again, or — for one that never showed + * up within [graceMillis] — be idle. A sync already running at the first look + * isn't the requested one, so it has to finish before the account counts. Unconfirmed after [timeoutMillis], or at + * once when the system won't report sync state. + */ +suspend fun SyncRequester.awaitSyncs( + accounts: Set, + timeoutMillis: Long = SYNC_WAIT_MILLIS, + graceMillis: Long = SYNC_GRACE_MILLIS, + pollMillis: Long = SYNC_POLL_MILLIS, +): SyncWait { + if (accounts.isEmpty()) return SyncWait.Completed + val seen = HashSet() + // One already running when asked is someone else's sync: it only counts once idle again. + var priorRuns: MutableSet? = null + val graceOver = AtomicBoolean(false) + return withTimeoutOrNull(timeoutMillis) { + channelFlow { + launch { syncActivityChanges().collect { send(Unit) } } + launch { + delay(graceMillis) + graceOver.set(true) + send(Unit) + } + // The listener alone can miss a change made before it was registered. + while (true) { + send(Unit) + delay(pollMillis) + } + }.conflate().map { + val states = accounts.associateWith { syncActivity(it) ?: return@map SyncWait.Unconfirmed } + val prior = priorRuns ?: states.filterValues { it == SyncActivity.Active }.keys.toMutableSet() + .also { priorRuns = it } + states.forEach { (account, state) -> + if (state != SyncActivity.Active) prior -= account + if (state != SyncActivity.Idle && account !in prior) seen += account + } + val done = states.all { (account, state) -> + state == SyncActivity.Idle && account !in prior && (account in seen || graceOver.get()) + } + if (done) SyncWait.Completed else null + }.filterNotNull().first() + } ?: SyncWait.Unconfirmed +} + +const val SYNC_WAIT_MILLIS = 60_000L +const val SYNC_GRACE_MILLIS = 5_000L +const val SYNC_POLL_MILLIS = 2_000L + @Singleton class AndroidSyncRequester @Inject constructor( @ApplicationContext private val context: Context, @@ -70,6 +145,28 @@ class AndroidSyncRequester @Inject constructor( extras, ) } + + override fun syncActivity(account: SyncAccount): SyncActivity? = try { + val android = Account(account.name, account.type) + when { + ContentResolver.isSyncActive(android, CalendarContract.AUTHORITY) -> SyncActivity.Active + ContentResolver.isSyncPending(android, CalendarContract.AUTHORITY) -> SyncActivity.Pending + else -> SyncActivity.Idle + } + } catch (e: SecurityException) { + null + } + + override fun syncActivityChanges(): Flow = callbackFlow { + val handle = try { + ContentResolver.addStatusChangeListener( + ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING, + ) { trySend(Unit) } + } catch (e: SecurityException) { + null + } + awaitClose { handle?.let(ContentResolver::removeStatusChangeListener) } + } } /** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */ @@ -108,5 +205,11 @@ fun accountAccessIntent(account: SyncAccount, description: String): Intent = null, ) -/** Outcome of a user-triggered sync request (#240). */ -enum class SyncRequestResult { Requested, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed } +/** + * Outcome of a user-triggered sync request (#240). [Completed] is only ever set + * once the requested syncs were seen through, see [awaitSyncs]. + */ +enum class SyncRequestResult { Requested, Completed, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed } + +/** A sync request's [result] and the [accounts] it actually reached. */ +data class SyncRequest(val result: SyncRequestResult, val accounts: Set = emptySet()) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index bfb9dda8..d13f7998 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -56,6 +56,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer import de.jeanlucmakiola.calendula.ui.common.DrawerSync import de.jeanlucmakiola.calendula.ui.common.SyncViewModel import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen +import de.jeanlucmakiola.calendula.ui.common.rememberSyncChipOutcome import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker @@ -449,14 +450,15 @@ fun CalendarHost( val eventActions: EventActionsViewModel = hiltViewModel() val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle() val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() - // "Sync now" in the drawer (#240); its receipt shares the move chip. + // "Sync now" in the drawer (#240): its outcome shows in the drawer row, or in + // the move chip when it lands with the drawer closed. val sync: SyncViewModel = hiltViewModel() val loadedSyncTargets by sync.targets.collectAsStateWithLifecycle() val syncTargets = loadedSyncTargets ?: SyncTargets.None val syncInFlight by sync.inFlight.collectAsStateWithLifecycle() val syncResult by sync.result.collectAsStateWithLifecycle() val selectionFailureMessage = eventActionFailureMessage(selectionFailure) - val syncMessage = syncResult?.let { stringResource(it.messageRes()) } + val syncRowMessage = syncResult?.let { stringResource(it.messageRes()) } val launchAccessPicker = rememberSyncAccessPicker(sync) var showSyncAccess by rememberSaveable { mutableStateOf(false) } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } @@ -557,6 +559,8 @@ fun CalendarHost( val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) RefreshSyncAccessOnOpen(drawerState, sync) + val syncChip = rememberSyncChipOutcome(drawerState, sync) + val syncChipMessage = syncChip.value?.let { stringResource(it.messageRes()) } val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -607,10 +611,11 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, - sync = remember(syncTargets, syncInFlight) { + sync = remember(syncTargets, syncInFlight, syncRowMessage) { DrawerSync( canSync = syncTargets.reachable.isNotEmpty(), inFlight = syncInFlight, + outcome = syncRowMessage, needsAccess = syncTargets.needsAccess.isNotEmpty(), // Stays open, so the row's progress and the result are seen. onSync = { sync.requestSync() }, @@ -642,12 +647,12 @@ fun CalendarHost( // A fresh event, like a duplicate from the detail screen (#52). openImportForm(form, ImportSource.Insert) }, - chipShown = moveOutcome != null || selectionFailure != null || syncResult != null, + chipShown = moveOutcome != null || selectionFailure != null || syncChip.value != null, onDismissChip = { reschedule.consumeOutcome() eventActions.consumeFailure() // Only the chip on show: a receipt queued behind it still gets its turn. - if (moveOutcome == null && selectionFailure == null) sync.consumeResult() + if (moveOutcome == null && selectionFailure == null) syncChip.value = null }, ) CalendarFab(chromeHost, todayInToolbar, fabSelection) @@ -710,9 +715,9 @@ fun CalendarHost( EventMoveHost( reschedule, modifier = Modifier.fillMaxSize(), - notice = selectionFailureMessage ?: syncMessage, + notice = selectionFailureMessage ?: syncChipMessage, onNoticeShown = { - if (selectionFailureMessage != null) eventActions.consumeFailure() else sync.consumeResult() + if (selectionFailureMessage != null) eventActions.consumeFailure() else syncChip.value = null }, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index d115d61b..9426546d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -150,11 +150,13 @@ fun CalendarDrawer( /** * The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress - * and ignores taps), and a grant row while some account [needsAccess]. + * and ignores taps, [outcome] the last request's result while the drawer stays + * open), and a grant row while some account [needsAccess]. */ data class DrawerSync( val canSync: Boolean, val inFlight: Boolean, + val outcome: String?, val needsAccess: Boolean, val onSync: () -> Unit, val onGrantAccess: () -> Unit, @@ -182,9 +184,10 @@ private fun SyncRows(sync: DrawerSync) { @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable private fun SyncNowRow(sync: DrawerSync, position: Position) { - val inFlightText = stringResource(R.string.sync_requested) + val inFlightText = stringResource(R.string.sync_in_progress) GroupedRow( title = stringResource(R.string.drawer_sync_now), + summary = if (sync.inFlight) inFlightText else sync.outcome, position = position, modifier = if (sync.inFlight) { Modifier.semantics { stateDescription = inFlightText } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt index f2fd2639..2863d769 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -1,5 +1,10 @@ package de.jeanlucmakiola.calendula.ui.common +import kotlinx.coroutines.flow.combine +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.MutableState import android.content.ActivityNotFoundException import android.util.Log import androidx.activity.compose.rememberLauncherForActivityResult @@ -69,6 +74,33 @@ fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { } } +/** + * Routes "Sync now"'s outcome (#240): one that lands while the drawer is open + * shows in its row and is dropped when the drawer closes; one that lands while + * it is closed is handed to the returned state, for the chip. + */ +@Composable +fun rememberSyncChipOutcome(drawerState: DrawerState, sync: SyncViewModel): MutableState { + val chip = rememberSaveable { mutableStateOf(null) } + LaunchedEffect(drawerState, sync) { + var shownInRow = false + combine(sync.result, snapshotFlow { drawerState.targetValue == DrawerValue.Closed }) { result, closed -> + result to closed + }.collect { (result, closed) -> + when { + result == null -> shownInRow = false + !closed -> shownInRow = true + else -> { + if (!shownInRow) chip.value = result + shownInRow = false + sync.consumeResult() + } + } + } + } + return chip +} + /** * The accounts sync requests can't reach yet (#240), one row each: tapping one * opens the system picker for just that account, "Don't ask" stops offering it. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 8b16f10e..59994b46 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.common +import android.util.Log import androidx.annotation.StringRes import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -9,23 +10,21 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult import de.jeanlucmakiola.calendula.data.calendar.SyncTargets +import de.jeanlucmakiola.calendula.data.calendar.SyncWait import de.jeanlucmakiola.floret.android.stateWhileSubscribed -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.async +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject /** * The drawer's "Sync now" (#240): asks the sync adapters of every visible synced - * calendar to run now. [inFlight] holds until the provider next reports a change - * or [SETTLE_MILLIS] pass — the request itself says nothing about when, or - * whether, the sync completes. + * calendar to run now, then follows them through the system's sync state. + * [inFlight] holds until every reached account has synced or the wait gives up; + * [result] then says [SyncRequestResult.Completed] only when that was seen. */ @HiltViewModel class SyncViewModel @Inject constructor( @@ -51,18 +50,21 @@ class SyncViewModel @Inject constructor( fun requestSync() { if (_inFlight.value) return _inFlight.value = true + _result.value = null viewModelScope.launch { try { - // Listening before asking, so a sync that lands at once still counts. - val settled = async(start = CoroutineStart.UNDISPATCHED) { - withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.firstOrNull() } + val request = repository.requestSync() + val waited = if (request.accounts.isEmpty()) null else repository.awaitSyncs(request.accounts) + _result.value = if (waited == SyncWait.Completed && request.result == SyncRequestResult.Requested) { + SyncRequestResult.Completed + } else { + request.result } - val outcome = repository.requestSync() - _result.value = outcome - val sent = outcome == SyncRequestResult.Requested || - outcome == SyncRequestResult.SomeNeedAccess || - outcome == SyncRequestResult.PartlyFailed - if (sent) settled.await() else settled.cancel() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync now failed", e) + _result.value = SyncRequestResult.Failed } finally { _inFlight.value = false } @@ -79,14 +81,15 @@ class SyncViewModel @Inject constructor( } private companion object { - const val SETTLE_MILLIS = 15_000L + const val TAG = "SyncViewModel" } } -/** The chip text for a sync request's outcome. */ +/** The text for a sync request's outcome, in the drawer row or the chip. */ @StringRes fun SyncRequestResult.messageRes(): Int = when (this) { SyncRequestResult.Requested -> R.string.sync_requested + SyncRequestResult.Completed -> R.string.sync_completed SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed SyncRequestResult.NeedsAccess -> R.string.sync_request_needs_access SyncRequestResult.SomeNeedAccess -> R.string.sync_request_some_need_access diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5c40047e..2e4b7f02 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -405,6 +405,8 @@ Ask again Choose an account Calendula may ask to sync your calendars Sync requested + Syncing… + Sync completed Couldn\'t request a sync Sync requested. Allow sync requests in the menu for the other accounts Allow sync requests in the menu first diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index 460a16f4..ff668ab0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.Preferences import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncActivity import de.jeanlucmakiola.calendula.data.calendar.SyncRequester import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -13,6 +14,8 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain @@ -86,6 +89,16 @@ class RecordingSyncRequester( if (!accepts || account.type in refusedTypes) throw SecurityException("refused") requests += Request(account, userInitiated) } + + /** Each account's sync state; null stands for a system that won't say. */ + var activity: (SyncAccount) -> SyncActivity? = { SyncActivity.Idle } + + /** Emit to tell waiters the sync state changed. */ + val activityChanges = MutableSharedFlow(extraBufferCapacity = 8) + + override fun syncActivity(account: SyncAccount): SyncActivity? = activity(account) + + override fun syncActivityChanges(): Flow = activityChanges } /** Installs [dispatcher] as `Dispatchers.Main` around each test. */ diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt index 1fb3be7a..abb8f9de 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -151,7 +151,7 @@ class SyncNudgeTest { } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) } @@ -161,7 +161,7 @@ class SyncNudgeTest { val source = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(4L, local)) } val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync) assertThat(sync.requests).isEmpty() } @@ -170,7 +170,7 @@ class SyncNudgeTest { val sync = RecordingSyncRequester(accepts = false) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Failed) } @Test @@ -194,7 +194,7 @@ class SyncNudgeTest { repo.createEvent(form(3L)) assertThat(sync.requests).isEmpty() - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) assertThat(sync.requests).containsExactly(Request(dav, true)) } @@ -217,7 +217,7 @@ class SyncNudgeTest { val sync = RecordingSyncRequester(refusedTypes = setOf(google.type)) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.PartlyFailed) assertThat(sync.requests).containsExactly(Request(dav, true)) } @@ -233,7 +233,7 @@ class SyncNudgeTest { assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) sync.requests.clear() - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.SomeNeedAccess) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.SomeNeedAccess) assertThat(sync.requests).containsExactly(Request(dav, true)) } @@ -246,7 +246,7 @@ class SyncNudgeTest { sync.hiddenTypes = setOf("other") assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav, google), emptySet())) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) } @@ -256,7 +256,7 @@ class SyncNudgeTest { sync.knownAccounts = setOf(dav, google) val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NeedsAccess) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NeedsAccess) repo.createEvent(form(1L)) assertThat(sync.requests).isEmpty() } @@ -281,7 +281,7 @@ class SyncNudgeTest { repo.setSyncAccessDismissed(google, dismissed = true) assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet(), dismissed = setOf(google))) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) repo.setSyncAccessDismissed(google, dismissed = false) assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) @@ -297,7 +297,7 @@ class SyncNudgeTest { repo.setSyncAccessDismissed(google, dismissed = true) assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(dav, google))) - assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync) } @Test diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt index 803c9586..d36aa258 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -5,6 +5,7 @@ import de.jeanlucmakiola.calendula.MainDispatcherExtension import de.jeanlucmakiola.calendula.RecordingSyncRequester import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncActivity import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult import de.jeanlucmakiola.calendula.data.calendar.SyncTargets import kotlinx.coroutines.launch @@ -46,29 +47,89 @@ class SyncViewModelTest { } @Test - fun `in flight until the provider next reports a change`(@TempDir dir: Path) = runTest(dispatcher) { - val (vm, source) = viewModel(dir) + fun `completed once the reached account has synced`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + var state = SyncActivity.Pending + sync.activity = { state } + val (vm, _) = viewModel(dir, sync) vm.requestSync() runCurrent() - assertThat(vm.inFlight.value).isTrue() - assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) + assertThat(vm.result.value).isNull() - source.tick() + state = SyncActivity.Active + sync.activityChanges.tryEmit(Unit) + runCurrent() + assertThat(vm.inFlight.value).isTrue() + + state = SyncActivity.Idle + sync.activityChanges.tryEmit(Unit) runCurrent() assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) } @Test - fun `in flight ends on its own when nothing changes`(@TempDir dir: Path) = runTest(dispatcher) { + fun `a sync already running when asked has to finish and the asked one run`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + var state = SyncActivity.Active + sync.activity = { state } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + state = SyncActivity.Pending + sync.activityChanges.tryEmit(Unit) + runCurrent() + assertThat(vm.inFlight.value).isTrue() + + state = SyncActivity.Idle + sync.activityChanges.tryEmit(Unit) + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) + } + + @Test + fun `a sync that never shows up counts as done after the grace`(@TempDir dir: Path) = runTest(dispatcher) { val (vm, _) = viewModel(dir) vm.requestSync() - advanceTimeBy(15_001L) + advanceTimeBy(4_000L) + assertThat(vm.inFlight.value).isTrue() + + advanceTimeBy(1_500L) + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) + } + + @Test + fun `a sync still running after a minute stays unconfirmed`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester().apply { activity = { SyncActivity.Active } } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + advanceTimeBy(59_000L) + assertThat(vm.inFlight.value).isTrue() + + advanceTimeBy(1_500L) + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) + } + + @Test + fun `unreadable sync state says requested at once`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester().apply { activity = { null } } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) } @Test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7b9a9ac1..67512c27 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -28,6 +28,14 @@ the package list (recurring writes, save conflicts, reminder delivery). grant row. Per account the user can choose "Don't ask" instead (`CalendarPrefs.syncAccessDismissed`); such accounts drop out of the grant row and the receipts, and the calendar manager lists them to ask again. Whether and when the adapter syncs stays its call. + "Sync now" then follows what it asked for through the system's sync state + (`READ_SYNC_STATS`: `isSyncPending` / `isSyncActive` plus a status-change + listener, see `awaitSyncs`): it reports "Sync completed" once every reached + account was seen pending or running and is idle again (or, never seen, is + still idle after a short grace), and only "Sync requested" when that isn't + seen within a minute or the state can't be read. The outcome shows in the + drawer row while the drawer is open; one that lands with the drawer closed + gets the chip. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index adfd8a34..eae8f552 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -96,6 +96,7 @@ The settings screen contains links to the source code, the licence, the issue tr - `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing. - `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart. - `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting. +- `READ_SYNC_STATS`: only to see whether a sync asked for with “Sync now” is still pending or running, so the menu can say when it has finished. It reveals nothing about your data. - `WAKE_LOCK`, `FOREGROUND_SERVICE`, `ACCESS_NETWORK_STATE`: required by the Android system component used for scheduled background work (WorkManager). `ACCESS_NETWORK_STATE` allows reading *whether* a network connection exists. It does **not** permit using one. Without `INTERNET`, no connection is possible. From 524c4cbb90a5586f8716399db5b3aaafaa08b1ce Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 20:24:30 +0100 Subject: [PATCH 17/17] fix(#240): a failed read of the sync targets is retried instead of hiding Sync now --- .../data/calendar/CalendarRepositoryImpl.kt | 10 +++++++++- .../calendula/ui/common/SyncViewModel.kt | 13 +++++++++++-- .../data/calendar/FakeCalendarDataSource.kt | 4 ++++ .../calendula/ui/common/SyncViewModelTest.kt | 16 ++++++++++++++++ 4 files changed, 40 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 648a85b4..2179d79c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -201,7 +201,15 @@ class CalendarRepositoryImpl @Inject constructor( override val syncTargets: Flow get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ -> - targetsOf(calendars, dismissed) + // One failed read leaves the rows off until the next change, not for good. + try { + targetsOf(calendars, dismissed) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync targets unreadable", e) + SyncTargets.None + } }.flowOn(io) override fun refreshSyncAccess() { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt index 59994b46..bcb2f9e8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -16,7 +16,8 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.launch import javax.inject.Inject @@ -33,7 +34,13 @@ class SyncViewModel @Inject constructor( /** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */ val targets: StateFlow = repository.syncTargets - .catch { emit(SyncTargets.None) } + // A failed read hides the rows for now, then reads again rather than for good. + .retryWhen { e, attempt -> + if (e is CancellationException) return@retryWhen false + emit(SyncTargets.None) + delay((RETRY_BASE_MILLIS shl attempt.coerceAtMost(5).toInt()).coerceAtMost(RETRY_MAX_MILLIS)) + true + } .stateWhileSubscribed(scope = viewModelScope, initialValue = null) /** Re-read account access: on resume (which includes the picker returning) and drawer open. */ @@ -81,6 +88,8 @@ class SyncViewModel @Inject constructor( } private companion object { + const val RETRY_BASE_MILLIS = 1_000L + const val RETRY_MAX_MILLIS = 30_000L const val TAG = "SyncViewModel" } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index 493b2708..c926950e 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -79,8 +79,12 @@ internal class FakeCalendarDataSource : CalendarDataSource { var calendarQueries = 0 private set + /** Set to make [calendars] throw until cleared. */ + var calendarsError: Exception? = null + override fun calendars(): List { calendarQueries++ + calendarsError?.let { throw it } return calendarsResult } override fun instances(beginMillis: Long, endMillis: Long): List = diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt index d36aa258..1d525b00 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -190,4 +190,20 @@ class SyncViewModelTest { assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(davAccount))) } + + @Test + fun `a failed read of the targets is retried rather than hiding Sync now for good`(@TempDir dir: Path) = + runTest(dispatcher) { + val (vm, source) = viewModel(dir) + source.calendarsError = IllegalStateException("provider gone") + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + assertThat(vm.targets.value?.reachable.orEmpty()).isEmpty() + + source.calendarsError = null + advanceTimeBy(31_000) + runCurrent() + + assertThat(vm.targets.value?.reachable).containsExactly(davAccount) + } }