Compare commits

..
Author SHA1 Message Date
makiolaj ed72920da1 fix(#171): stack the alert's large buttons so their labels fit 2026-11-16 19:31:48 +01:00
makiolaj 84acc33bd6 Merge feat/145-per-calendar-notifications into feat/171-fullscreen-alerts 2026-11-16 19:21:54 +01:00
makiolaj f181ae7ac9 fix(#171): merge review - ring channel up front, held-back status in the calendar header, silenced calendars stop a live ring 2026-11-14 03:10:20 +01:00
makiolaj 04f3b7ec8f Merge feat/145-per-calendar-notifications into feat/171-fullscreen-alerts 2026-11-14 03:04:24 +01:00
makiolaj 7361e8d98e fix(#171): review round 6 - mark the redeliverable start done on takeover 2026-11-13 18:18:04 +01:00
makiolaj 9178828b41 fix(#171): review round 5 - hand back on a hidden ring, counted pending starts, keep the first start's redelivery 2026-11-13 18:13:27 +01:00
makiolaj 0b6cdf992e fix(#171): review round 4 - targeted ring stops, verdict before any sound, stop when the ring notification is hidden, no re-ring of a handed-back reminder 2026-11-13 18:06:17 +01:00
makiolaj 014d31f9b9 fix(#171): review round 3 - re-check settings in the ring, follow calls, anchored timeout, close the screen on every stop 2026-11-13 17:56:11 +01:00
makiolaj 4287862f47 chore(#171): floret-kit ring fixes 2026-11-13 17:45:25 +01:00
makiolaj 6cf6a6fdbf fix(#171): review round 2 - ordered ring commands, hand-back that outlives the service, in-call and blocked-group checks, scrolling alert screen 2026-11-13 17:33:26 +01:00
makiolaj d2b6637f72 chore(#171): floret-kit ring review fixes 2026-11-13 17:20:13 +01:00
makiolaj 0b223f53fc fix(#171): review round 1 - ring ids, hand-back off the main thread, blocked channels, closing the alert screen 2026-11-13 17:12:03 +01:00
makiolaj c52c6c54cc feat(#171): full-screen reminder alerts per calendar 2026-11-13 17:00:46 +01:00
46 changed files with 1497 additions and 1947 deletions

No files matched your search

+1
View File
@@ -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)
+22 -3
View File
@@ -41,10 +41,15 @@
-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
<!-- WorkManager declares this for network constraints, which the app doesn't use (#448). -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove" />
<!-- Full-screen reminder alerts and their ring (#171), opt-in per calendar. -->
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
returns null and the calendar manager's per-account "manage" button can't
@@ -322,6 +327,20 @@
android:name=".data.reminders.ReminderActionReceiver"
android:exported="false" />
<!-- The full-screen reminder alert (#171), in a task of its own. -->
<activity
android:name=".ui.reminders.ReminderAlertActivity"
android:exported="false"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:taskAffinity="" />
<!-- Rings a "Ring until dismissed" reminder (#171). -->
<service
android:name=".data.reminders.ReminderRingService"
android:exported="false"
android:foregroundServiceType="systemExempted" />
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
<activity
android:name=".widget.config.WidgetConfigActivity"
@@ -67,10 +67,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant
@@ -623,20 +620,6 @@ class MainActivity : AppCompatActivity() {
putExtra(EXTRA_SOURCE_VIEW, source.name)
}
/**
* Open the day view on [date] over the default home view — the daily
* summary's tap (#459). Spoken as the system's own "view time" intent,
* at the day's local noon, so it lands on the path a clock tap takes.
*/
fun openDayIntent(context: Context, date: LocalDate): Intent {
val noon = LocalDateTime(date, LocalTime(12, 0))
.toInstant(TimeZone.currentSystemDefault())
.toEpochMilliseconds()
return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri())
.setClass(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
/** Open the create-event form prefilled for [date] (home-screen widgets). */
fun openCreateIntent(context: Context, date: LocalDate): Intent =
Intent(context, MainActivity::class.java).apply {
@@ -35,7 +35,6 @@ import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
import de.jeanlucmakiola.calendula.domain.toEditForm
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toJavaLocalDate
@@ -920,15 +919,11 @@ class AndroidCalendarDataSource @Inject constructor(
minutes
}
/**
* [form]'s reminders as the distinct raw provider offsets to store, its
* fixed-time ones (#459) measured from the start it is saved with.
*/
/** [form]'s reminders as the distinct raw provider offsets to store. */
private fun encodedReminders(form: EventForm, allDayReminderTimeMinutes: Int): List<Int> =
(
form.reminders.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) } +
form.fixedReminderOffsets(TimeZone.currentSystemDefault())
).distinct()
form.reminders
.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) }
.distinct()
override fun insertEvent(form: EventForm, allDayReminderTimeMinutes: Int): Long {
// A globally-unique UID so a later .ics backup/restore can identify
@@ -1031,11 +1026,7 @@ class AndroidCalendarDataSource @Inject constructor(
// Untouched reminder sets are left alone so unrelated edits can't
// disturb provider rows the form never knew about. The diff is on the
// form's semantic minutes; reconcile works in encoded provider minutes.
// A fixed-time reminder also changes when the start's day or time does.
val zone = TimeZone.currentSystemDefault()
if (updated.reminders.toSet() != original.reminders.toSet() ||
updated.fixedReminderOffsets(zone).toSet() != original.fixedReminderOffsets(zone).toSet()
) {
if (updated.reminders.toSet() != original.reminders.toSet()) {
reconcileReminders(eventId, encodedReminders(updated, allDayReminderTimeMinutes))
}
// Same untouched-set guard for guests: only reconcile when the form's
@@ -1236,9 +1227,8 @@ class AndroidCalendarDataSource @Inject constructor(
)
}
// Whether the provider copied the parent's reminder rows is its
// business — reconciling against the actual rows handles both ways. The
// exception is a one-off, so a fixed-time reminder takes real minutes.
reconcileReminders(exceptionId, encodedReminders(form.toDetachedOccurrence(), allDayReminderTimeMinutes))
// business — reconciling against the actual rows handles both ways.
reconcileReminders(exceptionId, encodedReminders(form, allDayReminderTimeMinutes))
reconcileAttendees(exceptionId, form.attendees)
return exceptionId
}
@@ -4,8 +4,6 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.floret.prefs.PrefStore
import de.jeanlucmakiola.floret.prefs.nullableLongPref
import de.jeanlucmakiola.floret.prefs.nullableStringPref
import java.time.LocalDate
import javax.inject.Inject
import javax.inject.Singleton
@@ -29,20 +27,7 @@ class ReminderStatePrefs @Inject constructor(
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
/**
* The day the last daily summary listed (#459): recorded at once, so neither
* a pass failing after posting nor a later time picked the same evening
* lists it twice.
*/
suspend fun lastDigestDay(): LocalDate? =
prefs.get(LAST_DIGEST_DAY)?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
suspend fun setLastDigestDay(day: LocalDate) = prefs.set(LAST_DIGEST_DAY, day.toString())
suspend fun clearLastDigestDay() = prefs.set(LAST_DIGEST_DAY, null)
private companion object {
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
val LAST_DIGEST_DAY = nullableStringPref("reminder_last_digest_day")
}
}
@@ -1,15 +1,13 @@
package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
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.DEFAULT_DIGEST_TIME_MINUTES
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
import de.jeanlucmakiola.calendula.domain.reminders.parseAlertStyles
import de.jeanlucmakiola.calendula.domain.reminders.toStoredAlertStyles
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.storageValue
@@ -172,6 +170,7 @@ class SettingsPrefs @Inject constructor(
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
val mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
val reminderAlertStyles: Flow<Map<Long, ReminderAlertStyle>> = prefs.flow(SettingsKeys.reminderAlertStyles)
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
@@ -183,20 +182,6 @@ class SettingsPrefs @Inject constructor(
prefs.flow(SettingsKeys.perCalendarReminderOverride)
val perCalendarAllDayReminderOverride: Flow<Map<Long, List<Int>>> =
prefs.flow(SettingsKeys.perCalendarAllDayReminderOverride)
val defaultFixedTimeReminder: Flow<FixedTimeReminder?> = prefs.flow(SettingsKeys.defaultFixedTimeReminder)
val perCalendarFixedTimeReminderOverride: Flow<Map<Long, FixedTimeReminder?>> =
prefs.flow(SettingsKeys.perCalendarFixedTimeReminderOverride)
/**
* Every "N days before at HH:MM" the defaults name, so an offset landing on
* one reads back as that reminder rather than a lead time (#459).
*/
val knownFixedTimeReminders: Flow<Set<FixedTimeReminder>> = prefs.snapshot {
setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() +
it[SettingsKeys.recentFixedTimeReminders]
}
val dailyDigest: Flow<DailyDigestSettings> = prefs.snapshot { it.dailyDigest }
val autoBackupEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupEnabled)
val autoBackupIntervalMinutes: Flow<Long> = prefs.flow(SettingsKeys.autoBackupIntervalMinutes)
val autoBackupFolderUri: Flow<String?> = prefs.flow(SettingsKeys.autoBackupFolderUri)
@@ -300,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)
@@ -351,77 +340,6 @@ class SettingsPrefs @Inject constructor(
suspend fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) =
prefs.applyOverride(SettingsKeys.perCalendarAllDayReminderOverride, calendarId, override)
/** The replaced default stays a known pattern, so events that got it keep reading as it. */
suspend fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) {
prefs.edit {
val old = it[SettingsKeys.defaultFixedTimeReminder]
if (old != reminder) retireFixedTimeReminder(it, old)
it[SettingsKeys.defaultFixedTimeReminder] = reminder
}
}
/** [override] [FixedTimeOverride.Inherit] drops the calendar's entry; a replaced value stays known. */
suspend fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) {
prefs.edit {
val current = it[SettingsKeys.perCalendarFixedTimeReminderOverride]
val old = current[calendarId]
if (old != (override as? FixedTimeOverride.At)?.reminder) retireFixedTimeReminder(it, old)
it[SettingsKeys.perCalendarFixedTimeReminderOverride] = when (override) {
FixedTimeOverride.Inherit -> current - calendarId
FixedTimeOverride.Off -> current + (calendarId to null)
is FixedTimeOverride.At -> current + (calendarId to override.reminder)
}
}
}
/**
* Remember fixed-time reminders saved by hand (#459), so their rows read
* back as them; the defaults are known anyway and take no slot.
*/
suspend fun rememberFixedTimeReminders(reminders: Collection<FixedTimeReminder>) {
prefs.edit {
val defaults = setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
val fresh = reminders.filterNot { reminder -> reminder in defaults }
if (fresh.isNotEmpty()) {
it[SettingsKeys.recentFixedTimeReminders] = (fresh + it[SettingsKeys.recentFixedTimeReminders]).distinct()
}
}
}
/** Keep a default being replaced known, unless it still is a default elsewhere. */
private fun retireFixedTimeReminder(preferences: MutablePreferences, reminder: FixedTimeReminder?) {
if (reminder == null) return
val defaults = listOfNotNull(preferences[SettingsKeys.defaultFixedTimeReminder]) +
preferences[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
if (defaults.count { it == reminder } > 1) return
preferences[SettingsKeys.recentFixedTimeReminders] =
(listOf(reminder) + preferences[SettingsKeys.recentFixedTimeReminders]).distinct()
}
suspend fun setDailyDigestEnabled(enabled: Boolean) = editDigest { it[SettingsKeys.dailyDigestEnabled] = enabled }
suspend fun setDailyDigestTimeMinutes(minutesOfDay: Int) =
editDigest { it[SettingsKeys.dailyDigestTimeMinutes] = minutesOfDay }
suspend fun setDailyDigestDay(day: DigestDay) = editDigest { it[SettingsKeys.dailyDigestDay] = day }
/**
* Change when the summary arrives, stamping the moment: a summary whose time
* had already passed today is not owed by the change itself.
*/
private suspend fun editDigest(change: (MutablePreferences) -> Unit) {
prefs.edit {
change(it)
it[SettingsKeys.dailyDigestArmedAt] = System.currentTimeMillis()
}
}
suspend fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) {
prefs.update(SettingsKeys.digestExcludedCalendarIds) { if (included) it - calendarId else it + calendarId }
}
suspend fun setAutoBackupEnabled(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupEnabled, enabled)
suspend fun setAutoBackupIntervalMinutes(minutes: Long) =
@@ -471,7 +389,6 @@ class SettingsPrefs @Inject constructor(
/** 09:00 as minutes from midnight; the default all-day reminder fire time. */
internal const val DEFAULT_ALLDAY_REMINDER_TIME = 540
internal const val MINUTES_PER_DAY = 1_440
internal const val MAX_RECENT_FIXED_TIME_REMINDERS = 12
/** Default snooze delay for the notification "Snooze" action. */
const val DEFAULT_SNOOZE_MINUTES = 10
const val DEFAULT_MULTI_DAY_COUNT = 3
@@ -699,6 +616,10 @@ object SettingsKeys {
*/
val mutedReminderCalendarIds: Pref<Set<Long>> = idSetPref("muted_reminder_calendar_ids")
/** Per-calendar alert styles (#171); a calendar absent from the map uses plain notifications. */
val reminderAlertStyles: Pref<Map<Long, ReminderAlertStyle>> =
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).
@@ -794,48 +715,6 @@ object SettingsKeys {
val perCalendarAllDayReminderOverride: Pref<Map<Long, List<Int>>> =
reminderOverridePref("per_calendar_allday_reminder_override")
/**
* The "N days before at HH:MM" reminder added to new **timed** events
* (#459), or null for none — the factory default. Stored as `days@minute`.
*/
val defaultFixedTimeReminder: Pref<FixedTimeReminder?> =
nullableStringPref("default_fixed_time_reminder").map(FixedTimeReminder::parse) { it?.toToken() }
/**
* Per-calendar overrides of [defaultFixedTimeReminder]: present with a
* value replaces it, present as null turns it off, absent inherits.
* Serialised as `id=days@minute` or `id=none`, joined by `;`.
*/
val perCalendarFixedTimeReminderOverride: Pref<Map<Long, FixedTimeReminder?>> =
nullableStringPref("per_calendar_fixed_time_reminder").map(::parseFixedTimeOverrides) {
it.toStoredFixedTimeOverrides()
}
/** The daily summary notification (#459): opt-in, and which day it lists at what time. */
val dailyDigestEnabled: Pref<Boolean> = booleanPref("daily_digest_enabled", false)
val dailyDigestTimeMinutes: Pref<Int> =
intPref("daily_digest_time_minutes", DEFAULT_DIGEST_TIME_MINUTES).coerced {
it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1)
}
val dailyDigestDay: Pref<DigestDay> = enumPref("daily_digest_day", DigestDay.Tomorrow)
/** Calendars left out of the daily summary; every other one is in. */
val digestExcludedCalendarIds: Pref<Set<Long>> = idSetPref("digest_excluded_calendar_ids")
/** When the summary's switch, time or day last changed; a moment before it is never owed. */
val dailyDigestArmedAt: Pref<Long> = longPref("daily_digest_armed_at", 0L)
/**
* Fixed-time reminders last saved by hand, and defaults since replaced,
* newest first — with the current defaults, the patterns a stored offset is
* recognised as. Capped, so the oldest falls out of recognition.
*/
val recentFixedTimeReminders: Pref<List<FixedTimeReminder>> =
nullableStringPref("recent_fixed_time_reminders").map(
{ stored -> stored?.split(LIST_SEP).orEmpty().mapNotNull(FixedTimeReminder::parse).distinct() },
{ reminders -> reminders.take(SettingsPrefs.MAX_RECENT_FIXED_TIME_REMINDERS).joinToString(LIST_SEP) { it.toToken() } },
)
/** Whether periodic automatic `.ics` export of local calendars is on (issue #8). */
val autoBackupEnabled: Pref<Boolean> = booleanPref("auto_backup_enabled", false)
@@ -1032,57 +911,6 @@ data class BackupStatus(
val consecutiveFailures: Int,
)
/** The daily summary's settings, read together. */
internal val Preferences.dailyDigest: DailyDigestSettings
get() = DailyDigestSettings(
enabled = this[SettingsKeys.dailyDigestEnabled],
timeMinutes = this[SettingsKeys.dailyDigestTimeMinutes],
day = this[SettingsKeys.dailyDigestDay],
excludedCalendarIds = this[SettingsKeys.digestExcludedCalendarIds],
armedAtMillis = this[SettingsKeys.dailyDigestArmedAt],
)
/** A calendar's choice for the fixed-time default, as a picker returns it. */
sealed interface FixedTimeOverride {
data object Inherit : FixedTimeOverride
data object Off : FixedTimeOverride
data class At(val reminder: FixedTimeReminder) : FixedTimeOverride
}
/** [calendarId]'s entry read as a [FixedTimeOverride]. */
fun Map<Long, FixedTimeReminder?>.fixedTimeOverrideFor(calendarId: Long): FixedTimeOverride = when {
!containsKey(calendarId) -> FixedTimeOverride.Inherit
else -> getValue(calendarId)?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off
}
/** The fixed-time reminder a new timed event on [calendarId] gets, or null for none. */
fun resolveDefaultFixedTimeReminder(
global: FixedTimeReminder?,
overrides: Map<Long, FixedTimeReminder?>,
calendarId: Long?,
): FixedTimeReminder? =
if (calendarId != null && overrides.containsKey(calendarId)) overrides[calendarId] else global
private fun parseFixedTimeOverrides(stored: String?): Map<Long, FixedTimeReminder?> =
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
val parts = entry.split(KEY_VALUE_SEP)
if (parts.size != 2) return@mapNotNull null
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
val value = parts[1].trim()
if (value == NONE) return@mapNotNull calendarId to null
val reminder = FixedTimeReminder.parse(value) ?: return@mapNotNull null
calendarId to reminder
}.toMap()
private fun Map<Long, FixedTimeReminder?>.toStoredFixedTimeOverrides(): String? =
if (isEmpty()) {
null
} else {
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, reminder) ->
"$id$KEY_VALUE_SEP${reminder?.toToken() ?: NONE}"
}
}
/**
* The lead times to prefill on a new event: the matching per-calendar override
* if [calendarId] has one for this event kind, otherwise the global default for
@@ -1,157 +0,0 @@
package de.jeanlucmakiola.calendula.data.reminders
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R
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.ReminderEventInstance
import kotlinx.coroutines.flow.first
import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.toKotlinLocalDate
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
/**
* Posts the daily summary (#459): one notification listing a day's events, on
* its own channel, replacing the one before it. Tapping opens that day.
*/
@Singleton
class DailyDigestNotifier @Inject constructor(
@ApplicationContext private val context: Context,
private val settingsPrefs: SettingsPrefs,
) {
/**
* Post the summary of [day] listing [listed], or withdraw the last one when
* there is nothing to list — yesterday's would otherwise stand in for it.
*/
suspend fun post(day: LocalDate, listed: List<ReminderEventInstance>) {
val manager = NotificationManagerCompat.from(context)
if (listed.isEmpty()) {
manager.cancel(TAG_DIGEST, NOTIFICATION_ID)
return
}
ensureChannel()
val zone = ZoneId.systemDefault()
val locale = Locale.getDefault()
val is24Hour = settingsPrefs.timeFormat.first()
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
val today = LocalDate.now(zone)
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
// The date rides along: the summary stays up into the day it lists,
// when "Tomorrow" alone would point at the wrong one.
val date = DateTimeFormatter.ofPattern(
android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEdMMM"),
locale,
).format(day)
val dayLabel = when (day) {
today -> context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_today), date)
today.plusDays(1) ->
context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_tomorrow), date)
else -> date
}
val allDay = context.getString(R.string.event_detail_all_day)
val lines = listed.map { entry ->
// Read against the listed day, so a timed event on it shows its bare
// range and one crossing midnight its dates.
val time = if (entry.isAllDay) allDay else reminderTimeText(
beginMillis = entry.beginMillis,
endMillis = entry.endMillis,
isAllDay = entry.isAllDay,
zone = zone,
locale = locale,
is24Hour = is24Hour,
today = day,
firstDayOfWeek = firstDayOfWeek,
todayLabel = allDay,
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
)
context.getString(R.string.digest_line, time, entry.title.ifBlank { context.getString(R.string.event_untitled) })
}
val title = context.resources.getQuantityString(R.plurals.digest_title, listed.size, dayLabel, listed.size)
val style = NotificationCompat.InboxStyle().setBigContentTitle(title)
lines.take(MAX_LINES).forEach(style::addLine)
if (lines.size > MAX_LINES) {
val more = lines.size - MAX_LINES
style.setSummaryText(context.resources.getQuantityString(R.plurals.digest_more, more, more))
}
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(listed.joinToString(", ") { it.title.ifBlank { context.getString(R.string.event_untitled) } })
.setStyle(style)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
// Gone once its day is over; "Tomorrow" would read wrong by then anyway.
.setTimeoutAfter(
(day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - System.currentTimeMillis())
.coerceAtLeast(1L),
)
.setContentIntent(openDay(day))
.build()
try {
manager.notify(TAG_DIGEST, NOTIFICATION_ID, notification)
} catch (e: SecurityException) {
Log.w(TAG, "Could not post the daily summary", e)
}
}
/** Whether the summary's own channel is switched off in the system settings. */
fun isChannelOff(): Boolean =
context.getSystemService(NotificationManager::class.java)
.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
/** Withdraw the summary showing, if any. */
fun cancel() {
NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID)
}
/** The summary's channel id, created if missing — for the settings deep-link. */
fun channelId(): String {
ensureChannel()
return CHANNEL_ID
}
/** Creates the channel, or renames it after a language change; the user's settings on it stay. */
private fun ensureChannel() {
val manager = context.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(
CHANNEL_ID,
context.getString(R.string.digest_channel_name),
NotificationManager.IMPORTANCE_DEFAULT,
).apply { description = context.getString(R.string.digest_channel_description) },
)
}
private fun openDay(day: LocalDate): PendingIntent = PendingIntent.getActivity(
context,
REQUEST_CODE,
MainActivity.openDayIntent(context, day.toKotlinLocalDate()),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
private companion object {
const val TAG = "DailyDigestNotifier"
const val CHANNEL_ID = "daily_digest"
const val TAG_DIGEST = "daily_digest"
const val NOTIFICATION_ID = 2
const val REQUEST_CODE = 0xD16E
const val MAX_LINES = 6
}
}
@@ -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<Long, Pair<ReminderAlert, Int>>()
/** 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<Long>(
extraBufferCapacity = 8,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
/** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */
val handled: SharedFlow<Long> = 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
}
}
@@ -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),
@@ -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<Long> = emptySet(),
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
val groupBlockedCalendarIds: Set<Long> = 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,
)
}
@@ -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
@@ -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.
@@ -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
}
}
}
}
@@ -6,13 +6,9 @@ import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.digestEntries
import de.jeanlucmakiola.calendula.domain.reminders.planReminders
import de.jeanlucmakiola.calendula.domain.reminders.scheduleDigest
import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon
import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark
import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders
@@ -47,12 +43,10 @@ class ReminderScanner @Inject constructor(
private val source: ReminderInstanceSource,
private val calendarDataSource: CalendarDataSource,
private val notifier: ReminderNotifier,
private val digestNotifier: DailyDigestNotifier,
private val channels: ReminderChannels,
private val snoozes: ReminderSnoozeScheduler,
private val alarms: ReminderAlarmScheduler,
private val state: ReminderStatePrefs,
private val calendarPrefs: CalendarPrefs,
private val settingsPrefs: SettingsPrefs,
@IoDispatcher private val io: kotlinx.coroutines.CoroutineDispatcher,
) {
@@ -84,29 +78,14 @@ class ReminderScanner @Inject constructor(
val now = System.currentTimeMillis()
if (!hasReadCalendar()) return
val lastFired = reminderWatermark(state.lastScanMillis(), now)
val horizon = now + MAX_ALARM_INTERVAL_MILLIS
val digestSettings = settingsPrefs.dailyDigest.first()
val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null
val nextReminder = try {
if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
} catch (e: Exception) {
// The watermark stays, so the next pass owes these reminders again;
// keep that pass, and the summary's next moment, armed.
alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS))
throw e
if (!settingsPrefs.remindersEnabled.first()) {
// Reminders off: drop the wake-up, but keep the watermark moving
// so switching them back on doesn't replay the backlog.
alarms.cancelScan()
state.setLastScanMillis(now)
return
}
// Advance even when nothing could be posted, so muting notifications
// doesn't build a backlog — and while both are off, so switching one
// back on doesn't replay it.
state.setLastScanMillis(now)
val next = listOfNotNull(nextReminder, nextDigest).minOrNull()
if (next == null) alarms.cancelScan() else alarms.scheduleScan(minOf(next, horizon))
}
/** Post the event reminders that are due; returns the next wake-up they need. */
private suspend fun reminders(lastFired: Long, now: Long, horizon: Long): Long {
syncChannels()
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
// Reach into the past too: an all-day "at time of event" encodes to a
@@ -125,9 +104,9 @@ class ReminderScanner @Inject constructor(
val schedule = scheduleReminders(
planned = planned,
lastFiredMillis = lastFired,
lastFiredMillis = reminderWatermark(state.lastScanMillis(), now),
nowMillis = now,
horizonMillis = horizon,
horizonMillis = now + MAX_ALARM_INTERVAL_MILLIS,
)
if (notifier.canPost()) {
@@ -137,48 +116,10 @@ class ReminderScanner @Inject constructor(
notifier.post(alert)
}
}
return schedule.nextAlarmMillis
}
/**
* Post the daily summary if it is owed (#459); returns its next moment. It
* leaves out calendars excluded from it, not those muted for reminders —
* a calendar too noisy to ping per event can still belong in the overview.
*/
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
val zone = ZoneId.systemDefault()
val listed = try {
state.lastDigestDay()
} catch (e: Exception) {
Log.w(TAG, "Could not read the last daily summary", e)
null
}
val schedule = scheduleDigest(
timeMinutes = settings.timeMinutes,
day = settings.day,
zone = zone,
// A moment that passed before the summary was last changed is not owed.
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
nowMillis = now,
lastListedDay = listed,
)
val day = schedule.dueDay
// A blocked channel would swallow it; the day stays owed until allowed.
if (day != null && notifier.canPost() && !digestNotifier.isChannelOff()) {
// A failed summary must not cost the event reminders this pass owes.
try {
// A day either side: all-day occurrences sit at UTC midnight, which
// can fall outside the local day they stand for.
val from = day.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli()
val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first()
digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left))
state.setLastDigestDay(day)
} catch (e: Exception) {
Log.w(TAG, "Daily summary failed", e)
}
}
return schedule.nextAlarmMillis
// Advance even when nothing could be posted, so muting notifications
// doesn't build a backlog.
state.setLastScanMillis(now)
alarms.scheduleScan(schedule.nextAlarmMillis)
}
/**
@@ -235,8 +176,5 @@ class ReminderScanner @Inject constructor(
const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000
const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L
/** How soon a pass whose reminders failed is tried again. */
const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000
}
}
@@ -1,7 +1,5 @@
package de.jeanlucmakiola.calendula.domain
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
@@ -42,12 +40,6 @@ data class EventForm(
val description: String = "",
/** Reminder lead times in minutes before the start, deduplicated. */
val reminders: List<Int> = emptyList(),
/**
* "N days before at HH:MM" reminders of a timed event (#459), written as lead
* times measured from [start] at save time. Ignored while [isAllDay], so a
* round trip through all-day keeps them.
*/
val fixedReminders: List<FixedTimeReminder> = emptyList(),
val availability: Availability = Availability.Busy,
val accessLevel: AccessLevel = AccessLevel.Default,
/** Confirmed / Tentative / Cancelled (#388). */
@@ -294,7 +286,7 @@ fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
if (location.isNotBlank()) add(EventFormField.Location)
if (description.isNotBlank()) add(EventFormField.Description)
if (timezone != null) add(EventFormField.Timezone)
if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders)
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
if (rrule != null) add(EventFormField.Recurrence)
if (availability != Availability.Busy) add(EventFormField.Availability)
if (status != EventStatus.Confirmed) add(EventFormField.Status)
@@ -332,37 +324,13 @@ fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
* cleared so the create resolves to a writable calendar, which lets a read-only
* event be copied into an editable one. [instance]'s own times carry over.
*/
fun EventDetail.toDuplicateForm(
canModify: Boolean,
zone: TimeZone,
knownFixed: Set<FixedTimeReminder> = emptySet(),
): EventForm =
fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
toEditForm(
beginMillis = instance.start.toEpochMilliseconds(),
endMillis = instance.end.toEpochMilliseconds(),
zone = zone,
).withFixedTimeRemindersRead(knownFixed, zone).copy(
).copy(
rrule = null,
calendarId = instance.calendarId.takeIf { canModify },
status = status.forNewEvent(),
)
/**
* This form with its timed reminders read back into lead times and
* [EventForm.fixedReminders] ([splitTimedReminders]), the wall clock taken in
* [deviceZone]. All-day forms come back untouched.
*/
fun EventForm.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, deviceZone: TimeZone): EventForm {
if (isAllDay || reminders.isEmpty()) return this
val split = splitTimedReminders(
reminders, startInstant(resolvedZone(deviceZone)), deviceZone, known, wallClock = rrule != null,
)
return copy(reminders = split.leadMinutes, fixedReminders = (fixedReminders + split.fixed).distinct())
}
/** The offsets [EventForm.fixedReminders] store for this form's start; empty for an all-day form. */
fun EventForm.fixedReminderOffsets(deviceZone: TimeZone): List<Int> {
if (isAllDay || fixedReminders.isEmpty()) return emptyList()
val start = startInstant(resolvedZone(deviceZone))
return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) }
}
@@ -1,87 +0,0 @@
package de.jeanlucmakiola.calendula.domain.reminders
import java.time.Instant
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZoneOffset
/** Which day the daily summary (#459) lists, counted from the day it arrives. */
enum class DigestDay(val daysAhead: Long) { Today(0), Tomorrow(1) }
/** 20:00, when the daily summary arrives until changed. */
const val DEFAULT_DIGEST_TIME_MINUTES = 1_200
/**
* The daily summary's settings. Calendars in [excludedCalendarIds] are left out
* of it; [armedAtMillis] is when its switch, time or day last changed.
*/
data class DailyDigestSettings(
val enabled: Boolean = false,
val timeMinutes: Int = DEFAULT_DIGEST_TIME_MINUTES,
val day: DigestDay = DigestDay.Tomorrow,
val excludedCalendarIds: Set<Long> = emptySet(),
val armedAtMillis: Long = 0L,
)
/**
* What one scan concluded for the summary: list [dueDay] now (null when nothing
* is owed), and wake up again at [nextAlarmMillis].
*/
data class DigestSchedule(
val dueDay: LocalDate?,
val nextAlarmMillis: Long,
)
/**
* When the summary is owed: a moment in `(lastFiredMillis, nowMillis]` is due.
* Only the latest such moment counts — a phone off for three evenings gets one
* summary, not three — and only while the day it lists has not passed and is
* not [lastListedDay]: each day is listed once.
*/
fun scheduleDigest(
timeMinutes: Int,
day: DigestDay,
zone: ZoneId,
lastFiredMillis: Long,
nowMillis: Long,
lastListedDay: LocalDate? = null,
): DigestSchedule {
val time = LocalTime.of(timeMinutes / 60, timeMinutes % 60)
val fireAt = { date: LocalDate -> date.atTime(time).atZone(zone).toInstant().toEpochMilli() }
val today = Instant.ofEpochMilli(nowMillis).atZone(zone).toLocalDate()
val latestDate = if (fireAt(today) <= nowMillis) today else today.minusDays(1)
val listed = latestDate.plusDays(day.daysAhead)
val dueAt = fireAt(latestDate)
val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) && it != lastListedDay }
return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
}
/**
* The occurrences the summary for [day] lists: all-day ones covering it (their
* UTC dates), then timed ones overlapping it in [zone], each group in start
* order. Calendars in [excludedCalendarIds] are left out.
*/
fun digestEntries(
instances: List<ReminderEventInstance>,
day: LocalDate,
zone: ZoneId,
excludedCalendarIds: Set<Long>,
): List<ReminderEventInstance> {
val dayStart = day.atStartOfDay(zone).toInstant().toEpochMilli()
val dayEnd = day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
val utcDay = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
return instances
.asSequence()
.filter { it.calendarId !in excludedCalendarIds }
.filter {
if (it.isAllDay) {
it.beginMillis <= utcDay && maxOf(it.endMillis, it.beginMillis + 1) > utcDay
} else {
it.beginMillis < dayEnd && maxOf(it.endMillis, it.beginMillis + 1) > dayStart
}
}
.distinctBy { occurrenceKey(it.eventId, it.beginMillis) }
.sortedWith(compareBy({ !it.isAllDay }, { it.beginMillis }, { it.title }))
.toList()
}
@@ -1,142 +0,0 @@
package de.jeanlucmakiola.calendula.domain.reminders
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.minus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant
/**
* A timed event's reminder "[daysBefore] days before, at [minuteOfDay]" (#459).
*
* The provider only knows lead times, so it is stored as an ordinary `Reminders`
* row whose offset is the distance from that wall-clock moment to the start
* ([offsetMinutes]) — it fires on every device and in every app. The pattern is
* only known to Calendula while it can be read back ([classifyTimedReminder]); the
* editor then re-derives the offset whenever the start moves.
*/
data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) {
init {
require(daysBefore in 1..MAX_DAYS_BEFORE) { "daysBefore out of range: $daysBefore" }
require(minuteOfDay in 0 until MINUTES_PER_DAY) { "minuteOfDay out of range: $minuteOfDay" }
}
/** The wall clock this reminder names for an event starting at [start], read in [zone]. */
private fun alarmWallClock(start: Instant, zone: TimeZone): LocalDateTime {
val day = start.toLocalDateTime(zone).date.minus(daysBefore, DateTimeUnit.DAY)
return LocalDateTime(day, LocalTime(minuteOfDay / 60, minuteOfDay % 60))
}
/**
* The provider offset to store for an event starting at [start]: the real
* minutes to that moment, or with [wallClock] the minutes on the clock face.
* A recurring series stores one offset for every occurrence, so it takes the
* wall-clock reading — otherwise an occurrence opened next to a DST change
* would bake that hour into all the others.
*/
fun offsetMinutes(start: Instant, zone: TimeZone, wallClock: Boolean = false): Int {
val alarm = alarmWallClock(start, zone)
return if (wallClock) {
(start.toLocalDateTime(zone).toInstant(TimeZone.UTC) - alarm.toInstant(TimeZone.UTC)).inWholeMinutes.toInt()
} else {
(start - alarm.toInstant(zone)).inWholeMinutes.toInt()
}
}
/** The stored form, `days@minuteOfDay`. */
fun toToken(): String = "$daysBefore$TOKEN_SEP$minuteOfDay"
companion object {
/** Two weeks, well inside the four weeks Google Calendar takes for a reminder. */
const val MAX_DAYS_BEFORE = 14
private const val TOKEN_SEP = "@"
/** [toToken] read back; null for anything malformed or out of range. */
fun parse(token: String?): FixedTimeReminder? {
val parts = token?.trim()?.split(TOKEN_SEP) ?: return null
if (parts.size != 2) return null
val days = parts[0].toIntOrNull() ?: return null
val minute = parts[1].toIntOrNull() ?: return null
if (days !in 1..MAX_DAYS_BEFORE || minute !in 0 until MINUTES_PER_DAY) return null
return FixedTimeReminder(days, minute)
}
}
}
/**
* The "N days before at HH:MM" a raw offset lands on for an event starting at
* [start], or null when it fires on the start's own day (or after it), or
* further back than [FixedTimeReminder.MAX_DAYS_BEFORE]. [wallClock] reads the
* offset as [FixedTimeReminder.offsetMinutes] wrote it.
*/
fun fixedTimeReminderAt(
offsetMinutes: Int,
start: Instant,
zone: TimeZone,
wallClock: Boolean = false,
): FixedTimeReminder? {
if (offsetMinutes <= 0) return null
val startLocal = start.toLocalDateTime(zone)
val alarm = if (wallClock) {
(startLocal.toInstant(TimeZone.UTC) - offsetMinutes.minutes).toLocalDateTime(TimeZone.UTC)
} else {
(start - offsetMinutes.minutes).toLocalDateTime(zone)
}
val startDate = startLocal.date
val days = startDate.toEpochDays() - alarm.date.toEpochDays()
if (days !in 1..FixedTimeReminder.MAX_DAYS_BEFORE) return null
return FixedTimeReminder(days.toInt(), alarm.hour * 60 + alarm.minute)
}
/** A timed event's reminders, read back: plain lead times and the fixed-time ones. */
data class TimedReminders(
val leadMinutes: List<Int>,
val fixed: List<FixedTimeReminder>,
)
/**
* The fixed-time reminder [offsetMinutes] stands for on an event starting at
* [start], or null when it reads as a plain lead time. The provider can't say
* which an offset was meant as, so only the patterns in [known] — the configured
* defaults, past and present, and the ones saved by hand on this device — are
* recognised: guessing from the offset's shape alone would turn ordinary leads
* ("12 hours before") into fixed-time ones. Where a lead and a known pattern
* coincide ("1 day before" on an event at the default's own time) the pattern
* wins. A wrong reading fires at the same moment; only a later change of the
* start's time of day then treats the reminder the other way.
*/
fun classifyTimedReminder(
offsetMinutes: Int,
start: Instant,
zone: TimeZone,
known: Set<FixedTimeReminder>,
wallClock: Boolean = false,
): FixedTimeReminder? = fixedTimeReminderAt(offsetMinutes, start, zone, wallClock)?.takeIf { it in known }
/** Sort a timed event's raw offsets into lead times and fixed-time reminders ([classifyTimedReminder]). */
fun splitTimedReminders(
offsets: List<Int>,
start: Instant,
zone: TimeZone,
known: Set<FixedTimeReminder>,
wallClock: Boolean = false,
): TimedReminders {
val leads = mutableListOf<Int>()
val fixed = mutableListOf<FixedTimeReminder>()
offsets.distinct().forEach { offset ->
val pattern = classifyTimedReminder(offset, start, zone, known, wallClock)
if (pattern != null) fixed += pattern else leads += offset
}
return TimedReminders(leads.sorted(), fixed.distinct().sortedWith(FIXED_ORDER))
}
/** Most days before first, then by time — the order they fire in. */
val FIXED_ORDER: Comparator<FixedTimeReminder> =
compareByDescending<FixedTimeReminder> { it.daysBefore }.thenBy { it.minuteOfDay }
private const val MINUTES_PER_DAY = 1_440
@@ -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<Long, ReminderAlertStyle>.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<Long, ReminderAlertStyle> =
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<Long, ReminderAlertStyle>.toStoredAlertStyles(): String =
entries.filter { it.value != ReminderAlertStyle.Notification }
.sortedBy { it.key }
.joinToString(";") { (id, style) -> "$id=${style.storageValue}" }
@@ -15,7 +15,6 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
import de.jeanlucmakiola.calendula.domain.atOccurrence
import de.jeanlucmakiola.calendula.domain.toDuplicateForm
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
@@ -44,7 +43,6 @@ class EventActionsViewModel @Inject constructor(
private val icsExporter: IcsExporter,
@IoDispatcher private val io: CoroutineDispatcher,
private val zoneSource: ZoneSource,
private val settingsPrefs: SettingsPrefs,
) : ViewModel() {
/** Every calendar by id, for what a selected event's bar may offer. */
@@ -67,7 +65,7 @@ class EventActionsViewModel @Inject constructor(
suspend fun duplicateForm(event: EventInstance): EventForm? {
val detail = load(event) ?: return null
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
return detail.toDuplicateForm(canModify, zoneSource.current(), settingsPrefs.knownFixedTimeReminders.first())
return detail.toDuplicateForm(canModify, zoneSource.current())
}
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
@@ -1,216 +0,0 @@
package de.jeanlucmakiola.calendula.ui.common
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
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.floret.components.CustomExpandRow
import de.jeanlucmakiola.floret.components.DialogAmountField
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.datetime.LocalTime
/** "1 day before at 20:00", in the app's 12/24-hour convention. */
@Composable
fun fixedTimeReminderLabel(reminder: FixedTimeReminder): String = stringResource(
R.string.reminder_fixed_time,
pluralStringResource(R.plurals.reminder_days, reminder.daysBefore, reminder.daysBefore),
formatMinuteOfDay(reminder.minuteOfDay, LocalUse24HourFormat.current, currentLocale()),
)
/**
* The "N days before at HH:MM" editor (#459): a day count and a time, read as
* one sentence. Seeded from [initial]; [onValueChange] follows every edit (null
* while the day count is out of range). With a [confirmLabel] it carries its own
* confirm, reporting through [onConfirm]; without one the host picker commits
* from its actions slot. [connected] gives it the shape that meets a row above it.
*/
@Composable
fun FixedTimeReminderEditor(
initial: FixedTimeReminder,
modifier: Modifier = Modifier,
confirmLabel: String? = null,
onConfirm: (FixedTimeReminder) -> Unit = {},
onValueChange: (FixedTimeReminder?) -> Unit = {},
connected: Boolean = true,
) {
var daysText by rememberSaveable { mutableStateOf(initial.daysBefore.toString()) }
var minuteOfDay by rememberSaveable { mutableStateOf(initial.minuteOfDay) }
var pickingTime by rememberSaveable { mutableStateOf(false) }
val days = daysText.toIntOrNull()?.takeIf { it in 1..FixedTimeReminder.MAX_DAYS_BEFORE }
val value = days?.let { FixedTimeReminder(it, minuteOfDay) }
LaunchedEffect(value) { onValueChange(value) }
Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
shape = if (connected) {
RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 22.dp, bottomEnd = 22.dp)
} else {
RoundedCornerShape(22.dp)
},
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
DialogAmountField(value = daysText, onValueChange = { daysText = it }, placeholder = "1")
Spacer(Modifier.width(12.dp))
Text(
text = stringResource(R.string.reminder_fixed_days_before_at),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f, fill = false),
)
Spacer(Modifier.width(12.dp))
FilledTonalButton(onClick = { pickingTime = true }) {
Text(formatMinuteOfDay(minuteOfDay, LocalUse24HourFormat.current, currentLocale()))
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = value?.let { fixedTimeReminderLabel(it) }
?: stringResource(R.string.reminder_fixed_days_range, FixedTimeReminder.MAX_DAYS_BEFORE),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
if (confirmLabel != null) {
Spacer(Modifier.width(16.dp))
FilledTonalButton(
enabled = value != null,
onClick = { value?.let(onConfirm) },
) { Text(confirmLabel) }
}
}
}
}
if (pickingTime) {
TimePickerAlert(
initial = LocalTime(minuteOfDay / 60, minuteOfDay % 60),
onConfirm = {
minuteOfDay = it.hour * 60 + it.minute
pickingTime = false
},
onDismiss = { pickingTime = false },
)
}
}
/**
* Picker for a fixed-time default (#459), full-screen: off, or a reminder at a
* set time edited in place — and, on a per-calendar picker ([inheritedLabel]
* non-null), deferring to the global default, [inherited], which also seeds the
* editor. Applies live; the user leaves via back.
*/
@Composable
fun FixedTimeReminderPicker(
title: String,
selected: FixedTimeOverride,
onSelect: (FixedTimeOverride) -> Unit,
onDismiss: () -> Unit,
inheritedLabel: String? = null,
inherited: FixedTimeReminder? = null,
) {
var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) }
var editing by rememberSaveable { mutableStateOf(false) }
// Mirrors [selected] until the first pick, as ReminderDefaultPicker does.
var userEdited by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(selected) {
if (!userEdited) current = selected
}
fun apply(choice: FixedTimeOverride) {
userEdited = true
current = choice
onSelect(choice)
}
val chosen = (current as? FixedTimeOverride.At)?.reminder
FullScreenPicker(title = title, onDismiss = onDismiss) {
GroupedHint(text = stringResource(R.string.settings_fixed_reminder_hint))
Spacer(Modifier.height(8.dp))
val rowCount = if (inheritedLabel != null) 3 else 2
if (inheritedLabel != null) {
GroupedRow(
title = stringResource(R.string.reminder_use_default),
summary = inheritedLabel,
position = Position.Top,
checked = current is FixedTimeOverride.Inherit,
onClick = { apply(FixedTimeOverride.Inherit) },
)
}
GroupedRow(
title = stringResource(R.string.reminder_none),
position = if (rowCount == 3) Position.Middle else Position.Top,
checked = current is FixedTimeOverride.Off,
onClick = { apply(FixedTimeOverride.Off) },
)
CustomExpandRow(
title = stringResource(R.string.reminder_fixed_at_set_time),
summary = chosen?.let { fixedTimeReminderLabel(it) },
position = Position.Bottom,
expanded = editing,
onExpandedChange = { editing = it },
checked = chosen != null,
) {
FixedTimeReminderEditor(
initial = chosen ?: inherited ?: DEFAULT_FIXED_TIME_REMINDER,
confirmLabel = stringResource(R.string.reminder_custom_set),
onConfirm = {
apply(FixedTimeOverride.At(it))
editing = false
},
)
}
}
}
/** What the editor offers first: the evening before. */
val DEFAULT_FIXED_TIME_REMINDER = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60)
private val FixedTimeOverrideSaver = Saver<FixedTimeOverride, String>(
save = {
when (it) {
FixedTimeOverride.Inherit -> "inherit"
FixedTimeOverride.Off -> "off"
is FixedTimeOverride.At -> it.reminder.toToken()
}
},
restore = {
when (it) {
"inherit" -> FixedTimeOverride.Inherit
"off" -> FixedTimeOverride.Off
else -> FixedTimeReminder.parse(it)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Off
}
},
)
@@ -23,12 +23,9 @@ import de.jeanlucmakiola.calendula.domain.resolvedZone
import de.jeanlucmakiola.calendula.domain.shiftedByDays
import de.jeanlucmakiola.calendula.domain.shiftedTo
import de.jeanlucmakiola.calendula.domain.toEditForm
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -175,7 +172,6 @@ class RescheduleViewModel @Inject constructor(
private val repository: CalendarRepository,
@IoDispatcher private val io: CoroutineDispatcher,
private val zoneSource: ZoneSource,
private val settingsPrefs: SettingsPrefs,
) : ViewModel() {
private val _scopePrompt = MutableStateFlow<MoveScopePrompt?>(null)
@@ -461,9 +457,7 @@ class RescheduleViewModel @Inject constructor(
dropped
}
// Read fixed-time reminders out, so the move keeps them on their wall clock (#459).
val original = detail.toEditForm(request.beginMillis, request.endMillis, zone)
.withFixedTimeRemindersRead(settingsPrefs.knownFixedTimeReminders.first(), zone)
val shifted = when (val target = request.target) {
is MoveTarget.Start -> original.shiftedTo(target.instant, zone)
is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone)
@@ -108,7 +108,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone
import de.jeanlucmakiola.calendula.ui.common.recurrenceText
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel
import kotlinx.coroutines.launch
import kotlinx.datetime.TimeZone
@@ -533,8 +532,7 @@ private fun EventDetailContent(
.sortedBy { it.minutes }
.forEach { reminder ->
Text(
text = state.fixedReminders[reminder.minutes]?.let { fixedTimeReminderLabel(it) }
?: reminderLeadTimeLabel(reminder.minutes),
text = reminderLeadTimeLabel(reminder.minutes),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(vertical = 2.dp),
)
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.detail
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.RichText
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
/**
* UI state for the event-detail screen (spec S4).
@@ -27,10 +26,6 @@ sealed interface EventDetailUiState {
val phoneLinks: EventPhoneLinks = EventPhoneLinks(),
/** The description as drawn — HTML rendered (#271); null when there is none. */
val description: RichText? = null,
/** Reminder offsets that read as "N days before at HH:MM" (#459), by raw minutes. */
val fixedReminders: Map<Int, FixedTimeReminder> = emptyMap(),
/** The fixed-time patterns the reminders were read against. */
val knownFixed: Set<FixedTimeReminder> = emptySet(),
) : EventDetailUiState
}
@@ -1,7 +1,5 @@
package de.jeanlucmakiola.calendula.ui.detail
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.reminders.classifyTimedReminder
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
@@ -48,7 +46,6 @@ class EventDetailViewModel @Inject constructor(
private val icsExporter: IcsExporter,
@IoDispatcher private val io: CoroutineDispatcher,
private val zoneSource: ZoneSource,
private val settingsPrefs: SettingsPrefs,
) : ViewModel() {
private val _target = MutableStateFlow<Target?>(null)
@@ -145,7 +142,7 @@ class EventDetailViewModel @Inject constructor(
*/
fun duplicateForm(): EventForm? {
val loaded = state.value as? EventDetailUiState.Success ?: return null
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current(), loaded.knownFixed)
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current())
}
private suspend fun loadDetail(target: Target): EventDetailUiState = try {
@@ -160,17 +157,6 @@ class EventDetailViewModel @Inject constructor(
}
val calendar = repository.calendars().first()
.firstOrNull { it.id == corrected.instance.calendarId }
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
val fixedReminders = if (corrected.instance.isAllDay) {
emptyMap()
} else {
val zone = zoneSource.current()
corrected.reminders.map { it.minutes }.distinct().mapNotNull { minutes ->
classifyTimedReminder(
minutes, corrected.instance.start, zone, knownFixed, wallClock = corrected.rrule != null,
)?.let { minutes to it }
}.toMap()
}
val description = corrected.description
?.let(::descriptionRichText)
?.takeIf { it.text.isNotBlank() }
@@ -187,8 +173,6 @@ class EventDetailViewModel @Inject constructor(
description = description?.text,
),
description = description,
fixedReminders = fixedReminders,
knownFixed = knownFixed,
)
} catch (e: CancellationException) {
throw e
@@ -125,10 +125,6 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventAttendee
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.ui.common.DEFAULT_FIXED_TIME_REMINDER
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderEditor
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
import de.jeanlucmakiola.calendula.domain.startInstant
import de.jeanlucmakiola.calendula.domain.endInstant
import de.jeanlucmakiola.calendula.domain.resolvedZone
@@ -157,7 +153,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.floret.components.DialogAmountField
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.DialogUnitDropdown
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldIcon
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel
@@ -880,9 +875,7 @@ private fun EventEditContent(
Spacer(Modifier.height(gap))
RemindersSection(
reminders = form.reminders,
fixedReminders = if (form.isAllDay) emptyList() else form.fixedReminders,
onRemove = viewModel::removeReminder,
onRemoveFixed = viewModel::removeFixedReminder,
onAdd = { sheet = EditSheet.Reminder },
)
}
@@ -1291,25 +1284,9 @@ private fun LocationCard(
* connected corners, the last row being "Add reminder".
*/
@Composable
private fun RemindersSection(
reminders: List<Int>,
fixedReminders: List<FixedTimeReminder>,
onRemove: (Int) -> Unit,
onRemoveFixed: (FixedTimeReminder) -> Unit,
onAdd: () -> Unit,
) {
val rows = fixedReminders.size + reminders.size + 1
fixedReminders.forEachIndexed { index, reminder ->
GroupedItemCard(
position = positionOf(index, rows),
icon = Icons.Default.Notifications,
title = fixedTimeReminderLabel(reminder),
removeContentDescription = stringResource(R.string.event_edit_remove_reminder),
onRemove = { onRemoveFixed(reminder) },
)
}
reminders.forEachIndexed { i, minutes ->
val index = fixedReminders.size + i
private fun RemindersSection(reminders: List<Int>, onRemove: (Int) -> Unit, onAdd: () -> Unit) {
val rows = reminders.size + 1
reminders.forEachIndexed { index, minutes ->
GroupedItemCard(
position = positionOf(index, rows),
icon = Icons.Default.Notifications,
@@ -1320,7 +1297,7 @@ private fun RemindersSection(
}
AddActionCard(
label = stringResource(R.string.event_edit_add_reminder),
position = positionOf(rows - 1, rows),
position = positionOf(reminders.size, rows),
onClick = onAdd,
)
}
@@ -1512,15 +1489,10 @@ private fun EditSheetHost(
}
EditSheet.Reminder -> ReminderPickerDialog(
alreadyChosen = form.reminders,
offerFixedTime = !form.isAllDay,
onSelect = { minutes ->
viewModel.addReminder(minutes)
onClose()
},
onSelectFixed = { reminder ->
viewModel.addFixedReminder(reminder)
onClose()
},
onDismiss = onClose,
)
EditSheet.Recurrence -> RecurrencePickerDialog(
@@ -1609,14 +1581,10 @@ private fun FieldPickerDialog(
@Composable
private fun ReminderPickerDialog(
alreadyChosen: List<Int>,
offerFixedTime: Boolean,
onSelect: (Int) -> Unit,
onSelectFixed: (FixedTimeReminder) -> Unit,
onDismiss: () -> Unit,
) {
var customMode by rememberSaveable { mutableStateOf(false) }
var fixedMode by rememberSaveable { mutableStateOf(false) }
var pendingFixed by remember { mutableStateOf<FixedTimeReminder?>(null) }
var amountText by rememberSaveable { mutableStateOf("") }
var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) }
val customMinutes = amountText.toIntOrNull()
@@ -1627,31 +1595,18 @@ private fun ReminderPickerDialog(
title = stringResource(R.string.event_edit_add_reminder),
onDismiss = onDismiss,
actions = {
// The quick-pick list adds on tap; only the custom steps need Add.
// The quick-pick list adds on tap; only the custom step needs Add.
if (customMode) {
TextButton(
enabled = customMinutes != null && customMinutes !in alreadyChosen,
onClick = { customMinutes?.let(onSelect) },
) { Text(stringResource(R.string.event_edit_add)) }
} else if (fixedMode) {
TextButton(
enabled = pendingFixed != null,
onClick = { pendingFixed?.let(onSelectFixed) },
) { Text(stringResource(R.string.event_edit_add)) }
}
},
) {
if (fixedMode) {
GroupedHint(text = stringResource(R.string.event_edit_reminder_fixed_hint))
Spacer(Modifier.height(8.dp))
FixedTimeReminderEditor(
initial = DEFAULT_FIXED_TIME_REMINDER,
onValueChange = { pendingFixed = it },
connected = false,
)
} else if (!customMode) {
if (!customMode) {
val presets = REMINDER_PRESETS.filterNot { it in alreadyChosen }
val rowCount = presets.size + if (offerFixedTime) 2 else 1
val rowCount = presets.size + 1
presets.forEachIndexed { index, minutes ->
GroupedRow(
title = reminderLeadTimeLabel(minutes),
@@ -1659,14 +1614,6 @@ private fun ReminderPickerDialog(
onClick = { onSelect(minutes) },
)
}
if (offerFixedTime) {
GroupedRow(
title = stringResource(R.string.reminder_fixed_at_set_time),
summary = stringResource(R.string.event_edit_reminder_fixed_summary),
position = positionOf(presets.size, rowCount),
onClick = { fixedMode = true },
)
}
GroupedRow(
title = stringResource(R.string.event_edit_reminder_custom),
position = positionOf(rowCount - 1, rowCount),
@@ -13,12 +13,7 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultFixedTimeReminder
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder
import de.jeanlucmakiola.calendula.domain.reminders.FIXED_ORDER
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
import de.jeanlucmakiola.calendula.domain.canSaveApartFromSeries
import de.jeanlucmakiola.calendula.domain.AccessLevel
import de.jeanlucmakiola.calendula.domain.Availability
@@ -144,7 +139,6 @@ enum class ImportSource(internal val ownsDuration: Boolean) {
data class ImportReminderPrompt(
val currentReminderCount: Int,
val defaultReminders: List<Int>,
val defaultFixedReminders: List<FixedTimeReminder> = emptyList(),
)
/**
@@ -214,8 +208,6 @@ class EventEditViewModel @Inject constructor(
val zone: TimeZone,
/** The event as loaded, on the tapped occurrence's times — what Share exports. */
val detail: EventDetail,
/** The fixed-time patterns its reminders were read against, so a re-read splits alike. */
val knownFixed: Set<FixedTimeReminder>,
) {
val original: EventForm get() = snapshot.form
}
@@ -233,13 +225,7 @@ class EventEditViewModel @Inject constructor(
val allDay: List<Int>,
val timedOverrides: Map<Long, List<Int>>,
val allDayOverrides: Map<Long, List<Int>>,
val fixed: FixedTimeReminder?,
val fixedOverrides: Map<Long, FixedTimeReminder?>,
) {
/** The fixed-time reminders a new event on [calendarId] gets (#459); none on an all-day one. */
fun resolveFixedFor(calendarId: Long?, isAllDay: Boolean): List<FixedTimeReminder> =
if (isAllDay) emptyList() else listOfNotNull(resolveDefaultFixedTimeReminder(fixed, fixedOverrides, calendarId))
/** The default reminders for an event on [calendarId] of the given kind. */
fun resolveFor(calendarId: Long?, isAllDay: Boolean): List<Int> = resolveDefaultReminder(
timedGlobal = timed,
@@ -449,7 +435,7 @@ class EventEditViewModel @Inject constructor(
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
when (source) {
ImportSource.Insert, ImportSource.InsertOpenEnded ->
if (form.reminders.isNotEmpty() || form.fixedReminders.isNotEmpty()) _remindersTouched.value = true
if (form.reminders.isNotEmpty()) _remindersTouched.value = true
else applyDefaultReminder()
ImportSource.File -> {
@@ -479,35 +465,27 @@ class EventEditViewModel @Inject constructor(
val form = _form.value ?: return@launch
if (_editTarget.value != null || _remindersTouched.value) return@launch
val reminders = defaults.resolveFor(targetId, form.isAllDay)
val fixed = defaults.resolveFixedFor(targetId, form.isAllDay)
// The duration default resolves in parallel, so both must compose
// onto the current form, not a pre-suspend copy.
applyDefault { it.copy(reminders = reminders, fixedReminders = fixed) }
applyDefault { it.copy(reminders = reminders) }
// Surface the section so an auto-applied default is visible and
// removable, even when Reminders isn't a default-shown field.
if (reminders.isNotEmpty() || fixed.isNotEmpty()) {
if (reminders.isNotEmpty()) {
_revealed.value = _revealed.value + EventFormField.Reminders
}
}
}
/** Snapshot the settings-default reminder flows into one value. */
/** Snapshot the four settings-default reminder flows into one value. */
private suspend fun reminderDefaults(): ReminderDefaults = combine(
combine(
settingsPrefs.defaultReminderMinutes,
settingsPrefs.defaultAllDayReminderMinutes,
settingsPrefs.perCalendarReminderOverride,
settingsPrefs.perCalendarAllDayReminderOverride,
::Quadruple,
),
settingsPrefs.defaultFixedTimeReminder,
settingsPrefs.perCalendarFixedTimeReminderOverride,
) { (timed, allDay, timedOv, allDayOv), fixed, fixedOv ->
ReminderDefaults(timed, allDay, timedOv, allDayOv, fixed, fixedOv)
settingsPrefs.defaultReminderMinutes,
settingsPrefs.defaultAllDayReminderMinutes,
settingsPrefs.perCalendarReminderOverride,
settingsPrefs.perCalendarAllDayReminderOverride,
) { timed, allDay, timedOv, allDayOv ->
ReminderDefaults(timed, allDay, timedOv, allDayOv)
}.first()
private data class Quadruple<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
/**
* Stretch a new timed event to the configured default length (#54) — the
* resolved calendar's per-calendar duration, otherwise the global default —
@@ -553,19 +531,15 @@ class EventEditViewModel @Inject constructor(
val opened = session
viewModelScope.launch {
val targetId = resolvedCalendarId.first()
val defaults = reminderDefaults()
val default = defaults.resolveFor(targetId, form.isAllDay)
val fixed = defaults.resolveFixedFor(targetId, form.isAllDay)
val default = reminderDefaults().resolveFor(targetId, form.isAllDay)
// Bail if the form closed or became an edit while we resolved.
if (opened != session) return@launch
val current = _form.value ?: return@launch
if (_editTarget.value != null) return@launch
if (default.isEmpty() && fixed.isEmpty()) return@launch
if (default == current.reminders && fixed == current.fixedReminders) return@launch
if (default.isEmpty() || default == current.reminders) return@launch
_importReminderPrompt.value = ImportReminderPrompt(
currentReminderCount = current.reminders.size + current.fixedReminders.size,
currentReminderCount = current.reminders.size,
defaultReminders = default,
defaultFixedReminders = fixed,
)
}
}
@@ -575,7 +549,7 @@ class EventEditViewModel @Inject constructor(
val prompt = _importReminderPrompt.value ?: return
_importReminderPrompt.value = null
// Already frozen as touched by openImported; this just swaps the values.
edit { it.copy(reminders = prompt.defaultReminders, fixedReminders = prompt.defaultFixedReminders) }
edit { it.copy(reminders = prompt.defaultReminders) }
_revealed.value = _revealed.value + EventFormField.Reminders
}
@@ -605,15 +579,14 @@ class EventEditViewModel @Inject constructor(
if (opened == session) _loadFailed.value = true
return@launch
}
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
if (opened != session) return@launch
val zone = zoneSource.current()
val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME }
?: detail.instance.start.toEpochMilliseconds()
val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME }
?: detail.instance.end.toEpochMilliseconds()
val snapshot = detail.toEditSnapshot(begin, end, zone).withFixedTimeRemindersRead(knownFixed, zone)
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end), knownFixed)
val snapshot = detail.toEditSnapshot(begin, end, zone)
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end))
// Sections holding data must show even when not in the defaults.
_revealed.value = snapshot.form.populatedFields()
open(snapshot.form)
@@ -718,11 +691,7 @@ class EventEditViewModel @Inject constructor(
fun addReminder(minutes: Int) {
_remindersTouched.value = true
edit {
// A lead firing with a set-time reminder would be one row once saved.
if (minutes in it.fixedReminderOffsets(zoneSource.current())) it
else it.copy(reminders = (it.reminders + minutes).distinct().sorted())
}
edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) }
}
fun removeReminder(minutes: Int) {
@@ -730,26 +699,6 @@ class EventEditViewModel @Inject constructor(
edit { it.copy(reminders = it.reminders - minutes) }
}
/**
* Add an "N days before at HH:MM" reminder (#459); timed events only. A lead
* time landing on the same moment is replaced by it — the two would be one
* row once saved.
*/
fun addFixedReminder(reminder: FixedTimeReminder) {
_remindersTouched.value = true
edit { form ->
if (form.isAllDay) return@edit form
val withFixed = form.copy(fixedReminders = (form.fixedReminders + reminder).distinct().sortedWith(FIXED_ORDER))
val offsets = withFixed.fixedReminderOffsets(zoneSource.current()).toSet()
withFixed.copy(reminders = form.reminders.filterNot { it in offsets })
}
}
fun removeFixedReminder(reminder: FixedTimeReminder) {
_remindersTouched.value = true
edit { it.copy(fixedReminders = it.fixedReminders - reminder) }
}
/**
* Add a guest, keyed on a trimmed lower-cased email so re-adding the same
* address just refreshes it (no duplicate row). A blank email is ignored —
@@ -866,7 +815,6 @@ class EventEditViewModel @Inject constructor(
val fresh = try {
repository.eventDetail(target.eventId)
.toEditSnapshot(target.beginMillis, target.endMillis, target.zone)
.withFixedTimeRemindersRead(target.knownFixed, target.zone)
} catch (e: CancellationException) {
throw e
} catch (e: NoSuchEventException) {
@@ -881,17 +829,6 @@ class EventEditViewModel @Inject constructor(
return@launch
}
}
// Remembered before the write, so the rows read back as these
// reminders from the first re-read on (#459).
if (!form.isAllDay && form.fixedReminders.isNotEmpty()) {
try {
settingsPrefs.rememberFixedTimeReminders(form.fixedReminders)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "Could not remember the set-time reminders", e)
}
}
val result = try {
if (target == null) {
repository.createEvent(form)
@@ -1013,7 +950,3 @@ class EventEditViewModel @Inject constructor(
_form.value = _form.value?.let(block)
}
}
/** [EditSnapshot.form] with its timed reminders read back into lead times and fixed-time ones. */
private fun EditSnapshot.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, zone: TimeZone): EditSnapshot =
copy(form = form.withFixedTimeRemindersRead(known, zone))
@@ -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>(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)
}
}
@@ -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() }
}
}
@@ -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
}
@@ -24,12 +24,11 @@ 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.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
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.FixedTimeReminderPicker
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
@@ -42,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
/**
@@ -67,7 +69,9 @@ internal fun CalendarRemindersScreen(
val scope = rememberCoroutineScope()
var expandedCalendars by rememberSaveable { mutableStateOf(emptyList<Long>()) }
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
var fixedOverrideFor by remember { mutableStateOf<Long?>(null) }
var alertStylePicker by remember { mutableStateOf<Long?>(null) }
var alertSoundPicker by remember { mutableStateOf<Long?>(null) }
val canFullScreen = rememberCanUseFullScreenIntent()
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
val calendarIds = state.reminderCalendars.map { it.id }
LifecycleResumeEffect(calendarIds) {
@@ -89,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
@@ -109,23 +121,60 @@ 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 },
onEditFixedOverride = { fixedOverrideFor = calendar.id },
onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) },
)
}
}
}
fixedOverrideFor?.let { calendarId ->
FixedTimeReminderPicker(
title = stringResource(R.string.settings_fixed_reminder),
selected = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendarId),
onSelect = { viewModel.setCalendarFixedTimeReminderOverride(calendarId, it) },
onDismiss = { fixedOverrideFor = null },
inheritedLabel = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
inherited = state.defaultFixedTimeReminder,
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 ->
@@ -176,24 +225,25 @@ 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,
onEditFixedOverride: () -> Unit,
onSetInDigest: (Boolean) -> Unit,
) {
val opensGroup = position == Position.Top || position == Position.Alone
val closesGroup = position == Position.Bottom || position == Position.Alone
GroupedRow(
title = calendar.displayName.orUnnamed(),
summary = when {
// Still in the summary, so only its reminders are off.
!notifying && state.dailyDigest.enabled && calendar.id !in state.dailyDigest.excludedCalendarIds ->
stringResource(R.string.settings_calendar_reminders_off)
!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 {
@@ -212,7 +262,7 @@ private fun CalendarReminderEntry(
) {
val managed = calendar.id in state.managedCalendarIds
val takesOverrides = calendar.canModifyContents && !managed
val digestOn = state.dailyDigest.enabled
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)) {
@@ -226,24 +276,52 @@ 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 || digestOn) Position.Middle else Position.Bottom,
position = Position.Middle,
container = nested,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
)
if (digestOn) {
GroupedSwitchRow(
title = stringResource(R.string.settings_calendar_in_digest),
checked = calendar.id !in state.dailyDigest.excludedCalendarIds,
onCheckedChange = onSetInDigest,
summary = stringResource(R.string.settings_calendar_in_digest_hint),
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
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) {
@@ -265,20 +343,6 @@ private fun CalendarReminderEntry(
container = nested,
onEditOverride = onEditOverride,
)
GroupedRow(
title = stringResource(R.string.settings_fixed_reminder),
summary = when (val fixed = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendar.id)) {
FixedTimeOverride.Inherit -> stringResource(
R.string.settings_calendar_reminder_inherits,
fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
)
FixedTimeOverride.Off -> stringResource(R.string.reminder_none)
is FixedTimeOverride.At -> fixedTimeReminderLabel(fixed.reminder)
},
position = Position.Middle,
container = nested,
onClick = onEditFixedOverride,
)
OverrideRow(
calendarId = calendar.id,
isAllDay = true,
@@ -337,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() }
@@ -1,9 +1,5 @@
package de.jeanlucmakiola.calendula.ui.settings
import de.jeanlucmakiola.floret.identity.collapseExit
import de.jeanlucmakiola.floret.identity.expandEnter
import androidx.compose.foundation.layout.Column
import androidx.compose.animation.AnimatedVisibility
import android.Manifest
import android.content.Context
import android.content.Intent
@@ -26,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
@@ -38,18 +33,9 @@ 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.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
import de.jeanlucmakiola.calendula.ui.common.DurationPicker
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
@@ -86,9 +72,8 @@ internal fun NotificationsScreen(
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
) { /* The pref is already on; a denial just leaves the OS gate shut. */ }
// Turning either kind of notification on asks for the permission if missing.
fun askingPermission(set: (Boolean) -> Unit): (Boolean) -> Unit = { enabled ->
set(enabled)
val toggleReminders: (Boolean) -> Unit = { enabled ->
viewModel.setRemindersEnabled(enabled)
val needsPermission = enabled &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
@@ -96,19 +81,13 @@ internal fun NotificationsScreen(
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
val toggleReminders = askingPermission(viewModel::setRemindersEnabled)
val toggleDigest = askingPermission(viewModel::setDailyDigestEnabled)
var showDefaultReminder by remember { mutableStateOf(false) }
var showAllDayReminder by remember { mutableStateOf(false) }
var showAllDayReminderTime by remember { mutableStateOf(false) }
var showSnooze by remember { mutableStateOf(false) }
var showFixedDefault by remember { mutableStateOf(false) }
var showDigestDay by remember { mutableStateOf(false) }
var showDigestTime by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
val digestBlocked by viewModel.digestBlocked.collectAsStateWithLifecycle()
val calendarIds = state.reminderCalendars.map { it.id }
LifecycleResumeEffect(calendarIds) {
viewModel.refreshChannelStatus(calendarIds)
@@ -127,8 +106,6 @@ internal fun NotificationsScreen(
viewModel.dismissNotificationCategoryHint()
scope.launch {
viewModel.syncReminderChannels()
// The summary's category too, so it is on the list to check.
if (state.dailyDigest.enabled) viewModel.digestChannel()
context.openNotificationSettings()
}
},
@@ -165,12 +142,6 @@ internal fun NotificationsScreen(
position = Position.Middle,
onClick = { showDefaultReminder = true },
)
GroupedRow(
title = stringResource(R.string.settings_fixed_reminder),
summary = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
position = Position.Middle,
onClick = { showFixedDefault = true },
)
GroupedRow(
title = stringResource(R.string.settings_default_reminder_allday),
summary = reminderChoiceLabel(state.defaultAllDayReminderMinutes),
@@ -187,21 +158,6 @@ internal fun NotificationsScreen(
onClick = { showAllDayReminderTime = true },
)
Spacer(Modifier.height(24.dp))
DailyDigestRows(
digest = state.dailyDigest,
blocked = channelStatus.appBlocked || digestBlocked,
onEnable = toggleDigest,
onPickDay = { showDigestDay = true },
onPickTime = { showDigestTime = true },
onOpenSound = {
// The app's own page while the app is blocked: the channel's would be greyed out.
scope.launch {
context.openNotificationSettings(viewModel.digestChannel().takeUnless { channelStatus.appBlocked })
}
},
)
// Reliability is a soft, optional battery-optimisation exemption via
// a system-settings deep-link, shown as live status.
Spacer(Modifier.height(24.dp))
@@ -247,34 +203,6 @@ internal fun NotificationsScreen(
}
}
if (showFixedDefault) {
FixedTimeReminderPicker(
title = stringResource(R.string.settings_fixed_reminder),
selected = state.defaultFixedTimeReminder?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off,
onSelect = { viewModel.setDefaultFixedTimeReminder((it as? FixedTimeOverride.At)?.reminder) },
onDismiss = { showFixedDefault = false },
)
}
if (showDigestDay) {
OptionPicker(
title = stringResource(R.string.settings_digest_day),
options = DigestDay.entries,
selected = state.dailyDigest.day,
label = { stringResource(digestDayLabel(it)) },
onSelect = viewModel::setDailyDigestDay,
onDismiss = { showDigestDay = false },
)
}
if (showDigestTime) {
TimePickerAlert(
initial = LocalTime(state.dailyDigest.timeMinutes / 60, state.dailyDigest.timeMinutes % 60),
onConfirm = {
viewModel.setDailyDigestTimeMinutes(it.hour * 60 + it.minute)
showDigestTime = false
},
onDismiss = { showDigestTime = false },
)
}
if (showSnooze) {
DurationPicker(
title = stringResource(R.string.settings_snooze_duration),
@@ -322,63 +250,6 @@ internal fun NotificationsScreen(
}
}
/**
* The daily summary (#459): its switch, and once on, which day it lists, when,
* and its channel's system settings.
*/
@Composable
private fun DailyDigestRows(
digest: DailyDigestSettings,
blocked: Boolean,
onEnable: (Boolean) -> Unit,
onPickDay: () -> Unit,
onPickTime: () -> Unit,
onOpenSound: () -> Unit,
) {
GroupedSwitchRow(
title = stringResource(R.string.settings_digest),
checked = digest.enabled,
onCheckedChange = onEnable,
summary = if (digest.enabled) {
stringResource(
R.string.settings_digest_summary,
stringResource(digestDayLabel(digest.day)),
settingsTimeOfDay(digest.timeMinutes),
)
} else {
stringResource(R.string.settings_digest_hint)
},
position = if (digest.enabled) Position.Top else Position.Alone,
)
AnimatedVisibility(visible = digest.enabled, enter = expandEnter(), exit = collapseExit()) {
Column {
GroupedRow(
title = stringResource(R.string.settings_digest_day),
summary = stringResource(digestDayLabel(digest.day)),
position = Position.Middle,
onClick = onPickDay,
)
GroupedRow(
title = stringResource(R.string.settings_digest_time),
summary = settingsTimeOfDay(digest.timeMinutes),
position = Position.Middle,
onClick = onPickTime,
)
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = if (blocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
stringResource(R.string.settings_digest_sound_hint)
},
position = Position.Bottom,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
)
}
}
}
/** Samsung's One UI can start a new notification category switched off (#145). */
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
@@ -401,16 +272,6 @@ private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit)
}
}
private fun digestDayLabel(day: DigestDay): Int = when (day) {
DigestDay.Today -> R.string.settings_digest_day_today
DigestDay.Tomorrow -> R.string.settings_digest_day_tomorrow
}
/** A fixed-time default's label, or "None". */
@Composable
internal fun fixedReminderChoiceLabel(reminder: FixedTimeReminder?): String =
reminder?.let { fixedTimeReminderLabel(it) } ?: stringResource(R.string.reminder_none)
@Composable
internal fun ExternalLinkIcon() {
Icon(
@@ -432,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 {
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui.settings
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
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
@@ -98,18 +97,14 @@ data class SettingsUiState(
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
/** The "N days before at HH:MM" default for new timed events (#459); null = none. */
val defaultFixedTimeReminder: FixedTimeReminder? = null,
/** Per-calendar overrides of [defaultFixedTimeReminder]: absent inherits, null turns it off. */
val perCalendarFixedTimeReminderOverride: Map<Long, FixedTimeReminder?> = emptyMap(),
/** The daily summary notification (#459). */
val dailyDigest: DailyDigestSettings = DailyDigestSettings(),
/** Switched-on calendars you can edit: the per-calendar event-duration rows. */
val writableCalendars: List<CalendarSource> = emptyList(),
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
val reminderCalendars: List<CalendarSource> = emptyList(),
/** Calendars whose reminders Calendula doesn't post (#272). */
val mutedReminderCalendarIds: Set<Long> = emptySet(),
/** Per-calendar alert styles (#171); absent means a plain notification. */
val reminderAlertStyles: Map<Long, ReminderAlertStyle> = emptyMap(),
/** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */
val notificationCategoryHintDismissed: Boolean = true,
/**
@@ -19,12 +19,6 @@ import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.dailyDigest
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
import de.jeanlucmakiola.calendula.data.reminders.DailyDigestNotifier
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
@@ -43,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
@@ -81,8 +78,7 @@ class SettingsViewModel @Inject constructor(
private val launcherNameManager: LauncherNameManager,
private val reminderScanner: ReminderScanner,
private val reminderChannels: ReminderChannels,
private val digestNotifier: DailyDigestNotifier,
private val reminderState: ReminderStatePrefs,
private val reminderNotifier: ReminderNotifier,
@IoDispatcher private val io: CoroutineDispatcher,
@ApplicationContext private val appContext: Context,
) : ViewModel() {
@@ -141,12 +137,10 @@ class SettingsViewModel @Inject constructor(
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
defaultFixedTimeReminder = this[SettingsKeys.defaultFixedTimeReminder],
perCalendarFixedTimeReminderOverride = this[SettingsKeys.perCalendarFixedTimeReminderOverride],
dailyDigest = dailyDigest,
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(),
@@ -372,7 +366,13 @@ class SettingsViewModel @Inject constructor(
* A scan follows the write: switching reminders off cancels the scan alarm,
* so switching them back on has to arm a new one (#75).
*/
fun setRemindersEnabled(enabled: Boolean) = saveAndScan { setRemindersEnabled(enabled) }
fun setRemindersEnabled(enabled: Boolean) {
viewModelScope.launch {
prefs.setRemindersEnabled(enabled)
if (!enabled) reminderNotifier.stopRing(RingMatch.Any)
reminderScanner.scan()
}
}
/**
* Re-plans, since a muted calendar armed no wake-up for its next reminder.
@@ -383,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). */
@@ -398,18 +414,9 @@ class SettingsViewModel @Inject constructor(
channelStatusJob?.cancel()
channelStatusJob = viewModelScope.launch {
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
_digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) }
}
}
private val _digestBlocked = MutableStateFlow(false)
/**
* Whether the daily summary's own channel is switched off (#459); the app-wide
* block is [channelStatus]'s. Refreshed with [refreshChannelStatus].
*/
val digestBlocked: StateFlow<Boolean> = _digestBlocked.asStateFlow()
fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() }
/**
@@ -425,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 <T> onChannels(block: ReminderChannels.() -> T): T? = withContext(io) {
@@ -451,7 +462,12 @@ class SettingsViewModel @Inject constructor(
fun setDefaultAllDayReminderMinutes(minutes: List<Int>) = save { setDefaultAllDayReminderMinutes(minutes) }
/** The armed alarm was planned for the old hour, so re-plan against the new one. */
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) = saveAndScan { setAllDayReminderTimeMinutes(minutesOfDay) }
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) {
viewModelScope.launch {
prefs.setAllDayReminderTimeMinutes(minutesOfDay)
reminderScanner.scan()
}
}
fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) }
@@ -461,53 +477,6 @@ class SettingsViewModel @Inject constructor(
fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = save { setAllowColorOnUnsupportedCalendars(enabled) }
fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) = save { setDefaultFixedTimeReminder(reminder) }
fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) =
save { setCalendarFixedTimeReminderOverride(calendarId, override) }
/** Every summary change re-plans, so the next one is armed for its new moment (#459). */
fun setDailyDigestEnabled(enabled: Boolean) {
viewModelScope.launch {
prefs.setDailyDigestEnabled(enabled)
// Created now, so a phone that starts new categories switched off
// shows it blocked here rather than dropping the first summary.
if (enabled) {
digestChannel()
_digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) }
}
// After the scan, so one already under way can't post past the cancel;
// a summary left showing would go stale with nothing to replace it.
reminderScanner.scan()
if (!enabled) digestNotifier.cancel()
}
}
fun setDailyDigestTimeMinutes(minutesOfDay: Int) = saveAndScan { setDailyDigestTimeMinutes(minutesOfDay) }
/** A new mode lists afresh: from "tomorrow" to "today", the day just listed comes again. */
fun setDailyDigestDay(day: DigestDay) {
viewModelScope.launch {
prefs.setDailyDigestDay(day)
reminderState.clearLastDigestDay()
reminderScanner.scan()
}
}
fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) = save { setCalendarInDailyDigest(calendarId, included) }
/** The summary's channel, created if needed so its system settings can open. */
suspend fun digestChannel(): String? = withContext(io) {
runCatching { digestNotifier.channelId() }.getOrNull()
}
private fun saveAndScan(write: suspend SettingsPrefs.() -> Unit) {
viewModelScope.launch {
prefs.write()
reminderScanner.scan()
}
}
private fun save(write: suspend SettingsPrefs.() -> Unit) {
viewModelScope.launch { prefs.write() }
}
+17 -38
View File
@@ -376,6 +376,8 @@
<string name="reminder_onboarding_skip_button">Not now</string>
<string name="reminder_action_snooze">Snooze</string>
<string name="reminder_action_dismiss">Dismiss</string>
<string name="reminder_ring_channel_name">Ringing reminders</string>
<string name="reminder_ring_channel_description">Full-screen reminders that ring until you dismiss them. Calendula plays their sound itself.</string>
<!-- Day context prefix in a reminder for an event on another day (v2.15.0) -->
<string name="reminder_day_today">Today</string>
<string name="reminder_day_tomorrow">Tomorrow</string>
@@ -736,7 +738,6 @@
<string name="settings_calendar_notifications">Notifications</string>
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
<string name="settings_calendar_notifications_off">Notifications off</string>
<string name="settings_calendar_reminders_off">Reminders off</string>
<string name="settings_notification_sound">Notification sound</string>
<string name="settings_notification_sound_hint">Sound, vibration and pop-ups for each calendar, in system settings</string>
<string name="settings_notifications_blocked">Blocked in system settings</string>
@@ -744,44 +745,22 @@
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
<string name="settings_notification_category_hint_open">Open settings</string>
<string name="settings_calendar_notification_sound_hint">Sound, vibration and pop-ups for this calendar, in system settings</string>
<string name="settings_alert_style">Alert style</string>
<string name="settings_alert_style_notification">Notification</string>
<string name="settings_alert_style_notification_summary">A notification that pops up and waits in the shade</string>
<string name="settings_alert_style_full_screen">Full-screen alert</string>
<string name="settings_alert_style_full_screen_summary">Fills the screen, even on the lock screen, until you dismiss or snooze it</string>
<string name="settings_alert_sound">Full-screen sound</string>
<string name="settings_alert_sound_once">Play sound once</string>
<string name="settings_alert_sound_once_summary">This calendar\'s notification sound, once</string>
<string name="settings_alert_sound_ring">Ring until dismissed</string>
<string name="settings_alert_sound_ring_summary">Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound</string>
<string name="settings_calendar_notification_sound_ring_hint">Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade.</string>
<string name="settings_full_screen_held_back">Full-screen alerts held back</string>
<string name="settings_ring_blocked_hint">Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow</string>
<string name="settings_full_screen_permission">Allow full-screen alerts</string>
<string name="settings_full_screen_permission_hint">Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them.</string>
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
<!-- Reminders at a set time (#459). %1$s is a lead in days ("1 day before"), %2$s a clock time. -->
<string name="reminder_fixed_time">%1$s at %2$s</string>
<string name="reminder_fixed_at_set_time">At a set time</string>
<!-- Read as one sentence with a number field before it and a time after it: "[2] days before, at [20:00]". The full wording shows below it. -->
<string name="reminder_fixed_days_before_at">days before, at</string>
<string name="reminder_fixed_days_range">Pick 1 to %1$d days</string>
<string name="settings_fixed_reminder">Reminder at a set time</string>
<string name="event_edit_reminder_fixed_summary">E.g. the evening before</string>
<string name="event_edit_reminder_fixed_hint">Fires at this time however early or late the event starts, and moves along when you change the event\'s time.</string>
<string name="settings_fixed_reminder_hint">Added to new timed events, e.g. the evening before. It follows the event when you move it to another time.</string>
<!-- Daily summary notification (#459) -->
<string name="settings_digest">Daily summary</string>
<string name="settings_digest_hint">One notification listing a day\'s events</string>
<!-- %1$s is settings_digest_day_today/tomorrow, %2$s a clock time. -->
<string name="settings_digest_summary">%1$s at %2$s</string>
<string name="settings_digest_day">Lists</string>
<string name="settings_digest_day_today">Today\'s events</string>
<string name="settings_digest_day_tomorrow">Tomorrow\'s events</string>
<string name="settings_digest_time">Time</string>
<string name="settings_digest_sound_hint">Sound and pop-up for the summary, in system settings</string>
<string name="settings_calendar_in_digest">In daily summary</string>
<string name="settings_calendar_in_digest_hint">List this calendar\'s events in the daily summary</string>
<string name="digest_channel_name">Daily summary</string>
<string name="digest_channel_description">One notification listing a day\'s events</string>
<!-- %1$s is "Today", "Tomorrow" or a date; %2$d the number of events. -->
<plurals name="digest_title">
<item quantity="one">%1$s: %2$d event</item>
<item quantity="other">%1$s: %2$d events</item>
</plurals>
<!-- %1$s is "Today" or "Tomorrow", %2$s a short date, e.g. "Fri, 14 Nov". -->
<string name="digest_day_relative">%1$s, %2$s</string>
<!-- One event in the summary: %1$s its time ("09:00 – 10:00" or "All day"), %2$s its title. -->
<string name="digest_line">%1$s · %2$s</string>
<plurals name="digest_more">
<item quantity="one">+%d more</item>
<item quantity="other">+%d more</item>
</plurals>
<string name="settings_reliable_delivery">Reliable delivery</string>
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
<string name="settings_reliable_delivery_exempt">Exempt from battery optimisation — reminders arrive on time.</string>
@@ -10,9 +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.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
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
@@ -617,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,
@@ -721,62 +731,4 @@ class SettingsPrefsTest {
prefs.recordSpecialDatesRun(2000L, null)
assertThat(prefs.specialDatesStatus.first()).isEqualTo(SpecialDatesStatus(2000L, null))
}
@Test
fun `fixed-time reminder defaults to off and round-trips`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.defaultFixedTimeReminder.first()).isNull()
val evening = FixedTimeReminder(1, 1_200)
prefs.setDefaultFixedTimeReminder(evening)
assertThat(prefs.defaultFixedTimeReminder.first()).isEqualTo(evening)
prefs.setDefaultFixedTimeReminder(null)
assertThat(prefs.defaultFixedTimeReminder.first()).isNull()
}
@Test
fun `per-calendar fixed-time overrides keep inherit, off and a value apart`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
val morning = FixedTimeReminder(2, 480)
prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200))
prefs.setCalendarFixedTimeReminderOverride(1L, FixedTimeOverride.Off)
prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.At(morning))
val overrides = prefs.perCalendarFixedTimeReminderOverride.first()
assertThat(overrides.fixedTimeOverrideFor(1L)).isEqualTo(FixedTimeOverride.Off)
assertThat(overrides.fixedTimeOverrideFor(2L)).isEqualTo(FixedTimeOverride.At(morning))
assertThat(overrides.fixedTimeOverrideFor(3L)).isEqualTo(FixedTimeOverride.Inherit)
assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 1L)).isNull()
assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 3L))
.isEqualTo(FixedTimeReminder(1, 1_200))
assertThat(prefs.knownFixedTimeReminders.first()).containsExactly(FixedTimeReminder(1, 1_200), morning)
val picked = FixedTimeReminder(3, 600)
prefs.rememberFixedTimeReminders(listOf(picked, morning))
assertThat(prefs.knownFixedTimeReminders.first()).contains(picked)
// A default already known takes no recents slot.
assertThat(prefs.knownFixedTimeReminders.first()).hasSize(3)
// A replaced default stays known.
prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_140))
assertThat(prefs.knownFixedTimeReminders.first()).contains(FixedTimeReminder(1, 1_200))
prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Inherit)
assertThat(prefs.perCalendarFixedTimeReminderOverride.first().containsKey(2L)).isFalse()
}
@Test
fun `daily summary is off by default and its settings round-trip`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.dailyDigest.first()).isEqualTo(DailyDigestSettings())
prefs.setDailyDigestEnabled(true)
prefs.setDailyDigestTimeMinutes(420)
prefs.setDailyDigestDay(DigestDay.Today)
prefs.setCalendarInDailyDigest(5L, included = false)
val digest = prefs.dailyDigest.first()
assertThat(digest.copy(armedAtMillis = 0L)).isEqualTo(
DailyDigestSettings(enabled = true, timeMinutes = 420, day = DigestDay.Today, excludedCalendarIds = setOf(5L)),
)
assertThat(digest.armedAtMillis).isGreaterThan(0L)
prefs.setCalendarInDailyDigest(5L, included = true)
assertThat(prefs.dailyDigest.first().excludedCalendarIds).isEmpty()
}
}
@@ -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"
}
@@ -1,47 +0,0 @@
package de.jeanlucmakiola.calendula.domain
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import org.junit.jupiter.api.Test
class FixedTimeReminderFormTest {
private val zone = TimeZone.of("Europe/Berlin")
private val evening = FixedTimeReminder(1, 20 * 60)
private fun form(start: String, reminders: List<Int> = emptyList(), allDay: Boolean = false) = EventForm(
calendarId = 1,
isAllDay = allDay,
start = FormTime(LocalDateTime.parse(start)),
end = FormTime(LocalDateTime.parse(start)),
reminders = reminders,
)
@Test
fun `a moved start re-derives the offset so the wall clock stays`() {
val loaded = form("2026-06-10T10:00", reminders = listOf(10, 840))
.withFixedTimeRemindersRead(known = setOf(evening), deviceZone = zone)
assertThat(loaded.reminders).containsExactly(10)
assertThat(loaded.fixedReminders).containsExactly(evening)
assertThat(loaded.fixedReminderOffsets(zone)).containsExactly(840)
val moved = loaded.copy(start = FormTime(LocalDateTime.parse("2026-06-10T15:30")))
assertThat(moved.fixedReminderOffsets(zone)).containsExactly(19 * 60 + 30)
}
@Test
fun `all-day forms keep their reminders and store no fixed ones`() {
val allDay = form("2026-06-10T00:00", reminders = listOf(840), allDay = true)
assertThat(allDay.withFixedTimeRemindersRead(setOf(evening), zone)).isEqualTo(allDay)
assertThat(allDay.copy(fixedReminders = listOf(evening)).fixedReminderOffsets(zone)).isEmpty()
}
@Test
fun `fixed reminders count as a populated reminders section on a timed event only`() {
val withFixed = form("2026-06-10T10:00").copy(fixedReminders = listOf(evening))
assertThat(withFixed.populatedFields()).contains(EventFormField.Reminders)
assertThat(withFixed.copy(isAllDay = true).populatedFields()).doesNotContain(EventFormField.Reminders)
}
}
@@ -1,89 +0,0 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
class DailyDigestTest {
private val zone = ZoneId.of("Europe/Berlin")
private val minute = 60_000L
private val eight = 20 * 60
private fun millis(text: String): Long = LocalDateTime.parse(text).atZone(zone).toInstant().toEpochMilli()
@Test
fun `due once the moment passes the watermark`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T19:59"), millis("2026-06-10T20:00"))
assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11))
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T20:00"))
}
@Test
fun `a second scan does not post again`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T20:00"), millis("2026-06-10T20:05"))
assertThat(schedule.dueDay).isNull()
}
@Test
fun `a day already listed is not listed again`() {
// Posted at 20:00, then the time moved to 21:00 the same evening.
val schedule = scheduleDigest(
21 * 60, DigestDay.Tomorrow, zone, millis("2026-06-10T20:30"), millis("2026-06-10T21:00"),
lastListedDay = LocalDate.of(2026, 6, 11),
)
assertThat(schedule.dueDay).isNull()
}
@Test
fun `before the moment it only arms the alarm`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T08:00"), millis("2026-06-10T09:00"))
assertThat(schedule.dueDay).isNull()
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-10T20:00"))
}
@Test
fun `a late catch-up still lists a day that has not passed`() {
// Off overnight: last scan before 20:00, back on the next morning.
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T18:00"), millis("2026-06-11T07:00"))
assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11))
}
@Test
fun `a today summary missed until the next day is dropped`() {
val seven = 7 * 60
val schedule = scheduleDigest(seven, DigestDay.Today, zone, millis("2026-06-10T06:00"), millis("2026-06-11T06:30"))
assertThat(schedule.dueDay).isNull()
assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T07:00"))
}
@Test
fun `entries list all-day first, keep the day's own, and skip excluded calendars`() {
val day = LocalDate.of(2026, 6, 11)
val utcMidnight = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
val allDay = instance(1, utcMidnight, utcMidnight + 24 * 60 * minute, isAllDay = true)
val previousAllDay = instance(2, utcMidnight - 24 * 60 * minute, utcMidnight, isAllDay = true)
val morning = instance(3, millis("2026-06-11T09:00"), millis("2026-06-11T10:00"))
val early = instance(4, millis("2026-06-11T07:00"), millis("2026-06-11T08:00"))
val nextDay = instance(5, millis("2026-06-12T00:00"), millis("2026-06-12T01:00"))
val excluded = instance(6, millis("2026-06-11T12:00"), millis("2026-06-11T13:00"), calendarId = 9)
val entries = digestEntries(
listOf(morning, previousAllDay, nextDay, early, allDay, excluded),
day,
zone,
excludedCalendarIds = setOf(9),
)
assertThat(entries.map { it.eventId }).containsExactly(1L, 4L, 3L).inOrder()
}
private fun instance(
eventId: Long,
begin: Long,
end: Long,
isAllDay: Boolean = false,
calendarId: Long = 1,
) = ReminderEventInstance(eventId, calendarId, begin, end, "Event $eventId", null, isAllDay)
}
@@ -1,100 +0,0 @@
package de.jeanlucmakiola.calendula.domain.reminders
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import org.junit.jupiter.api.Test
import kotlin.time.Instant
class FixedTimeReminderTest {
private val berlin = TimeZone.of("Europe/Berlin")
private val eveningBefore = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60)
private fun at(text: String, zone: TimeZone = berlin): Instant = LocalDateTime.parse(text).toInstant(zone)
@Test
fun `offset is the distance from the named wall clock to the start`() {
assertThat(eveningBefore.offsetMinutes(at("2026-06-10T10:00"), berlin)).isEqualTo(14 * 60)
assertThat(eveningBefore.offsetMinutes(at("2026-06-10T21:30"), berlin)).isEqualTo(25 * 60 + 30)
}
@Test
fun `offset spans a DST change in real minutes`() {
// Clocks go forward on 29 March 2026: 20:00 on the 28th to 10:00 on the 29th is 13 hours.
assertThat(eveningBefore.offsetMinutes(at("2026-03-29T10:00"), berlin)).isEqualTo(13 * 60)
}
@Test
fun `a series offset counts clock minutes, so a DST-side occurrence bakes in no hour`() {
// Opened on the Sunday clocks go back: the real span is 15 hours, the clock face says 14.
val start = at("2026-10-25T10:00")
assertThat(eveningBefore.offsetMinutes(start, berlin)).isEqualTo(15 * 60)
val offset = eveningBefore.offsetMinutes(start, berlin, wallClock = true)
assertThat(offset).isEqualTo(14 * 60)
// Read back the same way on any occurrence of the series.
assertThat(fixedTimeReminderAt(offset, at("2026-11-01T10:00"), berlin, wallClock = true)).isEqualTo(eveningBefore)
assertThat(fixedTimeReminderAt(offset, start, berlin, wallClock = true)).isEqualTo(eveningBefore)
}
@Test
fun `an offset reads back as the pattern it was written from`() {
val start = at("2026-03-29T10:00")
val offset = eveningBefore.offsetMinutes(start, berlin)
assertThat(fixedTimeReminderAt(offset, start, berlin)).isEqualTo(eveningBefore)
}
@Test
fun `a reminder on the start's own day or after it is no pattern`() {
val start = at("2026-06-10T10:00")
assertThat(fixedTimeReminderAt(60, start, berlin)).isNull()
assertThat(fixedTimeReminderAt(0, start, berlin)).isNull()
assertThat(fixedTimeReminderAt(-30, start, berlin)).isNull()
}
@Test
fun `only known patterns read as fixed-time`() {
val start = at("2026-06-10T10:00")
// 840 is "1 day before at 20:00" here, but also a plain "14 hours before".
val unknown = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = emptySet())
assertThat(unknown.leadMinutes).containsExactly(10, 840, 1_440).inOrder()
assertThat(unknown.fixed).isEmpty()
val known = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = setOf(eveningBefore))
assertThat(known.leadMinutes).containsExactly(10, 1_440).inOrder()
assertThat(known.fixed).containsExactly(eveningBefore)
}
@Test
fun `a whole-day offset landing on a known pattern is fixed-time`() {
// An event at 20:00 with "1 day before at 20:00" stores exactly a day.
val start = at("2026-06-10T20:00")
assertThat(splitTimedReminders(listOf(1_440), start, berlin, known = emptySet()).fixed).isEmpty()
val split = splitTimedReminders(listOf(1_440), start, berlin, known = setOf(eveningBefore))
assertThat(split.fixed).containsExactly(eveningBefore)
assertThat(split.leadMinutes).isEmpty()
}
@Test
fun `fixed reminders sort by when they fire`() {
val start = at("2026-06-10T10:00")
val twoDays = FixedTimeReminder(2, 9 * 60)
val split = splitTimedReminders(
listOf(eveningBefore.offsetMinutes(start, berlin), twoDays.offsetMinutes(start, berlin)),
start,
berlin,
known = setOf(eveningBefore, twoDays),
)
assertThat(split.fixed).containsExactly(twoDays, eveningBefore).inOrder()
}
@Test
fun `token round-trips and rejects garbage`() {
assertThat(FixedTimeReminder.parse(eveningBefore.toToken())).isEqualTo(eveningBefore)
assertThat(FixedTimeReminder.parse("0@600")).isNull()
assertThat(FixedTimeReminder.parse("1@1440")).isNull()
assertThat(FixedTimeReminder.parse("x")).isNull()
assertThat(FixedTimeReminder.parse(null)).isNull()
}
}
@@ -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()
}
}
@@ -92,13 +92,12 @@ class RescheduleViewModelTest {
io: CoroutineDispatcher = dispatcher,
): RescheduleViewModel {
fake.occurrencesAt(present)
val settings = testSettings(tempDir, CoroutineScope(dispatcher))
val repo = testRepository(
fake, tempDir, io,
prefs = testPrefs(tempDir, CoroutineScope(dispatcher)),
settings = settings,
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
)
return RescheduleViewModel(repo, io, FakeZoneSource(), settings)
return RescheduleViewModel(repo, io, FakeZoneSource())
}
private fun slowViewModel(tempDir: Path, fake: FakeCalendarDataSource): RescheduleViewModel =
@@ -51,14 +51,13 @@ class EventDetailViewModelTest {
)
private fun viewModel(tempDir: Path, fake: FakeCalendarDataSource): EventDetailViewModel {
val settings = testSettings(tempDir, CoroutineScope(dispatcher))
val repo = testRepository(
fake, tempDir, dispatcher,
prefs = testPrefs(tempDir, CoroutineScope(dispatcher)),
settings = settings,
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
)
// Only `shareUri()` touches the exporter, and nothing here shares.
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource(), settings)
return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource())
}
private fun fakeSource(description: () -> String?) = FakeCalendarDataSource().apply {
@@ -9,11 +9,7 @@ import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.FakeZoneSource
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.ReminderMethod
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
@@ -723,121 +719,4 @@ class EventEditViewModelTest {
assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Idle)
job.cancel()
}
@Test
fun `a new timed event gets the fixed-time default, and a calendar can turn it off`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
val evening = FixedTimeReminder(1, 1_200)
s.setDefaultFixedTimeReminder(evening)
s.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Off)
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders).containsExactly(evening)
vm.setCalendar(2L)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders).isEmpty()
job.cancel()
}
@Test
fun `an event's set-time reminder opens as one and saves without a conflict`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val zone = FakeZoneSource().current()
val start = Instant.fromEpochMilliseconds(beginMillis)
val evening = FixedTimeReminder(1, 1_200)
val offset = evening.offsetMinutes(start, zone)
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L))
eventDetailResult = {
detail(calendarId = 1L).copy(reminders = listOf(Reminder(offset, ReminderMethod.Alert)))
}
}
val s = settings(tempDir)
s.setDefaultFixedTimeReminder(evening)
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openForEdit(eventId = 42L, beginMillis = beginMillis, endMillis = endMillis)
advanceUntilIdle()
val form = vm.state.value!!.form!!
assertThat(form.fixedReminders).containsExactly(evening)
assertThat(form.reminders).isEmpty()
assertThat(vm.hasUnsavedChanges.value).isFalse()
vm.setTitle("Renamed")
vm.save()
advanceUntilIdle()
assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Saved)
assertThat(fake.updatedEvents.single().third.fixedReminders).containsExactly(evening)
job.cancel()
}
@Test
fun `a round trip through all-day keeps set-time reminders`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600)
advanceUntilIdle()
vm.addFixedReminder(FixedTimeReminder(2, 480))
vm.setAllDay(true)
vm.setAllDay(false)
advanceUntilIdle()
assertThat(vm.state.value!!.form!!.fixedReminders)
.containsExactly(FixedTimeReminder(2, 480), FixedTimeReminder(1, 1_200))
job.cancel()
}
@Test
fun `a set-time reminder replaces a lead firing at the same moment`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultReminderMinutes(listOf(1_440, 10))
val vm = viewModel(tempDir, fake, s, zones = FakeZoneSource(berlin))
val job = activate(vm)
vm.openNew(LocalDate(2030, 1, 15), startMinutes = 20 * 60)
advanceUntilIdle()
vm.addFixedReminder(FixedTimeReminder(1, 20 * 60))
val form = vm.state.value!!.form!!
assertThat(form.reminders).containsExactly(10)
assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 20 * 60))
job.cancel()
}
@Test
fun `a copy carrying only set-time reminders keeps them`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) }
val s = settings(tempDir)
s.setDefaultReminderMinutes(listOf(15))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
val copy = importedForm(end = LocalDateTime(2030, 1, 15, 10, 0))
.copy(reminders = emptyList(), fixedReminders = listOf(FixedTimeReminder(1, 1_200)))
vm.openImported(copy, ImportSource.Insert)
advanceUntilIdle()
val form = vm.state.value!!.form!!
assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 1_200))
assertThat(form.reminders).isEmpty()
job.cancel()
}
}
+25 -44
View File
@@ -411,50 +411,31 @@ 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.
**Reminders at a set time (#459).** "1 day before at 20:00" on a timed event
is an ordinary `Reminders` row whose offset is the distance from that wall-clock
moment (device zone) to the start, so it syncs and fires everywhere — the scan
plans it like any lead time. Only the editor knows it as a pattern
(`EventForm.fixedReminders`), and it re-derives the offset from the start it
saves with, so moving the event, in the form or by drag, keeps the wall clock.
Reading a row back is a guess, made in one place (`classifyTimedReminder`): an
offset is fixed-time only when it lands on a known pattern — a current or
replaced default, or one saved by hand on this device
(`recentFixedTimeReminders`, capped). Guessing from the offset's shape alone
would turn ordinary leads ("12 hours before") into fixed ones. Limits: where a
lead and a known pattern coincide ("1 day before" on an event at the default's
own time) the pattern wins, and a pattern that falls out of the recents reads as
a lead again — either way the alarm fires at the same moment until the start's
time of day changes. A recurring series stores one offset for all occurrences,
so it counts clock minutes rather than real ones (`wallClock`); the occurrence
whose lead spans a DST change then fires an hour off, as in every other app
reading that row. On another device or app the row is simply a lead time.
New timed events get the default (`SettingsKeys.defaultFixedTimeReminder`, with
a per-calendar inherit/off/value override) like the lead-time defaults.
**The daily summary (#459)** rides the same scan and watermark: its moment is
due when it falls in `(lastScan, now]` (`scheduleDigest`), only the latest one
counts after a long gap, and it is dropped once the day it lists has passed.
It is independent of the event-reminder switch, posts on its own channel
(`DailyDigestNotifier`), lists switched-on calendars minus its own exclusions,
and replaces the previous summary — or withdraws it when the day is empty.
Each day is listed once: the day is recorded as soon as it is posted
(`ReminderStatePrefs.lastDigestDay`), so neither a pass failing later nor a later
time picked the same evening lists it twice, and changing the switch, time or
day stamps `dailyDigestArmedAt`, so a moment that passed before the change is
not owed by it. A failing summary is logged and skipped; it never costs the
event reminders of the same pass, and a failing reminder pass still arms a retry
and the summary's next moment. Switching between "today's" and "tomorrow's"
events clears the day last listed, so the first summary of the new mode comes.
The notification names its date and times out when that day ends.
Its channel's blocked state is read separately (`DailyDigestNotifier.isChannelOff`,
with the app-wide block from `ReminderChannels.status`); while it is off the
scan neither posts nor records the day, so allowing it brings the summary back.
The channel is created when the summary is switched on, so a phone that starts
new categories off shows it blocked in settings before the first summary.
The per-calendar reminder mute does not apply: a calendar too noisy to ping per
event can still belong in the overview, and the summary has its own
per-calendar switch next to it.
**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 —
+2 -3
View File
@@ -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