Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce31e506f8 | ||
|
|
74549b2ec0 | ||
|
|
efe454f200 | ||
|
|
10e18ef888 | ||
|
|
14f2dfe158 | ||
|
|
d39ceb9ee0 | ||
|
|
081675906b | ||
|
|
661300728a | ||
|
|
18b9f19a61 | ||
|
|
6b108fb585 | ||
|
|
31ba82a295 | ||
|
|
99a584a82d | ||
|
|
2e71e4dc5f | ||
|
|
955dccff2b | ||
|
|
fa999f8cf0 | ||
|
|
515c7c3d26 | ||
|
|
9b5880b719 | ||
|
|
994fc1026f |
No files matched your search
@@ -81,7 +81,7 @@ class CalendarPrefs @Inject constructor(
|
||||
}
|
||||
|
||||
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||
)
|
||||
@@ -165,8 +165,10 @@ 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 mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
|
||||
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
|
||||
val reminderChannelVersions: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.reminderChannelVersions)
|
||||
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
|
||||
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
|
||||
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
|
||||
@@ -272,27 +274,27 @@ 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)
|
||||
|
||||
/**
|
||||
* Reserve a new reminder channel version for each calendar in [floors], above
|
||||
* both its stored high-water mark and its floor, and return them. Versions
|
||||
* only grow: the system would restore a deleted channel's old settings if
|
||||
* its id came back (#518).
|
||||
*/
|
||||
suspend fun reserveReminderChannelVersions(floors: Map<Long, Int>): Map<Long, Int> {
|
||||
val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current ->
|
||||
current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) }
|
||||
}
|
||||
return floors.keys.associateWith { stored.getValue(it) }
|
||||
}
|
||||
|
||||
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
|
||||
|
||||
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) =
|
||||
prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled)
|
||||
|
||||
@@ -608,21 +610,33 @@ 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.
|
||||
*/
|
||||
val remindersEnabled: Pref<Boolean> = booleanPref("reminders_enabled", true)
|
||||
|
||||
/**
|
||||
* Calendars whose reminders Calendula doesn't post (#272), independent of
|
||||
* `Calendars.VISIBLE`: the events still show, only the notifications stop.
|
||||
*/
|
||||
val mutedReminderCalendarIds: Pref<Set<Long>> = idSetPref("muted_reminder_calendar_ids")
|
||||
|
||||
/**
|
||||
* Whether the one-time hint that some skins (Samsung) start new notification
|
||||
* categories switched off has been dismissed (#145).
|
||||
*/
|
||||
val notificationCategoryHintDismissed: Pref<Boolean> = booleanPref("notification_category_hint_dismissed", false)
|
||||
|
||||
/**
|
||||
* The highest reminder channel version handed out per calendar (#518): a
|
||||
* sound picked in the app recreates the channel under a new one. The
|
||||
* channels themselves say which version is current; this only keeps ids
|
||||
* from being reused. Serialised as `id=version;id=version`.
|
||||
*/
|
||||
val reminderChannelVersions: Pref<Map<Long, Int>> =
|
||||
nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() }
|
||||
|
||||
/**
|
||||
* Whether to offer a custom event colour on calendars that publish no colour
|
||||
* palette; synced ones without a palette (some CalDAV) may drop or overwrite
|
||||
@@ -846,11 +860,9 @@ private fun parseFormFields(stored: String?): Set<EventFormField> = when (stored
|
||||
private fun parseViewOrder(stored: String?): List<CalendarView> =
|
||||
completeViewOrder(
|
||||
stored?.split(',').orEmpty()
|
||||
.mapNotNull { it.trim().toCalendarViewOrNull() },
|
||||
.mapNotNull { name -> CalendarView.entries.firstOrNull { it.name == name.trim() } },
|
||||
)
|
||||
|
||||
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
|
||||
@@ -858,7 +870,7 @@ private fun parseQuickSwitch(stored: String?): QuickSwitchConfig {
|
||||
val token = raw.trim()
|
||||
val disabled = token.startsWith("!")
|
||||
val name = if (disabled) token.drop(1) else token
|
||||
name.toCalendarViewOrNull()?.let { it to disabled }
|
||||
CalendarView.entries.firstOrNull { it.name == name }?.let { it to disabled }
|
||||
}
|
||||
val order = completeViewOrder(parsed.map { it.first })
|
||||
// Only views explicitly stored disabled are excluded; anything appended
|
||||
@@ -1008,32 +1020,17 @@ 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>> =
|
||||
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val views = parts[1].split(LIST_SEP)
|
||||
.mapNotNullTo(mutableSetOf()) { it.trim().toCalendarViewOrNull() }
|
||||
if (views.isEmpty()) null else calendarId to views
|
||||
val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
|
||||
calendarId to version
|
||||
}.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>.toStoredVersions(): String? =
|
||||
if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" }
|
||||
|
||||
private fun Map<Long, Int>.toStoredDurations(): String =
|
||||
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
|
||||
/** The single channel every reminder posted on before they moved per calendar (#145). */
|
||||
const val LEGACY_REMINDER_CHANNEL_ID = "reminders"
|
||||
|
||||
private const val CHANNEL_PREFIX = "reminders.calendar."
|
||||
private const val GROUP_PREFIX = "reminders.account."
|
||||
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
|
||||
|
||||
private const val VERSION_SEPARATOR = ".v"
|
||||
|
||||
/**
|
||||
* The notification channel [calendarId]'s reminders post on. A sound picked in
|
||||
* the app moves it to a new [version] (#518), since a channel's sound is fixed
|
||||
* once created; version 0 is the unversioned id #145 introduced.
|
||||
*/
|
||||
fun reminderChannelId(calendarId: Long, version: Int = 0): String =
|
||||
if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version"
|
||||
|
||||
/** The calendar and version a reminder channel id names, or null for any other id. */
|
||||
fun parseReminderChannelId(channelId: String): Pair<Long, Int>? {
|
||||
if (!isReminderChannelId(channelId)) return null
|
||||
val rest = channelId.removePrefix(CHANNEL_PREFIX)
|
||||
val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null
|
||||
if (VERSION_SEPARATOR !in rest) return calendar to 0
|
||||
val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return calendar to version
|
||||
}
|
||||
|
||||
/**
|
||||
* Each calendar's current channel version: the highest one that exists, so a
|
||||
* new version only takes over once it is written. A calendar with none falls
|
||||
* back to its [highWater] mark — re-creating that id restores its own settings.
|
||||
*/
|
||||
fun currentReminderChannelVersions(existingChannelIds: Collection<String>, highWater: Map<Long, Int>): Map<Long, Int> {
|
||||
val existing = existingChannelIds.mapNotNull(::parseReminderChannelId)
|
||||
.groupBy({ it.first }, { it.second })
|
||||
.mapValues { (_, versions) -> versions.max() }
|
||||
return highWater + existing
|
||||
}
|
||||
|
||||
/** Whether [channelId] is one of the per-calendar reminder channels. */
|
||||
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
|
||||
|
||||
/** Whether [groupId] is one of the per-account reminder channel groups. */
|
||||
fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX)
|
||||
|
||||
/**
|
||||
* One account's channel group, labelled as the calendar manager labels it. The
|
||||
* app's own device calendars share a single group ([isLocal]); [ambiguous]
|
||||
* marks a [label] another group shows too, so it should name the source app.
|
||||
*/
|
||||
data class ReminderChannelGroupSpec(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val accountType: String,
|
||||
val isLocal: Boolean,
|
||||
val ambiguous: Boolean,
|
||||
)
|
||||
|
||||
data class ReminderChannelSpec(
|
||||
val id: String,
|
||||
val calendarId: Long,
|
||||
val name: String,
|
||||
/** Null only for a channel created before its calendar could be looked up. */
|
||||
val groupId: String?,
|
||||
/**
|
||||
* Whether a sync creates it up front. A calendar that syncs no events never
|
||||
* fires, so its channel only appears once something posts on it.
|
||||
*/
|
||||
val upFront: Boolean = true,
|
||||
)
|
||||
|
||||
/** What a channel already looks like in the system, as far as the plan compares it. */
|
||||
data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?)
|
||||
|
||||
data class ReminderChannelPlan(
|
||||
val groups: List<ReminderChannelGroupSpec>,
|
||||
val channels: List<ReminderChannelSpec>,
|
||||
/**
|
||||
* The [channels] a sync writes: missing up-front ones, and existing ones
|
||||
* whose name or (localized) description changed, or that still lack a group.
|
||||
*/
|
||||
val channelsToWrite: List<ReminderChannelSpec>,
|
||||
/** The [groups] holding a channel that exists or is about to be written. */
|
||||
val groupsInUse: List<ReminderChannelGroupSpec>,
|
||||
val staleChannelIds: List<String>,
|
||||
val staleGroupIds: List<String>,
|
||||
/** Stale channels kept for now, because a notification on them is still showing. */
|
||||
val keptChannelIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the reminder channels should look like for [calendars]: one channel per
|
||||
* calendar inside a group per account, which of them need writing, and the
|
||||
* reminder channels and groups in [existing] / [existingGroupIds] no calendar
|
||||
* claims any more. Ids outside the reminder namespace (the backup channel, the
|
||||
* legacy channel) are never touched.
|
||||
*/
|
||||
fun planReminderChannels(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: Collection<ExistingReminderChannel>,
|
||||
existingGroupIds: Collection<String>,
|
||||
unnamed: String,
|
||||
description: String,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan {
|
||||
val (local, synced) = calendars.partition { it.isLocal }
|
||||
val groups = buildList {
|
||||
if (local.isNotEmpty()) {
|
||||
add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false))
|
||||
}
|
||||
synced.groupByAccount().forEach { group ->
|
||||
add(
|
||||
ReminderChannelGroupSpec(
|
||||
id = accountGroupId(group.key.type, group.key.name),
|
||||
label = group.label,
|
||||
accountType = group.accountType,
|
||||
isLocal = false,
|
||||
ambiguous = group.ambiguous,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val existingById = existing.associateBy { it.id }
|
||||
val channels = calendars.map { calendar ->
|
||||
ReminderChannelSpec(
|
||||
id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0),
|
||||
calendarId = calendar.id,
|
||||
name = calendar.displayName.ifBlank { unnamed },
|
||||
groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName),
|
||||
upFront = calendar.isLocal || calendar.syncsEvents,
|
||||
)
|
||||
}
|
||||
val wantedChannels = channels.mapTo(HashSet()) { it.id }
|
||||
val wantedGroups = groups.mapTo(HashSet()) { it.id }
|
||||
val toWrite = channels.filter { spec ->
|
||||
val current = existingById[spec.id]
|
||||
if (current == null) {
|
||||
spec.upFront
|
||||
} else {
|
||||
current.name != spec.name || current.description != description ||
|
||||
(current.groupId == null && spec.groupId != null)
|
||||
}
|
||||
}
|
||||
val usedGroupIds = channels
|
||||
.filter { it.id in existingById || it in toWrite }
|
||||
.mapNotNullTo(HashSet()) { it.groupId }
|
||||
val (kept, stale) = existingById.keys
|
||||
.filter { isReminderChannelId(it) && it !in wantedChannels }
|
||||
.partition { it in showingChannelIds }
|
||||
val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId }
|
||||
return ReminderChannelPlan(
|
||||
groups = groups,
|
||||
channels = channels,
|
||||
channelsToWrite = toWrite,
|
||||
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||
staleChannelIds = stale,
|
||||
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups },
|
||||
keptChannelIds = kept,
|
||||
)
|
||||
}
|
||||
|
||||
private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name"
|
||||
|
||||
/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */
|
||||
data class ReminderChannelState(val blocked: Boolean, val groupId: String?)
|
||||
|
||||
/** Reminder notifications the system blocks, while Calendula would post them. */
|
||||
data class ReminderChannelStatus(
|
||||
val appBlocked: Boolean = false,
|
||||
val blockedCalendarIds: Set<Long> = emptySet(),
|
||||
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
|
||||
val groupBlockedCalendarIds: Set<Long> = emptySet(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the system blocks of [calendarIds]' reminders: all of them while the
|
||||
* app's notifications are off, otherwise those whose channel, or the group it
|
||||
* sits in, is switched off. A calendar without a channel yet isn't blocked.
|
||||
*/
|
||||
fun reminderChannelStatus(
|
||||
calendarIds: Collection<Long>,
|
||||
appEnabled: Boolean,
|
||||
channels: Map<String, ReminderChannelState>,
|
||||
blockedGroupIds: Set<String>,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
): ReminderChannelStatus {
|
||||
fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)]
|
||||
val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds }
|
||||
val blocked = if (!appEnabled) {
|
||||
calendarIds.toSet()
|
||||
} else {
|
||||
calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked
|
||||
}
|
||||
return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked)
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationChannelGroup
|
||||
import android.app.NotificationManager
|
||||
import android.app.NotificationManager.IMPORTANCE_DEFAULT
|
||||
import android.app.NotificationManager.IMPORTANCE_LOW
|
||||
import android.app.NotificationManager.IMPORTANCE_MIN
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The reminder notification channels: one per calendar, grouped by account
|
||||
* (#145), created up front so each calendar can be muted or given its own sound
|
||||
* in the system settings before it ever fires.
|
||||
*
|
||||
* A channel the user has touched keeps their settings; [sync] only creates the
|
||||
* missing ones, renames changed ones, and deletes those whose calendar is gone.
|
||||
* A sound picked in the app ([setSound], #518) recreates the channel under the
|
||||
* calendar's next version; the old one goes once nothing shows on it.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderChannels @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) {
|
||||
private val manager: NotificationManager
|
||||
get() = context.getSystemService(NotificationManager::class.java)
|
||||
|
||||
/** What the last [sync] saw, so an unchanged provider costs no channel writes. */
|
||||
@Volatile
|
||||
private var lastSync: Any? = null
|
||||
|
||||
/**
|
||||
* Bring the channels in line with the provider's calendars. An empty
|
||||
* snapshot changes nothing: that is a provider hiccup far more often than
|
||||
* every calendar gone at once.
|
||||
*/
|
||||
@Synchronized
|
||||
fun sync() {
|
||||
val calendars = calendarDataSource.calendars()
|
||||
if (calendars.isEmpty()) return
|
||||
val manager = manager
|
||||
val existing = manager.notificationChannels
|
||||
val existingIds = existing.mapTo(HashSet()) { it.id }
|
||||
val versions = currentVersions(existingIds).also { knownVersions = it }
|
||||
if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||
val groups = manager.notificationChannelGroups
|
||||
val groupIds = groups.map { it.id }
|
||||
// Active notifications are only read when there is something stale to protect.
|
||||
val plan = plan(calendars, existing, groupIds, versions).let { draft ->
|
||||
if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds))
|
||||
}
|
||||
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
|
||||
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
|
||||
val groupNames = groups.associate { it.id to it.name?.toString() }
|
||||
write(
|
||||
groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) },
|
||||
channels = plan.channelsToWrite,
|
||||
existing = existing,
|
||||
)
|
||||
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
|
||||
val legacyGone = retireLegacyChannel()
|
||||
// A kept channel still has to go once its notification does, so don't cache.
|
||||
lastSync = if (plan.keptChannelIds.isEmpty()) {
|
||||
syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): Any = listOf(
|
||||
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||
Locale.getDefault(),
|
||||
channelIds,
|
||||
versions,
|
||||
)
|
||||
|
||||
/**
|
||||
* The current versions last resolved under the lock ([sync], [channelFor]).
|
||||
* Only [recreate], under the same lock, moves a calendar higher and updates
|
||||
* it, so a hit whose channel still exists is current.
|
||||
*/
|
||||
@Volatile
|
||||
private var knownVersions: Map<Long, Int> = emptyMap()
|
||||
|
||||
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
|
||||
currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() })
|
||||
|
||||
/** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */
|
||||
private fun showingChannelIds(candidates: Collection<String>): Set<String> = runCatching {
|
||||
manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId }
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "Could not read active notifications", e)
|
||||
candidates.toSet()
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel to post [calendarId]'s reminder on, created first if a sync
|
||||
* has not got to it yet. Null when the calendar no longer exists. Should the
|
||||
* calendar lookup fail or come back empty, the channel is still created,
|
||||
* plainly named and ungrouped, for the next sync to name and file — a
|
||||
* reminder is never lost to its channel.
|
||||
*/
|
||||
@Synchronized
|
||||
fun channelFor(calendarId: Long): String? {
|
||||
val manager = manager
|
||||
knownVersions[calendarId]?.let { version ->
|
||||
val known = reminderChannelId(calendarId, version)
|
||||
if (manager.getNotificationChannel(known) != null) return known
|
||||
}
|
||||
val existing = manager.notificationChannels
|
||||
val versions = currentVersions(existing.map { it.id }).also { knownVersions = it }
|
||||
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
|
||||
if (existing.any { it.id == id }) return id
|
||||
val calendars = try {
|
||||
calendarDataSource.calendars()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not look up calendar $calendarId for its channel", e)
|
||||
emptyList()
|
||||
}
|
||||
val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)
|
||||
if (calendars.isEmpty()) {
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
return id
|
||||
}
|
||||
val plan = plan(calendars, existing, emptyList(), versions)
|
||||
val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null
|
||||
try {
|
||||
val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id }
|
||||
write(
|
||||
groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups },
|
||||
channels = listOf(spec),
|
||||
existing = existing,
|
||||
)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not file the channel of calendar $calendarId", e)
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Run [block] with [calendarId]'s channel held: no sound pick or sync can
|
||||
* move or retire it until [block] returns. Null, without running [block],
|
||||
* when the calendar is gone or its channel can't be made; [block]'s own
|
||||
* failures propagate.
|
||||
*/
|
||||
@Synchronized
|
||||
fun <T> withChannel(calendarId: Long, block: (String) -> T): T? {
|
||||
val channelId = try {
|
||||
channelFor(calendarId)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No channel for calendar $calendarId", e)
|
||||
null
|
||||
}
|
||||
return channelId?.let(block)
|
||||
}
|
||||
|
||||
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||
val manager = manager
|
||||
val appEnabled = manager.areNotificationsEnabled()
|
||||
val existing = manager.notificationChannels
|
||||
val channels = existing.associate {
|
||||
it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group)
|
||||
}
|
||||
val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }
|
||||
return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys))
|
||||
}
|
||||
|
||||
/** A "Silent" (low) channel keeps its sound but never plays it. */
|
||||
private fun NotificationChannel.audibleSound(): Uri? =
|
||||
sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW }
|
||||
|
||||
/**
|
||||
* The sound each of [calendarIds]' channels plays; null is silent. A
|
||||
* calendar whose channel doesn't exist yet is left out.
|
||||
*/
|
||||
fun sounds(calendarIds: Collection<Long>): Map<Long, Uri?> {
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val versions = currentVersions(byId.keys)
|
||||
return calendarIds.mapNotNull { id ->
|
||||
byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() }
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
/**
|
||||
* Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is
|
||||
* fixed once created, so each moves to a new channel version carrying over
|
||||
* everything else, and the old one retires in the sync that follows (#518). Calendars without a
|
||||
* channel are skipped unless [createMissing]. Returns whether every move
|
||||
* went through.
|
||||
*/
|
||||
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean): Boolean {
|
||||
if (createMissing) calendarIds.forEach(::channelFor)
|
||||
val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id }
|
||||
val current = currentVersions(existingIds)
|
||||
val floors = calendarIds
|
||||
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
|
||||
.associateWith { (current[it] ?: 0) + 1 }
|
||||
if (floors.isEmpty()) return false
|
||||
val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
|
||||
// Retire the old versions now, or each calendar shows twice in system settings until the next scan.
|
||||
try {
|
||||
sync()
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Old channel versions left to the next sync", e)
|
||||
}
|
||||
return applied
|
||||
}
|
||||
|
||||
/**
|
||||
* Create each calendar's [versions] from its current channel. The old one is
|
||||
* left to the next [sync], which retires it once nothing shows on it.
|
||||
*/
|
||||
@Synchronized
|
||||
private fun recreate(versions: Map<Long, Int>, sound: Uri?): Boolean {
|
||||
val manager = manager
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val current = currentReminderChannelVersions(byId.keys, emptyMap())
|
||||
var allApplied = true
|
||||
versions.forEach { (calendarId, version) ->
|
||||
val from = current[calendarId]?.takeIf { it < version }
|
||||
val old = from?.let { byId[reminderChannelId(calendarId, it)] }
|
||||
if (old == null) {
|
||||
allApplied = false
|
||||
return@forEach
|
||||
}
|
||||
try {
|
||||
// Picking a sound asks for one, which a "Silent" (low) channel would never play.
|
||||
val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) {
|
||||
IMPORTANCE_DEFAULT
|
||||
} else {
|
||||
old.importance
|
||||
}
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply {
|
||||
description = old.description
|
||||
old.group?.let { group = it }
|
||||
inheritFrom(old)
|
||||
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
|
||||
},
|
||||
)
|
||||
knownVersions = knownVersions + (calendarId to version)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not move calendar $calendarId to a new sound", e)
|
||||
allApplied = false
|
||||
}
|
||||
}
|
||||
lastSync = null
|
||||
return allApplied
|
||||
}
|
||||
|
||||
private fun plan(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: List<NotificationChannel>,
|
||||
existingGroupIds: List<String>,
|
||||
versions: Map<Long, Int>,
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan = planReminderChannels(
|
||||
calendars = calendars,
|
||||
existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) },
|
||||
existingGroupIds = existingGroupIds,
|
||||
unnamed = context.getString(R.string.calendar_unnamed),
|
||||
description = context.getString(R.string.reminder_channel_description),
|
||||
versions = versions,
|
||||
showingChannelIds = showingChannelIds,
|
||||
)
|
||||
|
||||
private fun write(
|
||||
groups: List<ReminderChannelGroupSpec>,
|
||||
channels: List<ReminderChannelSpec>,
|
||||
existing: List<NotificationChannel>,
|
||||
) {
|
||||
val manager = manager
|
||||
if (groups.isNotEmpty()) {
|
||||
manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) })
|
||||
}
|
||||
if (channels.isEmpty()) return
|
||||
val byId = existing.associateBy { it.id }
|
||||
val description = context.getString(R.string.reminder_channel_description)
|
||||
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
|
||||
// Importance only applies on creation; an existing channel keeps its own.
|
||||
manager.createNotificationChannels(
|
||||
channels.map { spec ->
|
||||
val current = byId[spec.id]
|
||||
NotificationChannel(
|
||||
spec.id,
|
||||
spec.name,
|
||||
current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
this.description = description
|
||||
spec.groupId?.let { group = it }
|
||||
if (current == null && template != null) inheritFrom(template)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry a channel's sound, vibration, lights and badge over to a new one: the
|
||||
* legacy channel to a per-calendar one on upgrade, or a calendar's channel to
|
||||
* its next version (#518). Lock-screen visibility and a DND override can't
|
||||
* follow: the system resets both on channels an app creates.
|
||||
*/
|
||||
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
|
||||
setSound(template.sound, template.audioAttributes)
|
||||
// The pattern setter also flips vibration on or off, so it goes first.
|
||||
vibrationPattern = template.vibrationPattern
|
||||
enableVibration(template.shouldVibrate())
|
||||
enableLights(template.shouldShowLights())
|
||||
lightColor = template.lightColor
|
||||
setShowBadge(template.canShowBadge())
|
||||
// Only honoured with Do Not Disturb access, so usually left to the user.
|
||||
setBypassDnd(template.canBypassDnd())
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the pre-#145 channel once the per-calendar ones carry its settings,
|
||||
* but not while a reminder posted on it is still on screen — deleting the
|
||||
* channel would take that notification with it. Returns whether it is gone.
|
||||
*/
|
||||
private fun retireLegacyChannel(): Boolean {
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
|
||||
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID))
|
||||
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
|
||||
return !showing
|
||||
}
|
||||
|
||||
private fun groupLabel(group: ReminderChannelGroupSpec): String {
|
||||
if (group.isLocal) return context.getString(R.string.calendars_local_header)
|
||||
val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) }
|
||||
if (!group.ambiguous) return name
|
||||
return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderChannels"
|
||||
|
||||
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
@@ -29,8 +27,8 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||
* the event's detail screen.
|
||||
* Posts one notification per occurrence on its calendar's channel
|
||||
* ([ReminderChannels], #145). Tapping opens the event's detail screen.
|
||||
*
|
||||
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||
@@ -43,6 +41,7 @@ class ReminderNotifier @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val channels: ReminderChannels,
|
||||
) {
|
||||
|
||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||
@@ -53,19 +52,19 @@ class ReminderNotifier @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* The single choke point for "this calendar is switched off", covering the
|
||||
* two paths that reach [post] around the scan's own filter: a snooze armed
|
||||
* before the switch-off, and a read-only install whose switch lives in
|
||||
* [CalendarPrefs].
|
||||
* The single choke point for "this calendar posts no reminders": switched
|
||||
* off (also covering a snooze armed before the switch-off, and a read-only
|
||||
* install whose switch lives in [CalendarPrefs]), or its notifications
|
||||
* turned off in Calendula's own settings (#272).
|
||||
*/
|
||||
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||
|
||||
/** Post [alert], unless its calendar is switched off. */
|
||||
/** Post [alert], unless its calendar is silenced or gone. */
|
||||
suspend fun post(alert: ReminderAlert) {
|
||||
if (isSilenced(alert.calendarId)) return
|
||||
ensureChannel()
|
||||
val title = displayTitle(alert)
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
@@ -88,7 +87,15 @@ class ReminderNotifier @Inject constructor(
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
// Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post.
|
||||
val posted = channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) }
|
||||
if (posted == null) {
|
||||
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun notify(alert: ReminderAlert, channelId: String, title: String, text: String) {
|
||||
val notification = NotificationCompat.Builder(context, channelId)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
@@ -153,7 +160,7 @@ class ReminderNotifier @Inject constructor(
|
||||
private fun cancelLegacy(alert: ReminderAlert) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
manager.activeNotifications
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID }
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||
.filter { it.notification.`when` == alert.beginMillis }
|
||||
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||
@@ -181,21 +188,8 @@ class ReminderNotifier @Inject constructor(
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
/** Channel creation is idempotent; re-running refreshes the localized name. */
|
||||
private fun ensureChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.reminder_channel_name),
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = context.getString(R.string.reminder_channel_description)
|
||||
}
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderNotifier"
|
||||
const val CHANNEL_ID = "reminders"
|
||||
|
||||
// One id, distinct tags: the tag (occurrence) already keys the
|
||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||
|
||||
@@ -43,6 +43,7 @@ class ReminderScanner @Inject constructor(
|
||||
private val source: ReminderInstanceSource,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val notifier: ReminderNotifier,
|
||||
private val channels: ReminderChannels,
|
||||
private val snoozes: ReminderSnoozeScheduler,
|
||||
private val alarms: ReminderAlarmScheduler,
|
||||
private val state: ReminderStatePrefs,
|
||||
@@ -85,10 +86,14 @@ class ReminderScanner @Inject constructor(
|
||||
return
|
||||
}
|
||||
|
||||
syncChannels()
|
||||
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
|
||||
// Reach into the past too: an all-day "at time of event" encodes to a
|
||||
// negative offset, and a catch-up pass needs the occurrences it missed.
|
||||
// Calendars muted in-app (#272) plan nothing, so they arm no wake-ups.
|
||||
val muted = settingsPrefs.mutedReminderCalendarIds.first()
|
||||
val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead)
|
||||
.filter { it.calendarId !in muted }
|
||||
val planned = planReminders(
|
||||
instances = occurrences,
|
||||
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
|
||||
@@ -117,6 +122,19 @@ class ReminderScanner @Inject constructor(
|
||||
alarms.scheduleScan(schedule.nextAlarmMillis)
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider change re-scans, so a calendar added, renamed or removed keeps
|
||||
* its channel in step here. Skipped while reminders are off, when the
|
||||
* channels have nothing to do. A failure never costs the reminders.
|
||||
*/
|
||||
private fun syncChannels() {
|
||||
try {
|
||||
channels.sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Reminder channel sync failed", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||
|
||||
/**
|
||||
|
||||
@@ -309,7 +309,3 @@ 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 }
|
||||
@@ -97,8 +97,6 @@ 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
|
||||
@@ -194,15 +192,10 @@ 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
|
||||
}
|
||||
@@ -218,7 +211,6 @@ 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,7 +316,6 @@ fun CalendarHost(
|
||||
requests.importUri = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
showViewCalendars = false
|
||||
importUri = requestedImportUri
|
||||
importForceMany = false
|
||||
importSession++
|
||||
@@ -342,7 +333,6 @@ fun CalendarHost(
|
||||
requests.insert = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
showViewCalendars = false
|
||||
if (importForm == null) {
|
||||
openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true)
|
||||
} else {
|
||||
@@ -359,7 +349,6 @@ fun CalendarHost(
|
||||
fun dismissCoveringOverlays(keepCreate: Boolean = false) {
|
||||
showSettings = false
|
||||
showSearch = false
|
||||
showViewCalendars = false
|
||||
showCalendars = false
|
||||
showBackup = false
|
||||
detailKey = null
|
||||
@@ -569,15 +558,6 @@ 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.
|
||||
@@ -608,10 +588,6 @@ fun CalendarHost(
|
||||
onOpenSettings()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
onHideInView = {
|
||||
showViewCalendars = true
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
|
||||
@@ -15,9 +15,6 @@ 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
|
||||
@@ -49,8 +46,6 @@ 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,
|
||||
@@ -143,7 +138,7 @@ class AgendaViewModel @Inject constructor(
|
||||
)
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(window, hiddenHere),
|
||||
repository.instances(window),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildState(params, calendars, instances, today)
|
||||
|
||||
@@ -3,7 +3,6 @@ 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
|
||||
@@ -46,7 +45,6 @@ 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
|
||||
@@ -56,7 +54,6 @@ 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
|
||||
@@ -75,10 +72,6 @@ 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
|
||||
@@ -99,7 +92,6 @@ 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
|
||||
@@ -138,19 +130,14 @@ fun CalendarsScreen(
|
||||
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
|
||||
val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle()
|
||||
val error by viewModel.error.collectAsStateWithLifecycle()
|
||||
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) }
|
||||
|
||||
// The editor and the picker seed from the stored hidden views, so both wait for the first read.
|
||||
if (editorId != null && loadedHiddenViews != null) {
|
||||
if (editorId != null) {
|
||||
val editing = calendars.firstOrNull { it.id == editorId }
|
||||
CalendarEditor(
|
||||
sessionKey = editorSession,
|
||||
@@ -158,15 +145,13 @@ 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, views ->
|
||||
onSave = { name, color, description ->
|
||||
val id = editorId
|
||||
if (id == null || id == NEW_CALENDAR_ID) {
|
||||
viewModel.createCalendar(name, color, description, views)
|
||||
viewModel.createCalendar(name, color, description)
|
||||
} else {
|
||||
viewModel.updateCalendar(id, name, color, description, views)
|
||||
viewModel.updateCalendar(id, name, color, description)
|
||||
}
|
||||
editorId = null
|
||||
},
|
||||
@@ -180,7 +165,6 @@ fun CalendarsScreen(
|
||||
CalendarsList(
|
||||
local = calendars.filter { it.isLocal },
|
||||
synced = calendars.filterNot { it.isLocal },
|
||||
hiddenViews = hiddenViews,
|
||||
error = error,
|
||||
onConsumeError = viewModel::consumeError,
|
||||
onOpenBackup = onOpenBackup,
|
||||
@@ -188,26 +172,9 @@ 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,
|
||||
)
|
||||
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 },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +182,6 @@ fun CalendarsScreen(
|
||||
private fun CalendarsList(
|
||||
local: List<CalendarSource>,
|
||||
synced: List<CalendarSource>,
|
||||
hiddenViews: Map<Long, Set<CalendarView>>,
|
||||
error: Boolean,
|
||||
onConsumeError: () -> Unit,
|
||||
onOpenBackup: () -> Unit,
|
||||
@@ -223,7 +189,6 @@ private fun CalendarsList(
|
||||
visible: Boolean,
|
||||
onAdd: () -> Unit,
|
||||
onEdit: (CalendarSource) -> Unit,
|
||||
onEditHiddenViews: (CalendarSource) -> Unit,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
|
||||
) {
|
||||
@@ -276,7 +241,6 @@ private fun CalendarsList(
|
||||
local.forEachIndexed { index, calendar ->
|
||||
CalendarManagerRow(
|
||||
calendar = calendar,
|
||||
hiddenViews = hiddenViews[calendar.id].orEmpty(),
|
||||
last = index == local.lastIndex,
|
||||
onSetVisible = onSetVisible,
|
||||
onClick = { onEdit(calendar) },
|
||||
@@ -351,10 +315,8 @@ private fun CalendarsList(
|
||||
ordered.forEachIndexed { index, calendar ->
|
||||
CalendarManagerRow(
|
||||
calendar = calendar,
|
||||
hiddenViews = hiddenViews[calendar.id].orEmpty(),
|
||||
last = index == ordered.lastIndex,
|
||||
onSetVisible = onSetVisible,
|
||||
onClick = { onEditHiddenViews(calendar) },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -377,32 +339,19 @@ internal fun CalendarEditor(
|
||||
initialName: String,
|
||||
initialColor: Int,
|
||||
initialDescription: String,
|
||||
onSave: (name: String, color: Int, description: String?, hiddenChanges: Map<CalendarView, Boolean>) -> Unit,
|
||||
onSave: (name: String, color: Int, description: String?) -> 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) {
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
val commit = { if (valid) onSave(name.trim(), color, description.trim().ifEmpty { null }) }
|
||||
|
||||
FullScreenPicker(
|
||||
title = stringResource(
|
||||
@@ -454,16 +403,6 @@ 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 })
|
||||
@@ -471,17 +410,6 @@ 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 },
|
||||
@@ -708,7 +636,7 @@ private fun EditorSectionLabel(text: String) {
|
||||
* plain writable one (#76), then its own description.
|
||||
*/
|
||||
@Composable
|
||||
private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<CalendarView>): String? {
|
||||
private fun calendarRowSummary(calendar: CalendarSource): String? {
|
||||
val states = calendar.stateLabels().map { label ->
|
||||
stringResource(
|
||||
when (label) {
|
||||
@@ -718,8 +646,7 @@ private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<Calend
|
||||
},
|
||||
)
|
||||
}
|
||||
val hidden = if (hiddenViews.isEmpty()) null else hiddenViewsSummary(hiddenViews)
|
||||
val parts = states + listOfNotNull(hidden, calendar.description?.takeIf { it.isNotBlank() })
|
||||
val parts = states + listOfNotNull(calendar.description?.takeIf { it.isNotBlank() })
|
||||
return parts.joinToString(" · ").ifEmpty { null }
|
||||
}
|
||||
|
||||
@@ -735,7 +662,6 @@ private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<Calend
|
||||
@Composable
|
||||
private fun CalendarManagerRow(
|
||||
calendar: CalendarSource,
|
||||
hiddenViews: Set<CalendarView>,
|
||||
last: Boolean,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
onClick: (() -> Unit)? = null,
|
||||
@@ -743,7 +669,7 @@ private fun CalendarManagerRow(
|
||||
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = calendarRowSummary(calendar, hiddenViews),
|
||||
summary = calendarRowSummary(calendar),
|
||||
position = if (last) Position.Bottom else Position.Middle,
|
||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
dimmed = disabled,
|
||||
@@ -763,51 +689,6 @@ 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,7 +3,6 @@ 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
|
||||
@@ -16,8 +15,6 @@ 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
|
||||
@@ -107,19 +104,6 @@ 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()
|
||||
|
||||
@@ -155,41 +139,16 @@ class CalendarsViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
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 createCalendar(displayName: String, color: Int, description: String?) = write {
|
||||
repository.createLocalCalendar(displayName, color, description)
|
||||
}
|
||||
|
||||
fun updateCalendar(
|
||||
id: Long,
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
hiddenChanges: Map<CalendarView, Boolean>,
|
||||
) = write {
|
||||
fun updateCalendar(id: Long, displayName: String, color: Int, description: String?) = 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)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -72,11 +73,13 @@ fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||
@Composable
|
||||
fun sourceAppName(accountType: String): String {
|
||||
val context = LocalContext.current
|
||||
return remember(accountType) {
|
||||
val pm = context.packageManager
|
||||
val packages = sourceAppPackages(context, accountType)
|
||||
packages.firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
}
|
||||
return remember(accountType) { sourceAppLabel(context, accountType) }
|
||||
}
|
||||
|
||||
/** [sourceAppName] outside composition, e.g. for notification channel groups. */
|
||||
fun sourceAppLabel(context: Context, accountType: String): String {
|
||||
val pm = context.packageManager
|
||||
return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
}
|
||||
@@ -70,7 +70,6 @@ fun CalendarDrawer(
|
||||
onSelectView: (CalendarView) -> Unit,
|
||||
onJumpToDate: (LocalDate) -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
onHideInView: () -> Unit,
|
||||
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
|
||||
) {
|
||||
var showDatePicker by remember { mutableStateOf(false) }
|
||||
@@ -113,7 +112,7 @@ fun CalendarDrawer(
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
DrawerSectionHeader(stringResource(R.string.filter_title))
|
||||
CalendarFilterList(currentView = currentView, onHideInView = onHideInView)
|
||||
CalendarFilterList()
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
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,23 +4,15 @@ 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
|
||||
@@ -30,26 +22,20 @@ 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). 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).
|
||||
* re-filters live. Three states (Loading / Failure / Success).
|
||||
*/
|
||||
@Composable
|
||||
fun CalendarFilterList(
|
||||
currentView: CalendarView,
|
||||
onHideInView: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: FilterViewModel = hiltViewModel(),
|
||||
) {
|
||||
@@ -57,18 +43,12 @@ fun CalendarFilterList(
|
||||
when (val s = state) {
|
||||
FilterUiState.Loading -> FilterLoading(modifier)
|
||||
is FilterUiState.Failure -> FilterMessage(s.reason, 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,
|
||||
)
|
||||
}
|
||||
is FilterUiState.Success -> FilterList(
|
||||
groups = s.groups,
|
||||
hidden = s.hidden,
|
||||
onSetVisible = viewModel::setVisible,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,9 +61,6 @@ 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,
|
||||
) {
|
||||
@@ -104,7 +81,6 @@ 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) },
|
||||
@@ -118,32 +94,11 @@ 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
|
||||
internal fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
private fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
@@ -164,7 +119,7 @@ internal fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) {
|
||||
private 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,8 +2,6 @@ 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
|
||||
@@ -13,22 +11,9 @@ import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
sealed interface FilterUiState {
|
||||
data object Loading : FilterUiState
|
||||
data class Failure(val reason: FailureReason) : FilterUiState
|
||||
/**
|
||||
* A calendar shows when its id is *not* in [hidden]; [hiddenViews] are the
|
||||
* views each calendar is hidden in regardless (#270).
|
||||
*/
|
||||
/** A calendar shows when its id is *not* in [hidden]. */
|
||||
data class Success(
|
||||
val groups: List<CalendarAccountGroup>,
|
||||
val hidden: Set<Long>,
|
||||
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 }
|
||||
}
|
||||
}
|
||||
) : FilterUiState
|
||||
}
|
||||
@@ -1,20 +1,15 @@
|
||||
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
|
||||
@@ -28,7 +23,6 @@ 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() {
|
||||
|
||||
@@ -36,9 +30,7 @@ class FilterViewModel @Inject constructor(
|
||||
combine(
|
||||
repository.calendars(),
|
||||
prefs.hiddenCalendarIds,
|
||||
// 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, hidden ->
|
||||
// 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 }
|
||||
@@ -46,7 +38,7 @@ class FilterViewModel @Inject constructor(
|
||||
if (failure != null) {
|
||||
FilterUiState.Failure(failure)
|
||||
} else {
|
||||
FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews)
|
||||
FilterUiState.Success(enabled.groupByAccount(), hidden)
|
||||
}
|
||||
}
|
||||
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
|
||||
@@ -56,19 +48,6 @@ 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 {
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
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,10 +19,7 @@ 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
|
||||
@@ -71,8 +68,6 @@ 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)
|
||||
|
||||
@@ -157,7 +152,7 @@ class MonthViewModel @Inject constructor(
|
||||
) { (ym, ws) ->
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(monthGridRange(ym, ws, zone), hiddenHere),
|
||||
repository.instances(monthGridRange(ym, ws, zone)),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildState(ym, ws, calendars, instances, today)
|
||||
@@ -229,7 +224,7 @@ class MonthViewModel @Inject constructor(
|
||||
val range = dayRange(first, last, zone)
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(range, hiddenHere),
|
||||
repository.instances(range),
|
||||
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)
|
||||
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
|
||||
/**
|
||||
* Per-calendar notifications and reminder overrides (#145, #272), reached from
|
||||
* Settings → Notifications. Calendars are listed by account as connected groups;
|
||||
* a calendar unfolds its options in place, one tone darker, inside its group.
|
||||
*/
|
||||
@Composable
|
||||
internal fun CalendarRemindersScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
var expandedCalendars by rememberSaveable { mutableStateOf(emptyList<Long>()) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
onBack = onBack,
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
GroupedHint(stringResource(R.string.settings_calendar_reminders_hint), style = MaterialTheme.typography.bodySmall)
|
||||
state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group ->
|
||||
if (groupIndex > 0) Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(accountGroupTitle(group))
|
||||
val calendars = group.calendars
|
||||
calendars.forEachIndexed { index, calendar ->
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
val notifying = calendar.id !in state.mutedReminderCalendarIds
|
||||
CalendarReminderEntry(
|
||||
calendar = calendar,
|
||||
state = state,
|
||||
position = positionOf(index, calendars.size),
|
||||
expanded = expanded,
|
||||
notifying = notifying,
|
||||
blocked = notifying && calendar.id in channelStatus.blockedCalendarIds,
|
||||
onToggleExpand = {
|
||||
expandedCalendars = if (expanded) {
|
||||
expandedCalendars - calendar.id
|
||||
} else {
|
||||
expandedCalendars + calendar.id
|
||||
}
|
||||
},
|
||||
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
|
||||
soundLabel = soundPicker.loadedSounds?.let { soundLabel(it[calendar.id]) },
|
||||
onPickSound = { soundPicker.pick(calendar.id) },
|
||||
onOpenSettings = { soundPicker.openCalendarSettings(calendar.id) },
|
||||
onOpenSpecialDates = onOpenSpecialDates,
|
||||
onEditOverride = { overrideDialog = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overrideDialog?.let { target ->
|
||||
val map = if (target.isAllDay) {
|
||||
state.perCalendarAllDayReminderOverride
|
||||
} else {
|
||||
state.perCalendarReminderOverride
|
||||
}
|
||||
ReminderDefaultPicker(
|
||||
title = stringResource(
|
||||
if (target.isAllDay) {
|
||||
R.string.settings_default_reminder_allday
|
||||
} else {
|
||||
R.string.settings_default_reminder
|
||||
},
|
||||
),
|
||||
presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS,
|
||||
selected = map.reminderOverrideFor(target.calendarId),
|
||||
allowInherit = true,
|
||||
onSelect = {
|
||||
if (target.isAllDay) {
|
||||
viewModel.setCalendarAllDayReminderOverride(target.calendarId, it)
|
||||
} else {
|
||||
viewModel.setCalendarReminderOverride(target.calendarId, it)
|
||||
}
|
||||
},
|
||||
onDismiss = { overrideDialog = null },
|
||||
leadTimeSummary = if (target.isAllDay) {
|
||||
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One calendar in its account group, with its options unfolding beneath it:
|
||||
* the notification switch and channel deep-link for every calendar, then the
|
||||
* default-reminder overrides where it takes them — or, for a special-dates
|
||||
* calendar, a link to the section that owns them.
|
||||
*/
|
||||
@Composable
|
||||
private fun CalendarReminderEntry(
|
||||
calendar: CalendarSource,
|
||||
state: SettingsUiState,
|
||||
position: Position,
|
||||
expanded: Boolean,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
onToggleExpand: () -> Unit,
|
||||
onSetNotifying: (Boolean) -> Unit,
|
||||
soundLabel: String?,
|
||||
onPickSound: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
val opensGroup = position == Position.Top || position == Position.Alone
|
||||
val closesGroup = position == Position.Bottom || position == Position.Alone
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = when {
|
||||
!notifying -> stringResource(R.string.settings_calendar_notifications_off)
|
||||
blocked -> stringResource(R.string.settings_notifications_blocked)
|
||||
else -> null
|
||||
},
|
||||
position = when {
|
||||
!expanded -> position
|
||||
opensGroup -> Position.Top
|
||||
else -> Position.Middle
|
||||
},
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
onClick = onToggleExpand,
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
val managed = calendar.id in state.managedCalendarIds
|
||||
val takesOverrides = calendar.canModifyContents && !managed
|
||||
val nested = MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
// The options round off their calendar; mid-group they keep the row gap.
|
||||
Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_notifications),
|
||||
checked = notifying,
|
||||
onCheckedChange = onSetNotifying,
|
||||
summary = stringResource(R.string.settings_calendar_notifications_hint),
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = soundLabel,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onClick = onPickSound,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_more),
|
||||
summary = if (blocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_calendar_notification_sound_hint)
|
||||
},
|
||||
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
|
||||
container = nested,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSettings,
|
||||
)
|
||||
if (managed) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
trailing = { ChevronIcon() },
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
} else if (takesOverrides) {
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = false,
|
||||
choice = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultReminderMinutes,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = true,
|
||||
choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultAllDayReminderMinutes,
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverrideRow(
|
||||
calendarId: Long,
|
||||
isAllDay: Boolean,
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
position: Position,
|
||||
container: Color,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = stringResource(
|
||||
if (isAllDay) R.string.settings_default_reminder_allday else R.string.settings_default_reminder,
|
||||
),
|
||||
summary = calendarOverrideSummary(choice, globalDefault),
|
||||
position = position,
|
||||
container = container,
|
||||
onClick = { onEditOverride(OverrideTarget(calendarId, isAllDay)) },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChevronIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
|
||||
/** Row summary for a calendar: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun calendarOverrideSummary(
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes)
|
||||
}
|
||||
+202
-130
@@ -6,22 +6,33 @@ import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -29,27 +40,28 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.DurationPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
|
||||
import de.jeanlucmakiola.calendula.ui.common.durationLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import de.jeanlucmakiola.floret.android.notificationSoundPickerIntent
|
||||
import de.jeanlucmakiola.floret.android.openNotificationSettings
|
||||
import de.jeanlucmakiola.floret.android.pickedSound
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.minutesOrEmpty
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/**
|
||||
@@ -62,7 +74,7 @@ internal fun NotificationsScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onOpenCalendarReminders: () -> Unit,
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
@@ -83,9 +95,17 @@ internal fun NotificationsScreen(
|
||||
var showAllDayReminder by remember { mutableStateOf(false) }
|
||||
var showAllDayReminderTime by remember { mutableStateOf(false) }
|
||||
var showSnooze by remember { mutableStateOf(false) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
var calendarSectionExpanded by remember { mutableStateOf(false) }
|
||||
var expandedCalendars by remember { mutableStateOf(emptySet<Long>()) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
|
||||
val openAppSettings = soundPicker.openAppSettings
|
||||
val loadedSounds = soundPicker.loadedSounds
|
||||
val pickSound = soundPicker.pick
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_section_notifications),
|
||||
@@ -93,6 +113,16 @@ internal fun NotificationsScreen(
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) {
|
||||
NotificationCategoryHint(
|
||||
onOpen = {
|
||||
viewModel.dismissNotificationCategoryHint()
|
||||
openAppSettings()
|
||||
},
|
||||
onDismiss = viewModel::dismissNotificationCategoryHint,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_reminders),
|
||||
checked = state.remindersEnabled,
|
||||
@@ -100,6 +130,25 @@ internal fun NotificationsScreen(
|
||||
summary = stringResource(R.string.settings_reminders_hint),
|
||||
position = Position.Top,
|
||||
)
|
||||
if (calendarIds.isNotEmpty()) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) },
|
||||
position = Position.Middle,
|
||||
onClick = { pickSound(ALL_CALENDARS) },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_more),
|
||||
summary = if (channelStatus.appBlocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = openAppSettings,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = reminderChoiceLabel(state.defaultReminderMinutes),
|
||||
@@ -149,84 +198,21 @@ internal fun NotificationsScreen(
|
||||
onClick = { showSnooze = true },
|
||||
)
|
||||
|
||||
// Per-calendar overrides, folded behind one header. Each writable
|
||||
// calendar may keep, drop or replace the global default, separately for
|
||||
// timed and all-day events.
|
||||
if (state.writableCalendars.isNotEmpty()) {
|
||||
if (state.reminderCalendars.isNotEmpty()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_hint),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_subtitle),
|
||||
position = Position.Alone,
|
||||
trailing = { ExpandIcon(calendarSectionExpanded) },
|
||||
onClick = { calendarSectionExpanded = !calendarSectionExpanded },
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenCalendarReminders,
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = calendarSectionExpanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
state.writableCalendars.forEach { calendar ->
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// Special-dates calendars own their reminders in their
|
||||
// own section — link there instead.
|
||||
if (calendar.id in state.managedCalendarIds) {
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
return@forEach
|
||||
}
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
position = if (expanded) Position.Top else Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
onClick = {
|
||||
expandedCalendars = if (expanded) {
|
||||
expandedCalendars - calendar.id
|
||||
} else {
|
||||
expandedCalendars + calendar.id
|
||||
}
|
||||
},
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) },
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,59 +261,80 @@ internal fun NotificationsScreen(
|
||||
onDismiss = { showAllDayReminderTime = false },
|
||||
)
|
||||
}
|
||||
overrideDialog?.let { target ->
|
||||
val map = if (target.isAllDay) {
|
||||
state.perCalendarAllDayReminderOverride
|
||||
} else {
|
||||
state.perCalendarReminderOverride
|
||||
}
|
||||
ReminderDefaultPicker(
|
||||
title = stringResource(
|
||||
if (target.isAllDay) {
|
||||
R.string.settings_default_reminder_allday
|
||||
} else {
|
||||
R.string.settings_default_reminder
|
||||
},
|
||||
),
|
||||
presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS,
|
||||
selected = map.reminderOverrideFor(target.calendarId),
|
||||
allowInherit = true,
|
||||
onSelect = {
|
||||
if (target.isAllDay) {
|
||||
viewModel.setCalendarAllDayReminderOverride(target.calendarId, it)
|
||||
} else {
|
||||
viewModel.setCalendarReminderOverride(target.calendarId, it)
|
||||
}
|
||||
},
|
||||
onDismiss = { overrideDialog = null },
|
||||
leadTimeSummary = if (target.isAllDay) {
|
||||
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** [soundTarget] meaning every calendar at once. */
|
||||
internal const val ALL_CALENDARS = Long.MIN_VALUE
|
||||
|
||||
/** What the calendars that have a channel share, sound-wise. */
|
||||
private sealed interface SharedSound {
|
||||
data object None : SharedSound
|
||||
data object Mixed : SharedSound
|
||||
data class Same(val sound: ReminderSound) : SharedSound
|
||||
}
|
||||
|
||||
private fun sharedSound(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): SharedSound {
|
||||
val distinct = calendarIds.mapNotNull { sounds[it] }.distinctBy { it.uri }
|
||||
return when (distinct.size) {
|
||||
0 -> SharedSound.None
|
||||
1 -> SharedSound.Same(distinct.single())
|
||||
else -> SharedSound.Mixed
|
||||
}
|
||||
}
|
||||
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
@Composable
|
||||
internal fun soundLabel(sound: ReminderSound?): String = when {
|
||||
sound == null -> stringResource(R.string.settings_notification_sound_default)
|
||||
sound.uri == null -> stringResource(R.string.settings_notification_sound_silent)
|
||||
sound.uri == DEFAULT_NOTIFICATION_URI -> sound.title
|
||||
?.let { stringResource(R.string.settings_notification_sound_default_named, it) }
|
||||
?: stringResource(R.string.settings_notification_sound_default)
|
||||
else -> sound.title ?: stringResource(R.string.settings_notification_sound_custom)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun globalSoundLabel(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): String =
|
||||
when (val shared = sharedSound(sounds, calendarIds)) {
|
||||
SharedSound.None -> soundLabel(null)
|
||||
SharedSound.Mixed -> stringResource(R.string.settings_notification_sound_mixed)
|
||||
is SharedSound.Same -> soundLabel(shared.sound)
|
||||
}
|
||||
|
||||
/** Samsung's One UI can start a new notification category switched off (#145). */
|
||||
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
|
||||
/** The one-time Samsung note, with a way into the app's notification settings. */
|
||||
@Composable
|
||||
private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) {
|
||||
IconInfoCard(
|
||||
icon = Icons.Outlined.Info,
|
||||
iconContentDescription = null,
|
||||
iconAlignment = Alignment.Top,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_notification_category_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) }
|
||||
TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ExternalLinkIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** A global default (empty = none) as a picker choice for selection highlighting. */
|
||||
private fun List<Int>.toReminderChoice(): ReminderOverride =
|
||||
if (isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(this)
|
||||
|
||||
/** Row summary for a calendar: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun calendarOverrideSummary(
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes)
|
||||
}
|
||||
|
||||
/** Snooze delays offered for the notification "Snooze" action, in minutes. */
|
||||
private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
||||
|
||||
@@ -372,3 +379,68 @@ private fun openBatteryOptimizationSettings(context: Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The reminder-sound picker (#518) shared by Notifications (all calendars) and the per-calendar page. */
|
||||
internal class ReminderSoundPicker(
|
||||
val loadedSounds: Map<Long, ReminderSound>?,
|
||||
val pick: (Long) -> Unit,
|
||||
val openAppSettings: () -> Unit,
|
||||
val openCalendarSettings: (Long) -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun rememberReminderSoundPicker(viewModel: SettingsViewModel, calendarIds: List<Long>): ReminderSoundPicker {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val openCalendarSettings: (Long) -> Unit = { calendarId ->
|
||||
scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) }
|
||||
}
|
||||
val openAppSettings: () -> Unit = {
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
}
|
||||
val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle()
|
||||
val sounds = loadedSounds.orEmpty()
|
||||
val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed)
|
||||
val soundUnreadableMessage = stringResource(R.string.settings_notification_sound_unreadable)
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.soundFailed.collect { failure ->
|
||||
val message = if (failure == SoundFailure.Unreadable) soundUnreadableMessage else soundFailedMessage
|
||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
// ALL_CALENDARS, a calendar id, or null when no pick is pending.
|
||||
var soundTarget by rememberSaveable { mutableStateOf<Long?>(null) }
|
||||
val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
val target = soundTarget
|
||||
soundTarget = null
|
||||
val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult
|
||||
when (target) {
|
||||
null -> Unit
|
||||
ALL_CALENDARS -> viewModel.setReminderSoundForAll(picked.uri)
|
||||
else -> viewModel.setReminderSound(target, picked.uri)
|
||||
}
|
||||
}
|
||||
val pickSoundTitle = stringResource(R.string.settings_notification_sound)
|
||||
val pickSound: (Long) -> Unit = pick@{ target ->
|
||||
if (soundTarget != null) return@pick
|
||||
val current = if (target == ALL_CALENDARS) {
|
||||
(sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound
|
||||
} else {
|
||||
sounds[target]
|
||||
}
|
||||
soundTarget = target
|
||||
try {
|
||||
// A missing or mixed sound preselects Default; a silent one, Silent.
|
||||
val preselect = if (current == null) DEFAULT_NOTIFICATION_URI else current.uri
|
||||
soundPicker.launch(notificationSoundPickerIntent(preselect, pickSoundTitle))
|
||||
} catch (e: RuntimeException) {
|
||||
// No picker, or one that refuses to start: the system screen still has the sound.
|
||||
soundTarget = null
|
||||
if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target)
|
||||
}
|
||||
}
|
||||
return ReminderSoundPicker(loadedSounds, pickSound, openAppSettings, openCalendarSettings)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ import de.jeanlucmakiola.floret.identity.predictiveBackExit
|
||||
|
||||
/** The settings sub-screens reached from the hub's category rows. */
|
||||
private enum class SettingsSection {
|
||||
Appearance, Views, EventForm, Notifications, SpecialDates, Widgets, Licences
|
||||
Appearance, Views, EventForm, Notifications, CalendarReminders, SpecialDates, Widgets, Licences
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,8 +131,9 @@ fun SettingsScreen(
|
||||
) {
|
||||
EventFormScreen(state = state, viewModel = viewModel, onBack = { section = null }, visible = section == SettingsSection.EventForm)
|
||||
}
|
||||
// Stays up beneath its per-calendar subpage, so backing out reveals it.
|
||||
AnimatedVisibility(
|
||||
visible = section == SettingsSection.Notifications,
|
||||
visible = section == SettingsSection.Notifications || section == SettingsSection.CalendarReminders,
|
||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
||||
exit = overlayExit,
|
||||
) {
|
||||
@@ -140,10 +141,23 @@ fun SettingsScreen(
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
onBack = { section = null },
|
||||
onOpenSpecialDates = { section = SettingsSection.SpecialDates },
|
||||
onOpenCalendarReminders = { section = SettingsSection.CalendarReminders },
|
||||
visible = section == SettingsSection.Notifications,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = section == SettingsSection.CalendarReminders,
|
||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
||||
exit = overlayExit,
|
||||
) {
|
||||
CalendarRemindersScreen(
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
onBack = { section = SettingsSection.Notifications },
|
||||
onOpenSpecialDates = { section = SettingsSection.SpecialDates },
|
||||
visible = section == SettingsSection.CalendarReminders,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = section == SettingsSection.SpecialDates,
|
||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import android.net.Uri
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -96,8 +97,14 @@ data class SettingsUiState(
|
||||
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
|
||||
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Writable calendars, shown as per-calendar reminder-override rows. */
|
||||
/** Switched-on calendars you can edit: the per-calendar event-duration rows. */
|
||||
val writableCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
|
||||
val reminderCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Calendars whose reminders Calendula doesn't post (#272). */
|
||||
val mutedReminderCalendarIds: Set<Long> = emptySet(),
|
||||
/** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */
|
||||
val notificationCategoryHintDismissed: Boolean = true,
|
||||
/**
|
||||
* Whether the event-colour picker is offered on calendars that publish no
|
||||
* colour palette (the colour may then not survive their next sync).
|
||||
@@ -130,3 +137,9 @@ data class SpecialDatesUiState(
|
||||
/** Epoch millis of the last sync, or 0 if it has never run. */
|
||||
val lastRun: Long = 0L,
|
||||
)
|
||||
|
||||
/** A reminder channel's sound: null [uri] is silent; [title] is null when it can't be resolved. */
|
||||
data class ReminderSound(val uri: Uri?, val title: String?)
|
||||
|
||||
/** Why a picked reminder sound wasn't applied. */
|
||||
enum class SoundFailure { NotApplied, Unreadable }
|
||||
@@ -3,6 +3,8 @@ package de.jeanlucmakiola.calendula.ui.settings
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -16,10 +18,12 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
|
||||
import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate
|
||||
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
|
||||
import de.jeanlucmakiola.floret.android.ringtoneTitle
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -33,6 +37,8 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
@@ -45,7 +51,12 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale
|
||||
import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle
|
||||
import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -54,6 +65,7 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -62,11 +74,13 @@ import javax.inject.Inject
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
calendarPrefs: CalendarPrefs,
|
||||
repository: CalendarRepository,
|
||||
private val specialDatesEngine: SpecialDatesSyncEngine,
|
||||
specialDatesSpec: SpecialDatesCalendarSpec,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
private val reminderScanner: ReminderScanner,
|
||||
private val reminderChannels: ReminderChannels,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
) : ViewModel() {
|
||||
@@ -74,16 +88,16 @@ class SettingsViewModel @Inject constructor(
|
||||
private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
/**
|
||||
* Writable calendars that are switched on — the only ones that take a
|
||||
* per-calendar reminder override, since a switched-off one plans no
|
||||
* reminders at all (#75).
|
||||
* Calendars that are switched on — the only ones that plan reminders at
|
||||
* all (#75), so the only ones with notification settings.
|
||||
*/
|
||||
private val writableCalendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } }
|
||||
.catch { emit(emptyList()) }
|
||||
private val visibleCalendars: Flow<List<CalendarSource>> =
|
||||
combine(repository.calendars(), calendarPrefs.pendingDisabledCalendarIds) { calendars, pending ->
|
||||
calendars.filter { it.isVisibleInSystem && it.id !in pending }
|
||||
}.catch { emit(emptyList()) }
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable),
|
||||
@@ -125,7 +139,10 @@ class SettingsViewModel @Inject constructor(
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
writableCalendars = calendars,
|
||||
writableCalendars = calendars.filter { it.canModifyContents },
|
||||
reminderCalendars = calendars,
|
||||
mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds],
|
||||
notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed],
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
@@ -357,6 +374,130 @@ class SettingsViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans, since a muted calendar armed no wake-up for its next reminder.
|
||||
* Unmuting scans once more before the write, so the watermark starts at the
|
||||
* unmute and nothing that came due while muted is replayed.
|
||||
*/
|
||||
fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
if (enabled) reminderScanner.scan()
|
||||
prefs.setCalendarRemindersEnabled(calendarId, enabled)
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
private val _channelStatus = MutableStateFlow(ReminderChannelStatus())
|
||||
|
||||
/** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */
|
||||
val channelStatus: StateFlow<ReminderChannelStatus> = _channelStatus.asStateFlow()
|
||||
|
||||
private var channelStatusJob: Job? = null
|
||||
|
||||
private val _channelSounds = MutableStateFlow<Map<Long, ReminderSound>?>(null)
|
||||
|
||||
/** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */
|
||||
val channelSounds: StateFlow<Map<Long, ReminderSound>?> = _channelSounds.asStateFlow()
|
||||
|
||||
private val _soundFailed = Channel<SoundFailure>(Channel.CONFLATED)
|
||||
|
||||
/** Emits when a picked sound couldn't be applied; kept until the screen collects it. */
|
||||
val soundFailed: Flow<SoundFailure> = _soundFailed.receiveAsFlow()
|
||||
|
||||
private val soundTitles = mutableMapOf<Uri, String?>()
|
||||
|
||||
fun refreshChannelStatus(calendarIds: Collection<Long>) {
|
||||
channelStatusJob?.cancel()
|
||||
channelStatusJob = viewModelScope.launch {
|
||||
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
|
||||
val sounds = onChannels { sounds(calendarIds) } ?: return@launch
|
||||
_channelSounds.value = withContext(io) {
|
||||
sounds.mapValues { (_, uri) ->
|
||||
ReminderSound(uri, uri?.let(::soundTitle))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sound's title, cached unless it is a "default" alias whose target can change. */
|
||||
private fun soundTitle(uri: Uri): String? {
|
||||
if (uri.authority == Settings.AUTHORITY) return appContext.ringtoneTitle(uri)
|
||||
return synchronized(soundTitles) { soundTitles.getOrPut(uri) { appContext.ringtoneTitle(uri) } }
|
||||
}
|
||||
|
||||
/** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */
|
||||
fun setReminderSound(calendarId: Long, sound: Uri?) = applySound(sound) {
|
||||
setSound(listOf(calendarId), sound, createMissing = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Give every switched-on calendar's reminders [sound]. Reads the calendars
|
||||
* itself, so a pick returning after process death still finds them; those
|
||||
* that only get a channel when something posts are left alone.
|
||||
*/
|
||||
fun setReminderSoundForAll(sound: Uri?) = applySound(sound) {
|
||||
try {
|
||||
sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e)
|
||||
}
|
||||
val ids = visibleCalendars.first().map { it.id }
|
||||
ids.isNotEmpty() && setSound(ids, sound, createMissing = false)
|
||||
}
|
||||
|
||||
private fun canRead(uri: Uri): Boolean = uri.authority == Settings.AUTHORITY ||
|
||||
runCatching { appContext.contentResolver.openAssetFileDescriptor(uri, "r")?.close() != null }.getOrDefault(false)
|
||||
|
||||
/** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */
|
||||
private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) {
|
||||
viewModelScope.launch {
|
||||
val failure = withContext(io + NonCancellable) {
|
||||
try {
|
||||
// The system plays the sound but checks that Calendula could read it.
|
||||
when {
|
||||
sound != null && !canRead(sound) -> SoundFailure.Unreadable
|
||||
reminderChannels.block() -> null
|
||||
else -> SoundFailure.NotApplied
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Could not set the reminder sound", e)
|
||||
SoundFailure.NotApplied
|
||||
}
|
||||
}
|
||||
failure?.let(_soundFailed::trySend)
|
||||
refreshChannelStatus(visibleCalendars.first().map { it.id })
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() }
|
||||
|
||||
/**
|
||||
* The channel whose system screen to open for [calendarId] (#340), created
|
||||
* if needed; null when only the app's own screen can help — the app or the
|
||||
* calendar's account group is blocked there, or the channel couldn't be made.
|
||||
*/
|
||||
suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels {
|
||||
val channelId = channelFor(calendarId) ?: return@onChannels null
|
||||
val status = status(listOf(calendarId))
|
||||
channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds }
|
||||
}
|
||||
|
||||
/** Create the per-calendar channels before showing the app's channel list, even with reminders off. */
|
||||
suspend fun syncReminderChannels() {
|
||||
onChannels { sync() }
|
||||
}
|
||||
|
||||
private suspend fun <T> onChannels(block: ReminderChannels.() -> T): T? = withContext(io) {
|
||||
try {
|
||||
reminderChannels.block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Reminder channel update failed", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
|
||||
|
||||
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
|
||||
|
||||
@@ -19,10 +19,7 @@ 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
|
||||
@@ -92,11 +89,8 @@ 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).
|
||||
@@ -173,7 +167,7 @@ abstract class PagedTimelineViewModel(
|
||||
zone.flatMapLatest { zone ->
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(spanRange(span.start, span.count, zone), hiddenHere),
|
||||
repository.instances(spanRange(span.start, span.count, zone)),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildState(span, calendars, instances, today, zone)
|
||||
@@ -246,7 +240,6 @@ class WeekViewModel @Inject constructor(
|
||||
rule
|
||||
},
|
||||
initialRule = { DaysGrid.weeks(DayOfWeek.MONDAY) },
|
||||
view = CalendarView.Week,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -271,7 +264,6 @@ 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. */
|
||||
@@ -290,7 +282,6 @@ class DayViewModel @Inject constructor(
|
||||
io = io,
|
||||
gridRule = flowOf { _: LocalDate -> DaysGrid.days },
|
||||
initialRule = { DaysGrid.days },
|
||||
view = CalendarView.Day,
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,7 @@ 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
|
||||
@@ -115,5 +116,8 @@ 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,7 +14,6 @@ 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,7 +12,6 @@ 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
|
||||
@@ -23,6 +22,7 @@ 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
|
||||
|
||||
@@ -731,7 +731,27 @@
|
||||
<string name="reminder_custom_amount">Amount</string>
|
||||
<string name="reminder_custom_set">Set</string>
|
||||
<string name="settings_calendar_reminders_title">Per-calendar reminders</string>
|
||||
<string name="settings_calendar_reminders_hint">Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own.</string>
|
||||
<string name="settings_calendar_reminders_subtitle">Notifications, sound and default reminders per calendar</string>
|
||||
<string name="settings_calendar_reminders_hint">Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit.</string>
|
||||
<string name="settings_calendar_notifications">Notifications</string>
|
||||
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
|
||||
<string name="settings_calendar_notifications_off">Notifications off</string>
|
||||
<string name="settings_notification_sound">Notification sound</string>
|
||||
<string name="settings_notification_sound_silent">Silent</string>
|
||||
<string name="settings_notification_sound_default">Default</string>
|
||||
<!-- %1$s is the name of the device's default notification sound. -->
|
||||
<string name="settings_notification_sound_default_named">Default (%1$s)</string>
|
||||
<string name="settings_notification_sound_custom">Custom sound</string>
|
||||
<string name="settings_notification_sound_failed">Couldn\'t change the notification sound</string>
|
||||
<string name="settings_notification_sound_unreadable">Calendula can\'t play this sound. Pick another one.</string>
|
||||
<string name="settings_notification_sound_mixed">Differs per calendar</string>
|
||||
<string name="settings_notification_more">More notification settings</string>
|
||||
<string name="settings_notification_sound_hint">Vibration, pop-ups and more for each calendar, in system settings</string>
|
||||
<string name="settings_notifications_blocked">Blocked in system settings</string>
|
||||
<string name="settings_notifications_blocked_hint">Blocked in system settings — tap to allow</string>
|
||||
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
|
||||
<string name="settings_notification_category_hint_open">Open settings</string>
|
||||
<string name="settings_calendar_notification_sound_hint">Vibration, pop-ups and more for this calendar, in system settings</string>
|
||||
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
|
||||
<string name="settings_reliable_delivery">Reliable delivery</string>
|
||||
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
|
||||
@@ -849,7 +869,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; tap one here to hide it in some views.</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_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>
|
||||
@@ -863,19 +883,6 @@
|
||||
<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>
|
||||
|
||||
@@ -601,6 +601,30 @@ class SettingsPrefsTest {
|
||||
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calendar notifications default on and toggle per calendar`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty()
|
||||
prefs.setCalendarRemindersEnabled(7L, false)
|
||||
prefs.setCalendarRemindersEnabled(9L, false)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L)
|
||||
prefs.setCalendarRemindersEnabled(7L, true)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reminder channel versions only grow`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.reminderChannelVersions.first()).isEmpty()
|
||||
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1))).containsExactly(7L, 1)
|
||||
assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1, 9L to 5))).containsExactly(7L, 2, 9L, 5)
|
||||
assertThat(prefs.reminderChannelVersions.first()).containsExactly(7L, 2, 9L, 5)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `garbage per-calendar duration entries are dropped, the rest survive`(
|
||||
@TempDir tempDir: Path,
|
||||
@@ -616,66 +640,6 @@ 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)
|
||||
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ReminderChannelPlanTest {
|
||||
|
||||
private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource(
|
||||
id = id,
|
||||
displayName = "Cal $id",
|
||||
accountName = account,
|
||||
accountType = type,
|
||||
color = 0,
|
||||
isVisibleInSystem = true,
|
||||
isLocal = local,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `one channel per calendar, grouped by account`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "com.google"),
|
||||
calendar(3, "dav", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(2)
|
||||
assertThat(plan.channels.map { it.id })
|
||||
.containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3))
|
||||
assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId)
|
||||
assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId)
|
||||
assertThat(plan.staleChannelIds).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `device calendars share one group`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "Calendula", "LOCAL", local = true),
|
||||
calendar(2, "Other", "LOCAL", local = true),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(1)
|
||||
assertThat(plan.groups.single().isLocal).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `same account name under two types is ambiguous`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "bitfire.at.davdroid"),
|
||||
calendar(3, "work", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType })
|
||||
.containsExactly("com.google", "bitfire.at.davdroid")
|
||||
assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale reminder channels and groups go, foreign ones stay`() {
|
||||
val current = calendar(1, "me@example.org", "com.google")
|
||||
fun plan(calendars: List<CalendarSource>, existing: List<String> = emptyList(), groups: List<String> = emptyList()) =
|
||||
planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC)
|
||||
val keptGroup = plan(listOf(current)).groups.single().id
|
||||
val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id
|
||||
val result = plan(
|
||||
calendars = listOf(current),
|
||||
existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"),
|
||||
groups = listOf(keptGroup, goneGroup, "other"),
|
||||
)
|
||||
assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9))
|
||||
assertThat(result.staleGroupIds).containsExactly(goneGroup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only missing or renamed channels are written`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "a", "com.google"),
|
||||
calendar(2, "a", "com.google"),
|
||||
calendar(3, "a", "com.google").copy(displayName = ""),
|
||||
calendar(4, "a", "com.google"),
|
||||
),
|
||||
existing = listOf(
|
||||
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
|
||||
ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"),
|
||||
ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"),
|
||||
),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L)
|
||||
assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non-syncing calendars keep a channel but get none up front`() {
|
||||
val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false)
|
||||
val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC)
|
||||
assertThat(fresh.channelsToWrite).isEmpty()
|
||||
assertThat(fresh.groupsInUse).isEmpty()
|
||||
val posted = planReminderChannels(
|
||||
calendars = listOf(quiet),
|
||||
existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(posted.staleChannelIds).isEmpty()
|
||||
assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L)
|
||||
assertThat(posted.groupsInUse).hasSize(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blocked calendars follow app, channel and group`() {
|
||||
val channels = mapOf(
|
||||
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"),
|
||||
reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"),
|
||||
reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"),
|
||||
)
|
||||
val ids = listOf(1L, 2L, 3L, 4L)
|
||||
val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))
|
||||
assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L)
|
||||
assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L)
|
||||
assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds)
|
||||
.containsExactly(1L)
|
||||
val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet())
|
||||
assertThat(appOff.appBlocked).isTrue()
|
||||
assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `channel ids round-trip with versions`() {
|
||||
assertThat(parseReminderChannelId(reminderChannelId(7))).isEqualTo(7L to 0)
|
||||
assertThat(parseReminderChannelId(reminderChannelId(7, 3))).isEqualTo(7L to 3)
|
||||
assertThat(parseReminderChannelId("reminders.calendar.7.v0")).isNull()
|
||||
assertThat(parseReminderChannelId("reminders.calendar.x")).isNull()
|
||||
assertThat(parseReminderChannelId(LEGACY_REMINDER_CHANNEL_ID)).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a version bump retires the old channel unless it is showing`() {
|
||||
val existing = listOf(
|
||||
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
|
||||
ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, "g"),
|
||||
)
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(calendar(1, "a", "com.google"), calendar(2, "a", "com.google")),
|
||||
existing = existing,
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
versions = mapOf(1L to 2, 2L to 1),
|
||||
showingChannelIds = setOf(reminderChannelId(2)),
|
||||
)
|
||||
assertThat(plan.channels.map { it.id }).containsExactly(reminderChannelId(1, 2), reminderChannelId(2, 1))
|
||||
assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(1))
|
||||
assertThat(plan.keptChannelIds).containsExactly(reminderChannelId(2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the current version is the highest that exists, else the high-water mark`() {
|
||||
val versions = currentReminderChannelVersions(
|
||||
existingChannelIds = listOf(reminderChannelId(1), reminderChannelId(1, 2), reminderChannelId(3), "backup"),
|
||||
highWater = mapOf(1L to 5, 2L to 4),
|
||||
)
|
||||
// Calendar 1 reserved v5 but never wrote it, so v2 stays current.
|
||||
assertThat(versions).containsExactly(1L, 2, 2L, 4, 3L, 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `status reads the current channel version`() {
|
||||
val channels = mapOf(
|
||||
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = null),
|
||||
reminderChannelId(1, 2) to ReminderChannelState(blocked = false, groupId = null),
|
||||
)
|
||||
val status = reminderChannelStatus(listOf(1L), true, channels, emptySet(), versions = mapOf(1L to 2))
|
||||
assertThat(status.blockedCalendarIds).isEmpty()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DESC = "Reminders"
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
+31
-6
@@ -389,12 +389,37 @@ 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. 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.
|
||||
separate in-app declutter that never touches reminders.
|
||||
|
||||
**A channel per calendar (#145).** `ReminderChannels` keeps one notification
|
||||
channel per calendar, grouped by account (one that syncs no events only gets
|
||||
its channel once something posts on it), so a calendar can be
|
||||
muted or given its own sound in the system settings before it ever fires. Every
|
||||
scan with reminders on syncs them (skipped when nothing changed): missing
|
||||
channels are created, renamed ones updated, and channels of deleted calendars
|
||||
removed — but never on an empty snapshot, which is a provider hiccup more often
|
||||
than every calendar gone. Switched-off calendars keep theirs, so toggling one
|
||||
never cancels a showing reminder or loses its settings. `post` creates a missing
|
||||
channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and
|
||||
importance of the pre-#145 single `reminders` channel, which is deleted once
|
||||
nothing showing still sits on it. Settings → Notifications deep-links into the
|
||||
system's channel screens for everything but the sound (#340). A sound picked in
|
||||
the app (#518) can't be set on an existing channel, so
|
||||
`ReminderChannels.setSound` recreates it under a new version
|
||||
(`reminders.calendar.<id>.v<n>`), copying everything else from the old one. The
|
||||
current version is simply the highest channel that exists, so the new one only
|
||||
takes over once written; `SettingsPrefs.reminderChannelVersions` is just a
|
||||
high-water mark that keeps ids from being reused (a re-used id would bring back
|
||||
the deleted channel's settings). `setSound` leaves the old version to the sync,
|
||||
which treats older versions as stale and keeps one while a notification still
|
||||
shows on it; `ReminderNotifier.post` resolves and posts under the channel lock
|
||||
(`withChannel`), so a pick never moves a channel mid-post.
|
||||
Separate from the channels, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar
|
||||
off switch (#272): the scan plans nothing for those calendars (so they arm no
|
||||
wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again
|
||||
for snoozes. The settings screen re-reads `ReminderChannels.status` on every
|
||||
resume and marks a calendar "Blocked in system settings" when the app, its
|
||||
channel or its account group is switched off there.
|
||||
|
||||
Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast.
|
||||
Keeping both would double-post wherever the provider works, and Etar's way out —
|
||||
|
||||
+1
-1
Submodule floret-kit updated: dd77a16b5e...31aa7e1fc6.
Reference in new issue
Block a user