diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 409adcb7..27bece29 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -182,6 +182,7 @@ dependencies { implementation("de.jeanlucmakiola.floret:identity") implementation("de.jeanlucmakiola.floret:components") implementation("de.jeanlucmakiola.floret:glance") + implementation("de.jeanlucmakiola.floret:ring") implementation(libs.kotlinx.coroutines.core) debugImplementation(libs.androidx.ui.tooling) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b272d8e9..ba46a26e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,10 +41,15 @@ --> - + - - + + + + + + + + + + + + > = prefs.flow(SettingsKeys.perCalendarEventDuration) val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) + val reminderAlertStyles: Flow> = prefs.flow(SettingsKeys.reminderAlertStyles) val notificationCategoryHintDismissed: Flow = prefs.flow(SettingsKeys.notificationCategoryHintDismissed) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) @@ -281,6 +285,10 @@ class SettingsPrefs @Inject constructor( prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId } } + suspend fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + prefs.update(SettingsKeys.reminderAlertStyles) { it + (calendarId to style) } + } + suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled) @@ -608,6 +616,10 @@ object SettingsKeys { */ val mutedReminderCalendarIds: Pref> = idSetPref("muted_reminder_calendar_ids") + /** Per-calendar alert styles (#171); a calendar absent from the map uses plain notifications. */ + val reminderAlertStyles: Pref> = + nullableStringPref("reminder_alert_styles").map(::parseAlertStyles) { it.toStoredAlertStyles() } + /** * Whether the one-time hint that some skins (Samsung) start new notification * categories switched off has been dismissed (#145). diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt new file mode 100644 index 00000000..cfc415eb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -0,0 +1,85 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * What the full-screen alerts (#171) share within the process: the reminder + * [ReminderRingService] is ringing for, and the reminders just dismissed or + * snoozed, so an alert screen showing one closes whichever way it was handled. + */ +@Singleton +class FullScreenAlerts @Inject constructor() { + + /** Written only by [ReminderRingService], on the main thread, for as long as it rings. */ + @Volatile + var ringing: ReminderAlert? = null + internal set + + /** Rings handed to [ReminderRingService] that have not reached it yet, with how many starts each. */ + private val pending = ConcurrentHashMap>() + + /** Set when the service is stopped from outside but its ring should go back to the shade. */ + @Volatile + internal var handBackOnDestroy = false + + internal fun addPending(alert: ReminderAlert) { + pending.compute(alert.key) { _, entry -> alert to ((entry?.second ?: 0) + 1) } + } + + internal fun removePending(alert: ReminderAlert) { + pending.computeIfPresent(alert.key) { _, entry -> if (entry.second <= 1) null else entry.first to entry.second - 1 } + } + + internal fun isPending(alert: ReminderAlert): Boolean = pending.containsKey(alert.key) + + internal val anyPending: Boolean get() = pending.isNotEmpty() + + /** + * Whether a ring going or on its way [match]es, so a stop is worth sending. + * Pending first: the service sets [ringing] before it lets a start go. + */ + fun mayRing(match: RingMatch): Boolean = + pending.values.any { match.matches(it.first) } || ringing?.let(match::matches) == true + + private val handledKeys = MutableSharedFlow( + extraBufferCapacity = 8, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */ + val handled: SharedFlow = handledKeys.asSharedFlow() + + fun markHandled(alert: ReminderAlert) { + handledKeys.tryEmit(alert.key) + } +} + +/** What becomes of a ring once its settings are re-read. */ +enum class RingVerdict { Ring, HandBack, Drop } + +/** Which ring a stop is for. */ +sealed interface RingMatch { + fun matches(alert: ReminderAlert): Boolean + + data class Key(val key: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.key == key + } + + data class Occurrence(val occurrenceKey: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.occurrenceKey == occurrenceKey + } + + data class Calendar(val calendarId: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.calendarId == calendarId + } + + data object Any : RingMatch { + override fun matches(alert: ReminderAlert) = true + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt index c0bd7569..7329fd06 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt @@ -13,8 +13,8 @@ import javax.inject.Inject /** * Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus * the internal re-show when a snooze elapses. All three are app-internal - * intents (notification action buttons and our own [ReminderSnoozeScheduler] - * alarm), so the receiver is not exported. + * intents (notification action buttons, the full-screen alert's buttons and + * our own [ReminderSnoozeScheduler] alarm), so the receiver is not exported. * * - **Dismiss** just cancels the notification — the scan's watermark has moved * past this reminder, so nothing re-posts it. @@ -74,6 +74,9 @@ class ReminderActionReceiver : BroadcastReceiver() { */ const val ACTION_OPEN = "de.jeanlucmakiola.calendula.reminders.OPEN" + /** Not handled here either: the slot of the full-screen alert's own intent (#171). */ + const val ACTION_ALERT_SCREEN = "de.jeanlucmakiola.calendula.reminders.ALERT_SCREEN" + private const val EXTRA_ALERT_KEY = "alert_key" private const val EXTRA_EVENT_ID = "event_id" private const val EXTRA_CALENDAR_ID = "calendar_id" @@ -94,16 +97,21 @@ class ReminderActionReceiver : BroadcastReceiver() { Intent(context, ReminderActionReceiver::class.java).apply { this.action = action data = "calendula://reminder/${identity(alert, action)}".toUri() - putExtra(EXTRA_ALERT_KEY, alert.key) - putExtra(EXTRA_EVENT_ID, alert.eventId) - putExtra(EXTRA_CALENDAR_ID, alert.calendarId) - putExtra(EXTRA_BEGIN, alert.beginMillis) - putExtra(EXTRA_END, alert.endMillis) - putExtra(EXTRA_TITLE, alert.title) - putExtra(EXTRA_LOCATION, alert.location) - putExtra(EXTRA_ALL_DAY, alert.isAllDay) + putAlert(alert) } + /** Carries [alert] as extras, for [alertFrom] to read back. */ + fun Intent.putAlert(alert: ReminderAlert): Intent = apply { + putExtra(EXTRA_ALERT_KEY, alert.key) + putExtra(EXTRA_EVENT_ID, alert.eventId) + putExtra(EXTRA_CALENDAR_ID, alert.calendarId) + putExtra(EXTRA_BEGIN, alert.beginMillis) + putExtra(EXTRA_END, alert.endMillis) + putExtra(EXTRA_TITLE, alert.title) + putExtra(EXTRA_LOCATION, alert.location) + putExtra(EXTRA_ALL_DAY, alert.isAllDay) + } + /** * A stable request code per (alert, action), so one notification's * PendingIntents stay distinct. The shift keeps the action slot intact; @@ -115,6 +123,7 @@ class ReminderActionReceiver : BroadcastReceiver() { ACTION_DISMISS -> 2 ACTION_SHOW -> 3 ACTION_OPEN -> 4 + ACTION_ALERT_SCREEN -> 5 else -> 0 } return (identity(alert, action).toInt() shl 3) + actionOffset @@ -123,7 +132,7 @@ class ReminderActionReceiver : BroadcastReceiver() { private fun identity(alert: ReminderAlert, action: String): Long = if (action == ACTION_SHOW) alert.occurrenceKey else alert.key - private fun alertFrom(intent: Intent): ReminderAlert? { + fun alertFrom(intent: Intent): ReminderAlert? { if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null return ReminderAlert( key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt index e67a7727..aa3a6b68 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 @@ -6,6 +6,9 @@ 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" +/** The silent channel ringing full-screen alerts post on (#171); outside the per-calendar namespace. */ +const val RING_CHANNEL_ID = "reminders_ring" + private const val CHANNEL_PREFIX = "reminders.calendar." private const val GROUP_PREFIX = "reminders.account." private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local" @@ -138,6 +141,8 @@ data class ReminderChannelStatus( 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 shared ring channel (#171) is switched off, so ringing calendars only sound once. */ + val ringBlocked: Boolean = false, ) /** @@ -157,5 +162,10 @@ fun reminderChannelStatus( } else { calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.blocked == true } + groupBlocked } - return ReminderChannelStatus(appBlocked = !appEnabled, blockedCalendarIds = blocked, groupBlockedCalendarIds = groupBlocked) + return ReminderChannelStatus( + appBlocked = !appEnabled, + blockedCalendarIds = blocked, + groupBlockedCalendarIds = groupBlocked, + ringBlocked = appEnabled && channels[RING_CHANNEL_ID]?.blocked == true, + ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 3698ee76..20ec0453 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.data.reminders +import android.app.Notification import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager @@ -9,6 +10,7 @@ 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.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel import java.util.Locale import javax.inject.Inject @@ -57,6 +59,7 @@ class ReminderChannels @Inject constructor( channels = plan.channelsToWrite, existing = existing, ) + if (RING_CHANNEL_ID in existingIds) ensureRingChannel() val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids) } @@ -72,10 +75,64 @@ class ReminderChannels @Inject constructor( * has not got to it yet. Null when the calendar no longer exists. Should the * calendar lookup fail or come back empty, the channel is still created, * plainly named and ungrouped, for the next sync to name and file — a - * reminder is never lost to its channel. + * reminder is never lost to its channel. A ringing [style] posts on the + * shared ring channel instead, once the calendar is known to exist. */ @Synchronized - fun channelFor(calendarId: Long): String? { + fun channelFor(calendarId: Long, style: ReminderAlertStyle = ReminderAlertStyle.Notification): String? { + val calendarChannel = calendarChannelFor(calendarId) ?: return null + return if (style == ReminderAlertStyle.FullScreenRing) ringChannel() else calendarChannel + } + + /** + * The channel a ringing full-screen alert (#171) posts on, shared by every + * calendar. Silent: the ring service owns the sound and vibration, so the + * channel adds neither. High importance keeps the heads-up a denied + * full-screen intent degrades to. + */ + private fun ringChannel(): String { + ensureRingChannel() + return RING_CHANNEL_ID + } + + /** + * Creates the ring channel, or renames it after a language change. Called + * as soon as a calendar is set to ring, so the channel can be checked in + * system settings (and switched on, where a skin starts it off) before the + * first ring. + */ + @Synchronized + fun ensureRingChannel() { + val manager = manager + val name = context.getString(R.string.reminder_ring_channel_name) + val description = context.getString(R.string.reminder_ring_channel_description) + val current = manager.getNotificationChannel(RING_CHANNEL_ID) + if (current != null && current.name?.toString() == name && current.description == description) return + manager.createNotificationChannel( + NotificationChannel( + RING_CHANNEL_ID, + name, + NotificationManager.IMPORTANCE_HIGH, + ).apply { + this.description = description + setSound(null, null) + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + }, + ) + } + + /** + * Whether a ring may sound for [calendarId]: neither its own channel, its + * account's group nor the ring channel is blocked, since the service plays + * the sound itself. + */ + fun canRing(calendarId: Long): Boolean { + val status = status(listOf(calendarId)) + return !status.appBlocked && calendarId !in status.blockedCalendarIds && !status.ringBlocked + } + + private fun calendarChannelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager if (manager.getNotificationChannel(id) != null) return id diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index f7a4fd46..5d6582e6 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,6 +1,7 @@ package de.jeanlucmakiola.calendula.data.reminders import android.Manifest +import android.app.Notification import android.app.PendingIntent import android.content.Context import android.os.Build @@ -16,7 +17,11 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor +import de.jeanlucmakiola.calendula.ui.reminders.ReminderAlertActivity import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent import kotlinx.coroutines.flow.first import kotlinx.datetime.isoDayNumber import java.time.DayOfWeek @@ -28,7 +33,8 @@ import javax.inject.Singleton /** * Posts one notification per occurrence on its calendar's channel - * ([ReminderChannels], #145). Tapping opens the event's detail screen. + * ([ReminderChannels], #145), or as a full-screen alert where the calendar + * asks for one (#171). 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 @@ -42,6 +48,7 @@ class ReminderNotifier @Inject constructor( private val calendarPrefs: CalendarPrefs, private val calendarDataSource: CalendarDataSource, private val channels: ReminderChannels, + private val alerts: FullScreenAlerts, ) { /** False when the user declined `POST_NOTIFICATIONS` or muted the app. */ @@ -62,19 +69,86 @@ class ReminderNotifier @Inject constructor( calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || calendarDataSource.isCalendarVisible(calendarId) == false - /** Post [alert], unless its calendar is silenced or gone. */ - suspend fun post(alert: ReminderAlert) { + /** + * Post [alert] in its calendar's alert style (#171), unless the calendar is + * silenced or gone. [ring] false posts a ringing style as a full-screen + * alert that sounds once instead; [quiet] posts a plain notification that + * makes no sound. Both are how a ring hands a reminder back to the shade. + */ + suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) { if (isSilenced(alert.calendarId)) return - val channelId = try { - channels.channelFor(alert.calendarId) ?: run { - Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + var style = when { + quiet -> ReminderAlertStyle.Notification + else -> effectiveStyle(alert).let { + if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it + } + } + // Rung already and handed back to the shade: a catch-up post leaves it there. + if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return + val channelId = channelFor(alert, style) + // The ring channel could not be made: still full-screen, sounding once. + ?: if (style == ReminderAlertStyle.FullScreenRing) { + style = ReminderAlertStyle.FullScreen + channelFor(alert, style) ?: return + } else { return } - } catch (e: Exception) { - Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + val title = displayTitle(alert) + val text = contentText(alert) + if (style == ReminderAlertStyle.FullScreenRing) { + if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, title, text, style, quiet = false))) { + // An earlier reminder for this occurrence gives way to the ring. + NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) + cancelLegacy(alert) + return + } + // Android refused the ring: still full-screen, sounding once on the calendar's channel. + stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return + notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet = false)) return } - val title = displayTitle(alert) + // A fresh reminder replaces a ring for its occurrence from before the style changed. + if (ring) stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + notify(alert, build(alert, channelId, title, text, style, quiet)) + } + + /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ + suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when { + !settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) || + calendarDataSource.isCalendarVisible(alert.calendarId) == null -> RingVerdict.Drop + effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack + else -> RingVerdict.Ring + } + + /** Whether a live ring for [alert] may go on: its notification can still be seen, and its calendar still notifies. */ + suspend fun canStillRing(alert: ReminderAlert): Boolean = + canPost() && channels.canRing(alert.calendarId) && !isSilenced(alert.calendarId) + + /** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */ + private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle { + val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) + return if (chosen == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) { + ReminderAlertStyle.FullScreen + } else { + chosen + } + } + + private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { + channels.channelFor(alert.calendarId, style).also { + if (it == null) Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + } + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + null + } + + private suspend fun contentText(alert: ReminderAlert): String = + listOfNotNull(timeText(alert), alert.location).joinToString(" · ") + + /** When [alert]'s occurrence happens, as its notification words it. */ + suspend fun timeText(alert: ReminderAlert): String { val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) val zone = ZoneId.systemDefault() @@ -82,7 +156,7 @@ class ReminderNotifier @Inject constructor( // resolveFirstDay yields a kotlinx.datetime day; bridge it to java.time by // its shared ISO number (1..7) for the date math in reminderTimeText. val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber) - val time = reminderTimeText( + return reminderTimeText( beginMillis = alert.beginMillis, endMillis = alert.endMillis, isAllDay = alert.isAllDay, @@ -95,19 +169,35 @@ class ReminderNotifier @Inject constructor( tomorrowLabel = context.getString(R.string.reminder_day_tomorrow), yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) - val text = listOfNotNull(time, alert.location).joinToString(" · ") - val notification = NotificationCompat.Builder(context, channelId) + } + + /** + * The reminder's notification in [style]. A ringing one belongs to + * [ReminderRingService]: ongoing and opening the alert screen. A full-screen + * one adds the alert screen as a full-screen intent where Android allows + * it, degrading to a heads-up where it does not, and is dismissed by a + * swipe, so its screen closes too. + */ + private fun build( + alert: ReminderAlert, + channelId: String, + title: String, + text: String, + style: ReminderAlertStyle, + quiet: Boolean, + ): Notification { + val ringing = style == ReminderAlertStyle.FullScreenRing + val fullScreen = style.isFullScreen + val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) .setWhen(alert.beginMillis) .setShowWhen(false) - .setCategory(NotificationCompat.CATEGORY_EVENT) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setAutoCancel(true) - .setOnlyAlertOnce(shownKey(alert) == alert.key) + .setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT) + .setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH) .addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) }) - .setContentIntent(detailIntent(alert)) + .setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert)) .addAction( R.drawable.ic_notification_snooze, context.getString(R.string.reminder_action_snooze), @@ -118,7 +208,18 @@ class ReminderNotifier @Inject constructor( context.getString(R.string.reminder_action_dismiss), actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS), ) - .build() + if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) + if (ringing) { + builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + } else { + builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key) + } + if (quiet) builder.setSilent(true) + if (fullScreen && context.canUseFullScreenIntent()) builder.setFullScreenIntent(alertScreenIntent(alert), true) + return builder.build() + } + + private fun notify(alert: ReminderAlert, notification: Notification) { val manager = NotificationManagerCompat.from(context) cancelLegacy(alert) try { @@ -139,10 +240,25 @@ class ReminderNotifier @Inject constructor( if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) // Posted before reminders shared a notification, under the reminder's own key. manager.cancel(alert.key.toString(), NOTIFICATION_ID) + stopRing(RingMatch.Key(alert.key)) + alerts.markHandled(alert) + } + + /** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */ + fun stopRing(match: RingMatch, handBack: Boolean = false) { + if (alerts.mayRing(match)) ReminderRingService.stop(context, alerts, match, handBack) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ - fun isSuperseded(alert: ReminderAlert): Boolean = shownKey(alert).let { it != null && it != alert.key } + fun isSuperseded(alert: ReminderAlert): Boolean { + val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey } + if (ringing != null) return ringing.key != alert.key + return shownKey(alert).let { it != null && it != alert.key } + } + + /** Whether [alert] itself is still on screen, as a notification or ringing. */ + fun isShowing(alert: ReminderAlert): Boolean = + alerts.ringing?.key == alert.key || shownKey(alert) == alert.key /** The key of the reminder showing for [alert]'s occurrence, if any. */ private fun shownKey(alert: ReminderAlert): Long? { @@ -179,6 +295,13 @@ class ReminderNotifier @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) + private fun alertScreenIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( + context, + ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_ALERT_SCREEN), + ReminderAlertActivity.intent(context, alert), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( context, // Shares the per-(alert, action) request-code scheme with the buttons. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt new file mode 100644 index 00000000..47244dd3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -0,0 +1,354 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.Notification +import android.app.Service +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.os.IBinder +import android.util.Log +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.IntentCompat +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.di.ApplicationScope +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.floret.ring.RingVibrator +import de.jeanlucmakiola.floret.ring.RingWakeLock +import de.jeanlucmakiola.floret.ring.TonePlayer +import de.jeanlucmakiola.floret.ring.isInCall +import de.jeanlucmakiola.floret.ring.startRingForeground +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * Rings a reminder whose calendar asks for "Ring until dismissed" (#171): the + * alarm sound looped with vibration, for as long as the reminder is neither + * dismissed nor snoozed, up to [RING_TIMEOUT_MILLIS]. Then it goes quiet and + * hands the reminder back to the shade as an ordinary notification. + * + * One reminder rings at a time. A new one takes over, and the one it replaces + * goes back to the shade, silently, unless it was for the same occurrence. + * Starts and stops both arrive as commands, so they are handled on the main + * thread in the order they were sent. + */ +@AndroidEntryPoint +class ReminderRingService : Service() { + + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var notifier: ReminderNotifier + + @Inject @ApplicationScope + lateinit var appScope: CoroutineScope + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + private val tones by lazy { TonePlayer(this) } + private val vibrator by lazy { RingVibrator(this) } + private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, RING_TIMEOUT_MILLIS) } + + private var ringing: Job? = null + private var timeout: Job? = null + private var notificationId = RING_NOTIFICATION_ID + private var lastStartId: Int? = null + + /** The start the system would redeliver, so a takeover can mark it done. */ + private var ringStartId: Int? = null + + /** Whether the ring's players were ever built, so a stop-only service builds none. */ + private var rang = false + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + lastStartId = startId + if (intent?.action == ACTION_STOP) { + stop(intent) + return START_NOT_STICKY + } + val alert = intent?.let(ReminderActionReceiver::alertFrom) + if (intent == null || alert == null) { + stopIfIdle() + return START_NOT_STICKY + } + try { + return startRing(intent, alert, startId) + } finally { + // Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped. + if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert) + } + } + + private fun startRing(intent: Intent, alert: ReminderAlert, startId: Int): Int { + val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java) + if (notification == null) { + stopIfIdle() + return START_NOT_STICKY + } + val previous = alerts.ringing + // A different reminder posts under the other id, so it is a new + // notification whose full-screen intent opens; an update would not. + val replacing = previous != null && previous.key != alert.key + val shown = notificationId + if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID + val foreground = runCatching { startRingForeground(notificationId, notification) } + if (foreground.isFailure) { + // A restart after a process death may be refused a foreground start: + // the reminder still shows full-screen, sounding once. + Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull()) + notificationId = shown + handBack(alert, quiet = false) + stopIfIdle() + return START_NOT_STICKY + } + if (replacing) NotificationManagerCompat.from(this).cancel(shown) + // A duplicate start for this very ring leaves the original in charge of redelivery. + if (previous?.key == alert.key) return START_NOT_STICKY + // Only the newest start is redelivered after a process death; the older + // ones are done, so a handled reminder never rings again. + ringStartId?.let { stopSelfResult(it) } + ringStartId = startId + alerts.ringing = alert + if (previous != null) { + // Its screen closes either way; another occurrence goes back to the shade. + if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous) + } + val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) + ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis()) + return START_REDELIVER_INTENT + } + + override fun onDestroy() { + if (rang) releaseRing() + // Stopped from outside: its screen must not stay up for a ring that is gone. + alerts.ringing?.let { if (alerts.handBackOnDestroy) handBack(it) else alerts.markHandled(it) } + alerts.handBackOnDestroy = false + alerts.ringing = null + scope.cancel() + super.onDestroy() + } + + /** Rings for what is left of the ring's time, so a ring restarted after a process death does not begin again. */ + private fun ring(alert: ReminderAlert, remaining: Long) { + releaseRing() + rang = true + wakeLock.acquire() + timeout = scope.launch { + delay(remaining.coerceAtLeast(0L)) + giveUp() + } + ringing = scope.launch { + // Settings changed while this ring was on its way apply before it makes a sound. + val verdict = try { + withContext(Dispatchers.IO) { notifier.ringVerdict(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + RingVerdict.Ring + } + if (verdict != RingVerdict.Ring) { + // Never heard yet, so it alerts once in its new style. + if (verdict == RingVerdict.HandBack) handBack(alert, quiet = false) + end() + return@launch + } + sound(alert) + } + } + + /** + * Tone and vibration, paused for a phone call and back after it, until the + * user hides the ring's notification, which would leave no way to stop it. + */ + private suspend fun sound(alert: ReminderAlert) { + var sounding = false + var tick = 0 + while (true) { + if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !stillRings(alert)) { + handBack(alert) + end() + return + } + val inCall = isInCall() + if (inCall && sounding) { + tones.stop() + vibrator.stop() + sounding = false + } else if (!inCall && !sounding) { + vibrator.start() + tones.play(scope, ringSources()) + sounding = true + } + delay(CALL_CHECK_MILLIS) + } + } + + private suspend fun stillRings(alert: ReminderAlert): Boolean = try { + withContext(Dispatchers.IO) { notifier.canStillRing(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + true + } + + private fun stop(intent: Intent) { + val current = alerts.ringing + if (current != null && matchFrom(intent).matches(current)) { + if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current) + end() + } else { + stopIfIdle() + } + } + + /** Rung long enough: back to the shade quietly. */ + private fun giveUp() { + timeout = null + alerts.ringing?.let(::handBack) + end() + } + + /** Ends the ring, closes its screen, and stops the service unless a newer command is on its way. */ + private fun end() { + alerts.ringing?.let(alerts::markHandled) + releaseRing() + alerts.ringing = null + stopForeground(STOP_FOREGROUND_REMOVE) + stopIfIdle() + } + + /** Declines while a newer command is still on its way. */ + private fun stopIfIdle() { + if (alerts.ringing == null) lastStartId?.let { stopSelfResult(it) } + } + + /** + * [alert] back in the shade, in the app's scope so a service stopped + * meanwhile cannot cancel it, and its alert screen closed. A newer reminder + * for the occurrence that took its place meanwhile is left alone. + */ + private fun handBack(alert: ReminderAlert, quiet: Boolean = true) { + alerts.markHandled(alert) + appScope.launch { + try { + if (!notifier.isSuperseded(alert)) notifier.post(alert, quiet = quiet, ring = false) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + } + } + } + + private fun releaseRing() { + ringing?.cancel() + ringing = null + timeout?.cancel() + timeout = null + tones.stop() + vibrator.stop() + wakeLock.release() + } + + /** The device's alarm sound; "None", or none opening, leaves the vibration. */ + private fun ringSources() = listOfNotNull( + RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM), + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), + ) + + companion object { + private const val TAG = "ReminderRingService" + private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING" + private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP" + private const val EXTRA_NOTIFICATION = "notification" + private const val EXTRA_SINCE = "since" + private const val CALL_CHECK_MILLIS = 1_000L + + /** How many call checks between re-reading whether the ring's notification can still be seen. */ + private const val VISIBILITY_CHECK_TICKS = 5 + private const val EXTRA_MATCH_KIND = "match_kind" + private const val EXTRA_MATCH_VALUE = "match_value" + private const val EXTRA_HAND_BACK = "hand_back" + private const val WAKE_LOCK_TAG = "calendula:reminder-ring" + + /** Clear of the reminders' tagged id 1 and the backup notice's 2. */ + private const val RING_NOTIFICATION_ID = 171 + private const val OTHER_RING_NOTIFICATION_ID = 172 + + /** How long a reminder rings unanswered before it goes quiet. */ + const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000 + + /** + * Rings [alert] under [notification]. False when Android refused to + * start the service from where the reminder fired. + */ + fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean { + val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_RING) + .putAlert(alert) + .putExtra(EXTRA_NOTIFICATION, notification) + .putExtra(EXTRA_SINCE, System.currentTimeMillis()) + alerts.addPending(alert) + return try { + RingWakeLock.handOff(context, WAKE_LOCK_TAG) + context.startForegroundService(intent) + true + } catch (e: Exception) { + Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) + alerts.removePending(alert) + false + } + } + + /** + * Stops the ring if it is for a reminder [match]es, in order with the + * starts sent before it. [handBack] puts it back in the shade quietly. + * A command rather than `stopService`, which would also drop a start + * still on its way; sent while the ring's foreground service keeps the + * app allowed to. + */ + fun stop(context: Context, alerts: FullScreenAlerts, match: RingMatch, handBack: Boolean = false) { + val (kind, value) = when (match) { + is RingMatch.Key -> 0 to match.key + is RingMatch.Occurrence -> 1 to match.occurrenceKey + is RingMatch.Calendar -> 2 to match.calendarId + RingMatch.Any -> 3 to 0L + } + val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_STOP) + .putExtra(EXTRA_MATCH_KIND, kind) + .putExtra(EXTRA_MATCH_VALUE, value) + .putExtra(EXTRA_HAND_BACK, handBack) + try { + context.startService(intent) + } catch (e: Exception) { + Log.w(TAG, "Could not stop the ring", e) + // Refused from the background: nothing must ring on regardless, + // unless a start is still on its way, which this would crash. + if (!alerts.anyPending) { + alerts.handBackOnDestroy = handBack + context.stopService(Intent(context, ReminderRingService::class.java)) + } + } + } + + private fun matchFrom(intent: Intent): RingMatch { + val value = intent.getLongExtra(EXTRA_MATCH_VALUE, 0L) + return when (intent.getIntExtra(EXTRA_MATCH_KIND, 3)) { + 0 -> RingMatch.Key(value) + 1 -> RingMatch.Occurrence(value) + 2 -> RingMatch.Calendar(value) + else -> RingMatch.Any + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt new file mode 100644 index 00000000..850efaad --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt @@ -0,0 +1,43 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +/** How a calendar's reminders get the user's attention (#171). */ +enum class ReminderAlertStyle(val storageValue: String) { + /** An ordinary notification on the calendar's channel. */ + Notification("notification"), + + /** A full-screen alert that sounds the calendar's notification sound once and stays until handled. */ + FullScreen("full_screen"), + + /** A full-screen alert that rings and vibrates like an alarm until handled. */ + FullScreenRing("full_screen_ring"), + ; + + val isFullScreen: Boolean get() = this != Notification + + companion object { + fun fromStorage(value: String): ReminderAlertStyle? = entries.firstOrNull { it.storageValue == value } + } +} + +/** [calendarId]'s alert style; a calendar without one uses plain notifications. */ +fun Map.alertStyleFor(calendarId: Long): ReminderAlertStyle = + this[calendarId] ?: ReminderAlertStyle.Notification + +/** + * Parse `id=style` entries joined by `;`. Malformed entries and unknown styles + * are dropped, so a garbled value degrades to plain notifications. + */ +fun parseAlertStyles(stored: String?): Map = + stored?.split(";").orEmpty().mapNotNull { entry -> + val parts = entry.split("=") + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val style = ReminderAlertStyle.fromStorage(parts[1].trim()) ?: return@mapNotNull null + calendarId to style + }.toMap() + +/** The stored form of [parseAlertStyles]; plain-notification entries are left out. */ +fun Map.toStoredAlertStyles(): String = + entries.filter { it.value != ReminderAlertStyle.Notification } + .sortedBy { it.key } + .joinToString(";") { (id, style) -> "$id=${style.storageValue}" } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt new file mode 100644 index 00000000..e132b4d3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -0,0 +1,181 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import android.view.WindowManager +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.reminders.FullScreenAlerts +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.ReminderRingService +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme +import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache +import de.jeanlucmakiola.floret.di.IoDispatcher +import de.jeanlucmakiola.floret.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.isDark +import de.jeanlucmakiola.floret.prefs.isPureBlack +import de.jeanlucmakiola.floret.ring.showOverLockScreen +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * The full-screen reminder alert (#171), opened by the reminder's full-screen + * intent over the lock screen, or, for a ringing one, from its heads-up. + * It stays until the reminder is dismissed or snoozed — here, from the + * notification, or by the ring giving up — and back does not close it. + */ +@AndroidEntryPoint +class ReminderAlertActivity : ComponentActivity() { + + @Inject lateinit var notifier: ReminderNotifier + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var settingsPrefs: SettingsPrefs + @Inject lateinit var calendarDataSource: CalendarDataSource + + @Inject @IoDispatcher + lateinit var io: CoroutineDispatcher + + private var state by mutableStateOf(ReminderAlertUiState.Loading) + private var alert: ReminderAlert? = null + private var loading: Job? = null + private var screenOn: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + showOverLockScreen() + enableEdgeToEdge() + show(intent) + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + alerts.handled.collect { key -> if (key == alert?.key) finish() } + } + } + val cachedTheme = WindowThemeCache.read(this) ?: ThemeMode.SYSTEM + val cachedDynamicColor = WindowThemeCache.readDynamicColor(this) ?: true + setContent { + val themeMode by settingsPrefs.themeMode.collectAsStateWithLifecycle(cachedTheme) + val dynamicColor by settingsPrefs.dynamicColor.collectAsStateWithLifecycle(cachedDynamicColor) + val soften by settingsPrefs.softenCalendarColors.collectAsStateWithLifecycle(true) + CalendulaTheme( + darkTheme = themeMode.isDark(isSystemInDarkTheme()), + dynamicColor = dynamicColor, + pureBlack = themeMode.isPureBlack, + ) { + CompositionLocalProvider(LocalSoftenColors provides soften) { + BackHandler(enabled = true) { /* Handled by Dismiss or Snooze, not by leaving. */ } + when (val current = state) { + ReminderAlertUiState.Loading -> + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {} + is ReminderAlertUiState.Showing -> ReminderAlertScreen( + state = current, + onSnooze = { act(ReminderActionReceiver.ACTION_SNOOZE) }, + onDismiss = { act(ReminderActionReceiver.ACTION_DISMISS) }, + ) + } + } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + show(intent) + } + + /** Tapped from a stale notification, or handled while this window was away. */ + override fun onResume() { + super.onResume() + val current = alert + if (current != null && !notifier.isShowing(current)) finish() + } + + private fun show(intent: Intent) { + val next = ReminderActionReceiver.alertFrom(intent) + if (next == null) { + finish() + return + } + alert = next + // A ring still going, this one's or another's, keeps the screen up as long as it rings. + val ringing = alerts.ringing != null + keepScreenOn(if (ringing) ReminderRingService.RING_TIMEOUT_MILLIS else ONCE_SCREEN_ON_MILLIS) + loading?.cancel() + state = ReminderAlertUiState.Loading + loading = lifecycleScope.launch { + val calendar = try { + withContext(io) { calendarDataSource.calendars().firstOrNull { it.id == next.calendarId } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // The alert still shows, only without its calendar. + Log.w(TAG, "Could not read the calendar of event ${next.eventId}", e) + null + } + state = ReminderAlertUiState.Showing( + title = next.title, + time = notifier.timeText(next), + location = next.location?.takeIf { it.isNotBlank() }, + calendarName = calendar?.displayName, + calendarColor = calendar?.color, + ) + } + } + + /** An alert nobody answers lets the display sleep again; it stays on the lock screen. */ + private fun keepScreenOn(millis: Long) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + screenOn?.cancel() + screenOn = lifecycleScope.launch { + delay(millis) + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + + private fun act(action: String) { + val current = alert ?: return + sendBroadcast(ReminderActionReceiver.intent(this, action, current)) + finish() + } + + companion object { + private const val TAG = "ReminderAlertActivity" + private const val ONCE_SCREEN_ON_MILLIS = 60_000L + + fun intent(context: Context, alert: ReminderAlert): Intent = + Intent(context, ReminderAlertActivity::class.java) + .setData("calendula://reminder-alert/${alert.key}".toUri()) + .putAlert(alert) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt new file mode 100644 index 00000000..6cd8de1c --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt @@ -0,0 +1,195 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Event +import androidx.compose.material.icons.outlined.LocationOn +import androidx.compose.material.icons.outlined.Snooze +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.common.eventFill +import de.jeanlucmakiola.calendula.ui.common.eventInk +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.ring.RingBadge + +/** + * The alert itself, after the incoming-call screen: the calendar's pulsing + * badge, what and when in the middle, and the two ways out at the bottom, + * large enough to hit half awake. + */ +@Composable +internal fun ReminderAlertScreen( + state: ReminderAlertUiState.Showing, + onSnooze: () -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer) { + Column( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding() + .padding(horizontal = 24.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + // Centred, but scrolls rather than pushing the buttons off a short landscape screen. + BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + state.calendarName?.let { + Text( + text = it, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(24.dp)) + } + CalendarBadge(state.calendarColor) + Spacer(Modifier.size(32.dp)) + Text( + text = state.title.ifBlank { stringResource(R.string.event_untitled) }, + style = MaterialTheme.typography.displaySmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(12.dp)) + Text( + text = state.time, + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + state.location?.let { location -> + Spacer(Modifier.size(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.size(4.dp)) + Text( + text = location, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + Spacer(Modifier.size(24.dp)) + Column( + modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + AlertButton( + label = stringResource(R.string.reminder_action_dismiss), + icon = Icons.Rounded.Close, + tonal = false, + onClick = onDismiss, + modifier = Modifier.fillMaxWidth(), + ) + AlertButton( + label = stringResource(R.string.reminder_action_snooze), + icon = Icons.Outlined.Snooze, + tonal = true, + onClick = onSnooze, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +/** The calendar's colour as the badge fill, or the theme's primary container without one. */ +@Composable +private fun CalendarBadge(color: Int?) { + if (color == null) { + RingBadge(icon = Icons.Outlined.Event, size = 120.dp) + return + } + val fill = eventFill(color, LocalFloretDarkTheme.current, LocalSoftenColors.current) + RingBadge( + icon = Icons.Outlined.Event, + containerColor = fill, + contentColor = eventInk(fill, alpha = 1f), + size = 120.dp, + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun AlertButton( + label: String, + icon: ImageVector, + tonal: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val height = ButtonDefaults.LargeContainerHeight + val content: @Composable () -> Unit = { + Icon(icon, contentDescription = null, modifier = Modifier.size(ButtonDefaults.iconSizeFor(height))) + Spacer(Modifier.size(ButtonDefaults.iconSpacingFor(height))) + Text(label, style = ButtonDefaults.textStyleFor(height), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + val buttonModifier = modifier.heightIn(min = height) + val padding = ButtonDefaults.contentPaddingFor(height) + if (tonal) { + FilledTonalButton( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } else { + Button( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt new file mode 100644 index 00000000..8368a571 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt @@ -0,0 +1,16 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +sealed interface ReminderAlertUiState { + /** The calendar is still being read; the surface is already up. */ + data object Loading : ReminderAlertUiState + + data class Showing( + /** Raw title; blank shows as "(no title)". */ + val title: String, + val time: String, + val location: String?, + /** Null when the calendar could not be read. */ + val calendarName: String?, + val calendarColor: Int?, + ) : ReminderAlertUiState +} 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 ef670cad..22e79cc8 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 @@ -24,7 +24,10 @@ 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.data.reminders.RING_CHANNEL_ID import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker @@ -38,12 +41,15 @@ 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.OptionPicker 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 de.jeanlucmakiola.floret.ring.canUseFullScreenIntent +import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings import kotlinx.coroutines.launch /** @@ -63,6 +69,9 @@ internal fun CalendarRemindersScreen( val scope = rememberCoroutineScope() var expandedCalendars by rememberSaveable { mutableStateOf(emptyList()) } var overrideDialog by remember { mutableStateOf(null) } + var alertStylePicker by remember { mutableStateOf(null) } + var alertSoundPicker by remember { mutableStateOf(null) } + val canFullScreen = rememberCanUseFullScreenIntent() val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() val calendarIds = state.reminderCalendars.map { it.id } LifecycleResumeEffect(calendarIds) { @@ -84,13 +93,21 @@ internal fun CalendarRemindersScreen( calendars.forEachIndexed { index, calendar -> val expanded = calendar.id in expandedCalendars val notifying = calendar.id !in state.mutedReminderCalendarIds + val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds CalendarReminderEntry( calendar = calendar, state = state, position = positionOf(index, calendars.size), expanded = expanded, notifying = notifying, - blocked = notifying && calendar.id in channelStatus.blockedCalendarIds, + blocked = blocked, + heldBack = fullScreenHeldBack( + style = state.reminderAlertStyles.alertStyleFor(calendar.id), + notifying = notifying, + blocked = blocked, + ringBlocked = channelStatus.ringBlocked, + canFullScreen = canFullScreen, + ), onToggleExpand = { expandedCalendars = if (expanded) { expandedCalendars - calendar.id @@ -104,6 +121,10 @@ internal fun CalendarRemindersScreen( context.openNotificationSettings(viewModel.soundSettingsChannel(calendar.id)) } }, + onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) }, + onEditAlertStyle = { alertStylePicker = calendar.id }, + onEditAlertSound = { alertSoundPicker = calendar.id }, + onAllowFullScreen = { context.openFullScreenIntentSettings() }, onOpenSpecialDates = onOpenSpecialDates, onEditOverride = { overrideDialog = it }, ) @@ -111,6 +132,51 @@ internal fun CalendarRemindersScreen( } } + alertStylePicker?.let { calendarId -> + val current = state.reminderAlertStyles.alertStyleFor(calendarId) + OptionPicker( + title = stringResource(R.string.settings_alert_style), + options = listOf(ReminderAlertStyle.Notification, ReminderAlertStyle.FullScreen), + selected = if (current.isFullScreen) ReminderAlertStyle.FullScreen else ReminderAlertStyle.Notification, + label = { alertStyleLabel(it) }, + summary = { + stringResource( + if (it.isFullScreen) { + R.string.settings_alert_style_full_screen_summary + } else { + R.string.settings_alert_style_notification_summary + }, + ) + }, + onSelect = { picked -> + if (picked.isFullScreen != current.isFullScreen) { + viewModel.setCalendarAlertStyle(calendarId, picked) + // Guide the user straight to the switch Android 14+ may hold back. + if (picked.isFullScreen && !canFullScreen) context.openFullScreenIntentSettings() + } + }, + onDismiss = { alertStylePicker = null }, + ) + } + alertSoundPicker?.let { calendarId -> + OptionPicker( + title = stringResource(R.string.settings_alert_sound), + options = listOf(ReminderAlertStyle.FullScreen, ReminderAlertStyle.FullScreenRing), + selected = state.reminderAlertStyles.alertStyleFor(calendarId), + label = { alertSoundLabel(it) }, + summary = { + stringResource( + if (it == ReminderAlertStyle.FullScreenRing) { + R.string.settings_alert_sound_ring_summary + } else { + R.string.settings_alert_sound_once_summary + }, + ) + }, + onSelect = { viewModel.setCalendarAlertStyle(calendarId, it) }, + onDismiss = { alertSoundPicker = null }, + ) + } overrideDialog?.let { target -> val map = if (target.isAllDay) { state.perCalendarAllDayReminderOverride @@ -159,9 +225,14 @@ private fun CalendarReminderEntry( expanded: Boolean, notifying: Boolean, blocked: Boolean, + heldBack: FullScreenHeldBack, onToggleExpand: () -> Unit, onSetNotifying: (Boolean) -> Unit, onOpenSound: () -> Unit, + onOpenRingSettings: () -> Unit, + onEditAlertStyle: () -> Unit, + onEditAlertSound: () -> Unit, + onAllowFullScreen: () -> Unit, onOpenSpecialDates: () -> Unit, onEditOverride: (OverrideTarget) -> Unit, ) { @@ -172,6 +243,7 @@ private fun CalendarReminderEntry( summary = when { !notifying -> stringResource(R.string.settings_calendar_notifications_off) blocked -> stringResource(R.string.settings_notifications_blocked) + heldBack.any -> stringResource(R.string.settings_full_screen_held_back) else -> null }, position = when { @@ -190,6 +262,7 @@ private fun CalendarReminderEntry( ) { val managed = calendar.id in state.managedCalendarIds val takesOverrides = calendar.canModifyContents && !managed + val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id) val nested = MaterialTheme.colorScheme.surfaceContainerHighest // The options round off their calendar; mid-group they keep the row gap. Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) { @@ -203,16 +276,54 @@ private fun CalendarReminderEntry( ) 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) + summary = when { + blocked -> stringResource(R.string.settings_notifications_blocked_hint) + alertStyle == ReminderAlertStyle.FullScreenRing -> + stringResource(R.string.settings_calendar_notification_sound_ring_hint) + else -> stringResource(R.string.settings_calendar_notification_sound_hint) }, - position = if (managed || takesOverrides) Position.Middle else Position.Bottom, + position = Position.Middle, container = nested, trailing = { ExternalLinkIcon() }, onClick = onOpenSound, ) + val lastAlertRow = !(managed || takesOverrides) + GroupedRow( + title = stringResource(R.string.settings_alert_style), + summary = alertStyleLabel(alertStyle), + position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle, + container = nested, + onClick = onEditAlertStyle, + ) + if (alertStyle.isFullScreen) { + GroupedRow( + title = stringResource(R.string.settings_alert_sound), + summary = alertSoundLabel(alertStyle), + position = if (lastAlertRow && !heldBack.any) Position.Bottom else Position.Middle, + container = nested, + onClick = onEditAlertSound, + ) + } + if (heldBack.ring) { + GroupedRow( + title = stringResource(R.string.reminder_ring_channel_name), + summary = stringResource(R.string.settings_ring_blocked_hint), + position = if (lastAlertRow && !heldBack.permission) Position.Bottom else Position.Middle, + container = nested, + trailing = { ExternalLinkIcon() }, + onClick = onOpenRingSettings, + ) + } + if (heldBack.permission) { + GroupedRow( + title = stringResource(R.string.settings_full_screen_permission), + summary = stringResource(R.string.settings_full_screen_permission_hint), + position = if (lastAlertRow) Position.Bottom else Position.Middle, + container = nested, + trailing = { ExternalLinkIcon() }, + onClick = onAllowFullScreen, + ) + } if (managed) { GroupedRow( title = stringResource(R.string.settings_default_reminder_allday), @@ -290,3 +401,36 @@ private fun calendarOverrideSummary( ReminderOverride.None -> stringResource(R.string.reminder_none) is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) } + +/** What keeps a full-screen calendar from alerting as chosen: the missing permission, or the blocked ring channel. */ +private data class FullScreenHeldBack(val permission: Boolean, val ring: Boolean) { + val any: Boolean get() = permission || ring +} + +private fun fullScreenHeldBack( + style: ReminderAlertStyle, + notifying: Boolean, + blocked: Boolean, + ringBlocked: Boolean, + canFullScreen: Boolean, +): FullScreenHeldBack { + val live = notifying && !blocked + return FullScreenHeldBack( + permission = live && style.isFullScreen && !canFullScreen, + ring = live && style == ReminderAlertStyle.FullScreenRing && ringBlocked, + ) +} + +@Composable +private fun alertStyleLabel(style: ReminderAlertStyle): String = stringResource( + if (style.isFullScreen) R.string.settings_alert_style_full_screen else R.string.settings_alert_style_notification, +) + +@Composable +private fun alertSoundLabel(style: ReminderAlertStyle): String = stringResource( + if (style == ReminderAlertStyle.FullScreenRing) R.string.settings_alert_sound_ring else R.string.settings_alert_sound_once, +) + +/** Whether Android lets full-screen alerts open, re-read on every `ON_RESUME`. */ +@Composable +private fun rememberCanUseFullScreenIntent(): Boolean = rememberOnResume { it.canUseFullScreenIntent() } 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 b90b06c9..c3d027ff 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 @@ -22,7 +22,6 @@ 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 import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -34,10 +33,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.ui.common.DurationPicker @@ -51,6 +47,7 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow import de.jeanlucmakiola.floret.components.IconInfoCard +import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.reminders.ReminderOverride @@ -296,20 +293,18 @@ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) * `ON_RESUME` so a change made in system settings shows up at once. */ @Composable -private fun rememberBatteryOptimizationExempt(): Boolean { +private fun rememberBatteryOptimizationExempt(): Boolean = rememberOnResume(::isIgnoringBatteryOptimizations) + +/** [read], re-read on every `ON_RESUME` so a change made in system settings shows up at once. */ +@Composable +internal fun rememberOnResume(read: (Context) -> Boolean): Boolean { val context = LocalContext.current - var exempt by remember { mutableStateOf(isIgnoringBatteryOptimizations(context)) } - val lifecycleOwner = LocalLifecycleOwner.current - DisposableEffect(lifecycleOwner) { - val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_RESUME) { - exempt = isIgnoringBatteryOptimizations(context) - } - } - lifecycleOwner.lifecycle.addObserver(observer) - onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + var value by remember { mutableStateOf(read(context)) } + LifecycleResumeEffect(context) { + value = read(context) + onPauseOrDispose {} } - return exempt + return value } private fun isIgnoringBatteryOptimizations(context: Context): 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 34e603b3..12edff70 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.settings +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -102,6 +103,8 @@ data class SettingsUiState( val reminderCalendars: List = emptyList(), /** Calendars whose reminders Calendula doesn't post (#272). */ val mutedReminderCalendarIds: Set = emptySet(), + /** Per-calendar alert styles (#171); absent means a plain notification. */ + val reminderAlertStyles: Map = emptyMap(), /** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */ val notificationCategoryHintDismissed: Boolean = true, /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 21ff880b..4aaaa3a0 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 @@ -37,8 +37,11 @@ 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.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.RingMatch import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType @@ -75,6 +78,7 @@ class SettingsViewModel @Inject constructor( private val launcherNameManager: LauncherNameManager, private val reminderScanner: ReminderScanner, private val reminderChannels: ReminderChannels, + private val reminderNotifier: ReminderNotifier, @IoDispatcher private val io: CoroutineDispatcher, @ApplicationContext private val appContext: Context, ) : ViewModel() { @@ -136,6 +140,7 @@ class SettingsViewModel @Inject constructor( writableCalendars = calendars.filter { it.canModifyContents }, reminderCalendars = calendars, mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds], + reminderAlertStyles = this[SettingsKeys.reminderAlertStyles], notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed], allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], managedCalendarIds = specialDatesCalendars.values.toSet(), @@ -364,6 +369,7 @@ class SettingsViewModel @Inject constructor( fun setRemindersEnabled(enabled: Boolean) { viewModelScope.launch { prefs.setRemindersEnabled(enabled) + if (!enabled) reminderNotifier.stopRing(RingMatch.Any) reminderScanner.scan() } } @@ -377,10 +383,26 @@ class SettingsViewModel @Inject constructor( viewModelScope.launch { if (enabled) reminderScanner.scan() prefs.setCalendarRemindersEnabled(calendarId, enabled) + if (!enabled) reminderNotifier.stopRing(RingMatch.Calendar(calendarId)) reminderScanner.scan() } } + fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + viewModelScope.launch { + prefs.setCalendarAlertStyle(calendarId, style) + // Up front, so it can be checked in system settings before the first ring. + if (style == ReminderAlertStyle.FullScreenRing) { + onChannels { ensureRingChannel() } + refreshChannelStatus(state.value.reminderCalendars.map { it.id }) + } + // A ring for it goes quiet but stays in the shade. + if (style != ReminderAlertStyle.FullScreenRing) { + reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) + } + } + } + private val _channelStatus = MutableStateFlow(ReminderChannelStatus()) /** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */ @@ -410,7 +432,11 @@ class SettingsViewModel @Inject constructor( /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ suspend fun syncReminderChannels() { - onChannels { sync() } + val ringing = state.value.reminderAlertStyles.containsValue(ReminderAlertStyle.FullScreenRing) + onChannels { + sync() + if (ringing) ensureRingChannel() + } } private suspend fun onChannels(block: ReminderChannels.() -> T): T? = withContext(io) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8d182bf1..2371206a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -376,6 +376,8 @@ Not now Snooze Dismiss + Ringing reminders + Full-screen reminders that ring until you dismiss them. Calendula plays their sound itself. Today Tomorrow @@ -743,6 +745,21 @@ 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 + Alert style + Notification + A notification that pops up and waits in the shade + Full-screen alert + Fills the screen, even on the lock screen, until you dismiss or snooze it + Full-screen sound + Play sound once + This calendar\'s notification sound, once + Ring until dismissed + Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound + Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade. + Full-screen alerts held back + Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow + Allow full-screen alerts + Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them. Default (%1$s) Reliable delivery Android may delay reminders to save battery. Exempt Calendula so they arrive on time. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index 1e113689..beb7a63e 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 @@ -10,6 +10,7 @@ import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS @@ -614,6 +615,18 @@ class SettingsPrefsTest { assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L) } + @Test + fun `calendar alert styles default to notifications and persist per calendar`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.reminderAlertStyles.first()).isEmpty() + prefs.setCalendarAlertStyle(7L, ReminderAlertStyle.FullScreenRing) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.FullScreen) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.Notification) + assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing) + } + @Test fun `garbage per-calendar duration entries are dropped, the rest survive`( @TempDir tempDir: Path, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt index 4634644b..af4bb15e 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -145,6 +145,14 @@ class ReminderChannelPlanTest { assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L) } + @Test + fun `a switched-off ring channel is reported while the app may notify`() { + val ringOff = mapOf(RING_CHANNEL_ID to ReminderChannelState(blocked = true, groupId = null)) + assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, ringOff, emptySet()).ringBlocked).isTrue() + assertThat(reminderChannelStatus(listOf(1L), appEnabled = false, ringOff, emptySet()).ringBlocked).isFalse() + assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, emptyMap(), emptySet()).ringBlocked).isFalse() + } + private companion object { const val DESC = "Reminders" } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt new file mode 100644 index 00000000..17e9b0ec --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt @@ -0,0 +1,38 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ReminderAlertStyleTest { + + @Test + fun `styles round-trip through their stored form`() { + val styles = mapOf(9L to ReminderAlertStyle.FullScreenRing, 3L to ReminderAlertStyle.FullScreen) + + assertThat(parseAlertStyles(styles.toStoredAlertStyles())).isEqualTo(styles) + } + + @Test + fun `plain notifications are not stored`() { + val stored = mapOf(1L to ReminderAlertStyle.Notification, 2L to ReminderAlertStyle.FullScreen).toStoredAlertStyles() + + assertThat(stored).isEqualTo("2=full_screen") + } + + @Test + fun `garbled entries are dropped, the rest survive`() { + assertThat(parseAlertStyles("x=full_screen;4=loud;5;6=full_screen_ring")) + .containsExactly(6L, ReminderAlertStyle.FullScreenRing) + assertThat(parseAlertStyles(null)).isEmpty() + } + + @Test + fun `a calendar without a style uses notifications`() { + val styles = mapOf(1L to ReminderAlertStyle.FullScreen) + + assertThat(styles.alertStyleFor(1L)).isEqualTo(ReminderAlertStyle.FullScreen) + assertThat(styles.alertStyleFor(2L)).isEqualTo(ReminderAlertStyle.Notification) + assertThat(ReminderAlertStyle.Notification.isFullScreen).isFalse() + assertThat(ReminderAlertStyle.FullScreenRing.isFullScreen).isTrue() + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8f0a77ba..869d7d71 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -411,6 +411,32 @@ 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. +**Full-screen alerts (#171).** Settings → Notifications gives each calendar an +alert style (`SettingsPrefs.reminderAlertStyles`): a plain notification, a +full-screen alert that sounds once, or one that rings until handled. Only +`ReminderNotifier.post` reads it, and `ReminderChannels.channelFor(id, style)` +picks the channel. "Sound once" stays on the calendar's own channel, so its +sound is still the one chosen in system settings, and adds a full-screen intent +to `ReminderAlertActivity`. "Ring" starts `ReminderRingService`, which goes +foreground on the shared silent `reminders_ring` channel and loops the alarm +sound with vibration through floret-kit's `ring` module — the same player +Clockula's alarms use. One reminder rings at a time; a newer one takes over and +hands the older back to the shade quietly, as does a ring left unanswered for +ten minutes, and switching the calendar away from ringing. Dismiss and Snooze, +from the screen, the notification or a swipe, all go through +`ReminderActionReceiver`, so the ring stops and the screen closes +(`FullScreenAlerts`) however the reminder was handled. Starts and stops reach +the service as commands, so a dismiss sent while a newer ring is on its way +applies in order rather than killing it, and the service re-reads the settings +once a ring arrives, so a style change or mute that raced a scan still wins. A +blocked calendar, account group or ring channel never rings (Settings flags a +blocked ring channel next to each ringing calendar, beside #145's blocked status), the tone pauses +for a phone call, and a ring restarted after a process death only rings out +what was left of its ten minutes. When Android 14+ +withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a +heads-up; Settings shows a row leading to the system switch. When Android +refuses the ring service, the reminder falls back to sounding once. + 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/docs/PRIVACY.md b/docs/PRIVACY.md index adfd8a34..e542cedb 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -96,9 +96,8 @@ The settings screen contains links to the source code, the licence, the issue tr - `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing. - `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart. - `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting. -- `WAKE_LOCK`, `FOREGROUND_SERVICE`, `ACCESS_NETWORK_STATE`: required by the Android system component used for scheduled background work (WorkManager). - -`ACCESS_NETWORK_STATE` allows reading *whether* a network connection exists. It does **not** permit using one. Without `INTERNET`, no connection is possible. +- `USE_FULL_SCREEN_INTENT`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`, `VIBRATE`: for calendars you set to full-screen alerts — showing the alert over the lock screen and, with “Ring until dismissed”, ringing and vibrating until you dismiss or snooze it. +- `WAKE_LOCK`: keeps the phone awake while a full-screen alert rings, and lets the Android component that runs scheduled background work (WorkManager) finish it. ## 7. Distribution channels