fix(#240): Sync now shows the real sync state in the drawer, chip only when closed

This commit is contained in:
makiolaj committed 2026-11-16 20:20:30 +01:00
1 parent 5e03916d12
commit 1bd055a0b7
14 files changed
+297 -58

No files matched your search

+3
View File
@@ -41,6 +41,9 @@
-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Lets "Sync now" (#240) follow the sync it asked for: read-only sync state, install-time. -->
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
@@ -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<SyncAccount>): SyncWait = SyncWait.Unconfirmed
/**
* The accounts behind visible calendars with a sync adapter, split by
@@ -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<SyncAccount>): SyncWait =
withContext(io) { syncRequester.awaitSyncs(accounts) }
override val localChanges: Flow<Unit> = merge(
writes,
prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {},
@@ -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<Unit>
}
/** 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<SyncAccount>,
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<SyncAccount>()
// One already running when asked is someone else's sync: it only counts once idle again.
var priorRuns: MutableSet<SyncAccount>? = 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<Unit> = 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<SyncAccount> = emptySet())
@@ -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
},
)
@@ -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 }
@@ -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<SyncRequestResult?> {
val chip = rememberSaveable { mutableStateOf<SyncRequestResult?>(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.
@@ -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
+2
View File
@@ -405,6 +405,8 @@
<string name="calendars_sync_access_ask_again">Ask again</string>
<string name="sync_access_picker_description">Choose an account Calendula may ask to sync your calendars</string>
<string name="sync_requested">Sync requested</string>
<string name="sync_in_progress">Syncing…</string>
<string name="sync_completed">Sync completed</string>
<string name="sync_request_failed">Couldn\'t request a sync</string>
<string name="sync_request_some_need_access">Sync requested. Allow sync requests in the menu for the other accounts</string>
<string name="sync_request_needs_access">Allow sync requests in the menu first</string>
@@ -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<Unit>(extraBufferCapacity = 8)
override fun syncActivity(account: SyncAccount): SyncActivity? = activity(account)
override fun syncActivityChanges(): Flow<Unit> = activityChanges
}
/** Installs [dispatcher] as `Dispatchers.Main` around each test. */
@@ -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
@@ -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
+8
View File
@@ -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.
+1
View File
@@ -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.