Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2b27bf6ac | ||
|
|
6e1bbf8ec4 | ||
|
|
38e7910d3c | ||
|
|
aa1ce0405a | ||
|
|
6a9274402a | ||
|
|
9577e6c0c8 |
No files matched your search
-1
@@ -37,7 +37,6 @@ class CalendarRepositorySmokeTest {
|
||||
CalendarPrefs(store),
|
||||
SettingsPrefs(store),
|
||||
Dispatchers.IO,
|
||||
AndroidSyncRequester(context),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -41,9 +41,6 @@
|
||||
-->
|
||||
<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" />
|
||||
@@ -59,10 +56,6 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
<!-- Sync adapters to ask for a calendar sync (#240, #303). -->
|
||||
<intent>
|
||||
<action android:name="android.content.SyncAdapter" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
|
||||
@@ -365,6 +365,7 @@ class MainActivity : AppCompatActivity() {
|
||||
description = getStringExtra(CalendarContract.Events.DESCRIPTION),
|
||||
location = getStringExtra(CalendarContract.Events.EVENT_LOCATION),
|
||||
rrule = getStringExtra(CalendarContract.Events.RRULE),
|
||||
calendarId = calendarIdExtraOrNull(),
|
||||
zone = TimeZone.currentSystemDefault(),
|
||||
now = Clock.System.now(),
|
||||
)
|
||||
@@ -425,6 +426,15 @@ class MainActivity : AppCompatActivity() {
|
||||
private fun Intent.longExtraOrNull(key: String): Long? =
|
||||
if (hasExtra(key)) getLongExtra(key, 0L) else null
|
||||
|
||||
/** The calendar an insert intent names (#429); callers pass it as an int, a long or a string. */
|
||||
@Suppress("DEPRECATION")
|
||||
private fun Intent.calendarIdExtraOrNull(): Long? =
|
||||
when (val value = extras?.get(CalendarContract.Events.CALENDAR_ID)) {
|
||||
is Number -> value.toLong()
|
||||
is String -> value.trim().toLongOrNull()
|
||||
else -> null
|
||||
}?.takeIf { it > 0 }
|
||||
|
||||
/**
|
||||
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
|
||||
* "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/
|
||||
|
||||
@@ -301,12 +301,6 @@ 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)
|
||||
}
|
||||
@@ -887,7 +881,8 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
return eventId
|
||||
}
|
||||
|
||||
override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query(
|
||||
/** The account a calendar belongs to, for scoping a `Colors` lookup. */
|
||||
private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query(
|
||||
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
|
||||
arrayOf(
|
||||
CalendarContract.Calendars.ACCOUNT_NAME,
|
||||
@@ -896,17 +891,13 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
null, null, null,
|
||||
)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
private data class CalendarAccount(val name: String, val type: String)
|
||||
|
||||
/**
|
||||
* The raw provider `MINUTES` to store for one of [form]'s reminders: an
|
||||
|
||||
@@ -11,7 +11,6 @@ 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 {
|
||||
@@ -135,31 +134,6 @@ 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(): 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
|
||||
* 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<SyncTargets> get() = flowOf(SyncTargets.None)
|
||||
|
||||
/** 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) {}
|
||||
|
||||
/** Every provider notification and [refresh], including the app's own writes. */
|
||||
val providerChanges: Flow<Unit> get() = emptyFlow()
|
||||
}
|
||||
|
||||
class NoSuchEventException(eventId: Long) :
|
||||
|
||||
+15
-175
@@ -18,8 +18,6 @@ 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
|
||||
@@ -49,7 +47,6 @@ 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. */
|
||||
@@ -87,172 +84,16 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
override val providerChanges: Flow<Unit> 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) 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 <T> write(
|
||||
syncCalendars: suspend () -> Collection<Long?>,
|
||||
block: suspend () -> T,
|
||||
): T = withContext(io) {
|
||||
val accounts = syncAccountsOf(syncCalendars)
|
||||
/** Run a provider write on [io], then re-query whether or not it threw. */
|
||||
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
|
||||
try {
|
||||
block()
|
||||
} finally {
|
||||
refresh()
|
||||
writes.tryEmit(Unit)
|
||||
requestSyncs(accounts, userInitiated = false)
|
||||
}
|
||||
}
|
||||
|
||||
private val noSync: suspend () -> Collection<Long?> = { emptyList() }
|
||||
|
||||
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
|
||||
try {
|
||||
calendarIds().filterNotNull().distinct()
|
||||
.mapNotNull { accountOf(it) }
|
||||
.withAdapter()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No sync nudge: the calendar account could not be read", e)
|
||||
emptySet()
|
||||
}
|
||||
|
||||
/** 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)
|
||||
|
||||
/** The syncable accounts among these whose type has a calendar sync adapter. */
|
||||
private fun Collection<SyncAccount>.withAdapter(): Set<SyncAccount> {
|
||||
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 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 reach(accounts: Set<SyncAccount>): 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)
|
||||
null
|
||||
}
|
||||
if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet())
|
||||
val (reachable, hidden) = accounts.partition { it in addressable }
|
||||
return SyncTargets(reachable.toSet(), hidden.toSet())
|
||||
}
|
||||
|
||||
/** Ask each reachable one of [accounts] once. */
|
||||
private fun requestSyncs(accounts: Set<SyncAccount>, userInitiated: Boolean) {
|
||||
reach(accounts).reachable.forEach { requestSync(it, userInitiated) }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/** 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<Long?> =
|
||||
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
|
||||
|
||||
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): SyncTargets =
|
||||
reach(
|
||||
calendars.syncAccounts().withAdapter()
|
||||
.sortedWith(compareBy({ it.name.lowercase() }, { it.type }))
|
||||
.toSet(),
|
||||
).let {
|
||||
if (dismissed.isEmpty()) {
|
||||
it
|
||||
} else {
|
||||
it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed)
|
||||
}
|
||||
}
|
||||
|
||||
private val accessChecks = MutableStateFlow(0)
|
||||
|
||||
override val syncTargets: Flow<SyncTargets>
|
||||
get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { 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() {
|
||||
accessChecks.update { it + 1 }
|
||||
}
|
||||
|
||||
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(): 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 SyncRequest(SyncRequestResult.Failed)
|
||||
}
|
||||
if (targets.reachable.isEmpty()) {
|
||||
return@withContext SyncRequest(
|
||||
if (targets.needsAccess.isEmpty()) SyncRequestResult.NothingToSync else SyncRequestResult.NeedsAccess,
|
||||
)
|
||||
}
|
||||
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 {},
|
||||
@@ -377,7 +218,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
): Long = write(noSync) {
|
||||
): Long = write {
|
||||
dataSource.createLocalCalendar(displayName, color, description)
|
||||
}
|
||||
|
||||
@@ -386,14 +227,13 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
) = write { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
|
||||
override suspend fun deleteCalendar(id: Long) =
|
||||
write(noSync) { dataSource.deleteCalendar(id) }
|
||||
write { dataSource.deleteCalendar(id) }
|
||||
|
||||
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
||||
// VISIBLE is device-local: nothing for an adapter to upload.
|
||||
write(noSync) {
|
||||
write {
|
||||
val canWrite = dataSource.canWriteCalendars()
|
||||
if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) }
|
||||
// Nothing of ours is left waiting for the provider once the write
|
||||
@@ -413,7 +253,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
override suspend fun importEvents(
|
||||
targetCalendarId: Long,
|
||||
events: List<ParsedIcsEvent>,
|
||||
): IcsImportSummary = write({ listOf(targetCalendarId) }) {
|
||||
): IcsImportSummary = write {
|
||||
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
|
||||
@@ -464,7 +304,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
|
||||
override suspend fun createEvent(form: EventForm): Long = write {
|
||||
dataSource.insertEvent(form, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
@@ -472,11 +312,11 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
eventId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
) = write(eventCalendar(eventId, original, updated.calendarId)) {
|
||||
) = write {
|
||||
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
|
||||
override suspend fun deleteEvent(eventId: Long) = write {
|
||||
dataSource.deleteEvent(eventId)
|
||||
}
|
||||
|
||||
@@ -485,7 +325,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
targetCalendarId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
|
||||
): Long = write {
|
||||
dataSource.moveEvent(
|
||||
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -496,7 +336,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
form: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
): Long = write {
|
||||
dataSource.updateOccurrence(
|
||||
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -507,7 +347,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
): Long = write {
|
||||
dataSource.updateEventFromOccurrence(
|
||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -517,14 +357,14 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
|
||||
override val seriesSplits: Flow<SeriesSplit> = splits
|
||||
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) {
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
|
||||
dataSource.deleteOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
override suspend fun deleteEventFromOccurrence(
|
||||
eventId: Long,
|
||||
beginMillis: Long,
|
||||
) = write(eventCalendar(eventId)) {
|
||||
) = write {
|
||||
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.calendar
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
/** 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 {
|
||||
/** Account types with a calendar sync adapter installed; for any other a request does nothing. */
|
||||
fun adapterAccountTypes(): Set<String>
|
||||
|
||||
/**
|
||||
* 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(types: Set<String>): Set<SyncAccount>?
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
/** 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,
|
||||
) : SyncRequester {
|
||||
// Lists only adapters in packages visible to the app — hence the SyncAdapter <queries> entry.
|
||||
override fun adapterAccountTypes(): Set<String> =
|
||||
ContentResolver.getSyncAdapterTypes()
|
||||
.filter { it.authority == CalendarContract.AUTHORITY }
|
||||
.mapTo(mutableSetOf()) { it.accountType }
|
||||
|
||||
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
|
||||
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 {
|
||||
putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
|
||||
if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
|
||||
}
|
||||
ContentResolver.requestSync(
|
||||
Account(account.name, account.type),
|
||||
CalendarContract.AUTHORITY,
|
||||
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. */
|
||||
fun List<CalendarSource>.syncAccounts(): Set<SyncAccount> =
|
||||
filter { it.isVisibleInSystem }
|
||||
.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]).
|
||||
* [dismissed] are hidden accounts the user said not to ask about.
|
||||
*/
|
||||
data class SyncTargets(
|
||||
val reachable: Set<SyncAccount>,
|
||||
val needsAccess: Set<SyncAccount>,
|
||||
val dismissed: Set<SyncAccount> = emptySet(),
|
||||
) {
|
||||
companion object {
|
||||
val None = SyncTargets(emptySet(), emptySet())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The system account picker, limited to [account]: once picked it becomes
|
||||
* visible to the app, so sync requests can name it.
|
||||
*/
|
||||
fun accountAccessIntent(account: SyncAccount, description: String): Intent =
|
||||
AccountManager.newChooseAccountIntent(
|
||||
null,
|
||||
listOf(Account(account.name, account.type)),
|
||||
arrayOf(account.type),
|
||||
description,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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())
|
||||
@@ -11,11 +11,9 @@ 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
|
||||
@@ -51,12 +49,6 @@ abstract class DataBindModule {
|
||||
impl: CalendarRepositoryImpl,
|
||||
): CalendarRepository
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindSyncRequester(
|
||||
impl: AndroidSyncRequester,
|
||||
): SyncRequester
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindReminderInstanceSource(
|
||||
|
||||
@@ -7,8 +7,6 @@ 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
|
||||
@@ -74,28 +72,7 @@ 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<Set<SyncAccount>> = 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<Set<SyncAccount>>(
|
||||
{ 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")
|
||||
|
||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
@@ -163,6 +164,7 @@ class SettingsPrefs @Inject constructor(
|
||||
val defaultFormFields: Flow<Set<EventFormField>> = prefs.flow(SettingsKeys.defaultFormFields)
|
||||
val recentTimeZones: Flow<List<String>> = prefs.flow(SettingsKeys.recentTimeZones)
|
||||
val autofocusEventTitle: Flow<Boolean> = prefs.flow(SettingsKeys.autofocusEventTitle)
|
||||
val defaultNewEventCalendar: Flow<DefaultCalendarRef?> = prefs.flow(SettingsKeys.defaultNewEventCalendar)
|
||||
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
|
||||
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
|
||||
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
|
||||
@@ -257,6 +259,10 @@ class SettingsPrefs @Inject constructor(
|
||||
|
||||
suspend fun setAutofocusEventTitle(enabled: Boolean) = prefs.set(SettingsKeys.autofocusEventTitle, enabled)
|
||||
|
||||
/** [calendar] null goes back to Automatic. */
|
||||
suspend fun setDefaultNewEventCalendar(calendar: DefaultCalendarRef?) =
|
||||
prefs.set(SettingsKeys.defaultNewEventCalendar, calendar)
|
||||
|
||||
suspend fun setDefaultEventDurationMinutes(minutes: Int) =
|
||||
prefs.set(SettingsKeys.defaultEventDurationMinutes, minutes)
|
||||
|
||||
@@ -570,6 +576,14 @@ object SettingsKeys {
|
||||
*/
|
||||
val autofocusEventTitle: Pref<Boolean> = booleanPref("autofocus_event_title", true)
|
||||
|
||||
/**
|
||||
* The calendar new events open in (#429); null is Automatic (the last-used
|
||||
* calendar). Kept when the calendar stops being a target, which only makes
|
||||
* it fall back for as long as that lasts.
|
||||
*/
|
||||
val defaultNewEventCalendar: Pref<DefaultCalendarRef?> =
|
||||
nullableStringPref("default_new_event_calendar").map(DefaultCalendarRef::decode) { it?.encode() }
|
||||
|
||||
/**
|
||||
* How long a new **timed** event lasts, in minutes (#54). Per-calendar
|
||||
* overrides in [perCalendarEventDuration] take precedence; all-day events
|
||||
|
||||
@@ -320,17 +320,17 @@ fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
|
||||
/**
|
||||
* A create form seeded from this occurrence, to save a copy as a new,
|
||||
* independent event (#52). The recurrence is dropped — a duplicate is a single
|
||||
* event. The source calendar is kept only when [canModify], otherwise the id is
|
||||
* cleared so the create resolves to a writable calendar, which lets a read-only
|
||||
* event be copied into an editable one. [instance]'s own times carry over.
|
||||
* event. The source calendar is only requested: the editor keeps it while it can
|
||||
* take new events and otherwise resolves the calendar like a new event, which
|
||||
* lets a read-only event be copied into an editable one. [instance]'s own times
|
||||
* carry over.
|
||||
*/
|
||||
fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
|
||||
fun EventDetail.toDuplicateForm(zone: TimeZone): EventForm =
|
||||
toEditForm(
|
||||
beginMillis = instance.start.toEpochMilliseconds(),
|
||||
endMillis = instance.end.toEpochMilliseconds(),
|
||||
zone = zone,
|
||||
).copy(
|
||||
rrule = null,
|
||||
calendarId = instance.calendarId.takeIf { canModify },
|
||||
status = status.forNewEvent(),
|
||||
)
|
||||
@@ -13,9 +13,9 @@ import kotlin.time.Instant
|
||||
* back to the same defaults the in-app "new event" uses — a timed start at the
|
||||
* next full hour, and a placeholder hour for a missing end that the form then
|
||||
* stretches to the default-duration setting (the intent is opened as
|
||||
* `ImportSource.InsertOpenEnded`, #54). [EventForm.calendarId] is left null so
|
||||
* it resolves to the last-used / first-writable calendar, exactly like the
|
||||
* `.ics` single-event and plain new-event paths.
|
||||
* `ImportSource.InsertOpenEnded`, #54). [calendarId] is the calendar the
|
||||
* intent names, if any; the editor preselects it while it is a target and otherwise
|
||||
* resolves the calendar like a plain new event (#429).
|
||||
*
|
||||
* Pure (no Android types) so it is unit-testable; the intent parsing that reads
|
||||
* the extras lives in `MainActivity.insertFormOrNull`.
|
||||
@@ -28,6 +28,7 @@ fun buildInsertEventForm(
|
||||
description: String?,
|
||||
location: String? = null,
|
||||
rrule: String? = null,
|
||||
calendarId: Long? = null,
|
||||
zone: TimeZone,
|
||||
now: Instant,
|
||||
): EventForm {
|
||||
@@ -44,7 +45,7 @@ fun buildInsertEventForm(
|
||||
startAt.toFormTime(zone) to endAt.toFormTime(zone)
|
||||
}
|
||||
return EventForm(
|
||||
calendarId = null,
|
||||
calendarId = calendarId,
|
||||
title = title.orEmpty(),
|
||||
isAllDay = isAllDay,
|
||||
start = start,
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
/**
|
||||
* The calendar chosen as default for new events (#429). Provider ids are
|
||||
* device-local and get reassigned when an account is re-added or a backup is
|
||||
* restored onto another device, so the account and name ride along: see [find].
|
||||
*/
|
||||
data class DefaultCalendarRef(
|
||||
val id: Long,
|
||||
val accountType: String,
|
||||
val accountName: String,
|
||||
val displayName: String,
|
||||
) {
|
||||
/**
|
||||
* The calendar this refers to: the exact one, else the account's calendar of
|
||||
* that name (the id changed), else the id within the account (it was renamed).
|
||||
*/
|
||||
fun find(calendars: List<CalendarSource>): CalendarSource? {
|
||||
val inAccount = calendars.filter { it.accountType == accountType && it.accountName == accountName }
|
||||
return inAccount.firstOrNull { it.id == id && it.displayName == displayName }
|
||||
?: inAccount.singleOrNull { it.displayName == displayName }
|
||||
?: inAccount.firstOrNull { it.id == id }
|
||||
}
|
||||
|
||||
fun encode(): String = listOf(id.toString(), accountType, accountName, displayName).joinToString(SEPARATOR)
|
||||
|
||||
companion object {
|
||||
private const val SEPARATOR = "\u001F"
|
||||
|
||||
fun of(calendar: CalendarSource) =
|
||||
DefaultCalendarRef(calendar.id, calendar.accountType, calendar.accountName, calendar.displayName)
|
||||
|
||||
fun decode(stored: String?): DefaultCalendarRef? {
|
||||
val parts = stored?.split(SEPARATOR, limit = 4)?.takeIf { it.size == 4 } ?: return null
|
||||
val id = parts[0].toLongOrNull() ?: return null
|
||||
return DefaultCalendarRef(id, parts[1], parts[2], parts[3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What decides a new event's calendar when the user hasn't picked one (#429).
|
||||
* [requested] is a calendar named by whoever opened the form (an insert intent,
|
||||
* a duplicate's source), [default] the "default calendar" setting and
|
||||
* [lastUsed] the calendar the last new event went into.
|
||||
*/
|
||||
data class NewEventCalendarHints(
|
||||
val requested: Long? = null,
|
||||
val default: DefaultCalendarRef? = null,
|
||||
val lastUsed: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* The calendar the event form targets: [picked] when set, otherwise the first of
|
||||
* the requested, default and last-used calendar that is still an event target,
|
||||
* then the first target.
|
||||
*/
|
||||
fun resolveEventCalendar(
|
||||
picked: Long?,
|
||||
hints: NewEventCalendarHints,
|
||||
calendars: List<CalendarSource>,
|
||||
): Long? {
|
||||
fun Long.ifTarget() = takeIf { id -> calendars.any { it.id == id && it.isEventTarget } }
|
||||
return picked
|
||||
?: hints.requested?.ifTarget()
|
||||
?: effectiveDefaultCalendar(hints.default, calendars)?.id
|
||||
?: hints.lastUsed?.ifTarget()
|
||||
?: calendars.firstOrNull { it.isEventTarget }?.id
|
||||
}
|
||||
|
||||
/**
|
||||
* The default calendar setting as it applies now: null ("Automatic") when unset,
|
||||
* or when the stored calendar is gone, read-only or switched off.
|
||||
*/
|
||||
fun effectiveDefaultCalendar(default: DefaultCalendarRef?, calendars: List<CalendarSource>): CalendarSource? =
|
||||
default?.find(calendars)?.takeIf { it.isEventTarget }
|
||||
@@ -10,7 +10,7 @@ import kotlinx.datetime.toLocalDateTime
|
||||
|
||||
/**
|
||||
* Prefill the create form from a single parsed `.ics` event (the "open one
|
||||
* event" path). [calendarId] is left null so the form preselects the last-used
|
||||
* event" path). [calendarId] is left null so the form preselects the default
|
||||
* calendar, exactly like a fresh create — the user confirms the target and
|
||||
* reviews everything before saving. Mirrors `EventDetail.toEditForm`'s all-day
|
||||
* handling (provider all-day times are UTC midnights with an exclusive end).
|
||||
|
||||
@@ -35,7 +35,6 @@ 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
|
||||
@@ -53,14 +52,6 @@ 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.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
|
||||
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
|
||||
@@ -450,17 +441,6 @@ 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 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 syncRowMessage = syncResult?.let { stringResource(it.messageRes()) }
|
||||
val launchAccessPicker = rememberSyncAccessPicker(sync)
|
||||
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
|
||||
@@ -558,9 +538,6 @@ fun CalendarHost(
|
||||
val stayingPut = remember { StayingPut() }
|
||||
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() }
|
||||
@@ -611,17 +588,6 @@ fun CalendarHost(
|
||||
onOpenSettings()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
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() },
|
||||
onGrantAccess = { showSyncAccess = true },
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
@@ -647,12 +613,10 @@ fun CalendarHost(
|
||||
// A fresh event, like a duplicate from the detail screen (#52).
|
||||
openImportForm(form, ImportSource.Insert)
|
||||
},
|
||||
chipShown = moveOutcome != null || selectionFailure != null || syncChip.value != null,
|
||||
chipShown = moveOutcome != null || selectionFailure != 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) syncChip.value = null
|
||||
},
|
||||
)
|
||||
CalendarFab(chromeHost, todayInToolbar, fabSelection)
|
||||
@@ -715,21 +679,10 @@ fun CalendarHost(
|
||||
EventMoveHost(
|
||||
reschedule,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
notice = selectionFailureMessage ?: syncChipMessage,
|
||||
onNoticeShown = {
|
||||
if (selectionFailureMessage != null) eventActions.consumeFailure() else syncChip.value = null
|
||||
},
|
||||
actionFailure = eventActionFailureMessage(selectionFailure),
|
||||
onActionFailureShown = eventActions::consumeFailure,
|
||||
)
|
||||
|
||||
if (showSyncAccess) {
|
||||
SyncAccessSheet(
|
||||
accounts = loadedSyncTargets?.needsAccess?.toList(),
|
||||
onGrant = launchAccessPicker,
|
||||
onDismissAccount = sync::dismissAccess,
|
||||
onDismiss = { showSyncAccess = false },
|
||||
)
|
||||
}
|
||||
|
||||
// The delete prompt and failure chip of a selected event's actions (#141).
|
||||
EventSelectionHost(host = chromeHost, viewModel = eventActions)
|
||||
|
||||
|
||||
@@ -85,11 +85,6 @@ 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.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
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
@@ -135,8 +130,6 @@ 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()
|
||||
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
|
||||
@@ -181,8 +174,6 @@ fun CalendarsScreen(
|
||||
onEdit = { calendar -> editorSession++; editorId = calendar.id },
|
||||
onSetVisible = viewModel::setCalendarVisible,
|
||||
onSetAccountVisible = viewModel::setAccountVisible,
|
||||
syncAccessDismissed = syncAccessDismissed,
|
||||
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -200,8 +191,6 @@ private fun CalendarsList(
|
||||
onEdit: (CalendarSource) -> Unit,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
|
||||
syncAccessDismissed: List<SyncAccount>,
|
||||
onAskSyncAccessAgain: (SyncAccount) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
@@ -332,20 +321,6 @@ 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 ->
|
||||
SyncAccountRow(
|
||||
account = account,
|
||||
position = positionOf(index, syncAccessDismissed.size),
|
||||
actionLabel = stringResource(R.string.calendars_sync_access_ask_again),
|
||||
onAction = { onAskSyncAccessAgain(account) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,7 +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 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
|
||||
@@ -57,23 +56,6 @@ class CalendarsViewModel @Inject constructor(
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* 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<List<SyncAccount>> =
|
||||
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() = repository.refreshSyncAccess()
|
||||
|
||||
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
|
||||
|
||||
@@ -20,12 +20,8 @@ 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
|
||||
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
|
||||
@@ -42,8 +38,6 @@ 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
|
||||
@@ -67,8 +61,6 @@ 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),
|
||||
* and a row to grant account access while some account can't be reached yet.
|
||||
*/
|
||||
@Composable
|
||||
fun CalendarDrawer(
|
||||
@@ -79,7 +71,6 @@ fun CalendarDrawer(
|
||||
onJumpToDate: (LocalDate) -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
|
||||
sync: DrawerSync? = null,
|
||||
) {
|
||||
var showDatePicker by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -112,12 +103,11 @@ fun CalendarDrawer(
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_jump_to_date),
|
||||
position = if (sync?.hasRows == true) Position.Top else Position.Alone,
|
||||
position = Position.Alone,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.DateRange) },
|
||||
onClick = { showDatePicker = true },
|
||||
)
|
||||
if (sync != null) SyncRows(sync)
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
@@ -148,64 +138,6 @@ fun CalendarDrawer(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress
|
||||
* 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,
|
||||
) {
|
||||
val hasRows: Boolean get() = canSync || needsAccess
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncRows(sync: DrawerSync) {
|
||||
if (sync.canSync) {
|
||||
SyncNowRow(sync, if (sync.needsAccess) Position.Middle else Position.Bottom)
|
||||
}
|
||||
if (sync.needsAccess) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_sync_access),
|
||||
summary = stringResource(R.string.drawer_sync_access_summary),
|
||||
position = Position.Bottom,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.ManageAccounts) },
|
||||
onClick = sync.onGrantAccess,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun SyncNowRow(sync: DrawerSync, position: Position) {
|
||||
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 }
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
dimmed = sync.inFlight,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.Sync) },
|
||||
trailing = if (sync.inFlight) {
|
||||
{ LoadingIndicator(Modifier.size(32.dp)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = sync.onSync.takeIf { !sync.inFlight },
|
||||
)
|
||||
}
|
||||
|
||||
/** Leading slot for the drawer's plain icons: the same 40.dp footprint
|
||||
* [CalendarColorChip] takes, so every leading glyph shares one vertical axis. */
|
||||
@Composable
|
||||
|
||||
@@ -64,8 +64,7 @@ class EventActionsViewModel @Inject constructor(
|
||||
/** A create form copying [event], or null when it can't be read. */
|
||||
suspend fun duplicateForm(event: EventInstance): EventForm? {
|
||||
val detail = load(event) ?: return null
|
||||
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
|
||||
return detail.toDuplicateForm(canModify, zoneSource.current())
|
||||
return detail.toDuplicateForm(zoneSource.current())
|
||||
}
|
||||
|
||||
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
|
||||
|
||||
@@ -51,8 +51,8 @@ private val FAB_BAND = 88.dp
|
||||
fun EventMoveHost(
|
||||
viewModel: RescheduleViewModel,
|
||||
modifier: Modifier = Modifier,
|
||||
notice: String? = null,
|
||||
onNoticeShown: () -> Unit = {},
|
||||
actionFailure: String? = null,
|
||||
onActionFailureShown: () -> 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 -> notice
|
||||
null -> actionFailure
|
||||
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(notice, outcome == null) {
|
||||
if (notice == null || outcome != null) return@LaunchedEffect
|
||||
LaunchedEffect(actionFailure, outcome == null) {
|
||||
if (actionFailure == null || outcome != null) return@LaunchedEffect
|
||||
delay(CHIP_MILLIS)
|
||||
onNoticeShown()
|
||||
onActionFailureShown()
|
||||
}
|
||||
|
||||
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 || notice != null,
|
||||
visible = outcome != null || actionFailure != null,
|
||||
message = content.message,
|
||||
maxWidth = chipMaxWidth,
|
||||
actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null },
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
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
|
||||
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
|
||||
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.Alignment
|
||||
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.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* 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): (SyncAccount) -> 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) {
|
||||
{ account ->
|
||||
if (!open) {
|
||||
try {
|
||||
launcher.launch(accountAccessIntent(account, 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()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Closes itself once no account is left.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun SyncAccessSheet(
|
||||
accounts: List<SyncAccount>?,
|
||||
onGrant: (SyncAccount) -> Unit,
|
||||
onDismissAccount: (SyncAccount) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
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,
|
||||
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,
|
||||
)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.util.Log
|
||||
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.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.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* The drawer's "Sync now" (#240): asks the sync adapters of every visible synced
|
||||
* 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(
|
||||
private val repository: CalendarRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */
|
||||
val targets: StateFlow<SyncTargets?> = repository.syncTargets
|
||||
// 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. */
|
||||
fun refreshAccess() = repository.refreshSyncAccess()
|
||||
|
||||
private val _inFlight = MutableStateFlow(false)
|
||||
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
||||
|
||||
private val _result = MutableStateFlow<SyncRequestResult?>(null)
|
||||
|
||||
/** The last request's outcome, until [consumeResult]. */
|
||||
val result: StateFlow<SyncRequestResult?> = _result.asStateFlow()
|
||||
|
||||
fun requestSync() {
|
||||
if (_inFlight.value) return
|
||||
_inFlight.value = true
|
||||
_result.value = null
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
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
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync now failed", e)
|
||||
_result.value = SyncRequestResult.Failed
|
||||
} finally {
|
||||
_inFlight.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop asking for [account]'s access (#240); undone from the calendar manager. */
|
||||
fun dismissAccess(account: SyncAccount) {
|
||||
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = true) }
|
||||
}
|
||||
|
||||
fun consumeResult() {
|
||||
_result.value = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RETRY_BASE_MILLIS = 1_000L
|
||||
const val RETRY_MAX_MILLIS = 30_000L
|
||||
const val TAG = "SyncViewModel"
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync
|
||||
SyncRequestResult.Failed -> R.string.sync_request_failed
|
||||
}
|
||||
@@ -142,7 +142,7 @@ class EventDetailViewModel @Inject constructor(
|
||||
*/
|
||||
fun duplicateForm(): EventForm? {
|
||||
val loaded = state.value as? EventDetailUiState.Success ?: return null
|
||||
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current())
|
||||
return loaded.detail.toDuplicateForm(zoneSource.current())
|
||||
}
|
||||
|
||||
private suspend fun loadDetail(target: Target): EventDetailUiState = try {
|
||||
|
||||
@@ -12,7 +12,7 @@ import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
* form means the screen hasn't been opened yet.
|
||||
*/
|
||||
data class EventEditUiState(
|
||||
/** The form with its calendar id resolved (picked > last used > first writable). */
|
||||
/** The form with its calendar id resolved, see [de.jeanlucmakiola.calendula.domain.resolveEventCalendar]. */
|
||||
val form: EventForm,
|
||||
/** Calendars that accept writes — the only valid targets. */
|
||||
val calendars: List<CalendarSource>,
|
||||
|
||||
@@ -33,6 +33,8 @@ import de.jeanlucmakiola.calendula.domain.withStart
|
||||
import de.jeanlucmakiola.calendula.domain.withTimes
|
||||
import de.jeanlucmakiola.calendula.domain.withTimezone
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.NewEventCalendarHints
|
||||
import de.jeanlucmakiola.calendula.domain.resolveEventCalendar
|
||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.isEventTarget
|
||||
@@ -142,9 +144,9 @@ data class ImportReminderPrompt(
|
||||
)
|
||||
|
||||
/**
|
||||
* Holds the event form being composed. The form's calendar id resolves to
|
||||
* (user pick > last used > first writable); the resolved value is what the UI
|
||||
* shows and what gets saved.
|
||||
* Holds the event form being composed. The form's calendar id resolves through
|
||||
* [resolveEventCalendar] (user pick > requested > default > last used > first
|
||||
* target); the resolved value is what the UI shows and what gets saved.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class EventEditViewModel @Inject constructor(
|
||||
@@ -181,6 +183,9 @@ class EventEditViewModel @Inject constructor(
|
||||
// A one-time offer, raised when a .ics import opens, to replace the file's
|
||||
// reminders with the settings default (#49). Null while there's nothing to ask.
|
||||
private val _importReminderPrompt = MutableStateFlow<ImportReminderPrompt?>(null)
|
||||
// A calendar named by an insert intent or a duplicate's source (#429); wins
|
||||
// over the default calendar while it is an event target.
|
||||
private val _requestedCalendarId = MutableStateFlow<Long?>(null)
|
||||
// The form as the user received it: the loaded event, or a new form with its
|
||||
// prefill and auto-applied defaults. Anything else is an unsaved change.
|
||||
private val _baseline = MutableStateFlow<EventForm?>(null)
|
||||
@@ -239,7 +244,7 @@ class EventEditViewModel @Inject constructor(
|
||||
|
||||
private data class ExternalInputs(
|
||||
val writable: List<CalendarSource>,
|
||||
val lastUsed: Long?,
|
||||
val hints: NewEventCalendarHints,
|
||||
val defaultFields: Set<EventFormField>,
|
||||
val allowColorOnUnsupported: Boolean,
|
||||
val autofocusTitle: Boolean,
|
||||
@@ -252,8 +257,8 @@ class EventEditViewModel @Inject constructor(
|
||||
/**
|
||||
* The calendars a new event can be saved to ([isEventTarget]): writable,
|
||||
* switched on, not a contact-filled mirror, not a non-syncing subscription.
|
||||
* A last-used preselect landing on an excluded calendar falls back to the
|
||||
* first remaining one (handled by [resolvedCalendarId] and [state]).
|
||||
* A preselect landing on an excluded calendar falls back as
|
||||
* [resolveEventCalendar] describes.
|
||||
*
|
||||
* This is the list of *targets*. An event already living in an excluded
|
||||
* calendar keeps it — [state] adds it back to the picker.
|
||||
@@ -262,16 +267,20 @@ class EventEditViewModel @Inject constructor(
|
||||
calendars.filter { it.isEventTarget }
|
||||
}
|
||||
|
||||
private val calendarHints: Flow<NewEventCalendarHints> = combine(
|
||||
_requestedCalendarId,
|
||||
settingsPrefs.defaultNewEventCalendar,
|
||||
prefs.lastUsedCalendarId,
|
||||
::NewEventCalendarHints,
|
||||
)
|
||||
|
||||
/** The target calendar id, resolved exactly as the form shows it. */
|
||||
private val resolvedCalendarId: Flow<Long?> = combine(
|
||||
_form.map { it?.calendarId },
|
||||
writableCalendars,
|
||||
prefs.lastUsedCalendarId,
|
||||
) { picked, writable, lastUsed ->
|
||||
picked
|
||||
?: lastUsed?.takeIf { id -> writable.any { it.id == id } }
|
||||
?: writable.firstOrNull()?.id
|
||||
}.distinctUntilChanged()
|
||||
calendarHints,
|
||||
allCalendars,
|
||||
::resolveEventCalendar,
|
||||
).distinctUntilChanged()
|
||||
|
||||
/** The resolved calendar's published event palette, refetched when it changes. */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@@ -285,7 +294,7 @@ class EventEditViewModel @Inject constructor(
|
||||
combine(_form, _saveState, _showProblems, _revealed, _editTarget, ::LocalInputs),
|
||||
combine(
|
||||
writableCalendars,
|
||||
prefs.lastUsedCalendarId,
|
||||
calendarHints,
|
||||
settingsPrefs.defaultFormFields,
|
||||
settingsPrefs.allowColorOnUnsupportedCalendars,
|
||||
settingsPrefs.autofocusEventTitle,
|
||||
@@ -296,10 +305,14 @@ class EventEditViewModel @Inject constructor(
|
||||
settingsPrefs.recentTimeZones.flowOn(io),
|
||||
) { local, external, palette, allCalendars, recentTimeZones ->
|
||||
val form = local.form ?: return@combine null
|
||||
val resolvedId = form.calendarId
|
||||
?: external.lastUsed?.takeIf { id -> external.writable.any { it.id == id } }
|
||||
?: external.writable.firstOrNull()?.id
|
||||
val resolved = form.copy(calendarId = resolvedId)
|
||||
val resolvedId = resolveEventCalendar(form.calendarId, external.hints, allCalendars)
|
||||
// A colour is scoped to the calendar it came from, so one that came with
|
||||
// a requested calendar the form couldn't take goes, as on [setCalendar].
|
||||
val requestRefused = form.calendarId == null && resolvedId != null &&
|
||||
external.hints.requested.let { it != null && it != resolvedId }
|
||||
val resolved = form.copy(calendarId = resolvedId).let {
|
||||
if (requestRefused) it.copy(colorKey = null, color = null) else it
|
||||
}
|
||||
val resolvedCalendar = allCalendars.firstOrNull { it.id == resolvedId }
|
||||
// Editing an event in a managed calendar locks its synced fields. Keyed
|
||||
// off the calendar's durable marker, not a stored id, so it holds after a
|
||||
@@ -407,8 +420,9 @@ class EventEditViewModel @Inject constructor(
|
||||
* Seed a fresh event from a prefilled [form] — a parsed single-event `.ics`
|
||||
* file ([ImportSource.File]) or an external `ACTION_INSERT` intent (another
|
||||
* app/widget creating an event, e.g. Google Maps' "add to calendar";
|
||||
* [ImportSource.Insert]; #30, #49). [EventForm.calendarId] is null so the
|
||||
* calendar still resolves to the last-used/first-writable one.
|
||||
* [ImportSource.Insert]; #30, #49). A set [EventForm.calendarId] is the
|
||||
* calendar the caller asked for: it is preselected while it is an event
|
||||
* target, and the form otherwise resolves its calendar like a new event (#429).
|
||||
*
|
||||
* Reminders are handled per [source], because the two paths mean different
|
||||
* things by "no reminders":
|
||||
@@ -431,7 +445,8 @@ class EventEditViewModel @Inject constructor(
|
||||
fun openImported(form: EventForm, source: ImportSource) {
|
||||
if (_form.value != null || _editTarget.value != null) return
|
||||
_revealed.value = form.populatedFields()
|
||||
open(form)
|
||||
_requestedCalendarId.value = form.calendarId
|
||||
open(form.copy(calendarId = null))
|
||||
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
|
||||
when (source) {
|
||||
ImportSource.Insert, ImportSource.InsertOpenEnded ->
|
||||
@@ -609,6 +624,7 @@ class EventEditViewModel @Inject constructor(
|
||||
_remindersTouched.value = false
|
||||
_durationTouched.value = false
|
||||
_importReminderPrompt.value = null
|
||||
_requestedCalendarId.value = null
|
||||
}
|
||||
|
||||
/** Unfold one optional field, picked in the "more fields" dialog. */
|
||||
@@ -667,6 +683,11 @@ class EventEditViewModel @Inject constructor(
|
||||
* The event falls back to the new calendar's colour until re-picked.
|
||||
*/
|
||||
fun setCalendar(id: Long) {
|
||||
// Confirming the calendar the form shows pins it and changes nothing else.
|
||||
if (id == state.value?.form?.calendarId) {
|
||||
pinShownCalendar()
|
||||
return
|
||||
}
|
||||
edit { it.copy(calendarId = id, colorKey = null, color = null) }
|
||||
// A fresh event re-inherits the new calendar's default reminder and
|
||||
// length unless the user has already hand-edited them (guarded inside).
|
||||
@@ -678,13 +699,32 @@ class EventEditViewModel @Inject constructor(
|
||||
fun setAccessLevel(value: AccessLevel) = edit { it.copy(accessLevel = value) }
|
||||
|
||||
/** Pick a palette colour (round-trips via its key); [argb] is its swatch. */
|
||||
fun setColorKey(key: String, argb: Int) = edit { it.copy(colorKey = key, color = argb) }
|
||||
fun setColorKey(key: String, argb: Int) {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = key, color = argb) }
|
||||
}
|
||||
|
||||
/** Pick a raw colour (local / opted-in calendars), clearing any palette key. */
|
||||
fun setColorRaw(argb: Int) = edit { it.copy(colorKey = null, color = argb) }
|
||||
fun setColorRaw(argb: Int) {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = null, color = argb) }
|
||||
}
|
||||
|
||||
/** Clear the colour so the event inherits its calendar's. */
|
||||
fun clearColor() = edit { it.copy(colorKey = null, color = null) }
|
||||
fun clearColor() {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = null, color = null) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix a still-resolving form to the calendar and colour it shows, so a colour
|
||||
* picked for that calendar stays with it. Not a change of its own.
|
||||
*/
|
||||
private fun pinShownCalendar() {
|
||||
val shown = state.value?.form ?: return
|
||||
if (_form.value?.calendarId != null) return
|
||||
applyDefault { it.copy(calendarId = shown.calendarId, colorKey = shown.colorKey, color = shown.color) }
|
||||
}
|
||||
|
||||
/** Bare RRULE value from the recurrence picker; null = does not repeat. */
|
||||
fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) }
|
||||
|
||||
@@ -5,6 +5,8 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.AutoMode
|
||||
import androidx.compose.material.icons.filled.Event
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -19,7 +21,10 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups
|
||||
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.DurationPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.durationLabel
|
||||
@@ -28,6 +33,7 @@ import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
@@ -45,6 +51,7 @@ internal fun EventFormScreen(
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
var showDefaultDuration by remember { mutableStateOf(false) }
|
||||
var showDefaultCalendar by remember { mutableStateOf(false) }
|
||||
// The calendar whose duration-override picker is open, if any.
|
||||
var durationTarget by remember { mutableStateOf<Long?>(null) }
|
||||
var durationSectionExpanded by remember { mutableStateOf(false) }
|
||||
@@ -78,6 +85,26 @@ internal fun EventFormScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// The calendar a new event opens in (#429).
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_calendar),
|
||||
summary = state.defaultNewEventCalendar?.displayName?.orUnnamed()
|
||||
?: state.unavailableDefaultCalendar?.let {
|
||||
stringResource(R.string.settings_default_calendar_unavailable, it.displayName.orUnnamed())
|
||||
}
|
||||
?: stringResource(R.string.settings_default_calendar_automatic),
|
||||
position = Position.Alone,
|
||||
leading = {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Event,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = { showDefaultCalendar = true },
|
||||
)
|
||||
|
||||
// Auto-focus the title on a new event (#10), on by default.
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedSwitchRow(
|
||||
@@ -159,6 +186,17 @@ internal fun EventFormScreen(
|
||||
)
|
||||
}
|
||||
|
||||
if (showDefaultCalendar) {
|
||||
DefaultCalendarPicker(
|
||||
calendars = state.eventTargetCalendars,
|
||||
selectedId = state.defaultNewEventCalendar?.id,
|
||||
onSelect = { id ->
|
||||
viewModel.setDefaultNewEventCalendar(state.eventTargetCalendars.firstOrNull { it.id == id })
|
||||
showDefaultCalendar = false
|
||||
},
|
||||
onDismiss = { showDefaultCalendar = false },
|
||||
)
|
||||
}
|
||||
if (showDefaultDuration) {
|
||||
DurationPicker(
|
||||
title = stringResource(R.string.settings_event_duration),
|
||||
@@ -189,5 +227,34 @@ internal fun EventFormScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/** "Automatic" above every calendar a new event can go into, grouped by account. */
|
||||
@Composable
|
||||
private fun DefaultCalendarPicker(
|
||||
calendars: List<CalendarSource>,
|
||||
selectedId: Long?,
|
||||
onSelect: (Long?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
FullScreenPicker(
|
||||
title = stringResource(R.string.settings_default_calendar),
|
||||
onDismiss = onDismiss,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_calendar_automatic),
|
||||
summary = stringResource(R.string.settings_default_calendar_automatic_hint),
|
||||
position = Position.Alone,
|
||||
checked = selectedId == null,
|
||||
leading = { LeadingAvatar(Icons.Default.AutoMode) },
|
||||
onClick = { onSelect(null) },
|
||||
)
|
||||
if (calendars.isNotEmpty()) Spacer(Modifier.height(16.dp))
|
||||
CalendarPickerGroups(
|
||||
calendars = calendars,
|
||||
selectedId = selectedId,
|
||||
onSelect = onSelect,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Lengths offered for a new timed event, in minutes — up to a full work day. */
|
||||
private val EVENT_DURATION_PRESETS = listOf(15, 30, 45, 60, 90, 120, 240, 480)
|
||||
@@ -98,6 +98,12 @@ data class SettingsUiState(
|
||||
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Writable calendars, shown as per-calendar reminder-override rows. */
|
||||
val writableCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Calendars a new event can go into: the default calendar picker's choices. */
|
||||
val eventTargetCalendars: List<CalendarSource> = emptyList(),
|
||||
/** The default calendar for new events (#429); null is Automatic, also when the stored one fell out. */
|
||||
val defaultNewEventCalendar: CalendarSource? = null,
|
||||
/** The stored default while it exists but takes no new events, named on the Automatic row. */
|
||||
val unavailableDefaultCalendar: CalendarSource? = null,
|
||||
/**
|
||||
* Whether the event-colour picker is offered on calendars that publish no
|
||||
* colour palette (the colour may then not survive their next sync).
|
||||
|
||||
@@ -36,7 +36,10 @@ import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
|
||||
import de.jeanlucmakiola.calendula.domain.effectiveDefaultCalendar
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.isEventTarget
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
@@ -74,61 +77,66 @@ class SettingsViewModel @Inject constructor(
|
||||
private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
/**
|
||||
* Writable calendars that are switched on — the only ones that take a
|
||||
* per-calendar reminder override, since a switched-off one plans no
|
||||
* reminders at all (#75).
|
||||
* Every calendar; [SettingsUiState.writableCalendars] keeps the writable,
|
||||
* switched-on ones — the only ones that take a per-calendar reminder
|
||||
* override, since a switched-off one plans no reminders at all (#75).
|
||||
*/
|
||||
private val writableCalendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } }
|
||||
private val calendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.catch { emit(emptyList()) }
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
combine(prefs.data, calendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable),
|
||||
)
|
||||
|
||||
private fun Preferences.toUiState(calendars: List<CalendarSource>) = SettingsUiState(
|
||||
themeMode = this[SettingsKeys.themeMode],
|
||||
dynamicColor = this[SettingsKeys.dynamicColor] && dynamicColorAvailable,
|
||||
dynamicColorAvailable = dynamicColorAvailable,
|
||||
softenColors = this[SettingsKeys.softenCalendarColors],
|
||||
weekStart = this[SettingsKeys.weekStart],
|
||||
timeFormat = this[SettingsKeys.timeFormat],
|
||||
showHourGrid = this[SettingsKeys.showHourGrid],
|
||||
multiDayCount = this[SettingsKeys.multiDayCount],
|
||||
pastEventDisplay = this[SettingsKeys.pastEventDisplay],
|
||||
dimCompletedEvents = this[SettingsKeys.dimCompletedEvents],
|
||||
showWeekNumbers = this[SettingsKeys.showWeekNumbers],
|
||||
monthShowStartTimes = this[SettingsKeys.monthShowStartTimes],
|
||||
todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar],
|
||||
dragToReschedule = this[SettingsKeys.dragToReschedule],
|
||||
tapOpensEditor = this[SettingsKeys.tapOpensEditor],
|
||||
agendaScreenRange = this[SettingsKeys.agendaScreenRange],
|
||||
agendaShowToday = this[SettingsKeys.agendaShowToday],
|
||||
agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar],
|
||||
defaultView = this[SettingsKeys.defaultView],
|
||||
quickSwitchConfig = this[SettingsKeys.quickSwitchConfig],
|
||||
monthViewStyle = this[SettingsKeys.monthViewStyle],
|
||||
timelineScale = this[SettingsKeys.timelineScale],
|
||||
timelineHours = timelineHours,
|
||||
drawerViewOrder = this[SettingsKeys.drawerViewOrder],
|
||||
defaultFormFields = this[SettingsKeys.defaultFormFields],
|
||||
autofocusEventTitle = this[SettingsKeys.autofocusEventTitle],
|
||||
defaultEventDurationMinutes = this[SettingsKeys.defaultEventDurationMinutes],
|
||||
perCalendarEventDuration = this[SettingsKeys.perCalendarEventDuration],
|
||||
remindersEnabled = this[SettingsKeys.remindersEnabled],
|
||||
defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes],
|
||||
defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes],
|
||||
allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes],
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
writableCalendars = calendars,
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
private fun Preferences.toUiState(calendars: List<CalendarSource>): SettingsUiState {
|
||||
val storedDefault = this[SettingsKeys.defaultNewEventCalendar]
|
||||
return SettingsUiState(
|
||||
themeMode = this[SettingsKeys.themeMode],
|
||||
dynamicColor = this[SettingsKeys.dynamicColor] && dynamicColorAvailable,
|
||||
dynamicColorAvailable = dynamicColorAvailable,
|
||||
softenColors = this[SettingsKeys.softenCalendarColors],
|
||||
weekStart = this[SettingsKeys.weekStart],
|
||||
timeFormat = this[SettingsKeys.timeFormat],
|
||||
showHourGrid = this[SettingsKeys.showHourGrid],
|
||||
multiDayCount = this[SettingsKeys.multiDayCount],
|
||||
pastEventDisplay = this[SettingsKeys.pastEventDisplay],
|
||||
dimCompletedEvents = this[SettingsKeys.dimCompletedEvents],
|
||||
showWeekNumbers = this[SettingsKeys.showWeekNumbers],
|
||||
monthShowStartTimes = this[SettingsKeys.monthShowStartTimes],
|
||||
todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar],
|
||||
dragToReschedule = this[SettingsKeys.dragToReschedule],
|
||||
tapOpensEditor = this[SettingsKeys.tapOpensEditor],
|
||||
agendaScreenRange = this[SettingsKeys.agendaScreenRange],
|
||||
agendaShowToday = this[SettingsKeys.agendaShowToday],
|
||||
agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar],
|
||||
defaultView = this[SettingsKeys.defaultView],
|
||||
quickSwitchConfig = this[SettingsKeys.quickSwitchConfig],
|
||||
monthViewStyle = this[SettingsKeys.monthViewStyle],
|
||||
timelineScale = this[SettingsKeys.timelineScale],
|
||||
timelineHours = timelineHours,
|
||||
drawerViewOrder = this[SettingsKeys.drawerViewOrder],
|
||||
defaultFormFields = this[SettingsKeys.defaultFormFields],
|
||||
autofocusEventTitle = this[SettingsKeys.autofocusEventTitle],
|
||||
defaultEventDurationMinutes = this[SettingsKeys.defaultEventDurationMinutes],
|
||||
perCalendarEventDuration = this[SettingsKeys.perCalendarEventDuration],
|
||||
remindersEnabled = this[SettingsKeys.remindersEnabled],
|
||||
defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes],
|
||||
defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes],
|
||||
allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes],
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
writableCalendars = calendars.filter { it.canModifyContents && it.isVisibleInSystem },
|
||||
eventTargetCalendars = calendars.filter { it.isEventTarget },
|
||||
defaultNewEventCalendar = effectiveDefaultCalendar(storedDefault, calendars),
|
||||
unavailableDefaultCalendar = storedDefault?.find(calendars)?.takeUnless { it.isEventTarget },
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The app-wide custom-font choice (issue #19). Its own flow — both this
|
||||
@@ -359,6 +367,10 @@ class SettingsViewModel @Inject constructor(
|
||||
|
||||
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
|
||||
|
||||
/** [calendar] null goes back to Automatic. */
|
||||
fun setDefaultNewEventCalendar(calendar: CalendarSource?) =
|
||||
save { setDefaultNewEventCalendar(calendar?.let(DefaultCalendarRef::of)) }
|
||||
|
||||
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
|
||||
|
||||
/** [minutes] null clears the override, so the calendar inherits the default. */
|
||||
|
||||
@@ -395,23 +395,6 @@
|
||||
|
||||
<!-- Jump to date (drawer) -->
|
||||
<string name="drawer_jump_to_date">Jump to date</string>
|
||||
<string name="drawer_sync_now">Sync now</string>
|
||||
<string name="drawer_sync_access">Allow sync requests</string>
|
||||
<string name="drawer_sync_access_summary">Pick each account Calendula may ask to sync</string>
|
||||
<string name="sync_access_hint">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.</string>
|
||||
<string name="sync_access_dont_ask">Don\'t ask</string>
|
||||
<string name="calendars_sync_access_header">Not asked for sync access</string>
|
||||
<string name="calendars_sync_access_hint">Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu.</string>
|
||||
<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>
|
||||
<string name="sync_request_partly_failed">Sync requested, but not for every account</string>
|
||||
<string name="sync_nothing_to_sync">No synced calendars to sync</string>
|
||||
|
||||
<!-- Agenda view -->
|
||||
<string name="agenda_today_action">Today</string>
|
||||
@@ -722,6 +705,10 @@
|
||||
<string name="reorder_drag_handle">Drag to reorder</string>
|
||||
<string name="settings_section_event_form">New event form</string>
|
||||
<string name="settings_form_fields_hint">Fields shown by default — everything else sits behind \"More fields\"</string>
|
||||
<string name="settings_default_calendar">Default calendar</string>
|
||||
<string name="settings_default_calendar_automatic">Automatic</string>
|
||||
<string name="settings_default_calendar_unavailable">Automatic while %1$s can’t take new events</string>
|
||||
<string name="settings_default_calendar_automatic_hint">The calendar you last added or moved an event to</string>
|
||||
<string name="settings_autofocus_title">Focus title on new event</string>
|
||||
<string name="settings_autofocus_title_hint">When you start a new event, place the cursor in the title field and open the keyboard right away.</string>
|
||||
<string name="settings_event_duration">Default duration</string>
|
||||
|
||||
@@ -5,17 +5,12 @@ 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.SyncActivity
|
||||
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
|
||||
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
|
||||
@@ -48,58 +43,7 @@ fun testRepository(
|
||||
io: CoroutineDispatcher,
|
||||
prefs: CalendarPrefs = testPrefs(dir),
|
||||
settings: SettingsPrefs = testSettings(dir),
|
||||
syncRequester: SyncRequester = RecordingSyncRequester(),
|
||||
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester)
|
||||
|
||||
/**
|
||||
* 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),
|
||||
* [hiddenTypes] account types the app can't address by name.
|
||||
*/
|
||||
class RecordingSyncRequester(
|
||||
var accepts: Boolean = true,
|
||||
var adapterTypes: Set<String>? = null,
|
||||
var refusedTypes: Set<String> = emptySet(),
|
||||
var hiddenTypes: Set<String> = emptySet(),
|
||||
) : SyncRequester {
|
||||
data class Request(val account: SyncAccount, val userInitiated: Boolean)
|
||||
|
||||
val requests = mutableListOf<Request>()
|
||||
|
||||
override fun adapterAccountTypes(): Set<String> =
|
||||
adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL")
|
||||
|
||||
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
|
||||
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<SyncAccount> = emptySet()
|
||||
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
|
||||
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
|
||||
}
|
||||
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io)
|
||||
|
||||
/** Installs [dispatcher] as `Dispatchers.Main` around each test. */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
|
||||
@@ -64,27 +64,14 @@ internal class FakeCalendarDataSource : CalendarDataSource {
|
||||
val updatedCalendars = mutableListOf<UpdatedCalendar>()
|
||||
val deletedCalendarIds = mutableListOf<Long>()
|
||||
|
||||
/** eventId → calendarId, for [eventCalendarId]. */
|
||||
val eventCalendars = mutableMapOf<Long, Long>()
|
||||
|
||||
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. */
|
||||
var calendarQueries = 0
|
||||
private set
|
||||
|
||||
/** Set to make [calendars] throw until cleared. */
|
||||
var calendarsError: Exception? = null
|
||||
|
||||
override fun calendars(): List<CalendarSource> {
|
||||
calendarQueries++
|
||||
calendarsError?.let { throw it }
|
||||
return calendarsResult
|
||||
}
|
||||
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> =
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
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.flow.first
|
||||
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<IllegalStateException> { repo.deleteEvent(10L) }
|
||||
|
||||
assertThat(sync.requests).containsExactly(auto(dav))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest {
|
||||
val throwing = RecordingSyncRequester(accepts = false)
|
||||
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().result).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().result).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().result).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)
|
||||
}
|
||||
|
||||
@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().result).isEqualTo(SyncRequestResult.Requested)
|
||||
assertThat(sync.requests).containsExactly(Request(dav, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
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.syncTargets.first()).isEqualTo(SyncTargets.None)
|
||||
|
||||
sync.adapterTypes = setOf(dav.type)
|
||||
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet()))
|
||||
}
|
||||
|
||||
@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().result).isEqualTo(SyncRequestResult.PartlyFailed)
|
||||
assertThat(sync.requests).containsExactly(Request(dav, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
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(auto(dav))
|
||||
|
||||
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google)))
|
||||
|
||||
sync.requests.clear()
|
||||
assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.SomeNeedAccess)
|
||||
assertThat(sync.requests).containsExactly(Request(dav, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
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().result).isEqualTo(SyncRequestResult.Requested)
|
||||
assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
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().result).isEqualTo(SyncRequestResult.NeedsAccess)
|
||||
repo.createEvent(form(1L))
|
||||
assertThat(sync.requests).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
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).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(), dismissed = setOf(google)))
|
||||
assertThat(repo.requestSync().result).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(emptySet(), emptySet(), dismissed = setOf(dav, google)))
|
||||
assertThat(repo.requestSync().result).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))
|
||||
assertThat(repo.syncTargets.first().dismissed).isEmpty()
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ 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
|
||||
@@ -109,18 +108,4 @@ 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)
|
||||
}
|
||||
}
|
||||
@@ -583,9 +583,16 @@ class EventFormTest {
|
||||
@Test
|
||||
fun `a copy of a cancelled event starts confirmed, a tentative one stays tentative`() {
|
||||
val zone = TimeZone.of("Europe/Berlin")
|
||||
assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(canModify = true, zone).status)
|
||||
assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(zone).status)
|
||||
.isEqualTo(EventStatus.Confirmed)
|
||||
assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(canModify = true, zone).status)
|
||||
assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(zone).status)
|
||||
.isEqualTo(EventStatus.Tentative)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a copy requests its source calendar and keeps its colour`() {
|
||||
val form = testDetail(eventColor = 7, eventColorKey = "3").toDuplicateForm(TimeZone.of("Europe/Berlin"))
|
||||
assertThat(form.calendarId).isEqualTo(testEvent().calendarId)
|
||||
assertThat(form.colorKey).isEqualTo("3")
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ class InsertEventFormTest {
|
||||
description: String? = null,
|
||||
location: String? = null,
|
||||
rrule: String? = null,
|
||||
calendarId: Long? = null,
|
||||
): EventForm = buildInsertEventForm(
|
||||
beginMillis = beginMillis,
|
||||
endMillis = endMillis,
|
||||
@@ -32,6 +33,7 @@ class InsertEventFormTest {
|
||||
description = description,
|
||||
location = location,
|
||||
rrule = rrule,
|
||||
calendarId = calendarId,
|
||||
zone = zone,
|
||||
now = now,
|
||||
)
|
||||
@@ -50,7 +52,7 @@ class InsertEventFormTest {
|
||||
location = "Room 1",
|
||||
rrule = "FREQ=DAILY",
|
||||
)
|
||||
assertThat(form.calendarId).isNull() // resolves to last-used / first-writable
|
||||
assertThat(form.calendarId).isNull() // resolved by the editor
|
||||
assertThat(form.isAllDay).isFalse()
|
||||
assertThat(form.start.dateTime).isEqualTo(start)
|
||||
assertThat(form.end.dateTime).isEqualTo(end)
|
||||
@@ -60,6 +62,11 @@ class InsertEventFormTest {
|
||||
assertThat(form.rrule).isEqualTo("FREQ=DAILY")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a named calendar is carried over`() {
|
||||
assertThat(build(calendarId = 7L).calendarId).isEqualTo(7L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing times default to the next full hour and a one-hour duration`() {
|
||||
val form = build(title = "Quick note")
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class NewEventCalendarTest {
|
||||
|
||||
private fun cal(
|
||||
id: Long,
|
||||
writable: Boolean = true,
|
||||
visible: Boolean = true,
|
||||
managed: Boolean = false,
|
||||
) = CalendarSource(
|
||||
id = id,
|
||||
displayName = "Cal $id",
|
||||
accountName = "account",
|
||||
accountType = "com.google",
|
||||
color = 0,
|
||||
isVisibleInSystem = visible,
|
||||
canModifyContents = writable,
|
||||
isManaged = managed,
|
||||
)
|
||||
|
||||
private fun ref(id: Long) = DefaultCalendarRef.of(cal(id))
|
||||
|
||||
private val calendars = listOf(
|
||||
cal(1L),
|
||||
cal(2L),
|
||||
cal(3L),
|
||||
cal(4L, writable = false),
|
||||
cal(5L, visible = false),
|
||||
cal(6L, managed = true),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a user pick always wins`() {
|
||||
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L), lastUsed = 1L)
|
||||
assertThat(resolveEventCalendar(4L, hints, calendars)).isEqualTo(4L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a requested calendar beats the default`() {
|
||||
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L))
|
||||
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a requested calendar that is no target falls back to the default`() {
|
||||
listOf(4L, 5L, 6L, 99L).forEach { requested ->
|
||||
val hints = NewEventCalendarHints(requested = requested, default = ref(3L))
|
||||
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the default beats the last used calendar`() {
|
||||
val hints = NewEventCalendarHints(default = ref(3L), lastUsed = 2L)
|
||||
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a default that is no target falls back to the last used calendar`() {
|
||||
listOf(4L, 5L, 6L).forEach { id ->
|
||||
val default = DefaultCalendarRef.of(calendars.single { it.id == id })
|
||||
val hints = NewEventCalendarHints(default = default, lastUsed = 2L)
|
||||
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
|
||||
assertThat(effectiveDefaultCalendar(default, calendars)).isNull()
|
||||
}
|
||||
assertThat(effectiveDefaultCalendar(ref(99L), calendars)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without hints the first target is used`() {
|
||||
val withoutFirst = listOf(cal(4L, writable = false), cal(5L, visible = false), cal(2L))
|
||||
assertThat(resolveEventCalendar(null, NewEventCalendarHints(lastUsed = 5L), withoutFirst)).isEqualTo(2L)
|
||||
assertThat(resolveEventCalendar(null, NewEventCalendarHints(), emptyList())).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the effective default is the stored calendar while it is a target`() {
|
||||
assertThat(effectiveDefaultCalendar(ref(3L), calendars)?.id).isEqualTo(3L)
|
||||
assertThat(effectiveDefaultCalendar(null, calendars)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the default survives a rename and a new id, but not another account`() {
|
||||
assertThat(effectiveDefaultCalendar(ref(3L).copy(displayName = "Old name"), calendars)?.id).isEqualTo(3L)
|
||||
assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 99L), calendars)?.id).isEqualTo(3L)
|
||||
// The id was handed to another calendar of the account; the name decides.
|
||||
assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 2L), calendars)?.id).isEqualTo(3L)
|
||||
assertThat(effectiveDefaultCalendar(ref(3L).copy(accountName = "other"), calendars)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the stored reference round-trips`() {
|
||||
val stored = DefaultCalendarRef(12L, "com.google", "me@example.com", "Work | Team")
|
||||
assertThat(DefaultCalendarRef.decode(stored.encode())).isEqualTo(stored)
|
||||
assertThat(DefaultCalendarRef.decode(null)).isNull()
|
||||
assertThat(DefaultCalendarRef.decode("12")).isNull()
|
||||
assertThat(DefaultCalendarRef.decode("x\u001Fa\u001Fb\u001Fc")).isNull()
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
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.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
|
||||
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
|
||||
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 val davAccount = SyncAccount("me@dav", "bitfire.at.davdroid")
|
||||
|
||||
private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()):
|
||||
Pair<SyncViewModel, FakeCalendarDataSource> {
|
||||
val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) }
|
||||
val repo = testRepository(
|
||||
source, dir, dispatcher,
|
||||
prefs = testPrefs(dir, CoroutineScope(dispatcher)),
|
||||
settings = testSettings(dir, CoroutineScope(dispatcher)),
|
||||
syncRequester = sync,
|
||||
)
|
||||
return SyncViewModel(repo) to source
|
||||
}
|
||||
|
||||
@Test
|
||||
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).isNull()
|
||||
|
||||
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 `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(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
|
||||
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()
|
||||
}
|
||||
|
||||
@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()))
|
||||
}
|
||||
|
||||
@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)))
|
||||
}
|
||||
|
||||
@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)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.time.FakeZoneSource
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
|
||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.FormTime
|
||||
@@ -21,6 +22,7 @@ import de.jeanlucmakiola.calendula.testEvent
|
||||
import de.jeanlucmakiola.calendula.testPrefs
|
||||
import de.jeanlucmakiola.calendula.testRepository
|
||||
import de.jeanlucmakiola.calendula.testSettings
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
@@ -719,4 +721,150 @@ class EventEditViewModelTest {
|
||||
assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Idle)
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a new event opens in the default calendar with its reminders`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
|
||||
val s = settings(tempDir)
|
||||
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
|
||||
s.setCalendarReminderOverride(2L, ReminderOverride.Minutes(listOf(5)))
|
||||
val p = prefs(tempDir)
|
||||
p.setLastUsedCalendarId(1L)
|
||||
val repo = testRepository(fake, tempDir, dispatcher, p, s)
|
||||
val vm = EventEditViewModel(repo, p, s, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource())
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 9 * 60)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
|
||||
assertThat(vm.state.value?.form?.reminders).containsExactly(5)
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a switched-off default calendar falls back to the first target`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) }
|
||||
val s = settings(tempDir)
|
||||
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
|
||||
val vm = viewModel(tempDir, fake, s)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openNew(LocalDate(2030, 1, 15))
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an insert naming a calendar wins over the default`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L), cal(3L)) }
|
||||
val s = settings(tempDir)
|
||||
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
|
||||
val vm = viewModel(tempDir, fake, s)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openImported(
|
||||
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 3L),
|
||||
ImportSource.Insert,
|
||||
)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(3L)
|
||||
assertThat(vm.hasUnsavedChanges.value).isFalse()
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an insert naming an unknown calendar falls back to the default`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
|
||||
val s = settings(tempDir)
|
||||
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
|
||||
val vm = viewModel(tempDir, fake, s)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openImported(
|
||||
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 77L),
|
||||
ImportSource.Insert,
|
||||
)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a duplicate in its own calendar keeps its colour`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
|
||||
val vm = viewModel(tempDir, fake)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openImported(
|
||||
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
|
||||
ImportSource.Insert,
|
||||
)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L)
|
||||
assertThat(vm.state.value?.form?.colorKey).isEqualTo("3")
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `re-picking the shown calendar is no change`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
|
||||
val vm = viewModel(tempDir, fake)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openImported(
|
||||
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
|
||||
ImportSource.Insert,
|
||||
)
|
||||
advanceUntilIdle()
|
||||
vm.setCalendar(2L)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.colorKey).isEqualTo("3")
|
||||
assertThat(vm.hasUnsavedChanges.value).isFalse()
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a duplicate that can't stay in its calendar drops its colour`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest(dispatcher) {
|
||||
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) }
|
||||
val vm = viewModel(tempDir, fake)
|
||||
val job = activate(vm)
|
||||
|
||||
vm.openImported(
|
||||
importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7),
|
||||
ImportSource.Insert,
|
||||
)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
|
||||
assertThat(vm.state.value?.form?.colorKey).isNull()
|
||||
assertThat(vm.state.value?.form?.color).isNull()
|
||||
|
||||
vm.setColorRaw(9)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L)
|
||||
assertThat(vm.state.value?.form?.color).isEqualTo(9)
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
+2
-27
@@ -10,32 +10,6 @@ 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), 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 `<queries>` entry). From Android 13 a
|
||||
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 on
|
||||
every resume and drawer open, so a revoke simply puts the account back behind the
|
||||
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.
|
||||
@@ -88,7 +62,8 @@ flowchart TD
|
||||
of `data/calendar/` because the receiver needs neither the repository
|
||||
nor its flows.
|
||||
- **`data/prefs/`** — DataStore-backed settings (theme, week start, form
|
||||
field defaults, reminders toggle) and small state (last-used calendar).
|
||||
field defaults, default calendar, reminders toggle) and small state
|
||||
(last-used calendar).
|
||||
- **`ui/`** — one package per screen, each with Screen + ViewModel +
|
||||
UiState. Shared pieces in `ui/common/` (recurrence humanizer, FAB column,
|
||||
drawer, transitions). Selection pickers are full-screen and come from
|
||||
|
||||
@@ -96,7 +96,6 @@ 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.
|
||||
|
||||
Reference in new issue
Block a user