Compare commits

...
Author SHA1 Message Date
makiolaj f9b4ebd167 Release v2.25.0-beta.2
Beta — Codeberg pre-release / detect (push) Successful in 3s
Beta — Codeberg pre-release / beta (push) Successful in 11m51s
2026-11-25 16:32:09 +01:00
makiolaj 08df8ca77c Merge fix/459-summary-pointer into release/2.25.0 2026-11-25 16:28:38 +01:00
makiolaj 9a872bd3d9 Merge fix/143-hide-in-view-label into release/2.25.0 2026-11-25 16:28:38 +01:00
makiolaj 2e65421f68 Merge fix/530-widget-back-home into release/2.25.0 2026-11-25 16:28:38 +01:00
makiolaj a705c89656 Merge fix/516-interval-off into release/2.25.0 2026-11-25 16:28:38 +01:00
makiolaj b328fa8e42 Merge fix/502-imported-series-edit into release/2.25.0 2026-11-25 16:28:38 +01:00
makiolaj 616e468328 fix(#530): review round 6 - one leave target, home reset as its own request, detail delete and up arrow stay in app 2026-11-25 16:01:10 +01:00
makiolaj 8306e8c636 fix(#530): review round 5 - a widget's event detail also leaves on back 2026-11-25 15:51:36 +01:00
makiolaj 7a8c41c73d fix(#143): review round 3 - name the view in the row notes, entry summary and picker hint 2026-11-25 15:32:27 +01:00
makiolaj 830e48c5e7 fix(#516): review round 4 - id suffix sticks, run-now rewrites every copy again, unchanged blocked series don't count as success 2026-11-25 15:31:55 +01:00
makiolaj 8bdc886226 fix(#530): review round 4 - home view reset on return, leave hint instead of stop, no clear-top 2026-11-25 15:30:38 +01:00
makiolaj 4a14ebde2d fix(#516): review round 3 - restore missing stable copies on change runs, blocked series reported once, kept copies of deselected calendars suffix the name 2026-11-25 15:20:11 +01:00
makiolaj cd7474f314 fix(#530): review round 3 - widget day backs to home warm, pending nav restored as sent 2026-11-25 15:18:48 +01:00
makiolaj fc1a76f274 fix(#502): review round 3 - length checked before inserting, sync cancel and all-day spans covered 2026-11-25 15:17:15 +01:00
makiolaj 2970ca08d0 fix(#530): replay a date open that was never handled 2026-11-25 12:30:48 +01:00
makiolaj 2f51260f9d fix(#502): review round 2 - length only checked where the series is re-expanded, zero spans kept 2026-11-25 12:30:34 +01:00
makiolaj 85cf59ad82 fix(#502): review round 1 - occurrence span first, no guessed length, move path covered 2026-11-25 12:23:38 +01:00
makiolaj ed4129580b fix(#530): arm the exit only for a widget's day, skip it on replay 2026-11-25 12:17:45 +01:00
makiolaj 732548a989 fix(#516): keep a blocked series' hash, back up when a settings restore switches the interval 2026-11-25 12:16:32 +01:00
makiolaj 0652859ecc fix(#502): series rows without a usable DURATION no longer lose their occurrences on a single edit or delete 2026-11-25 12:16:05 +01:00
makiolaj 613ddfb532 fix(#143): give the named title a fresh key, keep docs in step 2026-11-25 12:13:15 +01:00
makiolaj 3039d48aa4 fix(#530): keep the home view under a widget's day, finish on back 2026-11-25 12:12:38 +01:00
makiolaj 242ccd3b70 fix(#516): don't retry a run only blocked series failed, back up on any interval switch 2026-11-25 12:12:22 +01:00
makiolaj 4d342c98ad fix(#516): flag series the undated copy can't cover, back up when the interval returns 2026-11-25 12:08:44 +01:00
makiolaj 0e859622c6 fix(#530): open a widget's day on its own so back returns home 2026-11-25 12:07:51 +01:00
makiolaj 2eeabb40c8 fix(#143): quote the view name and share the title 2026-11-25 12:07:50 +01:00
makiolaj 81c38b424d fix(#143): name the view in the hide-in-view label 2026-11-25 12:04:13 +01:00
makiolaj 91cb57f940 fix(#516): hide the interval switch without after-change backups and test the interval rules 2026-11-25 12:03:36 +01:00
makiolaj b15b324965 fix(#516): let the backup interval be switched off while backing up after changes 2026-11-20 22:15:57 +01:00
33 changed files with 715 additions and 150 deletions

No files matched your search

+7 -1
View File
@@ -20,13 +20,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **A default calendar for new events,** under Settings → Event form; Automatic keeps the one you last used ([#429]). - **A default calendar for new events,** under Settings → Event form; Automatic keeps the one you last used ([#429]).
- **Sync now.** The drawer can ask your sync apps to sync, and shows when they are done. Calendula also nudges them after you change an event in a synced calendar, so edits reach the server sooner ([#240], [#303]). - **Sync now.** The drawer can ask your sync apps to sync, and shows when they are done. Calendula also nudges them after you change an event in a synced calendar, so edits reach the server sooner ([#240], [#303]).
- **Copy events between calendars,** for example from a synced calendar into a local or DAVx5 one, with exceptions of repeating events, progress and Cancel ([#325]). - **Copy events between calendars,** for example from a synced calendar into a local or DAVx5 one, with exceptions of repeating events, progress and Cancel ([#325]).
- **Back up synced calendars too,** each into its own file. The automatic backup keeps one up-to-date copy per calendar next to the dated ones, lets you choose how many dated files to keep, and can run right after a change instead of only on its schedule ([#147], [#411], [#516]). - **Back up synced calendars too,** each into its own file. The automatic backup keeps one up-to-date copy per calendar next to the dated ones, lets you choose how many dated files to keep, and can run right after a change, with or without the schedule ([#147], [#411], [#516]).
- **Back up and restore your settings.** Backup & restore → Settings saves Calendula's settings to a file and reads one back, also on another phone; per-calendar settings find their calendar by account and name ([#481]). - **Back up and restore your settings.** Backup & restore → Settings saves Calendula's settings to a file and reads one back, also on another phone; per-calendar settings find their calendar by account and name ([#481]).
### Changed ### Changed
- **Back from a widget goes back to your home screen.** A day or event opened from a widget no longer leaves you in the app's month view on Back ([#530]).
- **Hiding calendars names the view.** The drawer and the picker say which view the setting applies to, e.g. Hide in “Month” view ([#143]).
- **The daily summary is one tap away** from "Reminder at a set time" ([#459]).
- **All-day reminders show the day they fire on.** A reminder kept from a timed event no longer reads "30 minutes before" on an all-day event ([#514]). - **All-day reminders show the day they fire on.** A reminder kept from a timed event no longer reads "30 minutes before" on an all-day event ([#514]).
### Fixed ### Fixed
- **Editing one occurrence no longer wipes the rest of a series** whose events were stored without a length, as some imported Google Calendar series were. Deleting a single occurrence was affected too ([#502]).
- **Repeating events with extra dates survive a backup.** `.ics` backups now write and read back RDATE ([#515]). - **Repeating events with extra dates survive a backup.** `.ics` backups now write and read back RDATE ([#515]).
## [2.24.2] — 2026-11-13 ## [2.24.2] — 2026-11-13
@@ -2023,8 +2027,10 @@ automatically, with zero telemetry and no internet permission.
[#459]: https://codeberg.org/jlmakiola/calendula/issues/459 [#459]: https://codeberg.org/jlmakiola/calendula/issues/459
[#464]: https://codeberg.org/jlmakiola/calendula/issues/464 [#464]: https://codeberg.org/jlmakiola/calendula/issues/464
[#481]: https://codeberg.org/jlmakiola/calendula/issues/481 [#481]: https://codeberg.org/jlmakiola/calendula/issues/481
[#502]: https://codeberg.org/jlmakiola/calendula/issues/502
[#514]: https://codeberg.org/jlmakiola/calendula/issues/514 [#514]: https://codeberg.org/jlmakiola/calendula/issues/514
[#515]: https://codeberg.org/jlmakiola/calendula/issues/515 [#515]: https://codeberg.org/jlmakiola/calendula/issues/515
[#516]: https://codeberg.org/jlmakiola/calendula/issues/516 [#516]: https://codeberg.org/jlmakiola/calendula/issues/516
[#517]: https://codeberg.org/jlmakiola/calendula/issues/517 [#517]: https://codeberg.org/jlmakiola/calendula/issues/517
[#518]: https://codeberg.org/jlmakiola/calendula/issues/518 [#518]: https://codeberg.org/jlmakiola/calendula/issues/518
[#530]: https://codeberg.org/jlmakiola/calendula/issues/530
+2 -2
View File
@@ -32,8 +32,8 @@ android {
// (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001, // (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001,
// 2.22.4 -> 2220499), and CI fails if the committed one doesn't match. // 2.22.4 -> 2220499), and CI fails if the committed one doesn't match.
// See docs/RELEASING.md. // See docs/RELEASING.md.
versionCode = 2250001 versionCode = 2250002
versionName = "2.25.0-beta.1" versionName = "2.25.0-beta.2"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
@@ -24,6 +24,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.core.content.IntentCompat import androidx.core.content.IntentCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.os.BundleCompat
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
@@ -39,6 +40,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.buildInsertEventForm import de.jeanlucmakiola.calendula.domain.buildInsertEventForm
import de.jeanlucmakiola.calendula.domain.sharedTextOrNull import de.jeanlucmakiola.calendula.domain.sharedTextOrNull
import de.jeanlucmakiola.calendula.ui.ExternalRequests import de.jeanlucmakiola.calendula.ui.ExternalRequests
import de.jeanlucmakiola.calendula.ui.LeaveTarget
import de.jeanlucmakiola.calendula.ui.InsertRequest import de.jeanlucmakiola.calendula.ui.InsertRequest
import de.jeanlucmakiola.calendula.ui.RootScreen import de.jeanlucmakiola.calendula.ui.RootScreen
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
@@ -92,6 +94,10 @@ class MainActivity : AppCompatActivity() {
insertFormOpen = false insertFormOpen = false
if (launchedForInsert) finish() if (launchedForInsert) finish()
}, },
onLeave = {
homeOnReturn = moveTaskToBack(true)
homeOnReturn
},
) )
// Whether such a form is still open. Only then does a recreation re-read the // Whether such a form is still open. Only then does a recreation re-read the
@@ -102,6 +108,9 @@ class MainActivity : AppCompatActivity() {
// app that asked instead of leaving the calendar on top of it. // app that asked instead of leaving the calendar on top of it.
private var launchedForInsert = false private var launchedForInsert = false
// Back left a widget's day or event for the home screen; the next start shows the home view.
private var homeOnReturn = false
// A captured crash report awaiting the user's decision, surfaced as a dialog // A captured crash report awaiting the user's decision, surfaced as a dialog
// over the calendar on the next launch (the single-crash path). A startup // over the calendar on the next launch (the single-crash path). A startup
// crash-loop is handled out of band, before setContent — see below. // crash-loop is handled out of band, before setContent — see below.
@@ -150,7 +159,10 @@ class MainActivity : AppCompatActivity() {
// specific event is what made a single reminder or widget tap re-open // specific event is what made a single reminder or widget tap re-open
// that event on every later launch, an error screen once the event had // that event on every later launch, an error screen once the event had
// been deleted (#309); the user left it long ago, and the activity // been deleted (#309); the user left it long ago, and the activity
// restores where they actually were along with its saved state. // restores where they actually were along with its saved state. Every
// widget/shortcut navigation is held back the same way; one still pending
// at the recreation is restored from the saved state instead, so it's the
// request that actually arrived last, not the launch intent's (#530).
// //
// Only those channels are held back. An .ics import or a prefilled // Only those channels are held back. An .ics import or a prefilled
// create form keeps no saved state of its own, so re-reading the intent // create form keeps no saved state of its own, so re-reading the intent
@@ -162,8 +174,15 @@ class MainActivity : AppCompatActivity() {
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull() requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requests.editKey = intent.editEventKeyOrNull() requests.editKey = intent.editEventKeyOrNull()
} }
requests.nav = intent.navRequestOrNull() requests.nav = if (replaying) {
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent } savedInstanceState?.let { BundleCompat.getSerializable(it, KEY_PENDING_NAV, WidgetNavRequest::class.java) }
} else {
intent.navRequestOrNull()
}
requests.leaveTarget = savedInstanceState?.let {
BundleCompat.getSerializable(it, KEY_LEAVE_TARGET, LeaveTarget::class.java)
}
homeOnReturn = savedInstanceState?.getBoolean(KEY_HOME_ON_RETURN) == true
requests.importUri = intent.importUriOrNull() requests.importUri = intent.importUriOrNull()
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore } requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
@@ -274,10 +293,22 @@ class MainActivity : AppCompatActivity() {
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
// Reset only now, so the screen doesn't change while the task animates away.
// A request arriving with this start (onNewIntent comes after) opens over it.
if (homeOnReturn) {
homeOnReturn = false
requests.resetToHome = true
}
// Changes made while we were away may never have notified us (#364). // Changes made while we were away may never have notified us (#364).
calendarRepository.refresh() calendarRepository.refresh()
} }
override fun onUserLeaveHint() {
super.onUserLeaveHint()
// Once the user has left, a later return is no longer the widget's day or event.
requests.leaveTarget = null
}
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
// Reaching a running UI means startup succeeded; reset the loop trail. // Reaching a running UI means startup succeeded; reset the loop trail.
@@ -289,6 +320,9 @@ class MainActivity : AppCompatActivity() {
super.onSaveInstanceState(outState) super.onSaveInstanceState(outState)
outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen) outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen)
outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert) outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert)
outState.putSerializable(KEY_PENDING_NAV, requests.nav)
outState.putSerializable(KEY_LEAVE_TARGET, requests.leaveTarget)
outState.putBoolean(KEY_HOME_ON_RETURN, homeOnReturn)
} }
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
@@ -456,9 +490,9 @@ class MainActivity : AppCompatActivity() {
} }
private fun Intent.navRequestOrNull(): WidgetNavRequest? { private fun Intent.navRequestOrNull(): WidgetNavRequest? {
// An external date tap (launcher/clock) has no widget source, so it opens // An external date tap (launcher/clock) opens the day view over the default
// the day view rooted over the default home view (OpenDate source = null). // home view, and backs out to it.
calendarTimeDateOrNull()?.let { return WidgetNavRequest.OpenDate(it.toString(), source = null) } calendarTimeDateOrNull()?.let { return WidgetNavRequest.OpenDate(it.toString(), fromWidget = false) }
// A widget header tap: open a top-level view with no date drill-in. The // A widget header tap: open a top-level view with no date drill-in. The
// empty string carried by [openViewIntent] means "the default home view". // empty string carried by [openViewIntent] means "the default home view".
if (hasExtra(EXTRA_OPEN_VIEW)) { if (hasExtra(EXTRA_OPEN_VIEW)) {
@@ -481,8 +515,8 @@ class MainActivity : AppCompatActivity() {
endMillis = getLongExtra(EXTRA_END_MILLIS, 0L), endMillis = getLongExtra(EXTRA_END_MILLIS, 0L),
source = source, source = source,
) )
source != null && getStringExtra(EXTRA_DATE_ISO) != null -> getStringExtra(EXTRA_DATE_ISO) != null ->
WidgetNavRequest.OpenDate(getStringExtra(EXTRA_DATE_ISO)!!, source) WidgetNavRequest.OpenDate(getStringExtra(EXTRA_DATE_ISO)!!, fromWidget = true)
else -> null else -> null
} }
} }
@@ -564,6 +598,9 @@ class MainActivity : AppCompatActivity() {
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs") private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
private const val KEY_INSERT_FORM_OPEN = "insert_form_open" private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert" private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
private const val KEY_PENDING_NAV = "pending_nav"
private const val KEY_LEAVE_TARGET = "leave_target"
private const val KEY_HOME_ON_RETURN = "home_on_return"
private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID" private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN" private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
@@ -602,17 +639,13 @@ class MainActivity : AppCompatActivity() {
} }
/** /**
* Open the day view anchored on [date], drilled in over the launching * Open the day view anchored on [date] from a home-screen widget; backing
* widget's [source] view (home-screen widgets). Backing out of the day * out of the day returns to the home screen (#530).
* returns to [source], then to the default home view.
*/ */
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent = fun openDateIntent(context: Context, date: LocalDate): Intent =
Intent(context, MainActivity::class.java).apply { Intent(context, MainActivity::class.java).apply {
// The source is part of the URI so widgets of different kinds data = "calendula://date/$date".toUri()
// tapping the same date don't share one PendingIntent.
data = "calendula://date/$date/${source.name}".toUri()
putExtra(EXTRA_DATE_ISO, date.toString()) putExtra(EXTRA_DATE_ISO, date.toString())
putExtra(EXTRA_SOURCE_VIEW, source.name)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
} }
@@ -32,7 +32,9 @@ import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.backup.BackupFilePlan import de.jeanlucmakiola.calendula.domain.backup.BackupFilePlan
import de.jeanlucmakiola.calendula.domain.backup.BackupTarget import de.jeanlucmakiola.calendula.domain.backup.BackupTarget
import de.jeanlucmakiola.calendula.domain.backup.backedUp
import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint
import de.jeanlucmakiola.calendula.domain.backup.backupRunLatestOnly
import de.jeanlucmakiola.calendula.domain.backup.backupTargets import de.jeanlucmakiola.calendula.domain.backup.backupTargets
import de.jeanlucmakiola.calendula.domain.backup.inBackupOrder import de.jeanlucmakiola.calendula.domain.backup.inBackupOrder
import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere
@@ -76,8 +78,8 @@ object BackupScheduler {
/** /**
* Reconcile the scheduled work with the saved settings: enqueue a unique * Reconcile the scheduled work with the saved settings: enqueue a unique
* periodic request when backup is on and a folder is set, otherwise cancel * periodic request when backup is on, a folder is set and the interval
* it. WorkManager persists the request across reboots on its own. * isn't switched off (#516), otherwise cancel it. WorkManager persists the request across reboots on its own.
* *
* The first run is delayed by one interval so it doesn't follow an immediate * The first run is delayed by one interval so it doesn't follow an immediate
* [runNow] with a near-identical copy. With backing up after changes on * [runNow] with a near-identical copy. With backing up after changes on
@@ -109,16 +111,20 @@ object BackupScheduler {
stopWatching() stopWatching()
return return
} }
// WorkManager's own floor is 15 min; the UI floors the user choice at 30. if (prefs.autoBackupScheduled.first()) {
val interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L) // WorkManager's own floor is 15 min; the UI floors the user choice at 30.
val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES) val interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L)
.setInitialDelay(interval, TimeUnit.MINUTES) val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES)
.build() .setInitialDelay(interval, TimeUnit.MINUTES)
workManager.enqueueUniquePeriodicWork( .build()
WORK_NAME, workManager.enqueueUniquePeriodicWork(
ExistingPeriodicWorkPolicy.UPDATE, WORK_NAME,
request, ExistingPeriodicWorkPolicy.UPDATE,
) request,
)
} else {
workManager.cancelUniqueWork(WORK_NAME)
}
if (!prefs.autoBackupOnChange.first()) { if (!prefs.autoBackupOnChange.first()) {
stopWatching() stopWatching()
} else if (watchDropped || !BackupChangeJob.isPending(context)) { } else if (watchDropped || !BackupChangeJob.isPending(context)) {
@@ -238,7 +244,7 @@ class BackupWorker(
if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success() if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success()
val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure() val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure()
val outcome = try { val outcome = try {
runBackup(deps, prefs, folder.toUri(), latestOnly = changeRun) runBackup(deps, prefs, folder.toUri(), changeRun, prefs.autoBackupScheduled.first())
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
} catch (e: Exception) { } catch (e: Exception) {
@@ -261,17 +267,28 @@ class BackupWorker(
return if (outcome == RunOutcome.Failed && !changeRun) Result.retry() else Result.success() return if (outcome == RunOutcome.Failed && !changeRun) Result.retry() else Result.success()
} }
private enum class RunOutcome { Written, PartlyFailed, Failed, NothingToDo } /** [Blocked]: failed only on series no retry can back up, so it isn't retried. */
private enum class RunOutcome { Written, PartlyFailed, Failed, Blocked, NothingToDo }
/** How a stable copy's write went: under its own name, under one the provider picked, or not at all. */ /** How a stable copy's write went: under its own name, under one the provider picked, or not at all. */
private enum class LatestWrite { Landed, Renamed, Failed } private enum class LatestWrite { Landed, Renamed, Failed }
/** /**
* Writes each series and prunes it only once its new file has landed. A * Writes each series and prunes it only once its new file has landed. A
* [latestOnly] run (#516) leaves the dated files and their retention to the * change run (#516) leaves the dated files and their retention to the
* schedule and rewrites only the stable copies whose calendars changed. * schedule and rewrites only the stable copies whose calendars changed.
* With the interval off, no run writes dated files, so a series whose
* stable name a file of the user's holds counts as failed (a change run
* only when its content changed).
*/ */
private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri, latestOnly: Boolean): RunOutcome { private suspend fun runBackup(
deps: Deps,
prefs: SettingsPrefs,
folder: Uri,
changeRun: Boolean,
intervalOn: Boolean,
): RunOutcome {
val latestOnly = backupRunLatestOnly(changeRun, intervalOn)
val repository = deps.repository() val repository = deps.repository()
val exporter = deps.exporter() val exporter = deps.exporter()
if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed
@@ -303,12 +320,18 @@ class BackupWorker(
val trackHashes = prefs.autoBackupOnChange.first() val trackHashes = prefs.autoBackupOnChange.first()
if (!trackHashes && fingerprints.isNotEmpty()) prefs.updateAutoBackupFingerprints(folder.toString()) { emptyMap() } if (!trackHashes && fingerprints.isNotEmpty()) prefs.updateAutoBackupFingerprints(folder.toString()) { emptyMap() }
// A change run hashes first (null: unreadable) and leaves the folder alone when nothing moved. // A change run hashes first (null: unreadable) and leaves the folder alone when nothing moved.
val preHashes: Map<String, String?> = if (latestOnly) { val preHashes: Map<String, String?> = if (changeRun) {
targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } } targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } }
} else { } else {
emptyMap() emptyMap()
} }
if (latestOnly && targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } }) { // With the interval off, unless a stable copy went missing: no scheduled run would restore it.
fun copyListed(target: BackupTarget) = latestFileName(target.baseName) in listing.files ||
ledger[latestLedgerKey(target.key)].orEmpty().any { it in listing.files }
if (changeRun &&
targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } } &&
(intervalOn || !listing.complete || targets.all(::copyListed))
) {
return RunOutcome.NothingToDo return RunOutcome.NothingToDo
} }
val plans = planBackupFiles( val plans = planBackupFiles(
@@ -382,19 +405,36 @@ class BackupWorker(
var written = 0 var written = 0
var failed = 0 var failed = 0
var blocked = 0
var stillBlocked = 0
val landedLatest = mutableSetOf<String>() val landedLatest = mutableSetOf<String>()
for (plan in plans) { for (plan in plans) {
val target = plan.target val target = plan.target
if (latestOnly) { val hash = if (changeRun) {
val hash = preHashes[target.key] ?: run { preHashes[target.key] ?: run {
failed++ failed++
continue continue
} }
rememberBlocked(plan, hash) } else {
if (!plan.needsRefresh(hash, fingerprints, listing.files.keys, listing.complete)) { null
if (plan.latestName in listing.files) landedLatest += target.key }
if (!plan.backedUp(intervalOn)) {
// Its hash still goes on record, so a later change run can stop early.
val blockedHash = hash ?: if (trackHashes) export(target)?.let { fingerprintOf(target, it) } else null
blockedHash?.let { rememberBlocked(plan, it) }
// A change run doesn't fail again on one that didn't change, nor report the run a success.
if (changeRun && hash == fingerprints[target.key]) {
stillBlocked++
continue continue
} }
failed++
blocked++
continue
}
if (hash != null) rememberBlocked(plan, hash)
if (hash != null && !plan.needsRefresh(hash, fingerprints, listing.files.keys, listing.complete)) {
if (plan.latestName in listing.files) landedLatest += target.key
continue
} }
// Read again rather than held since the pre-pass: one series' text in memory at a time. // Read again rather than held since the pre-pass: one series' text in memory at a time.
val text = export(target) ?: run { val text = export(target) ?: run {
@@ -402,7 +442,7 @@ class BackupWorker(
continue continue
} }
val fingerprint = fingerprintOf(target, text) val fingerprint = fingerprintOf(target, text)
if (!latestOnly) rememberBlocked(plan, fingerprint) if (!changeRun) rememberBlocked(plan, fingerprint)
val bytes = text.toByteArray(Charsets.UTF_8) val bytes = text.toByteArray(Charsets.UTF_8)
// Not cancellable once a file exists: it must reach the ledger. // Not cancellable once a file exists: it must reach the ledger.
withContext(NonCancellable) { withContext(NonCancellable) {
@@ -426,8 +466,9 @@ class BackupWorker(
} }
} }
return when { return when {
failed == 0 && written == 0 -> RunOutcome.NothingToDo failed == 0 && (written == 0 || stillBlocked > 0) -> RunOutcome.NothingToDo
failed == 0 -> RunOutcome.Written failed == 0 -> RunOutcome.Written
written == 0 && failed == blocked -> RunOutcome.Blocked
written == 0 -> RunOutcome.Failed written == 0 -> RunOutcome.Failed
else -> RunOutcome.PartlyFailed else -> RunOutcome.PartlyFailed
} }
@@ -18,6 +18,7 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.autoBackupScheduled
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.widget.requestWidgetRedraw import de.jeanlucmakiola.calendula.widget.requestWidgetRedraw
@@ -128,7 +129,12 @@ class SettingsBackupEngine @Inject constructor(
} }
} }
step("reminders") { reminderScanner.scan() } step("reminders") { reminderScanner.scan() }
step("auto backup") { BackupScheduler.reconcile(context, settingsPrefs) } step("auto backup") {
BackupScheduler.reconcile(context, settingsPrefs)
// Like the settings screen, an import that switches the interval (#516) backs up right away.
val active = after[SettingsKeys.autoBackupEnabled] && after[SettingsKeys.autoBackupFolderUri] != null
if (active && before.autoBackupScheduled != after.autoBackupScheduled) BackupScheduler.runNow(context)
}
plan.launcherName?.let { name -> plan.launcherName?.let { name ->
step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) } step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) }
} }
@@ -64,6 +64,7 @@ internal object SettingsBackupSchema {
SettingsKeys.autoBackupCombinedStored, SettingsKeys.autoBackupCombinedStored,
SettingsKeys.autoBackupKeep, SettingsKeys.autoBackupKeep,
SettingsKeys.autoBackupOnChange, SettingsKeys.autoBackupOnChange,
SettingsKeys.autoBackupScheduledStored,
SettingsKeys.specialDatesEnabled, SettingsKeys.specialDatesEnabled,
SettingsKeys.specialDatesShowYear, SettingsKeys.specialDatesShowYear,
) + SettingsKeys.specialDateTypeEnabled.values + SettingsKeys.specialDatesTitleTemplate.values ) + SettingsKeys.specialDateTypeEnabled.values + SettingsKeys.specialDatesTitleTemplate.values
@@ -1270,7 +1270,7 @@ class AndroidCalendarDataSource @Inject constructor(
form: EventForm, form: EventForm,
allDayReminderTimeMinutes: Int, allDayReminderTimeMinutes: Int,
): Long { ): Long {
val row = querySeriesRow(eventId) val row = querySeriesRow(eventId, beginMillis)
// Not a series, so there is no occurrence to single out: the row *is* the // Not a series, so there is no occurrence to single out: the row *is* the
// event, and an exception with nothing to be an exception to would leave // event, and an exception with nothing to be an exception to would leave
// an orphan holding the edit (the same test deleteOccurrence makes). // an orphan holding the edit (the same test deleteOccurrence makes).
@@ -1349,6 +1349,8 @@ class AndroidCalendarDataSource @Inject constructor(
// Reminders, guests and colour come along like any new event, and so does // Reminders, guests and colour come along like any new event, and so does
// a fresh UID — the detached row is a separate event now, and sharing the // a fresh UID — the detached row is a separate event now, and sharing the
// parent's would collide with it in .ics restore dedup. // parent's would collide with it in .ics restore dedup.
// Fail before inserting: the EXDATE write below needs a usable length.
row.writeDuration()
val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes) val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes)
// Rows touched, not occurrences excluded — 1 whenever the series row still // Rows touched, not occurrences excluded — 1 whenever the series row still
// exists. It catches the row disappearing under us, not an EXDATE the // exists. It catches the row disappearing under us, not an EXDATE the
@@ -1384,7 +1386,7 @@ class AndroidCalendarDataSource @Inject constructor(
updated: EventForm, updated: EventForm,
allDayReminderTimeMinutes: Int, allDayReminderTimeMinutes: Int,
): Long { ): Long {
val row = querySeriesRow(eventId) val row = querySeriesRow(eventId, beginMillis)
// From the first occurrence on (or with no rule to split) this is // From the first occurrence on (or with no rule to split) this is
// just a series update. // just a series update.
if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) {
@@ -1392,6 +1394,8 @@ class AndroidCalendarDataSource @Inject constructor(
return eventId return eventId
} }
// Insert the new series first: if it fails, the original is untouched. // Insert the new series first: if it fails, the original is untouched.
// Fail before inserting: truncating the original needs a usable length.
row.writeDuration()
val newEventId = insertEvent(updated, allDayReminderTimeMinutes) val newEventId = insertEvent(updated, allDayReminderTimeMinutes)
carrySplitExdate(newEventId, row, beginMillis, original, updated) carrySplitExdate(newEventId, row, beginMillis, original, updated)
truncateSeries(eventId, row, beginMillis) truncateSeries(eventId, row, beginMillis)
@@ -1447,7 +1451,7 @@ class AndroidCalendarDataSource @Inject constructor(
} }
override fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) { override fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) {
val row = querySeriesRow(eventId) val row = querySeriesRow(eventId, beginMillis)
// From the first occurrence on = the whole series; also the fallback // From the first occurrence on = the whole series; also the fallback
// when there is no RRULE to truncate. // when there is no RRULE to truncate.
if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) {
@@ -1476,8 +1480,12 @@ class AndroidCalendarDataSource @Inject constructor(
updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis") updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis")
} }
/** The series anchor: every time-related column of the Events row. */ /**
private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query( * The series anchor: every time-related column of the Events row. A recurring
* row with no usable DURATION gets one derived ([seriesDuration]), from the
* expanded occurrence at [occurrenceMillis] when DTEND can't supply it.
*/
private fun querySeriesRow(eventId: Long, occurrenceMillis: Long? = null): SeriesRow = resolver.query(
eventUri(eventId), eventUri(eventId),
arrayOf( arrayOf(
CalendarContract.Events.DTSTART, CalendarContract.Events.DTSTART,
@@ -1488,11 +1496,12 @@ class AndroidCalendarDataSource @Inject constructor(
CalendarContract.Events._SYNC_ID, CalendarContract.Events._SYNC_ID,
CalendarContract.Events.EXDATE, CalendarContract.Events.EXDATE,
CalendarContract.Events.RDATE, CalendarContract.Events.RDATE,
CalendarContract.Events.DTEND,
), ),
null, null, null, null, null, null,
)?.use { c -> )?.use { c ->
if (c.moveToFirst()) { if (c.moveToFirst()) {
SeriesRow( val row = SeriesRow(
dtStartMillis = c.getLong(0), dtStartMillis = c.getLong(0),
rrule = c.getString(1), rrule = c.getString(1),
timezone = c.getString(2), timezone = c.getString(2),
@@ -1502,11 +1511,27 @@ class AndroidCalendarDataSource @Inject constructor(
exdate = c.getString(6), exdate = c.getString(6),
rdate = c.getString(7), rdate = c.getString(7),
) )
if (!row.recurs || !row.duration.isNullOrBlank()) return@use row
row.copy(
dtEndMillis = if (c.isNull(8)) null else c.getLong(8),
occurrenceSpanMillis = occurrenceMillis?.let { occurrenceSpan(eventId, it) },
)
} else { } else {
null null
} }
} ?: throw WriteFailedException("read series row of event id=$eventId") } ?: throw WriteFailedException("read series row of event id=$eventId")
/** Length of the already-expanded occurrence of [eventId] starting at [beginMillis]. */
private fun occurrenceSpan(eventId: Long, beginMillis: Long): Long? {
return resolver.query(
instancesUri(beginMillis, beginMillis + 1),
arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END),
"${CalendarContract.Instances.EVENT_ID} = ? AND ${CalendarContract.Instances.BEGIN} = ?",
arrayOf(eventId.toString(), beginMillis.toString()),
null,
)?.use { c -> if (c.moveToFirst()) c.getLong(1) - c.getLong(0) else null }
}
private data class SeriesRow( private data class SeriesRow(
val dtStartMillis: Long, val dtStartMillis: Long,
val rrule: String?, val rrule: String?,
@@ -1517,6 +1542,9 @@ class AndroidCalendarDataSource @Inject constructor(
val syncId: String? = null, val syncId: String? = null,
val exdate: String? = null, val exdate: String? = null,
val rdate: String? = null, val rdate: String? = null,
/** Only read for a series with no DURATION, to derive one ([writeDuration]). */
val dtEndMillis: Long? = null,
val occurrenceSpanMillis: Long? = null,
) { ) {
/** /**
* Whether this row expands into more than itself. RDATE counts as much as * Whether this row expands into more than itself. RDATE counts as much as
@@ -1526,14 +1554,23 @@ class AndroidCalendarDataSource @Inject constructor(
*/ */
val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank() val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
/**
* DURATION for a write that re-expands the series. Refuses rather than
* writing none, which would leave the provider nothing to expand (#502).
*/
fun writeDuration(): String = duration?.takeIf { it.isNotBlank() }
?: seriesDuration(dtStartMillis, dtEndMillis, occurrenceSpanMillis, allDay != 0)
?: throw WriteFailedException("series has no usable length")
/** /**
* The time/recurrence set a series write carries together: the provider * The time/recurrence set a series write carries together: the provider
* re-expands instances only from what the update itself holds. * re-expands instances only from what the update itself holds.
*/ */
fun timeColumns(): ContentValues = ContentValues().apply { fun timeColumns(): ContentValues = ContentValues().apply {
put(CalendarContract.Events.DTSTART, dtStartMillis) put(CalendarContract.Events.DTSTART, dtStartMillis)
putNull(CalendarContract.Events.DTEND)
put(CalendarContract.Events.RRULE, rrule) put(CalendarContract.Events.RRULE, rrule)
put(CalendarContract.Events.DURATION, duration) put(CalendarContract.Events.DURATION, writeDuration())
put(CalendarContract.Events.EVENT_TIMEZONE, timezone) put(CalendarContract.Events.EVENT_TIMEZONE, timezone)
put(CalendarContract.Events.ALL_DAY, allDay) put(CalendarContract.Events.ALL_DAY, allDay)
} }
@@ -1545,7 +1582,7 @@ class AndroidCalendarDataSource @Inject constructor(
dtStartMillis = dtStartMillis, dtStartMillis = dtStartMillis,
rrule = rrule, rrule = rrule,
rdate = rdate, rdate = rdate,
duration = duration, duration = writeDuration(),
timezone = timezone, timezone = timezone,
allDay = allDay, allDay = allDay,
) )
@@ -1732,7 +1769,7 @@ class AndroidCalendarDataSource @Inject constructor(
} }
override fun deleteOccurrence(eventId: Long, beginMillis: Long) { override fun deleteOccurrence(eventId: Long, beginMillis: Long) {
val row = querySeriesRow(eventId) val row = querySeriesRow(eventId, beginMillis)
// Not a series, so the row *is* the event: an exclusion would put a // Not a series, so the row *is* the event: an exclusion would put a
// recurrence set on a one-off, an exception would leave an orphan. // recurrence set on a one-off, an exception would leave an orphan.
if (!row.recurs) { if (!row.recurs) {
@@ -1762,7 +1799,7 @@ class AndroidCalendarDataSource @Inject constructor(
val values = buildOccurrenceCancelValues( val values = buildOccurrenceCancelValues(
originalInstanceMillis = beginMillis, originalInstanceMillis = beginMillis,
dtStartMillis = beginMillis, dtStartMillis = beginMillis,
duration = row.duration, duration = row.writeDuration(),
timezone = row.timezone, timezone = row.timezone,
allDay = row.allDay, allDay = row.allDay,
) )
@@ -369,7 +369,8 @@ internal fun buildMovedMasterValues(
/** The recurring copy's DURATION: its own if present, else derived from DTEND. */ /** The recurring copy's DURATION: its own if present, else derived from DTEND. */
private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() } private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() }
?: rfc2445Duration((dtEndMillis ?: dtStartMillis) - dtStartMillis, isAllDay) ?: seriesDuration(dtStartMillis, dtEndMillis ?: dtStartMillis, occurrenceSpanMillis = null, isAllDay = isAllDay)
?: throw WriteFailedException("move series with no usable length")
/** /**
* Raw provider snapshot of one exception row of a recurring series (a modified * Raw provider snapshot of one exception row of a recurring series (a modified
@@ -454,6 +455,29 @@ internal fun buildOccurrenceExdateValues(
existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay, existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay,
) )
/**
* DURATION for a series row that has none. Rows from other tools can carry a
* DTEND (sometimes 0) instead; rewriting them without a DURATION leaves the
* provider nothing to expand, and every occurrence vanishes (#502). The span of
* an occurrence the provider actually expanded wins over DTEND; null when
* neither gives a length (a DTEND before DTSTART), so the caller fails
* instead of guessing.
*/
internal fun seriesDuration(
dtStartMillis: Long,
dtEndMillis: Long?,
occurrenceSpanMillis: Long?,
isAllDay: Boolean,
): String? {
val span = occurrenceSpanMillis?.takeIf { it >= 0 }
?: dtEndMillis?.minus(dtStartMillis)?.takeIf { it >= 0 }
?: return null
if (!isAllDay) return rfc2445Duration(span, isAllDay = false)
// Whole days, rounded: a span read across a DST change or zone offset is a few hours off.
val days = ((span + MILLIS_PER_DAY / 2) / MILLIS_PER_DAY).coerceAtLeast(1)
return rfc2445Duration(days * MILLIS_PER_DAY, isAllDay = true)
}
/** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */ /** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */
internal fun buildOccurrencesExdateValues( internal fun buildOccurrencesExdateValues(
existingExdate: String?, existingExdate: String?,
@@ -469,6 +493,7 @@ internal fun buildOccurrencesExdateValues(
mergedExdate(exdate, millis, allDay != 0, timezone) mergedExdate(exdate, millis, allDay != 0, timezone)
}, },
CalendarContract.Events.DTSTART to dtStartMillis, CalendarContract.Events.DTSTART to dtStartMillis,
CalendarContract.Events.DTEND to null,
CalendarContract.Events.RRULE to rrule, CalendarContract.Events.RRULE to rrule,
CalendarContract.Events.RDATE to rdate, CalendarContract.Events.RDATE to rdate,
CalendarContract.Events.DURATION to duration, CalendarContract.Events.DURATION to duration,
@@ -9,6 +9,7 @@ import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.backup.BackupSelection import de.jeanlucmakiola.calendula.domain.backup.BackupSelection
import de.jeanlucmakiola.calendula.domain.backup.backupIntervalOn
import de.jeanlucmakiola.calendula.domain.backup.COMBINED_SERIES import de.jeanlucmakiola.calendula.domain.backup.COMBINED_SERIES
import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP
import de.jeanlucmakiola.calendula.domain.backup.LEGACY_BACKUP_FILE import de.jeanlucmakiola.calendula.domain.backup.LEGACY_BACKUP_FILE
@@ -229,6 +230,11 @@ class SettingsPrefs @Inject constructor(
val autoBackupKeep: Flow<Int> = prefs.flow(SettingsKeys.autoBackupKeep) val autoBackupKeep: Flow<Int> = prefs.flow(SettingsKeys.autoBackupKeep)
val autoBackupLedger: Flow<BackupLedger> = prefs.flow(SettingsKeys.autoBackupLedger) val autoBackupLedger: Flow<BackupLedger> = prefs.flow(SettingsKeys.autoBackupLedger)
val autoBackupOnChange: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupOnChange) val autoBackupOnChange: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupOnChange)
val autoBackupScheduled: Flow<Boolean> = prefs.snapshot { it.autoBackupScheduled }
/** Read together, so the screen never shows one updated without the other. */
val autoBackupOnChangeAndScheduled: Flow<Pair<Boolean, Boolean>> =
prefs.snapshot { it[SettingsKeys.autoBackupOnChange] to it.autoBackupScheduled }
val autoBackupFingerprints: Flow<BackupFingerprints> = prefs.flow(SettingsKeys.autoBackupFingerprints) val autoBackupFingerprints: Flow<BackupFingerprints> = prefs.flow(SettingsKeys.autoBackupFingerprints)
val specialDatesEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.specialDatesEnabled) val specialDatesEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.specialDatesEnabled)
val specialDatesTypes: Flow<Set<SpecialDateType>> = prefs.snapshot { it.specialDatesTypes } val specialDatesTypes: Flow<Set<SpecialDateType>> = prefs.snapshot { it.specialDatesTypes }
@@ -523,7 +529,28 @@ class SettingsPrefs @Inject constructor(
suspend fun setAutoBackupKeep(keep: Int) = prefs.set(SettingsKeys.autoBackupKeep, keep) suspend fun setAutoBackupKeep(keep: Int) = prefs.set(SettingsKeys.autoBackupKeep, keep)
suspend fun setAutoBackupOnChange(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupOnChange, enabled) /** Returns whether this switched the interval on or off. */
suspend fun setAutoBackupOnChange(enabled: Boolean): Boolean = editAutoBackupScheduled {
applyAutoBackupOnChange(it, enabled)
}
/**
* Off only sticks while backing up after changes is on; see
* [applyAutoBackupOnChange]. Returns whether this switched the interval.
*/
suspend fun setAutoBackupScheduled(enabled: Boolean): Boolean = editAutoBackupScheduled {
if (enabled || it[SettingsKeys.autoBackupOnChange]) it[SettingsKeys.autoBackupScheduledStored] = enabled
}
private suspend fun editAutoBackupScheduled(transform: (MutablePreferences) -> Unit): Boolean {
var switched = false
prefs.edit {
val before = it.autoBackupScheduled
transform(it)
switched = it.autoBackupScheduled != before
}
return switched
}
/** /**
* Atomic, so a run's ledger writes never undo one made meanwhile (pinning * Atomic, so a run's ledger writes never undo one made meanwhile (pinning
@@ -1048,6 +1075,9 @@ object SettingsKeys {
/** Whether a change to a backed-up calendar also refreshes the stable copies (#516). Opt-in. */ /** Whether a change to a backed-up calendar also refreshes the stable copies (#516). Opt-in. */
val autoBackupOnChange: Pref<Boolean> = booleanPref("auto_backup_on_change", false) val autoBackupOnChange: Pref<Boolean> = booleanPref("auto_backup_on_change", false)
/** Whether the dated backups run on the interval; read as [Preferences.autoBackupScheduled]. */
val autoBackupScheduledStored: Pref<Boolean> = booleanPref("auto_backup_scheduled", true)
/** Content hash of each series' stable copy, so a change run skips untouched ones (#516). */ /** Content hash of each series' stable copy, so a change run skips untouched ones (#516). */
val autoBackupFingerprints: Pref<BackupFingerprints> = val autoBackupFingerprints: Pref<BackupFingerprints> =
nullableStringPref("auto_backup_fingerprints").map(::parseBackupFingerprints, ::persistBackupFingerprints) nullableStringPref("auto_backup_fingerprints").map(::parseBackupFingerprints, ::persistBackupFingerprints)
@@ -1107,6 +1137,20 @@ val Preferences.autoBackupSelection: BackupSelection
excluded = this[SettingsKeys.autoBackupExcluded], excluded = this[SettingsKeys.autoBackupExcluded],
) )
/** Whether the dated backups run on the interval; see [backupIntervalOn]. */
val Preferences.autoBackupScheduled: Boolean
get() = backupIntervalOn(this[SettingsKeys.autoBackupScheduledStored], this[SettingsKeys.autoBackupOnChange])
/**
* Turning it off brings the interval back for good, and turning it on starts
* with the interval on, so an interval-off stored without it (a settings
* import) never takes effect.
*/
internal fun applyAutoBackupOnChange(prefs: MutablePreferences, enabled: Boolean) {
if (!enabled || !prefs[SettingsKeys.autoBackupOnChange]) prefs[SettingsKeys.autoBackupScheduledStored] = true
prefs[SettingsKeys.autoBackupOnChange] = enabled
}
/** /**
* Unset means an install from before #411: one that already had a backup * Unset means an install from before #411: one that already had a backup
* folder keeps the single file it was writing, anything else gets per-calendar * folder keeps the single file it was writing, anything else gets per-calendar
@@ -129,10 +129,12 @@ private val STAMP_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern(STAMP_
* something follows shouldn't move because another calendar took the same * something follows shouldn't move because another calendar took the same
* name. So the series holding the stable copy of the name in [ledger] keeps * name. So the series holding the stable copy of the name in [ledger] keeps
* it, then one holding dated files under it; series that already write under * it, then one holding dated files under it; series that already write under
* their id suffix keep that; with no claim at all the lowest id keeps the * their id suffix keep that, clash or not; with no claim at all the lowest id keeps the
* name. The others take their id as a suffix until every name in the run is * name. The others take their id as a suffix until every name in the run is
* distinct. Ledger names gone from the folder ([existing], when known) claim * distinct. A stable copy a series outside the run still holds (a calendar
* nothing. A calendar named like the combined file is always suffixed. * taken out of the backup) is kept, so a calendar now named like it is
* suffixed too. Ledger names gone from the folder ([existing], when known)
* claim nothing. A calendar named like the combined file is always suffixed.
*/ */
fun backupTargets( fun backupTargets(
calendars: List<CalendarSource>, calendars: List<CalendarSource>,
@@ -148,16 +150,26 @@ fun backupTargets(
} }
val present = if (existing == null) ledger else ledger.mapValues { (_, names) -> names.filter { it in existing } } val present = if (existing == null) ledger else ledger.mapValues { (_, names) -> names.filter { it in existing } }
val bases = calendars.associateTo(LinkedHashMap()) { val bases = calendars.associateTo(LinkedHashMap()) {
it.id to safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar") val base = safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar")
val suffixed = "$base-${it.id}"
it.id to if (present.holdsLatest(it.id.toString(), suffixed)) suffixed else base
} }
val runKeys = calendars.map { latestLedgerKey(it.id.toString()) }.toSet()
val heldOutside = present.filterKeys { it.startsWith(LATEST_PREFIX) && it !in runKeys }
.values.flatten().map { it.lowercase() }.toSet()
while (true) { while (true) {
val clashing = bases.entries.groupBy({ it.value.lowercase() }, { it.key }) val clashing = bases.entries.groupBy({ it.value.lowercase() }, { it.key })
.filter { (lower, ids) -> ids.size > 1 || lower == COMBINED_BACKUP_BASE.lowercase() } .filter { (lower, ids) -> ids.size > 1 || lower == COMBINED_BACKUP_BASE.lowercase() }
if (clashing.isEmpty()) break if (clashing.isNotEmpty()) {
clashing.forEach { (lower, ids) -> clashing.forEach { (lower, ids) ->
val keeper = if (lower == COMBINED_BACKUP_BASE.lowercase()) null else present.keeperOf(ids, bases) val keeper = if (lower == COMBINED_BACKUP_BASE.lowercase()) null else present.keeperOf(ids, bases)
ids.filter { it != keeper }.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" } ids.filter { it != keeper }.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" }
}
continue
} }
val taken = bases.filterValues { latestFileName(it).lowercase() in heldOutside }.keys
if (taken.isEmpty()) break
taken.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" }
} }
return calendars.map { calendar -> return calendars.map { calendar ->
BackupTarget( BackupTarget(
@@ -311,6 +323,18 @@ fun parseBackupLedger(stored: String?): BackupLedger =
parts.first().takeIf { it.isNotEmpty() && names.isNotEmpty() }?.let { it to names } parts.first().takeIf { it.isNotEmpty() && names.isNotEmpty() }?.let { it to names }
}.toMap() }.toMap()
/** The interval can only be off while backing up after changes is on (#516), or nothing would ever run. */
fun backupIntervalOn(stored: Boolean, onChange: Boolean): Boolean = stored || !onChange
/** Without the interval there are no dated files, so every run only refreshes the stable copies. */
fun backupRunLatestOnly(changeRun: Boolean, intervalOn: Boolean): Boolean = changeRun || !intervalOn
/**
* Whether a run can back this series up at all: without dated files, only
* through its stable copy, which a file of the user's can block.
*/
fun BackupFilePlan.backedUp(intervalOn: Boolean): Boolean = intervalOn || latestName != null
/** Closest offered retention count to [stored], so a stray value still shows a row. */ /** Closest offered retention count to [stored], so a stray value still shows a row. */
fun normalizeBackupKeep(stored: Int): Int = fun normalizeBackupKeep(stored: Int): Int =
BACKUP_KEEP_OPTIONS.minBy { kotlin.math.abs(it - stored) } BACKUP_KEEP_OPTIONS.minBy { kotlin.math.abs(it - stored) }
@@ -369,7 +393,7 @@ fun parseBackupFingerprints(stored: String?): BackupFingerprints =
* only when its content moved on from what the copy holds (a rename changes * only when its content moved on from what the copy holds (a rename changes
* the name written into it), or the copy is missing. Never when the name belongs to a file of the user's, * the name written into it), or the copy is missing. Never when the name belongs to a file of the user's,
* nor when a [complete]-less listing doesn't show the copy: writing then would * nor when a [complete]-less listing doesn't show the copy: writing then would
* add a duplicate beside it, so that is left to the scheduled run. * add a duplicate beside it, so that is left to the next run that isn't a change run.
*/ */
fun BackupFilePlan.needsRefresh( fun BackupFilePlan.needsRefresh(
fingerprint: String, fingerprint: String,
@@ -125,11 +125,12 @@ import kotlin.time.Instant
* *
* The stack's bottom is the user's [CalendarHostViewModel.defaultView] home view. * The stack's bottom is the user's [CalendarHostViewModel.defaultView] home view.
* A lateral switch (pill / drawer) builds a visit history so back retraces it * A lateral switch (pill / drawer) builds a visit history so back retraces it
* (see [selectView]); a widget launch resets the stack to its own view; a date * (see [selectView]); a widget event or header launch resets the stack to the
* tap drills the day view on top. Pressing back pops one level, and the * widget's view; a date tap or date launch drills the day view on top. Pressing
* base-level [BackHandler] hands off to the system to exit once only the home * back pops one level, and the base-level [BackHandler] hands off to the system
* view remains. So back from a widget-opened screen returns to that widget's * to exit once only the home view remains. Back from a widget-opened day or
* view, then home; and back through pill switches walks the views in reverse. * event leaves the app at once (#530), until the user navigates on from it; and
* back through pill switches walks the views in reverse.
* *
* [requests] carries what notifications, widgets and other apps asked to * [requests] carries what notifications, widgets and other apps asked to
* open. A tapped reminder's occurrence opens the detail overlay exactly like an * open. A tapped reminder's occurrence opens the detail overlay exactly like an
@@ -182,7 +183,9 @@ fun CalendarHost(
val switchTo: ((List<CalendarView>) -> List<CalendarView>) -> Unit = { move -> val switchTo: ((List<CalendarView>) -> List<CalendarView>) -> Unit = { move ->
navigationVersion++ navigationVersion++
returnedFromDay = false returnedFromDay = false
viewStack = move(viewStack) val moved = move(viewStack)
requests.leaveTarget = requests.leaveTarget.afterMove(viewStack, moved)
viewStack = moved
} }
val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } } val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } }
val onOpenDay: (LocalDate) -> Unit = { date -> val onOpenDay: (LocalDate) -> Unit = { date ->
@@ -201,12 +204,28 @@ fun CalendarHost(
// Like every overlay below, it draws its last key through the slide-out // Like every overlay below, it draws its last key through the slide-out
// ([rememberHeld]) rather than a placeholder. // ([rememberHeld]) rather than a placeholder.
var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) } var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
LaunchedEffect(detailKey) { requests.leaveTarget = requests.leaveTarget.afterDetail(detailKey) }
val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() } val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() }
// The drawer's "Hide in this view" picker (#517). It is its own window over // The drawer's "Hide in “<view>” view" picker (#517). It is its own window over
// everything here, so each external request below closes it first. // everything here, so each external request below closes it first.
var showViewCalendars by rememberSaveable { mutableStateOf(false) } var showViewCalendars by rememberSaveable { mutableStateOf(false) }
// Back left a widget's day or event (#530): the app comes back on the home
// view. Ahead of the other requests, so one arriving with the return opens over it.
val resetToHome = requests.resetToHome
LaunchedEffect(resetToHome) {
if (resetToHome) {
navigationVersion++
returnedFromDay = false
detailKey = null
focus.navigateTo(currentDate())
viewStack = listOf(defaultView)
requests.leaveTarget = null
requests.resetToHome = false
}
}
// A tapped reminder notification asks for a specific occurrence. // A tapped reminder notification asks for a specific occurrence.
val requestedDetailKey = requests.detailKey val requestedDetailKey = requests.detailKey
LaunchedEffect(requestedDetailKey) { LaunchedEffect(requestedDetailKey) {
@@ -403,8 +422,7 @@ fun CalendarHost(
// A home-screen widget launch asks to open a date (→ day view), open an // A home-screen widget launch asks to open a date (→ day view), open an
// event's detail, or start a create. Handled once and cleared, mirroring // event's detail, or start a create. Handled once and cleared, mirroring
// the detail request. Date/event opens root the stack in the widget's own // the detail request. A widget's day or event leaves the app on back (#530).
// view so backing out returns there (then home), not to the default.
val widgetNavRequest = requests.nav val widgetNavRequest = requests.nav
LaunchedEffect(widgetNavRequest) { LaunchedEffect(widgetNavRequest) {
if (widgetNavRequest != null) { if (widgetNavRequest != null) {
@@ -413,13 +431,12 @@ fun CalendarHost(
} }
when (val req = widgetNavRequest) { when (val req = widgetNavRequest) {
is WidgetNavRequest.OpenDate -> { is WidgetNavRequest.OpenDate -> {
// Drill the day view in over the widget's view: drop any overlay // Drop any overlay that would cover the day, so the open doesn't
// that would cover it, so the open doesn't land under Settings/form. // land under Settings/form.
dismissCoveringOverlays() dismissCoveringOverlays()
focus.navigateTo(LocalDate.parse(req.dateIso)) focus.navigateTo(LocalDate.parse(req.dateIso))
// No widget source (an external date tap) roots over the default viewStack = listOf(defaultView).drillToDay()
// home view, so backing out of the day returns home then exits. requests.leaveTarget = req.leaveTarget
viewStack = viewBaseStack(defaultView, req.source ?: defaultView).drillToDay()
requests.nav = null requests.nav = null
} }
is WidgetNavRequest.OpenEvent -> { is WidgetNavRequest.OpenEvent -> {
@@ -428,6 +445,7 @@ fun CalendarHost(
dismissCoveringOverlays() dismissCoveringOverlays()
viewStack = viewBaseStack(defaultView, req.source) viewStack = viewBaseStack(defaultView, req.source)
detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis) detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
requests.leaveTarget = req.leaveTarget
requests.nav = null requests.nav = null
} }
is WidgetNavRequest.OpenView -> { is WidgetNavRequest.OpenView -> {
@@ -438,6 +456,7 @@ fun CalendarHost(
dismissCoveringOverlays() dismissCoveringOverlays()
focus.navigateTo(currentDate()) focus.navigateTo(currentDate())
viewStack = viewBaseStack(defaultView, req.view ?: defaultView) viewStack = viewBaseStack(defaultView, req.view ?: defaultView)
requests.leaveTarget = null
requests.nav = null requests.nav = null
} }
is WidgetNavRequest.Create -> { is WidgetNavRequest.Create -> {
@@ -534,7 +553,12 @@ fun CalendarHost(
val viewTransition = remember { SeekableTransitionState(view) } val viewTransition = remember { SeekableTransitionState(view) }
LaunchedEffect(view) { viewTransition.animateTo(view) } LaunchedEffect(view) { viewTransition.animateTo(view) }
val reduceMotion = rememberReduceMotion() val reduceMotion = rememberReduceMotion()
val viewBackEnabled = !anyOverlayVisible && viewStack.size > 1 val leaveOnBack = requests.leaveTarget.leaves(detailKey, anyOverlayVisible)
val viewBackEnabled = !anyOverlayVisible && viewStack.size > 1 && !leaveOnBack
// The app goes to the background and comes back on the home view. Overlays
// opened over a widget's detail register later, so their own back still wins.
// A refused move (screen pinning) falls back to the in-app back from then on.
BackHandler(enabled = leaveOnBack) { if (!requests.onLeave()) requests.leaveTarget = null }
if (reduceMotion) { if (reduceMotion) {
BackHandler(enabled = viewBackEnabled) { BackHandler(enabled = viewBackEnabled) {
navigationVersion++ navigationVersion++
@@ -784,6 +808,8 @@ fun CalendarHost(
detailKey = null detailKey = null
}, },
visible = detailKey != null, visible = detailKey != null,
// A widget's own detail leaves the app on back, through the handler above.
backEnabled = !leaveOnBack,
) )
} }
} }
@@ -15,10 +15,15 @@ import de.jeanlucmakiola.calendula.ui.edit.ImportSource
* it, so a later recomposition can't act on it twice. * it, so a later recomposition can't act on it twice.
* *
* [onExternalFormClosed] runs when a form opened for [insert] closes, so the * [onExternalFormClosed] runs when a form opened for [insert] closes, so the
* activity can hand control back to the app that asked. * activity can hand control back to the app that asked. [onLeave] sends the app
* to the background when back leaves a widget's day or event ([leaveTarget]),
* false when the system refused.
*/ */
@Stable @Stable
class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) { class ExternalRequests(
val onExternalFormClosed: () -> Unit = {},
val onLeave: () -> Boolean = { false },
) {
/** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */ /** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */
var detailKey by mutableStateOf<LongArray?>(null) var detailKey by mutableStateOf<LongArray?>(null)
@@ -37,6 +42,12 @@ class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) {
/** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */ /** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */
var editKey by mutableStateOf<LongArray?>(null) var editKey by mutableStateOf<LongArray?>(null)
/** What back leaves the app from (#530). Cleared once the user leaves the app. */
var leaveTarget by mutableStateOf<LeaveTarget?>(null)
/** Set when the app comes back after [onLeave]: show the home view. */
var resetToHome by mutableStateOf(false)
/** Whether these came from re-reading the launch intent on a recreation. */ /** Whether these came from re-reading the launch intent on a recreation. */
var replayed = false var replayed = false
} }
@@ -1,27 +1,25 @@
package de.jeanlucmakiola.calendula.ui package de.jeanlucmakiola.calendula.ui
import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.CalendarView
import java.io.Serializable
/** /**
* A navigation a home-screen widget asked the app to perform when launched. * A navigation a home-screen widget asked the app to perform when launched.
* Parsed from the launch intent in MainActivity and consumed once by * Parsed from the launch intent in MainActivity and consumed once by
* [CalendarHost]. Every request carries the [source] view of the widget it came * [CalendarHost]. An event open carries the [OpenEvent.source] view of the
* from (the agenda widget → [CalendarView.Agenda], the month widget → * widget it came from (the agenda widget → [CalendarView.Agenda]) as the view
* [CalendarView.Month]) so the in-app back stack roots itself in that view: * under its detail. (Reminder notifications are not widgets — they keep the
* backing out of the opened date/event returns to the widget's own view, not the * separate detail-key channel and leave the base view untouched.)
* default home. (Reminder notifications are not widgets — they keep the separate
* detail-key channel and leave the base view untouched.)
*/ */
sealed interface WidgetNavRequest { sealed interface WidgetNavRequest : Serializable {
/** /**
* Open the day view anchored on [dateIso] (an ISO `yyyy-MM-dd` date), over * Open the day view anchored on [dateIso] (an ISO `yyyy-MM-dd` date), over the
* [source]. A null [source] means the request came from outside the app (a * default home view. [fromWidget] makes back leave the app at once (#530); a
* launcher/clock date tap, issue #9) rather than a widget, so it roots over * launcher/clock date tap (issue #9) or the daily summary backs out to home.
* the default home view instead of a widget's view.
*/ */
data class OpenDate(val dateIso: String, val source: CalendarView?) : WidgetNavRequest data class OpenDate(val dateIso: String, val fromWidget: Boolean) : WidgetNavRequest
/** Open one occurrence's detail (an agenda-widget event tap), over [source]. */ /** Open one occurrence's detail (a widget event tap), over [source]; back leaves the app (#530). */
data class OpenEvent( data class OpenEvent(
val eventId: Long, val eventId: Long,
val beginMillis: Long, val beginMillis: Long,
@@ -41,3 +39,38 @@ sealed interface WidgetNavRequest {
*/ */
data class OpenView(val view: CalendarView?) : WidgetNavRequest data class OpenView(val view: CalendarView?) : WidgetNavRequest
} }
/** What back leaves the app from (#530): a widget's day, or a widget's event detail. */
sealed interface LeaveTarget : Serializable {
/** The view a widget opened, while no overlay covers it. */
data object View : LeaveTarget
/** The detail of the occurrence a widget opened. */
data class Detail(val eventId: Long, val beginMillis: Long, val endMillis: Long) : LeaveTarget {
fun matches(key: LongArray?): Boolean =
key != null && key.size == 3 && key[0] == eventId && key[1] == beginMillis && key[2] == endMillis
}
}
/** What back leaves the app from after this request: a widget's day or event, else nothing. */
val WidgetNavRequest.leaveTarget: LeaveTarget?
get() = when (this) {
is WidgetNavRequest.OpenDate -> LeaveTarget.View.takeIf { fromWidget }
is WidgetNavRequest.OpenEvent -> LeaveTarget.Detail(eventId, beginMillis, endMillis)
else -> null
}
/** The target after a move from [before] to [after]: kept only while the user stays on the same views. */
fun LeaveTarget?.afterMove(before: List<CalendarView>, after: List<CalendarView>): LeaveTarget? =
takeIf { before == after }
/** The target once the detail shows [shown]: a widget's detail is dropped once it closes or changes. */
fun LeaveTarget?.afterDetail(shown: LongArray?): LeaveTarget? =
if (this is LeaveTarget.Detail && !matches(shown)) null else this
/** Whether back leaves the app now, given the open detail and whether any overlay is up. */
fun LeaveTarget?.leaves(detail: LongArray?, overlayVisible: Boolean): Boolean = when (this) {
LeaveTarget.View -> !overlayVisible
is LeaveTarget.Detail -> matches(detail)
null -> false
}
@@ -371,13 +371,29 @@ private fun BackupContent(
) )
GroupedRow( GroupedRow(
title = stringResource(R.string.calendars_auto_backup_interval), title = stringResource(R.string.calendars_auto_backup_interval),
summary = backupIntervalLabel(autoBackup.intervalMinutes), summary = if (autoBackup.scheduled) {
backupIntervalLabel(autoBackup.intervalMinutes)
} else {
stringResource(R.string.calendars_auto_backup_interval_off)
},
position = Position.Middle, position = Position.Middle,
onClick = onEditInterval, // Off is only offered alongside backing up after changes, or nothing would run.
trailing = if (autoBackup.onChange) {
{ Switch(checked = autoBackup.scheduled, onCheckedChange = viewModel::setAutoBackupScheduled) }
} else {
null
},
onClick = if (autoBackup.scheduled) onEditInterval else ({ viewModel.setAutoBackupScheduled(true) }),
) )
GroupedSwitchRow( GroupedSwitchRow(
title = stringResource(R.string.calendars_auto_backup_on_change), title = stringResource(R.string.calendars_auto_backup_on_change),
summary = stringResource(R.string.calendars_auto_backup_on_change_summary), summary = stringResource(
if (autoBackup.scheduled) {
R.string.calendars_auto_backup_on_change_summary
} else {
R.string.calendars_auto_backup_on_change_only_summary
},
),
checked = autoBackup.onChange, checked = autoBackup.onChange,
onCheckedChange = viewModel::setAutoBackupOnChange, onCheckedChange = viewModel::setAutoBackupOnChange,
position = Position.Middle, position = Position.Middle,
@@ -404,14 +420,17 @@ private fun BackupContent(
), ),
checked = autoBackup.combined, checked = autoBackup.combined,
onCheckedChange = viewModel::setAutoBackupCombined, onCheckedChange = viewModel::setAutoBackupCombined,
position = Position.Middle, position = if (autoBackup.scheduled) Position.Middle else Position.Bottom,
)
GroupedRow(
title = stringResource(R.string.calendars_auto_backup_keep),
summary = backupKeepLabel(autoBackup.keep),
position = Position.Bottom,
onClick = onEditKeep,
) )
// Retention only applies to the dated files the interval writes.
if (autoBackup.scheduled) {
GroupedRow(
title = stringResource(R.string.calendars_auto_backup_keep),
summary = backupKeepLabel(autoBackup.keep),
position = Position.Bottom,
onClick = onEditKeep,
)
}
GroupedHint( GroupedHint(
if (selectedCount == 0) { if (selectedCount == 0) {
stringResource(R.string.calendars_auto_backup_nothing_selected) stringResource(R.string.calendars_auto_backup_nothing_selected)
@@ -109,9 +109,9 @@ class CalendarsViewModel @Inject constructor(
settingsPrefs.autoBackupSelection, settingsPrefs.autoBackupSelection,
settingsPrefs.autoBackupCombined, settingsPrefs.autoBackupCombined,
settingsPrefs.autoBackupKeep, settingsPrefs.autoBackupKeep,
settingsPrefs.autoBackupOnChange, settingsPrefs.autoBackupOnChangeAndScheduled,
) { base, selection, combined, keep, onChange -> ) { base, selection, combined, keep, (onChange, scheduled) ->
base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange) base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange, scheduled = scheduled)
} }
.flowOn(io) .flowOn(io)
.stateWhileSubscribed( .stateWhileSubscribed(
@@ -296,8 +296,21 @@ class CalendarsViewModel @Inject constructor(
fun setAutoBackupOnChange(enabled: Boolean) { fun setAutoBackupOnChange(enabled: Boolean) {
viewModelScope.launch { viewModelScope.launch {
settingsPrefs.setAutoBackupOnChange(enabled) val switched = settingsPrefs.setAutoBackupOnChange(enabled)
reschedule() reschedule()
if (switched) runBackupIfActive()
}
}
/**
* Switching the interval backs up right away: back on, rather than an
* interval later; off, so a series only its dated files covered shows up.
*/
fun setAutoBackupScheduled(enabled: Boolean) {
viewModelScope.launch {
val switched = settingsPrefs.setAutoBackupScheduled(enabled)
reschedule()
if (switched) runBackupIfActive()
} }
} }
@@ -356,6 +369,7 @@ data class AutoBackupUiState(
val combined: Boolean = false, val combined: Boolean = false,
val keep: Int = DEFAULT_BACKUP_KEEP, val keep: Int = DEFAULT_BACKUP_KEEP,
val onChange: Boolean = false, val onChange: Boolean = false,
val scheduled: Boolean = true,
) )
/** Outcome of a whole-calendar backup, surfaced once to the screen. */ /** Outcome of a whole-calendar backup, surfaced once to the screen. */
@@ -112,11 +112,11 @@ data class QuickSwitchConfig(
* top; switching to one already in the stack pops back to it (collapsing the * top; switching to one already in the stack pops back to it (collapsing the
* loop, so the depth stays bounded by the number of distinct views). Selecting * loop, so the depth stays bounded by the number of distinct views). Selecting
* the home view collapses to just `[default]`. * the home view collapses to just `[default]`.
* - [viewBaseStack] — the stack a widget launch resets to: just `[default]` when * - [viewBaseStack] — the stack a widget event or header launch resets to: just `[default]` when
* the widget's view is the home view, else `[default, source]`. A widget entry * the widget's view is the home view, else `[default, source]`. A widget entry
* starts a fresh context rather than extending in-app history. * starts a fresh context rather than extending in-app history.
* - [drillToDay] — pushes the day view on top (a date tap from the month grid or * - [drillToDay] — pushes the day view on top (a date tap from the month grid, a
* a widget), unless the day view is already current. * widget or a launcher), unless the day view is already current.
*/ */
fun List<CalendarView>.selectView(target: CalendarView): List<CalendarView> { fun List<CalendarView>.selectView(target: CalendarView): List<CalendarView> {
val existing = indexOf(target) val existing = indexOf(target)
@@ -142,6 +142,7 @@ fun EventDetailScreen(
onEdit: () -> Unit, onEdit: () -> Unit,
onDuplicate: (EventForm) -> Unit, onDuplicate: (EventForm) -> Unit,
visible: Boolean = true, visible: Boolean = true,
backEnabled: Boolean = true,
viewModel: EventDetailViewModel = hiltViewModel(), viewModel: EventDetailViewModel = hiltViewModel(),
) { ) {
LaunchedEffect(eventId, beginMillis, endMillis) { LaunchedEffect(eventId, beginMillis, endMillis) {
@@ -198,7 +199,7 @@ fun EventDetailScreen(
} }
Scaffold( Scaffold(
modifier = Modifier.predictiveBack(onBack = onBack, visible = visible), modifier = Modifier.predictiveBack(onBack = onBack, enabled = backEnabled, visible = visible),
snackbarHost = { SnackbarHost(snackbarHostState) }, snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = { topBar = {
TopAppBar( TopAppBar(
@@ -38,6 +38,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.label
import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
@@ -70,6 +71,7 @@ fun CalendarFilterList(
hidden = s.hidden, hidden = s.hidden,
hiddenInView = hiddenInView, hiddenInView = hiddenInView,
hiddenOnlyHere = hiddenInView.size, hiddenOnlyHere = hiddenInView.size,
currentView = currentView,
onHideInView = onHideInView, onHideInView = onHideInView,
onToggleCalendar = viewModel::toggleCalendar, onToggleCalendar = viewModel::toggleCalendar,
onToggleGroup = viewModel::toggleGroup, onToggleGroup = viewModel::toggleGroup,
@@ -90,11 +92,13 @@ private fun FilterList(
hidden: Set<Long>, hidden: Set<Long>,
hiddenInView: Set<Long>, hiddenInView: Set<Long>,
hiddenOnlyHere: Int, hiddenOnlyHere: Int,
currentView: CalendarView,
onHideInView: () -> Unit, onHideInView: () -> Unit,
onToggleCalendar: (Long) -> Unit, onToggleCalendar: (Long) -> Unit,
onToggleGroup: (List<Long>) -> Unit, onToggleGroup: (List<Long>) -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val viewName = currentView.label()
Column(modifier = modifier.fillMaxWidth()) { Column(modifier = modifier.fillMaxWidth()) {
groups.forEach { group -> groups.forEach { group ->
val ids = group.calendars.map { it.id } val ids = group.calendars.map { it.id }
@@ -107,7 +111,7 @@ private fun FilterList(
val visible = cal.id !in hidden val visible = cal.id !in hidden
GroupedRow( GroupedRow(
title = cal.displayName.orUnnamed(), title = cal.displayName.orUnnamed(),
summary = if (cal.id in hiddenInView) stringResource(R.string.filter_hidden_in_view) else null, summary = if (cal.id in hiddenInView) stringResource(R.string.filter_hidden_in_named_view, viewName) else null,
position = positionOf(index, group.calendars.size), position = positionOf(index, group.calendars.size),
minHeight = 56.dp, minHeight = 56.dp,
leading = { CalendarColorChip(cal.color) }, leading = { CalendarColorChip(cal.color) },
@@ -124,11 +128,11 @@ private fun FilterList(
// The per-view hide (#517): the drawer filter above hides everywhere, this only here. // The per-view hide (#517): the drawer filter above hides everywhere, this only here.
Spacer(Modifier.height(8.dp)) Spacer(Modifier.height(8.dp))
GroupedRow( GroupedRow(
title = stringResource(R.string.view_calendars_title), title = stringResource(R.string.view_hide_in_title, viewName),
summary = if (hiddenOnlyHere > 0) { summary = if (hiddenOnlyHere > 0) {
pluralStringResource(R.plurals.drawer_hidden_in_view_count, hiddenOnlyHere, hiddenOnlyHere) pluralStringResource(R.plurals.drawer_hidden_in_named_view_count, hiddenOnlyHere, hiddenOnlyHere, viewName)
} else { } else {
stringResource(R.string.drawer_hidden_in_view_none) stringResource(R.string.drawer_hidden_in_named_view_none, viewName)
}, },
position = Position.Alone, position = Position.Alone,
minHeight = 56.dp, minHeight = 56.dp,
@@ -12,6 +12,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
import de.jeanlucmakiola.calendula.ui.common.label
import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedHint
@@ -30,8 +31,9 @@ fun ViewCalendarsPicker(
onSetHidden: (calendarId: Long, hidden: Boolean) -> Unit, onSetHidden: (calendarId: Long, hidden: Boolean) -> Unit,
onDismiss: () -> Unit, onDismiss: () -> Unit,
) { ) {
val viewName = view.label()
FullScreenPicker( FullScreenPicker(
title = stringResource(R.string.view_calendars_title), title = stringResource(R.string.view_hide_in_title, viewName),
onDismiss = onDismiss, onDismiss = onDismiss,
predictiveBack = true, predictiveBack = true,
) { ) {
@@ -42,7 +44,7 @@ fun ViewCalendarsPicker(
// Seeded once, then ahead of the store: the picker is the only // Seeded once, then ahead of the store: the picker is the only
// writer while open, so a quick second tap still flips. // writer while open, so a quick second tap still flips.
var hidden by remember(view) { mutableStateOf(state.hiddenViews.calendarsHiddenIn(view)) } var hidden by remember(view) { mutableStateOf(state.hiddenViews.calendarsHiddenIn(view)) }
GroupedHint(stringResource(R.string.view_calendars_hint), verticalPadding = 8.dp) GroupedHint(stringResource(R.string.view_calendars_named_hint, viewName), verticalPadding = 8.dp)
state.groups.forEach { group -> state.groups.forEach { group ->
GroupedSectionHeader(accountGroupTitle(group)) GroupedSectionHeader(accountGroupTitle(group))
MultiOptionRows( MultiOptionRows(
@@ -39,9 +39,9 @@ internal fun EventInstance.openIntent(context: Context, source: CalendarView) =
source = source, source = source,
) )
/** Opens [date] in the app's agenda. */ /** Opens [date]'s day view. */
internal fun openDayAction(context: Context, date: LocalDate) = internal fun openDayAction(context: Context, date: LocalDate) =
actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda)) actionStartActivity(MainActivity.openDateIntent(context, date))
/** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */ /** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */
internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String = internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String =
@@ -33,7 +33,6 @@ import androidx.glance.text.Text
import androidx.glance.text.TextAlign import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle import androidx.glance.text.TextStyle
import de.jeanlucmakiola.calendula.MainActivity import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
import de.jeanlucmakiola.calendula.widget.WidgetAppearance import de.jeanlucmakiola.calendula.widget.WidgetAppearance
@@ -99,7 +98,7 @@ internal fun DateWidgetContent(today: LocalDate, appearance: WidgetAppearance, a
Column( Column(
modifier = GlanceModifier modifier = GlanceModifier
.fillMaxSize() .fillMaxSize()
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day))) .clickable(actionStartActivity(MainActivity.openDateIntent(context, today)))
.semantics { contentDescription = label }, .semantics { contentDescription = label },
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -14,7 +14,6 @@ import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.isCrossedOut import de.jeanlucmakiola.calendula.domain.isCrossedOut
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.ui.common.eventInk import de.jeanlucmakiola.calendula.ui.common.eventInk
import de.jeanlucmakiola.floret.glance.RemoteColor import de.jeanlucmakiola.floret.glance.RemoteColor
@@ -161,7 +160,7 @@ private fun span(text: String, span: Any): CharSequence =
private fun openDayIntent(context: Context, date: LocalDate): PendingIntent = PendingIntent.getActivity( private fun openDayIntent(context: Context, date: LocalDate): PendingIntent = PendingIntent.getActivity(
context, context,
date.toEpochDays().toInt(), date.toEpochDays().toInt(),
MainActivity.openDateIntent(context, date, CalendarView.Month), MainActivity.openDateIntent(context, date),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
) )
@@ -415,7 +415,7 @@ private fun DayList(day: LocalDate, data: MonthDayData.Ready, preview: Boolean)
val events = groupAgendaDays(day, day, source.instances, zone).firstOrNull()?.events.orEmpty() val events = groupAgendaDays(day, day, source.instances, zone).firstOrNull()?.events.orEmpty()
.let { all -> if (data.options.pastDisplay == PastEventDisplay.HIDE) all.filterNot { it.hasEnded(data.now) } else all } .let { all -> if (data.options.pastDisplay == PastEventDisplay.HIDE) all.filterNot { it.hasEnded(data.now) } else all }
val metrics = compactRowMetrics(data.options.textSize, context.resources.configuration.fontScale) val metrics = compactRowMetrics(data.options.textSize, context.resources.configuration.fontScale)
val openDay = actionStartActivity(MainActivity.openDateIntent(context, day, CalendarView.Month)) val openDay = actionStartActivity(MainActivity.openDateIntent(context, day))
Column(modifier = GlanceModifier.fillMaxSize()) { Column(modifier = GlanceModifier.fillMaxSize()) {
val date = localizedDateFormatter(widgetLocale(), "EEEdMMM").format(day.toJavaLocalDate()) val date = localizedDateFormatter(widgetLocale(), "EEEdMMM").format(day.toJavaLocalDate())
val label = when (day) { val label = when (day) {
@@ -245,7 +245,7 @@ private fun TodayPill(today: LocalDate) {
.fillMaxHeight() .fillMaxHeight()
.cornerRadius(PillWidth / 2) .cornerRadius(PillWidth / 2)
.background(GlanceTheme.colors.primary) .background(GlanceTheme.colors.primary)
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day))) .clickable(actionStartActivity(MainActivity.openDateIntent(context, today)))
.semantics { contentDescription = localizedDateFormatter(locale, "EEEEdMMMM").format(today.toJavaLocalDate()) }, .semantics { contentDescription = localizedDateFormatter(locale, "EEEEdMMMM").format(today.toJavaLocalDate()) },
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -46,7 +46,6 @@ import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider import androidx.glance.unit.ColorProvider
import de.jeanlucmakiola.calendula.MainActivity import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.eventAccent import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
@@ -155,7 +154,7 @@ private fun DayTile(date: LocalDate, data: DaysWidgetData.Ready) {
.fillMaxSize() .fillMaxSize()
.cornerRadius(14.dp) .cornerRadius(14.dp)
.background(container) .background(container)
.clickable(actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Week))) .clickable(actionStartActivity(MainActivity.openDateIntent(context, date)))
.semantics { .semantics {
contentDescription = if (colors.isEmpty()) label else context.resources.getQuantityString( contentDescription = if (colors.isEmpty()) label else context.resources.getQuantityString(
R.plurals.widget_day_with_events, events.size, label, events.size, R.plurals.widget_day_with_events, events.size, label, events.size,
+14 -7
View File
@@ -968,14 +968,19 @@
<string name="calendars_hide_in_views_hint">Events from “%1$s” stay out of the views checked here. Reminders, search and widgets still include them.</string> <string name="calendars_hide_in_views_hint">Events from “%1$s” stay out of the views checked here. Reminders, search and widgets still include them.</string>
<string name="calendars_hide_in_views_none">Shown in every view</string> <string name="calendars_hide_in_views_none">Shown in every view</string>
<string name="calendars_hidden_in">Hidden in %1$s</string> <string name="calendars_hidden_in">Hidden in %1$s</string>
<string name="filter_hidden_in_view">Hidden in this view</string> <!-- %1$s: the quoted view name, as in view_hide_in_title. -->
<string name="view_calendars_title">Hide in this view</string> <string name="filter_hidden_in_named_view">Hidden in “%1$s” view</string>
<plurals name="drawer_hidden_in_view_count"> <!-- %1$s is the view's name as the view switcher shows it, e.g. "Month" or "3 days". It is a quoted label: phrase around it instead of inflecting it. -->
<item quantity="one">%d calendar hidden in this view</item> <string name="view_hide_in_title">Hide in “%1$s” view</string>
<item quantity="other">%d calendars hidden in this view</item> <!-- %2$s: the quoted view name, as in view_hide_in_title. -->
<plurals name="drawer_hidden_in_named_view_count">
<item quantity="one">%1$d calendar hidden in “%2$s” view</item>
<item quantity="other">%1$d calendars hidden in “%2$s” view</item>
</plurals> </plurals>
<string name="drawer_hidden_in_view_none">Leave calendars out of this view only</string> <!-- %1$s: the quoted view name, as in view_hide_in_title. -->
<string name="view_calendars_hint">Checked calendars stay out of this view only. Reminders, search and widgets still include them.</string> <string name="drawer_hidden_in_named_view_none">Leave calendars out of the “%1$s” view only</string>
<!-- %1$s: the quoted view name, as in view_hide_in_title. -->
<string name="view_calendars_named_hint">Checked calendars stay out of the “%1$s” view only. Reminders, search and widgets still include them.</string>
<string name="view_calendars_hidden_everywhere">Hidden in every view from the menu</string> <string name="view_calendars_hidden_everywhere">Hidden in every view from the menu</string>
<string name="color_name_mauve">Mauve</string> <string name="color_name_mauve">Mauve</string>
<string name="color_name_red">Red</string> <string name="color_name_red">Red</string>
@@ -1035,8 +1040,10 @@
<string name="calendars_auto_backup_interval">Interval</string> <string name="calendars_auto_backup_interval">Interval</string>
<string name="calendars_auto_backup_every">Every %1$s</string> <string name="calendars_auto_backup_every">Every %1$s</string>
<string name="calendars_auto_backup_interval_min">Minimum 30 minutes.</string> <string name="calendars_auto_backup_interval_min">Minimum 30 minutes.</string>
<string name="calendars_auto_backup_interval_off">Off, only after changes</string>
<string name="calendars_auto_backup_on_change">Also back up after changes</string> <string name="calendars_auto_backup_on_change">Also back up after changes</string>
<string name="calendars_auto_backup_on_change_summary">Updates the undated copy a few minutes after events change. Dated backups stay on the interval.</string> <string name="calendars_auto_backup_on_change_summary">Updates the undated copy a few minutes after events change. Dated backups stay on the interval.</string>
<string name="calendars_auto_backup_on_change_only_summary">Updates the undated copy a few minutes after events change. No dated backups.</string>
<string name="calendars_auto_backup_calendars">Calendars</string> <string name="calendars_auto_backup_calendars">Calendars</string>
<plurals name="calendars_auto_backup_calendars_count"> <plurals name="calendars_auto_backup_calendars_count">
<item quantity="one">%d calendar</item> <item quantity="one">%d calendar</item>
@@ -13,6 +13,7 @@ import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime import kotlinx.datetime.LocalTime
import kotlinx.datetime.UtcOffset import kotlinx.datetime.UtcOffset
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.time.ZoneId import java.time.ZoneId
import kotlin.time.Instant import kotlin.time.Instant
@@ -500,6 +501,58 @@ class EventWriteMapperTest {
.isEqualTo(CalendarContract.Events.STATUS_CANCELED) .isEqualTo(CalendarContract.Events.STATUS_CANCELED)
} }
// --- seriesDuration (#502) ---
@Test
fun `series duration prefers the expanded occurrence over dtend`() {
// DTEND as the end of the whole series must not stretch every occurrence.
assertThat(seriesDuration(1_000_000L, 9_000_000_000L, 3_600_000L, isAllDay = false)).isEqualTo("P3600S")
}
@Test
fun `series duration falls back to dtend when it lies after dtstart`() {
assertThat(seriesDuration(1_000_000L, 8_200_000L, null, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration ignores a zero dtend and uses the occurrence span`() {
assertThat(seriesDuration(1_790_852_400_000L, 0L, 7_200_000L, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration gives up rather than guessing`() {
assertThat(seriesDuration(1_000L, 0L, null, isAllDay = false)).isNull()
assertThat(seriesDuration(1_000L, null, null, isAllDay = true)).isNull()
}
@Test
fun `all-day series duration rounds to whole days`() {
// 47 h: a two-day occurrence read across a DST change.
assertThat(seriesDuration(0L, null, 47L * 3_600_000L, isAllDay = true)).isEqualTo("P2D")
}
@Test
fun `series duration keeps a zero length the provider already shows`() {
assertThat(seriesDuration(1_000L, 0L, 0L, isAllDay = false)).isEqualTo("P0S")
assertThat(seriesDuration(1_000L, 1_000L, null, isAllDay = true)).isEqualTo("P1D")
}
@Test
fun `exdate drop clears a stray dtend on the series`() {
val values = buildOccurrenceExdateValues(
existingExdate = null,
occurrenceMillis = 1_784_102_400_000L,
dtStartMillis = 1_783_929_600_000L,
rrule = "FREQ=DAILY;COUNT=5",
rdate = null,
duration = "PT1H",
timezone = "Europe/Berlin",
allDay = 0,
)
assertThat(values).containsKey(CalendarContract.Events.DTEND)
assertThat(values[CalendarContract.Events.DTEND]).isNull()
}
// --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) --- // --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) ---
@Test @Test
@@ -1194,6 +1247,14 @@ class EventWriteMapperTest {
description = "", description = "",
) )
@Test
fun `moved series with a zero dtend and no duration is refused, not copied broken`() {
val snapshot = masterSnapshot(dtEndMillis = 0L, rrule = "FREQ=WEEKLY;BYDAY=TH")
assertThrows<WriteFailedException> {
buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula")
}
}
@Test @Test
fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() { fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() {
val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula") val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula")
@@ -5,6 +5,7 @@ import de.jeanlucmakiola.calendula.testSettings
import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.ReminderOverride
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
@@ -932,6 +933,71 @@ class SettingsPrefsTest {
assertThat(prefs.autoBackupKeep.first()).isEqualTo(10) assertThat(prefs.autoBackupKeep.first()).isEqualTo(10)
} }
@Test
fun `the backup interval is on by default and can only go off alongside after-change backups`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
prefs.setAutoBackupScheduled(false)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
prefs.setAutoBackupOnChange(true)
prefs.setAutoBackupScheduled(false)
assertThat(prefs.autoBackupScheduled.first()).isFalse()
prefs.setAutoBackupScheduled(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `turning after-change backups off brings the interval back for good`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupIntervalMinutes(6 * 60L)
prefs.setAutoBackupOnChange(true)
prefs.setAutoBackupScheduled(false)
prefs.setAutoBackupOnChange(false)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
assertThat(prefs.autoBackupIntervalMinutes.first()).isEqualTo(6 * 60L)
prefs.setAutoBackupOnChange(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `the interval setters report whether they switched it`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.setAutoBackupScheduled(false)).isFalse()
assertThat(prefs.setAutoBackupOnChange(true)).isFalse()
assertThat(prefs.setAutoBackupScheduled(false)).isTrue()
assertThat(prefs.setAutoBackupScheduled(false)).isFalse()
assertThat(prefs.setAutoBackupOnChange(false)).isTrue()
assertThat(prefs.autoBackupOnChangeAndScheduled.first()).isEqualTo(false to true)
}
@Test
fun `switching the interval off without after-change backups leaves nothing behind`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
prefs.setAutoBackupScheduled(false)
prefs.setAutoBackupOnChange(true)
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `an interval-off stored without after-change backups doesn't stick once they go on`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
m[booleanPreferencesKey("auto_backup_scheduled")] = false
m
}
assertThat(prefs.autoBackupScheduled.first()).isTrue()
assertThat(prefs.setAutoBackupOnChange(true)).isFalse()
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test @Test
fun `a pre-411 install adopts its old file when the layout is pinned in place`(@TempDir tempDir: Path) = runTest { fun `a pre-411 install adopts its old file when the layout is pinned in place`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings") val store = testDataStore(tempDir, "test_settings")
@@ -107,6 +107,26 @@ class BackupPlanTest {
.containsExactly("Fitness", "Fitness-20").inOrder() .containsExactly("Fitness", "Fitness-20").inOrder()
} }
@Test
fun `a stable copy kept for a calendar out of the backup isn't taken over or left blocking`() {
val ledger = mapOf(latestLedgerKey("9") to listOf("Fitness.ics"))
val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics")).single()
assertThat(target.baseName).isEqualTo("Fitness-20")
val plan = planBackupFiles(listOf(target), ledger, setOf("Fitness.ics"), at, keep = 3).single()
assertThat(plan.backedUp(intervalOn = false)).isTrue()
val gone = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, existing = emptySet()).single()
assertThat(gone.baseName).isEqualTo("Fitness")
}
@Test
fun `a series writing under its id suffix keeps it once the clash is gone`() {
val ledger = mapOf(latestLedgerKey("20") to listOf("Fitness-20.ics"))
val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics", "Fitness-20.ics"))
.single()
assertThat(target.baseName).isEqualTo("Fitness-20")
}
@Test @Test
fun `a calendar named like the combined file doesn't share its series`() { fun `a calendar named like the combined file doesn't share its series`() {
val target = backupTargets(listOf(cal(4L, COMBINED_BACKUP_BASE)), combined = false).single() val target = backupTargets(listOf(cal(4L, COMBINED_BACKUP_BASE)), combined = false).single()
@@ -402,4 +422,30 @@ class BackupPlanTest {
assertThat(one.inBackupOrder()).isEqualTo(other.inBackupOrder()) assertThat(one.inBackupOrder()).isEqualTo(other.inBackupOrder())
assertThat(one.inBackupOrder().map { it.uid }).containsExactly("a", "b").inOrder() assertThat(one.inBackupOrder().map { it.uid }).containsExactly("a", "b").inOrder()
} }
@Test
fun `the interval stays on unless after-change backups cover for it`() {
assertThat(backupIntervalOn(stored = true, onChange = false)).isTrue()
assertThat(backupIntervalOn(stored = false, onChange = false)).isTrue()
assertThat(backupIntervalOn(stored = true, onChange = true)).isTrue()
assertThat(backupIntervalOn(stored = false, onChange = true)).isFalse()
}
@Test
fun `only a run with the interval on writes dated files`() {
assertThat(backupRunLatestOnly(changeRun = false, intervalOn = true)).isFalse()
assertThat(backupRunLatestOnly(changeRun = true, intervalOn = true)).isTrue()
assertThat(backupRunLatestOnly(changeRun = false, intervalOn = false)).isTrue()
assertThat(backupRunLatestOnly(changeRun = true, intervalOn = false)).isTrue()
}
@Test
fun `without the interval a series whose stable name is the user's goes unbacked`() {
val free = planBackupFiles(listOf(work), emptyMap(), emptySet(), at, keep = 3).single()
val blocked = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 3).single()
assertThat(free.backedUp(intervalOn = false)).isTrue()
assertThat(blocked.backedUp(intervalOn = false)).isFalse()
assertThat(blocked.backedUp(intervalOn = true)).isTrue()
}
} }
@@ -0,0 +1,48 @@
package de.jeanlucmakiola.calendula.ui
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import org.junit.jupiter.api.Test
class WidgetNavRequestTest {
private val detail = LeaveTarget.Detail(1, 2, 3)
@Test
fun `a widget's day or event is what back leaves from`() {
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = true).leaveTarget).isEqualTo(LeaveTarget.View)
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = false).leaveTarget).isNull()
assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Agenda).leaveTarget).isEqualTo(detail)
assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Day).leaveTarget).isEqualTo(detail)
assertThat(WidgetNavRequest.OpenView(CalendarView.Month).leaveTarget).isNull()
assertThat(WidgetNavRequest.Create(null).leaveTarget).isNull()
}
@Test
fun `the target stays only while the views stay put`() {
val day = listOf(CalendarView.Week, CalendarView.Day)
assertThat(LeaveTarget.View.afterMove(day, day.toList())).isEqualTo(LeaveTarget.View)
assertThat(LeaveTarget.View.afterMove(day, listOf(CalendarView.Week))).isNull()
assertThat(detail.afterMove(day, day + CalendarView.Month)).isNull()
assertThat(null.afterMove(day, day)).isNull()
}
@Test
fun `a widget's detail is dropped once it closes or another opens`() {
assertThat(detail.afterDetail(longArrayOf(1, 2, 3))).isEqualTo(detail)
assertThat(detail.afterDetail(null)).isNull()
assertThat(detail.afterDetail(longArrayOf(4, 5, 6))).isNull()
// A widget's day keeps its target under an in-app detail.
assertThat(LeaveTarget.View.afterDetail(longArrayOf(4, 5, 6))).isEqualTo(LeaveTarget.View)
}
@Test
fun `back leaves only from the widget's own day or detail`() {
assertThat(LeaveTarget.View.leaves(detail = null, overlayVisible = false)).isTrue()
assertThat(LeaveTarget.View.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse()
assertThat(detail.leaves(detail = longArrayOf(1, 2, 3), overlayVisible = true)).isTrue()
assertThat(detail.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse()
assertThat(detail.leaves(detail = null, overlayVisible = false)).isFalse()
assertThat(null.leaves(detail = null, overlayVisible = false)).isFalse()
}
}
@@ -6,8 +6,8 @@ import org.junit.jupiter.api.Test
/** /**
* The pure back-stack rules behind [CalendarHost]'s top-level navigation: * The pure back-stack rules behind [CalendarHost]'s top-level navigation:
* the home view is always the bottom, a lateral move keeps the stack one deep, * the home view is always the bottom, a lateral move keeps the stack one deep,
* and a date tap drills the day view on top. Verifies the back sequences the * and a date tap drills the day view on top. Verifies the back sequences, e.g.
* widget-UX fix promises (e.g. agenda widget → day → back → agenda → back → home). * agenda → day → back → agenda → back → home.
*/ */
class ViewBackStackTest { class ViewBackStackTest {
@@ -74,8 +74,8 @@ class ViewBackStackTest {
} }
@Test @Test
fun `agenda widget date tap backs out agenda then home`() { fun `a day tapped in a widget event's view backs out to it, then home`() {
// openDate(source = Agenda): root in Agenda over the Week home, then drill. // Agenda widget event tap roots [Week, Agenda]; a day tapped there drills on top.
val stack = viewBaseStack(CalendarView.Week, CalendarView.Agenda).drillToDay() val stack = viewBaseStack(CalendarView.Week, CalendarView.Agenda).drillToDay()
assertThat(stack) assertThat(stack)
.containsExactly(CalendarView.Week, CalendarView.Agenda, CalendarView.Day) .containsExactly(CalendarView.Week, CalendarView.Agenda, CalendarView.Day)
@@ -86,11 +86,11 @@ class ViewBackStackTest {
} }
@Test @Test
fun `month widget date tap backs out month then home`() { fun `a date launch drills the day over the home view only`() {
val stack = viewBaseStack(CalendarView.Week, CalendarView.Month).drillToDay() assertThat(listOf(CalendarView.Week).drillToDay())
assertThat(stack.last()).isEqualTo(CalendarView.Day) .containsExactly(CalendarView.Week, CalendarView.Day)
assertThat(stack.dropLast(1).last()).isEqualTo(CalendarView.Month) .inOrder()
assertThat(stack.first()).isEqualTo(CalendarView.Week) assertThat(listOf(CalendarView.Day).drillToDay()).containsExactly(CalendarView.Day)
} }
@Test @Test
+16 -3
View File
@@ -420,8 +420,8 @@ separate in-app declutter that never touches reminders. Narrower still is the pe
(`SettingsPrefs.perCalendarHiddenViews`, #270): each view model asks for its (`SettingsPrefs.perCalendarHiddenViews`, #270): each view model asks for its
events through `instancesWithout(range, calendarsHiddenIn(view, …))`, which drops events through `instancesWithout(range, calendarsHiddenIn(view, …))`, which drops
the calendars hidden in that one view on top of the repository's filters; reminders, search and widgets read the calendars hidden in that one view on top of the repository's filters; reminders, search and widgets read
the repository and never see it. The drawer's "Hide in this view" entry (#517) edits the same the repository and never see it. The drawer's "Hide in “<view>” view" entry (#517, #143) edits the same
set for the view on show, and the drawer's per-row "Hidden in this view" notes read it. set for the view on show, and the drawer's per-row "Hidden in “<view>” view" notes read it.
**A channel per calendar (#145).** `ReminderChannels` keeps one notification **A channel per calendar (#145).** `ReminderChannels` keeps one notification
channel per calendar, grouped by account (one that syncs no events only gets channel per calendar, grouped by account (one that syncs no events only gets
@@ -630,7 +630,7 @@ process start (the boot receivers start one), without replacing a waiting watch.
Runs share the scheduled backup's lock. A change run only rewrites the stable Runs share the scheduled backup's lock. A change run only rewrites the stable
copies and never retries: the dated files and their retention stay on the copies and never retries: the dated files and their retention stay on the
interval, so a day of edits can't rotate the history out. Every run that writes interval, so a day of edits can't rotate the history out. Every run that writes
something is recorded on the status line; the failure notification comes once something, or fails to, is recorded on the status line; the failure notification comes once
per failure streak, as it reaches the threshold, and the next success of any run per failure streak, as it reaches the threshold, and the next success of any run
clears it. Since the trigger fires for any provider change (reminders, other clears it. Since the trigger fires for any provider change (reminders, other
calendars, sync bookkeeping), each series' file (events in a fixed order) is calendars, sync bookkeeping), each series' file (events in a fixed order) is
@@ -642,6 +642,19 @@ rewritten. A copy that went missing is restored by the next run that lists the
folder; one a still-loading listing doesn't show, or one edited in place outside folder; one a still-loading listing doesn't show, or one edited in place outside
the app, is left to the next scheduled run. the app, is left to the next scheduled run.
While the option is on, the interval itself can be switched off
(`auto_backup_scheduled`, read through `backupIntervalOn`, so it never counts as
off without the option): the periodic work is cancelled and no run writes or
prunes dated files. Run-now then rewrites every stable copy, change runs the
changed ones and any missing from a complete listing (checked even when no hash
moved, since no scheduled run would restore them), and a series whose stable
name a file of the user's holds counts as failed (not retried), since nothing
else backs it up. A change run fails on it again only once its content changed,
and while it stays unchanged doesn't record the run as a success either. Turning the option on or off sets the interval back
on, at the interval it had; any switch of the interval backs up right away.
What the text above leaves to the next scheduled run then waits for the next
run-now.
**A backup carries the series' deleted and moved occurrences.** `EXDATE` lives on **A backup carries the series' deleted and moved occurrences.** `EXDATE` lives on
the master row and is part of `EventExportProjection`; `IcsWriter` marks an the master row and is part of `EventExportProjection`; `IcsWriter` marks an
all-day series' exclusions `VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value all-day series' exclusions `VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value
+1 -1
View File
@@ -58,7 +58,7 @@ e.g. `"theme_mode": "DARK"`, `"multi_day_count": 4`,
`"default_reminder_minutes": "10,60"`. Only keys that have been set are `"default_reminder_minutes": "10,60"`. Only keys that have been set are
written. `SettingsBackupSchema.plain` lists them: appearance, fonts, written. `SettingsBackupSchema.plain` lists them: appearance, fonts,
views, the agenda screen, the event form and its default calendar, reminders views, the agenda screen, the event form and its default calendar, reminders
and the daily summary, automatic backup (switch, interval, layout, retention, and the daily summary, automatic backup (switch, interval and whether it runs, layout, retention,
backup on change) and contact special dates (switch, types, title backup on change) and contact special dates (switch, types, title
templates, year). templates, year).