Compare commits

..
Author SHA1 Message Date
makiolaj 95c40c9d88 fix(#517): review round 2 - back off failed pref reads, one derivation for the drawer's hidden-in-view set 2026-11-14 12:09:19 +01:00
makiolaj 8df21b965a fix(#517): review round 1 - keep reading after a failed pref read, drawer count and notes agree, entry row not 'selected' 2026-11-14 12:00:29 +01:00
makiolaj 1aa66ffc99 feat(#517): move the per-view hide entry from the top bar into the drawer 2026-11-14 11:52:48 +01:00
makiolaj d5b51f2c01 fix(#517): review round 3 - close picker in each request handler, keep hidden set alive across page swaps 2026-11-14 03:41:14 +01:00
makiolaj dda0164c9f fix(#517): review round 2 - close picker for every external request, clearer title, provider write first 2026-11-14 03:31:43 +01:00
makiolaj bbcb8e00ed fix(#517): review round 1 - close picker on external navigation, proper load/failure states, wait for stored hidden views 2026-11-14 03:22:35 +01:00
makiolaj d943937b3a feat(#517): quick per-view calendar toggle in the top bar 2026-11-14 03:14:47 +01:00
makiolaj dad1f2cd9c fix(#270): review round 3 - one write per editor save, best-effort pref tidy-up 2026-11-13 19:11:33 +01:00
makiolaj db8d649467 fix(#270): review round 2 - safe pref reads, diff-only editor saves, optimistic picker 2026-11-13 19:04:25 +01:00
makiolaj 91fdaba6a2 fix(#270): review round 1 - atomic toggles, no stale editor write, shared per-view filter 2026-11-13 18:54:10 +01:00
makiolaj e3e9865d3f feat(#270): hide calendars in chosen views 2026-11-13 18:45:17 +01:00
40 changed files with 752 additions and 1315 deletions

No files matched your search

@@ -37,7 +37,6 @@ class CalendarRepositorySmokeTest {
CalendarPrefs(store),
SettingsPrefs(store),
Dispatchers.IO,
AndroidSyncRequester(context),
)
}
-4
View File
@@ -56,10 +56,6 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent>
<!-- Sync adapters to ask for a calendar sync (#240, #303). -->
<intent>
<action android:name="android.content.SyncAdapter" />
</intent>
</queries>
<application
@@ -301,12 +301,6 @@ interface CalendarDataSource {
*/
fun deleteOccurrence(eventId: Long, beginMillis: Long)
/** The account [calendarId] belongs to; null when the row is gone or unreadable. */
fun calendarAccount(calendarId: Long): SyncAccount?
/** The calendar event [eventId] lives in; null when the row is gone or unreadable. */
fun eventCalendarId(eventId: Long): Long?
fun registerChangeListener(listener: () -> Unit)
fun unregisterChangeListener(listener: () -> Unit)
}
@@ -887,7 +881,8 @@ class AndroidCalendarDataSource @Inject constructor(
return eventId
}
override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query(
/** The account a calendar belongs to, for scoping a `Colors` lookup. */
private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query(
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
arrayOf(
CalendarContract.Calendars.ACCOUNT_NAME,
@@ -896,17 +891,13 @@ class AndroidCalendarDataSource @Inject constructor(
null, null, null,
)?.use { c ->
if (c.moveToFirst()) {
SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
} else {
null
}
}
override fun eventCalendarId(eventId: Long): Long? = resolver.query(
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
arrayOf(CalendarContract.Events.CALENDAR_ID),
null, null, null,
)?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null }
private data class CalendarAccount(val name: String, val type: String)
/**
* The raw provider `MINUTES` to store for one of [form]'s reminders: an
@@ -11,7 +11,6 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flowOf
import kotlin.time.Instant
interface CalendarRepository {
@@ -135,28 +134,6 @@ interface CalendarRepository {
/** Delete a recurring event from the occurrence at [beginMillis] onwards. */
suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long)
/**
* Ask every account behind a visible synced calendar to sync now (#240).
* Only a request: the adapter may still run it late, or fail.
*/
suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync
/**
* 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) :
@@ -18,8 +18,6 @@ import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
@@ -49,7 +47,6 @@ class CalendarRepositoryImpl @Inject constructor(
private val prefs: CalendarPrefs,
private val settingsPrefs: SettingsPrefs,
@IoDispatcher private val io: CoroutineDispatcher,
private val syncRequester: SyncRequester,
) : CalendarRepository {
/** The configured wall-clock fire time for all-day reminders, read per write. */
@@ -87,159 +84,13 @@ class CalendarRepositoryImpl @Inject constructor(
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
override val providerChanges: Flow<Unit> get() = ticks
/**
* Run a provider write on [io], then re-query whether or not it threw. The
* accounts behind [syncCalendars] (read before the write, which may delete
* the row) then get one sync nudge each (#303), also after a failure, which
* may have landed part of a multi-row write. Once per write, so a multi-row
* save or a whole import asks once per account.
*/
private suspend fun <T> write(
syncCalendars: suspend () -> Collection<Long?>,
block: suspend () -> T,
): T = withContext(io) {
val accounts = syncAccountsOf(syncCalendars)
/** Run a provider write on [io], then re-query whether or not it threw. */
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
try {
block()
} finally {
refresh()
writes.tryEmit(Unit)
requestSyncs(accounts, userInitiated = false)
}
}
private val noSync: suspend () -> Collection<Long?> = { emptyList() }
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
try {
calendarIds().filterNotNull().distinct()
.mapNotNull { accountOf(it) }
.withAdapter()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "No sync nudge: the calendar account could not be read", e)
emptySet()
}
/** From the shared per-tick read; a calendar newer than it is read on its own. */
private suspend fun accountOf(calendarId: Long): SyncAccount? =
calendarsSnapshot().firstOrNull { it.id == calendarId }
?.let { SyncAccount(it.accountName, it.accountType) }
?: dataSource.calendarAccount(calendarId)
/** The syncable accounts among these whose type has a calendar sync adapter. */
private fun Collection<SyncAccount>.withAdapter(): Set<SyncAccount> {
val candidates = filter { it.isSyncable }
if (candidates.isEmpty()) return emptySet()
val adapterTypes = try {
syncRequester.adapterAccountTypes()
} catch (e: Exception) {
Log.w(TAG, "Sync adapters unreadable", e)
return emptySet()
}
return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes }
}
/**
* Splits [accounts] by whether a request may name them (see
* [SyncRequester.addressableAccounts]). The rest wait for the user's grant:
* an account-less request would reach them, but also every other calendar
* account on the device, so none is sent.
*/
private fun reach(accounts: Set<SyncAccount>): SyncTargets {
if (accounts.isEmpty()) return SyncTargets.None
// Unreadable access counts as reachable: a grant can't fix a failing read.
val addressable = try {
syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type })
} catch (e: Exception) {
Log.w(TAG, "Account visibility unreadable", e)
null
}
if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet())
val (reachable, hidden) = accounts.partition { it in addressable }
return SyncTargets(reachable.toSet(), hidden.toSet())
}
/** Ask each reachable one of [accounts] once. */
private fun requestSyncs(accounts: Set<SyncAccount>, userInitiated: Boolean) {
reach(accounts).reachable.forEach { requestSync(it, userInitiated) }
}
private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
syncRequester.requestSync(account, userInitiated)
true
} catch (e: Exception) {
Log.w(TAG, "Sync request refused", e)
false
}
/** The event's own calendar (from [original] when given, else read), plus [others]. */
private fun eventCalendar(
eventId: Long,
original: EventForm? = null,
vararg others: Long?,
): suspend () -> Collection<Long?> =
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): SyncTargets =
reach(
calendars.syncAccounts().withAdapter()
.sortedWith(compareBy({ it.name.lowercase() }, { it.type }))
.toSet(),
).let {
if (dismissed.isEmpty()) {
it
} else {
it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed)
}
}
private val accessChecks = MutableStateFlow(0)
override val syncTargets: Flow<SyncTargets>
get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ ->
targetsOf(calendars, dismissed)
}.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(): SyncRequestResult = withContext(io) {
val targets = try {
targetsOf(calendars().first(), prefs.syncAccessDismissed.first())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "Sync request skipped: calendars unreadable", e)
return@withContext SyncRequestResult.Failed
}
if (targets.reachable.isEmpty()) {
return@withContext if (targets.needsAccess.isEmpty()) {
SyncRequestResult.NothingToSync
} else {
SyncRequestResult.NeedsAccess
}
}
val sent = targets.reachable.count { requestSync(it, userInitiated = true) }
when {
sent == 0 -> SyncRequestResult.Failed
sent < targets.reachable.size -> SyncRequestResult.PartlyFailed
targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess
else -> SyncRequestResult.Requested
}
}
@@ -367,7 +218,7 @@ class CalendarRepositoryImpl @Inject constructor(
displayName: String,
color: Int,
description: String?,
): Long = write(noSync) {
): Long = write {
dataSource.createLocalCalendar(displayName, color, description)
}
@@ -376,14 +227,13 @@ class CalendarRepositoryImpl @Inject constructor(
displayName: String,
color: Int,
description: String?,
) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) }
) = write { dataSource.updateCalendar(id, displayName, color, description) }
override suspend fun deleteCalendar(id: Long) =
write(noSync) { dataSource.deleteCalendar(id) }
write { dataSource.deleteCalendar(id) }
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
// VISIBLE is device-local: nothing for an adapter to upload.
write(noSync) {
write {
val canWrite = dataSource.canWriteCalendars()
if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) }
// Nothing of ours is left waiting for the provider once the write
@@ -403,7 +253,7 @@ class CalendarRepositoryImpl @Inject constructor(
override suspend fun importEvents(
targetCalendarId: Long,
events: List<ParsedIcsEvent>,
): IcsImportSummary = write({ listOf(targetCalendarId) }) {
): IcsImportSummary = write {
val existing = dataSource.existingUids(targetCalendarId)
// Both are per-calendar, not per-event: looking them up once keeps a
// thousand-event restore to two extra queries. The palette is the
@@ -454,7 +304,7 @@ class CalendarRepositoryImpl @Inject constructor(
)
}
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
override suspend fun createEvent(form: EventForm): Long = write {
dataSource.insertEvent(form, allDayReminderTimeMinutes())
}
@@ -462,11 +312,11 @@ class CalendarRepositoryImpl @Inject constructor(
eventId: Long,
original: EventForm,
updated: EventForm,
) = write(eventCalendar(eventId, original, updated.calendarId)) {
) = write {
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
}
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
override suspend fun deleteEvent(eventId: Long) = write {
dataSource.deleteEvent(eventId)
}
@@ -475,7 +325,7 @@ class CalendarRepositoryImpl @Inject constructor(
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
): Long = write {
dataSource.moveEvent(
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
)
@@ -486,7 +336,7 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis: Long,
original: EventForm,
form: EventForm,
): Long = write(eventCalendar(eventId, original)) {
): Long = write {
dataSource.updateOccurrence(
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
)
@@ -497,7 +347,7 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis: Long,
original: EventForm,
updated: EventForm,
): Long = write(eventCalendar(eventId, original)) {
): Long = write {
dataSource.updateEventFromOccurrence(
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
)
@@ -507,14 +357,14 @@ class CalendarRepositoryImpl @Inject constructor(
override val seriesSplits: Flow<SeriesSplit> = splits
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) {
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
dataSource.deleteOccurrence(eventId, beginMillis)
}
override suspend fun deleteEventFromOccurrence(
eventId: Long,
beginMillis: Long,
) = write(eventCalendar(eventId)) {
) = write {
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
}
@@ -1,112 +0,0 @@
package de.jeanlucmakiola.calendula.data.calendar
import android.accounts.Account
import android.accounts.AccountManager
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.CalendarContract
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.CalendarSource
import 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)
}
@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,
)
}
}
/** 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). */
enum class SyncRequestResult { Requested, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed }
@@ -11,11 +11,9 @@ import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource
import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
@@ -51,12 +49,6 @@ abstract class DataBindModule {
impl: CalendarRepositoryImpl,
): CalendarRepository
@Binds
@Singleton
abstract fun bindSyncRequester(
impl: AndroidSyncRequester,
): SyncRequester
@Binds
@Singleton
abstract fun bindReminderInstanceSource(
@@ -7,8 +7,6 @@ import de.jeanlucmakiola.floret.prefs.PrefStore
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
import de.jeanlucmakiola.floret.prefs.nullableLongPref
import de.jeanlucmakiola.floret.prefs.nullableStringPref
import de.jeanlucmakiola.floret.prefs.stringSetPref
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
@@ -74,28 +72,7 @@ class CalendarPrefs @Inject constructor(
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id)
/**
* Synced accounts the user chose never to be asked to grant sync-request
* access for (#240): no grant row, no "other accounts" receipt.
*/
val syncAccessDismissed: Flow<Set<SyncAccount>> = prefs.flow(SYNC_ACCESS_DISMISSED)
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
prefs.update(SYNC_ACCESS_DISMISSED) { if (dismissed) it + account else it - account }
}
private companion object {
val SYNC_ACCESS_DISMISSED = stringSetPref("sync_access_dismissed").map<Set<SyncAccount>>(
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
)
const val FIELD_SEPARATOR = '\u001F'
fun String.toSyncAccount(): SyncAccount? {
val split = indexOf(FIELD_SEPARATOR)
return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split))
}
val HIDDEN_IDS = idSetPref("hidden_calendar_ids")
val DISABLED_IDS = idSetPref("disabled_calendar_ids")
val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending")
@@ -165,6 +165,7 @@ class SettingsPrefs @Inject constructor(
val autofocusEventTitle: Flow<Boolean> = prefs.flow(SettingsKeys.autofocusEventTitle)
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
val perCalendarHiddenViews: Flow<Map<Long, Set<CalendarView>>> = prefs.flow(SettingsKeys.perCalendarHiddenViews)
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
@@ -271,6 +272,25 @@ class SettingsPrefs @Inject constructor(
}
}
/** Show [calendarId] in every view again (#270), e.g. once it is deleted. */
suspend fun clearCalendarHiddenViews(calendarId: Long) {
prefs.update(SettingsKeys.perCalendarHiddenViews) { current -> current - calendarId }
}
/** Hide or show [calendarId] in one [view], against the stored set rather than a snapshot of it. */
suspend fun setCalendarHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) =
applyCalendarHiddenChanges(calendarId, mapOf(view to hidden))
/** Hide (true) or show (false) [calendarId] in each view of [changes], in one write; other views keep theirs. */
suspend fun applyCalendarHiddenChanges(calendarId: Long, changes: Map<CalendarView, Boolean>) {
if (changes.isEmpty()) return
prefs.update(SettingsKeys.perCalendarHiddenViews) { current ->
val views = current[calendarId].orEmpty()
val next = views + changes.filterValues { it }.keys - changes.filterValues { !it }.keys
current.withHiddenViews(calendarId, next)
}
}
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) =
@@ -588,6 +608,15 @@ object SettingsKeys {
val perCalendarEventDuration: Pref<Map<Long, Int>> =
nullableStringPref("per_calendar_event_duration").map(::parseDurationOverrides) { it.toStoredDurations() }
/**
* Views each calendar is hidden in (#270): a display-only filter on top of
* `Calendars.VISIBLE` and the drawer's filter, so reminders and search never
* see it. A calendar absent shows in every view. Serialised as
* `id=Month,Agenda;id=Week`.
*/
val perCalendarHiddenViews: Pref<Map<Long, Set<CalendarView>>> =
nullableStringPref("per_calendar_hidden_views").map(::parseHiddenViews) { it.toStoredHiddenViews() }
/**
* Whether Calendula posts reminder notifications (v1.4). On by default — for
* users whose only calendar app this is, reminders are essential.
@@ -817,9 +846,11 @@ private fun parseFormFields(stored: String?): Set<EventFormField> = when (stored
private fun parseViewOrder(stored: String?): List<CalendarView> =
completeViewOrder(
stored?.split(',').orEmpty()
.mapNotNull { name -> CalendarView.entries.firstOrNull { it.name == name.trim() } },
.mapNotNull { it.trim().toCalendarViewOrNull() },
)
private fun String.toCalendarViewOrNull(): CalendarView? = CalendarView.entries.firstOrNull { it.name == this }
/** Parse the quick-switch config; "!"-prefixed names are disabled. */
private fun parseQuickSwitch(stored: String?): QuickSwitchConfig {
if (stored == null) return QuickSwitchConfig.Default
@@ -827,7 +858,7 @@ private fun parseQuickSwitch(stored: String?): QuickSwitchConfig {
val token = raw.trim()
val disabled = token.startsWith("!")
val name = if (disabled) token.drop(1) else token
CalendarView.entries.firstOrNull { it.name == name }?.let { it to disabled }
name.toCalendarViewOrNull()?.let { it to disabled }
}
val order = completeViewOrder(parsed.map { it.first })
// Only views explicitly stored disabled are excluded; anything appended
@@ -977,6 +1008,33 @@ private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
calendarId to minutes
}.toMap()
/**
* Parse the per-calendar hidden-views map (`id=View,View` entries joined by `;`).
* Unknown view names and malformed entries are dropped; an entry left with no
* views is dropped with them.
*/
internal fun parseHiddenViews(stored: String?): Map<Long, Set<CalendarView>> =
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 views = parts[1].split(LIST_SEP)
.mapNotNullTo(mutableSetOf()) { it.trim().toCalendarViewOrNull() }
if (views.isEmpty()) null else calendarId to views
}.toMap()
private fun Map<Long, Set<CalendarView>>.withHiddenViews(
calendarId: Long,
views: Set<CalendarView>,
): Map<Long, Set<CalendarView>> = if (views.isEmpty()) this - calendarId else this + (calendarId to views)
internal fun Map<Long, Set<CalendarView>>.toStoredHiddenViews(): String? =
entries.filter { it.value.isNotEmpty() }.sortedBy { it.key }
.joinToString(ENTRY_SEP) { (id, views) ->
"$id$KEY_VALUE_SEP" + views.sortedBy { it.ordinal }.joinToString(LIST_SEP) { it.name }
}
.ifEmpty { null }
private fun Map<Long, Int>.toStoredDurations(): String =
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
"$id$KEY_VALUE_SEP$minutes"
@@ -309,3 +309,7 @@ enum class FailureReason {
EventNotFound,
Unknown,
}
/** [this] without the events of [hidden] calendars. */
fun List<EventInstance>.withoutCalendars(hidden: Set<Long>): List<EventInstance> =
if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden }
@@ -35,7 +35,6 @@ import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import de.jeanlucmakiola.calendula.ui.common.rememberHeld
import de.jeanlucmakiola.calendula.ui.common.screen
import de.jeanlucmakiola.calendula.ui.common.ViewScreen
@@ -53,13 +52,6 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen
import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip
import de.jeanlucmakiola.calendula.ui.common.StayingPut
import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer
import de.jeanlucmakiola.calendula.ui.common.DrawerSync
import de.jeanlucmakiola.calendula.ui.common.SyncViewModel
import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen
import de.jeanlucmakiola.calendula.ui.common.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
@@ -105,6 +97,8 @@ import de.jeanlucmakiola.calendula.ui.month.MonthScreen
import de.jeanlucmakiola.calendula.ui.search.SearchScreen
import de.jeanlucmakiola.calendula.ui.settings.SettingsScreen
import de.jeanlucmakiola.calendula.ui.week.TimelineScreen
import de.jeanlucmakiola.calendula.ui.filter.FilterViewModel
import de.jeanlucmakiola.calendula.ui.filter.ViewCalendarsPicker
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.launch
@@ -200,10 +194,15 @@ fun CalendarHost(
var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() }
// The drawer's "Hide in this view" picker (#517). It is its own window over
// everything here, so each external request below closes it first.
var showViewCalendars by rememberSaveable { mutableStateOf(false) }
// A tapped reminder notification asks for a specific occurrence.
val requestedDetailKey = requests.detailKey
LaunchedEffect(requestedDetailKey) {
if (requestedDetailKey != null) {
showViewCalendars = false
detailKey = requestedDetailKey
requests.detailKey = null
}
@@ -219,6 +218,7 @@ fun CalendarHost(
// top bar. Sits below the detail/edit overlays so tapping a result reveals
// the detail on top and backing out returns to the results.
var showSearch by rememberSaveable { mutableStateOf(false) }
val filterViewModel: FilterViewModel = hiltViewModel()
val onOpenSearch = { showSearch = true }
// Calendar manager (reached from Settings) — its own overlay so it slides
@@ -324,6 +324,7 @@ fun CalendarHost(
requests.importUri = null
return@LaunchedEffect
}
showViewCalendars = false
importUri = requestedImportUri
importForceMany = false
importSession++
@@ -341,6 +342,7 @@ fun CalendarHost(
requests.insert = null
return@LaunchedEffect
}
showViewCalendars = false
if (importForm == null) {
openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true)
} else {
@@ -357,6 +359,7 @@ fun CalendarHost(
fun dismissCoveringOverlays(keepCreate: Boolean = false) {
showSettings = false
showSearch = false
showViewCalendars = false
showCalendars = false
showBackup = false
detailKey = null
@@ -449,16 +452,6 @@ fun CalendarHost(
val eventActions: EventActionsViewModel = hiltViewModel()
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
// "Sync now" in the drawer (#240); its receipt shares the move chip.
val sync: SyncViewModel = hiltViewModel()
val loadedSyncTargets by sync.targets.collectAsStateWithLifecycle()
val syncTargets = loadedSyncTargets ?: SyncTargets.None
val syncInFlight by sync.inFlight.collectAsStateWithLifecycle()
val syncResult by sync.result.collectAsStateWithLifecycle()
val selectionFailureMessage = eventActionFailureMessage(selectionFailure)
val syncMessage = syncResult?.let { stringResource(it.messageRes()) }
val 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
@@ -556,7 +549,6 @@ fun CalendarHost(
val stayingPut = remember { StayingPut() }
val chromeHost = remember { ChromeHost() }
val drawerState = rememberDrawerState(DrawerValue.Closed)
RefreshSyncAccessOnOpen(drawerState, sync)
val density = LocalDensity.current
val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) +
with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() }
@@ -577,6 +569,15 @@ fun CalendarHost(
// (#239); nothing else in the calendar surfaces navigates here.
LocalManageCalendars provides remember { { showCalendars = true } },
) {
if (showViewCalendars) {
val filterState by filterViewModel.state.collectAsStateWithLifecycle()
ViewCalendarsPicker(
view = view,
state = filterState,
onSetHidden = { id, hidden -> filterViewModel.setHiddenIn(id, view, hidden) },
onDismiss = { showViewCalendars = false },
)
}
// One drawer, top bar and FAB for every screen (#184): a switch changes
// what they say, from what the screen on show publishes, rather than
// swapping them for another screen's.
@@ -607,17 +608,9 @@ fun CalendarHost(
onOpenSettings()
switchScope.launch { drawerState.close() }
},
sync = remember(syncTargets, syncInFlight) {
DrawerSync(
canSync = syncTargets.reachable.isNotEmpty(),
inFlight = syncInFlight,
needsAccess = syncTargets.needsAccess.isNotEmpty(),
onSync = {
sync.requestSync()
switchScope.launch { drawerState.close() }
},
onGrantAccess = { showSyncAccess = true },
)
onHideInView = {
showViewCalendars = true
switchScope.launch { drawerState.close() }
},
)
},
@@ -644,12 +637,10 @@ fun CalendarHost(
// A fresh event, like a duplicate from the detail screen (#52).
openImportForm(form, ImportSource.Insert)
},
chipShown = moveOutcome != null || selectionFailure != null || syncResult != null,
chipShown = moveOutcome != null || selectionFailure != null,
onDismissChip = {
reschedule.consumeOutcome()
eventActions.consumeFailure()
// Only the chip on show: a receipt queued behind it still gets its turn.
if (moveOutcome == null && selectionFailure == null) sync.consumeResult()
},
)
CalendarFab(chromeHost, todayInToolbar, fabSelection)
@@ -712,21 +703,10 @@ fun CalendarHost(
EventMoveHost(
reschedule,
modifier = Modifier.fillMaxSize(),
notice = selectionFailureMessage ?: syncMessage,
onNoticeShown = {
if (selectionFailureMessage != null) eventActions.consumeFailure() else sync.consumeResult()
},
actionFailure = eventActionFailureMessage(selectionFailure),
onActionFailureShown = eventActions::consumeFailure,
)
if (showSyncAccess) {
SyncAccessSheet(
accounts = loadedSyncTargets?.needsAccess?.toList(),
onGrant = launchAccessPicker,
onDismissAccount = sync::dismissAccess,
onDismiss = { showSyncAccess = false },
)
}
// The delete prompt and failure chip of a selected event's actions (#141).
EventSelectionHost(host = chromeHost, viewModel = eventActions)
@@ -15,6 +15,9 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
import de.jeanlucmakiola.calendula.ui.common.instancesWithout
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
@@ -46,6 +49,8 @@ class AgendaViewModel @Inject constructor(
@IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() {
private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, viewModelScope)
// The saved agenda range plus the range-bar visibility toggle.
private val agendaSettings = combine(
settingsPrefs.agendaScreenRange,
@@ -138,7 +143,7 @@ class AgendaViewModel @Inject constructor(
)
combine(
repository.calendars(),
repository.instances(window),
repository.instancesWithout(window, hiddenHere),
today,
) { calendars, instances, today ->
buildState(params, calendars, instances, today)
@@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.calendars
import android.accounts.AccountManager
import android.content.Context
import android.content.Intent
import android.icu.text.ListFormatter
import android.provider.Settings
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
@@ -45,6 +46,7 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
@@ -54,6 +56,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
@@ -72,6 +75,10 @@ import de.jeanlucmakiola.calendula.domain.stateLabels
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
import de.jeanlucmakiola.calendula.ui.common.AccountKey
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
import de.jeanlucmakiola.calendula.ui.common.icon
import de.jeanlucmakiola.calendula.ui.common.label
import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
@@ -85,11 +92,6 @@ import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.ui.common.SyncAccountRow
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.collapseExit
@@ -97,6 +99,7 @@ import de.jeanlucmakiola.floret.identity.expandEnter
import de.jeanlucmakiola.floret.identity.predictiveBack
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.InlineTextField
import de.jeanlucmakiola.floret.components.MultiOptionPicker
import de.jeanlucmakiola.floret.components.Position
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.heightIn
@@ -135,16 +138,19 @@ 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() }
val loadedHiddenViews by viewModel.hiddenViews.collectAsStateWithLifecycle()
val hiddenViews = loadedHiddenViews.orEmpty()
// 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
// a fresh open while still surviving configuration changes within one open.
var editorId by rememberSaveable { mutableStateOf<Long?>(null) }
var editorSession by rememberSaveable { mutableStateOf(0) }
// A synced calendar has no editor; tapping it opens its hidden-views picker.
var hidingId by rememberSaveable { mutableStateOf<Long?>(null) }
if (editorId != null) {
// The editor and the picker seed from the stored hidden views, so both wait for the first read.
if (editorId != null && loadedHiddenViews != null) {
val editing = calendars.firstOrNull { it.id == editorId }
CalendarEditor(
sessionKey = editorSession,
@@ -152,13 +158,15 @@ fun CalendarsScreen(
initialName = editing?.displayName.orEmpty(),
initialColor = editing?.color ?: CalendarColorPalette.all.first(),
initialDescription = editing?.description.orEmpty(),
showHiddenViews = true,
initialHiddenViews = editing?.let { hiddenViews[it.id] }.orEmpty(),
deleteLocked = editing != null && editing.id in deleteLockedIds,
onSave = { name, color, description ->
onSave = { name, color, description, views ->
val id = editorId
if (id == null || id == NEW_CALENDAR_ID) {
viewModel.createCalendar(name, color, description)
viewModel.createCalendar(name, color, description, views)
} else {
viewModel.updateCalendar(id, name, color, description)
viewModel.updateCalendar(id, name, color, description, views)
}
editorId = null
},
@@ -172,6 +180,7 @@ fun CalendarsScreen(
CalendarsList(
local = calendars.filter { it.isLocal },
synced = calendars.filterNot { it.isLocal },
hiddenViews = hiddenViews,
error = error,
onConsumeError = viewModel::consumeError,
onOpenBackup = onOpenBackup,
@@ -179,11 +188,26 @@ fun CalendarsScreen(
visible = visible,
onAdd = { editorSession++; editorId = NEW_CALENDAR_ID },
onEdit = { calendar -> editorSession++; editorId = calendar.id },
onEditHiddenViews = { calendar -> hidingId = calendar.id },
onSetVisible = viewModel::setCalendarVisible,
onSetAccountVisible = viewModel::setAccountVisible,
syncAccessDismissed = syncAccessDismissed,
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
)
hidingId?.let { id ->
val calendar = calendars.firstOrNull { it.id == id }
// Gone while the picker was up; an empty list is one still loading, not a deletion.
if (calendar == null && calendars.isNotEmpty()) {
LaunchedEffect(id) { hidingId = null }
} else if (calendar != null && loadedHiddenViews != null) {
key(id) {
HiddenViewsPicker(
calendarName = calendar.displayName.orUnnamed(),
hidden = hiddenViews[id].orEmpty(),
onToggle = { view, hide -> viewModel.setHiddenIn(id, view, hide) },
onDismiss = { hidingId = null },
)
}
}
}
}
}
@@ -191,6 +215,7 @@ fun CalendarsScreen(
private fun CalendarsList(
local: List<CalendarSource>,
synced: List<CalendarSource>,
hiddenViews: Map<Long, Set<CalendarView>>,
error: Boolean,
onConsumeError: () -> Unit,
onOpenBackup: () -> Unit,
@@ -198,10 +223,9 @@ private fun CalendarsList(
visible: Boolean,
onAdd: () -> Unit,
onEdit: (CalendarSource) -> Unit,
onEditHiddenViews: (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() }
@@ -252,6 +276,7 @@ private fun CalendarsList(
local.forEachIndexed { index, calendar ->
CalendarManagerRow(
calendar = calendar,
hiddenViews = hiddenViews[calendar.id].orEmpty(),
last = index == local.lastIndex,
onSetVisible = onSetVisible,
onClick = { onEdit(calendar) },
@@ -326,26 +351,14 @@ private fun CalendarsList(
ordered.forEachIndexed { index, calendar ->
CalendarManagerRow(
calendar = calendar,
hiddenViews = hiddenViews[calendar.id].orEmpty(),
last = index == ordered.lastIndex,
onSetVisible = onSetVisible,
onClick = { onEditHiddenViews(calendar) },
)
}
}
}
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) },
)
}
}
}
}
@@ -364,19 +377,32 @@ internal fun CalendarEditor(
initialName: String,
initialColor: Int,
initialDescription: String,
onSave: (name: String, color: Int, description: String?) -> Unit,
onSave: (name: String, color: Int, description: String?, hiddenChanges: Map<CalendarView, Boolean>) -> Unit,
onDelete: () -> Unit,
onClose: () -> Unit,
deleteLocked: Boolean = false,
showHiddenViews: Boolean = false,
initialHiddenViews: Set<CalendarView> = emptySet(),
) {
var name by rememberSaveable(sessionKey) { mutableStateOf(initialName) }
val seededHiddenViews = rememberSaveable(sessionKey) { initialHiddenViews }
var hiddenViews by rememberSaveable(sessionKey) { mutableStateOf(initialHiddenViews) }
var pickHiddenViews by rememberSaveable(sessionKey) { mutableStateOf(false) }
var color by rememberSaveable(sessionKey) { mutableStateOf(initialColor) }
var description by rememberSaveable(sessionKey) { mutableStateOf(initialDescription) }
var confirmDelete by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
val valid = name.isNotBlank()
val commit = { if (valid) onSave(name.trim(), color, description.trim().ifEmpty { null }) }
val commit = {
if (valid) {
// Only the views toggled here are written, so a save never resets ones it didn't load.
val changes = IMPLEMENTED_VIEWS
.filter { (it in hiddenViews) != (it in seededHiddenViews) }
.associateWith { it in hiddenViews }
onSave(name.trim(), color, description.trim().ifEmpty { null }, changes)
}
}
FullScreenPicker(
title = stringResource(
@@ -428,6 +454,16 @@ internal fun CalendarEditor(
}
}
if (showHiddenViews) {
Spacer(Modifier.height(20.dp))
GroupedRow(
title = stringResource(R.string.calendars_hide_in_views),
summary = hiddenViewsSummary(hiddenViews),
position = Position.Alone,
onClick = { pickHiddenViews = true },
)
}
if (!isNew && !deleteLocked) {
Spacer(Modifier.height(24.dp))
DeleteCalendarRow(onClick = { confirmDelete = true })
@@ -435,6 +471,17 @@ internal fun CalendarEditor(
Spacer(Modifier.height(24.dp))
}
if (pickHiddenViews) {
HiddenViewsPicker(
calendarName = name.trim().orUnnamed(),
hidden = hiddenViews,
onToggle = { view, hide ->
hiddenViews = if (hide) hiddenViews + view else hiddenViews - view
},
onDismiss = { pickHiddenViews = false },
)
}
if (confirmDelete) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
@@ -661,7 +708,7 @@ private fun EditorSectionLabel(text: String) {
* plain writable one (#76), then its own description.
*/
@Composable
private fun calendarRowSummary(calendar: CalendarSource): String? {
private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<CalendarView>): String? {
val states = calendar.stateLabels().map { label ->
stringResource(
when (label) {
@@ -671,7 +718,8 @@ private fun calendarRowSummary(calendar: CalendarSource): String? {
},
)
}
val parts = states + listOfNotNull(calendar.description?.takeIf { it.isNotBlank() })
val hidden = if (hiddenViews.isEmpty()) null else hiddenViewsSummary(hiddenViews)
val parts = states + listOfNotNull(hidden, calendar.description?.takeIf { it.isNotBlank() })
return parts.joinToString(" · ").ifEmpty { null }
}
@@ -687,6 +735,7 @@ private fun calendarRowSummary(calendar: CalendarSource): String? {
@Composable
private fun CalendarManagerRow(
calendar: CalendarSource,
hiddenViews: Set<CalendarView>,
last: Boolean,
onSetVisible: (Long, Boolean) -> Unit,
onClick: (() -> Unit)? = null,
@@ -694,7 +743,7 @@ private fun CalendarManagerRow(
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
GroupedRow(
title = calendar.displayName.orUnnamed(),
summary = calendarRowSummary(calendar),
summary = calendarRowSummary(calendar, hiddenViews),
position = if (last) Position.Bottom else Position.Middle,
container = MaterialTheme.colorScheme.surfaceContainerHighest,
dimmed = disabled,
@@ -714,6 +763,51 @@ private fun CalendarManagerRow(
)
}
/**
* Which views one calendar stays out of (#270); display only, so reminders and
* search keep the calendar. [onToggle] decides when a toggle lands: at once for
* a synced calendar, on Save inside the local editor.
*/
@Composable
private fun HiddenViewsPicker(
calendarName: String,
hidden: Set<CalendarView>,
onToggle: (CalendarView, Boolean) -> Unit,
onDismiss: () -> Unit,
) {
// Seeded once and then ahead of the store: the picker is the only writer while
// it is open, so following each write back would only flicker a quick second tap.
var shown by remember { mutableStateOf(hidden) }
MultiOptionPicker(
title = stringResource(R.string.calendars_hide_in_views),
options = IMPLEMENTED_VIEWS,
selected = shown,
label = { it.label() },
onToggle = { view, hide ->
shown = if (hide) shown + view else shown - view
onToggle(view, hide)
},
onDismiss = onDismiss,
leading = { Icon(it.icon, contentDescription = null) },
header = {
GroupedHint(
stringResource(R.string.calendars_hide_in_views_hint, calendarName),
verticalPadding = 8.dp,
)
},
predictiveBack = true,
)
}
/** "Shown in every view", or the views [hidden] names, in the app's view order. */
@Composable
private fun hiddenViewsSummary(hidden: Set<CalendarView>): String {
if (hidden.isEmpty()) return stringResource(R.string.calendars_hide_in_views_none)
val names = IMPLEMENTED_VIEWS.filter { it in hidden }.map { it.label() }
val locale = LocalConfiguration.current.locales[0]
return stringResource(R.string.calendars_hidden_in, ListFormatter.getInstance(locale).format(names))
}
/** Fade a leading element to the M3 disabled emphasis when [disabled]. */
private fun dimIf(disabled: Boolean): Modifier =
if (disabled) Modifier.alpha(0.38f) else Modifier
@@ -3,19 +3,21 @@ package de.jeanlucmakiola.calendula.ui.calendars
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
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
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
@@ -57,23 +59,6 @@ class CalendarsViewModel @Inject constructor(
initialValue = emptyList(),
)
/**
* Accounts the drawer was told not to ask sync-request access for (#240),
* limited to those still behind a visible calendar and still unreachable.
*/
val syncAccessDismissed: StateFlow<List<SyncAccount>> =
repository.syncTargets
.map { it.dismissed.toList() }
.catch { emit(emptyList()) }
.stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList())
/** Re-read account access, which can change outside the app; called on resume. */
fun refreshAccess() = repository.refreshSyncAccess()
fun askSyncAccessAgain(account: SyncAccount) {
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) }
}
/**
* The Backup & restore screen's own view of that list, with the loading and
* failure states [calendars] flattens away — it starts empty and catches to
@@ -122,6 +107,19 @@ class CalendarsViewModel @Inject constructor(
initialValue = emptySet(),
)
/** The views each calendar is hidden in (#270); null until first read. */
val hiddenViews: StateFlow<Map<Long, Set<CalendarView>>?> =
settingsPrefs.perCalendarHiddenViews
.hidingNothingOnError()
.stateWhileSubscribed(
scope = viewModelScope,
initialValue = null,
)
fun setHiddenIn(id: Long, view: CalendarView, hidden: Boolean) = write {
settingsPrefs.setCalendarHiddenIn(id, view, hidden)
}
private val _error = MutableStateFlow(false)
val error: StateFlow<Boolean> = _error.asStateFlow()
@@ -157,16 +155,41 @@ class CalendarsViewModel @Inject constructor(
}
}
fun createCalendar(displayName: String, color: Int, description: String?) = write {
repository.createLocalCalendar(displayName, color, description)
fun createCalendar(
displayName: String,
color: Int,
description: String?,
hiddenChanges: Map<CalendarView, Boolean>,
) = write {
val id = repository.createLocalCalendar(displayName, color, description)
settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges)
}
fun updateCalendar(id: Long, displayName: String, color: Int, description: String?) = write {
fun updateCalendar(
id: Long,
displayName: String,
color: Int,
description: String?,
hiddenChanges: Map<CalendarView, Boolean>,
) = write {
repository.updateCalendar(id, displayName, color, description)
settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges)
}
fun deleteCalendar(id: Long) = write {
repository.deleteCalendar(id)
// Tidy-up only: the delete already landed, so a failure here isn't its failure.
bestEffort { settingsPrefs.clearCalendarHiddenViews(id) }
}
private suspend fun bestEffort(block: suspend () -> Unit) {
try {
block()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("CalendarsViewModel", "Hidden-views write failed", e)
}
}
/**
@@ -20,12 +20,8 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.ManageAccounts
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.DrawerState
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.Icon
import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.Text
@@ -42,8 +38,6 @@ import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.ui.filter.CalendarFilterList
@@ -67,8 +61,6 @@ import kotlinx.datetime.LocalDate
*
* [currentDate] seeds the jump-to-date picker (the visible day/week-start/month
* anchor); [onJumpToDate] navigates the active view to the chosen day.
* [sync] adds "Sync now" beside it while there is a synced calendar (#240),
* and a row to grant account access while some account can't be reached yet.
*/
@Composable
fun CalendarDrawer(
@@ -78,8 +70,8 @@ fun CalendarDrawer(
onSelectView: (CalendarView) -> Unit,
onJumpToDate: (LocalDate) -> Unit,
onSettings: () -> Unit,
onHideInView: () -> Unit,
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
sync: DrawerSync? = null,
) {
var showDatePicker by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
@@ -112,17 +104,16 @@ fun CalendarDrawer(
Spacer(Modifier.height(16.dp))
GroupedRow(
title = stringResource(R.string.drawer_jump_to_date),
position = if (sync?.hasRows == true) Position.Top else Position.Alone,
position = Position.Alone,
minHeight = 56.dp,
leading = { DrawerLeadingIcon(Icons.Filled.DateRange) },
onClick = { showDatePicker = true },
)
if (sync != null) SyncRows(sync)
Spacer(Modifier.height(16.dp))
DrawerSectionHeader(stringResource(R.string.filter_title))
CalendarFilterList()
CalendarFilterList(currentView = currentView, onHideInView = onHideInView)
Spacer(Modifier.height(16.dp))
GroupedRow(
@@ -148,61 +139,6 @@ fun CalendarDrawer(
}
}
/**
* The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress
* and ignores taps), and a grant row while some account [needsAccess].
*/
data class DrawerSync(
val canSync: Boolean,
val inFlight: Boolean,
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_requested)
GroupedRow(
title = stringResource(R.string.drawer_sync_now),
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,
notice: String? = null,
onNoticeShown: () -> Unit = {},
actionFailure: String? = null,
onActionFailureShown: () -> Unit = {},
) {
val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle()
val outcome by viewModel.outcome.collectAsStateWithLifecycle()
@@ -81,7 +81,7 @@ fun EventMoveHost(
}
// A failed selection action (#141) shares the chip rather than stacking on it.
val message = when (outcome) {
null -> notice
null -> actionFailure
is MoveOutcome.Moved -> if (resizedLabel != null) {
stringResource(R.string.event_resize_done, resizedLabel)
} else {
@@ -116,10 +116,10 @@ fun EventMoveHost(
viewModel.consumeOutcome()
}
// A failure waits for the chip to be free, then has its own turn.
LaunchedEffect(notice, outcome == null) {
if (notice == null || outcome != null) return@LaunchedEffect
LaunchedEffect(actionFailure, outcome == null) {
if (actionFailure == null || outcome != null) return@LaunchedEffect
delay(CHIP_MILLIS)
onNoticeShown()
onActionFailureShown()
}
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
@@ -138,7 +138,7 @@ fun EventMoveHost(
// write anyway, so offering it would be a button that does nothing.
val undo = content.undo?.takeIf { !writeInFlight }
SnackChip(
visible = outcome != null || notice != null,
visible = outcome != null || actionFailure != null,
message = content.message,
maxWidth = chipMaxWidth,
actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null },
@@ -1,121 +0,0 @@
package de.jeanlucmakiola.calendula.ui.common
import android.content.ActivityNotFoundException
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.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()
}
}
/**
* The accounts sync requests can't reach yet (#240), one row each: tapping one
* opens the system picker for just that account, "Don't ask" stops offering it.
* Closes itself once no account is left.
*/
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun SyncAccessSheet(
accounts: List<SyncAccount>?,
onGrant: (SyncAccount) -> Unit,
onDismissAccount: (SyncAccount) -> Unit,
onDismiss: () -> Unit,
) {
LaunchedEffect(accounts?.isEmpty()) { if (accounts?.isEmpty() == true) onDismiss() }
FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) {
GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp)
if (accounts == null) {
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { LoadingIndicator() }
}
accounts.orEmpty().forEachIndexed { index, account ->
SyncAccountRow(
account = account,
position = positionOf(index, accounts.orEmpty().size),
actionLabel = stringResource(R.string.sync_access_dont_ask),
onAction = { onDismissAccount(account) },
onClick = { onGrant(account) },
)
}
}
}
/** One synced account with a text action, as the access sheet and the calendar manager list them. */
@Composable
fun SyncAccountRow(
account: SyncAccount,
position: Position,
actionLabel: String,
onAction: () -> Unit,
onClick: (() -> Unit)? = null,
) {
GroupedRow(
title = account.name,
summary = sourceAppName(account.type),
position = position,
minHeight = 64.dp,
leading = { SourceLogo(account.type) },
trailing = { TextButton(onClick = onAction) { Text(actionLabel) } },
onClick = onClick,
)
}
@@ -1,95 +0,0 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.annotation.StringRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
import de.jeanlucmakiola.calendula.data.calendar.SyncTargets
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
/**
* The drawer's "Sync now" (#240): asks the sync adapters of every visible synced
* calendar to run now. [inFlight] holds until the provider next reports a change
* or [SETTLE_MILLIS] pass — the request itself says nothing about when, or
* whether, the sync completes.
*/
@HiltViewModel
class SyncViewModel @Inject constructor(
private val repository: CalendarRepository,
) : ViewModel() {
/** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */
val targets: StateFlow<SyncTargets?> = repository.syncTargets
.catch { emit(SyncTargets.None) }
.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
viewModelScope.launch {
try {
// Listening before asking, so a sync that lands at once still counts.
val settled = async(start = CoroutineStart.UNDISPATCHED) {
withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.firstOrNull() }
}
val outcome = repository.requestSync()
_result.value = outcome
val sent = outcome == SyncRequestResult.Requested ||
outcome == SyncRequestResult.SomeNeedAccess ||
outcome == SyncRequestResult.PartlyFailed
if (sent) settled.await() else settled.cancel()
} 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 SETTLE_MILLIS = 15_000L
}
}
/** The chip text for a sync request's outcome. */
@StringRes
fun SyncRequestResult.messageRes(): Int = when (this) {
SyncRequestResult.Requested -> R.string.sync_requested
SyncRequestResult.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
}
@@ -0,0 +1,63 @@
package de.jeanlucmakiola.calendula.ui.common
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.withoutCalendars
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.retryWhen
import kotlinx.coroutines.flow.shareIn
import java.io.IOException
import kotlin.time.Instant
/** The calendars hidden in [view] under a per-calendar hidden-views map (#270). */
fun Map<Long, Set<CalendarView>>.calendarsHiddenIn(view: CalendarView): Set<Long> =
filterValues { view in it }.keys
/**
* The calendars hidden in [view], shared by everything one view model shows so
* the setting is read once rather than per page. A failed read hides nothing
* rather than failing the view; the replay expires with the last subscriber, so
* a returning view filters against a fresh read.
*/
fun Flow<Map<Long, Set<CalendarView>>>.calendarsHiddenIn(
view: CalendarView,
scope: CoroutineScope,
): Flow<Set<Long>> =
hidingNothingOnError()
.map { it.calendarsHiddenIn(view) }
.distinctUntilChanged()
// The grace period outlasts a flatMapLatest swap, so paging doesn't re-read it.
.shareIn(scope, SharingStarted.WhileSubscribed(5_000, replayExpirationMillis = 0), replay = 1)
/**
* A failed read of the per-view setting hides nothing rather than failing what
* shows it, and keeps reading, so the next change still lands.
*/
fun Flow<Map<Long, Set<CalendarView>>>.hidingNothingOnError(): Flow<Map<Long, Set<CalendarView>>> =
retryWhen { cause, attempt ->
if (cause !is IOException) return@retryWhen false
emit(emptyMap())
// Backs off, so a file that keeps failing (corrupt) isn't re-read every second.
delay((RETRY_BASE_DELAY_MS shl attempt.coerceAtMost(6).toInt()).coerceAtMost(RETRY_MAX_DELAY_MS))
true
}
private const val RETRY_BASE_DELAY_MS = 1_000L
private const val RETRY_MAX_DELAY_MS = 60_000L
/**
* [CalendarRepository.instances] as one view shows them: also without the
* [hidden] calendars the user keeps out of it. Display only — reminders, search
* and widgets read the repository directly.
*/
fun CalendarRepository.instancesWithout(
range: ClosedRange<Instant>,
hidden: Flow<Set<Long>>,
): Flow<List<EventInstance>> =
combine(instances(range), hidden) { instances, ids -> instances.withoutCalendars(ids) }
@@ -4,15 +4,23 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@@ -22,20 +30,26 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf
/**
* Calendar-visibility filter (M3), rendered inline in the navigation drawer.
* Every calendar grouped by account, each with a colour swatch and a visibility
* switch; toggling writes straight to DataStore and every calendar view
* re-filters live. Three states (Loading / Failure / Success).
* re-filters live. Three states (Loading / Failure / Success). A calendar hidden
* in [currentView] through its per-view setting (#270) says so on its row, and
* the entry below the list opens that setting for the view (#517).
*/
@Composable
fun CalendarFilterList(
currentView: CalendarView,
onHideInView: () -> Unit,
modifier: Modifier = Modifier,
viewModel: FilterViewModel = hiltViewModel(),
) {
@@ -43,12 +57,18 @@ fun CalendarFilterList(
when (val s = state) {
FilterUiState.Loading -> FilterLoading(modifier)
is FilterUiState.Failure -> FilterMessage(s.reason, modifier)
is FilterUiState.Success -> FilterList(
groups = s.groups,
hidden = s.hidden,
onSetVisible = viewModel::setVisible,
modifier = modifier,
)
is FilterUiState.Success -> {
val hiddenInView = remember(s, currentView) { s.hiddenOnlyIn(currentView) }
FilterList(
groups = s.groups,
hidden = s.hidden,
hiddenInView = hiddenInView,
hiddenOnlyHere = hiddenInView.size,
onHideInView = onHideInView,
onSetVisible = viewModel::setVisible,
modifier = modifier,
)
}
}
}
@@ -61,6 +81,9 @@ fun CalendarFilterList(
private fun FilterList(
groups: List<CalendarAccountGroup>,
hidden: Set<Long>,
hiddenInView: Set<Long>,
hiddenOnlyHere: Int,
onHideInView: () -> Unit,
onSetVisible: (Long, Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
@@ -81,6 +104,7 @@ private fun FilterList(
val visible = cal.id !in hidden
GroupedRow(
title = cal.displayName.orUnnamed(),
summary = if (cal.id in hiddenInView) stringResource(R.string.filter_hidden_in_view) else null,
position = positionOf(index, group.calendars.size),
minHeight = 56.dp,
leading = { CalendarColorChip(cal.color) },
@@ -94,11 +118,32 @@ private fun FilterList(
)
}
}
// The per-view hide (#517): the drawer filter above hides everywhere, this only here.
Spacer(Modifier.height(8.dp))
GroupedRow(
title = stringResource(R.string.view_calendars_title),
summary = if (hiddenOnlyHere > 0) {
pluralStringResource(R.plurals.drawer_hidden_in_view_count, hiddenOnlyHere, hiddenOnlyHere)
} else {
stringResource(R.string.drawer_hidden_in_view_none)
},
position = Position.Alone,
minHeight = 56.dp,
// Tinted, not "selected": it is an entry point, not a chosen option.
container = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.secondaryContainer else null,
contentColor = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.onSecondaryContainer else null,
leading = {
Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {
Icon(Icons.Filled.FilterList, contentDescription = null)
}
},
onClick = onHideInView,
)
}
}
@Composable
private fun FilterLoading(modifier: Modifier = Modifier) {
internal fun FilterLoading(modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp),
@@ -119,7 +164,7 @@ private fun FilterLoading(modifier: Modifier = Modifier) {
}
@Composable
private fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) {
internal fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) {
val msg = when (reason) {
FailureReason.NoCalendarsConfigured -> R.string.state_failure_no_calendars
FailureReason.AllCalendarsHidden -> R.string.state_failure_all_hidden
@@ -2,6 +2,8 @@ package de.jeanlucmakiola.calendula.ui.filter
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
/**
* State for the calendar-filter sheet (M3). The user toggles per-calendar
@@ -11,9 +13,22 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
sealed interface FilterUiState {
data object Loading : FilterUiState
data class Failure(val reason: FailureReason) : FilterUiState
/** A calendar shows when its id is *not* in [hidden]. */
/**
* A calendar shows when its id is *not* in [hidden]; [hiddenViews] are the
* views each calendar is hidden in regardless (#270).
*/
data class Success(
val groups: List<CalendarAccountGroup>,
val hidden: Set<Long>,
) : FilterUiState
val hiddenViews: Map<Long, Set<CalendarView>> = emptyMap(),
) : FilterUiState {
/**
* The listed calendars [view] hides on its own (#517); ones already
* hidden everywhere from the drawer, or not listed, aren't included.
*/
fun hiddenOnlyIn(view: CalendarView): Set<Long> {
val listed = groups.flatMapTo(mutableSetOf()) { group -> group.calendars.map { it.id } }
return hiddenViews.calendarsHiddenIn(view).filterTo(mutableSetOf()) { it in listed && it !in hidden }
}
}
}
@@ -1,15 +1,20 @@
package de.jeanlucmakiola.calendula.ui.filter
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
@@ -23,6 +28,7 @@ import javax.inject.Inject
class FilterViewModel @Inject constructor(
private val repository: CalendarRepository,
private val prefs: CalendarPrefs,
private val settingsPrefs: SettingsPrefs,
@IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() {
@@ -30,7 +36,9 @@ class FilterViewModel @Inject constructor(
combine(
repository.calendars(),
prefs.hiddenCalendarIds,
) { calendars, hidden ->
// Only feeds a note on the rows; a failed read leaves it off rather than failing the list.
settingsPrefs.perCalendarHiddenViews.hidingNothingOnError(),
) { calendars, hidden, hiddenViews ->
// Calendars switched off device-wide don't belong in the drawer's
// hide/show list; they live only in Settings → Calendars.
val enabled = calendars.filter { it.isVisibleInSystem }
@@ -38,7 +46,7 @@ class FilterViewModel @Inject constructor(
if (failure != null) {
FilterUiState.Failure(failure)
} else {
FilterUiState.Success(enabled.groupByAccount(), hidden)
FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews)
}
}
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
@@ -48,6 +56,19 @@ class FilterViewModel @Inject constructor(
initialValue = FilterUiState.Loading,
)
/** Hide or show one calendar in [view] only (#517), the same setting as Settings → Calendars. */
fun setHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) {
viewModelScope.launch {
try {
settingsPrefs.setCalendarHiddenIn(calendarId, view, hidden)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("FilterViewModel", "Could not change hidden views of $calendarId", e)
}
}
}
/** Show or hide a single calendar; persists the new hidden set. */
fun setVisible(calendarId: Long, visible: Boolean) {
viewModelScope.launch {
@@ -0,0 +1,65 @@
package de.jeanlucmakiola.calendula.ui.filter
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.MultiOptionRows
/**
* The calendars hidden in [view] (#517), opened from the drawer while on it: the
* per-view setting from Settings → Calendars (#270), seen from the view's side.
* Toggles apply at once.
*/
@Composable
fun ViewCalendarsPicker(
view: CalendarView,
state: FilterUiState,
onSetHidden: (calendarId: Long, hidden: Boolean) -> Unit,
onDismiss: () -> Unit,
) {
FullScreenPicker(
title = stringResource(R.string.view_calendars_title),
onDismiss = onDismiss,
predictiveBack = true,
) {
when (state) {
FilterUiState.Loading -> FilterLoading()
is FilterUiState.Failure -> FilterMessage(state.reason)
is FilterUiState.Success -> {
// Seeded once, then ahead of the store: the picker is the only
// writer while open, so a quick second tap still flips.
var hidden by remember(view) { mutableStateOf(state.hiddenViews.calendarsHiddenIn(view)) }
GroupedHint(stringResource(R.string.view_calendars_hint), verticalPadding = 8.dp)
state.groups.forEach { group ->
GroupedSectionHeader(accountGroupTitle(group))
MultiOptionRows(
options = group.calendars,
selected = group.calendars.filterTo(mutableSetOf()) { it.id in hidden },
label = { it.displayName.orUnnamed() },
onToggle = { calendar, hide ->
hidden = if (hide) hidden + calendar.id else hidden - calendar.id
onSetHidden(calendar.id, hide)
},
summary = { calendar ->
if (calendar.id in state.hidden) stringResource(R.string.view_calendars_hidden_everywhere) else null
},
leading = { CalendarColorChip(it.color) },
)
}
}
}
}
}
@@ -19,7 +19,10 @@ import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay
import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing
import de.jeanlucmakiola.calendula.ui.common.CalendarSpan
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.PageStateCache
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
import de.jeanlucmakiola.calendula.ui.common.instancesWithout
import de.jeanlucmakiola.calendula.domain.isCrossedOut
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
import de.jeanlucmakiola.calendula.ui.week.coversDay
@@ -68,6 +71,8 @@ class MonthViewModel @Inject constructor(
private val zone = TimeZone.currentSystemDefault()
private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Month, viewModelScope)
/** First day of the week, from the Settings preference (AUTO → locale). */
val weekStart: StateFlow<DayOfWeek> = settingsPrefs.firstDayOfWeek(viewModelScope)
@@ -152,7 +157,7 @@ class MonthViewModel @Inject constructor(
) { (ym, ws) ->
combine(
repository.calendars(),
repository.instances(monthGridRange(ym, ws, zone)),
repository.instancesWithout(monthGridRange(ym, ws, zone), hiddenHere),
today,
) { calendars, instances, today ->
buildState(ym, ws, calendars, instances, today)
@@ -224,7 +229,7 @@ class MonthViewModel @Inject constructor(
val range = dayRange(first, last, zone)
combine(
repository.calendars(),
repository.instances(range),
repository.instancesWithout(range, hiddenHere),
today,
) { calendars, instances, today ->
buildContinuousState(window, ws, style, calendars, instances, today)
@@ -89,7 +89,7 @@ internal fun CalendarsStep(
initialName = "",
initialColor = CalendarColorPalette.all.first(),
initialDescription = "",
onSave = { name, color, description ->
onSave = { name, color, description, _ ->
if (!submitted) {
submitted = true
onCreateLocal(name, color, description)
@@ -19,7 +19,10 @@ import de.jeanlucmakiola.calendula.domain.displayPriority
import de.jeanlucmakiola.calendula.domain.displayStart
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.PageStateCache
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
import de.jeanlucmakiola.calendula.ui.common.instancesWithout
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
@@ -89,8 +92,11 @@ abstract class PagedTimelineViewModel(
private val io: CoroutineDispatcher,
gridRule: Flow<(LocalDate) -> DaysGrid>,
initialRule: (LocalDate) -> DaysGrid,
view: CalendarView,
) : ViewModel() {
private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(view, viewModelScope)
/**
* The zone every page is laid out in; drags and drops resolve in it too, and
* pages lay out again when the device moves zones (#387).
@@ -167,7 +173,7 @@ abstract class PagedTimelineViewModel(
zone.flatMapLatest { zone ->
combine(
repository.calendars(),
repository.instances(spanRange(span.start, span.count, zone)),
repository.instancesWithout(spanRange(span.start, span.count, zone), hiddenHere),
today,
) { calendars, instances, today ->
buildState(span, calendars, instances, today, zone)
@@ -240,6 +246,7 @@ class WeekViewModel @Inject constructor(
rule
},
initialRule = { DaysGrid.weeks(DayOfWeek.MONDAY) },
view = CalendarView.Week,
)
/**
@@ -264,6 +271,7 @@ class MultiDayViewModel @Inject constructor(
{ anchor: LocalDate -> DaysGrid.startingAt(anchor, count) }
},
initialRule = { DaysGrid.startingAt(it, SettingsPrefs.DEFAULT_MULTI_DAY_COUNT) },
view = CalendarView.MultiDay,
)
/** The day view: the timeline one day at a time. */
@@ -282,6 +290,7 @@ class DayViewModel @Inject constructor(
io = io,
gridRule = flowOf { _: LocalDate -> DaysGrid.days },
initialRule = { DaysGrid.days },
view = CalendarView.Day,
)
/**
@@ -11,7 +11,6 @@ import androidx.glance.GlanceId
import androidx.glance.appwidget.state.getAppWidgetState
import androidx.glance.state.PreferencesGlanceStateDefinition
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.storageValue
@@ -116,8 +115,5 @@ internal fun MutablePreferences.putHiddenCalendars(ids: Set<Long>) {
this[HiddenCalendarsKey] = ids.map(Long::toString).toSet()
}
internal fun List<EventInstance>.withoutCalendars(hidden: Set<Long>): List<EventInstance> =
if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden }
internal suspend fun Context.widgetState(id: GlanceId): Preferences =
getAppWidgetState(this, PreferencesGlanceStateDefinition, id)
@@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.withoutCalendars
import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.agendaRange
@@ -12,6 +12,7 @@ import de.jeanlucmakiola.floret.glance.updateWithRefresh
import kotlinx.coroutines.CancellationException
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.withoutCalendars
import de.jeanlucmakiola.calendula.widget.Themed
import de.jeanlucmakiola.calendula.widget.WidgetKind
import de.jeanlucmakiola.calendula.widget.WidgetLoadContext
@@ -22,7 +23,6 @@ import de.jeanlucmakiola.calendula.widget.today
import de.jeanlucmakiola.calendula.widget.widgetEntryPoint
import de.jeanlucmakiola.calendula.widget.widgetLoadContext
import de.jeanlucmakiola.calendula.widget.widgetState
import de.jeanlucmakiola.calendula.widget.withoutCalendars
import de.jeanlucmakiola.floret.prefs.toEnum
import kotlinx.coroutines.flow.first
import kotlinx.datetime.LocalDate
+14 -16
View File
@@ -395,21 +395,6 @@
<!-- Jump to date (drawer) -->
<string name="drawer_jump_to_date">Jump to date</string>
<string name="drawer_sync_now">Sync now</string>
<string name="drawer_sync_access">Allow sync requests</string>
<string name="drawer_sync_access_summary">Pick each account Calendula may ask to sync</string>
<string name="sync_access_hint">Android only lets Calendula ask an account to sync once you pick it here. Tap an account to allow it, or choose Don\'t ask to stop offering it.</string>
<string name="sync_access_dont_ask">Don\'t ask</string>
<string name="calendars_sync_access_header">Not asked for sync access</string>
<string name="calendars_sync_access_hint">Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu.</string>
<string name="calendars_sync_access_ask_again">Ask again</string>
<string name="sync_access_picker_description">Choose an account Calendula may ask to sync your calendars</string>
<string name="sync_requested">Sync requested</string>
<string name="sync_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>
@@ -864,7 +849,7 @@
<string name="calendars_state_managed">Filled from your contacts</string>
<string name="calendars_managed_delete_locked">This calendar is filled from your contacts, so Calendula would create it again on the next sync. Turn special dates off under Settings → Special dates to delete it.</string>
<string name="calendars_synced_header">Synced calendars</string>
<string name="calendars_synced_hint">These come from accounts on your device. Create and edit them in their own app.</string>
<string name="calendars_synced_hint">These come from accounts on your device. Create and edit them in their own app; tap one here to hide it in some views.</string>
<string name="calendars_manage_in_app">Manage in app</string>
<!-- Account header when two accounts share a name: %1$s is the account, %2$s the app it comes from. -->
<string name="calendars_account_from_source">%1$s (%2$s)</string>
@@ -878,6 +863,19 @@
<string name="calendars_color_label">Color</string>
<string name="calendars_description_label">Description</string>
<string name="calendars_description_hint">Add a description</string>
<string name="calendars_hide_in_views">Hide in views</string>
<string name="calendars_hide_in_views_hint">Events from “%1$s” stay out of the views checked here. Reminders, search and widgets still include them.</string>
<string name="calendars_hide_in_views_none">Shown in every view</string>
<string name="calendars_hidden_in">Hidden in %1$s</string>
<string name="filter_hidden_in_view">Hidden in this view</string>
<string name="view_calendars_title">Hide in this view</string>
<plurals name="drawer_hidden_in_view_count">
<item quantity="one">%d calendar hidden in this view</item>
<item quantity="other">%d calendars hidden in this view</item>
</plurals>
<string name="drawer_hidden_in_view_none">Leave calendars out of this view only</string>
<string name="view_calendars_hint">Checked calendars stay out of this view only. Reminders, search and widgets still include them.</string>
<string name="view_calendars_hidden_everywhere">Hidden in every view from the menu</string>
<string name="color_name_mauve">Mauve</string>
<string name="color_name_red">Red</string>
<string name="color_name_orange">Orange</string>
@@ -5,8 +5,6 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import kotlinx.coroutines.CoroutineDispatcher
@@ -45,48 +43,7 @@ fun testRepository(
io: CoroutineDispatcher,
prefs: CalendarPrefs = testPrefs(dir),
settings: SettingsPrefs = testSettings(dir),
syncRequester: SyncRequester = RecordingSyncRequester(),
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester)
/**
* Records every sync request; [accepts] false models the system refusing all,
* [refusedTypes] refusing those account types, [adapterTypes] the installed
* calendar sync adapters (null: a fixed set covering the test accounts),
* [hiddenTypes] account types the app can't address by name.
*/
class RecordingSyncRequester(
var accepts: Boolean = true,
var adapterTypes: Set<String>? = null,
var refusedTypes: Set<String> = emptySet(),
var hiddenTypes: Set<String> = emptySet(),
) : SyncRequester {
data class Request(val account: SyncAccount, val userInitiated: Boolean)
val requests = mutableListOf<Request>()
override fun adapterAccountTypes(): Set<String> =
adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL")
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
visibilityError?.let { throw it }
return if (hiddenTypes.isEmpty()) {
null
} else {
knownAccounts.filterTo(mutableSetOf()) { it.type in types && it.type !in hiddenTypes }
}
}
/** Thrown by [addressableAccounts] when set. */
var visibilityError: Exception? = null
/** The accounts on the "device", for [addressableAccounts]. */
var knownAccounts: Set<SyncAccount> = emptySet()
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
if (!accepts || account.type in refusedTypes) throw SecurityException("refused")
requests += Request(account, userInitiated)
}
}
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io)
/** Installs [dispatcher] as `Dispatchers.Main` around each test. */
@OptIn(ExperimentalCoroutinesApi::class)
@@ -64,15 +64,6 @@ 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. */
@@ -1,314 +0,0 @@
package de.jeanlucmakiola.calendula.data.calendar
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.RecordingSyncRequester
import de.jeanlucmakiola.calendula.RecordingSyncRequester.Request
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.testRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Instant
class SyncNudgeTest {
private val dav = SyncAccount("me@dav", "bitfire.at.davdroid")
private val google = SyncAccount("me@gmail.com", "com.google")
private fun cal(id: Long, account: SyncAccount, visible: Boolean = true) = CalendarSource(
id = id,
displayName = "Cal $id",
accountName = account.name,
accountType = account.type,
color = 0,
isVisibleInSystem = visible,
isLocal = account.type == "LOCAL",
)
private val local = SyncAccount("Calendula", "LOCAL")
private fun fake() = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L, dav), cal(2L, dav), cal(3L, google), cal(4L, local))
eventCalendars += mapOf(10L to 1L, 30L to 3L, 40L to 4L)
}
private fun form(calendarId: Long) = EventForm(
calendarId = calendarId,
title = "Stand-up",
start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))),
end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))),
)
private fun auto(account: SyncAccount) = Request(account, userInitiated = false)
@Test
fun `a write to a synced calendar nudges its account once, not manually`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a write to a local calendar asks for no sync`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(4L))
repo.deleteEvent(40L)
assertThat(sync.requests).isEmpty()
}
@Test
fun `event writes resolve the account from the event's calendar`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.updateEventFromOccurrence(10L, 0L, form(1L), form(1L))
repo.deleteOccurrence(30L, 0L)
assertThat(sync.requests).containsExactly(auto(dav), auto(google)).inOrder()
}
@Test
fun `a move between accounts nudges both, each once`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.moveEvent(10L, 3L, form(1L), form(3L))
assertThat(sync.requests).containsExactly(auto(dav), auto(google))
}
@Test
fun `a move between calendars of one account nudges it once`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.moveEvent(10L, 2L, form(1L), form(2L))
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `an import nudges once at the end, however many events`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
val events = (1..5).map {
ParsedIcsEvent(
uid = "u$it",
summary = "E$it",
start = Instant.fromEpochMilliseconds(1_000_000_000L),
end = Instant.fromEpochMilliseconds(1_000_003_600L),
isAllDay = false,
zoneId = "UTC",
)
}
repo.importEvents(3L, events)
assertThat(sync.requests).containsExactly(auto(google))
}
@Test
fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = fake().apply { writeError = IllegalStateException("boom") }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThrows<IllegalStateException> { repo.deleteEvent(10L) }
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest {
val throwing = RecordingSyncRequester(accepts = false)
val source = fake().apply { nextInsertId = 77L }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing)
assertThat(repo.createEvent(form(1L))).isEqualTo(77L)
}
@Test
fun `manual sync asks each visible synced account once, as manual`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = fake().apply {
calendarsResult = calendarsResult + cal(5L, SyncAccount("hidden@dav", "bitfire.at.davdroid"), visible = false)
}
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested)
assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true))
}
@Test
fun `manual sync with only local calendars has nothing to sync`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val source = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(4L, local)) }
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync)
assertThat(sync.requests).isEmpty()
}
@Test
fun `manual sync the system refuses reports a failure`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(accepts = false)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Failed)
}
@Test
fun `syncAccounts skips local, invisible and blank accounts`() {
val calendars = listOf(
cal(1L, dav),
cal(2L, dav),
cal(3L, google, visible = false),
cal(4L, local),
cal(5L, SyncAccount("", "com.google")),
)
assertThat(calendars.syncAccounts()).containsExactly(dav)
}
@Test
fun `accounts without a calendar sync adapter are never asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(adapterTypes = setOf(dav.type))
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.createEvent(form(3L))
assertThat(sync.requests).isEmpty()
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested)
assertThat(sync.requests).containsExactly(Request(dav, true))
}
@Test
fun `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()).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()).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()).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()).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()).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()).isEqualTo(SyncRequestResult.NothingToSync)
}
@Test
fun `a dismissed account that becomes visible is still asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(dav, dismissed = true)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
assertThat(repo.syncTargets.first().dismissed).isEmpty()
}
}
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.testDataStore
import de.jeanlucmakiola.calendula.testPrefs
import kotlinx.coroutines.flow.first
@@ -109,18 +108,4 @@ class CalendarPrefsTest {
prefs.setVisibilityNoticePending(false)
assertThat(prefs.visibilityNoticePending.first()).isFalse()
}
@Test
fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest {
val prefs = testPrefs(tempDir)
val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid")
val google = SyncAccount("me@dav.example/cal, 1", "com.google")
prefs.setSyncAccessDismissed(dav, dismissed = true)
prefs.setSyncAccessDismissed(google, dismissed = true)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google)
prefs.setSyncAccessDismissed(dav, dismissed = false)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(google)
}
}
@@ -616,6 +616,66 @@ class SettingsPrefsTest {
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 45)
}
@Test
fun `per-calendar hidden views round-trip and clear back to every view`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.perCalendarHiddenViews.first()).isEmpty()
prefs.applyCalendarHiddenChanges(7L, listOf(CalendarView.Month, CalendarView.Agenda).associateWith { true })
prefs.applyCalendarHiddenChanges(9L, listOf(CalendarView.MultiDay).associateWith { true })
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(
7L, setOf(CalendarView.Month, CalendarView.Agenda),
9L, setOf(CalendarView.MultiDay),
)
prefs.clearCalendarHiddenViews(7L)
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.MultiDay))
// One write can hide some views and show others, leaving the rest alone.
prefs.applyCalendarHiddenChanges(9L, mapOf(CalendarView.MultiDay to false, CalendarView.Day to true))
assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.Day))
}
@Test
fun `toggling one hidden view keeps the others and clears the entry when empty`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = true)
prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = true)
assertThat(prefs.perCalendarHiddenViews.first())
.containsExactly(7L, setOf(CalendarView.Month, CalendarView.Week))
prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = false)
prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = false)
assertThat(prefs.perCalendarHiddenViews.first()).isEmpty()
}
@Test
fun `garbage hidden-views entries are dropped, the rest survive`(
@TempDir tempDir: Path,
) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
// A bad id, only an unknown view, no separator, and a good entry with one unknown view.
m[stringPreferencesKey("per_calendar_hidden_views")] = "x=Month;7=Year;8;9=Month,Year,Agenda"
m
}
assertThat(prefs.perCalendarHiddenViews.first())
.containsExactly(9L, setOf(CalendarView.Month, CalendarView.Agenda))
}
@Test
fun `hidden views serialise in view order and drop empty entries`() {
val stored = mapOf(
3L to setOf(CalendarView.Agenda, CalendarView.Month),
1L to emptySet(),
).toStoredHiddenViews()
assertThat(stored).isEqualTo("3=Month,Agenda")
assertThat(emptyMap<Long, Set<CalendarView>>().toStoredHiddenViews()).isNull()
assertThat(parseHiddenViews(stored)).containsExactly(3L, setOf(CalendarView.Month, CalendarView.Agenda))
}
@Test
fun `resolveDefaultEventDuration prefers the calendar's own length`() {
val overrides = mapOf(7L to 480)
@@ -1,132 +0,0 @@
package de.jeanlucmakiola.calendula.ui.common
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.MainDispatcherExtension
import de.jeanlucmakiola.calendula.RecordingSyncRequester
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.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 `in flight until the provider next reports a change`(@TempDir dir: Path) = runTest(dispatcher) {
val (vm, source) = viewModel(dir)
vm.requestSync()
runCurrent()
assertThat(vm.inFlight.value).isTrue()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested)
source.tick()
runCurrent()
assertThat(vm.inFlight.value).isFalse()
}
@Test
fun `in flight ends on its own when nothing changes`(@TempDir dir: Path) = runTest(dispatcher) {
val (vm, _) = viewModel(dir)
vm.requestSync()
advanceTimeBy(15_001L)
assertThat(vm.inFlight.value).isFalse()
}
@Test
fun `a tap while in flight asks only once`(@TempDir dir: Path) = runTest(dispatcher) {
val sync = RecordingSyncRequester()
val (vm, _) = viewModel(dir, sync)
vm.requestSync()
runCurrent()
vm.requestSync()
runCurrent()
assertThat(sync.requests).hasSize(1)
}
@Test
fun `a refused request stops at once and says so`(@TempDir dir: Path) = runTest(dispatcher) {
val (vm, _) = viewModel(dir, RecordingSyncRequester(accepts = false))
vm.requestSync()
runCurrent()
assertThat(vm.inFlight.value).isFalse()
assertThat(vm.result.value).isEqualTo(SyncRequestResult.Failed)
vm.consumeResult()
assertThat(vm.result.value).isNull()
}
@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)))
}
}
@@ -0,0 +1,100 @@
package de.jeanlucmakiola.calendula.ui.common
import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.testEvent
import de.jeanlucmakiola.calendula.testRepository
import de.jeanlucmakiola.calendula.testSettings
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
class ViewHiddenCalendarsTest {
private val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000_000_000L)
private fun event(id: Long, calendarId: Long) = testEvent(
id = id,
calendarId = calendarId,
title = "E $id",
start = Instant.fromEpochMilliseconds(1_000_000_000L),
end = Instant.fromEpochMilliseconds(1_000_003_600L),
color = 0,
)
private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true)
@Test
fun `calendarsHiddenIn picks only the calendars hidden in that view`() {
val map = mapOf(
1L to setOf(CalendarView.Month),
2L to setOf(CalendarView.Month, CalendarView.Agenda),
3L to setOf(CalendarView.Week),
)
assertThat(map.calendarsHiddenIn(CalendarView.Month)).containsExactly(1L, 2L)
assertThat(map.calendarsHiddenIn(CalendarView.Agenda)).containsExactly(2L)
assertThat(map.calendarsHiddenIn(CalendarView.Day)).isEmpty()
}
@Test
fun `instancesWithout drops a calendar only in the views it is hidden in`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(calendar(1L), calendar(2L))
instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) }
}
val settings = testSettings(tempDir)
val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings)
settings.applyCalendarHiddenChanges(2L, listOf(CalendarView.Month).associateWith { true })
val hidden = settings.perCalendarHiddenViews
assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Month, backgroundScope)).first().map { it.eventId })
.containsExactly(10L)
assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Week, backgroundScope)).first().map { it.eventId })
.containsExactly(10L, 20L)
// The repository itself, which reminders and search build on, is untouched.
assertThat(repo.instances(range).first().map { it.eventId }).containsExactly(10L, 20L)
}
@Test
fun `instancesWithout re-filters live when the setting changes`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(calendar(1L), calendar(2L))
instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) }
}
val settings = testSettings(tempDir)
val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings)
val hidden = settings.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, backgroundScope)
repo.instancesWithout(range, hidden).test {
assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L)
settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = true)
assertThat(awaitItem().map { it.eventId }).containsExactly(20L)
settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = false)
assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L)
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `a failed read hides nothing and keeps reading`() = runTest {
var reads = 0
val source = kotlinx.coroutines.flow.flow {
reads++
if (reads == 1) throw java.io.IOException("disk")
emit(mapOf(1L to setOf(CalendarView.Month)))
}
source.hidingNothingOnError().test {
assertThat(awaitItem()).isEmpty()
assertThat(awaitItem()).containsExactly(1L, setOf(CalendarView.Month))
awaitComplete()
}
}
}
@@ -0,0 +1,31 @@
package de.jeanlucmakiola.calendula.ui.filter
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import org.junit.jupiter.api.Test
class FilterUiStateTest {
private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true)
@Test
fun `hiddenOnlyIn lists the calendars the view hides on its own`() {
val state = FilterUiState.Success(
groups = listOf(calendar(1L), calendar(2L), calendar(3L)).groupByAccount(),
// 3 is hidden everywhere from the drawer already.
hidden = setOf(3L),
hiddenViews = mapOf(
1L to setOf(CalendarView.Month),
2L to setOf(CalendarView.Month, CalendarView.Week),
3L to setOf(CalendarView.Month),
// Not listed (switched off device-wide).
9L to setOf(CalendarView.Month),
),
)
assertThat(state.hiddenOnlyIn(CalendarView.Month)).containsExactly(1L, 2L)
assertThat(state.hiddenOnlyIn(CalendarView.Week)).containsExactly(2L)
assertThat(state.hiddenOnlyIn(CalendarView.Agenda)).isEmpty()
}
}
+6 -19
View File
@@ -10,24 +10,6 @@ the package list (recurring writes, save conflicts, reminder delivery).
1. **`CalendarContract` is the single source of truth.** No app database,
no caching layer, no sync code. Reads query the provider; writes go
straight back to it. Sync is DAVx5's / Google's / the system's job.
The app only *asks* for one through `ContentResolver.requestSync`: an
expedited nudge for the account after each of its own writes to a synced
calendar (#303, once per write, so a multi-row save or an import asks once
per account, and never `MANUAL`, which would override master-sync-off), and
a manual request from the drawer's "Sync now" (#240), which like the
system's own "Sync now" also runs for accounts whose auto-sync is off. Both
go through `SyncRequester` and only ask account types with a calendar sync
adapter (visible to the app via a `<queries>` entry). From Android 13 a
request naming an account the app can't see is silently dropped, and
without `GET_ACCOUNTS` that is most of them. Such accounts are not asked at
all (an account-less request would sync every account on the device); the
drawer offers "Allow sync requests" instead, which opens the system account
picker (`AccountManager.newChooseAccountIntent`) — the picked account
becomes visible to the app. Access is re-read on every request and on
every resume and drawer open, so a revoke simply puts the account back behind the
grant row. Per account the user can choose "Don't ask" instead
(`CalendarPrefs.syncAccessDismissed`); such accounts drop out of the grant
row and the receipts, and the calendar manager lists them to ask again. Whether and when the adapter syncs stays its call.
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.
@@ -407,7 +389,12 @@ pre-permission launch); `CalendarVisibilityReconciler` drains it entry by entry,
and until it does, the repository and `ReminderNotifier.post` honour it. That
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.
separate in-app declutter that never touches reminders. Narrower still is the per-view hide
(`SettingsPrefs.perCalendarHiddenViews`, #270): each view model asks for its
events through `instancesWithout(range, calendarsHiddenIn(view, …))`, which drops
the calendars hidden in that one view on top of the repository's filters; reminders, search and widgets read
the repository and never see it. The drawer's "Hide in this view" entry (#517) edits the same
set for the view on show, and the drawer's per-row "Hidden in this view" notes read it.
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 —