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.