From 994fc1026fd449c9343f32fdb72bb75b911da09e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:14:54 +0100 Subject: [PATCH] feat(#145, #272, #340): per-calendar reminder channels, in-app mute and sound deep-links --- .../calendula/data/prefs/CalendarPrefs.kt | 2 +- .../calendula/data/prefs/SettingsPrefs.kt | 11 ++ .../data/reminders/ReminderChannelPlan.kt | 105 +++++++++++++ .../data/reminders/ReminderChannels.kt | 138 +++++++++++++++++ .../data/reminders/ReminderNotifier.kt | 39 ++--- .../data/reminders/ReminderScanner.kt | 19 +++ .../ui/settings/NotificationSettings.kt | 146 +++++++++++++----- .../calendula/ui/settings/SettingsUiState.kt | 4 + .../ui/settings/SettingsViewModel.kt | 24 ++- app/src/main/res/values/strings.xml | 8 +- .../calendula/data/prefs/SettingsPrefsTest.kt | 13 ++ .../data/reminders/ReminderChannelPlanTest.kt | 83 ++++++++++ docs/ARCHITECTURE.md | 12 ++ floret-kit | 2 +- 14 files changed, 530 insertions(+), 76 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt index f75b69a4..c99dd887 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt @@ -81,7 +81,7 @@ class CalendarPrefs @Inject constructor( } /** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */ -private fun idSetPref(name: String): Pref> = nullableStringPref(name).map( +internal fun idSetPref(name: String): Pref> = nullableStringPref(name).map( { stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() }, { ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") }, ) 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 793c01e9..bd98b6ab 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 @@ -166,6 +166,7 @@ class SettingsPrefs @Inject constructor( val defaultEventDurationMinutes: Flow = prefs.flow(SettingsKeys.defaultEventDurationMinutes) val perCalendarEventDuration: Flow> = prefs.flow(SettingsKeys.perCalendarEventDuration) val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) + val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -273,6 +274,10 @@ class SettingsPrefs @Inject constructor( suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) + suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { + prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId } + } + suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled) @@ -594,6 +599,12 @@ object SettingsKeys { */ val remindersEnabled: Pref = booleanPref("reminders_enabled", true) + /** + * Calendars whose reminders Calendula doesn't post (#272), independent of + * `Calendars.VISIBLE`: the events still show, only the notifications stop. + */ + val mutedReminderCalendarIds: Pref> = idSetPref("muted_reminder_calendar_ids") + /** * 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 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 new file mode 100644 index 00000000..4eb99f89 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -0,0 +1,105 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import de.jeanlucmakiola.calendula.domain.CalendarSource + +/** The single channel every reminder posted on before they moved per calendar (#145). */ +const val LEGACY_REMINDER_CHANNEL_ID = "reminders" + +private const val CHANNEL_PREFIX = "reminders.calendar." +private const val GROUP_PREFIX = "reminders.account." +private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local" + +/** The notification channel [calendarId]'s reminders post on. */ +fun reminderChannelId(calendarId: Long): String = CHANNEL_PREFIX + calendarId + +/** Whether [channelId] is one of the per-calendar reminder channels. */ +fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX) + +/** Whether [groupId] is one of the per-account reminder channel groups. */ +fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX) + +/** + * One account's channel group. The app's own device calendars share a single + * group; [ambiguous] marks a name another group shows under a different type, + * so the label can name the source app as well. + */ +data class ReminderChannelGroupSpec( + val id: String, + val accountName: String, + val accountType: String, + val isLocal: Boolean, + val ambiguous: Boolean, +) + +data class ReminderChannelSpec( + val id: String, + val calendarId: Long, + /** The calendar's display name; blank when it has none. */ + val name: String, + val groupId: String, +) + +data class ReminderChannelPlan( + val groups: List, + /** Every channel that should exist; creating an existing one only refreshes its name. */ + val channels: List, + val staleChannelIds: List, + val staleGroupIds: List, +) + +/** + * What the reminder channels should look like for [calendars]: one channel per + * calendar inside a group per account, and the reminder channels and groups in + * [existingChannelIds] / [existingGroupIds] that no calendar claims any more. + * Ids outside the reminder namespace (the backup channel, the legacy channel) + * are never touched. + */ +fun planReminderChannels( + calendars: List, + existingChannelIds: Collection, + existingGroupIds: Collection, +): ReminderChannelPlan { + val groupsByKey = calendars.groupBy(::accountKey) + val nameCounts = groupsByKey.keys.filterNotNull().groupingBy { it.first }.eachCount() + val groups = groupsByKey.map { (key, members) -> + if (key == null) { + ReminderChannelGroupSpec( + id = LOCAL_GROUP_ID, + accountName = members.first().accountName, + accountType = members.first().accountType, + isLocal = true, + ambiguous = false, + ) + } else { + val (name, type) = key + ReminderChannelGroupSpec( + id = "$GROUP_PREFIX$type/$name", + accountName = name, + accountType = type, + isLocal = false, + ambiguous = nameCounts.getValue(name) > 1, + ) + } + } + val groupIdByKey = groupsByKey.keys.zip(groups.map { it.id }).toMap() + val channels = calendars.map { calendar -> + ReminderChannelSpec( + id = reminderChannelId(calendar.id), + calendarId = calendar.id, + name = calendar.displayName, + groupId = groupIdByKey.getValue(accountKey(calendar)), + ) + } + val wantedChannels = channels.mapTo(HashSet()) { it.id } + val wantedGroups = groups.mapTo(HashSet()) { it.id } + return ReminderChannelPlan( + groups = groups, + channels = channels, + staleChannelIds = existingChannelIds.filter { isReminderChannelId(it) && it !in wantedChannels }, + staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups }, + ) +} + +/** The app's own device calendars share one group (null); every other account has its own. */ +private fun accountKey(calendar: CalendarSource): Pair? = + if (calendar.isLocal) null else calendar.accountName to calendar.accountType 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 new file mode 100644 index 00000000..a4422687 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -0,0 +1,138 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.NotificationChannel +import android.app.NotificationChannelGroup +import android.app.NotificationManager +import android.content.Context +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.CalendarPrefs +import de.jeanlucmakiola.calendula.ui.common.sourceAppPackages +import kotlinx.coroutines.flow.first +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The reminder notification channels: one per switched-on calendar, grouped + * by account (#145), so each calendar can be muted or given its own sound in + * the system settings before it ever fires. + * + * A channel the user has touched keeps their settings; [sync] only creates the + * missing ones, refreshes names, and deletes channels whose calendar is gone or + * switched off — the system restores a deleted channel's settings if its id + * comes back. + */ +@Singleton +class ReminderChannels @Inject constructor( + @ApplicationContext private val context: Context, + private val calendarDataSource: CalendarDataSource, + private val calendarPrefs: CalendarPrefs, +) { + private val manager: NotificationManager + get() = context.getSystemService(NotificationManager::class.java) + + /** Bring the channels in line with the provider's switched-on calendars. */ + suspend fun sync() { + val pending = calendarPrefs.pendingDisabledCalendarIds.first() + val calendars = calendarDataSource.calendars().filter { it.isVisibleInSystem && it.id !in pending } + val manager = manager + val plan = planReminderChannels( + calendars = calendars, + existingChannelIds = manager.notificationChannels.map { it.id }, + existingGroupIds = manager.notificationChannelGroups.map { it.id }, + ) + plan.staleChannelIds.forEach(manager::deleteNotificationChannel) + plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) + create(plan) + if (plan.channels.isNotEmpty()) retireLegacyChannel() + } + + /** + * 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. + */ + fun channelFor(calendarId: Long): String? { + val id = reminderChannelId(calendarId) + if (manager.getNotificationChannel(id) != null) return id + val calendar = calendarDataSource.calendars().firstOrNull { it.id == calendarId } ?: return null + create(planReminderChannels(listOf(calendar), emptyList(), emptyList())) + return id + } + + private fun create(plan: ReminderChannelPlan) { + val manager = manager + manager.createNotificationChannelGroups( + plan.groups.map { NotificationChannelGroup(it.id, groupLabel(it)) }, + ) + // Only a channel's first creation sets its behaviour; later calls just + // rename it, so an existing one passes its own importance back. + val template = manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) + val unnamed = context.getString(R.string.calendar_unnamed) + manager.createNotificationChannels( + plan.channels.map { spec -> + val existing = manager.getNotificationChannel(spec.id) + NotificationChannel( + spec.id, + spec.name.ifBlank { unnamed }, + existing?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = context.getString(R.string.reminder_channel_description) + group = spec.groupId + if (existing == null && template != null) inheritFrom(template) + } + }, + ) + } + + /** + * Carry the old single channel's sound, vibration and lock-screen choices + * over to a new per-calendar one, so an upgrade keeps how reminders sounded. + */ + private fun NotificationChannel.inheritFrom(template: NotificationChannel) { + setSound(template.sound, template.audioAttributes) + enableVibration(template.shouldVibrate()) + vibrationPattern = template.vibrationPattern + enableLights(template.shouldShowLights()) + lightColor = template.lightColor + lockscreenVisibility = template.lockscreenVisibility + setShowBadge(template.canShowBadge()) + } + + /** + * Delete the pre-#145 channel once the per-calendar ones carry its settings, + * but not while a reminder posted on it is still on screen — deleting the + * channel would take that notification with it. + */ + private fun retireLegacyChannel() { + val manager = manager + if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return + 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 + } + if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) + } + + private fun groupLabel(group: ReminderChannelGroupSpec): String { + if (group.isLocal) return context.getString(R.string.calendars_local_header) + val name = group.accountName.ifBlank { group.accountType } + .ifBlank { context.getString(R.string.calendar_unnamed) } + if (!group.ambiguous) return name + return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(group.accountType)) + } + + private fun sourceAppLabel(accountType: String): String { + val pm = context.packageManager + return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg -> + runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull() + } ?: accountType + } + + private companion object { + const val TAG = "ReminderChannels" + } +} 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 215554b4..ec6f8c89 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 @@ -1,8 +1,6 @@ package de.jeanlucmakiola.calendula.data.reminders import android.Manifest -import android.app.NotificationChannel -import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.os.Build @@ -29,8 +27,8 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Posts one notification per occurrence on a dedicated channel. Tapping opens - * the event's detail screen. + * Posts one notification per occurrence on its calendar's channel + * ([ReminderChannels], #145). Tapping opens the event's detail screen. * * The tag is the [occurrenceKey], so each reminder for an occurrence replaces * the one before it in place (#463). A different reminder alerts afresh; the @@ -43,6 +41,7 @@ class ReminderNotifier @Inject constructor( private val settingsPrefs: SettingsPrefs, private val calendarPrefs: CalendarPrefs, private val calendarDataSource: CalendarDataSource, + private val channels: ReminderChannels, ) { /** False when the user declined `POST_NOTIFICATIONS` or muted the app. */ @@ -53,19 +52,20 @@ class ReminderNotifier @Inject constructor( } /** - * The single choke point for "this calendar is switched off", covering the - * two paths that reach [post] around the scan's own filter: a snooze armed - * before the switch-off, and a read-only install whose switch lives in - * [CalendarPrefs]. + * The single choke point for "this calendar posts no reminders": switched + * off (also covering a snooze armed before the switch-off, and a read-only + * install whose switch lives in [CalendarPrefs]), or its notifications + * turned off in Calendula's own settings (#272). */ private suspend fun isSilenced(calendarId: Long): Boolean = - calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || + calendarId in settingsPrefs.mutedReminderCalendarIds.first() || + calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || calendarDataSource.isCalendarVisible(calendarId) == false - /** Post [alert], unless its calendar is switched off. */ + /** Post [alert], unless its calendar is silenced or gone. */ suspend fun post(alert: ReminderAlert) { if (isSilenced(alert.calendarId)) return - ensureChannel() + val channelId = channels.channelFor(alert.calendarId) ?: return val title = displayTitle(alert) val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) @@ -88,7 +88,7 @@ class ReminderNotifier @Inject constructor( yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) val text = listOfNotNull(time, alert.location).joinToString(" · ") - val notification = NotificationCompat.Builder(context, CHANNEL_ID) + val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) @@ -153,7 +153,7 @@ class ReminderNotifier @Inject constructor( private fun cancelLegacy(alert: ReminderAlert) { val manager = NotificationManagerCompat.from(context) manager.activeNotifications - .filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID } + .filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID } .filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) } .filter { it.notification.`when` == alert.beginMillis } .filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) } @@ -181,21 +181,8 @@ class ReminderNotifier @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) - /** Channel creation is idempotent; re-running refreshes the localized name. */ - private fun ensureChannel() { - val channel = NotificationChannel( - CHANNEL_ID, - context.getString(R.string.reminder_channel_name), - NotificationManager.IMPORTANCE_HIGH, - ).apply { - description = context.getString(R.string.reminder_channel_description) - } - NotificationManagerCompat.from(context).createNotificationChannel(channel) - } - private companion object { const val TAG = "ReminderNotifier" - const val CHANNEL_ID = "reminders" // One id, distinct tags: the tag (occurrence) already keys the // notification, so a fixed id keeps cancellation/replacement simple. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt index a67c9b6a..32716da1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders import de.jeanlucmakiola.floret.android.hasPermission import de.jeanlucmakiola.floret.di.IoDispatcher +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.SupervisorJob @@ -43,6 +44,7 @@ class ReminderScanner @Inject constructor( private val source: ReminderInstanceSource, private val calendarDataSource: CalendarDataSource, private val notifier: ReminderNotifier, + private val channels: ReminderChannels, private val snoozes: ReminderSnoozeScheduler, private val alarms: ReminderAlarmScheduler, private val state: ReminderStatePrefs, @@ -76,6 +78,7 @@ class ReminderScanner @Inject constructor( private suspend fun runScan() { val now = System.currentTimeMillis() if (!hasReadCalendar()) return + syncChannels() if (!settingsPrefs.remindersEnabled.first()) { // Reminders off: drop the wake-up, but keep the watermark moving @@ -117,6 +120,22 @@ class ReminderScanner @Inject constructor( alarms.scheduleScan(schedule.nextAlarmMillis) } + /** + * Every trigger that can add, rename or drop a calendar reaches a scan, so + * the channels are kept in step here. A failure never costs the reminders. + */ + private suspend fun syncChannels() { + try { + channels.sync() + } catch (e: CancellationException) { + throw e + } catch (e: SecurityException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Reminder channel sync failed", e) + } + } + private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR) /** 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 b6fd7b28..0dcd416b 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 @@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable @@ -21,6 +22,7 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -31,6 +33,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.DurationPicker import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS @@ -39,6 +42,7 @@ 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.openNotificationSettings import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedRow @@ -50,6 +54,7 @@ import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.minutesOrEmpty import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import kotlinx.coroutines.launch import kotlinx.datetime.LocalTime /** @@ -86,6 +91,10 @@ internal fun NotificationsScreen( var overrideDialog by remember { mutableStateOf(null) } var calendarSectionExpanded by remember { mutableStateOf(false) } var expandedCalendars by remember { mutableStateOf(emptySet()) } + val scope = rememberCoroutineScope() + val openCalendarSound: (Long) -> Unit = { calendarId -> + scope.launch { context.openNotificationSettings(viewModel.reminderChannelFor(calendarId)) } + } CollapsingScaffold( title = stringResource(R.string.settings_section_notifications), @@ -100,6 +109,13 @@ internal fun NotificationsScreen( summary = stringResource(R.string.settings_reminders_hint), position = Position.Top, ) + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = stringResource(R.string.settings_notification_sound_hint), + position = Position.Middle, + trailing = { ExternalLinkIcon() }, + onClick = { context.openNotificationSettings() }, + ) GroupedRow( title = stringResource(R.string.settings_default_reminder), summary = reminderChoiceLabel(state.defaultReminderMinutes), @@ -149,10 +165,10 @@ internal fun NotificationsScreen( onClick = { showSnooze = true }, ) - // Per-calendar overrides, folded behind one header. Each writable - // calendar may keep, drop or replace the global default, separately for - // timed and all-day events. - if (state.writableCalendars.isNotEmpty()) { + // Per-calendar settings, folded behind one header: every switched-on + // calendar gets its notification switch and sound (#145, #272); the ones + // you can edit also keep, drop or replace the default reminders. + if (state.reminderCalendars.isNotEmpty()) { Spacer(Modifier.height(24.dp)) GroupedRow( title = stringResource(R.string.settings_calendar_reminders_title), @@ -167,30 +183,13 @@ internal fun NotificationsScreen( exit = collapseExit(), ) { Column { - state.writableCalendars.forEach { calendar -> + state.reminderCalendars.forEach { calendar -> Spacer(Modifier.height(16.dp)) - // Special-dates calendars own their reminders in their - // own section — link there instead. - if (calendar.id in state.managedCalendarIds) { - GroupedRow( - title = calendar.displayName.orUnnamed(), - summary = stringResource(R.string.settings_calendar_reminders_managed_hint), - position = Position.Alone, - leading = { CalendarColorChip(calendar.color) }, - trailing = { - Icon( - imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - onClick = onOpenSpecialDates, - ) - return@forEach - } val expanded = calendar.id in expandedCalendars + val notifying = calendar.id !in state.mutedReminderCalendarIds GroupedRow( title = calendar.displayName.orUnnamed(), + summary = if (notifying) null else stringResource(R.string.settings_calendar_notifications_off), position = if (expanded) Position.Top else Position.Alone, leading = { CalendarColorChip(calendar.color) }, trailing = { ExpandIcon(expanded) }, @@ -207,22 +206,15 @@ internal fun NotificationsScreen( enter = expandEnter(), exit = collapseExit(), ) { - Column { - val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id) - GroupedRow( - title = stringResource(R.string.settings_default_reminder), - summary = calendarOverrideSummary(timed, state.defaultReminderMinutes), - position = Position.Middle, - onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) }, - ) - val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id) - GroupedRow( - title = stringResource(R.string.settings_default_reminder_allday), - summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes), - position = Position.Bottom, - onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) }, - ) - } + CalendarNotificationRows( + calendar = calendar, + state = state, + notifying = notifying, + onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, + onOpenSound = { openCalendarSound(calendar.id) }, + onOpenSpecialDates = onOpenSpecialDates, + onEditOverride = { overrideDialog = it }, + ) } } } @@ -309,6 +301,80 @@ internal fun NotificationsScreen( } } +/** + * One calendar's expanded rows: its notification switch and channel deep-link + * for every calendar, then the default-reminder overrides where it takes them — + * or, for a special-dates calendar, a link to the section that owns them. + */ +@Composable +private fun CalendarNotificationRows( + calendar: CalendarSource, + state: SettingsUiState, + notifying: Boolean, + onSetNotifying: (Boolean) -> Unit, + onOpenSound: () -> Unit, + onOpenSpecialDates: () -> Unit, + onEditOverride: (OverrideTarget) -> Unit, +) { + val managed = calendar.id in state.managedCalendarIds + val takesOverrides = calendar.canModifyContents && !managed + Column { + GroupedSwitchRow( + title = stringResource(R.string.settings_calendar_notifications), + checked = notifying, + onCheckedChange = onSetNotifying, + summary = stringResource(R.string.settings_calendar_notifications_hint), + position = Position.Middle, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = stringResource(R.string.settings_calendar_notification_sound_hint), + position = if (managed || takesOverrides) Position.Middle else Position.Bottom, + trailing = { ExternalLinkIcon() }, + onClick = onOpenSound, + ) + if (managed) { + GroupedRow( + title = stringResource(R.string.settings_default_reminder_allday), + summary = stringResource(R.string.settings_calendar_reminders_managed_hint), + position = Position.Bottom, + trailing = { + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + onClick = onOpenSpecialDates, + ) + } else if (takesOverrides) { + val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id) + GroupedRow( + title = stringResource(R.string.settings_default_reminder), + summary = calendarOverrideSummary(timed, state.defaultReminderMinutes), + position = Position.Middle, + onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = false)) }, + ) + val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id) + GroupedRow( + title = stringResource(R.string.settings_default_reminder_allday), + summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes), + position = Position.Bottom, + onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = true)) }, + ) + } + } +} + +@Composable +private fun ExternalLinkIcon() { + Icon( + imageVector = Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + /** Which calendar + event kind a per-calendar reminder-override dialog targets. */ private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) 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 d97e7a00..3944032c 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 @@ -98,6 +98,10 @@ data class SettingsUiState( val perCalendarAllDayReminderOverride: Map> = emptyMap(), /** Writable calendars, shown as per-calendar reminder-override rows. */ val writableCalendars: List = emptyList(), + /** Switched-on calendars, each with its own notification switch and channel (#145, #272). */ + val reminderCalendars: List = emptyList(), + /** Calendars whose reminders Calendula doesn't post (#272). */ + val mutedReminderCalendarIds: Set = emptySet(), /** * Whether the event-colour picker is offered on calendars that publish no * colour palette (the colour may then not survive their next sync). 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 812910d8..dad8f8bf 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 @@ -33,6 +33,7 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref +import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventFormField @@ -67,6 +68,7 @@ class SettingsViewModel @Inject constructor( specialDatesSpec: SpecialDatesCalendarSpec, private val launcherNameManager: LauncherNameManager, private val reminderScanner: ReminderScanner, + private val reminderChannels: ReminderChannels, @IoDispatcher private val io: CoroutineDispatcher, @ApplicationContext private val appContext: Context, ) : ViewModel() { @@ -74,16 +76,15 @@ class SettingsViewModel @Inject constructor( private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S /** - * Writable calendars that are switched on — the only ones that take a - * per-calendar reminder override, since a switched-off one plans no - * reminders at all (#75). + * Calendars that are switched on — the only ones that plan reminders at + * all (#75), so the only ones with notification settings. */ - private val writableCalendars: Flow> = repository.calendars() - .map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } } + private val visibleCalendars: Flow> = repository.calendars() + .map { calendars -> calendars.filter { it.isVisibleInSystem } } .catch { emit(emptyList()) } val state: StateFlow = - combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) } + combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) } .stateWhileSubscribed( scope = viewModelScope, initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable), @@ -125,7 +126,9 @@ class SettingsViewModel @Inject constructor( snoozeMinutes = this[SettingsKeys.snoozeMinutes], perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride], perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride], - writableCalendars = calendars, + writableCalendars = calendars.filter { it.canModifyContents }, + reminderCalendars = calendars, + mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds], allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], managedCalendarIds = specialDatesCalendars.values.toSet(), ) @@ -357,6 +360,13 @@ class SettingsViewModel @Inject constructor( } } + fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) = + save { setCalendarRemindersEnabled(calendarId, enabled) } + + /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ + suspend fun reminderChannelFor(calendarId: Long): String? = + withContext(io) { runCatching { reminderChannels.channelFor(calendarId) }.getOrNull() } + fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) } fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 278cc7ca..cc92c56e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -731,7 +731,13 @@ Amount Set Per-calendar reminders - Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own. + Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit. + Notifications + Notify at this calendar\'s reminder times + Notifications off + Notification sound + Sound, vibration and pop-ups for each calendar, in system settings + Sound, vibration and pop-ups 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 d2fb8e65..1e113689 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 @@ -601,6 +601,19 @@ class SettingsPrefsTest { assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30) } + @Test + fun `calendar notifications default on and toggle per calendar`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty() + prefs.setCalendarRemindersEnabled(7L, false) + prefs.setCalendarRemindersEnabled(9L, false) + assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L) + prefs.setCalendarRemindersEnabled(7L, true) + assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L) + } + @Test fun `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 new file mode 100644 index 00000000..83ea80e9 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -0,0 +1,83 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.CalendarSource +import org.junit.jupiter.api.Test + +class ReminderChannelPlanTest { + + private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource( + id = id, + displayName = "Cal $id", + accountName = account, + accountType = type, + color = 0, + isVisibleInSystem = true, + isLocal = local, + ) + + @Test + fun `one channel per calendar, grouped by account`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "me@example.org", "com.google"), + calendar(2, "me@example.org", "com.google"), + calendar(3, "dav", "bitfire.at.davdroid"), + ), + existingChannelIds = emptyList(), + existingGroupIds = emptyList(), + ) + assertThat(plan.groups).hasSize(2) + assertThat(plan.channels.map { it.id }) + .containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3)) + assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId) + assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId) + assertThat(plan.staleChannelIds).isEmpty() + } + + @Test + fun `device calendars share one group`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "Calendula", "LOCAL", local = true), + calendar(2, "Other", "LOCAL", local = true), + ), + existingChannelIds = emptyList(), + existingGroupIds = emptyList(), + ) + assertThat(plan.groups).hasSize(1) + assertThat(plan.groups.single().isLocal).isTrue() + } + + @Test + fun `same account name under two types is ambiguous`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "me@example.org", "com.google"), + calendar(2, "me@example.org", "bitfire.at.davdroid"), + calendar(3, "work", "bitfire.at.davdroid"), + ), + existingChannelIds = emptyList(), + existingGroupIds = emptyList(), + ) + assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType }) + .containsExactly("com.google", "bitfire.at.davdroid") + assertThat(plan.groups.single { it.accountName == "work" }.ambiguous).isFalse() + } + + @Test + fun `stale reminder channels and groups go, foreign ones stay`() { + val current = calendar(1, "me@example.org", "com.google") + val keptGroup = planReminderChannels(listOf(current), emptyList(), emptyList()).groups.single().id + val gone = planReminderChannels(listOf(calendar(9, "old", "com.google")), emptyList(), emptyList()) + val plan = planReminderChannels( + calendars = listOf(current), + existingChannelIds = listOf( + reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup", + ), + existingGroupIds = listOf(keptGroup, gone.groups.single().id, "other"), + ) + assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(9)) + assertThat(plan.staleGroupIds).containsExactly(gone.groups.single().id) + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 771d9bd7..a3963343 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -391,6 +391,18 @@ gate also covers a snooze re-shown from our own alarm after its calendar was switched off. The drawer's filter sheet (`CalendarPrefs.hiddenCalendarIds`) is a separate in-app declutter that never touches reminders. +**A channel per calendar (#145).** `ReminderChannels` keeps one notification +channel per switched-on calendar, grouped by account, so a calendar can be muted +or given its own sound in the system settings before it ever fires. Every scan +syncs them first: missing channels are created, names refreshed, and channels of +gone or switched-off calendars deleted (the system restores a deleted channel's +settings if the id returns). 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 +off switch (#272), checked in `ReminderNotifier.post` alongside visibility. + Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast. Keeping both would double-post wherever the provider works, and Etar's way out — a latch that disables its own scheduling once a real broadcast arrives — cannot diff --git a/floret-kit b/floret-kit index a039ab5b..730c9eb2 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit a039ab5bd470a548d754f2e8e610dc03bbcea40e +Subproject commit 730c9eb25a6bf2f93e3388bf132769d6dd1afd91