Compare commits

...
12 changed files with 534 additions and 55 deletions

No files matched your search

@@ -168,6 +168,7 @@ class SettingsPrefs @Inject constructor(
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)
@@ -275,6 +276,19 @@ class SettingsPrefs @Inject constructor(
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
/**
* Reserve a new reminder channel version for each calendar in [floors], above
* both its stored high-water mark and its floor, and return them. Versions
* only grow: the system would restore a deleted channel's old settings if
* its id came back (#518).
*/
suspend fun reserveReminderChannelVersions(floors: Map<Long, Int>): Map<Long, Int> {
val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current ->
current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) }
}
return floors.keys.associateWith { stored.getValue(it) }
}
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
@@ -614,6 +628,15 @@ object SettingsKeys {
*/
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
@@ -997,6 +1020,18 @@ private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
calendarId to minutes
}.toMap()
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
val parts = entry.split(KEY_VALUE_SEP)
if (parts.size != 2) return@mapNotNull null
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
calendarId to version
}.toMap()
private fun Map<Long, Int>.toStoredVersions(): String? =
if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" }
private fun Map<Long, Int>.toStoredDurations(): String =
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
"$id$KEY_VALUE_SEP$minutes"
@@ -10,8 +10,37 @@ private const val CHANNEL_PREFIX = "reminders.calendar."
private const val GROUP_PREFIX = "reminders.account."
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
/** The notification channel [calendarId]'s reminders post on. */
fun reminderChannelId(calendarId: Long): String = CHANNEL_PREFIX + calendarId
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)
@@ -60,6 +89,8 @@ data class ReminderChannelPlan(
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(),
)
/**
@@ -75,6 +106,8 @@ fun planReminderChannels(
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 {
@@ -93,16 +126,16 @@ fun planReminderChannels(
)
}
}
val existingById = existing.associateBy { it.id }
val channels = calendars.map { calendar ->
ReminderChannelSpec(
id = reminderChannelId(calendar.id),
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 existingById = existing.associateBy { it.id }
val wantedChannels = channels.mapTo(HashSet()) { it.id }
val wantedGroups = groups.mapTo(HashSet()) { it.id }
val toWrite = channels.filter { spec ->
@@ -117,13 +150,18 @@ fun planReminderChannels(
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 = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels },
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups },
staleChannelIds = stale,
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups },
keptChannelIds = kept,
)
}
@@ -150,12 +188,14 @@ fun reminderChannelStatus(
appEnabled: Boolean,
channels: Map<String, ReminderChannelState>,
blockedGroupIds: Set<String>,
versions: Map<Long, Int> = emptyMap(),
): ReminderChannelStatus {
val groupBlocked = calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.groupId in blockedGroupIds }
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()) { channels[reminderChannelId(it)]?.blocked == true } + groupBlocked
calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked
}
return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked)
}
@@ -1,15 +1,24 @@
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
@@ -21,11 +30,14 @@ import javax.inject.Singleton
*
* 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)
@@ -46,9 +58,14 @@ class ReminderChannels @Inject constructor(
val manager = manager
val existing = manager.notificationChannels
val existingIds = existing.mapTo(HashSet()) { it.id }
if (syncKey(calendars, existingIds) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
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 plan = plan(calendars, existing, groups.map { it.id })
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() }
@@ -58,15 +75,41 @@ class ReminderChannels @Inject constructor(
existing = existing,
)
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids)
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>): Any = listOf(
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
@@ -76,10 +119,15 @@ class ReminderChannels @Inject constructor(
*/
@Synchronized
fun channelFor(calendarId: Long): String? {
val id = reminderChannelId(calendarId)
val manager = manager
if (manager.getNotificationChannel(id) != null) return id
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) {
@@ -91,7 +139,7 @@ class ReminderChannels @Inject constructor(
write(emptyList(), listOf(fallback), existing)
return id
}
val plan = plan(calendars, existing, emptyList())
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 }
@@ -107,27 +155,125 @@ class ReminderChannels @Inject constructor(
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 channels = manager.notificationChannels.associate {
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)
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 on the next sync (#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
return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
}
/**
* 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(
@@ -161,8 +307,10 @@ class ReminderChannels @Inject constructor(
}
/**
* Carry the old single channel's sound, vibration, lights and badge over to
* a new per-calendar one (the system resets lock-screen visibility itself), so an upgrade keeps how reminders sounded.
* 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)
@@ -184,12 +332,7 @@ class ReminderChannels @Inject constructor(
private fun retireLegacyChannel(): Boolean {
val manager = manager
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
val showing = runCatching {
manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
}.getOrElse { e ->
Log.w(TAG, "Could not read active notifications", e)
true
}
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID))
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
return !showing
}
@@ -203,6 +346,8 @@ class ReminderChannels @Inject constructor(
private companion object {
const val TAG = "ReminderChannels"
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT
}
}
@@ -65,15 +65,6 @@ class ReminderNotifier @Inject constructor(
/** Post [alert], unless its calendar is silenced or gone. */
suspend fun post(alert: ReminderAlert) {
if (isSilenced(alert.calendarId)) return
val channelId = try {
channels.channelFor(alert.calendarId) ?: run {
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
return
}
} catch (e: Exception) {
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
return
}
val title = displayTitle(alert)
val is24Hour = settingsPrefs.timeFormat.first()
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
@@ -96,6 +87,14 @@ class ReminderNotifier @Inject constructor(
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
)
val text = listOfNotNull(time, alert.location).joinToString(" · ")
// Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post.
val posted = channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) }
if (posted == null) {
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
}
}
private fun notify(alert: ReminderAlert, channelId: String, title: String, text: String) {
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
@@ -6,6 +6,8 @@ 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
@@ -25,10 +27,12 @@ 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
@@ -51,7 +55,9 @@ 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
@@ -108,9 +114,56 @@ internal fun NotificationsScreen(
viewModel.refreshChannelStatus(calendarIds)
onPauseOrDispose { }
}
val openCalendarSound: (Long) -> Unit = { calendarId ->
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)
}
}
CollapsingScaffold(
title = stringResource(R.string.settings_section_notifications),
@@ -122,10 +175,7 @@ internal fun NotificationsScreen(
NotificationCategoryHint(
onOpen = {
viewModel.dismissNotificationCategoryHint()
scope.launch {
viewModel.syncReminderChannels()
context.openNotificationSettings()
}
openAppSettings()
},
onDismiss = viewModel::dismissNotificationCategoryHint,
)
@@ -138,8 +188,16 @@ 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_sound),
title = stringResource(R.string.settings_notification_more),
summary = if (channelStatus.appBlocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
@@ -147,12 +205,7 @@ internal fun NotificationsScreen(
},
position = Position.Middle,
trailing = { ExternalLinkIcon() },
onClick = {
scope.launch {
viewModel.syncReminderChannels()
context.openNotificationSettings()
}
},
onClick = openAppSettings,
)
GroupedRow(
title = stringResource(R.string.settings_default_reminder),
@@ -252,8 +305,10 @@ internal fun NotificationsScreen(
state = state,
notifying = notifying,
blocked = blocked,
soundLabel = loadedSounds?.let { soundLabel(it[calendar.id]) },
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
onOpenSound = { openCalendarSound(calendar.id) },
onPickSound = { pickSound(calendar.id) },
onOpenSettings = { openCalendarSettings(calendar.id) },
onOpenSpecialDates = onOpenSpecialDates,
onEditOverride = { overrideDialog = it },
)
@@ -354,8 +409,10 @@ private fun CalendarNotificationRows(
state: SettingsUiState,
notifying: Boolean,
blocked: Boolean,
soundLabel: String?,
onSetNotifying: (Boolean) -> Unit,
onOpenSound: () -> Unit,
onPickSound: () -> Unit,
onOpenSettings: () -> Unit,
onOpenSpecialDates: () -> Unit,
onEditOverride: (OverrideTarget) -> Unit,
) {
@@ -371,6 +428,12 @@ private fun CalendarNotificationRows(
)
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = soundLabel,
position = Position.Middle,
onClick = onPickSound,
)
GroupedRow(
title = stringResource(R.string.settings_notification_more),
summary = if (blocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
@@ -378,7 +441,7 @@ private fun CalendarNotificationRows(
},
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
onClick = onOpenSettings,
)
if (managed) {
GroupedRow(
@@ -413,6 +476,43 @@ private fun CalendarNotificationRows(
}
}
/** [soundTarget] meaning every calendar at once. */
private const val ALL_CALENDARS = Long.MIN_VALUE
/** What the calendars that have a channel share, sound-wise. */
private sealed interface SharedSound {
data object None : SharedSound
data object Mixed : SharedSound
data class Same(val sound: ReminderSound) : SharedSound
}
private fun sharedSound(sounds: Map<Long, ReminderSound>, calendarIds: List<Long>): SharedSound {
val distinct = calendarIds.mapNotNull { sounds[it] }.distinctBy { it.uri }
return when (distinct.size) {
0 -> SharedSound.None
1 -> SharedSound.Same(distinct.single())
else -> SharedSound.Mixed
}
}
@Composable
private 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)
@@ -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
@@ -136,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,7 @@ 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
@@ -17,6 +18,7 @@ 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
@@ -52,6 +54,9 @@ 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
@@ -60,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
@@ -388,10 +394,78 @@ class SettingsViewModel @Inject constructor(
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 })
}
}
+11 -2
View File
@@ -736,12 +736,21 @@
<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_hint">Sound, vibration and pop-ups for each calendar, in system settings</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">Sound, vibration and pop-ups for this calendar, in system 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>
@@ -614,6 +614,17 @@ class SettingsPrefsTest {
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,
@@ -145,6 +145,55 @@ class ReminderChannelPlanTest {
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"
}
+13 -3
View File
@@ -402,9 +402,19 @@ 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 only deep-links into
the system's channel screens (#340); the app never sets a sound itself. Separate
from both, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar
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