From 6b108fb58578afc8f44b8c2831a1ec31718bd1ca Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:48:53 +0100 Subject: [PATCH 1/6] feat(#518): pick the reminder sound in the app via versioned channels --- .../calendula/data/prefs/SettingsPrefs.kt | 35 +++++++ .../data/reminders/ReminderChannelPlan.kt | 58 +++++++++-- .../data/reminders/ReminderChannels.kt | 97 +++++++++++++++++-- .../ui/settings/NotificationSettings.kt | 92 +++++++++++++++--- .../calendula/ui/settings/SettingsUiState.kt | 4 + .../ui/settings/SettingsViewModel.kt | 30 +++++- app/src/main/res/values/strings.xml | 8 +- .../calendula/data/prefs/SettingsPrefsTest.kt | 12 +++ .../data/reminders/ReminderChannelPlanTest.kt | 42 ++++++++ docs/ARCHITECTURE.md | 13 ++- floret-kit | 2 +- 11 files changed, 355 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt index 13e6c7b3..ac3c33b4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt @@ -168,6 +168,7 @@ class SettingsPrefs @Inject constructor( val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) val notificationCategoryHintDismissed: Flow = prefs.flow(SettingsKeys.notificationCategoryHintDismissed) + val reminderChannelVersions: Flow> = prefs.flow(SettingsKeys.reminderChannelVersions) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -275,6 +276,20 @@ class SettingsPrefs @Inject constructor( suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) + /** + * Move [calendarId]'s reminder channel to a new version, at least [atLeast], + * and return it. Versions only grow: the system would restore a deleted + * channel's old settings if its id came back (#518). + */ + suspend fun bumpReminderChannelVersion(calendarId: Long, atLeast: Int): Int { + var next = 0 + prefs.update(SettingsKeys.reminderChannelVersions) { current -> + next = maxOf((current[calendarId] ?: 0) + 1, atLeast) + current + (calendarId to next) + } + return next + } + suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true) suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { @@ -614,6 +629,14 @@ object SettingsKeys { */ val notificationCategoryHintDismissed: Pref = booleanPref("notification_category_hint_dismissed", false) + /** + * Each calendar's reminder channel version (#518): a sound picked in the app + * recreates the channel under the next one. Absent = 0, the unversioned id. + * Serialised as `id=version;id=version`. + */ + val reminderChannelVersions: Pref> = + 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 = calendarId to minutes }.toMap() +private fun parseChannelVersions(stored: String?): Map = + 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.toStoredVersions(): String? = + if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" } + private fun Map.toStoredDurations(): String = entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) -> "$id$KEY_VALUE_SEP$minutes" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt index e67a7727..0d278fda 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -10,8 +10,25 @@ 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? { + 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 +} /** Whether [channelId] is one of the per-calendar reminder channels. */ fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX) @@ -43,6 +60,12 @@ data class ReminderChannelSpec( * fires, so its channel only appears once something posts on it. */ val upFront: Boolean = true, + /** + * An older version of this calendar's channel to copy behaviour from when + * this one is missing, so a version bump that never got written loses no + * settings. + */ + val templateId: String? = null, ) /** What a channel already looks like in the system, as far as the plan compares it. */ @@ -60,6 +83,8 @@ data class ReminderChannelPlan( val groupsInUse: List, val staleChannelIds: List, val staleGroupIds: List, + /** Stale channels kept for now, because a notification on them is still showing. */ + val keptChannelIds: List = emptyList(), ) /** @@ -75,6 +100,8 @@ fun planReminderChannels( existingGroupIds: Collection, unnamed: String, description: String, + versions: Map = emptyMap(), + showingChannelIds: Set = emptySet(), ): ReminderChannelPlan { val (local, synced) = calendars.partition { it.isLocal } val groups = buildList { @@ -93,16 +120,24 @@ fun planReminderChannels( ) } } + val existingById = existing.associateBy { it.id } + val versionsByCalendar = existing.mapNotNull { parseReminderChannelId(it.id) }.groupBy({ it.first }, { it.second }) val channels = calendars.map { calendar -> + val version = versions[calendar.id] ?: 0 + val id = reminderChannelId(calendar.id, version) ReminderChannelSpec( - id = reminderChannelId(calendar.id), + id = id, 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, + templateId = versionsByCalendar[calendar.id] + ?.filter { it != version } + ?.maxOrNull() + ?.let { reminderChannelId(calendar.id, it) } + ?.takeIf { id !in existingById }, ) } - 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 +152,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 +190,14 @@ fun reminderChannelStatus( appEnabled: Boolean, channels: Map, blockedGroupIds: Set, + versions: Map = 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) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 3698ee76..21268647 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -4,12 +4,17 @@ import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager 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 +26,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 +54,10 @@ 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 = versions() + 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 plan = plan(calendars, existing, groups.map { it.id }, versions, showingChannelIds()) plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) val groupNames = groups.associate { it.id to it.name?.toString() } @@ -58,15 +67,32 @@ 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, channelIds: Set): Any = listOf( + private fun syncKey(calendars: List, channelIds: Set, versions: Map): Any = listOf( calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) }, Locale.getDefault(), channelIds, + versions, ) + private fun versions(): Map = runBlocking { settingsPrefs.reminderChannelVersions.first() } + + /** Channels with a notification on screen; on failure every channel counts, so none is deleted. */ + private fun showingChannelIds(): Set = runCatching { + manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId } + }.getOrElse { e -> + Log.w(TAG, "Could not read active notifications", e) + manager.notificationChannels.mapTo(HashSet()) { it.id } + } + /** * 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,7 +102,8 @@ class ReminderChannels @Inject constructor( */ @Synchronized fun channelFor(calendarId: Long): String? { - val id = reminderChannelId(calendarId) + val versions = versions() + val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) val manager = manager if (manager.getNotificationChannel(id) != null) return id val existing = manager.notificationChannels @@ -91,7 +118,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 } @@ -115,19 +142,67 @@ class ReminderChannels @Inject constructor( 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, versions()) + } + + /** + * 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): Map { + val versions = versions() + val manager = manager + return calendarIds.mapNotNull { id -> + manager.getNotificationChannel(reminderChannelId(id, versions[id] ?: 0))?.let { id to it.sound } + }.toMap() + } + + /** + * Give [calendarId]'s reminders [sound] (null = silent). A channel's sound is + * fixed once created, so this moves the calendar to a new channel version + * carrying over everything else, and retires the old one. Returns whether + * the calendar had a channel to move. + */ + suspend fun setSound(calendarId: Long, sound: Uri?): Boolean { + val oldId = channelFor(calendarId) ?: return false + val floor = manager.notificationChannels + .mapNotNull { parseReminderChannelId(it.id) } + .filter { it.first == calendarId } + .maxOfOrNull { it.second + 1 } ?: 1 + val version = settingsPrefs.bumpReminderChannelVersion(calendarId, atLeast = floor) + return recreate(oldId, reminderChannelId(calendarId, version), sound) + } + + @Synchronized + private fun recreate(oldId: String, newId: String, sound: Uri?): Boolean { + val manager = manager + val old = manager.getNotificationChannel(oldId) ?: return false + val channel = NotificationChannel(newId, old.name, old.importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + } + manager.createNotificationChannel(channel) + if (oldId !in showingChannelIds()) manager.deleteNotificationChannel(oldId) + lastSync = null + return true } private fun plan( calendars: List, existing: List, existingGroupIds: List, + versions: Map, + showingChannelIds: Set = 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( @@ -142,11 +217,12 @@ class ReminderChannels @Inject constructor( 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] + val legacy = 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] + val template = spec.templateId?.let(byId::get) ?: legacy NotificationChannel( spec.id, spec.name, @@ -203,6 +279,11 @@ class ReminderChannels @Inject constructor( private companion object { const val TAG = "ReminderChannels" + + val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .build() } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index efa61104..f9242301 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -1,11 +1,13 @@ package de.jeanlucmakiola.calendula.ui.settings import android.Manifest +import android.content.ActivityNotFoundException import android.content.Context 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 androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility @@ -29,6 +31,7 @@ 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 +54,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 +113,36 @@ 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 sounds by viewModel.channelSounds.collectAsStateWithLifecycle() + // ALL_CALENDARS, a calendar id, or null when no pick is pending. + var soundTarget by rememberSaveable { mutableStateOf(null) } + val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val target = soundTarget + soundTarget = null + val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult + val ids = if (target == ALL_CALENDARS) calendarIds else listOfNotNull(target) + viewModel.setReminderSound(ids, picked.uri) + } + val pickSoundTitle = stringResource(R.string.settings_notification_sound) + val pickSound: (Long) -> Unit = { target -> + val current = if (target == ALL_CALENDARS) sharedSound(sounds, calendarIds)?.uri else sounds[target]?.uri + soundTarget = target + try { + soundPicker.launch(notificationSoundPickerIntent(current ?: DEFAULT_NOTIFICATION_URI, pickSoundTitle)) + } catch (e: ActivityNotFoundException) { + soundTarget = null + if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target) + } + } CollapsingScaffold( title = stringResource(R.string.settings_section_notifications), @@ -122,10 +154,7 @@ internal fun NotificationsScreen( NotificationCategoryHint( onOpen = { viewModel.dismissNotificationCategoryHint() - scope.launch { - viewModel.syncReminderChannels() - context.openNotificationSettings() - } + openAppSettings() }, onDismiss = viewModel::dismissNotificationCategoryHint, ) @@ -138,8 +167,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 = globalSoundLabel(sounds, 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 +184,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 +284,10 @@ internal fun NotificationsScreen( state = state, notifying = notifying, blocked = blocked, + soundLabel = soundLabel(sounds[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 +388,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 +407,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 +420,7 @@ private fun CalendarNotificationRows( }, position = if (managed || takesOverrides) Position.Middle else Position.Bottom, trailing = { ExternalLinkIcon() }, - onClick = onOpenSound, + onClick = onOpenSettings, ) if (managed) { GroupedRow( @@ -413,6 +455,26 @@ private fun CalendarNotificationRows( } } +/** [soundTarget] meaning every calendar at once. */ +private const val ALL_CALENDARS = Long.MIN_VALUE + +/** The sound every one of [calendarIds] shares, or null when they differ or one has no channel yet. */ +private fun sharedSound(sounds: Map, calendarIds: List): ReminderSound? = + calendarIds.map { sounds[it] }.distinctBy { it?.uri }.singleOrNull() + +@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) + else -> sound.title ?: stringResource(R.string.settings_notification_sound_default) +} + +@Composable +private fun globalSoundLabel(sounds: Map, calendarIds: List): String { + val shared = calendarIds.map { sounds[it] }.distinctBy { it?.uri } + return if (shared.size == 1) soundLabel(shared.single()) else stringResource(R.string.settings_notification_sound_mixed) +} + /** Samsung's One UI can start a new notification category switched off (#145). */ private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 34e603b3..261c1c60 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -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,6 @@ 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?) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 21ff880b..6f159311 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -17,6 +17,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 @@ -388,10 +389,37 @@ class SettingsViewModel @Inject constructor( private var channelStatusJob: Job? = null + private val _channelSounds = MutableStateFlow>(emptyMap()) + + /** Each calendar's reminder sound (#518); a calendar without a channel yet is absent. */ + val channelSounds: StateFlow> = _channelSounds.asStateFlow() + fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() channelStatusJob = viewModelScope.launch { - onChannels { status(calendarIds) }?.let { _channelStatus.value = it } + val (status, sounds) = onChannels { status(calendarIds) to sounds(calendarIds) } ?: return@launch + _channelStatus.value = status + _channelSounds.value = withContext(io) { + sounds.mapValues { (_, uri) -> ReminderSound(uri, uri?.let { appContext.ringtoneTitle(it) }) } + } + } + } + + /** Give [calendarIds]' reminders [sound] (null = silent), each on a fresh channel (#518). */ + fun setReminderSound(calendarIds: Collection, sound: Uri?) { + viewModelScope.launch { + withContext(io) { + calendarIds.forEach { id -> + try { + reminderChannels.setSound(id, sound) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("SettingsViewModel", "Could not set the reminder sound of calendar $id", e) + } + } + } + refreshChannelStatus(state.value.reminderCalendars.map { it.id }) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e7b8d77..3e8df57c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -736,12 +736,16 @@ Notify at this calendar\'s reminder times Notifications off Notification sound - Sound, vibration and pop-ups for each calendar, in system settings + Silent + Default + Differs per calendar + More notification settings + Vibration, pop-ups and more for each calendar, in system settings Blocked in system settings Blocked in system settings — tap to allow On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on. Open settings - Sound, vibration and pop-ups for this calendar, in system settings + Vibration, pop-ups and more for this calendar, in system settings Default (%1$s) Reliable delivery Android may delay reminders to save battery. Exempt Calendula so they arrive on time. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index 1e113689..42f7fd71 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -614,6 +614,18 @@ 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.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(1) + assertThat(prefs.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(2) + assertThat(prefs.bumpReminderChannelVersion(9L, atLeast = 5)).isEqualTo(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, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt index 4634644b..92c5ed36 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -145,6 +145,48 @@ 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)) + // A bump the recreate never wrote still inherits from the version before it. + assertThat(plan.channelsToWrite.map { it.templateId }) + .containsExactly(reminderChannelId(1), reminderChannelId(2)) + } + + @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" } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8f0a77ba..e40d484f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -402,9 +402,16 @@ 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 the calendar's next version +(`reminders.calendar..v`, counter in `SettingsPrefs.reminderChannelVersions` +— it only grows, because a re-used id would bring back the deleted channel's +settings), copying everything else from the old one. The sync treats older +versions as stale, keeps one while a notification still shows on it, and a +version that was counted but never written inherits from the one before it. +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 diff --git a/floret-kit b/floret-kit index 20b136aa..ede5ebfd 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 20b136aaf71277643267018ed1c57dae0b0c54ec +Subproject commit ede5ebfdc85532422fad7e6a30709f720808a02d From 18b9f19a6162d4f1e8c335552407ded28ae0e814 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:57:51 +0100 Subject: [PATCH 2/6] =?UTF-8?q?fix(#518):=20review=20round=201=20=E2=80=94?= =?UTF-8?q?=20current=20version=20from=20existing=20channels,=20batched=20?= =?UTF-8?q?picks,=20silent=20vs=20unset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../calendula/data/prefs/SettingsPrefs.kt | 24 +++--- .../data/reminders/ReminderChannelPlan.kt | 28 +++---- .../data/reminders/ReminderChannels.kt | 84 +++++++++++-------- .../ui/settings/NotificationSettings.kt | 50 ++++++++--- .../ui/settings/SettingsViewModel.kt | 40 +++++---- app/src/main/res/values/strings.xml | 3 + .../calendula/data/prefs/SettingsPrefsTest.kt | 5 +- .../data/reminders/ReminderChannelPlanTest.kt | 13 ++- docs/ARCHITECTURE.md | 13 +-- floret-kit | 2 +- 10 files changed, 160 insertions(+), 102 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt index ac3c33b4..08680726 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt @@ -277,17 +277,16 @@ class SettingsPrefs @Inject constructor( suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) /** - * Move [calendarId]'s reminder channel to a new version, at least [atLeast], - * and return it. Versions only grow: the system would restore a deleted - * channel's old settings if its id came back (#518). + * 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 bumpReminderChannelVersion(calendarId: Long, atLeast: Int): Int { - var next = 0 - prefs.update(SettingsKeys.reminderChannelVersions) { current -> - next = maxOf((current[calendarId] ?: 0) + 1, atLeast) - current + (calendarId to next) + suspend fun reserveReminderChannelVersions(floors: Map): Map { + val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current -> + current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) } } - return next + return floors.keys.associateWith { stored.getValue(it) } } suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true) @@ -630,9 +629,10 @@ object SettingsKeys { val notificationCategoryHintDismissed: Pref = booleanPref("notification_category_hint_dismissed", false) /** - * Each calendar's reminder channel version (#518): a sound picked in the app - * recreates the channel under the next one. Absent = 0, the unversioned id. - * Serialised as `id=version;id=version`. + * 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> = nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt index 0d278fda..0359798a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -30,6 +30,18 @@ fun parseReminderChannelId(channelId: String): Pair? { 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, highWater: Map): Map { + 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,12 +72,6 @@ data class ReminderChannelSpec( * fires, so its channel only appears once something posts on it. */ val upFront: Boolean = true, - /** - * An older version of this calendar's channel to copy behaviour from when - * this one is missing, so a version bump that never got written loses no - * settings. - */ - val templateId: String? = null, ) /** What a channel already looks like in the system, as far as the plan compares it. */ @@ -121,21 +127,13 @@ fun planReminderChannels( } } val existingById = existing.associateBy { it.id } - val versionsByCalendar = existing.mapNotNull { parseReminderChannelId(it.id) }.groupBy({ it.first }, { it.second }) val channels = calendars.map { calendar -> - val version = versions[calendar.id] ?: 0 - val id = reminderChannelId(calendar.id, version) ReminderChannelSpec( - id = 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, - templateId = versionsByCalendar[calendar.id] - ?.filter { it != version } - ?.maxOrNull() - ?.let { reminderChannelId(calendar.id, it) } - ?.takeIf { id !in existingById }, ) } val wantedChannels = channels.mapTo(HashSet()) { it.id } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 21268647..ec9675b3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -54,7 +54,7 @@ class ReminderChannels @Inject constructor( val manager = manager val existing = manager.notificationChannels val existingIds = existing.mapTo(HashSet()) { it.id } - val versions = versions() + val versions = currentVersions(existingIds) 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 }, versions, showingChannelIds()) @@ -83,7 +83,8 @@ class ReminderChannels @Inject constructor( versions, ) - private fun versions(): Map = runBlocking { settingsPrefs.reminderChannelVersions.first() } + private fun currentVersions(existingChannelIds: Collection): Map = + currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) /** Channels with a notification on screen; on failure every channel counts, so none is deleted. */ private fun showingChannelIds(): Set = runCatching { @@ -102,11 +103,11 @@ class ReminderChannels @Inject constructor( */ @Synchronized fun channelFor(calendarId: Long): String? { - val versions = versions() - val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) val manager = manager - if (manager.getNotificationChannel(id) != null) return id val existing = manager.notificationChannels + val versions = currentVersions(existing.map { it.id }) + val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) + if (existing.any { it.id == id }) return id val calendars = try { calendarDataSource.calendars() } catch (e: Exception) { @@ -138,11 +139,12 @@ class ReminderChannels @Inject constructor( fun status(calendarIds: Collection): 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, versions()) + return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys)) } /** @@ -150,43 +152,51 @@ class ReminderChannels @Inject constructor( * calendar whose channel doesn't exist yet is left out. */ fun sounds(calendarIds: Collection): Map { - val versions = versions() - val manager = manager + val byId = manager.notificationChannels.associateBy { it.id } + val versions = currentVersions(byId.keys) return calendarIds.mapNotNull { id -> - manager.getNotificationChannel(reminderChannelId(id, versions[id] ?: 0))?.let { id to it.sound } + byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.sound } }.toMap() } /** - * Give [calendarId]'s reminders [sound] (null = silent). A channel's sound is - * fixed once created, so this moves the calendar to a new channel version - * carrying over everything else, and retires the old one. Returns whether - * the calendar had a channel to move. + * 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 (#518). Calendars without a + * channel are skipped unless [createMissing]. */ - suspend fun setSound(calendarId: Long, sound: Uri?): Boolean { - val oldId = channelFor(calendarId) ?: return false - val floor = manager.notificationChannels - .mapNotNull { parseReminderChannelId(it.id) } - .filter { it.first == calendarId } - .maxOfOrNull { it.second + 1 } ?: 1 - val version = settingsPrefs.bumpReminderChannelVersion(calendarId, atLeast = floor) - return recreate(oldId, reminderChannelId(calendarId, version), sound) + suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: 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 + recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } + /** Create each calendar's [versions] from its current channel, then retire the old one. */ @Synchronized - private fun recreate(oldId: String, newId: String, sound: Uri?): Boolean { + private fun recreate(versions: Map, sound: Uri?) { val manager = manager - val old = manager.getNotificationChannel(oldId) ?: return false - val channel = NotificationChannel(newId, old.name, old.importance).apply { - description = old.description - old.group?.let { group = it } - inheritFrom(old) - setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + val byId = manager.notificationChannels.associateBy { it.id } + val current = currentReminderChannelVersions(byId.keys, emptyMap()) + val showing = showingChannelIds() + versions.forEach { (calendarId, version) -> + val from = current[calendarId]?.takeIf { it < version } ?: return@forEach + val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach + manager.createNotificationChannel( + NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + }, + ) + if (old.id !in showing) manager.deleteNotificationChannel(old.id) } - manager.createNotificationChannel(channel) - if (oldId !in showingChannelIds()) manager.deleteNotificationChannel(oldId) lastSync = null - return true } private fun plan( @@ -217,12 +227,11 @@ class ReminderChannels @Inject constructor( if (channels.isEmpty()) return val byId = existing.associateBy { it.id } val description = context.getString(R.string.reminder_channel_description) - val legacy = byId[LEGACY_REMINDER_CHANNEL_ID] + 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] - val template = spec.templateId?.let(byId::get) ?: legacy NotificationChannel( spec.id, spec.name, @@ -237,8 +246,9 @@ 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, badge and lock-screen choice + * 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). */ private fun NotificationChannel.inheritFrom(template: NotificationChannel) { setSound(template.sound, template.audioAttributes) @@ -248,6 +258,8 @@ class ReminderChannels @Inject constructor( enableLights(template.shouldShowLights()) lightColor = template.lightColor setShowBadge(template.canShowBadge()) + // The system only keeps a private or secret choice; "public" resets to its default. + lockscreenVisibility = template.lockscreenVisibility // Only honoured with Do Not Disturb access, so usually left to the user. setBypassDnd(template.canBypassDnd()) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index f9242301..26254258 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -129,15 +129,24 @@ internal fun NotificationsScreen( val target = soundTarget soundTarget = null val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult - val ids = if (target == ALL_CALENDARS) calendarIds else listOfNotNull(target) - viewModel.setReminderSound(ids, picked.uri) + 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 = { target -> - val current = if (target == ALL_CALENDARS) sharedSound(sounds, calendarIds)?.uri else sounds[target]?.uri + val current = if (target == ALL_CALENDARS) { + (sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound + } else { + sounds[target] + } soundTarget = target try { - soundPicker.launch(notificationSoundPickerIntent(current ?: DEFAULT_NOTIFICATION_URI, pickSoundTitle)) + // 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: ActivityNotFoundException) { soundTarget = null if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target) @@ -458,22 +467,39 @@ private fun CalendarNotificationRows( /** [soundTarget] meaning every calendar at once. */ private const val ALL_CALENDARS = Long.MIN_VALUE -/** The sound every one of [calendarIds] shares, or null when they differ or one has no channel yet. */ -private fun sharedSound(sounds: Map, calendarIds: List): ReminderSound? = - calendarIds.map { sounds[it] }.distinctBy { it?.uri }.singleOrNull() +/** 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, calendarIds: List): 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) - else -> sound.title ?: stringResource(R.string.settings_notification_sound_default) + 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, calendarIds: List): String { - val shared = calendarIds.map { sounds[it] }.distinctBy { it?.uri } - return if (shared.size == 1) soundLabel(shared.single()) else stringResource(R.string.settings_notification_sound_mixed) -} +private fun globalSoundLabel(sounds: Map, calendarIds: List): 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) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 6f159311..7f341726 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -61,6 +61,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 @@ -397,29 +398,40 @@ class SettingsViewModel @Inject constructor( fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() channelStatusJob = viewModelScope.launch { - val (status, sounds) = onChannels { status(calendarIds) to sounds(calendarIds) } ?: return@launch - _channelStatus.value = status + 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 { appContext.ringtoneTitle(it) }) } + val titles = sounds.values.filterNotNull().distinct().associateWith { appContext.ringtoneTitle(it) } + sounds.mapValues { (_, uri) -> ReminderSound(uri, uri?.let(titles::get)) } } } } - /** Give [calendarIds]' reminders [sound] (null = silent), each on a fresh channel (#518). */ - fun setReminderSound(calendarIds: Collection, sound: Uri?) { + /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ + fun setReminderSound(calendarId: Long, sound: Uri?) = applySound { 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 { + sync() + setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false) + } + + private fun applySound(block: suspend ReminderChannels.() -> Unit) { viewModelScope.launch { withContext(io) { - calendarIds.forEach { id -> - try { - reminderChannels.setSound(id, sound) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.w("SettingsViewModel", "Could not set the reminder sound of calendar $id", e) - } + try { + reminderChannels.block() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("SettingsViewModel", "Could not set the reminder sound", e) } } - refreshChannelStatus(state.value.reminderCalendars.map { it.id }) + refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e8df57c..cc0a428f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -738,6 +738,9 @@ Notification sound Silent Default + + Default (%1$s) + Custom sound Differs per calendar More notification settings Vibration, pop-ups and more for each calendar, in system settings diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index 42f7fd71..765c4448 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -620,9 +620,8 @@ class SettingsPrefsTest { ) = runTest { val prefs = testSettings(tempDir) assertThat(prefs.reminderChannelVersions.first()).isEmpty() - assertThat(prefs.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(1) - assertThat(prefs.bumpReminderChannelVersion(7L, atLeast = 1)).isEqualTo(2) - assertThat(prefs.bumpReminderChannelVersion(9L, atLeast = 5)).isEqualTo(5) + 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) } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt index 92c5ed36..de783fe3 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -172,9 +172,16 @@ class ReminderChannelPlanTest { 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)) - // A bump the recreate never wrote still inherits from the version before it. - assertThat(plan.channelsToWrite.map { it.templateId }) - .containsExactly(reminderChannelId(1), 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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e40d484f..e9ca44e5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -405,12 +405,13 @@ 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 the calendar's next version -(`reminders.calendar..v`, counter in `SettingsPrefs.reminderChannelVersions` -— it only grows, because a re-used id would bring back the deleted channel's -settings), copying everything else from the old one. The sync treats older -versions as stale, keeps one while a notification still shows on it, and a -version that was counted but never written inherits from the one before it. +`ReminderChannels.setSound` recreates it under a new version +(`reminders.calendar..v`), 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). The sync treats older versions as stale and +keeps one while a notification still shows on it. 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 diff --git a/floret-kit b/floret-kit index ede5ebfd..8dc244fc 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit ede5ebfdc85532422fad7e6a30709f720808a02d +Subproject commit 8dc244fc331935ca0f7f9f04715fec928ebc91af From 661300728a96a1aa48bdd06d946479e9b053ecec Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 04:06:32 +0100 Subject: [PATCH 3/6] =?UTF-8?q?fix(#518):=20review=20round=202=20=E2=80=94?= =?UTF-8?q?=20late=20channel=20resolve,=20failure=20feedback,=20no=20sound?= =?UTF-8?q?=20flash,=20safer=20picks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannels.kt | 71 +++++++++++-------- .../data/reminders/ReminderNotifier.kt | 19 ++--- .../ui/settings/NotificationSettings.kt | 20 ++++-- .../ui/settings/SettingsViewModel.kt | 27 ++++--- app/src/main/res/values/strings.xml | 1 + floret-kit | 2 +- 6 files changed, 89 insertions(+), 51 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index ec9675b3..3ef3f2a4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -54,7 +54,7 @@ class ReminderChannels @Inject constructor( val manager = manager val existing = manager.notificationChannels val existingIds = existing.mapTo(HashSet()) { it.id } - val versions = currentVersions(existingIds) + 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 }, versions, showingChannelIds()) @@ -83,6 +83,14 @@ class ReminderChannels @Inject constructor( 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 = emptyMap() + private fun currentVersions(existingChannelIds: Collection): Map = currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) @@ -104,8 +112,12 @@ class ReminderChannels @Inject constructor( @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 }) + 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 { @@ -163,40 +175,49 @@ class ReminderChannels @Inject constructor( * 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 (#518). Calendars without a - * channel are skipped unless [createMissing]. + * channel are skipped unless [createMissing]. Returns whether every move + * went through. */ - suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: Boolean) { + suspend fun setSound(calendarIds: Collection, 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 - recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) + if (floors.isEmpty()) return true + return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } /** Create each calendar's [versions] from its current channel, then retire the old one. */ @Synchronized - private fun recreate(versions: Map, sound: Uri?) { + private fun recreate(versions: Map, sound: Uri?): Boolean { val manager = manager val byId = manager.notificationChannels.associateBy { it.id } val current = currentReminderChannelVersions(byId.keys, emptyMap()) val showing = showingChannelIds() + var allApplied = true versions.forEach { (calendarId, version) -> val from = current[calendarId]?.takeIf { it < version } ?: return@forEach val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach - manager.createNotificationChannel( - NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply { - description = old.description - old.group?.let { group = it } - inheritFrom(old) - setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) - }, - ) - if (old.id !in showing) manager.deleteNotificationChannel(old.id) + try { + manager.createNotificationChannel( + NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + }, + ) + knownVersions = knownVersions + (calendarId to version) + if (old.id !in showing) manager.deleteNotificationChannel(old.id) + } 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( @@ -246,9 +267,10 @@ class ReminderChannels @Inject constructor( } /** - * Carry a channel's sound, vibration, lights, badge and lock-screen choice - * 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). + * 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) @@ -258,8 +280,6 @@ class ReminderChannels @Inject constructor( enableLights(template.shouldShowLights()) lightColor = template.lightColor setShowBadge(template.canShowBadge()) - // The system only keeps a private or secret choice; "public" resets to its default. - lockscreenVisibility = template.lockscreenVisibility // Only honoured with Do Not Disturb access, so usually left to the user. setBypassDnd(template.canBypassDnd()) } @@ -272,12 +292,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() if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) return !showing } @@ -293,7 +308,7 @@ class ReminderChannels @Inject constructor( const val TAG = "ReminderChannels" val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) + .setUsage(AudioAttributes.USAGE_NOTIFICATION) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index f7a4fd46..47bd2cd7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -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,16 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" · ") + // Resolved last, so a sound picked meanwhile (#518) can't retire it before notify. + 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 notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index 26254258..be5b6fcf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -8,6 +8,7 @@ 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 @@ -27,6 +28,7 @@ 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 @@ -122,7 +124,14 @@ internal fun NotificationsScreen( context.openNotificationSettings() } } - val sounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val sounds = loadedSounds.orEmpty() + val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed) + LaunchedEffect(Unit) { + viewModel.soundFailed.collect { + Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show() + } + } // ALL_CALENDARS, a calendar id, or null when no pick is pending. var soundTarget by rememberSaveable { mutableStateOf(null) } val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> @@ -136,7 +145,8 @@ internal fun NotificationsScreen( } } val pickSoundTitle = stringResource(R.string.settings_notification_sound) - val pickSound: (Long) -> Unit = { target -> + 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 { @@ -179,7 +189,7 @@ internal fun NotificationsScreen( if (calendarIds.isNotEmpty()) { GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = globalSoundLabel(sounds, calendarIds), + summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) }, position = Position.Middle, onClick = { pickSound(ALL_CALENDARS) }, ) @@ -293,7 +303,7 @@ internal fun NotificationsScreen( state = state, notifying = notifying, blocked = blocked, - soundLabel = soundLabel(sounds[calendar.id]), + soundLabel = loadedSounds?.let { soundLabel(it[calendar.id]) }, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, onPickSound = { pickSound(calendar.id) }, onOpenSettings = { openCalendarSettings(calendar.id) }, @@ -397,7 +407,7 @@ private fun CalendarNotificationRows( state: SettingsUiState, notifying: Boolean, blocked: Boolean, - soundLabel: String, + soundLabel: String?, onSetNotifying: (Boolean) -> Unit, onPickSound: () -> Unit, onOpenSettings: () -> Unit, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 7f341726..f4bf87b6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -53,6 +53,7 @@ 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.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -390,10 +391,15 @@ class SettingsViewModel @Inject constructor( private var channelStatusJob: Job? = null - private val _channelSounds = MutableStateFlow>(emptyMap()) + private val _channelSounds = MutableStateFlow?>(null) - /** Each calendar's reminder sound (#518); a calendar without a channel yet is absent. */ - val channelSounds: StateFlow> = _channelSounds.asStateFlow() + /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ + val channelSounds: StateFlow?> = _channelSounds.asStateFlow() + + private val _soundFailed = MutableSharedFlow(extraBufferCapacity = 1) + + /** Emits when a picked sound couldn't be applied to every calendar. */ + val soundFailed: SharedFlow = _soundFailed fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() @@ -416,21 +422,26 @@ class SettingsViewModel @Inject constructor( * that only get a channel when something posts are left alone. */ fun setReminderSoundForAll(sound: Uri?) = applySound { - sync() + try { + sync() + } catch (e: Exception) { + Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) + } setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false) } - private fun applySound(block: suspend ReminderChannels.() -> Unit) { + /** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */ + private fun applySound(block: suspend ReminderChannels.() -> Boolean) { viewModelScope.launch { - withContext(io) { + val applied = withContext(io + NonCancellable) { try { reminderChannels.block() - } catch (e: CancellationException) { - throw e } catch (e: Exception) { Log.w("SettingsViewModel", "Could not set the reminder sound", e) + false } } + if (!applied) _soundFailed.tryEmit(Unit) refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cc0a428f..8943542d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -741,6 +741,7 @@ Default (%1$s) Custom sound + Couldn\'t change the sound for every calendar Differs per calendar More notification settings Vibration, pop-ups and more for each calendar, in system settings diff --git a/floret-kit b/floret-kit index 8dc244fc..40ef6992 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 8dc244fc331935ca0f7f9f04715fec928ebc91af +Subproject commit 40ef6992ae205a880272c47e396269d336762d83 From 081675906b4a1aa120dac680f5117078dc6aa7d4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 04:13:36 +0100 Subject: [PATCH 4/6] =?UTF-8?q?fix(#518):=20review=20round=203=20=E2=80=94?= =?UTF-8?q?=20post=20under=20the=20channel=20lock,=20refuse=20unreadable?= =?UTF-8?q?=20sounds,=20audible=20importance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannels.kt | 47 +++++++++++++------ .../data/reminders/ReminderNotifier.kt | 15 +++--- .../ui/settings/SettingsViewModel.kt | 34 ++++++++++---- docs/ARCHITECTURE.md | 6 ++- 4 files changed, 70 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 3ef3f2a4..4cd51d44 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -1,8 +1,12 @@ 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 @@ -57,7 +61,11 @@ class ReminderChannels @Inject constructor( 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 }, versions, showingChannelIds()) + 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() } @@ -94,12 +102,12 @@ class ReminderChannels @Inject constructor( private fun currentVersions(existingChannelIds: Collection): Map = currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) - /** Channels with a notification on screen; on failure every channel counts, so none is deleted. */ - private fun showingChannelIds(): Set = runCatching { + /** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */ + private fun showingChannelIds(candidates: Collection): Set = runCatching { manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId } }.getOrElse { e -> Log.w(TAG, "Could not read active notifications", e) - manager.notificationChannels.mapTo(HashSet()) { it.id } + candidates.toSet() } /** @@ -147,6 +155,13 @@ 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 when the calendar is gone. + */ + @Synchronized + fun withChannel(calendarId: Long, block: (String) -> T): T? = channelFor(calendarId)?.let(block) + /** What the system currently lets through for [calendarIds]' reminders (#145). */ fun status(calendarIds: Collection): ReminderChannelStatus { val manager = manager @@ -174,7 +189,7 @@ class ReminderChannels @Inject constructor( /** * 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 (#518). Calendars without a + * 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. */ @@ -189,20 +204,28 @@ class ReminderChannels @Inject constructor( return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } - /** Create each calendar's [versions] from its current channel, then retire the old one. */ + /** + * 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, sound: Uri?): Boolean { val manager = manager val byId = manager.notificationChannels.associateBy { it.id } val current = currentReminderChannelVersions(byId.keys, emptyMap()) - val showing = showingChannelIds() var allApplied = true versions.forEach { (calendarId, version) -> val from = current[calendarId]?.takeIf { it < version } ?: return@forEach val old = byId[reminderChannelId(calendarId, from)] ?: 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, old.importance).apply { + NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply { description = old.description old.group?.let { group = it } inheritFrom(old) @@ -210,7 +233,6 @@ class ReminderChannels @Inject constructor( }, ) knownVersions = knownVersions + (calendarId to version) - if (old.id !in showing) manager.deleteNotificationChannel(old.id) } catch (e: RuntimeException) { Log.w(TAG, "Could not move calendar $calendarId to a new sound", e) allApplied = false @@ -292,7 +314,7 @@ class ReminderChannels @Inject constructor( 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() + val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID)) if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) return !showing } @@ -307,10 +329,7 @@ class ReminderChannels @Inject constructor( private companion object { const val TAG = "ReminderChannels" - val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION) - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .build() + val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 47bd2cd7..d9b196ae 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -87,16 +87,19 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" · ") - // Resolved last, so a sound picked meanwhile (#518) can't retire it before notify. - val channelId = try { - channels.channelFor(alert.calendarId) ?: run { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") - return - } + val posted = try { + // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. + channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) } } catch (e: Exception) { Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) return } + if (posted == null) { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + } + } + + private fun notify(alert: ReminderAlert, channelId: String, title: String, text: String) { val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index f4bf87b6..56cb4ed5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -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 @@ -54,6 +55,8 @@ 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 @@ -396,10 +399,12 @@ class SettingsViewModel @Inject constructor( /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ val channelSounds: StateFlow?> = _channelSounds.asStateFlow() - private val _soundFailed = MutableSharedFlow(extraBufferCapacity = 1) + private val _soundFailed = Channel(Channel.CONFLATED) - /** Emits when a picked sound couldn't be applied to every calendar. */ - val soundFailed: SharedFlow = _soundFailed + /** Emits when a picked sound couldn't be applied to every calendar; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() + + private val soundTitles = mutableMapOf() fun refreshChannelStatus(calendarIds: Collection) { channelStatusJob?.cancel() @@ -407,41 +412,50 @@ class SettingsViewModel @Inject constructor( onChannels { status(calendarIds) }?.let { _channelStatus.value = it } val sounds = onChannels { sounds(calendarIds) } ?: return@launch _channelSounds.value = withContext(io) { - val titles = sounds.values.filterNotNull().distinct().associateWith { appContext.ringtoneTitle(it) } - sounds.mapValues { (_, uri) -> ReminderSound(uri, uri?.let(titles::get)) } + sounds.mapValues { (_, uri) -> + ReminderSound(uri, uri?.let { synchronized(soundTitles) { soundTitles.getOrPut(it) { appContext.ringtoneTitle(it) } } }) + } } } } /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ - fun setReminderSound(calendarId: Long, sound: Uri?) = applySound { setSound(listOf(calendarId), sound, createMissing = true) } + 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 { + fun setReminderSoundForAll(sound: Uri?) = applySound(sound) { try { sync() } catch (e: Exception) { Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) } - setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false) + 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(block: suspend ReminderChannels.() -> Boolean) { + private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) { viewModelScope.launch { val applied = withContext(io + NonCancellable) { try { + // The system plays the sound but checks that Calendula could read it. + if (sound != null && !canRead(sound)) return@withContext false reminderChannels.block() } catch (e: Exception) { Log.w("SettingsViewModel", "Could not set the reminder sound", e) false } } - if (!applied) _soundFailed.tryEmit(Unit) + if (!applied) _soundFailed.trySend(Unit) refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e9ca44e5..a15dfbc9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -410,8 +410,10 @@ the app (#518) can't be set on an existing channel, so 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). The sync treats older versions as stale and -keeps one while a notification still shows on it. +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 From d39ceb9ee0cfd16e3306ddc2730c792db8e5e246 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 04:21:27 +0100 Subject: [PATCH 5/6] =?UTF-8?q?fix(#518):=20review=20round=204=20=E2=80=94?= =?UTF-8?q?=20silent=20channels=20read=20as=20silent,=20honest=20pick=20re?= =?UTF-8?q?sults,=20clearer=20failures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannels.kt | 30 +++++++++++++++---- .../data/reminders/ReminderNotifier.kt | 11 ++----- .../ui/settings/NotificationSettings.kt | 10 ++++--- .../calendula/ui/settings/SettingsUiState.kt | 3 ++ .../ui/settings/SettingsViewModel.kt | 27 +++++++++++------ app/src/main/res/values/strings.xml | 3 +- 6 files changed, 56 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 4cd51d44..daee1254 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -157,10 +157,20 @@ class ReminderChannels @Inject constructor( /** * Run [block] with [calendarId]'s channel held: no sound pick or sync can - * move or retire it until [block] returns. Null when the calendar is gone. + * 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 withChannel(calendarId: Long, block: (String) -> T): T? = channelFor(calendarId)?.let(block) + fun 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): ReminderChannelStatus { @@ -174,6 +184,10 @@ class ReminderChannels @Inject constructor( 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. @@ -182,7 +196,7 @@ class ReminderChannels @Inject constructor( 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.sound } + byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() } }.toMap() } @@ -200,7 +214,7 @@ class ReminderChannels @Inject constructor( val floors = calendarIds .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } .associateWith { (current[it] ?: 0) + 1 } - if (floors.isEmpty()) return true + if (floors.isEmpty()) return false return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) } @@ -215,8 +229,12 @@ class ReminderChannels @Inject constructor( val current = currentReminderChannelVersions(byId.keys, emptyMap()) var allApplied = true versions.forEach { (calendarId, version) -> - val from = current[calendarId]?.takeIf { it < version } ?: return@forEach - val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach + 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) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index d9b196ae..81d9a791 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -87,15 +87,10 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" · ") - val posted = try { - // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. - channels.withChannel(alert.calendarId) { channelId -> notify(alert, channelId, title, text) } - } catch (e: Exception) { - Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) - return - } + // 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}: calendar ${alert.calendarId} is gone") + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}") } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index be5b6fcf..d926912e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -1,7 +1,6 @@ package de.jeanlucmakiola.calendula.ui.settings import android.Manifest -import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Build @@ -127,9 +126,11 @@ internal fun NotificationsScreen( 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 { - Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show() + 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. @@ -157,7 +158,8 @@ internal fun NotificationsScreen( // 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: ActivityNotFoundException) { + } 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) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 261c1c60..c4902c6b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -140,3 +140,6 @@ data class SpecialDatesUiState( /** 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 } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 56cb4ed5..def50ab1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -399,10 +399,10 @@ class SettingsViewModel @Inject constructor( /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ val channelSounds: StateFlow?> = _channelSounds.asStateFlow() - private val _soundFailed = Channel(Channel.CONFLATED) + private val _soundFailed = Channel(Channel.CONFLATED) - /** Emits when a picked sound couldn't be applied to every calendar; kept until the screen collects it. */ - val soundFailed: Flow = _soundFailed.receiveAsFlow() + /** Emits when a picked sound couldn't be applied; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() private val soundTitles = mutableMapOf() @@ -413,12 +413,18 @@ class SettingsViewModel @Inject constructor( val sounds = onChannels { sounds(calendarIds) } ?: return@launch _channelSounds.value = withContext(io) { sounds.mapValues { (_, uri) -> - ReminderSound(uri, uri?.let { synchronized(soundTitles) { soundTitles.getOrPut(it) { appContext.ringtoneTitle(it) } } }) + 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) @@ -445,17 +451,20 @@ class SettingsViewModel @Inject constructor( /** 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 applied = withContext(io + NonCancellable) { + val failure = withContext(io + NonCancellable) { try { // The system plays the sound but checks that Calendula could read it. - if (sound != null && !canRead(sound)) return@withContext false - reminderChannels.block() + 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) - false + SoundFailure.NotApplied } } - if (!applied) _soundFailed.trySend(Unit) + failure?.let(_soundFailed::trySend) refreshChannelStatus(visibleCalendars.first().map { it.id }) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8943542d..5cb0d084 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -741,7 +741,8 @@ Default (%1$s) Custom sound - Couldn\'t change the sound for every calendar + Couldn\'t change the notification sound + Calendula can\'t play this sound. Pick another one. Differs per calendar More notification settings Vibration, pop-ups and more for each calendar, in system settings From 74549b2ec093a2b8ac3ca5b3ae890cf4ab1c1d6d Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 21:05:39 +0100 Subject: [PATCH 6/6] fix(#518): retire the old channel versions right after a sound pick --- .../calendula/data/reminders/ReminderChannels.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index daee1254..e74edb3f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -203,7 +203,7 @@ class ReminderChannels @Inject constructor( /** * 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 + * 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. */ @@ -215,7 +215,14 @@ class ReminderChannels @Inject constructor( .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } .associateWith { (current[it] ?: 0) + 1 } if (floors.isEmpty()) return false - return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) + 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 } /**