fix(#481): snackbar feedback, uncancellable import, mirror per-type matching, progress

This commit is contained in:
makiolaj committed 2026-11-13 21:09:06 +01:00
1 parent 5ee25c2115
commit 47f3844d75
8 files changed
+112 -34

No files matched your search

@@ -10,7 +10,6 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.floret.backup.BackupDocument
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.backup.PrefsSection
import de.jeanlucmakiola.floret.backup.invalidBackup
import de.jeanlucmakiola.floret.backup.optBoolean
import de.jeanlucmakiola.floret.backup.optIntList
import de.jeanlucmakiola.floret.backup.optObject
@@ -164,8 +163,6 @@ private fun CalendarSettings.toJson(): JsonObject = buildJsonObject {
* reads as an ordinary calendar, which then simply finds no match.
*/
private fun JsonObject.toCalendarSettings(): CalendarSettings {
val duration = optInt(KEY_EVENT_DURATION)
if (duration != null && duration <= 0) invalidBackup("$KEY_EVENT_DURATION: $duration")
return CalendarSettings(
calendar = CalendarIdentity(
accountName = requireString(KEY_ACCOUNT_NAME),
@@ -175,7 +172,7 @@ private fun JsonObject.toCalendarSettings(): CalendarSettings {
),
hidden = optBoolean(KEY_HIDDEN) ?: false,
lastUsed = optBoolean(KEY_LAST_USED) ?: false,
eventDurationMinutes = duration,
eventDurationMinutes = optInt(KEY_EVENT_DURATION),
reminders = optIntList(KEY_REMINDERS),
allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS),
)
@@ -13,8 +13,10 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncResult
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
import de.jeanlucmakiola.calendula.domain.FontRole
@@ -24,6 +26,7 @@ import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.di.IoDispatcher
import de.jeanlucmakiola.floret.locale.AppLanguage
import de.jeanlucmakiola.floret.prefs.get
import de.jeanlucmakiola.floret.prefs.rawValue
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
@@ -46,6 +49,7 @@ class SettingsBackupEngine @Inject constructor(
private val calendars: CalendarDataSource,
private val contacts: ContactSpecialDatesDataSource,
private val specialDates: SpecialDatesSyncEngine,
private val settingsPrefs: SettingsPrefs,
private val reminderScanner: ReminderScanner,
private val launcherNames: LauncherNameManager,
@ApplicationContext private val context: Context,
@@ -75,16 +79,17 @@ class SettingsBackupEngine @Inject constructor(
}
val current = store.data.first()
val plan = planSettingsImport(backup, current, environment(current))
try {
withContext(NonCancellable) { store.edit { plan.applyTo(it) } }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "Settings import could not be written", e)
return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty())
// Once the write starts, the side effects have to follow it, whoever cancels.
withContext(NonCancellable) {
try {
store.edit { plan.applyTo(it) }
} catch (e: Exception) {
Log.w(TAG, "Settings import could not be written", e)
return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty())
}
val lateSkips = afterImport(plan, current)
BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped))
}
val lateSkips = withContext(NonCancellable) { afterImport(plan, current) }
BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped))
}
private class LateMatches(val matched: Int, val skipped: List<SkippedSetting>)
@@ -102,8 +107,15 @@ class SettingsBackupEngine @Inject constructor(
step("special dates") {
if (mirroring) {
SpecialDatesScheduler.apply(context, enabled = true)
specialDates.sync()
late = matchSpecialDates(plan, backup = plan.calendars != null)
val result = specialDates.sync()
if (result != SpecialDatesSyncResult.Disabled) {
val stalled = SpecialDatesStalledReason.PermissionRevoked
.takeIf { result == SpecialDatesSyncResult.PermissionMissing }
settingsPrefs.recordSpecialDatesRun(System.currentTimeMillis(), stalled)
}
if (result == SpecialDatesSyncResult.Success) {
late = matchSpecialDates(plan, backup = plan.calendars != null)
}
} else if (wasMirroring) {
SpecialDatesScheduler.apply(context, enabled = false)
specialDates.teardown()
@@ -155,8 +167,11 @@ class SettingsBackupEngine @Inject constructor(
val entries = (plan.calendars.orEmpty().values + resolved.map { it.second })
.mapNotNull { entry -> entry.calendar.specialDates?.let { it to entry } }
.toMap()
managed.map { it.type }.distinct().forEach { type ->
val stored = store.data.first()[SettingsKeys.perCalendarAllDayReminderOverride]
managed.distinctBy { it.type }.forEach { (id, type) ->
val minutes = entries[type]?.allDayReminders
// The sync wrote the events with the stored override; only a change needs rewriting.
if (stored[id] == minutes) return@forEach
val override = when {
minutes == null -> ReminderOverride.Inherit
minutes.isEmpty() -> ReminderOverride.None
@@ -181,11 +196,7 @@ class SettingsBackupEngine @Inject constructor(
)
private fun Preferences.hasCalendarSettings(): Boolean =
this[CalendarPrefKeys.hiddenCalendarIds].isNotEmpty() ||
this[CalendarPrefKeys.lastUsedCalendarId] != null ||
this[SettingsKeys.perCalendarEventDuration].isNotEmpty() ||
this[SettingsKeys.perCalendarReminderOverride].isNotEmpty() ||
this[SettingsKeys.perCalendarAllDayReminderOverride].isNotEmpty()
SettingsBackupSchema.perCalendar.any { rawValue(it) != null }
private fun supportedLanguages(): List<String> = AppLanguage.supportedTags(context, R.xml.locales_config)
@@ -6,6 +6,7 @@ import de.jeanlucmakiola.calendula.data.appname.LauncherName
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
@@ -123,7 +124,9 @@ fun planSettingsImport(
backup.calendars.forEach { entry ->
val type = entry.calendar.specialDates
if (type != null) {
if (!mirroring) return@forEach
// The mirror only keeps calendars for the types the imported settings switch on.
val typeOn = prefs[SettingsKeys.specialDateTypeEnabled.getValue(type)] != false
if (!mirroring || !typeOn) return@forEach
val id = environment.managed.firstOrNull { it.type == type }?.id
if (id != null) calendars[id] = entry else pending += entry
return@forEach
@@ -160,7 +163,7 @@ fun MutablePreferences.writeCalendarSettings(calendars: Map<Long, CalendarSettin
this[CalendarPrefKeys.hiddenCalendarIds] = calendars.filterValues { it.hidden }.keys
this[CalendarPrefKeys.lastUsedCalendarId] = calendars.entries.firstOrNull { it.value.lastUsed }?.key
this[SettingsKeys.perCalendarEventDuration] =
calendars.mapNotNull { (id, entry) -> entry.eventDurationMinutes?.let { id to it } }.toMap()
calendars.mapNotNull { (id, entry) -> entry.eventDurationMinutes?.let { id to it.clampDuration() } }.toMap()
this[SettingsKeys.perCalendarReminderOverride] =
calendars.mapNotNull { (id, entry) -> entry.reminders?.let { id to it } }.toMap()
this[SettingsKeys.perCalendarAllDayReminderOverride] =
@@ -174,7 +177,8 @@ fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
this[CalendarPrefKeys.lastUsedCalendarId] = id
}
entry.eventDurationMinutes?.let {
this[SettingsKeys.perCalendarEventDuration] = this[SettingsKeys.perCalendarEventDuration] + (id to it)
this[SettingsKeys.perCalendarEventDuration] =
this[SettingsKeys.perCalendarEventDuration] + (id to it.clampDuration())
}
entry.reminders?.let {
this[SettingsKeys.perCalendarReminderOverride] = this[SettingsKeys.perCalendarReminderOverride] + (id to it)
@@ -199,6 +203,9 @@ private fun CalendarSource.matches(identity: CalendarIdentity): Boolean =
accountName == identity.accountName &&
displayName == identity.displayName
/** The same range the per-calendar duration setter clamps to. */
private fun Int.clampDuration(): Int = coerceIn(SettingsPrefs.MIN_EVENT_DURATION, SettingsPrefs.MAX_EVENT_DURATION)
private fun FontRole.fontPref(): Pref<String> = when (this) {
FontRole.BRAND -> SettingsKeys.brandFont
FontRole.PLAIN -> SettingsKeys.plainFont
@@ -10,6 +10,9 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
@@ -149,12 +152,14 @@ fun BackupScreen(
visible = visible,
) {
when (val s = state) {
BackupUiState.Loading -> {
Box(Modifier.weight(1f)) { BackupLoading() }
// The settings block still works here, below a state that scrolls
// away with it rather than squeezing it off a short screen.
BackupUiState.Loading -> Column(Modifier.verticalScroll(rememberScrollState())) {
Box(Modifier.fillMaxWidth().heightIn(min = STATE_MIN_HEIGHT), contentAlignment = Alignment.Center) { BackupLoading() }
SettingsBackupSection(settings)
}
is BackupUiState.Failure -> {
Box(Modifier.weight(1f)) { CalendarFailure(reason = s.reason, onRetry = onBack) }
is BackupUiState.Failure -> Column(Modifier.verticalScroll(rememberScrollState())) {
Box(Modifier.fillMaxWidth().heightIn(min = STATE_MIN_HEIGHT), contentAlignment = Alignment.Center) { CalendarFailure(reason = s.reason, onRetry = onBack) }
SettingsBackupSection(settings)
}
is BackupUiState.Ready -> BackupContent(
@@ -449,5 +454,6 @@ private fun BackupIntervalDialog(
)
}
private val STATE_MIN_HEIGHT = 360.dp
private const val MINUTES_PER_DAY = 1_440L
private const val MINUTES_PER_WEEK = 10_080L
@@ -4,12 +4,15 @@ import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FileDownload
import androidx.compose.material.icons.filled.FileUpload
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
@@ -33,6 +36,7 @@ import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.Position
@@ -89,11 +93,18 @@ fun SettingsBackupSection(actions: SettingsBackupActions) {
dimmed = actions.busy,
onClick = { if (!actions.busy) actions.import() },
)
if (actions.busy) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = GroupedListInset, vertical = 16.dp),
)
}
}
/**
* The import's confirmation and summary dialogs, and the snackbars for
* everything else. Plain confirmations, so [AlertDialog]s.
* everything else.
*/
@Composable
fun SettingsBackupDialogs(
@@ -113,8 +124,8 @@ fun SettingsBackupDialogs(
is SettingsBackupResult.ImportFailed -> importFailed.getValue(r.problem)
is SettingsBackupResult.Imported, null -> return@LaunchedEffect
}
viewModel.consumeResult()
snackbarHostState.showSnackbar(message)
viewModel.consumeResult()
}
(result as? SettingsBackupResult.Imported)?.let { imported ->
@@ -147,6 +147,52 @@ class SettingsBackupTest {
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
}
@Test
fun `every per-calendar key travels with its calendar`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
source[CalendarPrefKeys.lastUsedCalendarId] = 1L
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5))
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0))
val target = mutablePreferencesOf()
import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList()))
// One assertion per key in the schema: a new per-calendar key fails here until it is carried.
SettingsBackupSchema.perCalendar.forEach { pref ->
assertThat(target.asMap().keys.map { it.name }).contains(pref.name)
}
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0))
}
@Test
fun `a mirror type the import switches off is left out`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.specialDateTypeEnabled.getValue(SpecialDateType.Birthday)] = false
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target)
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.pendingSpecialDates).isEmpty()
assertThat(plan.skipped).isEmpty()
}
@Test
fun `an out-of-range calendar length is clamped, not refused`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":5000}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
val target = mutablePreferencesOf()
import(backup, target)
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440)
}
@Test
fun `unreadable calendars leave the per-calendar settings alone`() {
val source = mutablePreferencesOf()
+2 -2
View File
@@ -82,7 +82,7 @@ identity instead:
| `special_dates` | String? | `Birthday`/`Anniversary`/`Custom` for a contact-dates mirror calendar. |
| `hidden` | Boolean | Hidden in the drawer's filter. |
| `last_used` | Boolean | Preselected for new events. |
| `event_duration_minutes` | Int? | Per-calendar default length. |
| `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. |
@@ -90,7 +90,7 @@ On import an entry matches the one calendar here with the same account name,
account type and display name. No match, or more than one, skips it and the
summary names it. A mirror calendar matches by `special_dates` instead, since
its name is localised, and only when the imported settings keep the mirror on
(otherwise the import tears it down). When the mirror has not created it yet,
and the type (otherwise the import tears that calendar down). When the mirror has not created it yet,
it is matched after the import's sync. Every mirror's all-day reminders are
applied through the mirror so its existing events follow; one the file doesn't
override inherits the default again. An id in the prefs whose calendar no