Compare commits

..
Author SHA1 Message Date
makiolaj 80197bf6d9 Per-calendar all-day reminder time (#541) 2026-11-30 19:29:17 +01:00
25 changed files with 329 additions and 73 deletions

No files matched your search

@@ -9,6 +9,7 @@ import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.toEditForm
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import kotlinx.datetime.TimeZone
import org.junit.Rule
import org.junit.Test
@@ -50,13 +51,13 @@ class MoveEventExceptionsTest {
try {
val src = insertSyncedSeries(a)
ds.deleteOccurrence(src, start + 2 * day)
val occurrence = ds.eventDetail(src, 540)!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
val occurrence = ds.eventDetail(src, AllDayReminderTimes(540))!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
ds.updateOccurrence(src, start + 3 * day, occurrence, occurrence.copy(title = "edited"), 540)
val expected = listOf("0:series", "1:series", "3:edited", "4:series")
assertThat(occurrences(a)).isEqualTo(expected)
val form = ds.eventDetail(src, 540)!!.toEditForm(start, start + hour, zone)
ds.moveEvent(src, b, form, form, 540)
val form = ds.eventDetail(src, AllDayReminderTimes(540))!!.toEditForm(start, start + hour, zone)
ds.moveEvent(src, b, form, form, AllDayReminderTimes(540))
assertThat(occurrences(a)).isEmpty()
assertThat(occurrences(b)).isEqualTo(expected)
@@ -6,6 +6,7 @@ import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
@@ -54,6 +55,8 @@ data class CalendarSettings(
/** Timed reminder override; an empty list is "no reminder". */
val reminders: List<Int>? = null,
val allDayReminders: List<Int>? = null,
/** Its own all-day reminder time (#541), in minutes from midnight. */
val allDayReminderTimeMinutes: Int? = null,
/** The views it is hidden in only (#270). */
val hiddenInViews: Set<CalendarView> = emptySet(),
/** False when Calendula posts none of its reminders (#272). */
@@ -98,6 +101,7 @@ fun buildSettingsBackup(
val durations = snapshot[SettingsKeys.perCalendarEventDuration]
val reminders = snapshot[SettingsKeys.perCalendarReminderOverride]
val allDay = snapshot[SettingsKeys.perCalendarAllDayReminderOverride]
val allDayTimes = snapshot[SettingsKeys.perCalendarAllDayReminderTime]
val hiddenViews = snapshot[SettingsKeys.perCalendarHiddenViews]
val muted = snapshot[SettingsKeys.mutedReminderCalendarIds]
val alertStyles = snapshot[SettingsKeys.reminderAlertStyles]
@@ -105,7 +109,7 @@ fun buildSettingsBackup(
val notInDigest = snapshot[SettingsKeys.digestExcludedCalendarIds]
val backupIncluded = snapshot[SettingsKeys.autoBackupIncluded]
val backupExcluded = snapshot[SettingsKeys.autoBackupExcluded]
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys +
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys + allDayTimes.keys +
hiddenViews.keys + muted + alertStyles.keys + fixedTime.keys + notInDigest + backupIncluded + backupExcluded
val byId = calendars.associateBy { it.id }
val managedType = managed.associate { it.id to it.type }
@@ -123,6 +127,7 @@ fun buildSettingsBackup(
eventDurationMinutes = durations[id],
reminders = reminders[id],
allDayReminders = allDay[id],
allDayReminderTimeMinutes = allDayTimes[id],
hiddenInViews = hiddenViews[id].orEmpty(),
notifications = id !in muted,
alertStyle = alertStyles[id]?.takeUnless { it == ReminderAlertStyle.Notification },
@@ -193,6 +198,7 @@ private fun CalendarSettings.toJson(): JsonObject = buildJsonObject {
eventDurationMinutes?.let { put(KEY_EVENT_DURATION, JsonPrimitive(it)) }
reminders?.let { put(KEY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
allDayReminders?.let { put(KEY_ALL_DAY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
allDayReminderTimeMinutes?.let { put(KEY_ALL_DAY_REMINDER_TIME, JsonPrimitive(it)) }
if (hiddenInViews.isNotEmpty()) {
put(KEY_HIDDEN_IN_VIEWS, JsonArray(hiddenInViews.sortedBy { it.ordinal }.map { JsonPrimitive(it.name) }))
}
@@ -224,6 +230,8 @@ private fun JsonObject.toCalendarSettings(): CalendarSettings {
eventDurationMinutes = optInt(KEY_EVENT_DURATION),
reminders = optIntList(KEY_REMINDERS)?.cleanReminders(),
allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS)?.cleanReminders(),
allDayReminderTimeMinutes = optInt(KEY_ALL_DAY_REMINDER_TIME)
?.takeIf { it in 0 until SettingsPrefs.MINUTES_PER_DAY },
hiddenInViews = optStringList(KEY_HIDDEN_IN_VIEWS).orEmpty()
.mapNotNullTo(mutableSetOf()) { name -> CalendarView.entries.firstOrNull { it.name == name } },
notifications = optBoolean(KEY_NOTIFICATIONS) ?: true,
@@ -256,6 +264,7 @@ private const val KEY_LAST_USED = "last_used"
private const val KEY_EVENT_DURATION = "event_duration_minutes"
private const val KEY_REMINDERS = "reminders"
private const val KEY_ALL_DAY_REMINDERS = "all_day_reminders"
private const val KEY_ALL_DAY_REMINDER_TIME = "all_day_reminder_time_minutes"
private const val KEY_HIDDEN_IN_VIEWS = "hidden_in_views"
private const val KEY_NOTIFICATIONS = "notifications"
private const val KEY_ALERT_STYLE = "alert_style"
@@ -79,6 +79,7 @@ internal object SettingsBackupSchema {
SettingsKeys.perCalendarEventDuration,
SettingsKeys.perCalendarReminderOverride,
SettingsKeys.perCalendarAllDayReminderOverride,
SettingsKeys.perCalendarAllDayReminderTime,
SettingsKeys.perCalendarHiddenViews,
SettingsKeys.mutedReminderCalendarIds,
SettingsKeys.reminderAlertStyles,
@@ -190,6 +190,9 @@ fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
this[SettingsKeys.perCalendarAllDayReminderOverride] =
this[SettingsKeys.perCalendarAllDayReminderOverride] + (id to it)
}
entry.allDayReminderTimeMinutes?.let {
this[SettingsKeys.perCalendarAllDayReminderTime] = this[SettingsKeys.perCalendarAllDayReminderTime] + (id to it)
}
if (entry.hiddenInViews.isNotEmpty()) {
this[SettingsKeys.perCalendarHiddenViews] = this[SettingsKeys.perCalendarHiddenViews] + (id to entry.hiddenInViews)
}
@@ -15,6 +15,7 @@ import android.os.Looper
import android.provider.CalendarContract
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.Attendee
import de.jeanlucmakiola.calendula.domain.AttendeeRelationship
import de.jeanlucmakiola.calendula.domain.AttendeeType
@@ -65,11 +66,11 @@ interface CalendarDataSource {
fun eventInstances(eventId: Long, beginMillis: Long, endMillis: Long): List<EventInstance> =
instances(beginMillis, endMillis).filter { it.eventId == eventId }
/**
* [allDayReminderTimeMinutes]: the hour all-day reminders fire at, needed to
* [allDayTimes]: the hour all-day reminders fire at, per calendar, needed to
* decode their stored offsets back to whole-day lead times (see
* [fromProviderAllDayMinutes]).
*/
fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail?
fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail?
/**
* Master/one-off events that may match [query], across all calendars: every
@@ -98,11 +99,11 @@ interface CalendarDataSource {
* (local, synced, read-only): the masters/one-offs and the modified and
* cancelled exception rows, each with the keys that link it to its series
* and tagged with its calendar's name. A plain read: which calendars may be
* read for what is the caller's call. [allDayReminderTimeMinutes]: needed to
* write all-day reminders as whole-day lead times rather than raw provider
* offsets (see [toIcsEvent]).
* read for what is the caller's call. [allDayTimes]: needed to write all-day
* reminders as whole-day lead times rather than raw provider offsets (see
* [toIcsEvent]).
*/
fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows
fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows
/**
* The non-empty `Events.UID_2445` values present in [calendarId] — used to
@@ -243,14 +244,14 @@ interface CalendarDataSource {
* [original]→[updated] field edits applied, then the source
* deleted. The source is removed only once the copy fully succeeds; a failure
* before that rolls the new event back, leaving the original untouched.
* [allDayReminderTimeMinutes]: see [insertEvent].
* [allDayTimes]: as [eventDetail] reads and [insertEvent] writes them.
*/
fun moveEvent(
eventId: Long,
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long
/**
@@ -750,7 +751,7 @@ class AndroidCalendarDataSource @Inject constructor(
}
}
override fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail? {
override fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail? {
val attendees = queryAttendees(eventId)
val reminders = queryReminders(eventId)
return resolver.query(
@@ -758,10 +759,14 @@ class AndroidCalendarDataSource @Inject constructor(
EventDetailProjection.COLUMNS,
null, null, null,
)?.use { c ->
if (!c.moveToFirst()) null
else CursorColumnReader(c).toEventDetailCore(
attendees, reminders, allDayReminderTimeMinutes,
)
if (!c.moveToFirst()) {
null
} else {
val reader = CursorColumnReader(c)
reader.toEventDetailCore(
attendees, reminders, allDayTimes.forCalendar(reader.getLong(EventDetailProjection.IDX_CALENDAR_ID)),
)
}
}
}
@@ -786,7 +791,7 @@ class AndroidCalendarDataSource @Inject constructor(
?: emptyList()
}
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
override fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows {
if (calendarIds.isEmpty()) return CalendarRows(emptyList(), emptyList())
// The name tags each event for a combined backup's restore to fan back
// out; an id that no longer exists drops out here.
@@ -797,7 +802,7 @@ class AndroidCalendarDataSource @Inject constructor(
"${CalendarContract.Events.DELETED} = 0"
val series = mutableListOf<MasterRow>()
val overrides = mutableListOf<OverrideRow>()
forEachExportRow(selection, allDayReminderTimeMinutes) { event ->
forEachExportRow(selection, allDayTimes) { event ->
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
val calendar = calendars[calendarId]
// An adapter may stamp the calendar colour on every row; a palette key means it was chosen.
@@ -844,7 +849,7 @@ class AndroidCalendarDataSource @Inject constructor(
*/
private fun forEachExportRow(
selection: String,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
row: ColumnReader.(event: (calendarName: String?) -> IcsEvent) -> Unit,
) {
val eventIds = resolver.query(
@@ -869,7 +874,9 @@ class AndroidCalendarDataSource @Inject constructor(
reader.toIcsEvent(
reminderMinutes = reminders[eventId].orEmpty(),
calendarName = calendarName,
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
allDayReminderTimeMinutes = allDayTimes.forCalendar(
reader.getLong(EventExportProjection.IDX_CALENDAR_ID),
),
)
}
}
@@ -1116,8 +1123,9 @@ class AndroidCalendarDataSource @Inject constructor(
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long {
val allDayReminderTimeMinutes = allDayTimes.forCalendar(targetCalendarId)
// CALENDAR_ID can't be updated in place, so re-create the event on the
// target calendar and delete the source. Everything that identifies or
// hangs off the event is copied first; the source row is removed only
@@ -1138,7 +1146,7 @@ class AndroidCalendarDataSource @Inject constructor(
try {
copyReminderRows(fromEventId = eventId, toEventId = newEventId)
insertAttendees(newEventId, editableAttendees(eventId))
copyExceptions(eventId, newEventId, targetCalendarId, allDayReminderTimeMinutes, detached)
copyExceptions(eventId, newEventId, targetCalendarId, allDayTimes, detached)
// Apply the user's field edits exactly as a same-calendar "all
// events" save would: the moved master carries the source's values,
// so the dirty diff against [original] writes only what changed
@@ -1224,20 +1232,20 @@ class AndroidCalendarDataSource @Inject constructor(
fromEventId: Long,
toEventId: Long,
targetCalendarId: Long,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
detached: MutableList<Long>,
) {
val exceptions = queryExceptionRows(fromEventId)
if (exceptions.isEmpty()) return
val zone = TimeZone.currentSystemDefault()
exceptions.filterNot { it.isCancelled }.forEach { ex ->
val detail = eventDetail(ex.exceptionEventId, allDayReminderTimeMinutes)
val detail = eventDetail(ex.exceptionEventId, allDayTimes)
?: throw WriteFailedException("read modified occurrence id=${ex.exceptionEventId}")
val endMillis = ex.dtEndMillis ?: (ex.dtStartMillis + parseRfc2445DurationMillis(ex.duration))
val form = detail.toEditForm(ex.dtStartMillis, endMillis, zone)
.copy(calendarId = targetCalendarId, colorKey = null)
.toDetachedOccurrence()
detached += insertEvent(form, allDayReminderTimeMinutes)
detached += insertEvent(form, allDayTimes.forCalendar(targetCalendarId))
}
val values = querySeriesRow(toEventId).exdateValues(exceptions.map { it.originalInstanceMillis })
updateEventRow(toEventId, values, "exdate moved exceptions event id=$toEventId")
@@ -12,6 +12,7 @@ import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides
@@ -56,9 +57,12 @@ class CalendarRepositoryImpl @Inject constructor(
private val syncRequester: SyncRequester,
) : CalendarRepository {
/** The configured wall-clock fire time for all-day reminders, read per write. */
private suspend fun allDayReminderTimeMinutes(): Int =
settingsPrefs.allDayReminderTimeMinutes.first()
/** The configured wall-clock fire times for all-day reminders, global and per calendar (#541), read per call. */
private suspend fun allDayReminderTimes(): AllDayReminderTimes = settingsPrefs.allDayReminderTimes.first()
/** [calendarId]'s all-day reminder time: its own, or the global one. */
private suspend fun allDayReminderTimeMinutes(calendarId: Long?): Int =
allDayReminderTimes().let { times -> calendarId?.let(times::forCalendar) ?: times.default }
// DROP_OLDEST: tryEmit never fails, so a tick that lands while a subscriber
// still holds the previous one is never lost (#364).
@@ -363,7 +367,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
dataSource.eventDetail(eventId, allDayReminderTimes())
?: throw NoSuchEventException(eventId)
}
@@ -412,7 +416,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun exportEvents(calendarIds: Set<Long>) = withContext(io) {
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp)
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimes()), ::formatExdateStamp)
}
override suspend fun copyEvents(
@@ -422,7 +426,7 @@ class CalendarRepositoryImpl @Inject constructor(
): IcsImportSummary {
val events = withContext(io) {
planCalendarCopy(
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()),
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimes()),
::formatExdateStamp,
)
}
@@ -445,7 +449,7 @@ class CalendarRepositoryImpl @Inject constructor(
// uncurated one — an imported colour is matched against every key the
// account accepts, not the subset the picker shows.
val palette = dataSource.publishedEventColors(targetCalendarId)
val allDayMinutes = allDayReminderTimeMinutes()
val allDayMinutes = allDayReminderTimeMinutes(targetCalendarId)
var imported = 0
var skipped = 0
var failed = 0
@@ -500,7 +504,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
dataSource.insertEvent(form, allDayReminderTimeMinutes())
dataSource.insertEvent(form, allDayReminderTimeMinutes(form.calendarId))
}
override suspend fun updateEvent(
@@ -508,7 +512,9 @@ class CalendarRepositoryImpl @Inject constructor(
original: EventForm,
updated: EventForm,
) = write(eventCalendar(eventId, original, updated.calendarId)) {
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
dataSource.updateEvent(
eventId, original, updated, allDayReminderTimeMinutes(updated.calendarId ?: original.calendarId),
)
}
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
@@ -522,7 +528,7 @@ class CalendarRepositoryImpl @Inject constructor(
updated: EventForm,
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
dataSource.moveEvent(
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
eventId, targetCalendarId, original, updated, allDayReminderTimes(),
)
}
@@ -533,7 +539,7 @@ class CalendarRepositoryImpl @Inject constructor(
form: EventForm,
): Long = write(eventCalendar(eventId, original)) {
dataSource.updateOccurrence(
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
eventId, beginMillis, original, form, allDayReminderTimeMinutes(form.calendarId ?: original.calendarId),
)
}
@@ -544,7 +550,7 @@ class CalendarRepositoryImpl @Inject constructor(
updated: EventForm,
): Long = write(eventCalendar(eventId, original)) {
dataSource.updateEventFromOccurrence(
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(updated.calendarId ?: original.calendarId),
)
}.also { newId -> if (newId != eventId) splits.tryEmit(SeriesSplit(eventId, newId)) }
@@ -16,6 +16,7 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.contacts.anchorDate
import de.jeanlucmakiola.calendula.domain.contacts.managedUid
import de.jeanlucmakiola.calendula.domain.contacts.renderSpecialDateTitle
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.toRRule
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
@@ -122,7 +123,7 @@ class SpecialDatesSyncEngine @Inject constructor(
}
calendars.applyManagedCalendarReminders(
calendarId = calendarId,
allDayReminderTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
allDayReminderTimeMinutes = prefs.allDayReminderTimes.first().forCalendar(calendarId),
minutes = minutes,
)
}
@@ -190,7 +191,9 @@ class SpecialDatesSyncEngine @Inject constructor(
val diff = diffManagedEvents(built.map { it.desired }, calendars.queryManagedEvents(calendarId))
val formByUid = built.associate { it.desired.uid to it.form }
diff.insertUids.forEach { uid ->
calendars.insertManagedEvent(formByUid.getValue(uid), uid, reminderCtx.allDayTimeMinutes)
calendars.insertManagedEvent(
formByUid.getValue(uid), uid, reminderCtx.allDayTimes.forCalendar(calendarId),
)
}
diff.updates.forEach { calendars.updateManagedFields(it.eventId, it.columns) }
diff.deleteEventIds.forEach { calendars.deleteEvent(it) }
@@ -235,13 +238,13 @@ class SpecialDatesSyncEngine @Inject constructor(
private suspend fun readReminderContext(): ReminderContext = ReminderContext(
allDayGlobal = prefs.defaultAllDayReminderMinutes.first(),
allDayOverrides = prefs.perCalendarAllDayReminderOverride.first(),
allDayTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
allDayTimes = prefs.allDayReminderTimes.first(),
)
private data class ReminderContext(
val allDayGlobal: List<Int>,
val allDayOverrides: Map<Long, List<Int>>,
val allDayTimeMinutes: Int,
val allDayTimes: AllDayReminderTimes,
) {
/** Same semantics as `resolveDefaultReminder`: present-empty = explicit none. */
fun resolveAllDay(calendarId: Long): List<Int> =
@@ -28,6 +28,7 @@ import de.jeanlucmakiola.calendula.domain.reminders.toStoredAlertStyles
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.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
@@ -202,6 +203,12 @@ class SettingsPrefs @Inject constructor(
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
val defaultAllDayReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultAllDayReminderMinutes)
val allDayReminderTimeMinutes: Flow<Int> = prefs.flow(SettingsKeys.allDayReminderTimeMinutes)
val perCalendarAllDayReminderTime: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarAllDayReminderTime)
/** The global all-day reminder time with each calendar's own (#541). */
val allDayReminderTimes: Flow<AllDayReminderTimes> = prefs.snapshot {
AllDayReminderTimes(it[SettingsKeys.allDayReminderTimeMinutes], it[SettingsKeys.perCalendarAllDayReminderTime])
}
val snoozeMinutes: Flow<Int> = prefs.flow(SettingsKeys.snoozeMinutes)
val perCalendarReminderOverride: Flow<Map<Long, List<Int>>> =
prefs.flow(SettingsKeys.perCalendarReminderOverride)
@@ -418,6 +425,17 @@ class SettingsPrefs @Inject constructor(
suspend fun setAllDayReminderTimeMinutes(minutesOfDay: Int) =
prefs.set(SettingsKeys.allDayReminderTimeMinutes, minutesOfDay)
/** [minutesOfDay] null drops the calendar's own all-day reminder time, so it follows the global one again. */
suspend fun setCalendarAllDayReminderTime(calendarId: Long, minutesOfDay: Int?) {
prefs.update(SettingsKeys.perCalendarAllDayReminderTime) { current ->
if (minutesOfDay == null) {
current - calendarId
} else {
current + (calendarId to minutesOfDay.coerceIn(0, MINUTES_PER_DAY - 1))
}
}
}
suspend fun setSnoozeMinutes(minutes: Int) = prefs.set(SettingsKeys.snoozeMinutes, minutes)
suspend fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) =
@@ -971,6 +989,16 @@ object SettingsKeys {
it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1)
}
/**
* Per-calendar overrides of [allDayReminderTimeMinutes] (#541): app-side
* only, nothing of it reaches the provider. A calendar absent follows the
* global time. Serialised as `id=minutes;id=minutes`.
*/
val perCalendarAllDayReminderTime: Pref<Map<Long, Int>> =
nullableStringPref("per_calendar_allday_reminder_time").map(
{ parseIdIntMap(it, 0 until SettingsPrefs.MINUTES_PER_DAY) },
) { it.toStoredIdInts() }
/**
* How long the notification "Snooze" action defers a reminder, in minutes,
* re-posted via an exact alarm (the calendar provider won't re-fire).
@@ -1465,14 +1493,16 @@ private fun List<Int>.toStoredReminders(): String =
* degrades to "inherits the global default" instead of throwing.
*/
private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
parseIdIntMap(stored, SettingsPrefs.MIN_EVENT_DURATION..SettingsPrefs.MAX_EVENT_DURATION)
/** Parse an `id=value` map joined by `;`, dropping malformed entries and values outside [valid]. */
private fun parseIdIntMap(stored: String?, valid: IntRange): Map<Long, Int> =
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 minutes = parts[1].trim().toIntOrNull()
?.takeIf { it in SettingsPrefs.MIN_EVENT_DURATION..SettingsPrefs.MAX_EVENT_DURATION }
?: return@mapNotNull null
calendarId to minutes
val value = parts[1].trim().toIntOrNull()?.takeIf { it in valid } ?: return@mapNotNull null
calendarId to value
}.toMap()
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
@@ -1519,3 +1549,5 @@ private fun Map<Long, Int>.toStoredDurations(): String =
"$id$KEY_VALUE_SEP$minutes"
}
private fun Map<Long, Int>.toStoredIdInts(): String? = toStoredDurations().ifEmpty { null }
@@ -120,7 +120,7 @@ class ReminderScanner @Inject constructor(
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
.withoutProviderDefaults(),
zone = ZoneId.systemDefault(),
allDayTimeMinutes = settingsPrefs.allDayReminderTimeMinutes.first(),
allDayTimes = settingsPrefs.allDayReminderTimes.first(),
)
val schedule = scheduleReminders(
@@ -0,0 +1,13 @@
package de.jeanlucmakiola.calendula.domain.reminders
/**
* The wall-clock times all-day reminders fire at, as minutes from local
* midnight: the global [default], and the calendars that set their own (#541).
*/
data class AllDayReminderTimes(
val default: Int,
val perCalendar: Map<Long, Int> = emptyMap(),
) {
/** [calendarId]'s own time, or the global one when it sets none. */
fun forCalendar(calendarId: Long): Int = perCalendar[calendarId] ?: default
}
@@ -67,8 +67,8 @@ private const val MINUTES_PER_DAY = 1_440
* Pair every instance with each of its event's reminder offsets.
*
* Timed occurrences fire at `begin − minutes`. All-day ones read the offset only
* for *which day* it means ([allDayLeadDays]) and take the hour from
* [allDayTimeMinutes], recomposed against each occurrence's own date in [zone].
* for *which day* it means ([allDayLeadDays]) and take the hour [allDayTimes]
* names for their calendar, recomposed against each occurrence's own date in [zone].
* Duplicate offsets in [minutesByEvent] collapse.
*
* Every offset given is planned. The provider's "use the account default"
@@ -81,7 +81,7 @@ fun planReminders(
instances: List<ReminderEventInstance>,
minutesByEvent: Map<Long, List<Int>>,
zone: ZoneId,
allDayTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): List<PlannedReminder> = instances.flatMap { instance ->
minutesByEvent[instance.eventId].orEmpty()
.distinct()
@@ -90,7 +90,9 @@ fun planReminders(
instance = instance,
minutes = minutes,
alarmMillis = if (instance.isAllDay) {
allDayAlarmMillis(instance.beginMillis, minutes, zone, allDayTimeMinutes)
allDayAlarmMillis(
instance.beginMillis, minutes, zone, allDayTimes.forCalendar(instance.calendarId),
)
} else {
instance.beginMillis - minutes * MILLIS_PER_MINUTE
},
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
@@ -13,7 +14,8 @@ import kotlinx.datetime.LocalTime
/**
* M3 time picker in an alert dialog, seeded with [initial]. Shared by the event
* form (start/end times) and Settings (the all-day reminder fire time).
* form (start/end times) and Settings (the all-day reminder fire time). With
* [resetLabel], an extra button beside Cancel calls [onReset].
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -21,6 +23,8 @@ fun TimePickerAlert(
initial: LocalTime,
onConfirm: (LocalTime) -> Unit,
onDismiss: () -> Unit,
resetLabel: String? = null,
onReset: () -> Unit = {},
) {
// Honour the app's own time-format preference (the value every time label
// reads), not the system/locale clock — otherwise an explicit 24h setting
@@ -38,7 +42,10 @@ fun TimePickerAlert(
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_cancel)) }
Row {
if (resetLabel != null) TextButton(onClick = onReset) { Text(resetLabel) }
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_cancel)) }
}
},
text = { TimePicker(state = state) },
)
@@ -33,6 +33,7 @@ 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.ReminderDefaultPicker
import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
@@ -52,6 +53,7 @@ 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.datetime.LocalTime
/**
* Per-calendar notifications and reminder overrides (#145, #272), reached from
@@ -73,6 +75,7 @@ internal fun CalendarRemindersScreen(
val canFullScreen = rememberCanUseFullScreenIntent()
val context = LocalContext.current
var fixedOverrideFor by remember { mutableStateOf<Long?>(null) }
var allDayTimeFor by remember { mutableStateOf<Long?>(null) }
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
val calendarIds = state.reminderCalendars.map { it.id }
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
@@ -129,6 +132,7 @@ internal fun CalendarRemindersScreen(
onEditOverride = { overrideDialog = it },
onEditFixedOverride = { fixedOverrideFor = calendar.id },
onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) },
onEditAllDayTime = { allDayTimeFor = calendar.id },
)
}
}
@@ -189,6 +193,26 @@ internal fun CalendarRemindersScreen(
inherited = state.defaultFixedTimeReminder,
)
}
allDayTimeFor?.let { calendarId ->
val minutes = state.allDayReminderTimeFor(calendarId)
TimePickerAlert(
initial = LocalTime(minutes / 60, minutes % 60),
onConfirm = {
viewModel.setCalendarAllDayReminderTime(calendarId, it.hour * 60 + it.minute)
allDayTimeFor = null
},
onDismiss = { allDayTimeFor = null },
resetLabel = if (calendarId in state.perCalendarAllDayReminderTime) {
stringResource(R.string.settings_calendar_allday_time_use_default)
} else {
null
},
onReset = {
viewModel.setCalendarAllDayReminderTime(calendarId, null)
allDayTimeFor = null
},
)
}
overrideDialog?.let { target ->
val map = if (target.isAllDay) {
state.perCalendarAllDayReminderOverride
@@ -215,7 +239,7 @@ internal fun CalendarRemindersScreen(
},
onDismiss = { overrideDialog = null },
leadTimeSummary = if (target.isAllDay) {
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
allDayFiringTimeSummary(state.allDayReminderTimeFor(target.calendarId))
} else {
null
},
@@ -227,7 +251,7 @@ internal fun CalendarRemindersScreen(
* One calendar in its account group, with its options unfolding beneath it:
* the notification switch and channel deep-link for every calendar, then the
* default-reminder overrides where it takes them — or, for a special-dates
* calendar, a link to the section that owns them.
* calendar, a link to the section that owns them — and its all-day reminder time (#541).
*/
@Composable
private fun CalendarReminderEntry(
@@ -251,6 +275,7 @@ private fun CalendarReminderEntry(
onEditOverride: (OverrideTarget) -> Unit,
onEditFixedOverride: () -> Unit,
onSetInDigest: (Boolean) -> Unit,
onEditAllDayTime: () -> Unit,
) {
val opensGroup = position == Position.Top || position == Position.Alone
val closesGroup = position == Position.Bottom || position == Position.Alone
@@ -313,11 +338,10 @@ private fun CalendarReminderEntry(
trailing = { ExternalLinkIcon() },
onClick = onOpenSettings,
)
val lastAlertRow = !(managed || takesOverrides || digestOn)
GroupedRow(
title = stringResource(R.string.settings_alert_style),
summary = alertStyleLabel(alertStyle),
position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle,
position = Position.Middle,
container = nested,
onClick = onEditAlertStyle,
)
@@ -325,7 +349,7 @@ private fun CalendarReminderEntry(
GroupedRow(
title = stringResource(R.string.settings_alert_sound),
summary = alertSoundLabel(alertStyle),
position = if (lastAlertRow && !heldBack.any) Position.Bottom else Position.Middle,
position = Position.Middle,
container = nested,
onClick = onEditAlertSound,
)
@@ -334,7 +358,7 @@ private fun CalendarReminderEntry(
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,
position = Position.Middle,
container = nested,
trailing = { ExternalLinkIcon() },
onClick = onOpenRingSettings,
@@ -344,7 +368,7 @@ private fun CalendarReminderEntry(
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,
position = Position.Middle,
container = nested,
trailing = { ExternalLinkIcon() },
onClick = onAllowFullScreen,
@@ -356,7 +380,7 @@ private fun CalendarReminderEntry(
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,
position = Position.Middle,
container = nested,
)
}
@@ -364,7 +388,7 @@ private fun CalendarReminderEntry(
GroupedRow(
title = stringResource(R.string.settings_default_reminder_allday),
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
position = Position.Bottom,
position = Position.Middle,
container = nested,
trailing = { ChevronIcon() },
onClick = onOpenSpecialDates,
@@ -398,11 +422,22 @@ private fun CalendarReminderEntry(
isAllDay = true,
choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id),
globalDefault = state.defaultAllDayReminderMinutes,
position = Position.Bottom,
position = Position.Middle,
container = nested,
onEditOverride = onEditOverride,
)
}
GroupedRow(
title = stringResource(R.string.settings_allday_reminder_time),
summary = state.perCalendarAllDayReminderTime[calendar.id]?.let { settingsTimeOfDay(it) }
?: stringResource(
R.string.settings_calendar_reminder_inherits,
settingsTimeOfDay(state.allDayReminderTimeMinutes),
),
position = Position.Bottom,
container = nested,
onClick = onEditAllDayTime,
)
}
}
}
@@ -79,7 +79,8 @@ internal fun settingsTimeOfDay(minutesOfDay: Int): String =
/**
* Second line for an all-day lead-time row: the clock time it fires at. The
* offset only decides which day; the hour comes from the global all-day setting
* offset only decides which day; the hour comes from [allDayReminderTimeMinutes],
* the calendar's own or the global all-day time
* (see [de.jeanlucmakiola.calendula.domain.reminders.planReminders]).
*/
@Composable
@@ -90,6 +90,8 @@ data class SettingsUiState(
val defaultAllDayReminderMinutes: List<Int> = emptyList(),
/** Wall-clock time (minutes from midnight) all-day reminders fire at; default 09:00. */
val allDayReminderTimeMinutes: Int = SettingsPrefs.DEFAULT_ALLDAY_REMINDER_TIME,
/** Calendars' own all-day reminder times (#541); absent = the global one. */
val perCalendarAllDayReminderTime: Map<Long, Int> = emptyMap(),
/** How long the notification "Snooze" action defers a reminder; default 10 min. */
val snoozeMinutes: Int = SettingsPrefs.DEFAULT_SNOOZE_MINUTES,
/**
@@ -133,7 +135,11 @@ data class SettingsUiState(
* out to it instead of offering an override here.
*/
val managedCalendarIds: Set<Long> = emptySet(),
)
) {
/** [calendarId]'s all-day reminder time: its own, or the global one. */
fun allDayReminderTimeFor(calendarId: Long): Int =
perCalendarAllDayReminderTime[calendarId] ?: allDayReminderTimeMinutes
}
/**
* State for the contact special-dates sub-page (issue #15). Exposed as its own
@@ -147,6 +153,8 @@ data class SpecialDatesUiState(
val titleTemplates: Map<SpecialDateType, String> = emptyMap(),
/** The reminder choice per type's managed calendar (applied to all its events). */
val reminderChoices: Map<SpecialDateType, ReminderOverride> = emptyMap(),
/** The time each type's managed calendar reminds at: its own, or the global one (#541). */
val allDayReminderTimes: Map<SpecialDateType, Int> = emptyMap(),
/** Whether {year} resolves in titles (the source year is static and always correct). */
val showYear: Boolean = true,
/** True when READ_CONTACTS was revoked after enabling — the mirror is paused. */
@@ -163,6 +163,7 @@ class SettingsViewModel @Inject constructor(
defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes],
defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes],
allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes],
perCalendarAllDayReminderTime = this[SettingsKeys.perCalendarAllDayReminderTime],
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
@@ -223,6 +224,8 @@ class SettingsViewModel @Inject constructor(
val specialDatesState: StateFlow<SpecialDatesUiState> = prefs.data.map { stored ->
val templates = stored.specialDatesTitleTemplates
val allDayOverrides = stored[SettingsKeys.perCalendarAllDayReminderOverride]
val allDayTimes = stored[SettingsKeys.perCalendarAllDayReminderTime]
val allDayTime = stored[SettingsKeys.allDayReminderTimeMinutes]
val status = stored.specialDatesStatus
SpecialDatesUiState(
enabled = stored[SettingsKeys.specialDatesEnabled],
@@ -236,6 +239,9 @@ class SettingsViewModel @Inject constructor(
reminderChoices = stored.specialDatesCalendars.mapValues { (_, calendarId) ->
allDayOverrides.reminderOverrideFor(calendarId)
},
allDayReminderTimes = stored.specialDatesCalendars.mapValues { (_, calendarId) ->
allDayTimes[calendarId] ?: allDayTime
},
showYear = stored[SettingsKeys.specialDatesShowYear],
stalledPermission = status.stalled == SpecialDatesStalledReason.PermissionRevoked,
lastRun = status.lastRun,
@@ -585,6 +591,10 @@ class SettingsViewModel @Inject constructor(
/** The armed alarm was planned for the old hour, so re-plan against the new one. */
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) = saveAndScan { setAllDayReminderTimeMinutes(minutesOfDay) }
/** [minutesOfDay] null follows the global time again; re-plans like the global setting (#541). */
fun setCalendarAllDayReminderTime(calendarId: Long, minutesOfDay: Int?) =
saveAndScan { setCalendarAllDayReminderTime(calendarId, minutesOfDay) }
fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) }
fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) = save { setCalendarReminderOverride(calendarId, override) }
@@ -202,7 +202,9 @@ internal fun SpecialDatesScreen(
allowInherit = false,
onSelect = { viewModel.setSpecialDatesReminders(type, it) },
onDismiss = { reminderPickerType = null },
leadTimeSummary = allDayFiringTimeSummary(settings.allDayReminderTimeMinutes),
leadTimeSummary = allDayFiringTimeSummary(
state.allDayReminderTimes[type] ?: settings.allDayReminderTimeMinutes,
),
)
}
}
+1
View File
@@ -796,6 +796,7 @@
<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>
<string name="settings_calendar_allday_time_use_default">Use default</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>
@@ -159,6 +159,7 @@ class SettingsBackupTest {
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5))
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0))
source[SettingsKeys.perCalendarAllDayReminderTime] = mapOf(1L to 1_140)
source[SettingsKeys.perCalendarHiddenViews] = mapOf(1L to setOf(CalendarView.Month, CalendarView.Week))
source[SettingsKeys.mutedReminderCalendarIds] = setOf(1L)
source[SettingsKeys.reminderAlertStyles] = mapOf(1L to ReminderAlertStyle.FullScreenRing)
@@ -176,6 +177,7 @@ class SettingsBackupTest {
assertThat(target.asMap().keys.map { it.name }).contains(pref.name)
}
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0))
assertThat(target[SettingsKeys.perCalendarAllDayReminderTime]).containsExactly(9L, 1_140)
assertThat(target[SettingsKeys.perCalendarHiddenViews]).containsExactly(9L, setOf(CalendarView.Month, CalendarView.Week))
assertThat(target[SettingsKeys.mutedReminderCalendarIds]).containsExactly(9L)
assertThat(target[SettingsKeys.reminderAlertStyles]).containsExactly(9L, ReminderAlertStyle.FullScreenRing)
@@ -226,6 +228,15 @@ class SettingsBackupTest {
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440)
}
@Test
fun `an out-of-range all-day reminder time is dropped`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","all_day_reminder_time_minutes":1440}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
assertThat(backup.calendars.single().allDayReminderTimeMinutes).isNull()
}
@Test
fun `unreadable calendars leave the per-calendar settings alone`() {
val source = mutablePreferencesOf()
@@ -532,6 +532,27 @@ class CalendarRepositoryImplTest {
assertThat(fake.allDayReminderTimes).containsExactly(480)
}
@Test
fun `writes encode all-day reminders at the target calendar's own time`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource()
val settings = testSettings(tempDir)
settings.setAllDayReminderTimeMinutes(8 * 60)
settings.setCalendarAllDayReminderTime(2L, 18 * 60)
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, settings = settings)
val day = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0))
val form = EventForm(calendarId = 1L, isAllDay = true, start = FormTime(day), end = FormTime(day))
repo.createEvent(form)
repo.createEvent(form.copy(calendarId = 2L))
repo.moveEvent(5L, 2L, form, form.copy(calendarId = 2L))
settings.setCalendarAllDayReminderTime(2L, null)
repo.createEvent(form.copy(calendarId = 2L))
assertThat(fake.allDayReminderTimes).containsExactly(480, 1080, 1080, 480).inOrder()
}
@Test
fun `createEvent propagates write failures`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.calendar
import android.provider.CalendarContract
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
@@ -91,11 +92,11 @@ internal class FakeCalendarDataSource : CalendarDataSource {
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> =
instancesResult(beginMillis, endMillis)
override fun searchEvents(query: String): List<SearchCandidate> = searchResult(query)
override fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail? =
override fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail? =
eventDetailResult(eventId)
override fun publishedEventColors(calendarId: Long): List<EventColorOption> =
publishedEventColorsResult(calendarId)
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
override fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows {
lastCalendarRowsIds = calendarIds
return calendarRowsResult
}
@@ -193,11 +194,11 @@ internal class FakeCalendarDataSource : CalendarDataSource {
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long {
writeError?.let { throw it }
movedEvents += MovedEvent(eventId, targetCalendarId, original, updated)
allDayReminderTimes += allDayReminderTimeMinutes
allDayReminderTimes += allDayTimes.forCalendar(targetCalendarId)
return nextInsertId
}
@@ -575,6 +575,26 @@ class SettingsPrefsTest {
assertThat(prefs.allDayReminderTimeMinutes.first()).isEqualTo(0)
}
@Test
fun `a calendar's own all-day reminder time overrides the global one until cleared`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
prefs.setAllDayReminderTimeMinutes(8 * 60)
prefs.setCalendarAllDayReminderTime(3L, 19 * 60)
prefs.setCalendarAllDayReminderTime(4L, 5_000)
val times = prefs.allDayReminderTimes.first()
assertThat(times.forCalendar(3L)).isEqualTo(1_140)
assertThat(times.forCalendar(4L)).isEqualTo(1_439)
assertThat(times.forCalendar(5L)).isEqualTo(480)
prefs.setCalendarAllDayReminderTime(3L, null)
prefs.setAllDayReminderTimeMinutes(10 * 60)
assertThat(prefs.allDayReminderTimes.first().forCalendar(3L)).isEqualTo(600)
assertThat(prefs.perCalendarAllDayReminderTime.first()).containsExactly(4L, 1_439)
}
@Test
fun `snooze duration defaults to 10 minutes`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
@@ -41,7 +41,7 @@ class ReminderPlanTest {
minutesByEvent: Map<Long, List<Int>>,
zone: ZoneId = berlin,
allDayTimeMinutes: Int = nineAm,
) = planReminders(instances, minutesByEvent, zone, allDayTimeMinutes)
) = planReminders(instances, minutesByEvent, zone, AllDayReminderTimes(allDayTimeMinutes))
@Test
fun `a reminder fires its offset before the occurrence begins`() {
@@ -104,6 +104,64 @@ class ReminderPlanTest {
.isEqualTo(LocalDate.parse("2026-01-14").atTime(9, 0))
}
@Test
fun `a calendar's own all-day time replaces the global one for its events only`() {
val sevenPm = 19 * 60
val times = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(2L to sevenPm))
val begin = allDayBegin("2026-01-15")
val planned = planReminders(
instances = listOf(
instance(1L, beginMillis = begin, calendarId = 1L, isAllDay = true),
instance(2L, beginMillis = begin, calendarId = 2L, isAllDay = true),
),
minutesByEvent = mapOf(
1L to listOf(encodedAllDayMinutes("2026-01-15", days = 1)),
2L to listOf(encodedAllDayMinutes("2026-01-15", days = 1)),
),
zone = berlin,
allDayTimes = times,
).associate { it.instance.calendarId to firedAt(it.alarmMillis).toLocalDateTime() }
assertThat(planned).containsExactly(
1L, LocalDate.parse("2026-01-14").atTime(9, 0),
2L, LocalDate.parse("2026-01-14").atTime(19, 0),
)
}
@Test
fun `an on-the-day reminder fires at the calendar's own time`() {
val sixAm = 6 * 60
val alarm = planReminders(
instances = listOf(instance(1L, beginMillis = allDayBegin("2026-07-15"), calendarId = 3L, isAllDay = true)),
minutesByEvent = mapOf(1L to listOf(encodedAllDayMinutes("2026-07-15", days = 0, timeOfDayMinutes = sixAm))),
zone = berlin,
allDayTimes = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(3L to sixAm)),
).single().alarmMillis
assertThat(firedAt(alarm).toLocalDateTime()).isEqualTo(LocalDate.parse("2026-07-15").atTime(6, 0))
}
@Test
fun `a timed event ignores its calendar's all-day time`() {
val begin = now + 30 * minute
val planned = planReminders(
instances = listOf(instance(1L, beginMillis = begin, calendarId = 3L)),
minutesByEvent = mapOf(1L to listOf(10)),
zone = berlin,
allDayTimes = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(3L to 0)),
)
assertThat(planned.single().alarmMillis).isEqualTo(begin - 10 * minute)
}
@Test
fun `all-day times resolve to the calendar's own, else the global default`() {
val times = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(4L to 0))
assertThat(times.forCalendar(4L)).isEqualTo(0)
assertThat(times.forCalendar(5L)).isEqualTo(nineAm)
}
@Test
fun `a summer occurrence of a row written in winter is not an hour early`() {
// The drift this replaces: the offset was sampled at UTC+1, the occurrence
+4 -2
View File
@@ -393,8 +393,10 @@ not a plain lead time — `AllDayReminderEncoding` folds a wall-clock hour into
sampled against one date's UTC offset — so taking it at face value drifts by the
offset delta across a DST boundary, and rows from other apps carry no hour at
all. The offset is therefore read only for *which day* it means; the hour comes
from the global all-day reminder setting, recomposed against each occurrence's
own date. Which day that is comes from the local date the encoded instant falls
from the all-day reminder setting — the calendar's own (#541,
`SettingsPrefs.perCalendarAllDayReminderTime`, app-side only) or else the global
one, resolved through `AllDayReminderTimes` — recomposed against each
occurrence's own date. Writes encode against the same per-calendar hour. Which day that is comes from the local date the encoded instant falls
on — except for a plain multiple of 1440, read at face value because a foreign
row means literal days from UTC midnight. The two collide where the all-day hour
equals the zone's UTC offset (20:00 in New York), and there the instant landing
+1
View File
@@ -87,6 +87,7 @@ identity instead:
| `event_duration_minutes` | Int? | Per-calendar default length, clamped to 1–1440 like the setting. |
| `reminders` | Int[]? | Timed reminder override; `[]` is "no reminder". |
| `all_day_reminders` | Int[]? | All-day reminder override. |
| `all_day_reminder_time_minutes` | Int? | Own all-day reminder time, minutes from midnight. Absent follows the global time. |
| `hidden_in_views` | String[]? | Views it is hidden in only (`Month`, `Week`, …); unknown names are dropped. |
| `notifications` | Boolean? | `false`: Calendula posts none of its reminders. |
| `alert_style` | String? | `full_screen` or `full_screen_ring`; absent or unknown is a plain notification. |