fix(#459): review round 1 — known patterns only, one summary per day, keep set-time reminders through all-day and copies
This commit is contained in:
1 parent
c28582ae6f
commit
589f2c3862
17 files changed
+223
-113
No files matched your search
@@ -4,6 +4,8 @@ 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
|
||||
|
||||
@@ -27,7 +29,13 @@ class ReminderStatePrefs @Inject constructor(
|
||||
|
||||
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
|
||||
|
||||
/** The day the last daily summary listed (#459), so a re-run scan never posts 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())
|
||||
|
||||
private companion object {
|
||||
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
|
||||
val LAST_DIGEST_DAY = nullableStringPref("reminder_last_digest_day")
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
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
|
||||
@@ -190,7 +192,8 @@ class SettingsPrefs @Inject constructor(
|
||||
*/
|
||||
val knownFixedTimeReminders: Flow<Set<FixedTimeReminder>> = prefs.snapshot {
|
||||
setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() +
|
||||
it[SettingsKeys.recentFixedTimeReminders]
|
||||
}
|
||||
val dailyDigest: Flow<DailyDigestSettings> = prefs.snapshot { it.dailyDigest }
|
||||
val autoBackupEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupEnabled)
|
||||
@@ -359,12 +362,28 @@ class SettingsPrefs @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setDailyDigestEnabled(enabled: Boolean) = prefs.set(SettingsKeys.dailyDigestEnabled, enabled)
|
||||
suspend fun setDailyDigestEnabled(enabled: Boolean) = editDigest { it[SettingsKeys.dailyDigestEnabled] = enabled }
|
||||
|
||||
suspend fun setDailyDigestTimeMinutes(minutesOfDay: Int) =
|
||||
prefs.set(SettingsKeys.dailyDigestTimeMinutes, minutesOfDay)
|
||||
editDigest { it[SettingsKeys.dailyDigestTimeMinutes] = minutesOfDay }
|
||||
|
||||
suspend fun setDailyDigestDay(day: DigestDay) = prefs.set(SettingsKeys.dailyDigestDay, day)
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
/** Remember a fixed-time reminder picked by hand, so it reads back as one later (#459). */
|
||||
suspend fun addRecentFixedTimeReminder(reminder: FixedTimeReminder) {
|
||||
prefs.update(SettingsKeys.recentFixedTimeReminders) { (listOf(reminder) + it).distinct() }
|
||||
}
|
||||
|
||||
suspend fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) {
|
||||
prefs.update(SettingsKeys.digestExcludedCalendarIds) { if (included) it - calendarId else it + calendarId }
|
||||
@@ -419,8 +438,7 @@ 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
|
||||
/** 20:00, when the daily summary arrives until changed. */
|
||||
internal const val DEFAULT_DIGEST_TIME = 1_200
|
||||
internal const val MAX_RECENT_FIXED_TIME_REMINDERS = 5
|
||||
/** Default snooze delay for the notification "Snooze" action. */
|
||||
const val DEFAULT_SNOOZE_MINUTES = 10
|
||||
const val DEFAULT_MULTI_DAY_COUNT = 3
|
||||
@@ -757,7 +775,7 @@ object SettingsKeys {
|
||||
/** 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", SettingsPrefs.DEFAULT_DIGEST_TIME).coerced {
|
||||
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)
|
||||
@@ -765,6 +783,19 @@ object SettingsKeys {
|
||||
/** 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 picked by hand in the editor, newest first —
|
||||
* with the defaults, the patterns a stored offset is recognised as.
|
||||
*/
|
||||
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)
|
||||
|
||||
@@ -968,6 +999,7 @@ internal val Preferences.dailyDigest: DailyDigestSettings
|
||||
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. */
|
||||
|
||||
+8
-20
@@ -1,22 +1,18 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
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.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.datetime.toKotlinLocalDate
|
||||
import java.time.DayOfWeek
|
||||
@@ -36,23 +32,13 @@ import javax.inject.Singleton
|
||||
class DailyDigestNotifier @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
) {
|
||||
|
||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||
fun canPost(): Boolean {
|
||||
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
|
||||
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Post the summary of [day] listing [entries], or withdraw the last one when
|
||||
* 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, entries: List<ReminderEventInstance>) {
|
||||
val switchedOff = calendarPrefs.pendingDisabledCalendarIds.first()
|
||||
val listed = entries.filter { it.calendarId !in switchedOff }
|
||||
suspend fun post(day: LocalDate, listed: List<ReminderEventInstance>) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
if (listed.isEmpty()) {
|
||||
manager.cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||
@@ -69,8 +55,11 @@ class DailyDigestNotifier @Inject constructor(
|
||||
today.plusDays(1) -> context.getString(R.string.reminder_day_tomorrow)
|
||||
else -> DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale).format(day)
|
||||
}
|
||||
val allDay = context.getString(R.string.event_detail_all_day)
|
||||
val lines = listed.map { entry ->
|
||||
val time = reminderTimeText(
|
||||
// Read against the listed day, so a timed event on it shows its bare
|
||||
// range and one crossing midnight its dates; the week start never shows.
|
||||
val time = if (entry.isAllDay) allDay else reminderTimeText(
|
||||
beginMillis = entry.beginMillis,
|
||||
endMillis = entry.endMillis,
|
||||
isAllDay = entry.isAllDay,
|
||||
@@ -78,9 +67,8 @@ class DailyDigestNotifier @Inject constructor(
|
||||
locale = locale,
|
||||
is24Hour = is24Hour,
|
||||
today = day,
|
||||
// Only cross-day spans name a date, so the week start never shows.
|
||||
firstDayOfWeek = DayOfWeek.MONDAY,
|
||||
todayLabel = context.getString(R.string.event_detail_all_day),
|
||||
todayLabel = allDay,
|
||||
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
@@ -115,9 +103,9 @@ class DailyDigestNotifier @Inject constructor(
|
||||
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)
|
||||
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
|
||||
@@ -6,6 +6,7 @@ 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
|
||||
@@ -51,6 +52,7 @@ class ReminderScanner @Inject constructor(
|
||||
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,
|
||||
) {
|
||||
@@ -138,17 +140,30 @@ class ReminderScanner @Inject constructor(
|
||||
*/
|
||||
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val schedule = scheduleDigest(settings.timeMinutes, settings.day, zone, lastFired, now)
|
||||
val schedule = scheduleDigest(
|
||||
timeMinutes = settings.timeMinutes,
|
||||
day = settings.day,
|
||||
zone = zone,
|
||||
// A moment that passed before the summary was set up is not owed.
|
||||
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
|
||||
nowMillis = now,
|
||||
lastPostedDay = state.lastDigestDay(),
|
||||
)
|
||||
val day = schedule.dueDay ?: return schedule.nextAlarmMillis
|
||||
// A failed summary must not cost the event reminders this pass owes.
|
||||
if (digestNotifier.canPost()) runCatching {
|
||||
// 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 entries = digestEntries(source.occurrences(from, to), day, zone, settings.excludedCalendarIds)
|
||||
digestNotifier.post(day, entries)
|
||||
}.onFailure { Log.w(TAG, "Daily summary failed", it) }
|
||||
if (notifier.canPost()) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,8 @@ data class EventForm(
|
||||
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. Always empty on an all-day event.
|
||||
* 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,
|
||||
@@ -293,7 +294,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() || fixedReminders.isNotEmpty()) add(EventFormField.Reminders)
|
||||
if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders)
|
||||
if (rrule != null) add(EventFormField.Recurrence)
|
||||
if (availability != Availability.Busy) add(EventFormField.Availability)
|
||||
if (status != EventStatus.Confirmed) add(EventFormField.Status)
|
||||
|
||||
@@ -9,12 +9,19 @@ 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) }
|
||||
|
||||
/** The daily summary's settings. Calendars in [excludedCalendarIds] are left out of it. */
|
||||
/** 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 = 1_200,
|
||||
val timeMinutes: Int = DEFAULT_DIGEST_TIME_MINUTES,
|
||||
val day: DigestDay = DigestDay.Tomorrow,
|
||||
val excludedCalendarIds: Set<Long> = emptySet(),
|
||||
val armedAtMillis: Long = 0L,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -30,7 +37,8 @@ data class DigestSchedule(
|
||||
* When the summary is owed, measured against the same watermark as the event
|
||||
* reminders: 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.
|
||||
* three — and only while the day it lists has not passed and is not
|
||||
* [lastPostedDay], so a pass that failed after posting can't post it again.
|
||||
*/
|
||||
fun scheduleDigest(
|
||||
timeMinutes: Int,
|
||||
@@ -38,13 +46,16 @@ fun scheduleDigest(
|
||||
zone: ZoneId,
|
||||
lastFiredMillis: Long,
|
||||
nowMillis: Long,
|
||||
lastPostedDay: 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 dueDay = listed.takeIf { fireAt(latestDate) > lastFiredMillis && !it.isBefore(today) }
|
||||
val dueDay = listed.takeIf {
|
||||
fireAt(latestDate) > lastFiredMillis && !it.isBefore(today) && it != lastPostedDay
|
||||
}
|
||||
return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
|
||||
}
|
||||
|
||||
|
||||
+18
-24
@@ -16,7 +16,7 @@ import kotlin.time.Instant
|
||||
* 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 ([splitTimedReminders]); the
|
||||
* 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) {
|
||||
@@ -41,7 +41,6 @@ data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) {
|
||||
|
||||
companion object {
|
||||
const val MAX_DAYS_BEFORE = 28
|
||||
private const val MINUTES_PER_DAY = 1_440
|
||||
private const val TOKEN_SEP = "@"
|
||||
|
||||
/** [toToken] read back; null for anything malformed or out of range. */
|
||||
@@ -77,35 +76,33 @@ data class TimedReminders(
|
||||
)
|
||||
|
||||
/**
|
||||
* Sort a timed event's raw offsets into lead times and "N days before at HH:MM"
|
||||
* reminders. The provider can't say which an offset was meant as, so:
|
||||
*
|
||||
* - one landing on a pattern in [known] (the configured defaults) is fixed-time;
|
||||
* - otherwise one reaching back past the start's own day is fixed-time, unless it
|
||||
* is a whole number of days or one of [plainLeadMinutes] — those read as the
|
||||
* lead time they look like.
|
||||
*
|
||||
* The cost of guessing wrong is small: the reminder fires at the same moment
|
||||
* either way, and only a later change of the start's time of day treats it
|
||||
* differently. A hand-entered "3 hours before" on an event at 01:00 does read as
|
||||
* "1 day before at 22:00".
|
||||
* 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 and the ones picked 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. A wrong reading never moves an alarm; it only changes
|
||||
* what a later edit of the start's time does.
|
||||
*/
|
||||
fun classifyTimedReminder(
|
||||
offsetMinutes: Int,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
known: Set<FixedTimeReminder>,
|
||||
): FixedTimeReminder? = fixedTimeReminderAt(offsetMinutes, start, zone)?.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>,
|
||||
plainLeadMinutes: Collection<Int> = PLAIN_LEAD_MINUTES,
|
||||
): TimedReminders {
|
||||
val leads = mutableListOf<Int>()
|
||||
val fixed = mutableListOf<FixedTimeReminder>()
|
||||
offsets.distinct().forEach { offset ->
|
||||
val pattern = fixedTimeReminderAt(offset, start, zone)
|
||||
val isFixed = pattern != null && (
|
||||
pattern in known ||
|
||||
(offset % MINUTES_PER_DAY != 0 && offset !in plainLeadMinutes)
|
||||
)
|
||||
if (isFixed) fixed += pattern!! else leads += offset
|
||||
val pattern = classifyTimedReminder(offset, start, zone, known)
|
||||
if (pattern != null) fixed += pattern else leads += offset
|
||||
}
|
||||
return TimedReminders(leads.sorted(), fixed.distinct().sortedWith(FIXED_ORDER))
|
||||
}
|
||||
@@ -114,7 +111,4 @@ fun splitTimedReminders(
|
||||
val FIXED_ORDER: Comparator<FixedTimeReminder> =
|
||||
compareByDescending<FixedTimeReminder> { it.daysBefore }.thenBy { it.minuteOfDay }
|
||||
|
||||
/** Lead times offered as presets: always read as what they look like. */
|
||||
private val PLAIN_LEAD_MINUTES = setOf(5, 10, 15, 30, 45, 60, 90, 120)
|
||||
|
||||
private const val MINUTES_PER_DAY = 1_440
|
||||
@@ -1,7 +1,7 @@
|
||||
package de.jeanlucmakiola.calendula.ui.detail
|
||||
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.classifyTimedReminder
|
||||
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
@@ -169,8 +169,7 @@ class EventDetailViewModel @Inject constructor(
|
||||
} else {
|
||||
val zone = zoneSource.current()
|
||||
corrected.reminders.map { it.minutes }.distinct().mapNotNull { minutes ->
|
||||
splitTimedReminders(listOf(minutes), corrected.instance.start, zone, knownFixed)
|
||||
.fixed.firstOrNull()?.let { minutes to it }
|
||||
classifyTimedReminder(minutes, corrected.instance.start, zone, knownFixed)?.let { minutes to it }
|
||||
}.toMap()
|
||||
}
|
||||
val description = corrected.description
|
||||
|
||||
@@ -880,7 +880,7 @@ private fun EventEditContent(
|
||||
Spacer(Modifier.height(gap))
|
||||
RemindersSection(
|
||||
reminders = form.reminders,
|
||||
fixedReminders = form.fixedReminders,
|
||||
fixedReminders = if (form.isAllDay) emptyList() else form.fixedReminders,
|
||||
onRemove = viewModel::removeReminder,
|
||||
onRemoveFixed = viewModel::removeFixedReminder,
|
||||
onAdd = { sheet = EditSheet.Reminder },
|
||||
|
||||
@@ -448,7 +448,7 @@ class EventEditViewModel @Inject constructor(
|
||||
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
|
||||
when (source) {
|
||||
ImportSource.Insert, ImportSource.InsertOpenEnded ->
|
||||
if (form.reminders.isNotEmpty()) _remindersTouched.value = true
|
||||
if (form.reminders.isNotEmpty() || form.fixedReminders.isNotEmpty()) _remindersTouched.value = true
|
||||
else applyDefaultReminder()
|
||||
|
||||
ImportSource.File -> {
|
||||
@@ -491,14 +491,21 @@ class EventEditViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
/** Snapshot the settings-default reminder flows into one value. */
|
||||
private suspend fun reminderDefaults(): ReminderDefaults = ReminderDefaults(
|
||||
timed = settingsPrefs.defaultReminderMinutes.first(),
|
||||
allDay = settingsPrefs.defaultAllDayReminderMinutes.first(),
|
||||
timedOverrides = settingsPrefs.perCalendarReminderOverride.first(),
|
||||
allDayOverrides = settingsPrefs.perCalendarAllDayReminderOverride.first(),
|
||||
fixed = settingsPrefs.defaultFixedTimeReminder.first(),
|
||||
fixedOverrides = settingsPrefs.perCalendarFixedTimeReminderOverride.first(),
|
||||
)
|
||||
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)
|
||||
}.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
|
||||
@@ -658,11 +665,7 @@ class EventEditViewModel @Inject constructor(
|
||||
// A kept pass of a repeated hour stays, so switching back out of all-day
|
||||
// lands where the event was — unless dropping the pin changed the zone.
|
||||
edit {
|
||||
if (value) {
|
||||
it.withTimezone(null, zoneSource.current()).copy(isAllDay = true, fixedReminders = emptyList())
|
||||
} else {
|
||||
it.copy(isAllDay = false)
|
||||
}
|
||||
if (value) it.withTimezone(null, zoneSource.current()).copy(isAllDay = true) else it.copy(isAllDay = false)
|
||||
}
|
||||
// The default reminder differs for all-day vs timed; re-apply the
|
||||
// type-appropriate default unless the user has hand-edited it (guarded).
|
||||
@@ -728,6 +731,8 @@ class EventEditViewModel @Inject constructor(
|
||||
edit {
|
||||
if (it.isAllDay) it else it.copy(fixedReminders = (it.fixedReminders + reminder).distinct().sortedWith(FIXED_ORDER))
|
||||
}
|
||||
// Remembered so the row reads back as this reminder when reopened.
|
||||
viewModelScope.launch { withContext(io) { settingsPrefs.addRecentFixedTimeReminder(reminder) } }
|
||||
}
|
||||
|
||||
fun removeFixedReminder(reminder: FixedTimeReminder) {
|
||||
|
||||
@@ -82,18 +82,9 @@ internal fun NotificationsScreen(
|
||||
val launcher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
) { /* The pref is already on; a denial just leaves the OS gate shut. */ }
|
||||
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)
|
||||
if (needsPermission) {
|
||||
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
|
||||
val toggleDigest: (Boolean) -> Unit = { enabled ->
|
||||
viewModel.setDailyDigestEnabled(enabled)
|
||||
// Turning either kind of notification on asks for the permission if missing.
|
||||
fun askingPermission(set: (Boolean) -> Unit): (Boolean) -> Unit = { enabled ->
|
||||
set(enabled)
|
||||
val needsPermission = enabled &&
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
!context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
|
||||
@@ -101,6 +92,8 @@ 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) }
|
||||
@@ -174,9 +167,7 @@ internal fun NotificationsScreen(
|
||||
Spacer(Modifier.height(24.dp))
|
||||
DailyDigestRows(
|
||||
digest = state.dailyDigest,
|
||||
onEnable = { enabled ->
|
||||
toggleDigest(enabled)
|
||||
},
|
||||
onEnable = toggleDigest,
|
||||
onPickDay = { showDigestDay = true },
|
||||
onPickTime = { showDigestTime = true },
|
||||
onOpenSound = {
|
||||
|
||||
@@ -748,6 +748,9 @@ class SettingsPrefsTest {
|
||||
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.addRecentFixedTimeReminder(picked)
|
||||
assertThat(prefs.knownFixedTimeReminders.first()).contains(picked)
|
||||
|
||||
prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Inherit)
|
||||
assertThat(prefs.perCalendarFixedTimeReminderOverride.first().containsKey(2L)).isFalse()
|
||||
@@ -761,9 +764,11 @@ class SettingsPrefsTest {
|
||||
prefs.setDailyDigestTimeMinutes(420)
|
||||
prefs.setDailyDigestDay(DigestDay.Today)
|
||||
prefs.setCalendarInDailyDigest(5L, included = false)
|
||||
assertThat(prefs.dailyDigest.first()).isEqualTo(
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ class FixedTimeReminderFormTest {
|
||||
@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 = emptySet(), deviceZone = zone)
|
||||
.withFixedTimeRemindersRead(known = setOf(evening), deviceZone = zone)
|
||||
assertThat(loaded.reminders).containsExactly(10)
|
||||
assertThat(loaded.fixedReminders).containsExactly(evening)
|
||||
assertThat(loaded.fixedReminderOffsets(zone)).containsExactly(840)
|
||||
@@ -34,13 +34,14 @@ class FixedTimeReminderFormTest {
|
||||
@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(emptySet(), zone)).isEqualTo(allDay)
|
||||
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`() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,15 @@ class DailyDigestTest {
|
||||
assertThat(schedule.dueDay).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a day already listed is not listed again`() {
|
||||
val schedule = scheduleDigest(
|
||||
eight, DigestDay.Tomorrow, zone, millis("2026-06-10T19:00"), millis("2026-06-10T20:01"),
|
||||
lastPostedDay = 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"))
|
||||
|
||||
+10
-5
@@ -42,11 +42,16 @@ class FixedTimeReminderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `split keeps presets and whole days as lead times`() {
|
||||
fun `only known patterns read as fixed-time`() {
|
||||
val start = at("2026-06-10T10:00")
|
||||
val split = splitTimedReminders(listOf(10, 1_440, 840, 2 * 1_440), start, berlin, known = emptySet())
|
||||
assertThat(split.leadMinutes).containsExactly(10, 1_440, 2_880).inOrder()
|
||||
assertThat(split.fixed).containsExactly(eveningBefore)
|
||||
// 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
|
||||
@@ -67,7 +72,7 @@ class FixedTimeReminderTest {
|
||||
listOf(eveningBefore.offsetMinutes(start, berlin), twoDays.offsetMinutes(start, berlin)),
|
||||
start,
|
||||
berlin,
|
||||
known = emptySet(),
|
||||
known = setOf(eveningBefore, twoDays),
|
||||
)
|
||||
assertThat(split.fixed).containsExactly(twoDays, eveningBefore).inOrder()
|
||||
}
|
||||
|
||||
@@ -779,5 +779,46 @@ class EventEditViewModelTest {
|
||||
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 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()
|
||||
}
|
||||
}
|
||||
|
||||
+10
-5
@@ -415,11 +415,12 @@ 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 (`splitTimedReminders`): an
|
||||
offset landing on a configured default's pattern is fixed-time; otherwise one
|
||||
reaching back past the start's day is, unless it is a whole number of days or a
|
||||
short preset. Guessing wrong never moves an alarm, only how a later time change
|
||||
treats it. Limits: a recurring series stores one offset, so an occurrence whose
|
||||
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 configured
|
||||
default, or one picked by hand on this device (`recentFixedTimeReminders`).
|
||||
Guessing from the offset's shape alone would turn ordinary leads ("12 hours
|
||||
before") into fixed ones; guessing wrong never moves an alarm, only how a later
|
||||
time change treats it. Limits: a recurring series stores one offset, so an occurrence whose
|
||||
lead spans a DST change fires an hour off the named time (as in every other
|
||||
app reading that row), and on another device or app the row is just a lead time.
|
||||
New timed events get the default (`SettingsKeys.defaultFixedTimeReminder`, with
|
||||
@@ -431,6 +432,10 @@ 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.
|
||||
Two guards keep it to one per day: the day last listed is recorded right after
|
||||
posting (`ReminderStatePrefs.lastDigestDay`), so a pass failing later can't post
|
||||
it twice, and changing the switch, time or day stamps `dailyDigestArmedAt`, so a
|
||||
moment that passed before the change is not owed by it.
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user