From 994fc1026fd449c9343f32fdb72bb75b911da09e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:14:54 +0100 Subject: [PATCH 01/11] 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 From 9b5880b719d8f3ef7bb33ff2d425d74f4f0cc2bb Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:23:08 +0100 Subject: [PATCH 02/11] =?UTF-8?q?fix(#145):=20review=20round=201=20?= =?UTF-8?q?=E2=80=94=20vibration=20carry-over,=20cheaper=20channel=20sync,?= =?UTF-8?q?=20shared=20account=20grouping?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannelPlan.kt | 75 ++++++++------- .../data/reminders/ReminderChannels.kt | 96 ++++++++++--------- .../data/reminders/ReminderScanner.kt | 12 +-- .../calendula/ui/common/AccountGroups.kt | 17 ++-- .../data/reminders/ReminderChannelPlanTest.kt | 48 +++++++--- docs/ARCHITECTURE.md | 10 +- 6 files changed, 146 insertions(+), 112 deletions(-) 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 4eb99f89..cb59e17b 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 @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.data.reminders import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.ui.common.groupByAccount /** The single channel every reminder posted on before they moved per calendar (#145). */ const val LEGACY_REMINDER_CHANNEL_ID = "reminders" @@ -19,13 +20,13 @@ fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANN 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. + * One account's channel group, labelled as the calendar manager labels it. The + * app's own device calendars share a single group ([isLocal]); [ambiguous] + * marks a [label] another group shows too, so it should name the source app. */ data class ReminderChannelGroupSpec( val id: String, - val accountName: String, + val label: String, val accountType: String, val isLocal: Boolean, val ambiguous: Boolean, @@ -39,67 +40,69 @@ data class ReminderChannelSpec( val groupId: String, ) +/** What a channel already looks like in the system, as far as the plan compares it. */ +data class ExistingReminderChannel(val id: String, val name: String) + data class ReminderChannelPlan( val groups: List, - /** Every channel that should exist; creating an existing one only refreshes its name. */ val channels: List, + /** The [channels] that are missing or whose name changed. */ + val channelsToWrite: 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. + * calendar inside a group per account, which of them need writing, and the + * reminder channels and groups in [existing] / [existingGroupIds] no calendar + * claims any more. Ids outside the reminder namespace (the backup channel, the + * legacy channel) are never touched. */ fun planReminderChannels( calendars: List, - existingChannelIds: Collection, + existing: Collection, existingGroupIds: Collection, + unnamed: String, ): 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 (local, synced) = calendars.partition { it.isLocal } + val groups = buildList { + if (local.isNotEmpty()) { + add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false)) + } + synced.groupByAccount().forEach { group -> + add( + ReminderChannelGroupSpec( + id = accountGroupId(group.key.type, group.key.name), + label = group.label, + accountType = group.accountType, + isLocal = false, + ambiguous = group.ambiguous, + ), ) } } - val 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)), + name = calendar.displayName.ifBlank { unnamed }, + groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName), ) } + val existingById = existing.associateBy { it.id } 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 }, + channelsToWrite = channels.filter { spec -> + val current = existingById[spec.id] + current == null || current.name != spec.name + }, + staleChannelIds = existingById.keys.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 +private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name" 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 a4422687..a7f8f004 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 @@ -8,44 +8,39 @@ 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 de.jeanlucmakiola.calendula.ui.common.sourceAppLabel 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. + * The reminder notification channels: one per calendar, grouped by account + * (#145), created up front so each calendar can be muted or given its own sound + * in the system settings before it ever fires. * * A channel the user has touched keeps their settings; [sync] only creates the - * missing ones, 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. + * missing ones, renames changed ones, and deletes those whose calendar is gone. */ @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 } + /** Bring the channels in line with the provider's calendars. */ + fun sync() { val manager = manager - val plan = planReminderChannels( - calendars = calendars, - existingChannelIds = manager.notificationChannels.map { it.id }, - existingGroupIds = manager.notificationChannelGroups.map { it.id }, - ) + val existing = manager.notificationChannels + val plan = plan(existing) plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) - create(plan) + val groupNames = manager.notificationChannelGroups.associate { it.id to it.name?.toString() } + write( + groups = plan.groups.filter { groupNames[it.id] != groupLabel(it) }, + channels = plan.channelsToWrite, + existing = existing, + ) if (plan.channels.isNotEmpty()) retireLegacyChannel() } @@ -55,32 +50,52 @@ class ReminderChannels @Inject constructor( */ fun channelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) + val manager = manager if (manager.getNotificationChannel(id) != null) return id - val calendar = calendarDataSource.calendars().firstOrNull { it.id == calendarId } ?: return null - create(planReminderChannels(listOf(calendar), emptyList(), emptyList())) + val existing = manager.notificationChannels + val plan = plan(existing) + val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null + val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } + write( + groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups }, + channels = listOf(spec), + existing = existing, + ) return id } - private fun create(plan: ReminderChannelPlan) { + private fun plan(existing: List): ReminderChannelPlan = planReminderChannels( + calendars = calendarDataSource.calendars(), + existing = existing.map { ExistingReminderChannel(it.id, it.name.toString()) }, + existingGroupIds = manager.notificationChannelGroups.map { it.id }, + unnamed = context.getString(R.string.calendar_unnamed), + ) + + private fun write( + groups: List, + channels: List, + existing: List, + ) { val manager = manager - manager.createNotificationChannelGroups( - plan.groups.map { NotificationChannelGroup(it.id, groupLabel(it)) }, - ) + if (groups.isNotEmpty()) { + manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) }) + } + if (channels.isEmpty()) return + val byId = existing.associateBy { it.id } + val template = byId[LEGACY_REMINDER_CHANNEL_ID] // 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) + channels.map { spec -> + val current = byId[spec.id] NotificationChannel( spec.id, - spec.name.ifBlank { unnamed }, - existing?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, + spec.name, + current?.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) + if (current == null && template != null) inheritFrom(template) } }, ) @@ -92,8 +107,9 @@ class ReminderChannels @Inject constructor( */ private fun NotificationChannel.inheritFrom(template: NotificationChannel) { setSound(template.sound, template.audioAttributes) - enableVibration(template.shouldVibrate()) + // The pattern setter also flips vibration on or off, so it goes first. vibrationPattern = template.vibrationPattern + enableVibration(template.shouldVibrate()) enableLights(template.shouldShowLights()) lightColor = template.lightColor lockscreenVisibility = template.lockscreenVisibility @@ -119,17 +135,9 @@ class ReminderChannels @Inject constructor( 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) } + val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) } if (!group.ambiguous) return name - return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(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 + return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType)) } private companion object { 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 32716da1..92845523 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,7 +14,6 @@ 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 @@ -78,7 +77,6 @@ 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 @@ -88,6 +86,7 @@ class ReminderScanner @Inject constructor( return } + syncChannels() val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes()) // Reach into the past too: an all-day "at time of event" encodes to a // negative offset, and a catch-up pass needs the occurrences it missed. @@ -121,14 +120,13 @@ class ReminderScanner @Inject constructor( } /** - * 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. + * A provider change re-scans, so a calendar added, renamed or removed keeps + * its channel in step here. Skipped while reminders are off, when the + * channels have nothing to do. A failure never costs the reminders. */ - private suspend fun syncChannels() { + private fun syncChannels() { try { channels.sync() - } catch (e: CancellationException) { - throw e } catch (e: SecurityException) { throw e } catch (e: Exception) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt index c92c1ce3..d2a56674 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.common +import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext @@ -72,11 +73,13 @@ fun accountGroupTitle(group: CalendarAccountGroup): String { @Composable fun sourceAppName(accountType: String): String { val context = LocalContext.current - return remember(accountType) { - val pm = context.packageManager - val packages = sourceAppPackages(context, accountType) - packages.firstNotNullOfOrNull { pkg -> - runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull() - } ?: accountType - } + return remember(accountType) { sourceAppLabel(context, accountType) } +} + +/** [sourceAppName] outside composition, e.g. for notification channel groups. */ +fun sourceAppLabel(context: Context, accountType: String): String { + val pm = context.packageManager + return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg -> + runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull() + } ?: accountType } 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 83ea80e9..4227de86 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 @@ -24,8 +24,9 @@ class ReminderChannelPlanTest { calendar(2, "me@example.org", "com.google"), calendar(3, "dav", "bitfire.at.davdroid"), ), - existingChannelIds = emptyList(), + existing = emptyList(), existingGroupIds = emptyList(), + unnamed = "Unnamed", ) assertThat(plan.groups).hasSize(2) assertThat(plan.channels.map { it.id }) @@ -42,8 +43,9 @@ class ReminderChannelPlanTest { calendar(1, "Calendula", "LOCAL", local = true), calendar(2, "Other", "LOCAL", local = true), ), - existingChannelIds = emptyList(), + existing = emptyList(), existingGroupIds = emptyList(), + unnamed = "Unnamed", ) assertThat(plan.groups).hasSize(1) assertThat(plan.groups.single().isLocal).isTrue() @@ -57,27 +59,47 @@ class ReminderChannelPlanTest { calendar(2, "me@example.org", "bitfire.at.davdroid"), calendar(3, "work", "bitfire.at.davdroid"), ), - existingChannelIds = emptyList(), + existing = emptyList(), existingGroupIds = emptyList(), + unnamed = "Unnamed", ) assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType }) .containsExactly("com.google", "bitfire.at.davdroid") - assertThat(plan.groups.single { it.accountName == "work" }.ambiguous).isFalse() + assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse() } @Test fun `stale reminder channels and groups go, foreign ones stay`() { val current = calendar(1, "me@example.org", "com.google") - val keptGroup = planReminderChannels(listOf(current), emptyList(), emptyList()).groups.single().id - val gone = planReminderChannels(listOf(calendar(9, "old", "com.google")), emptyList(), emptyList()) - val plan = planReminderChannels( + fun plan(calendars: List, existing: List = emptyList(), groups: List = emptyList()) = + planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}") }, groups, "Unnamed") + val keptGroup = plan(listOf(current)).groups.single().id + val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id + val result = plan( calendars = listOf(current), - existingChannelIds = listOf( - reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup", - ), - existingGroupIds = listOf(keptGroup, gone.groups.single().id, "other"), + existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"), + groups = listOf(keptGroup, goneGroup, "other"), ) - assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(9)) - assertThat(plan.staleGroupIds).containsExactly(gone.groups.single().id) + assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9)) + assertThat(result.staleGroupIds).containsExactly(goneGroup) + } + + @Test + fun `only missing or renamed channels are written`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "a", "com.google"), + calendar(2, "a", "com.google"), + calendar(3, "a", "com.google").copy(displayName = ""), + ), + existing = listOf( + ExistingReminderChannel(reminderChannelId(1), "Cal 1"), + ExistingReminderChannel(reminderChannelId(2), "Old name"), + ), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + ) + assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L) + assertThat(plan.channelsToWrite.last().name).isEqualTo("Unnamed") } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a3963343..503c49f6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -392,11 +392,11 @@ 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 +channel per 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 with +reminders on syncs them: missing channels are created, renamed ones updated, and +channels of deleted calendars removed. Switched-off calendars keep theirs, so +toggling one never cancels a showing reminder or loses its settings. 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 515c7c3d261d666fd1016b615e9ed54c9589792b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:29:34 +0100 Subject: [PATCH 03/11] =?UTF-8?q?fix(#145):=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20guard=20empty=20snapshots=20and=20the=20post=20path?= =?UTF-8?q?,=20skip=20muted=20calendars=20in=20the=20scan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannelPlan.kt | 11 ++-- .../data/reminders/ReminderChannels.kt | 60 +++++++++++++++---- .../data/reminders/ReminderNotifier.kt | 7 ++- .../data/reminders/ReminderScanner.kt | 5 +- .../ui/settings/NotificationSettings.kt | 7 ++- .../calendula/ui/settings/SettingsUiState.kt | 2 +- .../ui/settings/SettingsViewModel.kt | 23 ++++++- .../data/reminders/ReminderChannelPlanTest.kt | 20 +++++-- docs/ARCHITECTURE.md | 16 +++-- 9 files changed, 117 insertions(+), 34 deletions(-) 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 cb59e17b..bf00c6eb 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 @@ -35,18 +35,18 @@ data class ReminderChannelGroupSpec( 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, + /** Null only for a channel created before its calendar could be looked up. */ + val groupId: String?, ) /** What a channel already looks like in the system, as far as the plan compares it. */ -data class ExistingReminderChannel(val id: String, val name: String) +data class ExistingReminderChannel(val id: String, val name: String, val description: String?) data class ReminderChannelPlan( val groups: List, val channels: List, - /** The [channels] that are missing or whose name changed. */ + /** The [channels] that are missing, or whose name or (localized) description changed. */ val channelsToWrite: List, val staleChannelIds: List, val staleGroupIds: List, @@ -64,6 +64,7 @@ fun planReminderChannels( existing: Collection, existingGroupIds: Collection, unnamed: String, + description: String, ): ReminderChannelPlan { val (local, synced) = calendars.partition { it.isLocal } val groups = buildList { @@ -98,7 +99,7 @@ fun planReminderChannels( channels = channels, channelsToWrite = channels.filter { spec -> val current = existingById[spec.id] - current == null || current.name != spec.name + current == null || current.name != spec.name || current.description != description }, staleChannelIds = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels }, staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups }, 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 a7f8f004..4fdecf95 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 @@ -8,7 +8,9 @@ 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.domain.CalendarSource import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel +import java.util.Locale import javax.inject.Inject import javax.inject.Singleton @@ -28,32 +30,61 @@ class ReminderChannels @Inject constructor( private val manager: NotificationManager get() = context.getSystemService(NotificationManager::class.java) - /** Bring the channels in line with the provider's calendars. */ + /** What the last [sync] saw, so an unchanged provider costs no channel writes. */ + @Volatile + private var lastSync: Any? = null + + /** + * Bring the channels in line with the provider's calendars. A calendar that + * syncs no events gets none, and an empty snapshot changes nothing: that is + * a provider hiccup far more often than every calendar gone at once. + */ fun sync() { + val calendars = calendarDataSource.calendars().filter { it.isLocal || it.syncsEvents } + if (calendars.isEmpty()) return val manager = manager val existing = manager.notificationChannels - val plan = plan(existing) + val key = syncKey(calendars, existing) + if (key == lastSync && existing.none { it.id == LEGACY_REMINDER_CHANNEL_ID }) return + val groups = manager.notificationChannelGroups + val plan = plan(calendars, existing, groups.map { it.id }) plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) - val groupNames = manager.notificationChannelGroups.associate { it.id to it.name?.toString() } + val groupNames = groups.associate { it.id to it.name?.toString() } write( groups = plan.groups.filter { groupNames[it.id] != groupLabel(it) }, channels = plan.channelsToWrite, existing = existing, ) - if (plan.channels.isNotEmpty()) retireLegacyChannel() + retireLegacyChannel() + lastSync = syncKey(calendars, manager.notificationChannels) } + private fun syncKey(calendars: List, channels: List): Any = listOf( + calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal) }, + Locale.getDefault(), + channels.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. + * has not got to it yet. Null when the calendar no longer exists. Should the + * calendar lookup fail, the channel is still created, plainly named and + * ungrouped, for the next sync to name and file — a reminder is never lost + * to its channel. */ fun channelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager if (manager.getNotificationChannel(id) != null) return id val existing = manager.notificationChannels - val plan = plan(existing) + val plan = try { + plan(calendarDataSource.calendars(), existing, emptyList()) + } catch (e: Exception) { + Log.w(TAG, "Could not look up calendar $calendarId for its channel", e) + write(emptyList(), listOf(ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)), existing) + return id + } val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } write( @@ -64,11 +95,16 @@ class ReminderChannels @Inject constructor( return id } - private fun plan(existing: List): ReminderChannelPlan = planReminderChannels( - calendars = calendarDataSource.calendars(), - existing = existing.map { ExistingReminderChannel(it.id, it.name.toString()) }, - existingGroupIds = manager.notificationChannelGroups.map { it.id }, + private fun plan( + calendars: List, + existing: List, + existingGroupIds: List, + ): ReminderChannelPlan = planReminderChannels( + calendars = calendars, + existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description) }, + existingGroupIds = existingGroupIds, unnamed = context.getString(R.string.calendar_unnamed), + description = context.getString(R.string.reminder_channel_description), ) private fun write( @@ -94,7 +130,7 @@ class ReminderChannels @Inject constructor( current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, ).apply { description = context.getString(R.string.reminder_channel_description) - group = spec.groupId + spec.groupId?.let { group = it } if (current == null && template != null) inheritFrom(template) } }, @@ -114,6 +150,8 @@ class ReminderChannels @Inject constructor( lightColor = template.lightColor lockscreenVisibility = template.lockscreenVisibility setShowBadge(template.canShowBadge()) + // 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/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index ec6f8c89..3631482e 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,7 +65,12 @@ 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 = channels.channelFor(alert.calendarId) ?: return + val channelId = try { + channels.channelFor(alert.calendarId) + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + null + } ?: return val title = displayTitle(alert) val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) 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 92845523..f50e2728 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 @@ -90,7 +90,10 @@ class ReminderScanner @Inject constructor( val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes()) // Reach into the past too: an all-day "at time of event" encodes to a // negative offset, and a catch-up pass needs the occurrences it missed. + // Calendars muted in-app (#272) plan nothing, so they arm no wake-ups. + val muted = settingsPrefs.mutedReminderCalendarIds.first() val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead) + .filter { it.calendarId !in muted } val planned = planReminders( instances = occurrences, minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId }) @@ -127,8 +130,6 @@ class ReminderScanner @Inject constructor( private fun syncChannels() { try { channels.sync() - } catch (e: SecurityException) { - throw e } catch (e: Exception) { Log.w(TAG, "Reminder channel sync failed", e) } 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 0dcd416b..b87b4b9c 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 @@ -114,7 +114,12 @@ internal fun NotificationsScreen( summary = stringResource(R.string.settings_notification_sound_hint), position = Position.Middle, trailing = { ExternalLinkIcon() }, - onClick = { context.openNotificationSettings() }, + onClick = { + scope.launch { + viewModel.syncReminderChannels() + context.openNotificationSettings() + } + }, ) GroupedRow( title = stringResource(R.string.settings_default_reminder), 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 3944032c..43a8edce 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 @@ -96,7 +96,7 @@ data class SettingsUiState( val perCalendarReminderOverride: Map> = emptyMap(), /** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */ val perCalendarAllDayReminderOverride: Map> = emptyMap(), - /** Writable calendars, shown as per-calendar reminder-override rows. */ + /** Switched-on calendars you can edit: the per-calendar duration and reminder-override rows. */ val writableCalendars: List = emptyList(), /** Switched-on calendars, each with its own notification switch and channel (#145, #272). */ val reminderCalendars: List = emptyList(), 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 dad8f8bf..af7ff478 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 @@ -46,6 +46,7 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow @@ -364,8 +365,26 @@ class SettingsViewModel @Inject constructor( 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() } + suspend fun reminderChannelFor(calendarId: Long): String? = withContext(io) { + try { + reminderChannels.channelFor(calendarId) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + null + } + } + + /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ + suspend fun syncReminderChannels() = withContext(io) { + try { + reminderChannels.sync() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Unit + } + } fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) } 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 4227de86..d18fa12d 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 @@ -27,6 +27,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups).hasSize(2) assertThat(plan.channels.map { it.id }) @@ -46,6 +47,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups).hasSize(1) assertThat(plan.groups.single().isLocal).isTrue() @@ -62,6 +64,7 @@ class ReminderChannelPlanTest { existing = emptyList(), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType }) .containsExactly("com.google", "bitfire.at.davdroid") @@ -72,7 +75,7 @@ class ReminderChannelPlanTest { fun `stale reminder channels and groups go, foreign ones stay`() { val current = calendar(1, "me@example.org", "com.google") fun plan(calendars: List, existing: List = emptyList(), groups: List = emptyList()) = - planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}") }, groups, "Unnamed") + planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC) }, groups, "Unnamed", DESC) val keptGroup = plan(listOf(current)).groups.single().id val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id val result = plan( @@ -91,15 +94,22 @@ class ReminderChannelPlanTest { calendar(1, "a", "com.google"), calendar(2, "a", "com.google"), calendar(3, "a", "com.google").copy(displayName = ""), + calendar(4, "a", "com.google"), ), existing = listOf( - ExistingReminderChannel(reminderChannelId(1), "Cal 1"), - ExistingReminderChannel(reminderChannelId(2), "Old name"), + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC), + ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description"), + ExistingReminderChannel(reminderChannelId(2), "Old name", DESC), ), existingGroupIds = emptyList(), unnamed = "Unnamed", + description = DESC, ) - assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L) - assertThat(plan.channelsToWrite.last().name).isEqualTo("Unnamed") + assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L) + assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed") + } + + private companion object { + const val DESC = "Reminders" } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 503c49f6..9e8e4a2a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -392,16 +392,20 @@ 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 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 with -reminders on syncs them: missing channels are created, renamed ones updated, and -channels of deleted calendars removed. Switched-off calendars keep theirs, so -toggling one never cancels a showing reminder or loses its settings. A new channel copies the sound, vibration and +channel per calendar that syncs events, grouped by account, so a calendar can be +muted or given its own sound in the system settings before it ever fires. Every +scan with reminders on syncs them (skipped when nothing changed): missing +channels are created, renamed ones updated, and channels of deleted calendars +removed — but never on an empty snapshot, which is a provider hiccup more often +than every calendar gone. Switched-off calendars keep theirs, so toggling one +never cancels a showing reminder or loses its settings. `post` creates a missing +channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and importance of the pre-#145 single `reminders` channel, which is deleted once nothing showing still sits on it. Settings → Notifications 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. +off switch (#272): the scan plans nothing for those calendars (so they arm no +wake-ups), and `ReminderNotifier.post` checks it again for snoozes. 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 — From fa999f8cf06f8cf2acb6f3834104f111480c258c Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 16:37:11 +0100 Subject: [PATCH 04/11] =?UTF-8?q?fix(#145):=20review=20round=203=20?= =?UTF-8?q?=E2=80=94=20rescan=20on=20mute,=20serialise=20channel=20writes,?= =?UTF-8?q?=20never=20drop=20a=20reminder=20for=20its=20channel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannelPlan.kt | 33 +++++++++--- .../data/reminders/ReminderChannels.kt | 52 +++++++++++-------- .../ui/settings/SettingsViewModel.kt | 31 ++++++----- .../data/reminders/ReminderChannelPlanTest.kt | 26 ++++++++-- docs/ARCHITECTURE.md | 6 ++- 5 files changed, 100 insertions(+), 48 deletions(-) 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 bf00c6eb..1f070222 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 @@ -38,16 +38,26 @@ data class ReminderChannelSpec( val name: String, /** Null only for a channel created before its calendar could be looked up. */ val groupId: String?, + /** + * Whether a sync creates it up front. A calendar that syncs no events never + * fires, so its channel only appears once something posts on it. + */ + val upFront: Boolean = true, ) /** What a channel already looks like in the system, as far as the plan compares it. */ -data class ExistingReminderChannel(val id: String, val name: String, val description: String?) +data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?) data class ReminderChannelPlan( val groups: List, val channels: List, - /** The [channels] that are missing, or whose name or (localized) description changed. */ + /** + * The [channels] a sync writes: missing up-front ones, and existing ones + * whose name or (localized) description changed, or that still lack a group. + */ val channelsToWrite: List, + /** The [groups] holding a channel that exists or is about to be written. */ + val groupsInUse: List, val staleChannelIds: List, val staleGroupIds: List, ) @@ -89,18 +99,29 @@ fun planReminderChannels( calendarId = calendar.id, name = calendar.displayName.ifBlank { unnamed }, groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName), + upFront = calendar.isLocal || calendar.syncsEvents, ) } val existingById = existing.associateBy { it.id } val wantedChannels = channels.mapTo(HashSet()) { it.id } val wantedGroups = groups.mapTo(HashSet()) { it.id } + val toWrite = channels.filter { spec -> + val current = existingById[spec.id] + if (current == null) { + spec.upFront + } else { + current.name != spec.name || current.description != description || + (current.groupId == null && spec.groupId != null) + } + } + val usedGroupIds = channels + .filter { it.id in existingById || it in toWrite } + .mapNotNullTo(HashSet()) { it.groupId } return ReminderChannelPlan( groups = groups, channels = channels, - channelsToWrite = channels.filter { spec -> - val current = existingById[spec.id] - current == null || current.name != spec.name || current.description != description - }, + 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 }, ) 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 4fdecf95..2f80a55c 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 @@ -35,56 +35,63 @@ class ReminderChannels @Inject constructor( private var lastSync: Any? = null /** - * Bring the channels in line with the provider's calendars. A calendar that - * syncs no events gets none, and an empty snapshot changes nothing: that is - * a provider hiccup far more often than every calendar gone at once. + * Bring the channels in line with the provider's calendars. An empty + * snapshot changes nothing: that is a provider hiccup far more often than + * every calendar gone at once. */ + @Synchronized fun sync() { - val calendars = calendarDataSource.calendars().filter { it.isLocal || it.syncsEvents } + val calendars = calendarDataSource.calendars() if (calendars.isEmpty()) return val manager = manager val existing = manager.notificationChannels - val key = syncKey(calendars, existing) - if (key == lastSync && existing.none { it.id == LEGACY_REMINDER_CHANNEL_ID }) return + val existingIds = existing.mapTo(HashSet()) { it.id } + if (syncKey(calendars, existingIds) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return val groups = manager.notificationChannelGroups val plan = plan(calendars, existing, groups.map { it.id }) plan.staleChannelIds.forEach(manager::deleteNotificationChannel) plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) val groupNames = groups.associate { it.id to it.name?.toString() } write( - groups = plan.groups.filter { groupNames[it.id] != groupLabel(it) }, + groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) }, channels = plan.channelsToWrite, existing = existing, ) - retireLegacyChannel() - lastSync = syncKey(calendars, manager.notificationChannels) + val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } + lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids) } - private fun syncKey(calendars: List, channels: List): Any = listOf( - calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal) }, + private fun syncKey(calendars: List, channelIds: Set): Any = listOf( + calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) }, Locale.getDefault(), - channels.mapTo(HashSet()) { it.id }, + channelIds, ) /** * The channel to post [calendarId]'s reminder on, created first if a sync * has not got to it yet. Null when the calendar no longer exists. Should the - * calendar lookup fail, the channel is still created, plainly named and - * ungrouped, for the next sync to name and file — a reminder is never lost - * to its channel. + * calendar lookup fail or come back empty, the channel is still created, + * plainly named and ungrouped, for the next sync to name and file — a + * reminder is never lost to its channel. */ + @Synchronized fun channelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager if (manager.getNotificationChannel(id) != null) return id val existing = manager.notificationChannels - val plan = try { - plan(calendarDataSource.calendars(), existing, emptyList()) + val calendars = try { + calendarDataSource.calendars() } catch (e: Exception) { Log.w(TAG, "Could not look up calendar $calendarId for its channel", e) - write(emptyList(), listOf(ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)), existing) + emptyList() + } + if (calendars.isEmpty()) { + val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null) + write(emptyList(), listOf(fallback), existing) return id } + val plan = plan(calendars, existing, emptyList()) val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } write( @@ -101,7 +108,7 @@ class ReminderChannels @Inject constructor( existingGroupIds: List, ): ReminderChannelPlan = planReminderChannels( calendars = calendars, - existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description) }, + 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), @@ -157,11 +164,11 @@ class ReminderChannels @Inject constructor( /** * 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. + * channel would take that notification with it. Returns whether it is gone. */ - private fun retireLegacyChannel() { + private fun retireLegacyChannel(): Boolean { val manager = manager - if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return + 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 -> @@ -169,6 +176,7 @@ class ReminderChannels @Inject constructor( true } if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) + return !showing } private fun groupLabel(group: ReminderChannelGroupSpec): 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 af7ff478..5dae73ee 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.util.Log import androidx.datastore.preferences.core.Preferences import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -361,28 +362,30 @@ 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) { - try { - reminderChannels.channelFor(calendarId) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - null + /** Re-plans, since a muted calendar armed no wake-up for its next reminder. */ + fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { + viewModelScope.launch { + prefs.setCalendarRemindersEnabled(calendarId, enabled) + reminderScanner.scan() } } + /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ + suspend fun reminderChannelFor(calendarId: Long): String? = onChannels { channelFor(calendarId) } + /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ - suspend fun syncReminderChannels() = withContext(io) { + suspend fun syncReminderChannels() { + onChannels { sync() } + } + + private suspend fun onChannels(block: ReminderChannels.() -> T): T? = withContext(io) { try { - reminderChannels.sync() + reminderChannels.block() } catch (e: CancellationException) { throw e } catch (e: Exception) { - Unit + Log.w("SettingsViewModel", "Reminder channel update failed", e) + null } } 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 d18fa12d..e32fa3a4 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 @@ -75,7 +75,7 @@ class ReminderChannelPlanTest { fun `stale reminder channels and groups go, foreign ones stay`() { val current = calendar(1, "me@example.org", "com.google") fun plan(calendars: List, existing: List = emptyList(), groups: List = emptyList()) = - planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC) }, groups, "Unnamed", DESC) + planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC) val keptGroup = plan(listOf(current)).groups.single().id val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id val result = plan( @@ -97,9 +97,9 @@ class ReminderChannelPlanTest { calendar(4, "a", "com.google"), ), existing = listOf( - ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC), - ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description"), - ExistingReminderChannel(reminderChannelId(2), "Old name", DESC), + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"), + ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"), + ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"), ), existingGroupIds = emptyList(), unnamed = "Unnamed", @@ -109,6 +109,24 @@ class ReminderChannelPlanTest { assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed") } + @Test + fun `non-syncing calendars keep a channel but get none up front`() { + val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false) + val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC) + assertThat(fresh.channelsToWrite).isEmpty() + assertThat(fresh.groupsInUse).isEmpty() + val posted = planReminderChannels( + calendars = listOf(quiet), + existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(posted.staleChannelIds).isEmpty() + assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L) + assertThat(posted.groupsInUse).hasSize(1) + } + private companion object { const val DESC = "Reminders" } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9e8e4a2a..4822bd47 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -392,7 +392,8 @@ 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 calendar that syncs events, grouped by account, so a calendar can be +channel per calendar, grouped by account (one that syncs no events only gets +its channel once something posts on it), so a calendar can be muted or given its own sound in the system settings before it ever fires. Every scan with reminders on syncs them (skipped when nothing changed): missing channels are created, renamed ones updated, and channels of deleted calendars @@ -405,7 +406,8 @@ nothing showing still sits on it. Settings → Notifications only deep-links int 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): the scan plans nothing for those calendars (so they arm no -wake-ups), and `ReminderNotifier.post` checks it again for snoozes. +wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again +for snoozes. 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 — From 955dccff2b0528b51056bf8a77eb399b87462e1e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 02:25:34 +0100 Subject: [PATCH 05/11] feat(#145): show calendars blocked in system settings, one-time Samsung category hint --- .../calendula/data/prefs/SettingsPrefs.kt | 9 +++ .../data/reminders/ReminderChannelPlan.kt | 22 ++++++ .../data/reminders/ReminderChannels.kt | 21 +++++ .../ui/settings/NotificationSettings.kt | 78 ++++++++++++++++++- .../calendula/ui/settings/SettingsUiState.kt | 2 + .../ui/settings/SettingsViewModel.kt | 15 ++++ app/src/main/res/values/strings.xml | 4 + .../data/reminders/ReminderChannelPlanTest.kt | 16 ++++ docs/ARCHITECTURE.md | 4 +- 9 files changed, 166 insertions(+), 5 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 bd98b6ab..13e6c7b3 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 @@ -167,6 +167,7 @@ class SettingsPrefs @Inject constructor( val perCalendarEventDuration: Flow> = prefs.flow(SettingsKeys.perCalendarEventDuration) val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) + val notificationCategoryHintDismissed: Flow = prefs.flow(SettingsKeys.notificationCategoryHintDismissed) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -274,6 +275,8 @@ class SettingsPrefs @Inject constructor( suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) + suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true) + suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId } } @@ -605,6 +608,12 @@ object SettingsKeys { */ val mutedReminderCalendarIds: Pref> = idSetPref("muted_reminder_calendar_ids") + /** + * Whether the one-time hint that some skins (Samsung) start new notification + * categories switched off has been dismissed (#145). + */ + val notificationCategoryHintDismissed: Pref = booleanPref("notification_category_hint_dismissed", false) + /** * 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 index 1f070222..f75eb262 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 @@ -128,3 +128,25 @@ fun planReminderChannels( } private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name" + +/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */ +data class ReminderChannelState(val blocked: Boolean, val groupId: String?) + +/** + * The calendars among [calendarIds] whose reminders the system blocks: all of + * them while the app's notifications are off, otherwise those whose channel, + * or the group it sits in, is switched off. A calendar without a channel yet + * isn't blocked. + */ +fun blockedReminderCalendars( + calendarIds: Collection, + appEnabled: Boolean, + channels: Map, + blockedGroupIds: Set, +): Set { + if (!appEnabled) return calendarIds.toSet() + return calendarIds.filterTo(HashSet()) { id -> + val channel = channels[reminderChannelId(id)] ?: return@filterTo false + channel.blocked || channel.groupId in blockedGroupIds + } +} 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 2f80a55c..95fbfff5 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 @@ -102,6 +102,21 @@ class ReminderChannels @Inject constructor( return id } + /** What the system currently lets through for [calendarIds]' reminders (#145). */ + fun status(calendarIds: Collection): ReminderChannelStatus { + val manager = manager + val appEnabled = manager.areNotificationsEnabled() + val blocked = blockedReminderCalendars( + calendarIds = calendarIds, + appEnabled = appEnabled, + channels = manager.notificationChannels.associate { + it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group) + }, + blockedGroupIds = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }, + ) + return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked) + } + private fun plan( calendars: List, existing: List, @@ -190,3 +205,9 @@ class ReminderChannels @Inject constructor( const val TAG = "ReminderChannels" } } + +/** Reminder notifications the system blocks, while Calendula would post them. */ +data class ReminderChannelStatus( + val appBlocked: Boolean = false, + val blockedCalendarIds: Set = emptySet(), +) 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 b87b4b9c..85d5b064 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 @@ -9,6 +9,16 @@ import android.provider.Settings import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.ui.Alignment +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.floret.components.IconInfoCard import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height @@ -92,8 +102,19 @@ internal fun NotificationsScreen( var calendarSectionExpanded by remember { mutableStateOf(false) } var expandedCalendars by remember { mutableStateOf(emptySet()) } val scope = rememberCoroutineScope() + val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() + val calendarIds = state.reminderCalendars.map { it.id } + // Re-read whenever the screen returns from the system settings it links to. + LifecycleResumeEffect(calendarIds) { + viewModel.refreshChannelStatus(calendarIds) + onPauseOrDispose { } + } val openCalendarSound: (Long) -> Unit = { calendarId -> - scope.launch { context.openNotificationSettings(viewModel.reminderChannelFor(calendarId)) } + scope.launch { + val channelId = viewModel.reminderChannelFor(calendarId) + // With the whole app blocked, only the app's own screen can allow it. + context.openNotificationSettings(channelId.takeUnless { channelStatus.appBlocked }) + } } CollapsingScaffold( @@ -102,6 +123,18 @@ internal fun NotificationsScreen( predictiveBack = true, visible = visible, ) { + if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) { + NotificationCategoryHint( + onOpen = { + scope.launch { + viewModel.syncReminderChannels() + context.openNotificationSettings() + } + }, + onDismiss = viewModel::dismissNotificationCategoryHint, + ) + Spacer(Modifier.height(16.dp)) + } GroupedSwitchRow( title = stringResource(R.string.settings_reminders), checked = state.remindersEnabled, @@ -111,7 +144,11 @@ internal fun NotificationsScreen( ) GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = stringResource(R.string.settings_notification_sound_hint), + summary = if (channelStatus.appBlocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_notification_sound_hint) + }, position = Position.Middle, trailing = { ExternalLinkIcon() }, onClick = { @@ -192,9 +229,14 @@ internal fun NotificationsScreen( Spacer(Modifier.height(16.dp)) val expanded = calendar.id in expandedCalendars val notifying = calendar.id !in state.mutedReminderCalendarIds + val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds GroupedRow( title = calendar.displayName.orUnnamed(), - summary = if (notifying) null else stringResource(R.string.settings_calendar_notifications_off), + summary = when { + !notifying -> stringResource(R.string.settings_calendar_notifications_off) + blocked -> stringResource(R.string.settings_notifications_blocked) + else -> null + }, position = if (expanded) Position.Top else Position.Alone, leading = { CalendarColorChip(calendar.color) }, trailing = { ExpandIcon(expanded) }, @@ -215,6 +257,7 @@ internal fun NotificationsScreen( calendar = calendar, state = state, notifying = notifying, + blocked = blocked, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, onOpenSound = { openCalendarSound(calendar.id) }, onOpenSpecialDates = onOpenSpecialDates, @@ -316,6 +359,7 @@ private fun CalendarNotificationRows( calendar: CalendarSource, state: SettingsUiState, notifying: Boolean, + blocked: Boolean, onSetNotifying: (Boolean) -> Unit, onOpenSound: () -> Unit, onOpenSpecialDates: () -> Unit, @@ -333,7 +377,11 @@ private fun CalendarNotificationRows( ) GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = stringResource(R.string.settings_calendar_notification_sound_hint), + summary = if (blocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_calendar_notification_sound_hint) + }, position = if (managed || takesOverrides) Position.Middle else Position.Bottom, trailing = { ExternalLinkIcon() }, onClick = onOpenSound, @@ -371,6 +419,28 @@ private fun CalendarNotificationRows( } } +/** Samsung's One UI can start a new notification category switched off (#145). */ +private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true) + +/** The one-time Samsung note, with a way into the app's notification settings. */ +@Composable +private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) { + IconInfoCard( + icon = Icons.Outlined.Info, + iconContentDescription = null, + iconAlignment = Alignment.Top, + ) { + Text( + text = stringResource(R.string.settings_notification_category_hint), + style = MaterialTheme.typography.bodyMedium, + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) } + TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) } + } + } +} + @Composable private fun ExternalLinkIcon() { Icon( 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 43a8edce..1a0cc2fc 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 @@ -102,6 +102,8 @@ data class SettingsUiState( val reminderCalendars: List = emptyList(), /** Calendars whose reminders Calendula doesn't post (#272). */ val mutedReminderCalendarIds: Set = emptySet(), + /** Whether the Samsung notification-category hint has been dismissed (#145). */ + val notificationCategoryHintDismissed: Boolean = false, /** * 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 5dae73ee..ce2e2adf 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 @@ -34,6 +34,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.ReminderChannelStatus import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource @@ -131,6 +132,7 @@ class SettingsViewModel @Inject constructor( writableCalendars = calendars.filter { it.canModifyContents }, reminderCalendars = calendars, mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds], + notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed], allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], managedCalendarIds = specialDatesCalendars.values.toSet(), ) @@ -370,6 +372,19 @@ class SettingsViewModel @Inject constructor( } } + private val _channelStatus = MutableStateFlow(ReminderChannelStatus()) + + /** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */ + val channelStatus: StateFlow = _channelStatus.asStateFlow() + + fun refreshChannelStatus(calendarIds: Collection) { + viewModelScope.launch { + onChannels { status(calendarIds) }?.let { _channelStatus.value = it } + } + } + + fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() } + /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ suspend fun reminderChannelFor(calendarId: Long): String? = onChannels { channelFor(calendarId) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cc92c56e..3e7b8d77 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -737,6 +737,10 @@ Notifications off Notification sound Sound, vibration and pop-ups 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 Default (%1$s) Reliable delivery 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 e32fa3a4..84d0c21d 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 @@ -127,6 +127,22 @@ class ReminderChannelPlanTest { assertThat(posted.groupsInUse).hasSize(1) } + @Test + fun `blocked calendars follow app, channel and group`() { + val channels = mapOf( + reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"), + reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"), + reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"), + ) + val ids = listOf(1L, 2L, 3L, 4L) + assertThat(blockedReminderCalendars(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))) + .containsExactly(1L, 2L) + assertThat(blockedReminderCalendars(ids, appEnabled = true, channels, blockedGroupIds = emptySet())) + .containsExactly(1L) + assertThat(blockedReminderCalendars(ids, appEnabled = false, channels, blockedGroupIds = emptySet())) + .containsExactly(1L, 2L, 3L, 4L) + } + private companion object { const val DESC = "Reminders" } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4822bd47..8f0a77ba 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -407,7 +407,9 @@ 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): 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. +for snoozes. The settings screen re-reads `ReminderChannels.status` on every +resume and marks a calendar "Blocked in system settings" when the app, its +channel or its account group is switched off there. Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast. Keeping both would double-post wherever the provider works, and Etar's way out — From 2e71e4dc5fbe31acbfce40cb5222a56647e64530 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 02:34:07 +0100 Subject: [PATCH 06/11] =?UTF-8?q?fix(#145):=20review=20round=20A=20?= =?UTF-8?q?=E2=80=94=20group-blocked=20deep-link,=20status=20refresh=20rac?= =?UTF-8?q?e,=20hint=20dismiss=20on=20open?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannels.kt | 21 +++++++++++-------- .../ui/settings/NotificationSettings.kt | 10 ++++----- .../ui/settings/SettingsViewModel.kt | 6 +++++- floret-kit | 2 +- 4 files changed, 22 insertions(+), 17 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 95fbfff5..0a82fe55 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 @@ -106,15 +106,17 @@ class ReminderChannels @Inject constructor( fun status(calendarIds: Collection): ReminderChannelStatus { val manager = manager val appEnabled = manager.areNotificationsEnabled() - val blocked = blockedReminderCalendars( - calendarIds = calendarIds, - appEnabled = appEnabled, - channels = manager.notificationChannels.associate { - it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group) + val channels = manager.notificationChannels.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( + appBlocked = !appEnabled, + blockedCalendarIds = blockedReminderCalendars(calendarIds, appEnabled, channels, blockedGroups), + groupBlockedCalendarIds = calendarIds.filterTo(HashSet()) { + channels[reminderChannelId(it)]?.groupId in blockedGroups }, - blockedGroupIds = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }, ) - return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked) } private fun plan( @@ -141,8 +143,7 @@ class ReminderChannels @Inject constructor( if (channels.isEmpty()) return val byId = existing.associateBy { it.id } val template = byId[LEGACY_REMINDER_CHANNEL_ID] - // Only a channel's first creation sets its behaviour; later calls just - // rename it, so an existing one passes its own importance back. + // Importance only applies on creation; an existing channel keeps its own. manager.createNotificationChannels( channels.map { spec -> val current = byId[spec.id] @@ -210,4 +211,6 @@ class ReminderChannels @Inject constructor( data class ReminderChannelStatus( val appBlocked: Boolean = false, val blockedCalendarIds: Set = emptySet(), + /** The blocked ones whose whole account group is off, which only the app's own screen can undo. */ + val groupBlockedCalendarIds: Set = emptySet(), ) 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 85d5b064..46b90ee7 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 @@ -104,7 +104,6 @@ internal fun NotificationsScreen( val scope = rememberCoroutineScope() val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() val calendarIds = state.reminderCalendars.map { it.id } - // Re-read whenever the screen returns from the system settings it links to. LifecycleResumeEffect(calendarIds) { viewModel.refreshChannelStatus(calendarIds) onPauseOrDispose { } @@ -112,8 +111,8 @@ internal fun NotificationsScreen( val openCalendarSound: (Long) -> Unit = { calendarId -> scope.launch { val channelId = viewModel.reminderChannelFor(calendarId) - // With the whole app blocked, only the app's own screen can allow it. - context.openNotificationSettings(channelId.takeUnless { channelStatus.appBlocked }) + val appScreen = channelStatus.appBlocked || calendarId in channelStatus.groupBlockedCalendarIds + context.openNotificationSettings(channelId.takeUnless { appScreen }) } } @@ -126,6 +125,7 @@ internal fun NotificationsScreen( if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) { NotificationCategoryHint( onOpen = { + viewModel.dismissNotificationCategoryHint() scope.launch { viewModel.syncReminderChannels() context.openNotificationSettings() @@ -207,9 +207,7 @@ internal fun NotificationsScreen( onClick = { showSnooze = true }, ) - // 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. + // Per-calendar notifications and reminder overrides (#145, #272). if (state.reminderCalendars.isNotEmpty()) { Spacer(Modifier.height(24.dp)) GroupedRow( 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 ce2e2adf..8b287aff 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 @@ -50,6 +50,7 @@ import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -377,8 +378,11 @@ class SettingsViewModel @Inject constructor( /** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */ val channelStatus: StateFlow = _channelStatus.asStateFlow() + private var channelStatusJob: Job? = null + fun refreshChannelStatus(calendarIds: Collection) { - viewModelScope.launch { + channelStatusJob?.cancel() + channelStatusJob = viewModelScope.launch { onChannels { status(calendarIds) }?.let { _channelStatus.value = it } } } diff --git a/floret-kit b/floret-kit index 730c9eb2..20b136aa 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 730c9eb25a6bf2f93e3388bf132769d6dd1afd91 +Subproject commit 20b136aaf71277643267018ed1c57dae0b0c54ec From 99a584a82d295c2e796eeed7f8736c0c9d8f46a6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 02:42:22 +0100 Subject: [PATCH 07/11] =?UTF-8?q?fix(#145):=20review=20round=20B=20?= =?UTF-8?q?=E2=80=94=20fresh=20status=20for=20the=20sound=20deep-link,=20o?= =?UTF-8?q?ne=20tested=20status=20function,=20no=20hint=20flash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannelPlan.kt | 29 ++++++++++++------- .../data/reminders/ReminderChannels.kt | 18 ++---------- .../data/reminders/ReminderNotifier.kt | 5 +++- .../ui/settings/NotificationSettings.kt | 24 +++++++-------- .../calendula/ui/settings/SettingsUiState.kt | 6 ++-- .../ui/settings/SettingsViewModel.kt | 12 ++++++-- .../data/reminders/ReminderChannelPlanTest.kt | 12 ++++---- 7 files changed, 56 insertions(+), 50 deletions(-) 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 f75eb262..e67a7727 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 @@ -132,21 +132,30 @@ private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$ /** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */ data class ReminderChannelState(val blocked: Boolean, val groupId: String?) +/** Reminder notifications the system blocks, while Calendula would post them. */ +data class ReminderChannelStatus( + val appBlocked: Boolean = false, + val blockedCalendarIds: Set = emptySet(), + /** The blocked ones whose whole account group is off, which only the app's own screen can undo. */ + val groupBlockedCalendarIds: Set = emptySet(), +) + /** - * The calendars among [calendarIds] whose reminders the system blocks: all of - * them while the app's notifications are off, otherwise those whose channel, - * or the group it sits in, is switched off. A calendar without a channel yet - * isn't blocked. + * What the system blocks of [calendarIds]' reminders: all of them while the + * app's notifications are off, otherwise those whose channel, or the group it + * sits in, is switched off. A calendar without a channel yet isn't blocked. */ -fun blockedReminderCalendars( +fun reminderChannelStatus( calendarIds: Collection, appEnabled: Boolean, channels: Map, blockedGroupIds: Set, -): Set { - if (!appEnabled) return calendarIds.toSet() - return calendarIds.filterTo(HashSet()) { id -> - val channel = channels[reminderChannelId(id)] ?: return@filterTo false - channel.blocked || channel.groupId in blockedGroupIds +): ReminderChannelStatus { + val groupBlocked = calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.groupId in blockedGroupIds } + val blocked = if (!appEnabled) { + calendarIds.toSet() + } else { + calendarIds.filterTo(HashSet()) { channels[reminderChannelId(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 0a82fe55..717292b8 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 @@ -110,13 +110,7 @@ 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( - appBlocked = !appEnabled, - blockedCalendarIds = blockedReminderCalendars(calendarIds, appEnabled, channels, blockedGroups), - groupBlockedCalendarIds = calendarIds.filterTo(HashSet()) { - channels[reminderChannelId(it)]?.groupId in blockedGroups - }, - ) + return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups) } private fun plan( @@ -142,6 +136,7 @@ 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] // Importance only applies on creation; an existing channel keeps its own. manager.createNotificationChannels( @@ -152,7 +147,7 @@ class ReminderChannels @Inject constructor( spec.name, current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, ).apply { - description = context.getString(R.string.reminder_channel_description) + this.description = description spec.groupId?.let { group = it } if (current == null && template != null) inheritFrom(template) } @@ -207,10 +202,3 @@ class ReminderChannels @Inject constructor( } } -/** Reminder notifications the system blocks, while Calendula would post them. */ -data class ReminderChannelStatus( - val appBlocked: Boolean = false, - val blockedCalendarIds: Set = emptySet(), - /** The blocked ones whose whole account group is off, which only the app's own screen can undo. */ - val groupBlockedCalendarIds: Set = emptySet(), -) 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 3631482e..7f03769c 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 @@ -70,7 +70,10 @@ class ReminderNotifier @Inject constructor( } catch (e: Exception) { Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) null - } ?: return + } ?: run { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + return + } val title = displayTitle(alert) val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) 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 46b90ee7..efa61104 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 @@ -10,23 +10,19 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.material.icons.outlined.Info -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.ui.Alignment -import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import de.jeanlucmakiola.floret.components.IconInfoCard import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue @@ -34,6 +30,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource @@ -41,7 +38,9 @@ import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip @@ -57,6 +56,7 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.IconInfoCard import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.identity.collapseExit @@ -109,11 +109,7 @@ internal fun NotificationsScreen( onPauseOrDispose { } } val openCalendarSound: (Long) -> Unit = { calendarId -> - scope.launch { - val channelId = viewModel.reminderChannelFor(calendarId) - val appScreen = channelStatus.appBlocked || calendarId in channelStatus.groupBlockedCalendarIds - context.openNotificationSettings(channelId.takeUnless { appScreen }) - } + scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) } } CollapsingScaffold( 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 1a0cc2fc..34e603b3 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 @@ -96,14 +96,14 @@ data class SettingsUiState( val perCalendarReminderOverride: Map> = emptyMap(), /** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */ val perCalendarAllDayReminderOverride: Map> = emptyMap(), - /** Switched-on calendars you can edit: the per-calendar duration and reminder-override rows. */ + /** Switched-on calendars you can edit: the per-calendar event-duration 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 Samsung notification-category hint has been dismissed (#145). */ - val notificationCategoryHintDismissed: Boolean = false, + /** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */ + val notificationCategoryHintDismissed: Boolean = true, /** * Whether the event-colour picker is offered on calendars that publish no * colour palette (the colour may then not survive their next sync). 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 8b287aff..18d7ed6b 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 @@ -389,8 +389,16 @@ class SettingsViewModel @Inject constructor( fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() } - /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ - suspend fun reminderChannelFor(calendarId: Long): String? = onChannels { channelFor(calendarId) } + /** + * The channel whose system screen to open for [calendarId] (#340), created + * if needed; null when only the app's own screen can help — the app or the + * calendar's account group is blocked there, or the channel couldn't be made. + */ + suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels { + val channelId = channelFor(calendarId) ?: return@onChannels null + val status = status(listOf(calendarId)) + channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds } + } /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ suspend fun syncReminderChannels() { 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 84d0c21d..4634644b 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 @@ -135,12 +135,14 @@ class ReminderChannelPlanTest { reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"), ) val ids = listOf(1L, 2L, 3L, 4L) - assertThat(blockedReminderCalendars(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))) - .containsExactly(1L, 2L) - assertThat(blockedReminderCalendars(ids, appEnabled = true, channels, blockedGroupIds = emptySet())) + val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2")) + assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L) + assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L) + assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds) .containsExactly(1L) - assertThat(blockedReminderCalendars(ids, appEnabled = false, channels, blockedGroupIds = emptySet())) - .containsExactly(1L, 2L, 3L, 4L) + val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet()) + assertThat(appOff.appBlocked).isTrue() + assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L) } private companion object { From 31ba82a295060ba3b35c7fe77f532e56862a1459 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 02:50:36 +0100 Subject: [PATCH 08/11] =?UTF-8?q?fix(#145):=20review=20round=20C=20?= =?UTF-8?q?=E2=80=94=20no=20replay=20on=20unmute,=20fallback=20channel=20o?= =?UTF-8?q?n=20write=20failure,=20hide=20pending-off=20calendars?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data/reminders/ReminderChannels.kt | 24 +++++++++++-------- .../data/reminders/ReminderNotifier.kt | 8 +++---- .../ui/settings/SettingsViewModel.kt | 16 +++++++++---- 3 files changed, 30 insertions(+), 18 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 717292b8..3698ee76 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 @@ -86,19 +86,24 @@ class ReminderChannels @Inject constructor( Log.w(TAG, "Could not look up calendar $calendarId for its channel", e) emptyList() } + val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null) if (calendars.isEmpty()) { - val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null) write(emptyList(), listOf(fallback), existing) return id } val plan = plan(calendars, existing, emptyList()) val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null - val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } - write( - groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups }, - channels = listOf(spec), - existing = existing, - ) + try { + val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } + write( + groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups }, + channels = listOf(spec), + existing = existing, + ) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not file the channel of calendar $calendarId", e) + write(emptyList(), listOf(fallback), existing) + } return id } @@ -156,8 +161,8 @@ class ReminderChannels @Inject constructor( } /** - * 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. + * 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. */ private fun NotificationChannel.inheritFrom(template: NotificationChannel) { setSound(template.sound, template.audioAttributes) @@ -166,7 +171,6 @@ class ReminderChannels @Inject constructor( enableVibration(template.shouldVibrate()) enableLights(template.shouldShowLights()) lightColor = template.lightColor - lockscreenVisibility = template.lockscreenVisibility setShowBadge(template.canShowBadge()) // 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/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 7f03769c..f7a4fd46 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 @@ -66,12 +66,12 @@ class ReminderNotifier @Inject constructor( suspend fun post(alert: ReminderAlert) { if (isSilenced(alert.calendarId)) return val channelId = try { - channels.channelFor(alert.calendarId) + 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) - null - } ?: run { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") return } val title = displayTitle(alert) 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 18d7ed6b..21ff880b 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 @@ -21,6 +21,7 @@ import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -67,6 +68,7 @@ import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val prefs: SettingsPrefs, + calendarPrefs: CalendarPrefs, repository: CalendarRepository, private val specialDatesEngine: SpecialDatesSyncEngine, specialDatesSpec: SpecialDatesCalendarSpec, @@ -83,9 +85,10 @@ class SettingsViewModel @Inject constructor( * Calendars that are switched on — the only ones that plan reminders at * all (#75), so the only ones with notification settings. */ - private val visibleCalendars: Flow> = repository.calendars() - .map { calendars -> calendars.filter { it.isVisibleInSystem } } - .catch { emit(emptyList()) } + private val visibleCalendars: Flow> = + combine(repository.calendars(), calendarPrefs.pendingDisabledCalendarIds) { calendars, pending -> + calendars.filter { it.isVisibleInSystem && it.id !in pending } + }.catch { emit(emptyList()) } val state: StateFlow = combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) } @@ -365,9 +368,14 @@ class SettingsViewModel @Inject constructor( } } - /** Re-plans, since a muted calendar armed no wake-up for its next reminder. */ + /** + * Re-plans, since a muted calendar armed no wake-up for its next reminder. + * Unmuting scans once more before the write, so the watermark starts at the + * unmute and nothing that came due while muted is replayed. + */ fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { viewModelScope.launch { + if (enabled) reminderScanner.scan() prefs.setCalendarRemindersEnabled(calendarId, enabled) reminderScanner.scan() } From 14f2dfe158ec1936354675a9d5f3268e61fef51c Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 18:52:19 +0100 Subject: [PATCH 09/11] fix(#145): per-calendar reminders on their own grouped subpage --- .../ui/settings/CalendarReminderSettings.kt | 290 ++++++++++++++++++ .../ui/settings/NotificationSettings.kt | 197 +----------- .../calendula/ui/settings/SettingsScreen.kt | 20 +- app/src/main/res/values/strings.xml | 1 + floret-kit | 2 +- 5 files changed, 320 insertions(+), 190 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt new file mode 100644 index 00000000..206d2987 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt @@ -0,0 +1,290 @@ +package de.jeanlucmakiola.calendula.ui.settings + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS +import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker +import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle +import de.jeanlucmakiola.calendula.ui.common.groupByAccount +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.android.openNotificationSettings +import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.ExpandIcon +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.identity.collapseExit +import de.jeanlucmakiola.floret.identity.expandEnter +import de.jeanlucmakiola.floret.reminders.ReminderOverride +import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import kotlinx.coroutines.launch + +/** + * Per-calendar notifications and reminder overrides (#145, #272), reached from + * Settings → Notifications. Calendars are listed by account as connected groups; + * a calendar unfolds its options in place, one tone darker, inside its group. + */ +@Composable +internal fun CalendarRemindersScreen( + state: SettingsUiState, + viewModel: SettingsViewModel, + onBack: () -> Unit, + onOpenSpecialDates: () -> Unit, + visible: Boolean = true, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var expandedCalendars by rememberSaveable { mutableStateOf(emptyList()) } + var overrideDialog by remember { mutableStateOf(null) } + val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() + val calendarIds = state.reminderCalendars.map { it.id } + LifecycleResumeEffect(calendarIds) { + viewModel.refreshChannelStatus(calendarIds) + onPauseOrDispose { } + } + + CollapsingScaffold( + title = stringResource(R.string.settings_calendar_reminders_title), + onBack = onBack, + predictiveBack = true, + visible = visible, + ) { + GroupedHint(stringResource(R.string.settings_calendar_reminders_hint), style = MaterialTheme.typography.bodySmall) + state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group -> + if (groupIndex > 0) Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(accountGroupTitle(group)) + group.calendars.forEachIndexed { index, calendar -> + val expanded = calendar.id in expandedCalendars + val notifying = calendar.id !in state.mutedReminderCalendarIds + CalendarReminderEntry( + calendar = calendar, + state = state, + position = positionOf(index, group.calendars.size), + expanded = expanded, + notifying = notifying, + blocked = notifying && calendar.id in channelStatus.blockedCalendarIds, + onToggleExpand = { + expandedCalendars = if (expanded) { + expandedCalendars - calendar.id + } else { + expandedCalendars + calendar.id + } + }, + onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, + onOpenSound = { + scope.launch { + context.openNotificationSettings(viewModel.soundSettingsChannel(calendar.id)) + } + }, + onOpenSpecialDates = onOpenSpecialDates, + onEditOverride = { overrideDialog = it }, + ) + } + } + } + + overrideDialog?.let { target -> + val map = if (target.isAllDay) { + state.perCalendarAllDayReminderOverride + } else { + state.perCalendarReminderOverride + } + ReminderDefaultPicker( + title = stringResource( + if (target.isAllDay) { + R.string.settings_default_reminder_allday + } else { + R.string.settings_default_reminder + }, + ), + presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS, + selected = map.reminderOverrideFor(target.calendarId), + allowInherit = true, + onSelect = { + if (target.isAllDay) { + viewModel.setCalendarAllDayReminderOverride(target.calendarId, it) + } else { + viewModel.setCalendarReminderOverride(target.calendarId, it) + } + }, + onDismiss = { overrideDialog = null }, + leadTimeSummary = if (target.isAllDay) { + allDayFiringTimeSummary(state.allDayReminderTimeMinutes) + } else { + null + }, + ) + } +} + +/** + * One calendar in its account group, with its options unfolding beneath it: + * the notification switch and channel deep-link for every calendar, then the + * default-reminder overrides where it takes them — or, for a special-dates + * calendar, a link to the section that owns them. + */ +@Composable +private fun CalendarReminderEntry( + calendar: CalendarSource, + state: SettingsUiState, + position: Position, + expanded: Boolean, + notifying: Boolean, + blocked: Boolean, + onToggleExpand: () -> Unit, + onSetNotifying: (Boolean) -> Unit, + onOpenSound: () -> Unit, + onOpenSpecialDates: () -> Unit, + onEditOverride: (OverrideTarget) -> Unit, +) { + val opensGroup = position == Position.Top || position == Position.Alone + val closesGroup = position == Position.Bottom || position == Position.Alone + GroupedRow( + title = calendar.displayName.orUnnamed(), + summary = when { + !notifying -> stringResource(R.string.settings_calendar_notifications_off) + blocked -> stringResource(R.string.settings_notifications_blocked) + else -> null + }, + position = when { + !expanded -> position + opensGroup -> Position.Top + else -> Position.Middle + }, + leading = { CalendarColorChip(calendar.color) }, + trailing = { ExpandIcon(expanded) }, + onClick = onToggleExpand, + ) + AnimatedVisibility( + visible = expanded, + enter = expandEnter(), + exit = collapseExit(), + ) { + val managed = calendar.id in state.managedCalendarIds + val takesOverrides = calendar.canModifyContents && !managed + val nested = MaterialTheme.colorScheme.surfaceContainerHighest + val last = if (closesGroup) Position.Bottom else Position.Middle + Column { + GroupedSwitchRow( + title = stringResource(R.string.settings_calendar_notifications), + checked = notifying, + onCheckedChange = onSetNotifying, + summary = stringResource(R.string.settings_calendar_notifications_hint), + position = Position.Middle, + container = nested, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = if (blocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_calendar_notification_sound_hint) + }, + position = if (managed || takesOverrides) Position.Middle else last, + container = nested, + 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 = last, + container = nested, + trailing = { ChevronIcon() }, + onClick = onOpenSpecialDates, + ) + } else if (takesOverrides) { + OverrideRow( + calendarId = calendar.id, + isAllDay = false, + choice = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id), + globalDefault = state.defaultReminderMinutes, + position = Position.Middle, + container = nested, + onEditOverride = onEditOverride, + ) + OverrideRow( + calendarId = calendar.id, + isAllDay = true, + choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id), + globalDefault = state.defaultAllDayReminderMinutes, + position = last, + container = nested, + onEditOverride = onEditOverride, + ) + } + } + } +} + +@Composable +private fun OverrideRow( + calendarId: Long, + isAllDay: Boolean, + choice: ReminderOverride, + globalDefault: List, + position: Position, + container: Color, + onEditOverride: (OverrideTarget) -> Unit, +) { + GroupedRow( + title = stringResource( + if (isAllDay) R.string.settings_default_reminder_allday else R.string.settings_default_reminder, + ), + summary = calendarOverrideSummary(choice, globalDefault), + position = position, + container = container, + onClick = { onEditOverride(OverrideTarget(calendarId, isAllDay)) }, + ) +} + +@Composable +private fun ChevronIcon() { + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** Which calendar + event kind a per-calendar reminder-override dialog targets. */ +private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) + +/** Row summary for a calendar: its override, or the inherited global default. */ +@Composable +private fun calendarOverrideSummary( + choice: ReminderOverride, + globalDefault: List, +): String = when (choice) { + ReminderOverride.Inherit -> + stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault)) + ReminderOverride.None -> stringResource(R.string.reminder_none) + is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) +} 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..b90b06c9 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,9 +8,7 @@ import android.os.PowerManager import android.provider.Settings import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth @@ -42,28 +40,21 @@ import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R -import de.jeanlucmakiola.calendula.domain.CalendarSource -import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.DurationPicker import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert import de.jeanlucmakiola.calendula.ui.common.durationLabel -import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.android.hasPermission import de.jeanlucmakiola.floret.android.openNotificationSettings import de.jeanlucmakiola.floret.components.CollapsingScaffold -import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.IconInfoCard import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck -import de.jeanlucmakiola.floret.identity.collapseExit -import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.minutesOrEmpty -import de.jeanlucmakiola.floret.reminders.reminderOverrideFor import kotlinx.coroutines.launch import kotlinx.datetime.LocalTime @@ -77,7 +68,7 @@ internal fun NotificationsScreen( state: SettingsUiState, viewModel: SettingsViewModel, onBack: () -> Unit, - onOpenSpecialDates: () -> Unit, + onOpenCalendarReminders: () -> Unit, visible: Boolean = true, ) { val context = LocalContext.current @@ -98,9 +89,6 @@ internal fun NotificationsScreen( var showAllDayReminder by remember { mutableStateOf(false) } var showAllDayReminderTime by remember { mutableStateOf(false) } var showSnooze by remember { mutableStateOf(false) } - var overrideDialog by remember { mutableStateOf(null) } - var calendarSectionExpanded by remember { mutableStateOf(false) } - var expandedCalendars by remember { mutableStateOf(emptySet()) } val scope = rememberCoroutineScope() val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() val calendarIds = state.reminderCalendars.map { it.id } @@ -108,9 +96,6 @@ internal fun NotificationsScreen( viewModel.refreshChannelStatus(calendarIds) onPauseOrDispose { } } - val openCalendarSound: (Long) -> Unit = { calendarId -> - scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) } - } CollapsingScaffold( title = stringResource(R.string.settings_section_notifications), @@ -203,64 +188,21 @@ internal fun NotificationsScreen( onClick = { showSnooze = true }, ) - // Per-calendar notifications and reminder overrides (#145, #272). if (state.reminderCalendars.isNotEmpty()) { Spacer(Modifier.height(24.dp)) GroupedRow( title = stringResource(R.string.settings_calendar_reminders_title), - summary = stringResource(R.string.settings_calendar_reminders_hint), + summary = stringResource(R.string.settings_calendar_reminders_subtitle), position = Position.Alone, - trailing = { ExpandIcon(calendarSectionExpanded) }, - onClick = { calendarSectionExpanded = !calendarSectionExpanded }, + trailing = { + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + onClick = onOpenCalendarReminders, ) - AnimatedVisibility( - visible = calendarSectionExpanded, - enter = expandEnter(), - exit = collapseExit(), - ) { - Column { - state.reminderCalendars.forEach { calendar -> - Spacer(Modifier.height(16.dp)) - val expanded = calendar.id in expandedCalendars - val notifying = calendar.id !in state.mutedReminderCalendarIds - val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds - GroupedRow( - title = calendar.displayName.orUnnamed(), - summary = when { - !notifying -> stringResource(R.string.settings_calendar_notifications_off) - blocked -> stringResource(R.string.settings_notifications_blocked) - else -> null - }, - position = if (expanded) Position.Top else Position.Alone, - leading = { CalendarColorChip(calendar.color) }, - trailing = { ExpandIcon(expanded) }, - onClick = { - expandedCalendars = if (expanded) { - expandedCalendars - calendar.id - } else { - expandedCalendars + calendar.id - } - }, - ) - AnimatedVisibility( - visible = expanded, - enter = expandEnter(), - exit = collapseExit(), - ) { - CalendarNotificationRows( - calendar = calendar, - state = state, - notifying = notifying, - blocked = blocked, - onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, - onOpenSound = { openCalendarSound(calendar.id) }, - onOpenSpecialDates = onOpenSpecialDates, - onEditOverride = { overrideDialog = it }, - ) - } - } - } - } } } @@ -309,108 +251,6 @@ internal fun NotificationsScreen( onDismiss = { showAllDayReminderTime = false }, ) } - overrideDialog?.let { target -> - val map = if (target.isAllDay) { - state.perCalendarAllDayReminderOverride - } else { - state.perCalendarReminderOverride - } - ReminderDefaultPicker( - title = stringResource( - if (target.isAllDay) { - R.string.settings_default_reminder_allday - } else { - R.string.settings_default_reminder - }, - ), - presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS, - selected = map.reminderOverrideFor(target.calendarId), - allowInherit = true, - onSelect = { - if (target.isAllDay) { - viewModel.setCalendarAllDayReminderOverride(target.calendarId, it) - } else { - viewModel.setCalendarReminderOverride(target.calendarId, it) - } - }, - onDismiss = { overrideDialog = null }, - leadTimeSummary = if (target.isAllDay) { - allDayFiringTimeSummary(state.allDayReminderTimeMinutes) - } else { - null - }, - ) - } -} - -/** - * 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, - blocked: 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 = if (blocked) { - stringResource(R.string.settings_notifications_blocked_hint) - } else { - stringResource(R.string.settings_calendar_notification_sound_hint) - }, - position = if (managed || takesOverrides) Position.Middle else Position.Bottom, - 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)) }, - ) - } - } } /** Samsung's One UI can start a new notification category switched off (#145). */ @@ -436,7 +276,7 @@ private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) } @Composable -private fun ExternalLinkIcon() { +internal fun ExternalLinkIcon() { Icon( imageVector = Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, @@ -444,25 +284,10 @@ private fun ExternalLinkIcon() { ) } -/** Which calendar + event kind a per-calendar reminder-override dialog targets. */ -private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) - /** A global default (empty = none) as a picker choice for selection highlighting. */ private fun List.toReminderChoice(): ReminderOverride = if (isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(this) -/** Row summary for a calendar: its override, or the inherited global default. */ -@Composable -private fun calendarOverrideSummary( - choice: ReminderOverride, - globalDefault: List, -): String = when (choice) { - ReminderOverride.Inherit -> - stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault)) - ReminderOverride.None -> stringResource(R.string.reminder_none) - is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) -} - /** Snooze delays offered for the notification "Snooze" action, in minutes. */ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt index 3bab7449..e3ba551c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt @@ -73,7 +73,7 @@ import de.jeanlucmakiola.floret.identity.predictiveBackExit /** The settings sub-screens reached from the hub's category rows. */ private enum class SettingsSection { - Appearance, Views, EventForm, Notifications, SpecialDates, Widgets, Licences + Appearance, Views, EventForm, Notifications, CalendarReminders, SpecialDates, Widgets, Licences } /** @@ -131,8 +131,9 @@ fun SettingsScreen( ) { EventFormScreen(state = state, viewModel = viewModel, onBack = { section = null }, visible = section == SettingsSection.EventForm) } + // Stays up beneath its per-calendar subpage, so backing out reveals it. AnimatedVisibility( - visible = section == SettingsSection.Notifications, + visible = section == SettingsSection.Notifications || section == SettingsSection.CalendarReminders, enter = slideInHorizontally(slideSpec) { it } + fadeIn(), exit = overlayExit, ) { @@ -140,10 +141,23 @@ fun SettingsScreen( state = state, viewModel = viewModel, onBack = { section = null }, - onOpenSpecialDates = { section = SettingsSection.SpecialDates }, + onOpenCalendarReminders = { section = SettingsSection.CalendarReminders }, visible = section == SettingsSection.Notifications, ) } + AnimatedVisibility( + visible = section == SettingsSection.CalendarReminders, + enter = slideInHorizontally(slideSpec) { it } + fadeIn(), + exit = overlayExit, + ) { + CalendarRemindersScreen( + state = state, + viewModel = viewModel, + onBack = { section = SettingsSection.Notifications }, + onOpenSpecialDates = { section = SettingsSection.SpecialDates }, + visible = section == SettingsSection.CalendarReminders, + ) + } AnimatedVisibility( visible = section == SettingsSection.SpecialDates, enter = slideInHorizontally(slideSpec) { it } + fadeIn(), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e7b8d77..8d182bf1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -731,6 +731,7 @@ Amount Set Per-calendar reminders + Notifications, sound and default reminders per calendar 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 diff --git a/floret-kit b/floret-kit index 20b136aa..a517ef6e 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 20b136aaf71277643267018ed1c57dae0b0c54ec +Subproject commit a517ef6e028b6e501d9397f5a74bad36c4188d09 From 10e18ef888ac813c9825600f7eead118c367e344 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 19:09:00 +0100 Subject: [PATCH 10/11] fix(#145): an expanded calendar closes off its own rounded run --- .../ui/settings/CalendarReminderSettings.kt | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt index 206d2987..fa6e15b5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt @@ -38,7 +38,6 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride @@ -79,13 +78,18 @@ internal fun CalendarRemindersScreen( state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group -> if (groupIndex > 0) Spacer(Modifier.height(8.dp)) GroupedSectionHeader(accountGroupTitle(group)) - group.calendars.forEachIndexed { index, calendar -> + val calendars = group.calendars + calendars.forEachIndexed { index, calendar -> val expanded = calendar.id in expandedCalendars + val isExpanded = { i: Int -> calendars[i].id in expandedCalendars } val notifying = calendar.id !in state.mutedReminderCalendarIds CalendarReminderEntry( calendar = calendar, state = state, - position = positionOf(index, group.calendars.size), + position = segmentPosition( + startsSegment = expanded || index == 0 || isExpanded(index - 1), + endsSegment = !expanded && (index == calendars.lastIndex || isExpanded(index + 1)), + ), expanded = expanded, notifying = notifying, blocked = notifying && calendar.id in channelStatus.blockedCalendarIds, @@ -163,8 +167,6 @@ private fun CalendarReminderEntry( onOpenSpecialDates: () -> Unit, onEditOverride: (OverrideTarget) -> Unit, ) { - val opensGroup = position == Position.Top || position == Position.Alone - val closesGroup = position == Position.Bottom || position == Position.Alone GroupedRow( title = calendar.displayName.orUnnamed(), summary = when { @@ -172,11 +174,7 @@ private fun CalendarReminderEntry( blocked -> stringResource(R.string.settings_notifications_blocked) else -> null }, - position = when { - !expanded -> position - opensGroup -> Position.Top - else -> Position.Middle - }, + position = position, leading = { CalendarColorChip(calendar.color) }, trailing = { ExpandIcon(expanded) }, onClick = onToggleExpand, @@ -189,7 +187,7 @@ private fun CalendarReminderEntry( val managed = calendar.id in state.managedCalendarIds val takesOverrides = calendar.canModifyContents && !managed val nested = MaterialTheme.colorScheme.surfaceContainerHighest - val last = if (closesGroup) Position.Bottom else Position.Middle + val last = Position.Bottom Column { GroupedSwitchRow( title = stringResource(R.string.settings_calendar_notifications), @@ -244,6 +242,17 @@ private fun CalendarReminderEntry( } } +/** + * A calendar row's place in its connected run: an expanded calendar opens its own + * run that its options close, so the rows around it round off against it. + */ +private fun segmentPosition(startsSegment: Boolean, endsSegment: Boolean): Position = when { + startsSegment && endsSegment -> Position.Alone + startsSegment -> Position.Top + endsSegment -> Position.Bottom + else -> Position.Middle +} + @Composable private fun OverrideRow( calendarId: Long, From efe454f200473f58b3f3b9192acc1bec7ef9a314 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 19:18:47 +0100 Subject: [PATCH 11/11] fix(#145): an expanded calendar's options round off with a gap below --- .../ui/settings/CalendarReminderSettings.kt | 37 ++++++++----------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt index fa6e15b5..ef670cad 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt @@ -4,6 +4,7 @@ import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material3.Icon @@ -38,6 +39,7 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride @@ -81,15 +83,11 @@ internal fun CalendarRemindersScreen( val calendars = group.calendars calendars.forEachIndexed { index, calendar -> val expanded = calendar.id in expandedCalendars - val isExpanded = { i: Int -> calendars[i].id in expandedCalendars } val notifying = calendar.id !in state.mutedReminderCalendarIds CalendarReminderEntry( calendar = calendar, state = state, - position = segmentPosition( - startsSegment = expanded || index == 0 || isExpanded(index - 1), - endsSegment = !expanded && (index == calendars.lastIndex || isExpanded(index + 1)), - ), + position = positionOf(index, calendars.size), expanded = expanded, notifying = notifying, blocked = notifying && calendar.id in channelStatus.blockedCalendarIds, @@ -167,6 +165,8 @@ private fun CalendarReminderEntry( onOpenSpecialDates: () -> Unit, onEditOverride: (OverrideTarget) -> Unit, ) { + val opensGroup = position == Position.Top || position == Position.Alone + val closesGroup = position == Position.Bottom || position == Position.Alone GroupedRow( title = calendar.displayName.orUnnamed(), summary = when { @@ -174,7 +174,11 @@ private fun CalendarReminderEntry( blocked -> stringResource(R.string.settings_notifications_blocked) else -> null }, - position = position, + position = when { + !expanded -> position + opensGroup -> Position.Top + else -> Position.Middle + }, leading = { CalendarColorChip(calendar.color) }, trailing = { ExpandIcon(expanded) }, onClick = onToggleExpand, @@ -187,8 +191,8 @@ private fun CalendarReminderEntry( val managed = calendar.id in state.managedCalendarIds val takesOverrides = calendar.canModifyContents && !managed val nested = MaterialTheme.colorScheme.surfaceContainerHighest - val last = Position.Bottom - Column { + // The options round off their calendar; mid-group they keep the row gap. + Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) { GroupedSwitchRow( title = stringResource(R.string.settings_calendar_notifications), checked = notifying, @@ -204,7 +208,7 @@ private fun CalendarReminderEntry( } else { stringResource(R.string.settings_calendar_notification_sound_hint) }, - position = if (managed || takesOverrides) Position.Middle else last, + position = if (managed || takesOverrides) Position.Middle else Position.Bottom, container = nested, trailing = { ExternalLinkIcon() }, onClick = onOpenSound, @@ -213,7 +217,7 @@ private fun CalendarReminderEntry( GroupedRow( title = stringResource(R.string.settings_default_reminder_allday), summary = stringResource(R.string.settings_calendar_reminders_managed_hint), - position = last, + position = Position.Bottom, container = nested, trailing = { ChevronIcon() }, onClick = onOpenSpecialDates, @@ -233,7 +237,7 @@ private fun CalendarReminderEntry( isAllDay = true, choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id), globalDefault = state.defaultAllDayReminderMinutes, - position = last, + position = Position.Bottom, container = nested, onEditOverride = onEditOverride, ) @@ -242,17 +246,6 @@ private fun CalendarReminderEntry( } } -/** - * A calendar row's place in its connected run: an expanded calendar opens its own - * run that its options close, so the rows around it round off against it. - */ -private fun segmentPosition(startsSegment: Boolean, endsSegment: Boolean): Position = when { - startsSegment && endsSegment -> Position.Alone - startsSegment -> Position.Top - endsSegment -> Position.Bottom - else -> Position.Middle -} - @Composable private fun OverrideRow( calendarId: Long,