fix(#429): only preselect target calendars, key the default by account and name

This commit is contained in:
makiolaj committed 2026-11-13 19:26:47 +01:00
1 parent 9577e6c0c8
commit 6a9274402a
11 files changed
+124 -41

No files matched your search

@@ -426,10 +426,14 @@ class MainActivity : AppCompatActivity() {
private fun Intent.longExtraOrNull(key: String): Long? =
if (hasExtra(key)) getLongExtra(key, 0L) else null
/** The calendar an insert intent names (#429); callers pass it as an int or a long. */
/** The calendar an insert intent names (#429); callers pass it as an int, a long or a string. */
@Suppress("DEPRECATION")
private fun Intent.calendarIdExtraOrNull(): Long? =
(extras?.get(CalendarContract.Events.CALENDAR_ID) as? Number)?.toLong()?.takeIf { it > 0 }
when (val value = extras?.get(CalendarContract.Events.CALENDAR_ID)) {
is Number -> value.toLong()
is String -> value.trim().toLongOrNull()
else -> null
}?.takeIf { it > 0 }
/**
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
@@ -163,7 +164,7 @@ class SettingsPrefs @Inject constructor(
val defaultFormFields: Flow<Set<EventFormField>> = prefs.flow(SettingsKeys.defaultFormFields)
val recentTimeZones: Flow<List<String>> = prefs.flow(SettingsKeys.recentTimeZones)
val autofocusEventTitle: Flow<Boolean> = prefs.flow(SettingsKeys.autofocusEventTitle)
val defaultNewEventCalendarId: Flow<Long?> = prefs.flow(SettingsKeys.defaultNewEventCalendarId)
val defaultNewEventCalendar: Flow<DefaultCalendarRef?> = prefs.flow(SettingsKeys.defaultNewEventCalendar)
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
@@ -258,8 +259,9 @@ class SettingsPrefs @Inject constructor(
suspend fun setAutofocusEventTitle(enabled: Boolean) = prefs.set(SettingsKeys.autofocusEventTitle, enabled)
/** [id] null goes back to Automatic. */
suspend fun setDefaultNewEventCalendarId(id: Long?) = prefs.set(SettingsKeys.defaultNewEventCalendarId, id)
/** [calendar] null goes back to Automatic. */
suspend fun setDefaultNewEventCalendar(calendar: DefaultCalendarRef?) =
prefs.set(SettingsKeys.defaultNewEventCalendar, calendar)
suspend fun setDefaultEventDurationMinutes(minutes: Int) =
prefs.set(SettingsKeys.defaultEventDurationMinutes, minutes)
@@ -579,7 +581,8 @@ object SettingsKeys {
* calendar). Kept when the calendar stops being a target, which only makes
* it fall back for as long as that lasts.
*/
val defaultNewEventCalendarId: Pref<Long?> = nullableLongPref("default_new_event_calendar_id")
val defaultNewEventCalendar: Pref<DefaultCalendarRef?> =
nullableStringPref("default_new_event_calendar").map(DefaultCalendarRef::decode) { it?.encode() }
/**
* How long a new **timed** event lasts, in minutes (#54). Per-calendar
@@ -14,7 +14,7 @@ import kotlin.time.Instant
* next full hour, and a placeholder hour for a missing end that the form then
* stretches to the default-duration setting (the intent is opened as
* `ImportSource.InsertOpenEnded`, #54). [calendarId] is the calendar the
* intent names, if any; the editor preselects it while writable and otherwise
* intent names, if any; the editor preselects it while it is a target and otherwise
* resolves the calendar like a plain new event (#429).
*
* Pure (no Android types) so it is unit-testable; the intent parsing that reads
@@ -1,5 +1,39 @@
package de.jeanlucmakiola.calendula.domain
/**
* The calendar chosen as default for new events (#429). Provider ids are
* device-local and can be handed out again, so the account and name ride along
* and the choice only holds while the calendar under [id] still matches them,
* e.g. not after a backup restore onto another device.
*/
data class DefaultCalendarRef(
val id: Long,
val accountType: String,
val accountName: String,
val displayName: String,
) {
fun matches(calendar: CalendarSource): Boolean =
calendar.id == id &&
calendar.accountType == accountType &&
calendar.accountName == accountName &&
calendar.displayName == displayName
fun encode(): String = listOf(id.toString(), accountType, accountName, displayName).joinToString(SEPARATOR)
companion object {
private const val SEPARATOR = "\u001F"
fun of(calendar: CalendarSource) =
DefaultCalendarRef(calendar.id, calendar.accountType, calendar.accountName, calendar.displayName)
fun decode(stored: String?): DefaultCalendarRef? {
val parts = stored?.split(SEPARATOR, limit = 4)?.takeIf { it.size == 4 } ?: return null
val id = parts[0].toLongOrNull() ?: return null
return DefaultCalendarRef(id, parts[1], parts[2], parts[3])
}
}
}
/**
* What decides a new event's calendar when the user hasn't picked one (#429).
* [requested] is a calendar named by whoever opened the form (an insert intent,
@@ -8,21 +42,21 @@ package de.jeanlucmakiola.calendula.domain
*/
data class NewEventCalendarHints(
val requested: Long? = null,
val default: Long? = null,
val default: DefaultCalendarRef? = null,
val lastUsed: Long? = null,
)
/**
* The calendar the event form targets: [picked] when set, otherwise a writable
* [NewEventCalendarHints.requested] calendar, then the default and the last-used
* calendar while each is still an event target, then the first target.
* The calendar the event form targets: [picked] when set, otherwise the first of
* the requested, default and last-used calendar that is still an event target,
* then the first target.
*/
fun resolveEventCalendar(
picked: Long?,
hints: NewEventCalendarHints,
calendars: List<CalendarSource>,
): Long? = picked
?: hints.requested?.takeIf { id -> calendars.any { it.id == id && it.canModifyContents } }
?: hints.requested?.takeIf { id -> calendars.any { it.id == id && it.isEventTarget } }
?: effectiveDefaultCalendar(hints.default, calendars)?.id
?: hints.lastUsed?.takeIf { id -> calendars.any { it.id == id && it.isEventTarget } }
?: calendars.firstOrNull { it.isEventTarget }?.id
@@ -31,5 +65,13 @@ fun resolveEventCalendar(
* The default calendar setting as it applies now: null ("Automatic") when unset,
* or when the stored calendar is gone, read-only or switched off.
*/
fun effectiveDefaultCalendar(defaultId: Long?, calendars: List<CalendarSource>): CalendarSource? =
defaultId?.let { id -> calendars.firstOrNull { it.id == id && it.isEventTarget } }
fun effectiveDefaultCalendar(default: DefaultCalendarRef?, calendars: List<CalendarSource>): CalendarSource? =
default?.let { ref -> calendars.firstOrNull { ref.matches(it) && it.isEventTarget } }
/**
* The stored default calendar while it still exists but can't take new events
* (switched off, read-only, managed), so the setting can say why it reads
* Automatic. Null when it applies, is unset or is gone.
*/
fun unavailableDefaultCalendar(default: DefaultCalendarRef?, calendars: List<CalendarSource>): CalendarSource? =
default?.let { ref -> calendars.firstOrNull { ref.matches(it) && !it.isEventTarget } }
@@ -184,7 +184,7 @@ class EventEditViewModel @Inject constructor(
// reminders with the settings default (#49). Null while there's nothing to ask.
private val _importReminderPrompt = MutableStateFlow<ImportReminderPrompt?>(null)
// A calendar named by an insert intent or a duplicate's source (#429); wins
// over the default calendar while it can still take events.
// over the default calendar while it is an event target.
private val _requestedCalendarId = MutableStateFlow<Long?>(null)
// The form as the user received it: the loaded event, or a new form with its
// prefill and auto-applied defaults. Anything else is an unsaved change.
@@ -269,7 +269,7 @@ class EventEditViewModel @Inject constructor(
private val calendarHints: Flow<NewEventCalendarHints> = combine(
_requestedCalendarId,
settingsPrefs.defaultNewEventCalendarId,
settingsPrefs.defaultNewEventCalendar,
prefs.lastUsedCalendarId,
::NewEventCalendarHints,
)
@@ -414,9 +414,9 @@ class EventEditViewModel @Inject constructor(
* Seed a fresh event from a prefilled [form] — a parsed single-event `.ics`
* file ([ImportSource.File]) or an external `ACTION_INSERT` intent (another
* app/widget creating an event, e.g. Google Maps' "add to calendar";
* [ImportSource.Insert]; #30, #49). For an insert, a set [EventForm.calendarId]
* is the calendar the caller asked for: it is preselected while writable, and
* the form otherwise resolves its calendar like a new event (#429).
* [ImportSource.Insert]; #30, #49). A set [EventForm.calendarId] is the
* calendar the caller asked for: it is preselected while it is an event
* target, and the form otherwise resolves its calendar like a new event (#429).
*
* Reminders are handled per [source], because the two paths mean different
* things by "no reminders":
@@ -439,9 +439,8 @@ class EventEditViewModel @Inject constructor(
fun openImported(form: EventForm, source: ImportSource) {
if (_form.value != null || _editTarget.value != null) return
_revealed.value = form.populatedFields()
val insert = source != ImportSource.File
_requestedCalendarId.value = form.calendarId.takeIf { insert }
open(if (insert) form.copy(calendarId = null) else form)
_requestedCalendarId.value = form.calendarId
open(form.copy(calendarId = null))
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
when (source) {
ImportSource.Insert, ImportSource.InsertOpenEnded ->
@@ -90,6 +90,9 @@ internal fun EventFormScreen(
GroupedRow(
title = stringResource(R.string.settings_default_calendar),
summary = state.defaultNewEventCalendar?.displayName?.orUnnamed()
?: state.unavailableDefaultCalendar?.let {
stringResource(R.string.settings_default_calendar_unavailable, it.displayName.orUnnamed())
}
?: stringResource(R.string.settings_default_calendar_automatic),
position = Position.Alone,
leading = {
@@ -188,7 +191,7 @@ internal fun EventFormScreen(
calendars = state.eventTargetCalendars,
selectedId = state.defaultNewEventCalendar?.id,
onSelect = { id ->
viewModel.setDefaultNewEventCalendar(id)
viewModel.setDefaultNewEventCalendar(state.eventTargetCalendars.firstOrNull { it.id == id })
showDefaultCalendar = false
},
onDismiss = { showDefaultCalendar = false },
@@ -102,6 +102,8 @@ data class SettingsUiState(
val eventTargetCalendars: List<CalendarSource> = emptyList(),
/** The default calendar for new events (#429); null is Automatic, also when the stored one fell out. */
val defaultNewEventCalendar: CalendarSource? = null,
/** The stored default while it exists but takes no new events, named on the Automatic row. */
val unavailableDefaultCalendar: CalendarSource? = null,
/**
* Whether the event-colour picker is offered on calendars that publish no
* colour palette (the colour may then not survive their next sync).
@@ -37,7 +37,9 @@ import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
import de.jeanlucmakiola.calendula.domain.effectiveDefaultCalendar
import de.jeanlucmakiola.calendula.domain.unavailableDefaultCalendar
import de.jeanlucmakiola.calendula.domain.isEventTarget
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
@@ -128,7 +130,8 @@ class SettingsViewModel @Inject constructor(
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
writableCalendars = calendars.filter { it.canModifyContents && it.isVisibleInSystem },
eventTargetCalendars = calendars.filter { it.isEventTarget },
defaultNewEventCalendar = effectiveDefaultCalendar(this[SettingsKeys.defaultNewEventCalendarId], calendars),
defaultNewEventCalendar = effectiveDefaultCalendar(this[SettingsKeys.defaultNewEventCalendar], calendars),
unavailableDefaultCalendar = unavailableDefaultCalendar(this[SettingsKeys.defaultNewEventCalendar], calendars),
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
managedCalendarIds = specialDatesCalendars.values.toSet(),
)
@@ -362,7 +365,9 @@ class SettingsViewModel @Inject constructor(
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
fun setDefaultNewEventCalendar(id: Long?) = save { setDefaultNewEventCalendarId(id) }
/** [calendar] null goes back to Automatic. */
fun setDefaultNewEventCalendar(calendar: CalendarSource?) =
save { setDefaultNewEventCalendar(calendar?.let(DefaultCalendarRef::of)) }
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
+1
View File
@@ -707,6 +707,7 @@
<string name="settings_form_fields_hint">Fields shown by default — everything else sits behind \"More fields\"</string>
<string name="settings_default_calendar">Default calendar</string>
<string name="settings_default_calendar_automatic">Automatic</string>
<string name="settings_default_calendar_unavailable">Automatic while %1$s is switched off or read-only</string>
<string name="settings_default_calendar_automatic_hint">The calendar you last added an event to</string>
<string name="settings_autofocus_title">Focus title on new event</string>
<string name="settings_autofocus_title_hint">When you start a new event, place the cursor in the title field and open the keyboard right away.</string>
@@ -21,6 +21,8 @@ class NewEventCalendarTest {
isManaged = managed,
)
private fun ref(id: Long) = DefaultCalendarRef.of(cal(id))
private val calendars = listOf(
cal(1L),
cal(2L),
@@ -32,39 +34,41 @@ class NewEventCalendarTest {
@Test
fun `a user pick always wins`() {
val hints = NewEventCalendarHints(requested = 2L, default = 3L, lastUsed = 1L)
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L), lastUsed = 1L)
assertThat(resolveEventCalendar(4L, hints, calendars)).isEqualTo(4L)
}
@Test
fun `a requested calendar beats the default`() {
val hints = NewEventCalendarHints(requested = 2L, default = 3L)
val hints = NewEventCalendarHints(requested = 2L, default = ref(3L))
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
}
@Test
fun `a requested calendar only needs to be writable`() {
assertThat(resolveEventCalendar(null, NewEventCalendarHints(requested = 5L, default = 3L), calendars))
.isEqualTo(5L)
assertThat(resolveEventCalendar(null, NewEventCalendarHints(requested = 4L, default = 3L), calendars))
.isEqualTo(3L)
assertThat(resolveEventCalendar(null, NewEventCalendarHints(requested = 99L, default = 3L), calendars))
.isEqualTo(3L)
fun `a requested calendar that is no target falls back to the default`() {
listOf(4L, 5L, 6L, 99L).forEach { requested ->
val hints = NewEventCalendarHints(requested = requested, default = ref(3L))
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
}
}
@Test
fun `the default beats the last used calendar`() {
val hints = NewEventCalendarHints(default = 3L, lastUsed = 2L)
val hints = NewEventCalendarHints(default = ref(3L), lastUsed = 2L)
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L)
}
@Test
fun `a default that is no target falls back to the last used calendar`() {
listOf(4L, 5L, 6L, 99L).forEach { default ->
listOf(4L, 5L, 6L).forEach { id ->
val default = DefaultCalendarRef.of(calendars.single { it.id == id })
val hints = NewEventCalendarHints(default = default, lastUsed = 2L)
assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L)
assertThat(effectiveDefaultCalendar(default, calendars)).isNull()
assertThat(unavailableDefaultCalendar(default, calendars)?.id).isEqualTo(id)
}
assertThat(effectiveDefaultCalendar(ref(99L), calendars)).isNull()
assertThat(unavailableDefaultCalendar(ref(99L), calendars)).isNull()
}
@Test
@@ -76,7 +80,26 @@ class NewEventCalendarTest {
@Test
fun `the effective default is the stored calendar while it is a target`() {
assertThat(effectiveDefaultCalendar(3L, calendars)?.id).isEqualTo(3L)
assertThat(effectiveDefaultCalendar(ref(3L), calendars)?.id).isEqualTo(3L)
assertThat(unavailableDefaultCalendar(ref(3L), calendars)).isNull()
assertThat(effectiveDefaultCalendar(null, calendars)).isNull()
}
@Test
fun `a reused id under another calendar is not the default`() {
val reused = ref(3L).copy(displayName = "Deleted calendar")
assertThat(effectiveDefaultCalendar(reused, calendars)).isNull()
assertThat(effectiveDefaultCalendar(ref(3L).copy(accountName = "other"), calendars)).isNull()
assertThat(resolveEventCalendar(null, NewEventCalendarHints(default = reused, lastUsed = 2L), calendars))
.isEqualTo(2L)
}
@Test
fun `the stored reference round-trips`() {
val stored = DefaultCalendarRef(12L, "com.google", "me@example.com", "Work | Team")
assertThat(DefaultCalendarRef.decode(stored.encode())).isEqualTo(stored)
assertThat(DefaultCalendarRef.decode(null)).isNull()
assertThat(DefaultCalendarRef.decode("12")).isNull()
assertThat(DefaultCalendarRef.decode("x\u001Fa\u001Fb\u001Fc")).isNull()
}
}
@@ -10,6 +10,7 @@ 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.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
@@ -727,7 +728,7 @@ class EventEditViewModelTest {
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendarId(2L)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
s.setCalendarReminderOverride(2L, ReminderOverride.Minutes(listOf(5)))
val p = prefs(tempDir)
p.setLastUsedCalendarId(1L)
@@ -749,7 +750,7 @@ class EventEditViewModelTest {
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendarId(2L)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
@@ -766,7 +767,7 @@ class EventEditViewModelTest {
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L), cal(3L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendarId(2L)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)
@@ -787,7 +788,7 @@ class EventEditViewModelTest {
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) }
val s = settings(tempDir)
s.setDefaultNewEventCalendarId(2L)
s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L)))
val vm = viewModel(tempDir, fake, s)
val job = activate(vm)