Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
524c4cbb90 | ||
|
|
1bd055a0b7 | ||
|
|
5e03916d12 | ||
|
|
145ef6c6bf | ||
|
|
6161efab40 | ||
|
|
34e8e8571c | ||
|
|
a026f24bed | ||
|
|
14a0725b21 | ||
|
|
e88ad7f533 | ||
|
|
67052352ac | ||
|
|
88de8f42b0 | ||
|
|
8c31e0f6ee | ||
|
|
1688b206a5 | ||
|
|
55934664e2 | ||
|
|
d1c601a6e2 | ||
|
|
1dcbffd6f2 | ||
|
|
fb5cb226ee |
No files matched your search
+1
@@ -37,6 +37,7 @@ class CalendarRepositorySmokeTest {
|
||||
CalendarPrefs(store),
|
||||
SettingsPrefs(store),
|
||||
Dispatchers.IO,
|
||||
AndroidSyncRequester(context),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@
|
||||
-->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- Lets "Sync now" (#240) follow the sync it asked for: read-only sync state, install-time. -->
|
||||
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
|
||||
|
||||
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
|
||||
@@ -56,6 +59,10 @@
|
||||
<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
|
||||
|
||||
@@ -301,6 +301,12 @@ interface CalendarDataSource {
|
||||
*/
|
||||
fun deleteOccurrence(eventId: Long, beginMillis: Long)
|
||||
|
||||
/** The account [calendarId] belongs to; null when the row is gone or unreadable. */
|
||||
fun calendarAccount(calendarId: Long): SyncAccount?
|
||||
|
||||
/** The calendar event [eventId] lives in; null when the row is gone or unreadable. */
|
||||
fun eventCalendarId(eventId: Long): Long?
|
||||
|
||||
fun registerChangeListener(listener: () -> Unit)
|
||||
fun unregisterChangeListener(listener: () -> Unit)
|
||||
}
|
||||
@@ -881,8 +887,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
return eventId
|
||||
}
|
||||
|
||||
/** The account a calendar belongs to, for scoping a `Colors` lookup. */
|
||||
private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query(
|
||||
override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query(
|
||||
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
|
||||
arrayOf(
|
||||
CalendarContract.Calendars.ACCOUNT_NAME,
|
||||
@@ -891,13 +896,17 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
null, null, null,
|
||||
)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private data class CalendarAccount(val name: String, val type: String)
|
||||
override fun eventCalendarId(eventId: Long): Long? = resolver.query(
|
||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
||||
arrayOf(CalendarContract.Events.CALENDAR_ID),
|
||||
null, null, null,
|
||||
)?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null }
|
||||
|
||||
/**
|
||||
* The raw provider `MINUTES` to store for one of [form]'s reminders: an
|
||||
|
||||
@@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlin.time.Instant
|
||||
|
||||
interface CalendarRepository {
|
||||
@@ -134,6 +135,31 @@ 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) :
|
||||
|
||||
+175
-15
@@ -18,6 +18,8 @@ import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
@@ -47,6 +49,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
private val prefs: CalendarPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val syncRequester: SyncRequester,
|
||||
) : CalendarRepository {
|
||||
|
||||
/** The configured wall-clock fire time for all-day reminders, read per write. */
|
||||
@@ -84,16 +87,172 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
/** Run a provider write on [io], then re-query whether or not it threw. */
|
||||
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
|
||||
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)
|
||||
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 {},
|
||||
@@ -218,7 +377,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
): Long = write {
|
||||
): Long = write(noSync) {
|
||||
dataSource.createLocalCalendar(displayName, color, description)
|
||||
}
|
||||
|
||||
@@ -227,13 +386,14 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
) = write { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
|
||||
override suspend fun deleteCalendar(id: Long) =
|
||||
write { dataSource.deleteCalendar(id) }
|
||||
write(noSync) { dataSource.deleteCalendar(id) }
|
||||
|
||||
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
||||
write {
|
||||
// VISIBLE is device-local: nothing for an adapter to upload.
|
||||
write(noSync) {
|
||||
val canWrite = dataSource.canWriteCalendars()
|
||||
if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) }
|
||||
// Nothing of ours is left waiting for the provider once the write
|
||||
@@ -253,7 +413,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
override suspend fun importEvents(
|
||||
targetCalendarId: Long,
|
||||
events: List<ParsedIcsEvent>,
|
||||
): IcsImportSummary = write {
|
||||
): IcsImportSummary = write({ listOf(targetCalendarId) }) {
|
||||
val existing = dataSource.existingUids(targetCalendarId)
|
||||
// Both are per-calendar, not per-event: looking them up once keeps a
|
||||
// thousand-event restore to two extra queries. The palette is the
|
||||
@@ -304,7 +464,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun createEvent(form: EventForm): Long = write {
|
||||
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
|
||||
dataSource.insertEvent(form, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
@@ -312,11 +472,11 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
eventId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
) = write {
|
||||
) = write(eventCalendar(eventId, original, updated.calendarId)) {
|
||||
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
override suspend fun deleteEvent(eventId: Long) = write {
|
||||
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
|
||||
dataSource.deleteEvent(eventId)
|
||||
}
|
||||
|
||||
@@ -325,7 +485,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
targetCalendarId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write {
|
||||
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
|
||||
dataSource.moveEvent(
|
||||
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -336,7 +496,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
form: EventForm,
|
||||
): Long = write {
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
dataSource.updateOccurrence(
|
||||
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -347,7 +507,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write {
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
dataSource.updateEventFromOccurrence(
|
||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -357,14 +517,14 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
|
||||
override val seriesSplits: Flow<SeriesSplit> = splits
|
||||
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) {
|
||||
dataSource.deleteOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
override suspend fun deleteEventFromOccurrence(
|
||||
eventId: Long,
|
||||
beginMillis: Long,
|
||||
) = write {
|
||||
) = write(eventCalendar(eventId)) {
|
||||
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
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,9 +11,11 @@ import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
|
||||
import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource
|
||||
import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec
|
||||
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
|
||||
@@ -49,6 +51,12 @@ abstract class DataBindModule {
|
||||
impl: CalendarRepositoryImpl,
|
||||
): CalendarRepository
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindSyncRequester(
|
||||
impl: AndroidSyncRequester,
|
||||
): SyncRequester
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindReminderInstanceSource(
|
||||
|
||||
@@ -7,6 +7,8 @@ import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||
import de.jeanlucmakiola.floret.prefs.stringSetPref
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -72,7 +74,28 @@ class CalendarPrefs @Inject constructor(
|
||||
|
||||
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id)
|
||||
|
||||
/**
|
||||
* Synced accounts the user chose never to be asked to grant sync-request
|
||||
* access for (#240): no grant row, no "other accounts" receipt.
|
||||
*/
|
||||
val syncAccessDismissed: Flow<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")
|
||||
@@ -81,7 +104,7 @@ class CalendarPrefs @Inject constructor(
|
||||
}
|
||||
|
||||
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||
)
|
||||
@@ -166,9 +166,6 @@ class SettingsPrefs @Inject constructor(
|
||||
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)
|
||||
val mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
|
||||
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
|
||||
val reminderChannelVersions: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.reminderChannelVersions)
|
||||
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
|
||||
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
|
||||
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
|
||||
@@ -276,25 +273,6 @@ class SettingsPrefs @Inject constructor(
|
||||
|
||||
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
|
||||
|
||||
/**
|
||||
* Reserve a new reminder channel version for each calendar in [floors], above
|
||||
* both its stored high-water mark and its floor, and return them. Versions
|
||||
* only grow: the system would restore a deleted channel's old settings if
|
||||
* its id came back (#518).
|
||||
*/
|
||||
suspend fun reserveReminderChannelVersions(floors: Map<Long, Int>): Map<Long, Int> {
|
||||
val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current ->
|
||||
current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) }
|
||||
}
|
||||
return floors.keys.associateWith { stored.getValue(it) }
|
||||
}
|
||||
|
||||
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
|
||||
|
||||
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) =
|
||||
prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled)
|
||||
|
||||
@@ -616,27 +594,6 @@ object SettingsKeys {
|
||||
*/
|
||||
val remindersEnabled: Pref<Boolean> = booleanPref("reminders_enabled", true)
|
||||
|
||||
/**
|
||||
* Calendars whose reminders Calendula doesn't post (#272), independent of
|
||||
* `Calendars.VISIBLE`: the events still show, only the notifications stop.
|
||||
*/
|
||||
val mutedReminderCalendarIds: Pref<Set<Long>> = idSetPref("muted_reminder_calendar_ids")
|
||||
|
||||
/**
|
||||
* Whether the one-time hint that some skins (Samsung) start new notification
|
||||
* categories switched off has been dismissed (#145).
|
||||
*/
|
||||
val notificationCategoryHintDismissed: Pref<Boolean> = booleanPref("notification_category_hint_dismissed", false)
|
||||
|
||||
/**
|
||||
* The highest reminder channel version handed out per calendar (#518): a
|
||||
* sound picked in the app recreates the channel under a new one. The
|
||||
* channels themselves say which version is current; this only keeps ids
|
||||
* from being reused. Serialised as `id=version;id=version`.
|
||||
*/
|
||||
val reminderChannelVersions: Pref<Map<Long, Int>> =
|
||||
nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() }
|
||||
|
||||
/**
|
||||
* Whether to offer a custom event colour on calendars that publish no colour
|
||||
* palette; synced ones without a palette (some CalDAV) may drop or overwrite
|
||||
@@ -1020,18 +977,6 @@ private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
|
||||
calendarId to minutes
|
||||
}.toMap()
|
||||
|
||||
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
|
||||
calendarId to version
|
||||
}.toMap()
|
||||
|
||||
private fun Map<Long, Int>.toStoredVersions(): String? =
|
||||
if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" }
|
||||
|
||||
private fun Map<Long, Int>.toStoredDurations(): String =
|
||||
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
|
||||
"$id$KEY_VALUE_SEP$minutes"
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
|
||||
/** The single channel every reminder posted on before they moved per calendar (#145). */
|
||||
const val LEGACY_REMINDER_CHANNEL_ID = "reminders"
|
||||
|
||||
private const val CHANNEL_PREFIX = "reminders.calendar."
|
||||
private const val GROUP_PREFIX = "reminders.account."
|
||||
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
|
||||
|
||||
private const val VERSION_SEPARATOR = ".v"
|
||||
|
||||
/**
|
||||
* The notification channel [calendarId]'s reminders post on. A sound picked in
|
||||
* the app moves it to a new [version] (#518), since a channel's sound is fixed
|
||||
* once created; version 0 is the unversioned id #145 introduced.
|
||||
*/
|
||||
fun reminderChannelId(calendarId: Long, version: Int = 0): String =
|
||||
if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version"
|
||||
|
||||
/** The calendar and version a reminder channel id names, or null for any other id. */
|
||||
fun parseReminderChannelId(channelId: String): Pair<Long, Int>? {
|
||||
if (!isReminderChannelId(channelId)) return null
|
||||
val rest = channelId.removePrefix(CHANNEL_PREFIX)
|
||||
val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null
|
||||
if (VERSION_SEPARATOR !in rest) return calendar to 0
|
||||
val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return calendar to version
|
||||
}
|
||||
|
||||
/**
|
||||
* Each calendar's current channel version: the highest one that exists, so a
|
||||
* new version only takes over once it is written. A calendar with none falls
|
||||
* back to its [highWater] mark — re-creating that id restores its own settings.
|
||||
*/
|
||||
fun currentReminderChannelVersions(existingChannelIds: Collection<String>, highWater: Map<Long, Int>): Map<Long, Int> {
|
||||
val existing = existingChannelIds.mapNotNull(::parseReminderChannelId)
|
||||
.groupBy({ it.first }, { it.second })
|
||||
.mapValues { (_, versions) -> versions.max() }
|
||||
return highWater + existing
|
||||
}
|
||||
|
||||
/** Whether [channelId] is one of the per-calendar reminder channels. */
|
||||
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
|
||||
|
||||
/** Whether [groupId] is one of the per-account reminder channel groups. */
|
||||
fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX)
|
||||
|
||||
/**
|
||||
* One account's channel group, labelled as the calendar manager labels it. The
|
||||
* app's own device calendars share a single group ([isLocal]); [ambiguous]
|
||||
* marks a [label] another group shows too, so it should name the source app.
|
||||
*/
|
||||
data class ReminderChannelGroupSpec(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val accountType: String,
|
||||
val isLocal: Boolean,
|
||||
val ambiguous: Boolean,
|
||||
)
|
||||
|
||||
data class ReminderChannelSpec(
|
||||
val id: String,
|
||||
val calendarId: Long,
|
||||
val name: String,
|
||||
/** Null only for a channel created before its calendar could be looked up. */
|
||||
val groupId: String?,
|
||||
/**
|
||||
* Whether a sync creates it up front. A calendar that syncs no events never
|
||||
* fires, so its channel only appears once something posts on it.
|
||||
*/
|
||||
val upFront: Boolean = true,
|
||||
)
|
||||
|
||||
/** What a channel already looks like in the system, as far as the plan compares it. */
|
||||
data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?)
|
||||
|
||||
data class ReminderChannelPlan(
|
||||
val groups: List<ReminderChannelGroupSpec>,
|
||||
val channels: List<ReminderChannelSpec>,
|
||||
/**
|
||||
* The [channels] a sync writes: missing up-front ones, and existing ones
|
||||
* whose name or (localized) description changed, or that still lack a group.
|
||||
*/
|
||||
val channelsToWrite: List<ReminderChannelSpec>,
|
||||
/** The [groups] holding a channel that exists or is about to be written. */
|
||||
val groupsInUse: List<ReminderChannelGroupSpec>,
|
||||
val staleChannelIds: List<String>,
|
||||
val staleGroupIds: List<String>,
|
||||
/** Stale channels kept for now, because a notification on them is still showing. */
|
||||
val keptChannelIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the reminder channels should look like for [calendars]: one channel per
|
||||
* calendar inside a group per account, which of them need writing, and the
|
||||
* reminder channels and groups in [existing] / [existingGroupIds] no calendar
|
||||
* claims any more. Ids outside the reminder namespace (the backup channel, the
|
||||
* legacy channel) are never touched.
|
||||
*/
|
||||
fun planReminderChannels(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: Collection<ExistingReminderChannel>,
|
||||
existingGroupIds: Collection<String>,
|
||||
unnamed: String,
|
||||
description: String,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan {
|
||||
val (local, synced) = calendars.partition { it.isLocal }
|
||||
val groups = buildList {
|
||||
if (local.isNotEmpty()) {
|
||||
add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false))
|
||||
}
|
||||
synced.groupByAccount().forEach { group ->
|
||||
add(
|
||||
ReminderChannelGroupSpec(
|
||||
id = accountGroupId(group.key.type, group.key.name),
|
||||
label = group.label,
|
||||
accountType = group.accountType,
|
||||
isLocal = false,
|
||||
ambiguous = group.ambiguous,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val existingById = existing.associateBy { it.id }
|
||||
val channels = calendars.map { calendar ->
|
||||
ReminderChannelSpec(
|
||||
id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0),
|
||||
calendarId = calendar.id,
|
||||
name = calendar.displayName.ifBlank { unnamed },
|
||||
groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName),
|
||||
upFront = calendar.isLocal || calendar.syncsEvents,
|
||||
)
|
||||
}
|
||||
val wantedChannels = channels.mapTo(HashSet()) { it.id }
|
||||
val wantedGroups = groups.mapTo(HashSet()) { it.id }
|
||||
val toWrite = channels.filter { spec ->
|
||||
val current = existingById[spec.id]
|
||||
if (current == null) {
|
||||
spec.upFront
|
||||
} else {
|
||||
current.name != spec.name || current.description != description ||
|
||||
(current.groupId == null && spec.groupId != null)
|
||||
}
|
||||
}
|
||||
val usedGroupIds = channels
|
||||
.filter { it.id in existingById || it in toWrite }
|
||||
.mapNotNullTo(HashSet()) { it.groupId }
|
||||
val (kept, stale) = existingById.keys
|
||||
.filter { isReminderChannelId(it) && it !in wantedChannels }
|
||||
.partition { it in showingChannelIds }
|
||||
val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId }
|
||||
return ReminderChannelPlan(
|
||||
groups = groups,
|
||||
channels = channels,
|
||||
channelsToWrite = toWrite,
|
||||
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||
staleChannelIds = stale,
|
||||
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups },
|
||||
keptChannelIds = kept,
|
||||
)
|
||||
}
|
||||
|
||||
private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name"
|
||||
|
||||
/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */
|
||||
data class ReminderChannelState(val blocked: Boolean, val groupId: String?)
|
||||
|
||||
/** Reminder notifications the system blocks, while Calendula would post them. */
|
||||
data class ReminderChannelStatus(
|
||||
val appBlocked: Boolean = false,
|
||||
val blockedCalendarIds: Set<Long> = emptySet(),
|
||||
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
|
||||
val groupBlockedCalendarIds: Set<Long> = emptySet(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the system blocks of [calendarIds]' reminders: all of them while the
|
||||
* app's notifications are off, otherwise those whose channel, or the group it
|
||||
* sits in, is switched off. A calendar without a channel yet isn't blocked.
|
||||
*/
|
||||
fun reminderChannelStatus(
|
||||
calendarIds: Collection<Long>,
|
||||
appEnabled: Boolean,
|
||||
channels: Map<String, ReminderChannelState>,
|
||||
blockedGroupIds: Set<String>,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
): ReminderChannelStatus {
|
||||
fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)]
|
||||
val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds }
|
||||
val blocked = if (!appEnabled) {
|
||||
calendarIds.toSet()
|
||||
} else {
|
||||
calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked
|
||||
}
|
||||
return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked)
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationChannelGroup
|
||||
import android.app.NotificationManager
|
||||
import android.app.NotificationManager.IMPORTANCE_DEFAULT
|
||||
import android.app.NotificationManager.IMPORTANCE_LOW
|
||||
import android.app.NotificationManager.IMPORTANCE_MIN
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The reminder notification channels: one per calendar, grouped by account
|
||||
* (#145), created up front so each calendar can be muted or given its own sound
|
||||
* in the system settings before it ever fires.
|
||||
*
|
||||
* A channel the user has touched keeps their settings; [sync] only creates the
|
||||
* missing ones, renames changed ones, and deletes those whose calendar is gone.
|
||||
* A sound picked in the app ([setSound], #518) recreates the channel under the
|
||||
* calendar's next version; the old one goes once nothing shows on it.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderChannels @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) {
|
||||
private val manager: NotificationManager
|
||||
get() = context.getSystemService(NotificationManager::class.java)
|
||||
|
||||
/** What the last [sync] saw, so an unchanged provider costs no channel writes. */
|
||||
@Volatile
|
||||
private var lastSync: Any? = null
|
||||
|
||||
/**
|
||||
* Bring the channels in line with the provider's calendars. An empty
|
||||
* snapshot changes nothing: that is a provider hiccup far more often than
|
||||
* every calendar gone at once.
|
||||
*/
|
||||
@Synchronized
|
||||
fun sync() {
|
||||
val calendars = calendarDataSource.calendars()
|
||||
if (calendars.isEmpty()) return
|
||||
val manager = manager
|
||||
val existing = manager.notificationChannels
|
||||
val existingIds = existing.mapTo(HashSet()) { it.id }
|
||||
val versions = currentVersions(existingIds).also { knownVersions = it }
|
||||
if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||
val groups = manager.notificationChannelGroups
|
||||
val groupIds = groups.map { it.id }
|
||||
// Active notifications are only read when there is something stale to protect.
|
||||
val plan = plan(calendars, existing, groupIds, versions).let { draft ->
|
||||
if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds))
|
||||
}
|
||||
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
|
||||
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
|
||||
val groupNames = groups.associate { it.id to it.name?.toString() }
|
||||
write(
|
||||
groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) },
|
||||
channels = plan.channelsToWrite,
|
||||
existing = existing,
|
||||
)
|
||||
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
|
||||
val legacyGone = retireLegacyChannel()
|
||||
// A kept channel still has to go once its notification does, so don't cache.
|
||||
lastSync = if (plan.keptChannelIds.isEmpty()) {
|
||||
syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): Any = listOf(
|
||||
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||
Locale.getDefault(),
|
||||
channelIds,
|
||||
versions,
|
||||
)
|
||||
|
||||
/**
|
||||
* The current versions last resolved under the lock ([sync], [channelFor]).
|
||||
* Only [recreate], under the same lock, moves a calendar higher and updates
|
||||
* it, so a hit whose channel still exists is current.
|
||||
*/
|
||||
@Volatile
|
||||
private var knownVersions: Map<Long, Int> = emptyMap()
|
||||
|
||||
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
|
||||
currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() })
|
||||
|
||||
/** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */
|
||||
private fun showingChannelIds(candidates: Collection<String>): Set<String> = runCatching {
|
||||
manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId }
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "Could not read active notifications", e)
|
||||
candidates.toSet()
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel to post [calendarId]'s reminder on, created first if a sync
|
||||
* has not got to it yet. Null when the calendar no longer exists. Should the
|
||||
* calendar lookup fail or come back empty, the channel is still created,
|
||||
* plainly named and ungrouped, for the next sync to name and file — a
|
||||
* reminder is never lost to its channel.
|
||||
*/
|
||||
@Synchronized
|
||||
fun channelFor(calendarId: Long): String? {
|
||||
val manager = manager
|
||||
knownVersions[calendarId]?.let { version ->
|
||||
val known = reminderChannelId(calendarId, version)
|
||||
if (manager.getNotificationChannel(known) != null) return known
|
||||
}
|
||||
val existing = manager.notificationChannels
|
||||
val versions = currentVersions(existing.map { it.id }).also { knownVersions = it }
|
||||
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
|
||||
if (existing.any { it.id == id }) return id
|
||||
val calendars = try {
|
||||
calendarDataSource.calendars()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not look up calendar $calendarId for its channel", e)
|
||||
emptyList()
|
||||
}
|
||||
val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)
|
||||
if (calendars.isEmpty()) {
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
return id
|
||||
}
|
||||
val plan = plan(calendars, existing, emptyList(), versions)
|
||||
val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null
|
||||
try {
|
||||
val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id }
|
||||
write(
|
||||
groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups },
|
||||
channels = listOf(spec),
|
||||
existing = existing,
|
||||
)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not file the channel of calendar $calendarId", e)
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Run [block] with [calendarId]'s channel held: no sound pick or sync can
|
||||
* move or retire it until [block] returns. Null, without running [block],
|
||||
* when the calendar is gone or its channel can't be made; [block]'s own
|
||||
* failures propagate.
|
||||
*/
|
||||
@Synchronized
|
||||
fun <T> withChannel(calendarId: Long, block: (String) -> T): T? {
|
||||
val channelId = try {
|
||||
channelFor(calendarId)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No channel for calendar $calendarId", e)
|
||||
null
|
||||
}
|
||||
return channelId?.let(block)
|
||||
}
|
||||
|
||||
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||
val manager = manager
|
||||
val appEnabled = manager.areNotificationsEnabled()
|
||||
val existing = manager.notificationChannels
|
||||
val channels = existing.associate {
|
||||
it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group)
|
||||
}
|
||||
val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }
|
||||
return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys))
|
||||
}
|
||||
|
||||
/** A "Silent" (low) channel keeps its sound but never plays it. */
|
||||
private fun NotificationChannel.audibleSound(): Uri? =
|
||||
sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW }
|
||||
|
||||
/**
|
||||
* The sound each of [calendarIds]' channels plays; null is silent. A
|
||||
* calendar whose channel doesn't exist yet is left out.
|
||||
*/
|
||||
fun sounds(calendarIds: Collection<Long>): Map<Long, Uri?> {
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val versions = currentVersions(byId.keys)
|
||||
return calendarIds.mapNotNull { id ->
|
||||
byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() }
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
/**
|
||||
* Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is
|
||||
* fixed once created, so each moves to a new channel version carrying over
|
||||
* everything else, and the old one retires in the sync that follows (#518). Calendars without a
|
||||
* channel are skipped unless [createMissing]. Returns whether every move
|
||||
* went through.
|
||||
*/
|
||||
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean): Boolean {
|
||||
if (createMissing) calendarIds.forEach(::channelFor)
|
||||
val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id }
|
||||
val current = currentVersions(existingIds)
|
||||
val floors = calendarIds
|
||||
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
|
||||
.associateWith { (current[it] ?: 0) + 1 }
|
||||
if (floors.isEmpty()) return false
|
||||
val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
|
||||
// Retire the old versions now, or each calendar shows twice in system settings until the next scan.
|
||||
try {
|
||||
sync()
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Old channel versions left to the next sync", e)
|
||||
}
|
||||
return applied
|
||||
}
|
||||
|
||||
/**
|
||||
* Create each calendar's [versions] from its current channel. The old one is
|
||||
* left to the next [sync], which retires it once nothing shows on it.
|
||||
*/
|
||||
@Synchronized
|
||||
private fun recreate(versions: Map<Long, Int>, sound: Uri?): Boolean {
|
||||
val manager = manager
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val current = currentReminderChannelVersions(byId.keys, emptyMap())
|
||||
var allApplied = true
|
||||
versions.forEach { (calendarId, version) ->
|
||||
val from = current[calendarId]?.takeIf { it < version }
|
||||
val old = from?.let { byId[reminderChannelId(calendarId, it)] }
|
||||
if (old == null) {
|
||||
allApplied = false
|
||||
return@forEach
|
||||
}
|
||||
try {
|
||||
// Picking a sound asks for one, which a "Silent" (low) channel would never play.
|
||||
val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) {
|
||||
IMPORTANCE_DEFAULT
|
||||
} else {
|
||||
old.importance
|
||||
}
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply {
|
||||
description = old.description
|
||||
old.group?.let { group = it }
|
||||
inheritFrom(old)
|
||||
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
|
||||
},
|
||||
)
|
||||
knownVersions = knownVersions + (calendarId to version)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not move calendar $calendarId to a new sound", e)
|
||||
allApplied = false
|
||||
}
|
||||
}
|
||||
lastSync = null
|
||||
return allApplied
|
||||
}
|
||||
|
||||
private fun plan(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: List<NotificationChannel>,
|
||||
existingGroupIds: List<String>,
|
||||
versions: Map<Long, Int>,
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan = planReminderChannels(
|
||||
calendars = calendars,
|
||||
existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) },
|
||||
existingGroupIds = existingGroupIds,
|
||||
unnamed = context.getString(R.string.calendar_unnamed),
|
||||
description = context.getString(R.string.reminder_channel_description),
|
||||
versions = versions,
|
||||
showingChannelIds = showingChannelIds,
|
||||
)
|
||||
|
||||
private fun write(
|
||||
groups: List<ReminderChannelGroupSpec>,
|
||||
channels: List<ReminderChannelSpec>,
|
||||
existing: List<NotificationChannel>,
|
||||
) {
|
||||
val manager = manager
|
||||
if (groups.isNotEmpty()) {
|
||||
manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) })
|
||||
}
|
||||
if (channels.isEmpty()) return
|
||||
val byId = existing.associateBy { it.id }
|
||||
val description = context.getString(R.string.reminder_channel_description)
|
||||
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
|
||||
// Importance only applies on creation; an existing channel keeps its own.
|
||||
manager.createNotificationChannels(
|
||||
channels.map { spec ->
|
||||
val current = byId[spec.id]
|
||||
NotificationChannel(
|
||||
spec.id,
|
||||
spec.name,
|
||||
current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
this.description = description
|
||||
spec.groupId?.let { group = it }
|
||||
if (current == null && template != null) inheritFrom(template)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry a channel's sound, vibration, lights and badge over to a new one: the
|
||||
* legacy channel to a per-calendar one on upgrade, or a calendar's channel to
|
||||
* its next version (#518). Lock-screen visibility and a DND override can't
|
||||
* follow: the system resets both on channels an app creates.
|
||||
*/
|
||||
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
|
||||
setSound(template.sound, template.audioAttributes)
|
||||
// The pattern setter also flips vibration on or off, so it goes first.
|
||||
vibrationPattern = template.vibrationPattern
|
||||
enableVibration(template.shouldVibrate())
|
||||
enableLights(template.shouldShowLights())
|
||||
lightColor = template.lightColor
|
||||
setShowBadge(template.canShowBadge())
|
||||
// Only honoured with Do Not Disturb access, so usually left to the user.
|
||||
setBypassDnd(template.canBypassDnd())
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the pre-#145 channel once the per-calendar ones carry its settings,
|
||||
* but not while a reminder posted on it is still on screen — deleting the
|
||||
* channel would take that notification with it. Returns whether it is gone.
|
||||
*/
|
||||
private fun retireLegacyChannel(): Boolean {
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
|
||||
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID))
|
||||
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
|
||||
return !showing
|
||||
}
|
||||
|
||||
private fun groupLabel(group: ReminderChannelGroupSpec): String {
|
||||
if (group.isLocal) return context.getString(R.string.calendars_local_header)
|
||||
val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) }
|
||||
if (!group.ambiguous) return name
|
||||
return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderChannels"
|
||||
|
||||
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
@@ -27,8 +29,8 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts one notification per occurrence on its calendar's channel
|
||||
* ([ReminderChannels], #145). Tapping opens the event's detail screen.
|
||||
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||
* the event's detail screen.
|
||||
*
|
||||
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||
@@ -41,7 +43,6 @@ class ReminderNotifier @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val channels: ReminderChannels,
|
||||
) {
|
||||
|
||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||
@@ -52,19 +53,19 @@ class ReminderNotifier @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* The single choke point for "this calendar posts no reminders": switched
|
||||
* off (also covering a snooze armed before the switch-off, and a read-only
|
||||
* install whose switch lives in [CalendarPrefs]), or its notifications
|
||||
* turned off in Calendula's own settings (#272).
|
||||
* The single choke point for "this calendar is switched off", covering the
|
||||
* two paths that reach [post] around the scan's own filter: a snooze armed
|
||||
* before the switch-off, and a read-only install whose switch lives in
|
||||
* [CalendarPrefs].
|
||||
*/
|
||||
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||
|
||||
/** Post [alert], unless its calendar is silenced or gone. */
|
||||
/** Post [alert], unless its calendar is switched off. */
|
||||
suspend fun post(alert: ReminderAlert) {
|
||||
if (isSilenced(alert.calendarId)) return
|
||||
ensureChannel()
|
||||
val title = displayTitle(alert)
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
@@ -87,15 +88,7 @@ class ReminderNotifier @Inject constructor(
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
||||
// Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post.
|
||||
val posted = channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) }
|
||||
if (posted == null) {
|
||||
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun notify(alert: ReminderAlert, channelId: String, title: String, text: String) {
|
||||
val notification = NotificationCompat.Builder(context, channelId)
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
@@ -160,7 +153,7 @@ class ReminderNotifier @Inject constructor(
|
||||
private fun cancelLegacy(alert: ReminderAlert) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
manager.activeNotifications
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID }
|
||||
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||
.filter { it.notification.`when` == alert.beginMillis }
|
||||
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||
@@ -188,8 +181,21 @@ class ReminderNotifier @Inject constructor(
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
/** Channel creation is idempotent; re-running refreshes the localized name. */
|
||||
private fun ensureChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.reminder_channel_name),
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = context.getString(R.string.reminder_channel_description)
|
||||
}
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderNotifier"
|
||||
const val CHANNEL_ID = "reminders"
|
||||
|
||||
// One id, distinct tags: the tag (occurrence) already keys the
|
||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||
|
||||
@@ -43,7 +43,6 @@ class ReminderScanner @Inject constructor(
|
||||
private val source: ReminderInstanceSource,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val notifier: ReminderNotifier,
|
||||
private val channels: ReminderChannels,
|
||||
private val snoozes: ReminderSnoozeScheduler,
|
||||
private val alarms: ReminderAlarmScheduler,
|
||||
private val state: ReminderStatePrefs,
|
||||
@@ -86,14 +85,10 @@ class ReminderScanner @Inject constructor(
|
||||
return
|
||||
}
|
||||
|
||||
syncChannels()
|
||||
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
|
||||
// Reach into the past too: an all-day "at time of event" encodes to a
|
||||
// negative offset, and a catch-up pass needs the occurrences it missed.
|
||||
// Calendars muted in-app (#272) plan nothing, so they arm no wake-ups.
|
||||
val muted = settingsPrefs.mutedReminderCalendarIds.first()
|
||||
val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead)
|
||||
.filter { it.calendarId !in muted }
|
||||
val planned = planReminders(
|
||||
instances = occurrences,
|
||||
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
|
||||
@@ -122,19 +117,6 @@ class ReminderScanner @Inject constructor(
|
||||
alarms.scheduleScan(schedule.nextAlarmMillis)
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider change re-scans, so a calendar added, renamed or removed keeps
|
||||
* its channel in step here. Skipped while reminders are off, when the
|
||||
* channels have nothing to do. A failure never costs the reminders.
|
||||
*/
|
||||
private fun syncChannels() {
|
||||
try {
|
||||
channels.sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Reminder channel sync failed", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,6 +35,7 @@ import androidx.compose.runtime.saveable.listSaver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberHeld
|
||||
import de.jeanlucmakiola.calendula.ui.common.screen
|
||||
import de.jeanlucmakiola.calendula.ui.common.ViewScreen
|
||||
@@ -52,6 +53,14 @@ 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
|
||||
@@ -441,6 +450,17 @@ 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
|
||||
@@ -538,6 +558,9 @@ 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() }
|
||||
@@ -588,6 +611,17 @@ 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 },
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
@@ -613,10 +647,12 @@ fun CalendarHost(
|
||||
// A fresh event, like a duplicate from the detail screen (#52).
|
||||
openImportForm(form, ImportSource.Insert)
|
||||
},
|
||||
chipShown = moveOutcome != null || selectionFailure != null,
|
||||
chipShown = moveOutcome != null || selectionFailure != null || syncChip.value != null,
|
||||
onDismissChip = {
|
||||
reschedule.consumeOutcome()
|
||||
eventActions.consumeFailure()
|
||||
// Only the chip on show: a receipt queued behind it still gets its turn.
|
||||
if (moveOutcome == null && selectionFailure == null) syncChip.value = null
|
||||
},
|
||||
)
|
||||
CalendarFab(chromeHost, todayInToolbar, fabSelection)
|
||||
@@ -679,10 +715,21 @@ fun CalendarHost(
|
||||
EventMoveHost(
|
||||
reschedule,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
actionFailure = eventActionFailureMessage(selectionFailure),
|
||||
onActionFailureShown = eventActions::consumeFailure,
|
||||
notice = selectionFailureMessage ?: syncChipMessage,
|
||||
onNoticeShown = {
|
||||
if (selectionFailureMessage != null) eventActions.consumeFailure() else syncChip.value = null
|
||||
},
|
||||
)
|
||||
|
||||
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,6 +85,11 @@ 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
|
||||
@@ -130,6 +135,8 @@ 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
|
||||
@@ -174,6 +181,8 @@ fun CalendarsScreen(
|
||||
onEdit = { calendar -> editorSession++; editorId = calendar.id },
|
||||
onSetVisible = viewModel::setCalendarVisible,
|
||||
onSetAccountVisible = viewModel::setAccountVisible,
|
||||
syncAccessDismissed = syncAccessDismissed,
|
||||
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -191,6 +200,8 @@ 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() }
|
||||
@@ -321,6 +332,20 @@ 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,6 +9,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
||||
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -56,6 +57,23 @@ 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
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -73,13 +72,11 @@ fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||
@Composable
|
||||
fun sourceAppName(accountType: String): String {
|
||||
val context = LocalContext.current
|
||||
return remember(accountType) { sourceAppLabel(context, accountType) }
|
||||
}
|
||||
|
||||
/** [sourceAppName] outside composition, e.g. for notification channel groups. */
|
||||
fun sourceAppLabel(context: Context, accountType: String): String {
|
||||
val pm = context.packageManager
|
||||
return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
return remember(accountType) {
|
||||
val pm = context.packageManager
|
||||
val packages = sourceAppPackages(context, accountType)
|
||||
packages.firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,12 @@ 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
|
||||
@@ -38,6 +42,8 @@ import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.filter.CalendarFilterList
|
||||
@@ -61,6 +67,8 @@ import kotlinx.datetime.LocalDate
|
||||
*
|
||||
* [currentDate] seeds the jump-to-date picker (the visible day/week-start/month
|
||||
* anchor); [onJumpToDate] navigates the active view to the chosen day.
|
||||
* [sync] adds "Sync now" beside it while there is a synced calendar (#240),
|
||||
* and a row to grant account access while some account can't be reached yet.
|
||||
*/
|
||||
@Composable
|
||||
fun CalendarDrawer(
|
||||
@@ -71,6 +79,7 @@ fun CalendarDrawer(
|
||||
onJumpToDate: (LocalDate) -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
|
||||
sync: DrawerSync? = null,
|
||||
) {
|
||||
var showDatePicker by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -103,11 +112,12 @@ fun CalendarDrawer(
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_jump_to_date),
|
||||
position = Position.Alone,
|
||||
position = if (sync?.hasRows == true) Position.Top else Position.Alone,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.DateRange) },
|
||||
onClick = { showDatePicker = true },
|
||||
)
|
||||
if (sync != null) SyncRows(sync)
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
@@ -138,6 +148,64 @@ 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
|
||||
|
||||
@@ -51,8 +51,8 @@ private val FAB_BAND = 88.dp
|
||||
fun EventMoveHost(
|
||||
viewModel: RescheduleViewModel,
|
||||
modifier: Modifier = Modifier,
|
||||
actionFailure: String? = null,
|
||||
onActionFailureShown: () -> Unit = {},
|
||||
notice: String? = null,
|
||||
onNoticeShown: () -> Unit = {},
|
||||
) {
|
||||
val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle()
|
||||
val outcome by viewModel.outcome.collectAsStateWithLifecycle()
|
||||
@@ -81,7 +81,7 @@ fun EventMoveHost(
|
||||
}
|
||||
// A failed selection action (#141) shares the chip rather than stacking on it.
|
||||
val message = when (outcome) {
|
||||
null -> actionFailure
|
||||
null -> notice
|
||||
is MoveOutcome.Moved -> if (resizedLabel != null) {
|
||||
stringResource(R.string.event_resize_done, resizedLabel)
|
||||
} else {
|
||||
@@ -116,10 +116,10 @@ fun EventMoveHost(
|
||||
viewModel.consumeOutcome()
|
||||
}
|
||||
// A failure waits for the chip to be free, then has its own turn.
|
||||
LaunchedEffect(actionFailure, outcome == null) {
|
||||
if (actionFailure == null || outcome != null) return@LaunchedEffect
|
||||
LaunchedEffect(notice, outcome == null) {
|
||||
if (notice == null || outcome != null) return@LaunchedEffect
|
||||
delay(CHIP_MILLIS)
|
||||
onActionFailureShown()
|
||||
onNoticeShown()
|
||||
}
|
||||
|
||||
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
|
||||
@@ -138,7 +138,7 @@ fun EventMoveHost(
|
||||
// write anyway, so offering it would be a button that does nothing.
|
||||
val undo = content.undo?.takeIf { !writeInFlight }
|
||||
SnackChip(
|
||||
visible = outcome != null || actionFailure != null,
|
||||
visible = outcome != null || notice != null,
|
||||
message = content.message,
|
||||
maxWidth = chipMaxWidth,
|
||||
actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null },
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
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,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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
|
||||
}
|
||||
-294
@@ -1,294 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
|
||||
/**
|
||||
* Per-calendar notifications and reminder overrides (#145, #272), reached from
|
||||
* Settings → Notifications. Calendars are listed by account as connected groups;
|
||||
* a calendar unfolds its options in place, one tone darker, inside its group.
|
||||
*/
|
||||
@Composable
|
||||
internal fun CalendarRemindersScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
var expandedCalendars by rememberSaveable { mutableStateOf(emptyList<Long>()) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
onBack = onBack,
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
GroupedHint(stringResource(R.string.settings_calendar_reminders_hint), style = MaterialTheme.typography.bodySmall)
|
||||
state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group ->
|
||||
if (groupIndex > 0) Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(accountGroupTitle(group))
|
||||
val calendars = group.calendars
|
||||
calendars.forEachIndexed { index, calendar ->
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
val notifying = calendar.id !in state.mutedReminderCalendarIds
|
||||
CalendarReminderEntry(
|
||||
calendar = calendar,
|
||||
state = state,
|
||||
position = positionOf(index, calendars.size),
|
||||
expanded = expanded,
|
||||
notifying = notifying,
|
||||
blocked = notifying && calendar.id in channelStatus.blockedCalendarIds,
|
||||
onToggleExpand = {
|
||||
expandedCalendars = if (expanded) {
|
||||
expandedCalendars - calendar.id
|
||||
} else {
|
||||
expandedCalendars + calendar.id
|
||||
}
|
||||
},
|
||||
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
|
||||
soundLabel = soundPicker.loadedSounds?.let { soundLabel(it[calendar.id]) },
|
||||
onPickSound = { soundPicker.pick(calendar.id) },
|
||||
onOpenSettings = { soundPicker.openCalendarSettings(calendar.id) },
|
||||
onOpenSpecialDates = onOpenSpecialDates,
|
||||
onEditOverride = { overrideDialog = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overrideDialog?.let { target ->
|
||||
val map = if (target.isAllDay) {
|
||||
state.perCalendarAllDayReminderOverride
|
||||
} else {
|
||||
state.perCalendarReminderOverride
|
||||
}
|
||||
ReminderDefaultPicker(
|
||||
title = stringResource(
|
||||
if (target.isAllDay) {
|
||||
R.string.settings_default_reminder_allday
|
||||
} else {
|
||||
R.string.settings_default_reminder
|
||||
},
|
||||
),
|
||||
presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS,
|
||||
selected = map.reminderOverrideFor(target.calendarId),
|
||||
allowInherit = true,
|
||||
onSelect = {
|
||||
if (target.isAllDay) {
|
||||
viewModel.setCalendarAllDayReminderOverride(target.calendarId, it)
|
||||
} else {
|
||||
viewModel.setCalendarReminderOverride(target.calendarId, it)
|
||||
}
|
||||
},
|
||||
onDismiss = { overrideDialog = null },
|
||||
leadTimeSummary = if (target.isAllDay) {
|
||||
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One calendar in its account group, with its options unfolding beneath it:
|
||||
* the notification switch and channel deep-link for every calendar, then the
|
||||
* default-reminder overrides where it takes them — or, for a special-dates
|
||||
* calendar, a link to the section that owns them.
|
||||
*/
|
||||
@Composable
|
||||
private fun CalendarReminderEntry(
|
||||
calendar: CalendarSource,
|
||||
state: SettingsUiState,
|
||||
position: Position,
|
||||
expanded: Boolean,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
onToggleExpand: () -> Unit,
|
||||
onSetNotifying: (Boolean) -> Unit,
|
||||
soundLabel: String?,
|
||||
onPickSound: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
val opensGroup = position == Position.Top || position == Position.Alone
|
||||
val closesGroup = position == Position.Bottom || position == Position.Alone
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = when {
|
||||
!notifying -> stringResource(R.string.settings_calendar_notifications_off)
|
||||
blocked -> stringResource(R.string.settings_notifications_blocked)
|
||||
else -> null
|
||||
},
|
||||
position = when {
|
||||
!expanded -> position
|
||||
opensGroup -> Position.Top
|
||||
else -> Position.Middle
|
||||
},
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
onClick = onToggleExpand,
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
val managed = calendar.id in state.managedCalendarIds
|
||||
val takesOverrides = calendar.canModifyContents && !managed
|
||||
val nested = MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
// The options round off their calendar; mid-group they keep the row gap.
|
||||
Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_notifications),
|
||||
checked = notifying,
|
||||
onCheckedChange = onSetNotifying,
|
||||
summary = stringResource(R.string.settings_calendar_notifications_hint),
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = soundLabel,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onClick = onPickSound,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_more),
|
||||
summary = if (blocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_calendar_notification_sound_hint)
|
||||
},
|
||||
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
|
||||
container = nested,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSettings,
|
||||
)
|
||||
if (managed) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
trailing = { ChevronIcon() },
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
} else if (takesOverrides) {
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = false,
|
||||
choice = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultReminderMinutes,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = true,
|
||||
choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultAllDayReminderMinutes,
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverrideRow(
|
||||
calendarId: Long,
|
||||
isAllDay: Boolean,
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
position: Position,
|
||||
container: Color,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = stringResource(
|
||||
if (isAllDay) R.string.settings_default_reminder_allday else R.string.settings_default_reminder,
|
||||
),
|
||||
summary = calendarOverrideSummary(choice, globalDefault),
|
||||
position = position,
|
||||
container = container,
|
||||
onClick = { onEditOverride(OverrideTarget(calendarId, isAllDay)) },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChevronIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
|
||||
/** Row summary for a calendar: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun calendarOverrideSummary(
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes)
|
||||
}
|
||||
+129
-201
@@ -6,33 +6,22 @@ import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -40,28 +29,27 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.DurationPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
|
||||
import de.jeanlucmakiola.calendula.ui.common.durationLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import de.jeanlucmakiola.floret.android.notificationSoundPickerIntent
|
||||
import de.jeanlucmakiola.floret.android.openNotificationSettings
|
||||
import de.jeanlucmakiola.floret.android.pickedSound
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.minutesOrEmpty
|
||||
import kotlinx.coroutines.launch
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/**
|
||||
@@ -74,7 +62,7 @@ internal fun NotificationsScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenCalendarReminders: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
@@ -95,17 +83,9 @@ internal fun NotificationsScreen(
|
||||
var showAllDayReminder by remember { mutableStateOf(false) }
|
||||
var showAllDayReminderTime by remember { mutableStateOf(false) }
|
||||
var showSnooze by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
|
||||
val openAppSettings = soundPicker.openAppSettings
|
||||
val loadedSounds = soundPicker.loadedSounds
|
||||
val pickSound = soundPicker.pick
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
var calendarSectionExpanded by remember { mutableStateOf(false) }
|
||||
var expandedCalendars by remember { mutableStateOf(emptySet<Long>()) }
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_section_notifications),
|
||||
@@ -113,16 +93,6 @@ internal fun NotificationsScreen(
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) {
|
||||
NotificationCategoryHint(
|
||||
onOpen = {
|
||||
viewModel.dismissNotificationCategoryHint()
|
||||
openAppSettings()
|
||||
},
|
||||
onDismiss = viewModel::dismissNotificationCategoryHint,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_reminders),
|
||||
checked = state.remindersEnabled,
|
||||
@@ -130,25 +100,6 @@ internal fun NotificationsScreen(
|
||||
summary = stringResource(R.string.settings_reminders_hint),
|
||||
position = Position.Top,
|
||||
)
|
||||
if (calendarIds.isNotEmpty()) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) },
|
||||
position = Position.Middle,
|
||||
onClick = { pickSound(ALL_CALENDARS) },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_more),
|
||||
summary = if (channelStatus.appBlocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = openAppSettings,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = reminderChoiceLabel(state.defaultReminderMinutes),
|
||||
@@ -198,21 +149,84 @@ internal fun NotificationsScreen(
|
||||
onClick = { showSnooze = true },
|
||||
)
|
||||
|
||||
if (state.reminderCalendars.isNotEmpty()) {
|
||||
// Per-calendar overrides, folded behind one header. Each writable
|
||||
// calendar may keep, drop or replace the global default, separately for
|
||||
// timed and all-day events.
|
||||
if (state.writableCalendars.isNotEmpty()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_subtitle),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_hint),
|
||||
position = Position.Alone,
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenCalendarReminders,
|
||||
trailing = { ExpandIcon(calendarSectionExpanded) },
|
||||
onClick = { calendarSectionExpanded = !calendarSectionExpanded },
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = calendarSectionExpanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
state.writableCalendars.forEach { calendar ->
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// Special-dates calendars own their reminders in their
|
||||
// own section — link there instead.
|
||||
if (calendar.id in state.managedCalendarIds) {
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
return@forEach
|
||||
}
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
position = if (expanded) Position.Top else Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
onClick = {
|
||||
expandedCalendars = if (expanded) {
|
||||
expandedCalendars - calendar.id
|
||||
} else {
|
||||
expandedCalendars + calendar.id
|
||||
}
|
||||
},
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) },
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,80 +275,59 @@ internal fun NotificationsScreen(
|
||||
onDismiss = { showAllDayReminderTime = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** [soundTarget] meaning every calendar at once. */
|
||||
internal const val ALL_CALENDARS = Long.MIN_VALUE
|
||||
|
||||
/** What the calendars that have a channel share, sound-wise. */
|
||||
private sealed interface SharedSound {
|
||||
data object None : SharedSound
|
||||
data object Mixed : SharedSound
|
||||
data class Same(val sound: ReminderSound) : SharedSound
|
||||
}
|
||||
|
||||
private fun sharedSound(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): SharedSound {
|
||||
val distinct = calendarIds.mapNotNull { sounds[it] }.distinctBy { it.uri }
|
||||
return when (distinct.size) {
|
||||
0 -> SharedSound.None
|
||||
1 -> SharedSound.Same(distinct.single())
|
||||
else -> SharedSound.Mixed
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun soundLabel(sound: ReminderSound?): String = when {
|
||||
sound == null -> stringResource(R.string.settings_notification_sound_default)
|
||||
sound.uri == null -> stringResource(R.string.settings_notification_sound_silent)
|
||||
sound.uri == DEFAULT_NOTIFICATION_URI -> sound.title
|
||||
?.let { stringResource(R.string.settings_notification_sound_default_named, it) }
|
||||
?: stringResource(R.string.settings_notification_sound_default)
|
||||
else -> sound.title ?: stringResource(R.string.settings_notification_sound_custom)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun globalSoundLabel(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): String =
|
||||
when (val shared = sharedSound(sounds, calendarIds)) {
|
||||
SharedSound.None -> soundLabel(null)
|
||||
SharedSound.Mixed -> stringResource(R.string.settings_notification_sound_mixed)
|
||||
is SharedSound.Same -> soundLabel(shared.sound)
|
||||
}
|
||||
|
||||
/** Samsung's One UI can start a new notification category switched off (#145). */
|
||||
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
|
||||
/** The one-time Samsung note, with a way into the app's notification settings. */
|
||||
@Composable
|
||||
private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) {
|
||||
IconInfoCard(
|
||||
icon = Icons.Outlined.Info,
|
||||
iconContentDescription = null,
|
||||
iconAlignment = Alignment.Top,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_notification_category_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) }
|
||||
TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) }
|
||||
overrideDialog?.let { target ->
|
||||
val map = if (target.isAllDay) {
|
||||
state.perCalendarAllDayReminderOverride
|
||||
} else {
|
||||
state.perCalendarReminderOverride
|
||||
}
|
||||
ReminderDefaultPicker(
|
||||
title = stringResource(
|
||||
if (target.isAllDay) {
|
||||
R.string.settings_default_reminder_allday
|
||||
} else {
|
||||
R.string.settings_default_reminder
|
||||
},
|
||||
),
|
||||
presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS,
|
||||
selected = map.reminderOverrideFor(target.calendarId),
|
||||
allowInherit = true,
|
||||
onSelect = {
|
||||
if (target.isAllDay) {
|
||||
viewModel.setCalendarAllDayReminderOverride(target.calendarId, it)
|
||||
} else {
|
||||
viewModel.setCalendarReminderOverride(target.calendarId, it)
|
||||
}
|
||||
},
|
||||
onDismiss = { overrideDialog = null },
|
||||
leadTimeSummary = if (target.isAllDay) {
|
||||
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ExternalLinkIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
|
||||
/** A global default (empty = none) as a picker choice for selection highlighting. */
|
||||
private fun List<Int>.toReminderChoice(): ReminderOverride =
|
||||
if (isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(this)
|
||||
|
||||
/** Row summary for a calendar: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun calendarOverrideSummary(
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes)
|
||||
}
|
||||
|
||||
/** Snooze delays offered for the notification "Snooze" action, in minutes. */
|
||||
private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
||||
|
||||
@@ -379,68 +372,3 @@ private fun openBatteryOptimizationSettings(context: Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The reminder-sound picker (#518) shared by Notifications (all calendars) and the per-calendar page. */
|
||||
internal class ReminderSoundPicker(
|
||||
val loadedSounds: Map<Long, ReminderSound>?,
|
||||
val pick: (Long) -> Unit,
|
||||
val openAppSettings: () -> Unit,
|
||||
val openCalendarSettings: (Long) -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun rememberReminderSoundPicker(viewModel: SettingsViewModel, calendarIds: List<Long>): ReminderSoundPicker {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val openCalendarSettings: (Long) -> Unit = { calendarId ->
|
||||
scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) }
|
||||
}
|
||||
val openAppSettings: () -> Unit = {
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
}
|
||||
val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle()
|
||||
val sounds = loadedSounds.orEmpty()
|
||||
val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed)
|
||||
val soundUnreadableMessage = stringResource(R.string.settings_notification_sound_unreadable)
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.soundFailed.collect { failure ->
|
||||
val message = if (failure == SoundFailure.Unreadable) soundUnreadableMessage else soundFailedMessage
|
||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
// ALL_CALENDARS, a calendar id, or null when no pick is pending.
|
||||
var soundTarget by rememberSaveable { mutableStateOf<Long?>(null) }
|
||||
val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
val target = soundTarget
|
||||
soundTarget = null
|
||||
val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult
|
||||
when (target) {
|
||||
null -> Unit
|
||||
ALL_CALENDARS -> viewModel.setReminderSoundForAll(picked.uri)
|
||||
else -> viewModel.setReminderSound(target, picked.uri)
|
||||
}
|
||||
}
|
||||
val pickSoundTitle = stringResource(R.string.settings_notification_sound)
|
||||
val pickSound: (Long) -> Unit = pick@{ target ->
|
||||
if (soundTarget != null) return@pick
|
||||
val current = if (target == ALL_CALENDARS) {
|
||||
(sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound
|
||||
} else {
|
||||
sounds[target]
|
||||
}
|
||||
soundTarget = target
|
||||
try {
|
||||
// A missing or mixed sound preselects Default; a silent one, Silent.
|
||||
val preselect = if (current == null) DEFAULT_NOTIFICATION_URI else current.uri
|
||||
soundPicker.launch(notificationSoundPickerIntent(preselect, pickSoundTitle))
|
||||
} catch (e: RuntimeException) {
|
||||
// No picker, or one that refuses to start: the system screen still has the sound.
|
||||
soundTarget = null
|
||||
if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target)
|
||||
}
|
||||
}
|
||||
return ReminderSoundPicker(loadedSounds, pickSound, openAppSettings, openCalendarSettings)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ import de.jeanlucmakiola.floret.identity.predictiveBackExit
|
||||
|
||||
/** The settings sub-screens reached from the hub's category rows. */
|
||||
private enum class SettingsSection {
|
||||
Appearance, Views, EventForm, Notifications, CalendarReminders, SpecialDates, Widgets, Licences
|
||||
Appearance, Views, EventForm, Notifications, SpecialDates, Widgets, Licences
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,9 +131,8 @@ fun SettingsScreen(
|
||||
) {
|
||||
EventFormScreen(state = state, viewModel = viewModel, onBack = { section = null }, visible = section == SettingsSection.EventForm)
|
||||
}
|
||||
// Stays up beneath its per-calendar subpage, so backing out reveals it.
|
||||
AnimatedVisibility(
|
||||
visible = section == SettingsSection.Notifications || section == SettingsSection.CalendarReminders,
|
||||
visible = section == SettingsSection.Notifications,
|
||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
||||
exit = overlayExit,
|
||||
) {
|
||||
@@ -141,21 +140,8 @@ fun SettingsScreen(
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
onBack = { section = null },
|
||||
onOpenCalendarReminders = { section = SettingsSection.CalendarReminders },
|
||||
visible = section == SettingsSection.Notifications,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = section == SettingsSection.CalendarReminders,
|
||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
||||
exit = overlayExit,
|
||||
) {
|
||||
CalendarRemindersScreen(
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
onBack = { section = SettingsSection.Notifications },
|
||||
onOpenSpecialDates = { section = SettingsSection.SpecialDates },
|
||||
visible = section == SettingsSection.CalendarReminders,
|
||||
visible = section == SettingsSection.Notifications,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import android.net.Uri
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -97,14 +96,8 @@ data class SettingsUiState(
|
||||
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
|
||||
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Switched-on calendars you can edit: the per-calendar event-duration rows. */
|
||||
/** Writable calendars, shown as per-calendar reminder-override rows. */
|
||||
val writableCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
|
||||
val reminderCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Calendars whose reminders Calendula doesn't post (#272). */
|
||||
val mutedReminderCalendarIds: Set<Long> = emptySet(),
|
||||
/** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */
|
||||
val notificationCategoryHintDismissed: Boolean = true,
|
||||
/**
|
||||
* Whether the event-colour picker is offered on calendars that publish no
|
||||
* colour palette (the colour may then not survive their next sync).
|
||||
@@ -137,9 +130,3 @@ data class SpecialDatesUiState(
|
||||
/** Epoch millis of the last sync, or 0 if it has never run. */
|
||||
val lastRun: Long = 0L,
|
||||
)
|
||||
|
||||
/** A reminder channel's sound: null [uri] is silent; [title] is null when it can't be resolved. */
|
||||
data class ReminderSound(val uri: Uri?, val title: String?)
|
||||
|
||||
/** Why a picked reminder sound wasn't applied. */
|
||||
enum class SoundFailure { NotApplied, Unreadable }
|
||||
@@ -3,8 +3,6 @@ package de.jeanlucmakiola.calendula.ui.settings
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -18,12 +16,10 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
|
||||
import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate
|
||||
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
|
||||
import de.jeanlucmakiola.floret.android.ringtoneTitle
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -37,8 +33,6 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
@@ -51,12 +45,7 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale
|
||||
import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle
|
||||
import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -65,7 +54,6 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -74,13 +62,11 @@ import javax.inject.Inject
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
calendarPrefs: CalendarPrefs,
|
||||
repository: CalendarRepository,
|
||||
private val specialDatesEngine: SpecialDatesSyncEngine,
|
||||
specialDatesSpec: SpecialDatesCalendarSpec,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
private val reminderScanner: ReminderScanner,
|
||||
private val reminderChannels: ReminderChannels,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
) : ViewModel() {
|
||||
@@ -88,16 +74,16 @@ class SettingsViewModel @Inject constructor(
|
||||
private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
/**
|
||||
* Calendars that are switched on — the only ones that plan reminders at
|
||||
* all (#75), so the only ones with notification settings.
|
||||
* 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).
|
||||
*/
|
||||
private val visibleCalendars: Flow<List<CalendarSource>> =
|
||||
combine(repository.calendars(), calendarPrefs.pendingDisabledCalendarIds) { calendars, pending ->
|
||||
calendars.filter { it.isVisibleInSystem && it.id !in pending }
|
||||
}.catch { emit(emptyList()) }
|
||||
private val writableCalendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } }
|
||||
.catch { emit(emptyList()) }
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable),
|
||||
@@ -139,10 +125,7 @@ class SettingsViewModel @Inject constructor(
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
writableCalendars = calendars.filter { it.canModifyContents },
|
||||
reminderCalendars = calendars,
|
||||
mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds],
|
||||
notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed],
|
||||
writableCalendars = calendars,
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
@@ -374,130 +357,6 @@ class SettingsViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans, since a muted calendar armed no wake-up for its next reminder.
|
||||
* Unmuting scans once more before the write, so the watermark starts at the
|
||||
* unmute and nothing that came due while muted is replayed.
|
||||
*/
|
||||
fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
if (enabled) reminderScanner.scan()
|
||||
prefs.setCalendarRemindersEnabled(calendarId, enabled)
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
private val _channelStatus = MutableStateFlow(ReminderChannelStatus())
|
||||
|
||||
/** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */
|
||||
val channelStatus: StateFlow<ReminderChannelStatus> = _channelStatus.asStateFlow()
|
||||
|
||||
private var channelStatusJob: Job? = null
|
||||
|
||||
private val _channelSounds = MutableStateFlow<Map<Long, ReminderSound>?>(null)
|
||||
|
||||
/** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */
|
||||
val channelSounds: StateFlow<Map<Long, ReminderSound>?> = _channelSounds.asStateFlow()
|
||||
|
||||
private val _soundFailed = Channel<SoundFailure>(Channel.CONFLATED)
|
||||
|
||||
/** Emits when a picked sound couldn't be applied; kept until the screen collects it. */
|
||||
val soundFailed: Flow<SoundFailure> = _soundFailed.receiveAsFlow()
|
||||
|
||||
private val soundTitles = mutableMapOf<Uri, String?>()
|
||||
|
||||
fun refreshChannelStatus(calendarIds: Collection<Long>) {
|
||||
channelStatusJob?.cancel()
|
||||
channelStatusJob = viewModelScope.launch {
|
||||
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
|
||||
val sounds = onChannels { sounds(calendarIds) } ?: return@launch
|
||||
_channelSounds.value = withContext(io) {
|
||||
sounds.mapValues { (_, uri) ->
|
||||
ReminderSound(uri, uri?.let(::soundTitle))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sound's title, cached unless it is a "default" alias whose target can change. */
|
||||
private fun soundTitle(uri: Uri): String? {
|
||||
if (uri.authority == Settings.AUTHORITY) return appContext.ringtoneTitle(uri)
|
||||
return synchronized(soundTitles) { soundTitles.getOrPut(uri) { appContext.ringtoneTitle(uri) } }
|
||||
}
|
||||
|
||||
/** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */
|
||||
fun setReminderSound(calendarId: Long, sound: Uri?) = applySound(sound) {
|
||||
setSound(listOf(calendarId), sound, createMissing = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Give every switched-on calendar's reminders [sound]. Reads the calendars
|
||||
* itself, so a pick returning after process death still finds them; those
|
||||
* that only get a channel when something posts are left alone.
|
||||
*/
|
||||
fun setReminderSoundForAll(sound: Uri?) = applySound(sound) {
|
||||
try {
|
||||
sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e)
|
||||
}
|
||||
val ids = visibleCalendars.first().map { it.id }
|
||||
ids.isNotEmpty() && setSound(ids, sound, createMissing = false)
|
||||
}
|
||||
|
||||
private fun canRead(uri: Uri): Boolean = uri.authority == Settings.AUTHORITY ||
|
||||
runCatching { appContext.contentResolver.openAssetFileDescriptor(uri, "r")?.close() != null }.getOrDefault(false)
|
||||
|
||||
/** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */
|
||||
private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) {
|
||||
viewModelScope.launch {
|
||||
val failure = withContext(io + NonCancellable) {
|
||||
try {
|
||||
// The system plays the sound but checks that Calendula could read it.
|
||||
when {
|
||||
sound != null && !canRead(sound) -> SoundFailure.Unreadable
|
||||
reminderChannels.block() -> null
|
||||
else -> SoundFailure.NotApplied
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Could not set the reminder sound", e)
|
||||
SoundFailure.NotApplied
|
||||
}
|
||||
}
|
||||
failure?.let(_soundFailed::trySend)
|
||||
refreshChannelStatus(visibleCalendars.first().map { it.id })
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() }
|
||||
|
||||
/**
|
||||
* The channel whose system screen to open for [calendarId] (#340), created
|
||||
* if needed; null when only the app's own screen can help — the app or the
|
||||
* calendar's account group is blocked there, or the channel couldn't be made.
|
||||
*/
|
||||
suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels {
|
||||
val channelId = channelFor(calendarId) ?: return@onChannels null
|
||||
val status = status(listOf(calendarId))
|
||||
channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds }
|
||||
}
|
||||
|
||||
/** Create the per-calendar channels before showing the app's channel list, even with reminders off. */
|
||||
suspend fun syncReminderChannels() {
|
||||
onChannels { sync() }
|
||||
}
|
||||
|
||||
private suspend fun <T> onChannels(block: ReminderChannels.() -> T): T? = withContext(io) {
|
||||
try {
|
||||
reminderChannels.block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Reminder channel update failed", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
|
||||
|
||||
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
|
||||
|
||||
@@ -395,6 +395,23 @@
|
||||
|
||||
<!-- 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>
|
||||
@@ -731,27 +748,7 @@
|
||||
<string name="reminder_custom_amount">Amount</string>
|
||||
<string name="reminder_custom_set">Set</string>
|
||||
<string name="settings_calendar_reminders_title">Per-calendar reminders</string>
|
||||
<string name="settings_calendar_reminders_subtitle">Notifications, sound and default reminders per calendar</string>
|
||||
<string name="settings_calendar_reminders_hint">Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit.</string>
|
||||
<string name="settings_calendar_notifications">Notifications</string>
|
||||
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
|
||||
<string name="settings_calendar_notifications_off">Notifications off</string>
|
||||
<string name="settings_notification_sound">Notification sound</string>
|
||||
<string name="settings_notification_sound_silent">Silent</string>
|
||||
<string name="settings_notification_sound_default">Default</string>
|
||||
<!-- %1$s is the name of the device's default notification sound. -->
|
||||
<string name="settings_notification_sound_default_named">Default (%1$s)</string>
|
||||
<string name="settings_notification_sound_custom">Custom sound</string>
|
||||
<string name="settings_notification_sound_failed">Couldn\'t change the notification sound</string>
|
||||
<string name="settings_notification_sound_unreadable">Calendula can\'t play this sound. Pick another one.</string>
|
||||
<string name="settings_notification_sound_mixed">Differs per calendar</string>
|
||||
<string name="settings_notification_more">More notification settings</string>
|
||||
<string name="settings_notification_sound_hint">Vibration, pop-ups and more for each calendar, in system settings</string>
|
||||
<string name="settings_notifications_blocked">Blocked in system settings</string>
|
||||
<string name="settings_notifications_blocked_hint">Blocked in system settings — tap to allow</string>
|
||||
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
|
||||
<string name="settings_notification_category_hint_open">Open settings</string>
|
||||
<string name="settings_calendar_notification_sound_hint">Vibration, pop-ups and more for this calendar, in system settings</string>
|
||||
<string name="settings_calendar_reminders_hint">Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own.</string>
|
||||
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
|
||||
<string name="settings_reliable_delivery">Reliable delivery</string>
|
||||
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
|
||||
|
||||
@@ -5,12 +5,17 @@ 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
|
||||
@@ -43,7 +48,58 @@ fun testRepository(
|
||||
io: CoroutineDispatcher,
|
||||
prefs: CalendarPrefs = testPrefs(dir),
|
||||
settings: SettingsPrefs = testSettings(dir),
|
||||
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io)
|
||||
syncRequester: SyncRequester = RecordingSyncRequester(),
|
||||
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester)
|
||||
|
||||
/**
|
||||
* Records every sync request; [accepts] false models the system refusing 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
|
||||
}
|
||||
|
||||
/** Installs [dispatcher] as `Dispatchers.Main` around each test. */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
|
||||
@@ -64,14 +64,27 @@ 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> =
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
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,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs
|
||||
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.testDataStore
|
||||
import de.jeanlucmakiola.calendula.testPrefs
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -108,4 +109,18 @@ class CalendarPrefsTest {
|
||||
prefs.setVisibilityNoticePending(false)
|
||||
assertThat(prefs.visibilityNoticePending.first()).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest {
|
||||
val prefs = testPrefs(tempDir)
|
||||
val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid")
|
||||
val google = SyncAccount("me@dav.example/cal, 1", "com.google")
|
||||
|
||||
prefs.setSyncAccessDismissed(dav, dismissed = true)
|
||||
prefs.setSyncAccessDismissed(google, dismissed = true)
|
||||
assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google)
|
||||
|
||||
prefs.setSyncAccessDismissed(dav, dismissed = false)
|
||||
assertThat(prefs.syncAccessDismissed.first()).containsExactly(google)
|
||||
}
|
||||
}
|
||||
@@ -601,30 +601,6 @@ class SettingsPrefsTest {
|
||||
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calendar notifications default on and toggle per calendar`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty()
|
||||
prefs.setCalendarRemindersEnabled(7L, false)
|
||||
prefs.setCalendarRemindersEnabled(9L, false)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L)
|
||||
prefs.setCalendarRemindersEnabled(7L, true)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reminder channel versions only grow`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.reminderChannelVersions.first()).isEmpty()
|
||||
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1))).containsExactly(7L, 1)
|
||||
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1, 9L to 5))).containsExactly(7L, 2, 9L, 5)
|
||||
assertThat(prefs.reminderChannelVersions.first()).containsExactly(7L, 2, 9L, 5)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `garbage per-calendar duration entries are dropped, the rest survive`(
|
||||
@TempDir tempDir: Path,
|
||||
|
||||
-200
@@ -1,200 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ReminderChannelPlanTest {
|
||||
|
||||
private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource(
|
||||
id = id,
|
||||
displayName = "Cal $id",
|
||||
accountName = account,
|
||||
accountType = type,
|
||||
color = 0,
|
||||
isVisibleInSystem = true,
|
||||
isLocal = local,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `one channel per calendar, grouped by account`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "com.google"),
|
||||
calendar(3, "dav", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(2)
|
||||
assertThat(plan.channels.map { it.id })
|
||||
.containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3))
|
||||
assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId)
|
||||
assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId)
|
||||
assertThat(plan.staleChannelIds).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `device calendars share one group`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "Calendula", "LOCAL", local = true),
|
||||
calendar(2, "Other", "LOCAL", local = true),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(1)
|
||||
assertThat(plan.groups.single().isLocal).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `same account name under two types is ambiguous`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "bitfire.at.davdroid"),
|
||||
calendar(3, "work", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType })
|
||||
.containsExactly("com.google", "bitfire.at.davdroid")
|
||||
assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale reminder channels and groups go, foreign ones stay`() {
|
||||
val current = calendar(1, "me@example.org", "com.google")
|
||||
fun plan(calendars: List<CalendarSource>, existing: List<String> = emptyList(), groups: List<String> = emptyList()) =
|
||||
planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC)
|
||||
val keptGroup = plan(listOf(current)).groups.single().id
|
||||
val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id
|
||||
val result = plan(
|
||||
calendars = listOf(current),
|
||||
existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"),
|
||||
groups = listOf(keptGroup, goneGroup, "other"),
|
||||
)
|
||||
assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9))
|
||||
assertThat(result.staleGroupIds).containsExactly(goneGroup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only missing or renamed channels are written`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "a", "com.google"),
|
||||
calendar(2, "a", "com.google"),
|
||||
calendar(3, "a", "com.google").copy(displayName = ""),
|
||||
calendar(4, "a", "com.google"),
|
||||
),
|
||||
existing = listOf(
|
||||
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
|
||||
ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"),
|
||||
ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"),
|
||||
),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L)
|
||||
assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non-syncing calendars keep a channel but get none up front`() {
|
||||
val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false)
|
||||
val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC)
|
||||
assertThat(fresh.channelsToWrite).isEmpty()
|
||||
assertThat(fresh.groupsInUse).isEmpty()
|
||||
val posted = planReminderChannels(
|
||||
calendars = listOf(quiet),
|
||||
existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(posted.staleChannelIds).isEmpty()
|
||||
assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L)
|
||||
assertThat(posted.groupsInUse).hasSize(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blocked calendars follow app, channel and group`() {
|
||||
val channels = mapOf(
|
||||
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"),
|
||||
reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"),
|
||||
reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"),
|
||||
)
|
||||
val ids = listOf(1L, 2L, 3L, 4L)
|
||||
val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))
|
||||
assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L)
|
||||
assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L)
|
||||
assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds)
|
||||
.containsExactly(1L)
|
||||
val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet())
|
||||
assertThat(appOff.appBlocked).isTrue()
|
||||
assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `channel ids round-trip with versions`() {
|
||||
assertThat(parseReminderChannelId(reminderChannelId(7))).isEqualTo(7L to 0)
|
||||
assertThat(parseReminderChannelId(reminderChannelId(7, 3))).isEqualTo(7L to 3)
|
||||
assertThat(parseReminderChannelId("reminders.calendar.7.v0")).isNull()
|
||||
assertThat(parseReminderChannelId("reminders.calendar.x")).isNull()
|
||||
assertThat(parseReminderChannelId(LEGACY_REMINDER_CHANNEL_ID)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a version bump retires the old channel unless it is showing`() {
|
||||
val existing = listOf(
|
||||
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
|
||||
ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, "g"),
|
||||
)
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(calendar(1, "a", "com.google"), calendar(2, "a", "com.google")),
|
||||
existing = existing,
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
versions = mapOf(1L to 2, 2L to 1),
|
||||
showingChannelIds = setOf(reminderChannelId(2)),
|
||||
)
|
||||
assertThat(plan.channels.map { it.id }).containsExactly(reminderChannelId(1, 2), reminderChannelId(2, 1))
|
||||
assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(1))
|
||||
assertThat(plan.keptChannelIds).containsExactly(reminderChannelId(2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the current version is the highest that exists, else the high-water mark`() {
|
||||
val versions = currentReminderChannelVersions(
|
||||
existingChannelIds = listOf(reminderChannelId(1), reminderChannelId(1, 2), reminderChannelId(3), "backup"),
|
||||
highWater = mapOf(1L to 5, 2L to 4),
|
||||
)
|
||||
// Calendar 1 reserved v5 but never wrote it, so v2 stays current.
|
||||
assertThat(versions).containsExactly(1L, 2, 2L, 4, 3L, 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `status reads the current channel version`() {
|
||||
val channels = mapOf(
|
||||
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = null),
|
||||
reminderChannelId(1, 2) to ReminderChannelState(blocked = false, groupId = null),
|
||||
)
|
||||
val status = reminderChannelStatus(listOf(1L), true, channels, emptySet(), versions = mapOf(1L to 2))
|
||||
assertThat(status.blockedCalendarIds).isEmpty()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DESC = "Reminders"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
+26
-30
@@ -10,6 +10,32 @@ 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.
|
||||
@@ -391,36 +417,6 @@ gate also covers a snooze re-shown from our own alarm after its calendar was
|
||||
switched off. The drawer's filter sheet (`CalendarPrefs.hiddenCalendarIds`) is a
|
||||
separate in-app declutter that never touches reminders.
|
||||
|
||||
**A channel per calendar (#145).** `ReminderChannels` keeps one notification
|
||||
channel per calendar, grouped by account (one that syncs no events only gets
|
||||
its channel once something posts on it), so a calendar can be
|
||||
muted or given its own sound in the system settings before it ever fires. Every
|
||||
scan with reminders on syncs them (skipped when nothing changed): missing
|
||||
channels are created, renamed ones updated, and channels of deleted calendars
|
||||
removed — but never on an empty snapshot, which is a provider hiccup more often
|
||||
than every calendar gone. Switched-off calendars keep theirs, so toggling one
|
||||
never cancels a showing reminder or loses its settings. `post` creates a missing
|
||||
channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and
|
||||
importance of the pre-#145 single `reminders` channel, which is deleted once
|
||||
nothing showing still sits on it. Settings → Notifications deep-links into the
|
||||
system's channel screens for everything but the sound (#340). A sound picked in
|
||||
the app (#518) can't be set on an existing channel, so
|
||||
`ReminderChannels.setSound` recreates it under a new version
|
||||
(`reminders.calendar.<id>.v<n>`), copying everything else from the old one. The
|
||||
current version is simply the highest channel that exists, so the new one only
|
||||
takes over once written; `SettingsPrefs.reminderChannelVersions` is just a
|
||||
high-water mark that keeps ids from being reused (a re-used id would bring back
|
||||
the deleted channel's settings). `setSound` leaves the old version to the sync,
|
||||
which treats older versions as stale and keeps one while a notification still
|
||||
shows on it; `ReminderNotifier.post` resolves and posts under the channel lock
|
||||
(`withChannel`), so a pick never moves a channel mid-post.
|
||||
Separate from the channels, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar
|
||||
off switch (#272): the scan plans nothing for those calendars (so they arm no
|
||||
wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again
|
||||
for snoozes. The settings screen re-reads `ReminderChannels.status` on every
|
||||
resume and marks a calendar "Blocked in system settings" when the app, its
|
||||
channel or its account group is switched off there.
|
||||
|
||||
Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast.
|
||||
Keeping both would double-post wherever the provider works, and Etar's way out —
|
||||
a latch that disables its own scheduling once a real broadcast arrives — cannot
|
||||
|
||||
@@ -96,6 +96,7 @@ The settings screen contains links to the source code, the licence, the issue tr
|
||||
- `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing.
|
||||
- `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart.
|
||||
- `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting.
|
||||
- `READ_SYNC_STATS`: only to see whether a sync asked for with “Sync now” is still pending or running, so the menu can say when it has finished. It reveals nothing about your data.
|
||||
- `WAKE_LOCK`, `FOREGROUND_SERVICE`, `ACCESS_NETWORK_STATE`: required by the Android system component used for scheduled background work (WorkManager).
|
||||
|
||||
`ACCESS_NETWORK_STATE` allows reading *whether* a network connection exists. It does **not** permit using one. Without `INTERNET`, no connection is possible.
|
||||
|
||||
+1
-1
Submodule floret-kit updated: 31aa7e1fc6...a039ab5bd4.
Reference in new issue
Block a user