Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95ad3a30cf | ||
|
|
8ce4831efa |
No files matched your search
@@ -318,16 +318,13 @@ jobs:
|
||||
# not provide node inside custom job containers, so JavaScript actions
|
||||
# (checkout, download-artifact) can't run there. The Renovate job gets away
|
||||
# with a container because its only step is a shell command. Ruby is installed
|
||||
# the same way sshpass, jq and fdroidserver are in the job above, from trixie:
|
||||
# fastlane >= 2.241 needs Ruby 3.2+, and bookworm's apt only has 3.1.
|
||||
# the same way sshpass, jq and fdroidserver are in the job above.
|
||||
play:
|
||||
needs: [detect, release]
|
||||
# workflow_dispatch is the F-Droid re-sign recovery path — it must never
|
||||
# touch Play, so gate on a real release only.
|
||||
if: needs.detect.outputs.is_release == 'true'
|
||||
runs-on: docker
|
||||
container:
|
||||
image: node:22-trixie
|
||||
env:
|
||||
VERSION: ${{ needs.detect.outputs.version }}
|
||||
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
# directly drops the docker-in-docker requirement entirely.
|
||||
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
||||
container:
|
||||
image: ghcr.io/renovatebot/renovate:44.237.3
|
||||
image: ghcr.io/renovatebot/renovate:43.232.0
|
||||
steps:
|
||||
- name: Run Renovate
|
||||
run: renovate
|
||||
|
||||
@@ -7,38 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- **Notifications per calendar.** Settings → Notifications → Calendars lists every calendar with its own switch, sound and system channel, grouped by account. Turn one calendar's reminders off without hiding it, give it its own sound, or see that the system blocks it ([#145], [#272], [#340]).
|
||||
- **Pick the reminder sound in the app.** Choose a sound for all calendars or for one, including Silent, without going through the system settings ([#518]).
|
||||
- **Full-screen reminders.** A calendar can show its reminders full screen, even on the lock screen, either sounding once or ringing like an alarm until you dismiss or snooze them ([#171]).
|
||||
- **Reminders at a set time.** Add a reminder like "1 day before at 20:00" to timed events, with a default for new events and per calendar ([#459]).
|
||||
- **A daily summary.** One notification a day lists today's or tomorrow's events, at a time you choose, with calendars you can leave out ([#459]).
|
||||
- **More reminder presets.** 2, 3, 4 and 5 days and 2 and 3 weeks before are one tap away, in the editor and the default pickers ([#365]).
|
||||
- **Open link or map from a reminder.** A reminder whose location holds a meeting link gets an Open link button, one with a place gets Open in maps ([#464]).
|
||||
- **Hide calendars in chosen views.** A calendar can stay in the agenda but leave the month view, for example. Set it under Settings → Calendars, or from the drawer for the view you're in ([#270], [#517]).
|
||||
- **Show or hide a whole account at once** by tapping its header in the drawer ([#143]).
|
||||
- **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]).
|
||||
- **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 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
|
||||
- **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
|
||||
- **Repeating events with extra dates survive a backup.** `.ics` backups now write and read back RDATE ([#515]).
|
||||
|
||||
## [2.24.2] — 2026-11-13
|
||||
|
||||
### Fixed
|
||||
- **Quick moves no longer get lost.** Dropping an event while an earlier move was still saving used to snap it back without a word. Drops now wait in line and are saved in order, and a moved event stays where you dropped it until the calendar shows it there. If an event changed before a drop could be saved, or the line is full, a message says so instead ([#494]).
|
||||
- **Undo after a run of moves** keeps the first move's Undo, and each failed move gets its own message rather than replacing the last one ([#494]).
|
||||
|
||||
### Changed
|
||||
- **The day view's title names the month**, like the week and 3-day views. Weekday and date already sit in the column header below it ([#501]).
|
||||
- Library updates (kotlinx-datetime, AppCompat).
|
||||
|
||||
## [2.24.1] — 2026-11-12
|
||||
|
||||
### Added
|
||||
@@ -2005,26 +1973,3 @@ automatically, with zero telemetry and no internet permission.
|
||||
[#489]: https://codeberg.org/jlmakiola/calendula/issues/489
|
||||
[#491]: https://codeberg.org/jlmakiola/calendula/issues/491
|
||||
[#493]: https://codeberg.org/jlmakiola/calendula/issues/493
|
||||
[#494]: https://codeberg.org/jlmakiola/calendula/issues/494
|
||||
[#501]: https://codeberg.org/jlmakiola/calendula/issues/501
|
||||
[#143]: https://codeberg.org/jlmakiola/calendula/issues/143
|
||||
[#145]: https://codeberg.org/jlmakiola/calendula/issues/145
|
||||
[#147]: https://codeberg.org/jlmakiola/calendula/issues/147
|
||||
[#171]: https://codeberg.org/jlmakiola/calendula/issues/171
|
||||
[#240]: https://codeberg.org/jlmakiola/calendula/issues/240
|
||||
[#270]: https://codeberg.org/jlmakiola/calendula/issues/270
|
||||
[#272]: https://codeberg.org/jlmakiola/calendula/issues/272
|
||||
[#303]: https://codeberg.org/jlmakiola/calendula/issues/303
|
||||
[#325]: https://codeberg.org/jlmakiola/calendula/issues/325
|
||||
[#340]: https://codeberg.org/jlmakiola/calendula/issues/340
|
||||
[#365]: https://codeberg.org/jlmakiola/calendula/issues/365
|
||||
[#411]: https://codeberg.org/jlmakiola/calendula/issues/411
|
||||
[#429]: https://codeberg.org/jlmakiola/calendula/issues/429
|
||||
[#459]: https://codeberg.org/jlmakiola/calendula/issues/459
|
||||
[#464]: https://codeberg.org/jlmakiola/calendula/issues/464
|
||||
[#481]: https://codeberg.org/jlmakiola/calendula/issues/481
|
||||
[#514]: https://codeberg.org/jlmakiola/calendula/issues/514
|
||||
[#515]: https://codeberg.org/jlmakiola/calendula/issues/515
|
||||
[#516]: https://codeberg.org/jlmakiola/calendula/issues/516
|
||||
[#517]: https://codeberg.org/jlmakiola/calendula/issues/517
|
||||
[#518]: https://codeberg.org/jlmakiola/calendula/issues/518
|
||||
@@ -7,4 +7,4 @@ source "https://rubygems.org"
|
||||
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
|
||||
# committed on purpose: this resolves an uploader's transitive deps, not the
|
||||
# app's, and none of it affects the reproducible release build.
|
||||
gem "fastlane", "2.241.1"
|
||||
gem "fastlane", "2.237.0"
|
||||
@@ -32,8 +32,8 @@ android {
|
||||
// (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.
|
||||
// See docs/RELEASING.md.
|
||||
versionCode = 2250001
|
||||
versionName = "2.25.0-beta.1"
|
||||
versionCode = 2240199
|
||||
versionName = "2.24.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -177,13 +177,11 @@ dependencies {
|
||||
implementation("de.jeanlucmakiola.floret:core-crash")
|
||||
implementation("de.jeanlucmakiola.floret:core-di")
|
||||
implementation("de.jeanlucmakiola.floret:core-prefs")
|
||||
implementation("de.jeanlucmakiola.floret:core-backup")
|
||||
implementation("de.jeanlucmakiola.floret:core-reminders")
|
||||
implementation("de.jeanlucmakiola.floret:core-android")
|
||||
implementation("de.jeanlucmakiola.floret:identity")
|
||||
implementation("de.jeanlucmakiola.floret:components")
|
||||
implementation("de.jeanlucmakiola.floret:glance")
|
||||
implementation("de.jeanlucmakiola.floret:ring")
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
|
||||
-1
@@ -37,7 +37,6 @@ class CalendarRepositorySmokeTest {
|
||||
CalendarPrefs(store),
|
||||
SettingsPrefs(store),
|
||||
Dispatchers.IO,
|
||||
AndroidSyncRequester(context),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -41,18 +41,10 @@
|
||||
-->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- Lets "Sync now" (#240) follow the sync it asked for: read-only sync state, install-time. -->
|
||||
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
|
||||
|
||||
<!-- WorkManager declares this for network constraints, which the app doesn't use (#448). -->
|
||||
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||
|
||||
<!-- Full-screen reminder alerts and their ring (#171), opt-in per calendar. -->
|
||||
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove" />
|
||||
|
||||
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
||||
returns null and the calendar manager's per-account "manage" button can't
|
||||
@@ -64,21 +56,6 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
<!-- Sync adapters to ask for a calendar sync (#240, #303). -->
|
||||
<intent>
|
||||
<action android:name="android.content.SyncAdapter" />
|
||||
</intent>
|
||||
<!-- A reminder's "Open link" button only shows when something can open the link (#464). -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="https" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="http" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
@@ -319,12 +296,6 @@
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<!-- The change watch behind "Also back up after changes" (#516). -->
|
||||
<service
|
||||
android:name=".data.backup.BackupChangeJob"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||
|
||||
<!-- Reminder delivery is the app's own (#75): it plans the alarms from
|
||||
Instances + Reminders instead of waiting for the provider's
|
||||
EVENT_REMINDER broadcast, which OEM-modified providers demonstrably
|
||||
@@ -351,20 +322,6 @@
|
||||
android:name=".data.reminders.ReminderActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- The full-screen reminder alert (#171), in a task of its own. -->
|
||||
<activity
|
||||
android:name=".ui.reminders.ReminderAlertActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="" />
|
||||
|
||||
<!-- Rings a "Ring until dismissed" reminder (#171). -->
|
||||
<service
|
||||
android:name=".data.reminders.ReminderRingService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="systemExempted" />
|
||||
|
||||
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
|
||||
<activity
|
||||
android:name=".widget.config.WidgetConfigActivity"
|
||||
@@ -523,18 +480,6 @@
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- WorkManager initialises on demand from CalendulaApp's configuration. -->
|
||||
<provider
|
||||
android:name="androidx.startup.InitializationProvider"
|
||||
android:authorities="${applicationId}.androidx-startup"
|
||||
android:exported="false"
|
||||
tools:node="merge">
|
||||
<meta-data
|
||||
android:name="androidx.work.WorkManagerInitializer"
|
||||
android:value="androidx.startup"
|
||||
tools:node="remove" />
|
||||
</provider>
|
||||
|
||||
<!-- Hands .ics files we stage in the cache to other apps via a content
|
||||
Uri (single-event share). Authority tracks applicationId so the
|
||||
debug suffix doesn't break getUriForFile. -->
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
package de.jeanlucmakiola.calendula
|
||||
|
||||
import android.app.Application
|
||||
import androidx.work.Configuration
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import de.jeanlucmakiola.calendula.data.backup.BackupChangeJob
|
||||
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler
|
||||
import de.jeanlucmakiola.calendula.data.backup.BackupWorker
|
||||
@@ -29,11 +27,7 @@ import kotlinx.coroutines.launch
|
||||
* in AndroidManifest.xml. Hilt initializes its component graph here.
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class CalendulaApp : Application(), Configuration.Provider {
|
||||
|
||||
/** Keeps WorkManager's JobScheduler ids clear of [BackupChangeJob]'s. */
|
||||
override val workManagerConfiguration: Configuration =
|
||||
Configuration.Builder().setJobSchedulerJobIdRange(0, BackupChangeJob.JOB_ID - 1).build()
|
||||
class CalendulaApp : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -116,7 +110,12 @@ class CalendulaApp : Application(), Configuration.Provider {
|
||||
val deps = EntryPointAccessors.fromApplication(this, BackupWorker.Deps::class.java)
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||
val prefs = deps.settingsPrefs()
|
||||
BackupScheduler.reconcile(this@CalendulaApp, prefs)
|
||||
BackupScheduler.apply(
|
||||
context = this@CalendulaApp,
|
||||
enabled = prefs.autoBackupEnabled.first(),
|
||||
intervalMinutes = prefs.autoBackupIntervalMinutes.first(),
|
||||
hasFolder = prefs.autoBackupFolderUri.first() != null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,10 +67,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.toInstant
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
@@ -368,7 +365,6 @@ class MainActivity : AppCompatActivity() {
|
||||
description = getStringExtra(CalendarContract.Events.DESCRIPTION),
|
||||
location = getStringExtra(CalendarContract.Events.EVENT_LOCATION),
|
||||
rrule = getStringExtra(CalendarContract.Events.RRULE),
|
||||
calendarId = calendarIdExtraOrNull(),
|
||||
zone = TimeZone.currentSystemDefault(),
|
||||
now = Clock.System.now(),
|
||||
)
|
||||
@@ -429,15 +425,6 @@ class MainActivity : AppCompatActivity() {
|
||||
private fun Intent.longExtraOrNull(key: String): Long? =
|
||||
if (hasExtra(key)) getLongExtra(key, 0L) else null
|
||||
|
||||
/** The calendar an insert intent names (#429); callers pass it as an int, a long or a string. */
|
||||
@Suppress("DEPRECATION")
|
||||
private fun Intent.calendarIdExtraOrNull(): Long? =
|
||||
when (val value = extras?.get(CalendarContract.Events.CALENDAR_ID)) {
|
||||
is Number -> value.toLong()
|
||||
is String -> value.trim().toLongOrNull()
|
||||
else -> null
|
||||
}?.takeIf { it > 0 }
|
||||
|
||||
/**
|
||||
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
|
||||
* "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/
|
||||
@@ -633,20 +620,6 @@ class MainActivity : AppCompatActivity() {
|
||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the day view on [date] over the default home view — the daily
|
||||
* summary's tap (#459). Spoken as the system's own "view time" intent,
|
||||
* at the day's local noon, so it lands on the path a clock tap takes.
|
||||
*/
|
||||
fun openDayIntent(context: Context, date: LocalDate): Intent {
|
||||
val noon = LocalDateTime(date, LocalTime(12, 0))
|
||||
.toInstant(TimeZone.currentSystemDefault())
|
||||
.toEpochMilliseconds()
|
||||
return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri())
|
||||
.setClass(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
|
||||
/** Open the create-event form prefilled for [date] (home-screen widgets). */
|
||||
fun openCreateIntent(context: Context, date: LocalDate): Intent =
|
||||
Intent(context, MainActivity::class.java).apply {
|
||||
|
||||
@@ -5,23 +5,18 @@ import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.await
|
||||
import androidx.work.workDataOf
|
||||
import dagger.hilt.EntryPoint
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
@@ -30,87 +25,42 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupFilePlan
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupTarget
|
||||
import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint
|
||||
import de.jeanlucmakiola.calendula.domain.backup.backupTargets
|
||||
import de.jeanlucmakiola.calendula.domain.backup.inBackupOrder
|
||||
import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere
|
||||
import de.jeanlucmakiola.calendula.domain.backup.latestFileName
|
||||
import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey
|
||||
import de.jeanlucmakiola.calendula.domain.backup.needsRefresh
|
||||
import de.jeanlucmakiola.calendula.domain.backup.planBackupFiles
|
||||
import de.jeanlucmakiola.calendula.domain.backup.replacedLatestCopies
|
||||
import de.jeanlucmakiola.calendula.domain.backup.withFingerprint
|
||||
import de.jeanlucmakiola.calendula.domain.backup.withLedgerEntry
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.time.LocalDateTime
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.time.Clock
|
||||
|
||||
/**
|
||||
* Schedules and runs the automatic periodic `.ics` backup (issue #8) of the
|
||||
* calendars the user picked (#147). One-way export only — it mirrors the manual
|
||||
* "Back up" into a user-chosen folder on an interval; it is not a sync. Stays
|
||||
* INTERNET-free: everything is local provider reads + local file writes.
|
||||
* Schedules and runs the automatic periodic `.ics` backup of local calendars
|
||||
* (issue #8). One-way export only — it mirrors the manual "Back up" into a
|
||||
* user-chosen folder on an interval; it is not a sync. Stays INTERNET-free:
|
||||
* everything is local provider reads + a local file write.
|
||||
*/
|
||||
object BackupScheduler {
|
||||
|
||||
private const val WORK_NAME = "auto-backup"
|
||||
private const val WORK_NAME_NOW = "auto-backup-now"
|
||||
private const val WORK_NAME_CHANGE = "auto-backup-change"
|
||||
internal const val KEY_CHANGE_RUN = "change_run"
|
||||
|
||||
private val reconcileLock = Mutex()
|
||||
|
||||
/** A watch that fired while the option was off: still pending until it finishes, but not re-armed. */
|
||||
private var watchDropped = false
|
||||
|
||||
/**
|
||||
* Reconcile the scheduled work with the saved settings: enqueue a unique
|
||||
* Reconcile the scheduled work with the current settings: enqueue a unique
|
||||
* periodic request when backup is on and a folder is set, 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
|
||||
* [runNow] with a near-identical copy. With backing up after changes on
|
||||
* (#516), the change watch ([BackupChangeJob]) is armed unless it already
|
||||
* waits; it doesn't survive a reboot, and this runs on every process start.
|
||||
* Serialised and not cancellable, so quick toggles settle on the last one.
|
||||
* The first run is delayed by one interval so it never overlaps an immediate
|
||||
* [runNow] (two simultaneous writes would race and leave a "(1)" duplicate).
|
||||
*/
|
||||
suspend fun reconcile(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable + Dispatchers.IO) {
|
||||
reconcileLock.withLock {
|
||||
try {
|
||||
apply(context, prefs)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Scheduling the automatic backup failed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun apply(context: Context, prefs: SettingsPrefs) {
|
||||
fun apply(context: Context, enabled: Boolean, intervalMinutes: Long, hasFolder: Boolean) {
|
||||
val workManager = WorkManager.getInstance(context)
|
||||
fun stopWatching() {
|
||||
BackupChangeJob.cancel(context)
|
||||
workManager.cancelUniqueWork(WORK_NAME_CHANGE)
|
||||
}
|
||||
if (!prefs.autoBackupEnabled.first() || prefs.autoBackupFolderUri.first() == null) {
|
||||
if (!enabled || !hasFolder) {
|
||||
workManager.cancelUniqueWork(WORK_NAME)
|
||||
// Also cancel any pending immediate run — otherwise a failing run-now
|
||||
// keeps retrying after the user has turned backup off.
|
||||
workManager.cancelUniqueWork(WORK_NAME_NOW)
|
||||
stopWatching()
|
||||
return
|
||||
}
|
||||
// WorkManager's own floor is 15 min; the UI floors the user choice at 30.
|
||||
val interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L)
|
||||
val interval = intervalMinutes.coerceAtLeast(15L)
|
||||
val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES)
|
||||
.setInitialDelay(interval, TimeUnit.MINUTES)
|
||||
.build()
|
||||
@@ -119,44 +69,6 @@ object BackupScheduler {
|
||||
ExistingPeriodicWorkPolicy.UPDATE,
|
||||
request,
|
||||
)
|
||||
if (!prefs.autoBackupOnChange.first()) {
|
||||
stopWatching()
|
||||
} else if (watchDropped || !BackupChangeJob.isPending(context)) {
|
||||
// Replacing a waiting watch would drop the changes it has seen.
|
||||
BackupChangeJob.schedule(context)
|
||||
watchDropped = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch fired: queue a change run and arm the next watch, unless the
|
||||
* option went off meanwhile. Under [reconcileLock], so it can't re-arm
|
||||
* after a switch-off.
|
||||
*/
|
||||
internal suspend fun changed(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable) {
|
||||
reconcileLock.withLock {
|
||||
// Re-armed even when queueing the run fails: a trigger fires only once.
|
||||
var wanted = true
|
||||
try {
|
||||
wanted = prefs.autoBackupEnabled.first() && prefs.autoBackupFolderUri.first() != null &&
|
||||
prefs.autoBackupOnChange.first()
|
||||
if (wanted) queueChangeRun(context)
|
||||
} finally {
|
||||
if (wanted) BackupChangeJob.schedule(context)
|
||||
watchDropped = !wanted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun queueChangeRun(context: Context) {
|
||||
val workManager = WorkManager.getInstance(context)
|
||||
val states = workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_CHANGE).first().map { it.state }
|
||||
val policy = changeRunPolicy(states) ?: return
|
||||
val run = OneTimeWorkRequestBuilder<BackupWorker>()
|
||||
.setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build())
|
||||
.setInputData(workDataOf(KEY_CHANGE_RUN to true))
|
||||
.build()
|
||||
workManager.enqueueUniqueWork(WORK_NAME_CHANGE, policy, run).await()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,25 +83,11 @@ object BackupScheduler {
|
||||
OneTimeWorkRequestBuilder<BackupWorker>().build(),
|
||||
)
|
||||
}
|
||||
|
||||
private const val TAG = "BackupScheduler"
|
||||
}
|
||||
|
||||
/**
|
||||
* How a fired change watch queues its run (#516), from the change runs' work
|
||||
* [states]: a run that hasn't started yet will see the change anyway (null);
|
||||
* one already going may have read too early, so the new one queues behind it.
|
||||
*/
|
||||
internal fun changeRunPolicy(states: List<WorkInfo.State>): ExistingWorkPolicy? = when {
|
||||
states.any { it == WorkInfo.State.ENQUEUED || it == WorkInfo.State.BLOCKED } -> null
|
||||
WorkInfo.State.RUNNING in states -> ExistingWorkPolicy.APPEND_OR_REPLACE
|
||||
else -> ExistingWorkPolicy.REPLACE
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the selected calendars into the configured folder — one dated file
|
||||
* per calendar, or one combined file (#411) — then prunes each series down to
|
||||
* the retention count. Pulls its collaborators through a Hilt
|
||||
* Exports the local calendars to `calendula-backup.ics` in the configured folder,
|
||||
* overwriting the previous file. Pulls its collaborators through a Hilt
|
||||
* [EntryPoint] so it works under WorkManager's default (no-arg) worker factory —
|
||||
* no custom factory / Application wiring needed. Records the outcome for the
|
||||
* settings status line, and notifies after repeated failures.
|
||||
@@ -209,232 +107,27 @@ class BackupWorker(
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java)
|
||||
val changeRun = inputData.getBoolean(BackupScheduler.KEY_CHANGE_RUN, false)
|
||||
if (!changeRun) return backUp(deps, deps.settingsPrefs(), changeRun = false)
|
||||
// A failed change run would fail the one queued behind it too.
|
||||
try {
|
||||
backUp(deps, deps.settingsPrefs(), changeRun = true)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
val prefs = deps.settingsPrefs()
|
||||
// Respect the toggle even for already-queued work: if backup was turned
|
||||
// off, no-op (and don't retry) so a lingering run can't revive itself.
|
||||
if (!prefs.autoBackupEnabled.first()) return Result.success()
|
||||
val folder = prefs.autoBackupFolderUri.first()
|
||||
?: return Result.failure() // nothing to write to — leave scheduling to settings
|
||||
val now = System.currentTimeMillis()
|
||||
return try {
|
||||
val events = deps.repository().exportEvents()
|
||||
val content = IcsWriter().writeCalendar(events, Clock.System.now())
|
||||
deps.exporter().writeToFolder(folder.toUri(), BACKUP_FILE_NAME, content)
|
||||
prefs.recordAutoBackupRun(success = true, atMillis = now)
|
||||
Result.success()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Backup after a change failed", e)
|
||||
}
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
/**
|
||||
* One run under the shared lock, recorded for the status line. A change
|
||||
* run (#516) refreshes only the stable copies and never retries. The
|
||||
* failure notification comes once per failure streak, when it reaches
|
||||
* [FAILURE_NOTIFY_THRESHOLD], and goes with the next success of any run.
|
||||
*/
|
||||
private suspend fun backUp(deps: Deps, prefs: SettingsPrefs, changeRun: Boolean): Result {
|
||||
// One run at a time, or each would overwrite the other's ledger.
|
||||
val outcome = runLock.withLock {
|
||||
val now = System.currentTimeMillis()
|
||||
// Respect the toggles even for already-queued work, so a lingering
|
||||
// run can't revive itself.
|
||||
if (!prefs.autoBackupEnabled.first()) return Result.success()
|
||||
if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success()
|
||||
val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure()
|
||||
val outcome = try {
|
||||
runBackup(deps, prefs, folder.toUri(), latestOnly = changeRun)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Automatic backup failed", e)
|
||||
RunOutcome.Failed
|
||||
prefs.recordAutoBackupRun(success = false, atMillis = now)
|
||||
if (prefs.autoBackupStatus.first().consecutiveFailures >= FAILURE_NOTIFY_THRESHOLD) {
|
||||
notifyFailure(applicationContext)
|
||||
}
|
||||
if (outcome != RunOutcome.NothingToDo) {
|
||||
withContext(NonCancellable) {
|
||||
prefs.recordAutoBackupRun(success = outcome == RunOutcome.Written, atMillis = now)
|
||||
when {
|
||||
outcome == RunOutcome.Written -> clearFailureNotification(applicationContext)
|
||||
prefs.autoBackupStatus.first().consecutiveFailures == FAILURE_NOTIFY_THRESHOLD ->
|
||||
notifyFailure(applicationContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
outcome
|
||||
Log.w(TAG, "Automatic backup failed", e)
|
||||
Result.retry()
|
||||
}
|
||||
// Only a run that wrote nothing retries: a retry rewrites every series.
|
||||
return if (outcome == RunOutcome.Failed && !changeRun) Result.retry() else Result.success()
|
||||
}
|
||||
|
||||
private enum class RunOutcome { Written, PartlyFailed, Failed, NothingToDo }
|
||||
|
||||
/** 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 }
|
||||
|
||||
/**
|
||||
* 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
|
||||
* schedule and rewrites only the stable copies whose calendars changed.
|
||||
*/
|
||||
private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri, latestOnly: Boolean): RunOutcome {
|
||||
val repository = deps.repository()
|
||||
val exporter = deps.exporter()
|
||||
if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed
|
||||
val all = repository.calendars().first()
|
||||
val selection = prefs.autoBackupSelection.first()
|
||||
val combined = prefs.autoBackupCombined.first()
|
||||
if (all.none(selection::selects)) return RunOutcome.NothingToDo
|
||||
prefs.adoptLegacyBackupFile()
|
||||
val listing = exporter.listFolder(folder)
|
||||
val ledger = prefs.autoBackupLedger.first()
|
||||
// A listing still loading can't tell a gone file from a late one.
|
||||
val existing = if (listing.complete) listing.files.keys else listing.files.keys + ledger.values.flatten()
|
||||
val targets = backupTargets(all.filter(selection::selects), combined, ledger, existing)
|
||||
if (targets.isEmpty()) return RunOutcome.NothingToDo
|
||||
val stamp = Clock.System.now()
|
||||
val fingerprints = prefs.autoBackupFingerprints.first()
|
||||
suspend fun export(target: BackupTarget): String? = try {
|
||||
val events = repository.exportEvents(target.calendarIds).inBackupOrder()
|
||||
IcsWriter().writeCalendar(events, stamp, target.calendarName)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Reading one series failed", e)
|
||||
null
|
||||
}
|
||||
fun fingerprintOf(target: BackupTarget, text: String) =
|
||||
backupFingerprint(text, latestFileName(target.baseName))
|
||||
// Hashes only serve change runs; without them a stale one could pass later.
|
||||
val trackHashes = prefs.autoBackupOnChange.first()
|
||||
if (!trackHashes && fingerprints.isNotEmpty()) prefs.updateAutoBackupFingerprints(folder.toString()) { emptyMap() }
|
||||
// A change run hashes first (null: unreadable) and leaves the folder alone when nothing moved.
|
||||
val preHashes: Map<String, String?> = if (latestOnly) {
|
||||
targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } }
|
||||
} else {
|
||||
emptyMap()
|
||||
}
|
||||
if (latestOnly && targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } }) {
|
||||
return RunOutcome.NothingToDo
|
||||
}
|
||||
val plans = planBackupFiles(
|
||||
targets = targets,
|
||||
ledger = ledger,
|
||||
existing = existing,
|
||||
at = LocalDateTime.now(),
|
||||
keep = prefs.autoBackupKeep.first(),
|
||||
)
|
||||
val liveKeys = all.map { it.id.toString() }.toSet()
|
||||
suspend fun record(key: String, files: List<String>) =
|
||||
prefs.updateAutoBackupLedger(folder.toString()) { withLedgerEntry(it, key, files, liveKeys) }
|
||||
|
||||
suspend fun writeDated(plan: BackupFilePlan, bytes: ByteArray): Boolean = try {
|
||||
val name = exporter.writeToFolder(folder, listing, plan.fileName, bytes)
|
||||
record(plan.target.key, plan.prune + plan.keep + name)
|
||||
val undeleted = exporter.deleteFromFolder(listing, plan.prune)
|
||||
record(plan.target.key, plan.prune.filter { it in undeleted } + plan.keep + name)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Backup of one series failed", e)
|
||||
false
|
||||
}
|
||||
|
||||
// An old copy goes only once the new one has landed.
|
||||
suspend fun writeLatest(plan: BackupFilePlan, bytes: ByteArray, fingerprint: String): LatestWrite {
|
||||
val target = plan.target
|
||||
val latest = checkNotNull(plan.latestName)
|
||||
var landed: String? = null
|
||||
try {
|
||||
val latestKey = latestLedgerKey(target.key)
|
||||
if (trackHashes && target.key in fingerprints) {
|
||||
prefs.updateAutoBackupFingerprints(folder.toString()) { it - target.key }
|
||||
}
|
||||
landed = exporter.writeToFolder(folder, listing, latest, bytes)
|
||||
// A provider that renamed it leaves a copy to clean up next
|
||||
// run; the intended name stays ours only if it already was.
|
||||
val ownsLatest = landed == latest || latest in ledger[latestKey].orEmpty()
|
||||
val current = listOfNotNull(landed, latest.takeIf { ownsLatest })
|
||||
// A hand-off stays on record only until its new owner claimed it.
|
||||
suspend fun recordLatest(stale: List<String>, landedFingerprint: String? = null) =
|
||||
prefs.updateAutoBackupLedger(
|
||||
folder.toString(),
|
||||
fingerprints = landedFingerprint?.let { hash ->
|
||||
{ old -> withFingerprint(old, target.key, hash, liveKeys) }
|
||||
},
|
||||
) {
|
||||
val pending = plan.handOff - it.latestHeldElsewhere(target.key)
|
||||
withLedgerEntry(it, latestKey, stale + pending + current, liveKeys)
|
||||
}
|
||||
recordLatest(plan.staleLatest, fingerprint.takeIf { trackHashes })
|
||||
val staleLeft = exporter.deleteFromFolder(listing, plan.staleLatest)
|
||||
recordLatest(plan.staleLatest.filter { it in staleLeft })
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Stable copy of one series failed", e)
|
||||
}
|
||||
return when (landed) {
|
||||
null -> LatestWrite.Failed
|
||||
latest -> LatestWrite.Landed
|
||||
else -> LatestWrite.Renamed
|
||||
}
|
||||
}
|
||||
|
||||
// A copy blocked by a file of the user's keeps its hash, so a later change run can stop early.
|
||||
suspend fun rememberBlocked(plan: BackupFilePlan, hash: String) {
|
||||
val key = plan.target.key
|
||||
if (plan.latestName == null && trackHashes && fingerprints[key] != hash) {
|
||||
prefs.updateAutoBackupFingerprints(folder.toString()) { withFingerprint(it, key, hash, liveKeys) }
|
||||
}
|
||||
}
|
||||
|
||||
var written = 0
|
||||
var failed = 0
|
||||
val landedLatest = mutableSetOf<String>()
|
||||
for (plan in plans) {
|
||||
val target = plan.target
|
||||
if (latestOnly) {
|
||||
val hash = preHashes[target.key] ?: run {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
rememberBlocked(plan, hash)
|
||||
if (!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.
|
||||
val text = export(target) ?: run {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
val fingerprint = fingerprintOf(target, text)
|
||||
if (!latestOnly) rememberBlocked(plan, fingerprint)
|
||||
val bytes = text.toByteArray(Charsets.UTF_8)
|
||||
// Not cancellable once a file exists: it must reach the ledger.
|
||||
withContext(NonCancellable) {
|
||||
val dated = if (latestOnly) null else writeDated(plan, bytes)
|
||||
val latest = plan.latestName?.let { writeLatest(plan, bytes, fingerprint) }
|
||||
if (latest == LatestWrite.Landed) landedLatest += target.key
|
||||
// A full run's status follows its dated file; the stable copy is best-effort there.
|
||||
val ok = dated ?: (latest != LatestWrite.Failed)
|
||||
if (ok) written++ else failed++
|
||||
}
|
||||
}
|
||||
// A layout switch retires the other layout's copies once every new one is there.
|
||||
if (landedLatest.size == plans.size) {
|
||||
replacedLatestCopies(targets, prefs.autoBackupLedger.first(), existing).forEach { (key, names) ->
|
||||
withContext(NonCancellable) {
|
||||
val left = exporter.deleteFromFolder(listing, names)
|
||||
record(latestLedgerKey(key), names.filter { it in left })
|
||||
// Its copy is gone, so its hash mustn't let a change run stop early.
|
||||
prefs.updateAutoBackupFingerprints(folder.toString()) { it - key }
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
failed == 0 && written == 0 -> RunOutcome.NothingToDo
|
||||
failed == 0 -> RunOutcome.Written
|
||||
written == 0 -> RunOutcome.Failed
|
||||
else -> RunOutcome.PartlyFailed
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearFailureNotification(context: Context) {
|
||||
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
|
||||
}
|
||||
|
||||
private fun notifyFailure(context: Context) {
|
||||
@@ -472,10 +165,10 @@ class BackupWorker(
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val BACKUP_FILE_NAME = "calendula-backup.ics"
|
||||
private const val FAILURE_NOTIFY_THRESHOLD = 2
|
||||
private const val CHANNEL_ID = "backup"
|
||||
private const val NOTIFICATION_ID = 2
|
||||
private const val TAG = "BackupWorker"
|
||||
private val runLock = Mutex()
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobScheduler
|
||||
import android.app.job.JobService
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.provider.CalendarContract
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* The watch behind "Also back up after changes" (#516): a JobScheduler job
|
||||
* with a content trigger on the provider's root URI, where it reports every
|
||||
* change, whoever made it (this app, a sync adapter or another app). It waits
|
||||
* for [SETTLE_MINUTES] of quiet, at most [MAX_WAIT_MINUTES], so a burst makes
|
||||
* one run. A trigger fires once; each firing queues a change run and schedules
|
||||
* the next watch under the same id before finishing, which hands over the
|
||||
* changes seen meanwhile, so exactly one watch exists and none are lost.
|
||||
*/
|
||||
class BackupChangeJob : JobService() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
override fun onStartJob(params: JobParameters): Boolean {
|
||||
scope.launch {
|
||||
// Retried when it failed early, so the watch isn't lost; once re-armed, the retry is moot.
|
||||
val failed = try {
|
||||
val deps = EntryPointAccessors.fromApplication(applicationContext, BackupWorker.Deps::class.java)
|
||||
BackupScheduler.changed(applicationContext, deps.settingsPrefs())
|
||||
false
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Queueing a backup after a change failed", e)
|
||||
true
|
||||
}
|
||||
jobFinished(params, failed)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Stopped before it could re-arm: run again rather than leave the provider unwatched. */
|
||||
override fun onStopJob(params: JobParameters): Boolean = true
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Above the range WorkManager is given (see CalendulaApp). */
|
||||
const val JOB_ID = 0x0516_0001
|
||||
private const val SETTLE_MINUTES = 2L
|
||||
private const val MAX_WAIT_MINUTES = 15L
|
||||
private const val TAG = "BackupChangeJob"
|
||||
|
||||
fun schedule(context: Context) {
|
||||
val job = JobInfo.Builder(JOB_ID, ComponentName(context, BackupChangeJob::class.java))
|
||||
.addTriggerContentUri(
|
||||
JobInfo.TriggerContentUri(
|
||||
CalendarContract.CONTENT_URI,
|
||||
JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS,
|
||||
),
|
||||
)
|
||||
.setTriggerContentUpdateDelay(TimeUnit.MINUTES.toMillis(SETTLE_MINUTES))
|
||||
.setTriggerContentMaxDelay(TimeUnit.MINUTES.toMillis(MAX_WAIT_MINUTES))
|
||||
.build()
|
||||
if (context.getSystemService(JobScheduler::class.java).schedule(job) != JobScheduler.RESULT_SUCCESS) {
|
||||
Log.w(TAG, "The change watch could not be scheduled")
|
||||
}
|
||||
}
|
||||
|
||||
fun isPending(context: Context): Boolean =
|
||||
context.getSystemService(JobScheduler::class.java).getPendingJob(JOB_ID) != null
|
||||
|
||||
fun cancel(context: Context) = context.getSystemService(JobScheduler::class.java).cancel(JOB_ID)
|
||||
}
|
||||
}
|
||||
@@ -1,265 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.data.appname.LauncherName
|
||||
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.floret.backup.BackupDocument
|
||||
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||
import de.jeanlucmakiola.floret.backup.PrefsSection
|
||||
import de.jeanlucmakiola.floret.backup.invalidBackup
|
||||
import de.jeanlucmakiola.floret.backup.optBoolean
|
||||
import de.jeanlucmakiola.floret.backup.optIntList
|
||||
import de.jeanlucmakiola.floret.backup.optObject
|
||||
import de.jeanlucmakiola.floret.backup.optObjectList
|
||||
import de.jeanlucmakiola.floret.backup.optInt
|
||||
import de.jeanlucmakiola.floret.backup.optString
|
||||
import de.jeanlucmakiola.floret.backup.optStringList
|
||||
import de.jeanlucmakiola.floret.backup.readBackup
|
||||
import de.jeanlucmakiola.floret.backup.requireString
|
||||
import de.jeanlucmakiola.floret.prefs.Pref
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
|
||||
/**
|
||||
* A calendar as another device can find it again: provider ids are per
|
||||
* device, so a calendar is named by its account and display name, and a
|
||||
* special-dates mirror by the date type it mirrors.
|
||||
*/
|
||||
data class CalendarIdentity(
|
||||
val accountName: String,
|
||||
val accountType: String,
|
||||
val displayName: String,
|
||||
val specialDates: SpecialDateType? = null,
|
||||
)
|
||||
|
||||
/** The per-calendar settings of one calendar; null fields inherit the global default. */
|
||||
data class CalendarSettings(
|
||||
val calendar: CalendarIdentity,
|
||||
val hidden: Boolean = false,
|
||||
val lastUsed: Boolean = false,
|
||||
val eventDurationMinutes: Int? = null,
|
||||
/** Timed reminder override; an empty list is "no reminder". */
|
||||
val reminders: List<Int>? = null,
|
||||
val allDayReminders: List<Int>? = null,
|
||||
/** The views it is hidden in only (#270). */
|
||||
val hiddenInViews: Set<CalendarView> = emptySet(),
|
||||
/** False when Calendula posts none of its reminders (#272). */
|
||||
val notifications: Boolean = true,
|
||||
/** Its alert style (#171); null is a plain notification. */
|
||||
val alertStyle: ReminderAlertStyle? = null,
|
||||
/** Its set-time reminder override (#459). */
|
||||
val fixedTimeReminder: FixedTimeOverride = FixedTimeOverride.Inherit,
|
||||
/** False when the daily summary leaves it out (#459). */
|
||||
val inDailyDigest: Boolean = true,
|
||||
/** The automatic backup's choice for it (#147); null follows the default for its kind. */
|
||||
val autoBackup: Boolean? = null,
|
||||
)
|
||||
|
||||
/** The app language a file carries; [tag] null follows the system. */
|
||||
data class LanguageChoice(val tag: String?)
|
||||
|
||||
/** Everything a settings backup holds. Null [language]/[launcherName]: the file didn't say. */
|
||||
data class SettingsBackup(
|
||||
val prefs: Map<Pref<*>, Any>,
|
||||
val calendars: List<CalendarSettings>,
|
||||
val language: LanguageChoice? = null,
|
||||
val launcherName: LauncherName? = null,
|
||||
)
|
||||
|
||||
internal val plainSection = PrefsSection(SettingsBackupSchema.plain)
|
||||
|
||||
/**
|
||||
* The backup of [snapshot]. Per-calendar entries are named through
|
||||
* [calendars] and [managed]; an id neither knows (a deleted calendar's
|
||||
* leftover) is dropped.
|
||||
*/
|
||||
fun buildSettingsBackup(
|
||||
snapshot: Preferences,
|
||||
calendars: List<CalendarSource>,
|
||||
managed: List<ManagedCalendarRow>,
|
||||
language: LanguageChoice?,
|
||||
launcherName: LauncherName?,
|
||||
): SettingsBackup {
|
||||
val hidden = snapshot[CalendarPrefKeys.hiddenCalendarIds]
|
||||
val lastUsed = snapshot[CalendarPrefKeys.lastUsedCalendarId]
|
||||
val durations = snapshot[SettingsKeys.perCalendarEventDuration]
|
||||
val reminders = snapshot[SettingsKeys.perCalendarReminderOverride]
|
||||
val allDay = snapshot[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||
val hiddenViews = snapshot[SettingsKeys.perCalendarHiddenViews]
|
||||
val muted = snapshot[SettingsKeys.mutedReminderCalendarIds]
|
||||
val alertStyles = snapshot[SettingsKeys.reminderAlertStyles]
|
||||
val fixedTime = snapshot[SettingsKeys.perCalendarFixedTimeReminderOverride]
|
||||
val notInDigest = snapshot[SettingsKeys.digestExcludedCalendarIds]
|
||||
val backupIncluded = snapshot[SettingsKeys.autoBackupIncluded]
|
||||
val backupExcluded = snapshot[SettingsKeys.autoBackupExcluded]
|
||||
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys +
|
||||
hiddenViews.keys + muted + alertStyles.keys + fixedTime.keys + notInDigest + backupIncluded + backupExcluded
|
||||
val byId = calendars.associateBy { it.id }
|
||||
val managedType = managed.associate { it.id to it.type }
|
||||
val entries = ids.sorted().mapNotNull { id ->
|
||||
val calendar = byId[id] ?: return@mapNotNull null
|
||||
CalendarSettings(
|
||||
calendar = CalendarIdentity(
|
||||
accountName = calendar.accountName,
|
||||
accountType = calendar.accountType,
|
||||
displayName = calendar.displayName,
|
||||
specialDates = managedType[id],
|
||||
),
|
||||
hidden = id in hidden,
|
||||
lastUsed = id == lastUsed,
|
||||
eventDurationMinutes = durations[id],
|
||||
reminders = reminders[id],
|
||||
allDayReminders = allDay[id],
|
||||
hiddenInViews = hiddenViews[id].orEmpty(),
|
||||
notifications = id !in muted,
|
||||
alertStyle = alertStyles[id]?.takeUnless { it == ReminderAlertStyle.Notification },
|
||||
fixedTimeReminder = fixedTime.fixedTimeOverrideFor(id),
|
||||
inDailyDigest = id !in notInDigest,
|
||||
autoBackup = when (id) {
|
||||
in backupIncluded -> true
|
||||
in backupExcluded -> false
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
return SettingsBackup(
|
||||
prefs = plainSection.snapshot(snapshot),
|
||||
calendars = entries,
|
||||
language = language,
|
||||
launcherName = launcherName,
|
||||
)
|
||||
}
|
||||
|
||||
fun encodeSettingsBackup(backup: SettingsBackup, exportedAtMillis: Long, appVersion: String?): String {
|
||||
val body = buildJsonObject {
|
||||
put(KEY_SETTINGS, plainSection.encode(backup.prefs))
|
||||
put(KEY_CALENDARS, JsonArray(backup.calendars.map { it.toJson() }))
|
||||
put(
|
||||
KEY_APP,
|
||||
buildJsonObject {
|
||||
backup.language?.let { put(KEY_LANGUAGE, it.tag?.let(::JsonPrimitive) ?: JsonNull) }
|
||||
backup.launcherName?.let { put(KEY_LAUNCHER_NAME, JsonPrimitive(it.name)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
val document = BackupDocument(
|
||||
version = SettingsBackupSchema.format.version,
|
||||
exportedAtMillis = exportedAtMillis,
|
||||
appVersion = appVersion,
|
||||
body = body,
|
||||
)
|
||||
return SettingsBackupSchema.format.encode(document)
|
||||
}
|
||||
|
||||
/** Validates the whole file before anything is applied; see docs/SETTINGS_BACKUP.md. */
|
||||
fun decodeSettingsBackup(text: String): BackupResult<SettingsBackup> {
|
||||
val document = when (val decoded = SettingsBackupSchema.format.decode(text)) {
|
||||
is BackupResult.Failure -> return decoded
|
||||
is BackupResult.Success -> decoded.value
|
||||
}
|
||||
return readBackup {
|
||||
val body = document.body
|
||||
val app = body.optObject(KEY_APP)
|
||||
SettingsBackup(
|
||||
prefs = plainSection.read(body.optObject(KEY_SETTINGS) ?: invalidBackup("$KEY_SETTINGS: missing")),
|
||||
calendars = body.optObjectList(KEY_CALENDARS).orEmpty().map { it.toCalendarSettings() },
|
||||
language = app?.takeIf { KEY_LANGUAGE in it }?.let { LanguageChoice(it.optString(KEY_LANGUAGE)) },
|
||||
launcherName = app?.optString(KEY_LAUNCHER_NAME)
|
||||
?.let { name -> LauncherName.entries.firstOrNull { it.name == name } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun CalendarSettings.toJson(): JsonObject = buildJsonObject {
|
||||
put(KEY_ACCOUNT_NAME, JsonPrimitive(calendar.accountName))
|
||||
put(KEY_ACCOUNT_TYPE, JsonPrimitive(calendar.accountType))
|
||||
put(KEY_DISPLAY_NAME, JsonPrimitive(calendar.displayName))
|
||||
calendar.specialDates?.let { put(KEY_SPECIAL_DATES, JsonPrimitive(it.name)) }
|
||||
if (hidden) put(KEY_HIDDEN, JsonPrimitive(true))
|
||||
if (lastUsed) put(KEY_LAST_USED, JsonPrimitive(true))
|
||||
eventDurationMinutes?.let { put(KEY_EVENT_DURATION, JsonPrimitive(it)) }
|
||||
reminders?.let { put(KEY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
|
||||
allDayReminders?.let { put(KEY_ALL_DAY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
|
||||
if (hiddenInViews.isNotEmpty()) {
|
||||
put(KEY_HIDDEN_IN_VIEWS, JsonArray(hiddenInViews.sortedBy { it.ordinal }.map { JsonPrimitive(it.name) }))
|
||||
}
|
||||
if (!notifications) put(KEY_NOTIFICATIONS, JsonPrimitive(false))
|
||||
alertStyle?.let { put(KEY_ALERT_STYLE, JsonPrimitive(it.storageValue)) }
|
||||
when (val fixed = fixedTimeReminder) {
|
||||
FixedTimeOverride.Inherit -> Unit
|
||||
FixedTimeOverride.Off -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(FIXED_TIME_OFF))
|
||||
is FixedTimeOverride.At -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(fixed.reminder.toToken()))
|
||||
}
|
||||
if (!inDailyDigest) put(KEY_IN_DAILY_DIGEST, JsonPrimitive(false))
|
||||
autoBackup?.let { put(KEY_AUTO_BACKUP, JsonPrimitive(it)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict about what it reads. A special-dates type this build doesn't know
|
||||
* reads as an ordinary calendar, which then simply finds no match.
|
||||
*/
|
||||
private fun JsonObject.toCalendarSettings(): CalendarSettings {
|
||||
return CalendarSettings(
|
||||
calendar = CalendarIdentity(
|
||||
accountName = requireString(KEY_ACCOUNT_NAME),
|
||||
accountType = requireString(KEY_ACCOUNT_TYPE),
|
||||
displayName = requireString(KEY_DISPLAY_NAME),
|
||||
specialDates = optString(KEY_SPECIAL_DATES)?.let { name -> SpecialDateType.entries.firstOrNull { it.name == name } },
|
||||
),
|
||||
hidden = optBoolean(KEY_HIDDEN) ?: false,
|
||||
lastUsed = optBoolean(KEY_LAST_USED) ?: false,
|
||||
eventDurationMinutes = optInt(KEY_EVENT_DURATION),
|
||||
reminders = optIntList(KEY_REMINDERS)?.cleanReminders(),
|
||||
allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS)?.cleanReminders(),
|
||||
hiddenInViews = optStringList(KEY_HIDDEN_IN_VIEWS).orEmpty()
|
||||
.mapNotNullTo(mutableSetOf()) { name -> CalendarView.entries.firstOrNull { it.name == name } },
|
||||
notifications = optBoolean(KEY_NOTIFICATIONS) ?: true,
|
||||
alertStyle = optString(KEY_ALERT_STYLE)?.let(ReminderAlertStyle::fromStorage)
|
||||
?.takeUnless { it == ReminderAlertStyle.Notification },
|
||||
fixedTimeReminder = when (val token = optString(KEY_FIXED_TIME_REMINDER)) {
|
||||
null -> FixedTimeOverride.Inherit
|
||||
FIXED_TIME_OFF -> FixedTimeOverride.Off
|
||||
else -> FixedTimeReminder.parse(token)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Inherit
|
||||
},
|
||||
inDailyDigest = optBoolean(KEY_IN_DAILY_DIGEST) ?: true,
|
||||
autoBackup = optBoolean(KEY_AUTO_BACKUP),
|
||||
)
|
||||
}
|
||||
|
||||
/** As the reminder setters store them: no negative leads, each once, ascending. */
|
||||
private fun List<Int>.cleanReminders(): List<Int> = filter { it >= 0 }.distinct().sorted()
|
||||
|
||||
private const val KEY_SETTINGS = "settings"
|
||||
private const val KEY_CALENDARS = "calendars"
|
||||
private const val KEY_APP = "app"
|
||||
private const val KEY_LANGUAGE = "language"
|
||||
private const val KEY_LAUNCHER_NAME = "launcher_name"
|
||||
private const val KEY_ACCOUNT_NAME = "account_name"
|
||||
private const val KEY_ACCOUNT_TYPE = "account_type"
|
||||
private const val KEY_DISPLAY_NAME = "display_name"
|
||||
private const val KEY_SPECIAL_DATES = "special_dates"
|
||||
private const val KEY_HIDDEN = "hidden"
|
||||
private const val KEY_LAST_USED = "last_used"
|
||||
private const val KEY_EVENT_DURATION = "event_duration_minutes"
|
||||
private const val KEY_REMINDERS = "reminders"
|
||||
private const val KEY_ALL_DAY_REMINDERS = "all_day_reminders"
|
||||
private const val KEY_HIDDEN_IN_VIEWS = "hidden_in_views"
|
||||
private const val KEY_NOTIFICATIONS = "notifications"
|
||||
private const val KEY_ALERT_STYLE = "alert_style"
|
||||
private const val KEY_FIXED_TIME_REMINDER = "fixed_time_reminder"
|
||||
private const val FIXED_TIME_OFF = "off"
|
||||
private const val KEY_IN_DAILY_DIGEST = "in_daily_digest"
|
||||
private const val KEY_AUTO_BACKUP = "auto_backup"
|
||||
@@ -1,233 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.BuildConfig
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.appname.LauncherNameManager
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
|
||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
|
||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncResult
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.widget.requestWidgetRedraw
|
||||
import de.jeanlucmakiola.floret.backup.BackupProblem
|
||||
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import de.jeanlucmakiola.floret.prefs.rawValue
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Exports and imports Calendula's settings (#481). The file format and what
|
||||
* it holds are [SettingsBackupSchema]'s; the import is planned purely by
|
||||
* [planSettingsImport], written in one DataStore edit, and then followed by
|
||||
* the side effects the settings screens would have run themselves.
|
||||
*/
|
||||
@Singleton
|
||||
class SettingsBackupEngine @Inject constructor(
|
||||
private val store: DataStore<Preferences>,
|
||||
private val calendars: CalendarDataSource,
|
||||
private val contacts: ContactSpecialDatesDataSource,
|
||||
private val specialDates: SpecialDatesSyncEngine,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val reminderScanner: ReminderScanner,
|
||||
private val launcherNames: LauncherNameManager,
|
||||
@ApplicationContext private val context: Context,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) {
|
||||
|
||||
suspend fun export(): String = withContext(io) {
|
||||
val supported = supportedLanguages()
|
||||
val snapshot = store.data.first()
|
||||
// Without the list the per-calendar settings would silently drop out of the file.
|
||||
val list = if (snapshot.hasCalendarSettings()) calendars.calendars() else emptyList()
|
||||
val backup = buildSettingsBackup(
|
||||
snapshot = snapshot,
|
||||
calendars = list,
|
||||
managed = if (list.any { it.isManaged }) calendars.findManagedCalendars() else emptyList(),
|
||||
language = LanguageChoice(AppLanguage.currentTag(context, supported)),
|
||||
launcherName = launcherNames.current(),
|
||||
)
|
||||
encodeSettingsBackup(backup, System.currentTimeMillis(), BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
/** Validates [text] in full, then replaces the settings; nothing is written for an invalid file. */
|
||||
suspend fun import(text: String): BackupResult<SettingsImportSummary> = withContext(io) {
|
||||
val backup = when (val decoded = decodeSettingsBackup(text)) {
|
||||
is BackupResult.Failure -> return@withContext decoded
|
||||
is BackupResult.Success -> decoded.value
|
||||
}
|
||||
val current = store.data.first()
|
||||
val supported = supportedLanguages()
|
||||
val environment = environment(current, backup, supported)
|
||||
val plan = planSettingsImport(backup, current, environment)
|
||||
val existingMirrors = environment.managed.map { it.id }.toSet()
|
||||
// Once the write starts, the side effects have to follow it, whoever cancels.
|
||||
withContext(NonCancellable) {
|
||||
try {
|
||||
store.edit { plan.applyTo(it) }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Settings import could not be written", e)
|
||||
return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty())
|
||||
}
|
||||
val lateSkips = afterImport(plan, current, supported, existingMirrors)
|
||||
BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped))
|
||||
}
|
||||
}
|
||||
|
||||
private class LateMatches(val matched: Int, val skipped: List<SkippedSetting>)
|
||||
|
||||
/**
|
||||
* Brings what reads the settings outside DataStore in line: the mirror,
|
||||
* reminder alarms, scheduled backups, the launcher alias and the language.
|
||||
* Each step stands alone, so one failing never undoes the import.
|
||||
*/
|
||||
private suspend fun afterImport(
|
||||
plan: SettingsImportPlan,
|
||||
before: Preferences,
|
||||
supported: List<String>,
|
||||
existingMirrors: Set<Long>,
|
||||
): LateMatches {
|
||||
val after = store.data.first()
|
||||
val wasMirroring = before[SettingsKeys.specialDatesEnabled]
|
||||
val mirroring = after[SettingsKeys.specialDatesEnabled]
|
||||
var late = LateMatches(0, plan.pendingSpecialDates.map { it.calendar.skipped() })
|
||||
step("special dates") {
|
||||
if (mirroring) {
|
||||
SpecialDatesScheduler.apply(context, enabled = true)
|
||||
val result = specialDates.sync()
|
||||
if (result != SpecialDatesSyncResult.Disabled) {
|
||||
val stalled = SpecialDatesStalledReason.PermissionRevoked
|
||||
.takeIf { result == SpecialDatesSyncResult.PermissionMissing }
|
||||
settingsPrefs.recordSpecialDatesRun(System.currentTimeMillis(), stalled)
|
||||
}
|
||||
late = matchSpecialDates(plan, before, existingMirrors, synced = result == SpecialDatesSyncResult.Success)
|
||||
} else if (wasMirroring) {
|
||||
SpecialDatesScheduler.apply(context, enabled = false)
|
||||
specialDates.teardown()
|
||||
}
|
||||
}
|
||||
step("reminders") { reminderScanner.scan() }
|
||||
step("auto backup") { BackupScheduler.reconcile(context, settingsPrefs) }
|
||||
plan.launcherName?.let { name ->
|
||||
step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) }
|
||||
}
|
||||
plan.language?.let { choice ->
|
||||
step("language") {
|
||||
if (AppLanguage.currentTag(context, supported) != choice.tag) {
|
||||
withContext(Dispatchers.Main) { AppLanguage.apply(context, choice.tag) }
|
||||
requestWidgetRedraw(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
return late
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives late-created mirror calendars their entries (only after a
|
||||
* successful [synced] run), then rewrites each mirror whose all-day
|
||||
* reminders differ from what its events carry: the pre-import override for
|
||||
* a calendar that already existed, the sync's seed for a new one. A mirror
|
||||
* the file doesn't override inherits again.
|
||||
*/
|
||||
private suspend fun matchSpecialDates(
|
||||
plan: SettingsImportPlan,
|
||||
before: Preferences,
|
||||
existingMirrors: Set<Long>,
|
||||
synced: Boolean,
|
||||
): LateMatches {
|
||||
val managed = calendars.findManagedCalendars()
|
||||
val skipped = mutableListOf<SkippedSetting>()
|
||||
var matched = 0
|
||||
val resolved = if (!synced) {
|
||||
skipped += plan.pendingSpecialDates.map { it.calendar.skipped() }
|
||||
emptyList()
|
||||
} else {
|
||||
plan.pendingSpecialDates.mapNotNull { entry ->
|
||||
val id = managed.firstOrNull { it.type == entry.calendar.specialDates }?.id
|
||||
if (id == null) skipped += entry.calendar.skipped() else matched++
|
||||
id?.let { it to entry }
|
||||
}
|
||||
}
|
||||
if (resolved.isNotEmpty()) {
|
||||
store.edit { prefs ->
|
||||
resolved.forEach { (id, entry) -> prefs.addCalendarSettings(id, entry.copy(allDayReminders = null)) }
|
||||
}
|
||||
}
|
||||
if (plan.calendars != null) {
|
||||
val wanted = (plan.calendars.values + resolved.map { it.second })
|
||||
.mapNotNull { entry -> entry.calendar.specialDates?.let { it to entry.allDayReminders } }
|
||||
.toMap()
|
||||
val carried = before[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||
val seeded = store.data.first()[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||
managed.distinctBy { it.type }.forEach { (id, type) ->
|
||||
val minutes = wanted[type]
|
||||
val onEvents = if (id in existingMirrors) carried[id] else seeded[id]
|
||||
if (onEvents == minutes) return@forEach
|
||||
val desired = minutes?.let { mapOf(id to it) }.orEmpty()
|
||||
specialDates.applyReminders(type, desired.reminderOverrideFor(id))
|
||||
}
|
||||
}
|
||||
return LateMatches(matched, skipped)
|
||||
}
|
||||
|
||||
/** The highest byte count [import] is worth reading. */
|
||||
val maxImportBytes: Int get() = SettingsBackupSchema.format.maxChars
|
||||
|
||||
private fun environment(
|
||||
current: Preferences,
|
||||
backup: SettingsBackup,
|
||||
supported: List<String>,
|
||||
): ImportEnvironment = ImportEnvironment(
|
||||
// An empty list here is a failed read as far as the import can tell, never "wipe them all".
|
||||
calendars = if (backup.calendars.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
runCatching { calendars.calendars() }.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||
},
|
||||
managed = runCatching { calendars.findManagedCalendars() }.getOrDefault(emptyList()),
|
||||
contactsPermission = contacts.hasPermission(),
|
||||
customFonts = FontRole.entries.filter { CustomFontStore.exists(context, it) }.toSet(),
|
||||
hasBackupFolder = current[SettingsKeys.autoBackupFolderUri] != null,
|
||||
supportedLanguages = supported,
|
||||
)
|
||||
|
||||
private fun Preferences.hasCalendarSettings(): Boolean =
|
||||
SettingsBackupSchema.perCalendar.any { rawValue(it) != null }
|
||||
|
||||
private fun supportedLanguages(): List<String> = AppLanguage.supportedTags(context, R.xml.locales_config)
|
||||
|
||||
private suspend fun step(name: String, block: suspend () -> Unit) {
|
||||
try {
|
||||
block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Settings import: $name could not be refreshed", e)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "SettingsBackup"
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.ReminderStateKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.floret.backup.BackupFormat
|
||||
import de.jeanlucmakiola.floret.prefs.Pref
|
||||
|
||||
/**
|
||||
* Which stored keys a settings backup carries (#481), and how. Every key of
|
||||
* the settings store is in exactly one of the three lists; a test holds that,
|
||||
* so a new setting cannot ship without deciding. See docs/SETTINGS_BACKUP.md.
|
||||
*/
|
||||
internal object SettingsBackupSchema {
|
||||
|
||||
val format = BackupFormat(name = "calendula-settings", version = 1)
|
||||
|
||||
/** Carried as stored and restored over the current value; an absent key restores the default. */
|
||||
val plain: List<Pref<*>> = listOf(
|
||||
SettingsKeys.themeMode,
|
||||
SettingsKeys.dynamicColor,
|
||||
SettingsKeys.weekStart,
|
||||
SettingsKeys.softenCalendarColors,
|
||||
SettingsKeys.brandFont,
|
||||
SettingsKeys.plainFont,
|
||||
SettingsKeys.timeFormat,
|
||||
SettingsKeys.showHourGrid,
|
||||
SettingsKeys.pastEventDisplay,
|
||||
SettingsKeys.dimCompletedEvents,
|
||||
SettingsKeys.showWeekNumbers,
|
||||
SettingsKeys.monthShowStartTimes,
|
||||
SettingsKeys.monthViewStyle,
|
||||
SettingsKeys.timelineScale,
|
||||
SettingsKeys.multiDayCount,
|
||||
SettingsKeys.timelineHoursEnabled,
|
||||
SettingsKeys.timelineHoursStart,
|
||||
SettingsKeys.timelineHoursEnd,
|
||||
SettingsKeys.todayButtonInToolbar,
|
||||
SettingsKeys.dragToReschedule,
|
||||
SettingsKeys.tapOpensEditor,
|
||||
SettingsKeys.agendaScreenRange,
|
||||
SettingsKeys.agendaShowRangeBar,
|
||||
SettingsKeys.agendaShowToday,
|
||||
SettingsKeys.defaultView,
|
||||
SettingsKeys.quickSwitchConfig,
|
||||
SettingsKeys.drawerViewOrder,
|
||||
SettingsKeys.defaultFormFields,
|
||||
SettingsKeys.autofocusEventTitle,
|
||||
// Names its calendar by account and display name, so it finds it again on another device.
|
||||
SettingsKeys.defaultNewEventCalendar,
|
||||
SettingsKeys.defaultEventDurationMinutes,
|
||||
SettingsKeys.remindersEnabled,
|
||||
SettingsKeys.allowColorOnUnsupportedCalendars,
|
||||
SettingsKeys.defaultReminderMinutes,
|
||||
SettingsKeys.defaultAllDayReminderMinutes,
|
||||
SettingsKeys.allDayReminderTimeMinutes,
|
||||
SettingsKeys.snoozeMinutes,
|
||||
SettingsKeys.defaultFixedTimeReminder,
|
||||
SettingsKeys.dailyDigestEnabled,
|
||||
SettingsKeys.dailyDigestTimeMinutes,
|
||||
SettingsKeys.dailyDigestDay,
|
||||
SettingsKeys.autoBackupEnabled,
|
||||
SettingsKeys.autoBackupIntervalMinutes,
|
||||
SettingsKeys.autoBackupCombinedStored,
|
||||
SettingsKeys.autoBackupKeep,
|
||||
SettingsKeys.autoBackupOnChange,
|
||||
SettingsKeys.specialDatesEnabled,
|
||||
SettingsKeys.specialDatesShowYear,
|
||||
) + SettingsKeys.specialDateTypeEnabled.values + SettingsKeys.specialDatesTitleTemplate.values
|
||||
|
||||
/**
|
||||
* Keyed by calendar id on disk, so carried per calendar under a portable
|
||||
* identity instead ([CalendarSettings]) and re-keyed to this device's ids.
|
||||
*/
|
||||
val perCalendar: List<Pref<*>> = listOf(
|
||||
CalendarPrefKeys.hiddenCalendarIds,
|
||||
CalendarPrefKeys.lastUsedCalendarId,
|
||||
SettingsKeys.perCalendarEventDuration,
|
||||
SettingsKeys.perCalendarReminderOverride,
|
||||
SettingsKeys.perCalendarAllDayReminderOverride,
|
||||
SettingsKeys.perCalendarHiddenViews,
|
||||
SettingsKeys.mutedReminderCalendarIds,
|
||||
SettingsKeys.reminderAlertStyles,
|
||||
SettingsKeys.perCalendarFixedTimeReminderOverride,
|
||||
SettingsKeys.digestExcludedCalendarIds,
|
||||
SettingsKeys.autoBackupIncluded,
|
||||
SettingsKeys.autoBackupExcluded,
|
||||
)
|
||||
|
||||
/** Never exported: this install's own state, bookkeeping, or meaningless on another device. */
|
||||
val excluded: List<Pref<*>> = (
|
||||
listOf(
|
||||
// Cache-busting counters for the locally imported font file.
|
||||
SettingsKeys.brandFontStamp,
|
||||
SettingsKeys.plainFontStamp,
|
||||
// Legacy defaults for unconfigured widgets; widget configuration stays out.
|
||||
SettingsKeys.agendaWidgetRange,
|
||||
SettingsKeys.widgetSize,
|
||||
// Usage history, not a setting.
|
||||
SettingsKeys.recentTimeZones,
|
||||
SettingsKeys.recentFixedTimeReminders,
|
||||
// A dismissed hint of this install.
|
||||
SettingsKeys.notificationCategoryHintDismissed,
|
||||
// This device's notification channels.
|
||||
SettingsKeys.reminderChannelVersions,
|
||||
// Sync-request grants of this device's accounts.
|
||||
CalendarPrefKeys.syncAccessDismissed,
|
||||
// First-run wizard progress of this install.
|
||||
SettingsKeys.onboardingWizardArmed,
|
||||
CalendarPrefKeys.visibilityNoticePending,
|
||||
// A SAF grant, which does not survive a reinstall or another device.
|
||||
SettingsKeys.autoBackupFolderUri,
|
||||
// Run status.
|
||||
SettingsKeys.autoBackupLastRun,
|
||||
SettingsKeys.autoBackupLastSuccess,
|
||||
SettingsKeys.autoBackupFailures,
|
||||
SettingsKeys.specialDatesLastRun,
|
||||
SettingsKeys.specialDatesStalled,
|
||||
SettingsKeys.specialDatesLastForegroundSync,
|
||||
SettingsKeys.dailyDigestArmedAt,
|
||||
ReminderStateKeys.lastDigestDay,
|
||||
// What the automatic backup wrote to this install's folder.
|
||||
SettingsKeys.autoBackupLedger,
|
||||
SettingsKeys.autoBackupFingerprints,
|
||||
// Switch-offs still owed to the provider on this device.
|
||||
CalendarPrefKeys.pendingDisabledCalendarIds,
|
||||
// The reminder delivery watermark.
|
||||
ReminderStateKeys.lastScanMillis,
|
||||
) +
|
||||
SettingsKeys.onboardingDone.values +
|
||||
// The mirror re-adopts its calendars by their provider marker.
|
||||
SettingsKeys.specialDatesCalendarId.values
|
||||
).distinct()
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.data.appname.LauncherName
|
||||
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||
import de.jeanlucmakiola.floret.prefs.Pref
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import de.jeanlucmakiola.floret.prefs.rawValue
|
||||
import de.jeanlucmakiola.floret.prefs.set
|
||||
import de.jeanlucmakiola.floret.prefs.setRawValue
|
||||
|
||||
/** What this device can take of a backup, read before planning. */
|
||||
data class ImportEnvironment(
|
||||
/** Null when the calendar list can't be read: the per-calendar settings are then left alone. */
|
||||
val calendars: List<CalendarSource>?,
|
||||
val managed: List<ManagedCalendarRow>,
|
||||
val contactsPermission: Boolean,
|
||||
val customFonts: Set<FontRole>,
|
||||
val hasBackupFolder: Boolean,
|
||||
val supportedLanguages: List<String>,
|
||||
)
|
||||
|
||||
/** Something in the file this device could not take, for the import summary. */
|
||||
sealed interface SkippedSetting {
|
||||
/** No calendar on this device matches the file's, or [ambiguous]ly more than one does. */
|
||||
data class Calendar(
|
||||
val displayName: String,
|
||||
val accountName: String,
|
||||
val ambiguous: Boolean = false,
|
||||
) : SkippedSetting
|
||||
|
||||
/** The calendars couldn't be read, so the per-calendar settings were left as they are. */
|
||||
data object CalendarsUnavailable : SkippedSetting
|
||||
|
||||
/** A custom font: the font file itself is not part of the backup. */
|
||||
data class CustomFont(val role: FontRole) : SkippedSetting
|
||||
|
||||
/** Contact special dates were on, but this device hasn't granted the contacts permission. */
|
||||
data object SpecialDates : SkippedSetting
|
||||
|
||||
/** Automatic backup was on, but its folder has to be chosen again here. */
|
||||
data object AutoBackupFolder : SkippedSetting
|
||||
|
||||
/** The file's app language isn't one this build ships. */
|
||||
data class Language(val tag: String) : SkippedSetting
|
||||
}
|
||||
|
||||
data class SettingsImportSummary(
|
||||
val calendarsMatched: Int,
|
||||
val skipped: List<SkippedSetting>,
|
||||
)
|
||||
|
||||
/**
|
||||
* A validated backup laid onto this device: the stored values to write in one
|
||||
* edit, the side effects the engine runs after it, and the summary.
|
||||
* [calendars] null leaves the per-calendar keys untouched.
|
||||
* [pendingSpecialDates] are mirror calendars that don't exist yet; the engine
|
||||
* matches them once the mirror's sync has created them.
|
||||
*/
|
||||
data class SettingsImportPlan(
|
||||
val prefs: Map<Pref<*>, Any?>,
|
||||
val calendars: Map<Long, CalendarSettings>?,
|
||||
val pendingSpecialDates: List<CalendarSettings>,
|
||||
val language: LanguageChoice?,
|
||||
val launcherName: LauncherName?,
|
||||
val skipped: List<SkippedSetting>,
|
||||
)
|
||||
|
||||
/** Plans an import that replaces every backed-up setting; see docs/SETTINGS_BACKUP.md. */
|
||||
fun planSettingsImport(
|
||||
backup: SettingsBackup,
|
||||
current: Preferences,
|
||||
environment: ImportEnvironment,
|
||||
): SettingsImportPlan {
|
||||
val skipped = mutableListOf<SkippedSetting>()
|
||||
val prefs = backup.prefs.toMutableMap<Pref<*>, Any?>()
|
||||
|
||||
fun keepCurrent(pref: Pref<*>) {
|
||||
prefs[pref] = current.rawValue(pref)
|
||||
}
|
||||
|
||||
FontRole.entries.forEach { role ->
|
||||
val pref = role.fontPref()
|
||||
if (prefs[pref] == FONT_CUSTOM_TOKEN && role !in environment.customFonts) {
|
||||
keepCurrent(pref)
|
||||
skipped += SkippedSetting.CustomFont(role)
|
||||
}
|
||||
}
|
||||
if (prefs[SettingsKeys.specialDatesEnabled] == true && !environment.contactsPermission) {
|
||||
keepCurrent(SettingsKeys.specialDatesEnabled)
|
||||
skipped += SkippedSetting.SpecialDates
|
||||
}
|
||||
if (prefs[SettingsKeys.autoBackupEnabled] == true && !environment.hasBackupFolder) {
|
||||
keepCurrent(SettingsKeys.autoBackupEnabled)
|
||||
skipped += SkippedSetting.AutoBackupFolder
|
||||
}
|
||||
|
||||
val language = backup.language?.let { choice ->
|
||||
val tag = choice.tag ?: return@let choice
|
||||
val resolved = AppLanguage.resolveTag(tag, environment.supportedLanguages)
|
||||
if (resolved in environment.supportedLanguages) {
|
||||
LanguageChoice(resolved)
|
||||
} else {
|
||||
skipped += SkippedSetting.Language(tag)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// The mirror's calendars are torn down when the imported settings leave it off.
|
||||
val mirroring = prefs[SettingsKeys.specialDatesEnabled] == true
|
||||
val available = environment.calendars
|
||||
val calendars = linkedMapOf<Long, CalendarSettings>()
|
||||
val pending = mutableListOf<CalendarSettings>()
|
||||
if (available == null) {
|
||||
if (backup.calendars.isNotEmpty()) skipped += SkippedSetting.CalendarsUnavailable
|
||||
} else {
|
||||
val repeated = backup.calendars.groupingBy { it.calendar }.eachCount().filterValues { it > 1 }.keys
|
||||
backup.calendars.forEach { entry ->
|
||||
val type = entry.calendar.specialDates
|
||||
if (type != null) {
|
||||
// The mirror only keeps calendars for the types the imported settings switch on.
|
||||
val typeOn = prefs[SettingsKeys.specialDateTypeEnabled.getValue(type)] != false
|
||||
if (!mirroring || !typeOn) return@forEach
|
||||
val id = environment.managed.firstOrNull { it.type == type }?.id
|
||||
if (id != null) calendars[id] = entry else pending += entry
|
||||
return@forEach
|
||||
}
|
||||
if (entry.calendar in repeated) {
|
||||
// Two calendars on the exporting phone that this one can't tell apart.
|
||||
val reported = SkippedSetting.Calendar(entry.calendar.displayName, entry.calendar.accountName, ambiguous = true)
|
||||
if (reported !in skipped) skipped += reported
|
||||
return@forEach
|
||||
}
|
||||
val candidates = available.filter { !it.isManaged && it.matches(entry.calendar) }
|
||||
when (candidates.size) {
|
||||
1 -> calendars[candidates.single().id] = entry
|
||||
else -> skipped += entry.calendar.skipped(ambiguous = candidates.size > 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return SettingsImportPlan(
|
||||
prefs = prefs,
|
||||
calendars = calendars.takeIf { available != null },
|
||||
pendingSpecialDates = pending,
|
||||
language = language,
|
||||
launcherName = backup.launcherName,
|
||||
skipped = skipped,
|
||||
)
|
||||
}
|
||||
|
||||
/** Writes the plan's stored values, replacing every backed-up setting and all per-calendar ones. */
|
||||
fun SettingsImportPlan.applyTo(target: MutablePreferences) {
|
||||
plainSection.apply(target, prefs)
|
||||
calendars?.let(target::writeCalendarSettings)
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the per-calendar keys with [calendars], by this device's ids. A
|
||||
* last-used calendar only counts from the first entry claiming it.
|
||||
*/
|
||||
fun MutablePreferences.writeCalendarSettings(calendars: Map<Long, CalendarSettings>) {
|
||||
SettingsBackupSchema.perCalendar.forEach { setRawValue(it, null) }
|
||||
calendars.forEach { (id, entry) -> addCalendarSettings(id, entry) }
|
||||
}
|
||||
|
||||
/** Adds one late-matched calendar's settings to what [writeCalendarSettings] stored. */
|
||||
fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
|
||||
if (entry.hidden) this[CalendarPrefKeys.hiddenCalendarIds] = this[CalendarPrefKeys.hiddenCalendarIds] + id
|
||||
if (entry.lastUsed && this[CalendarPrefKeys.lastUsedCalendarId] == null) {
|
||||
this[CalendarPrefKeys.lastUsedCalendarId] = id
|
||||
}
|
||||
entry.eventDurationMinutes?.let {
|
||||
this[SettingsKeys.perCalendarEventDuration] =
|
||||
this[SettingsKeys.perCalendarEventDuration] + (id to it.clampDuration())
|
||||
}
|
||||
entry.reminders?.let {
|
||||
this[SettingsKeys.perCalendarReminderOverride] = this[SettingsKeys.perCalendarReminderOverride] + (id to it)
|
||||
}
|
||||
entry.allDayReminders?.let {
|
||||
this[SettingsKeys.perCalendarAllDayReminderOverride] =
|
||||
this[SettingsKeys.perCalendarAllDayReminderOverride] + (id to it)
|
||||
}
|
||||
if (entry.hiddenInViews.isNotEmpty()) {
|
||||
this[SettingsKeys.perCalendarHiddenViews] = this[SettingsKeys.perCalendarHiddenViews] + (id to entry.hiddenInViews)
|
||||
}
|
||||
if (!entry.notifications) this[SettingsKeys.mutedReminderCalendarIds] = this[SettingsKeys.mutedReminderCalendarIds] + id
|
||||
entry.alertStyle?.let { this[SettingsKeys.reminderAlertStyles] = this[SettingsKeys.reminderAlertStyles] + (id to it) }
|
||||
val fixed = when (val override = entry.fixedTimeReminder) {
|
||||
FixedTimeOverride.Inherit -> null
|
||||
FixedTimeOverride.Off -> id to null
|
||||
is FixedTimeOverride.At -> id to override.reminder
|
||||
}
|
||||
fixed?.let {
|
||||
this[SettingsKeys.perCalendarFixedTimeReminderOverride] = this[SettingsKeys.perCalendarFixedTimeReminderOverride] + it
|
||||
}
|
||||
if (!entry.inDailyDigest) this[SettingsKeys.digestExcludedCalendarIds] = this[SettingsKeys.digestExcludedCalendarIds] + id
|
||||
when (entry.autoBackup) {
|
||||
true -> this[SettingsKeys.autoBackupIncluded] = this[SettingsKeys.autoBackupIncluded] + id
|
||||
false -> this[SettingsKeys.autoBackupExcluded] = this[SettingsKeys.autoBackupExcluded] + id
|
||||
null -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
fun CalendarIdentity.skipped(ambiguous: Boolean = false): SkippedSetting =
|
||||
SkippedSetting.Calendar(displayName, accountName, ambiguous)
|
||||
|
||||
fun SettingsImportPlan.summary(calendarsMatched: Int, more: List<SkippedSetting> = emptyList()) =
|
||||
SettingsImportSummary(
|
||||
calendarsMatched = calendarsMatched,
|
||||
skipped = skipped + more,
|
||||
)
|
||||
|
||||
private fun CalendarSource.matches(identity: CalendarIdentity): Boolean =
|
||||
accountType == identity.accountType &&
|
||||
accountName == identity.accountName &&
|
||||
displayName == identity.displayName
|
||||
|
||||
/** The same range the per-calendar duration setter clamps to. */
|
||||
private fun Int.clampDuration(): Int = coerceIn(SettingsPrefs.MIN_EVENT_DURATION, SettingsPrefs.MAX_EVENT_DURATION)
|
||||
|
||||
private fun FontRole.fontPref(): Pref<String> = when (this) {
|
||||
FontRole.BRAND -> SettingsKeys.brandFont
|
||||
FontRole.PLAIN -> SettingsKeys.plainFont
|
||||
}
|
||||
@@ -54,18 +54,6 @@ internal fun toProviderAllDayMinutes(
|
||||
return if (raw == MINUTES_DEFAULT) MINUTES_DEFAULT - 1 else raw
|
||||
}
|
||||
|
||||
/**
|
||||
* A lead time as the whole days an all-day reminder actually fires at: the
|
||||
* sub-day part is dropped, matching [toProviderAllDayMinutes]'s day count.
|
||||
* [MINUTES_DEFAULT] passes through.
|
||||
*/
|
||||
internal fun wholeDayLeadMinutes(minutes: Int): Int =
|
||||
if (minutes == MINUTES_DEFAULT) minutes else minutes / MINUTES_PER_DAY * MINUTES_PER_DAY
|
||||
|
||||
/** [wholeDayLeadMinutes] for a reminder list, merging lead times that land on the same day. */
|
||||
internal fun wholeDayLeadTimes(minutes: List<Int>): List<Int> =
|
||||
minutes.map(::wholeDayLeadMinutes).distinct().sorted()
|
||||
|
||||
/**
|
||||
* The next date on or after [today] carrying [month]/[day] — the date to sample
|
||||
* a yearly all-day reminder's UTC offset at. A managed birthday's DTSTART is an
|
||||
|
||||
+66
-149
@@ -30,15 +30,11 @@ import de.jeanlucmakiola.calendula.domain.Reminder
|
||||
import de.jeanlucmakiola.calendula.domain.SearchCandidate
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.domain.ics.CalendarRows
|
||||
import de.jeanlucmakiola.calendula.domain.ics.OverrideRow
|
||||
import de.jeanlucmakiola.calendula.domain.ics.MasterRow
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes
|
||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||
import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt
|
||||
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
|
||||
import de.jeanlucmakiola.calendula.domain.toEditForm
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.toJavaLocalDate
|
||||
@@ -94,15 +90,15 @@ interface CalendarDataSource {
|
||||
fun publishedEventColors(calendarId: Long): List<EventColorOption>
|
||||
|
||||
/**
|
||||
* Every event row of [calendarIds], whatever kind of calendar they are
|
||||
* (local, synced, read-only): the masters/one-offs and the modified and
|
||||
* cancelled exception rows, each with the keys that link it to its series
|
||||
* and tagged with its calendar's name. A plain read: which calendars may be
|
||||
* read for what is the caller's call. [allDayReminderTimeMinutes]: needed to
|
||||
* write all-day reminders as whole-day lead times rather than raw provider
|
||||
* offsets (see [toIcsEvent]).
|
||||
* Every master/one-off event of the writable local calendars, mapped for a
|
||||
* whole-calendar `.ics` backup. Modified-occurrence and cancelled-exception
|
||||
* rows are excluded (see [EventExportProjection]). When [calendarIds] is
|
||||
* given, only those calendars are exported (still intersected with the
|
||||
* eligible set); `null` exports every eligible calendar.
|
||||
* [allDayReminderTimeMinutes]: needed to write all-day reminders as whole-day
|
||||
* lead times rather than raw provider offsets (see [toIcsEvent]).
|
||||
*/
|
||||
fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows
|
||||
fun exportableEvents(calendarIds: Set<Long>?, allDayReminderTimeMinutes: Int): List<IcsEvent>
|
||||
|
||||
/**
|
||||
* The non-empty `Events.UID_2445` values present in [calendarId] — used to
|
||||
@@ -305,12 +301,6 @@ interface CalendarDataSource {
|
||||
*/
|
||||
fun deleteOccurrence(eventId: Long, beginMillis: Long)
|
||||
|
||||
/** The account [calendarId] belongs to; null when the row is gone or unreadable. */
|
||||
fun calendarAccount(calendarId: Long): SyncAccount?
|
||||
|
||||
/** The calendar event [eventId] lives in; null when the row is gone or unreadable. */
|
||||
fun eventCalendarId(eventId: Long): Long?
|
||||
|
||||
fun registerChangeListener(listener: () -> Unit)
|
||||
fun unregisterChangeListener(listener: () -> Unit)
|
||||
}
|
||||
@@ -786,94 +776,47 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
?: emptyList()
|
||||
}
|
||||
|
||||
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
|
||||
if (calendarIds.isEmpty()) return CalendarRows(emptyList(), emptyList())
|
||||
// The name tags each event for a combined backup's restore to fan back
|
||||
// out; an id that no longer exists drops out here.
|
||||
val calendars = calendars().filter { it.id in calendarIds }.associateBy { it.id }
|
||||
if (calendars.isEmpty()) return CalendarRows(emptyList(), emptyList())
|
||||
|
||||
val selection = "${CalendarContract.Events.CALENDAR_ID} IN (${calendars.keys.joinToString(",")}) AND " +
|
||||
"${CalendarContract.Events.DELETED} = 0"
|
||||
val series = mutableListOf<MasterRow>()
|
||||
val overrides = mutableListOf<OverrideRow>()
|
||||
forEachExportRow(selection, allDayReminderTimeMinutes) { event ->
|
||||
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
|
||||
val calendar = calendars[calendarId]
|
||||
// An adapter may stamp the calendar colour on every row; a palette key means it was chosen.
|
||||
val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf {
|
||||
it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty()
|
||||
}
|
||||
val mapped = event(calendar?.displayName).copy(color = color)
|
||||
val selfStatus = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS)
|
||||
val declined = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED
|
||||
val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID)
|
||||
val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() }
|
||||
// Without a link the provider shows the row as an event of its own.
|
||||
if (originalId == null && originalSyncId == null) {
|
||||
series += MasterRow(
|
||||
eventId = getLong(EventExportProjection.IDX_ID),
|
||||
calendarId = calendarId,
|
||||
syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() },
|
||||
event = mapped,
|
||||
declined = declined,
|
||||
)
|
||||
} else {
|
||||
// An exception without its occurrence time can't name what it replaces.
|
||||
val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME)
|
||||
?: return@forEachExportRow
|
||||
overrides += OverrideRow(
|
||||
calendarId = calendarId,
|
||||
originalId = originalId,
|
||||
originalSyncId = originalSyncId,
|
||||
originalInstance = originalInstance.toKotlinInstantFromEpochMillis(),
|
||||
event = mapped,
|
||||
declined = declined,
|
||||
accepted = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED ||
|
||||
selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE,
|
||||
)
|
||||
}
|
||||
}
|
||||
return CalendarRows(series, overrides)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand each Events row matching [selection], oldest first, to [row] with a
|
||||
* mapper to [IcsEvent] that takes the calendar name to tag it with.
|
||||
* Reminders are read in one batched pass ahead of the rows.
|
||||
*/
|
||||
private fun forEachExportRow(
|
||||
selection: String,
|
||||
override fun exportableEvents(
|
||||
calendarIds: Set<Long>?,
|
||||
allDayReminderTimeMinutes: Int,
|
||||
row: ColumnReader.(event: (calendarName: String?) -> IcsEvent) -> Unit,
|
||||
) {
|
||||
val eventIds = resolver.query(
|
||||
CalendarContract.Events.CONTENT_URI,
|
||||
arrayOf(CalendarContract.Events._ID),
|
||||
selection,
|
||||
null,
|
||||
null,
|
||||
)?.use { c -> c.mapRows { getLong(0) } }.orEmpty()
|
||||
val reminders = resolver.reminderMinutesByEvent(eventIds, alertsOnly = false)
|
||||
resolver.query(
|
||||
): List<IcsEvent> {
|
||||
// Only the local calendars the app owns and can write — synced calendars
|
||||
// already have a backup (their server). Exclude the managed special-dates
|
||||
// mirror calendars: their events are derived from contacts, not authored
|
||||
// here, and re-materialise from the contact sync — backing them up would
|
||||
// just duplicate them on restore. A non-null [calendarIds] narrows the
|
||||
// export to the user's chosen subset. Map id → display name for the
|
||||
// X-CALENDULA-CALENDAR tag a restore uses to fan back out.
|
||||
val names = calendars()
|
||||
.filter {
|
||||
it.isLocal && it.canModifyContents && !it.isManaged &&
|
||||
(calendarIds == null || it.id in calendarIds)
|
||||
}
|
||||
.associate { it.id to it.displayName }
|
||||
if (names.isEmpty()) return emptyList()
|
||||
|
||||
val idList = names.keys.joinToString(",")
|
||||
return resolver.query(
|
||||
CalendarContract.Events.CONTENT_URI,
|
||||
EventExportProjection.COLUMNS,
|
||||
selection,
|
||||
// Skip soft-deleted rows and exception rows (modified occurrences /
|
||||
// cancellations) — v1 exports masters + one-offs only.
|
||||
"${CalendarContract.Events.CALENDAR_ID} IN ($idList) AND " +
|
||||
"${CalendarContract.Events.DELETED} = 0 AND " +
|
||||
"${CalendarContract.Events.ORIGINAL_ID} IS NULL",
|
||||
null,
|
||||
CalendarContract.Events.DTSTART + " ASC",
|
||||
)?.use { c ->
|
||||
val reader = CursorColumnReader(c)
|
||||
while (c.moveToNext()) {
|
||||
val eventId = reader.getLong(EventExportProjection.IDX_ID)
|
||||
reader.row { calendarName ->
|
||||
reader.toIcsEvent(
|
||||
reminderMinutes = reminders[eventId].orEmpty(),
|
||||
calendarName = calendarName,
|
||||
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
|
||||
)
|
||||
}
|
||||
c.mapRows {
|
||||
val eventId = getLong(EventExportProjection.IDX_ID)
|
||||
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
|
||||
toIcsEvent(
|
||||
reminderMinutes = queryReminders(eventId).map { it.minutes },
|
||||
calendarName = names[calendarId],
|
||||
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
|
||||
)
|
||||
}
|
||||
}
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
override fun existingUids(calendarId: Long): Set<String> = resolver.query(
|
||||
@@ -922,30 +865,24 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
} else {
|
||||
null
|
||||
}
|
||||
// All or nothing: a row whose reminders failed would count as not added
|
||||
// and still be there.
|
||||
try {
|
||||
event.semanticReminderMinutes().forEach { minutes ->
|
||||
val providerMinutes = if (reminderDate != null) {
|
||||
toProviderAllDayMinutes(
|
||||
semanticMinutes = minutes,
|
||||
startDate = reminderDate,
|
||||
zone = zone,
|
||||
timeOfDayMinutes = allDayReminderTimeMinutes,
|
||||
)
|
||||
} else {
|
||||
minutes
|
||||
}
|
||||
insertReminderRow(eventId, providerMinutes)
|
||||
event.semanticReminderMinutes().forEach { minutes ->
|
||||
val providerMinutes = if (reminderDate != null) {
|
||||
toProviderAllDayMinutes(
|
||||
semanticMinutes = minutes,
|
||||
startDate = reminderDate,
|
||||
zone = zone,
|
||||
timeOfDayMinutes = allDayReminderTimeMinutes,
|
||||
)
|
||||
} else {
|
||||
minutes
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
runCatching { resolver.delete(eventUri(eventId), null, null) }
|
||||
throw t
|
||||
insertReminderRow(eventId, providerMinutes)
|
||||
}
|
||||
return eventId
|
||||
}
|
||||
|
||||
override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query(
|
||||
/** The account a calendar belongs to, for scoping a `Colors` lookup. */
|
||||
private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query(
|
||||
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
|
||||
arrayOf(
|
||||
CalendarContract.Calendars.ACCOUNT_NAME,
|
||||
@@ -954,17 +891,13 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
null, null, null,
|
||||
)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun eventCalendarId(eventId: Long): Long? = resolver.query(
|
||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
||||
arrayOf(CalendarContract.Events.CALENDAR_ID),
|
||||
null, null, null,
|
||||
)?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null }
|
||||
private data class CalendarAccount(val name: String, val type: String)
|
||||
|
||||
/**
|
||||
* The raw provider `MINUTES` to store for one of [form]'s reminders: an
|
||||
@@ -986,15 +919,11 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
minutes
|
||||
}
|
||||
|
||||
/**
|
||||
* [form]'s reminders as the distinct raw provider offsets to store, its
|
||||
* fixed-time ones (#459) measured from the start it is saved with.
|
||||
*/
|
||||
/** [form]'s reminders as the distinct raw provider offsets to store. */
|
||||
private fun encodedReminders(form: EventForm, allDayReminderTimeMinutes: Int): List<Int> =
|
||||
(
|
||||
form.reminders.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) } +
|
||||
form.fixedReminderOffsets(TimeZone.currentSystemDefault())
|
||||
).distinct()
|
||||
form.reminders
|
||||
.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) }
|
||||
.distinct()
|
||||
|
||||
override fun insertEvent(form: EventForm, allDayReminderTimeMinutes: Int): Long {
|
||||
// A globally-unique UID so a later .ics backup/restore can identify
|
||||
@@ -1095,12 +1024,9 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
updateEventRow(eventId, values.toContentValues(), "update event id=$eventId")
|
||||
}
|
||||
// Untouched reminder sets are left alone so unrelated edits can't
|
||||
// disturb provider rows the form never knew about. A fixed-time reminder
|
||||
// also changes when the start's day or time does.
|
||||
val zone = TimeZone.currentSystemDefault()
|
||||
if (remindersNeedRewrite(original, updated) ||
|
||||
updated.fixedReminderOffsets(zone).toSet() != original.fixedReminderOffsets(zone).toSet()
|
||||
) {
|
||||
// disturb provider rows the form never knew about. The diff is on the
|
||||
// form's semantic minutes; reconcile works in encoded provider minutes.
|
||||
if (updated.reminders.toSet() != original.reminders.toSet()) {
|
||||
reconcileReminders(eventId, encodedReminders(updated, allDayReminderTimeMinutes))
|
||||
}
|
||||
// Same untouched-set guard for guests: only reconcile when the form's
|
||||
@@ -1301,9 +1227,8 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
)
|
||||
}
|
||||
// Whether the provider copied the parent's reminder rows is its
|
||||
// business — reconciling against the actual rows handles both ways. The
|
||||
// exception is a one-off, so a fixed-time reminder takes real minutes.
|
||||
reconcileReminders(exceptionId, encodedReminders(form.toDetachedOccurrence(), allDayReminderTimeMinutes))
|
||||
// business — reconciling against the actual rows handles both ways.
|
||||
reconcileReminders(exceptionId, encodedReminders(form, allDayReminderTimeMinutes))
|
||||
reconcileAttendees(exceptionId, form.attendees)
|
||||
return exceptionId
|
||||
}
|
||||
@@ -1860,11 +1785,3 @@ class AndroidCalendarDataSource @Inject constructor(
|
||||
const val MAX_SEARCH_TOKENS = 8
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an update must rewrite the reminder rows. The diff is on the form's
|
||||
* semantic minutes, but the provider stores encoded minutes, so switching all-day
|
||||
* on or off re-encodes an otherwise unchanged set.
|
||||
*/
|
||||
internal fun remindersNeedRewrite(original: EventForm, updated: EventForm): Boolean =
|
||||
updated.reminders.toSet() != original.reminders.toSet() || updated.isAllDay != original.isAllDay
|
||||
@@ -11,7 +11,6 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlin.time.Instant
|
||||
|
||||
interface CalendarRepository {
|
||||
@@ -62,41 +61,18 @@ interface CalendarRepository {
|
||||
suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean)
|
||||
|
||||
/**
|
||||
* Every event of [calendarIds], ready to serialise into an `.ics` backup
|
||||
* (see [CalendarDataSource.calendarRows]). Any calendar can be read,
|
||||
* synced and read-only ones included (#147). Exception rows come out
|
||||
* flattened ([de.jeanlucmakiola.calendula.domain.ics.flattenOverrides]),
|
||||
* so a restore keeps moved and deleted occurrences of a series.
|
||||
* Every event of the writable local calendars, ready to serialise into a
|
||||
* whole-calendar `.ics` backup (see [CalendarDataSource.exportableEvents]).
|
||||
* [calendarIds] narrows the export to a chosen subset; `null` exports all.
|
||||
*/
|
||||
suspend fun exportEvents(calendarIds: Set<Long>): List<IcsEvent>
|
||||
suspend fun exportEvents(calendarIds: Set<Long>? = null): List<IcsEvent>
|
||||
|
||||
/**
|
||||
* Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose
|
||||
* UID already exists in the target are skipped (idempotent restore); the
|
||||
* rest are inserted, as is a standalone occurrence whose series is already
|
||||
* there ([ParsedIcsEvent.overrideOf]). See [CalendarDataSource.insertImportedEvent].
|
||||
* [onProgress] gets the count of events handled so far before each event
|
||||
* after the first and once more when all were handled; it may throw to stop
|
||||
* the import between events.
|
||||
* rest are inserted. See [CalendarDataSource.insertImportedEvent].
|
||||
*/
|
||||
suspend fun importEvents(
|
||||
targetCalendarId: Long,
|
||||
events: List<ParsedIcsEvent>,
|
||||
onProgress: (done: Int) -> Unit = {},
|
||||
): IcsImportSummary
|
||||
|
||||
/**
|
||||
* Copy every event of [sourceCalendarId] into [targetCalendarId] (#325),
|
||||
* exceptions included (see
|
||||
* [de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy]). The source is only read. Runs
|
||||
* through [importEvents], so a re-run skips what an earlier one copied.
|
||||
* [onProgress] gets (done, total) once the source is read and after each event.
|
||||
*/
|
||||
suspend fun copyEvents(
|
||||
sourceCalendarId: Long,
|
||||
targetCalendarId: Long,
|
||||
onProgress: (done: Int, total: Int) -> Unit = { _, _ -> },
|
||||
): IcsImportSummary
|
||||
suspend fun importEvents(targetCalendarId: Long, events: List<ParsedIcsEvent>): IcsImportSummary
|
||||
|
||||
/** Create a new event from a validated form; returns the new `Events._ID`. */
|
||||
suspend fun createEvent(form: EventForm): Long
|
||||
@@ -158,31 +134,6 @@ interface CalendarRepository {
|
||||
|
||||
/** Delete a recurring event from the occurrence at [beginMillis] onwards. */
|
||||
suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long)
|
||||
|
||||
/**
|
||||
* Ask every account behind a visible synced calendar to sync now (#240).
|
||||
* Only a request: the adapter may still run it late, or fail.
|
||||
*/
|
||||
suspend fun requestSync(): SyncRequest = SyncRequest(SyncRequestResult.NothingToSync)
|
||||
|
||||
/** Wait for the syncs a [requestSync] reached to run, see [awaitSyncs]. */
|
||||
suspend fun awaitSyncs(accounts: Set<SyncAccount>): SyncWait = SyncWait.Unconfirmed
|
||||
|
||||
/**
|
||||
* The accounts behind visible calendars with a sync adapter, split by
|
||||
* whether [requestSync] can reach them yet. Account access isn't observable:
|
||||
* it is re-read on each collection and on every [refreshSyncAccess].
|
||||
*/
|
||||
val syncTargets: Flow<SyncTargets> get() = flowOf(SyncTargets.None)
|
||||
|
||||
/** Re-read account access for every [syncTargets] collector; it can change outside the app. */
|
||||
fun refreshSyncAccess() {}
|
||||
|
||||
/** Stop or resume asking for [account]'s sync-request access. */
|
||||
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {}
|
||||
|
||||
/** Every provider notification and [refresh], including the app's own writes. */
|
||||
val providerChanges: Flow<Unit> get() = emptyFlow()
|
||||
}
|
||||
|
||||
class NoSuchEventException(eventId: Long) :
|
||||
|
||||
+22
-232
@@ -14,14 +14,10 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.SearchCandidate
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides
|
||||
import de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
@@ -34,8 +30,6 @@ import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.time.Instant
|
||||
@@ -53,7 +47,6 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
private val prefs: CalendarPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val syncRequester: SyncRequester,
|
||||
) : CalendarRepository {
|
||||
|
||||
/** The configured wall-clock fire time for all-day reminders, read per write. */
|
||||
@@ -91,172 +84,16 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
override val providerChanges: Flow<Unit> get() = ticks
|
||||
|
||||
/**
|
||||
* Run a provider write on [io], then re-query whether or not it threw. The
|
||||
* accounts behind [syncCalendars] (read before the write, which may delete
|
||||
* the row) then get one sync nudge each (#303), also after a failure, which
|
||||
* may have landed part of a multi-row write. Once per write, so a multi-row
|
||||
* save or a whole import asks once per account.
|
||||
*/
|
||||
private suspend fun <T> write(
|
||||
syncCalendars: suspend () -> Collection<Long?>,
|
||||
block: suspend () -> T,
|
||||
): T = withContext(io) {
|
||||
val accounts = syncAccountsOf(syncCalendars)
|
||||
/** Run a provider write on [io], then re-query whether or not it threw. */
|
||||
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
|
||||
try {
|
||||
block()
|
||||
} finally {
|
||||
refresh()
|
||||
writes.tryEmit(Unit)
|
||||
requestSyncs(accounts, userInitiated = false)
|
||||
}
|
||||
}
|
||||
|
||||
private val noSync: suspend () -> Collection<Long?> = { emptyList() }
|
||||
|
||||
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
|
||||
try {
|
||||
calendarIds().filterNotNull().distinct()
|
||||
.mapNotNull { accountOf(it) }
|
||||
.withAdapter()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No sync nudge: the calendar account could not be read", e)
|
||||
emptySet()
|
||||
}
|
||||
|
||||
/** From the shared per-tick read; a calendar newer than it is read on its own. */
|
||||
private suspend fun accountOf(calendarId: Long): SyncAccount? =
|
||||
calendarsSnapshot().firstOrNull { it.id == calendarId }
|
||||
?.let { SyncAccount(it.accountName, it.accountType) }
|
||||
?: dataSource.calendarAccount(calendarId)
|
||||
|
||||
/** The syncable accounts among these whose type has a calendar sync adapter. */
|
||||
private fun Collection<SyncAccount>.withAdapter(): Set<SyncAccount> {
|
||||
val candidates = filter { it.isSyncable }
|
||||
if (candidates.isEmpty()) return emptySet()
|
||||
val adapterTypes = try {
|
||||
syncRequester.adapterAccountTypes()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync adapters unreadable", e)
|
||||
return emptySet()
|
||||
}
|
||||
return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes }
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits [accounts] by whether a request may name them (see
|
||||
* [SyncRequester.addressableAccounts]). The rest wait for the user's grant:
|
||||
* an account-less request would reach them, but also every other calendar
|
||||
* account on the device, so none is sent.
|
||||
*/
|
||||
private fun reach(accounts: Set<SyncAccount>): SyncTargets {
|
||||
if (accounts.isEmpty()) return SyncTargets.None
|
||||
// Unreadable access counts as reachable: a grant can't fix a failing read.
|
||||
val addressable = try {
|
||||
syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type })
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Account visibility unreadable", e)
|
||||
null
|
||||
}
|
||||
if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet())
|
||||
val (reachable, hidden) = accounts.partition { it in addressable }
|
||||
return SyncTargets(reachable.toSet(), hidden.toSet())
|
||||
}
|
||||
|
||||
/** Ask each reachable one of [accounts] once. */
|
||||
private fun requestSyncs(accounts: Set<SyncAccount>, userInitiated: Boolean) {
|
||||
reach(accounts).reachable.forEach { requestSync(it, userInitiated) }
|
||||
}
|
||||
|
||||
private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
|
||||
syncRequester.requestSync(account, userInitiated)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync request refused", e)
|
||||
false
|
||||
}
|
||||
|
||||
/** The event's own calendar (from [original] when given, else read), plus [others]. */
|
||||
private fun eventCalendar(
|
||||
eventId: Long,
|
||||
original: EventForm? = null,
|
||||
vararg others: Long?,
|
||||
): suspend () -> Collection<Long?> =
|
||||
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
|
||||
|
||||
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): SyncTargets =
|
||||
reach(
|
||||
calendars.syncAccounts().withAdapter()
|
||||
.sortedWith(compareBy({ it.name.lowercase() }, { it.type }))
|
||||
.toSet(),
|
||||
).let {
|
||||
if (dismissed.isEmpty()) {
|
||||
it
|
||||
} else {
|
||||
it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed)
|
||||
}
|
||||
}
|
||||
|
||||
private val accessChecks = MutableStateFlow(0)
|
||||
|
||||
override val syncTargets: Flow<SyncTargets>
|
||||
get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ ->
|
||||
// One failed read leaves the rows off until the next change, not for good.
|
||||
try {
|
||||
targetsOf(calendars, dismissed)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync targets unreadable", e)
|
||||
SyncTargets.None
|
||||
}
|
||||
}.flowOn(io)
|
||||
|
||||
override fun refreshSyncAccess() {
|
||||
accessChecks.update { it + 1 }
|
||||
}
|
||||
|
||||
override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
|
||||
try {
|
||||
prefs.setSyncAccessDismissed(account, dismissed)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync access dismissal not saved", e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun requestSync(): SyncRequest = withContext(io) {
|
||||
val targets = try {
|
||||
targetsOf(calendars().first(), prefs.syncAccessDismissed.first())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync request skipped: calendars unreadable", e)
|
||||
return@withContext SyncRequest(SyncRequestResult.Failed)
|
||||
}
|
||||
if (targets.reachable.isEmpty()) {
|
||||
return@withContext SyncRequest(
|
||||
if (targets.needsAccess.isEmpty()) SyncRequestResult.NothingToSync else SyncRequestResult.NeedsAccess,
|
||||
)
|
||||
}
|
||||
val sent = targets.reachable.filterTo(linkedSetOf()) { requestSync(it, userInitiated = true) }
|
||||
val result = when {
|
||||
sent.isEmpty() -> SyncRequestResult.Failed
|
||||
sent.size < targets.reachable.size -> SyncRequestResult.PartlyFailed
|
||||
targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess
|
||||
else -> SyncRequestResult.Requested
|
||||
}
|
||||
SyncRequest(result, sent)
|
||||
}
|
||||
|
||||
override suspend fun awaitSyncs(accounts: Set<SyncAccount>): SyncWait =
|
||||
withContext(io) { syncRequester.awaitSyncs(accounts) }
|
||||
|
||||
override val localChanges: Flow<Unit> = merge(
|
||||
writes,
|
||||
prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {},
|
||||
@@ -381,7 +218,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
): Long = write(noSync) {
|
||||
): Long = write {
|
||||
dataSource.createLocalCalendar(displayName, color, description)
|
||||
}
|
||||
|
||||
@@ -390,14 +227,13 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
) = write { dataSource.updateCalendar(id, displayName, color, description) }
|
||||
|
||||
override suspend fun deleteCalendar(id: Long) =
|
||||
write(noSync) { dataSource.deleteCalendar(id) }
|
||||
write { dataSource.deleteCalendar(id) }
|
||||
|
||||
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
||||
// VISIBLE is device-local: nothing for an adapter to upload.
|
||||
write(noSync) {
|
||||
write {
|
||||
val canWrite = dataSource.canWriteCalendars()
|
||||
if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) }
|
||||
// Nothing of ours is left waiting for the provider once the write
|
||||
@@ -411,34 +247,13 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun exportEvents(calendarIds: Set<Long>) = withContext(io) {
|
||||
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp)
|
||||
}
|
||||
|
||||
override suspend fun copyEvents(
|
||||
sourceCalendarId: Long,
|
||||
targetCalendarId: Long,
|
||||
onProgress: (done: Int, total: Int) -> Unit,
|
||||
): IcsImportSummary {
|
||||
val events = withContext(io) {
|
||||
planCalendarCopy(
|
||||
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()),
|
||||
::formatExdateStamp,
|
||||
)
|
||||
}
|
||||
onProgress(0, events.size)
|
||||
val context = currentCoroutineContext()
|
||||
return importEvents(targetCalendarId, events) { done ->
|
||||
if (done < events.size) context.ensureActive()
|
||||
onProgress(done, events.size)
|
||||
}
|
||||
}
|
||||
override suspend fun exportEvents(calendarIds: Set<Long>?) =
|
||||
withContext(io) { dataSource.exportableEvents(calendarIds, allDayReminderTimeMinutes()) }
|
||||
|
||||
override suspend fun importEvents(
|
||||
targetCalendarId: Long,
|
||||
events: List<ParsedIcsEvent>,
|
||||
onProgress: (done: Int) -> Unit,
|
||||
): IcsImportSummary = write({ listOf(targetCalendarId) }) {
|
||||
): IcsImportSummary = write {
|
||||
val existing = dataSource.existingUids(targetCalendarId)
|
||||
// Both are per-calendar, not per-event: looking them up once keeps a
|
||||
// thousand-event restore to two extra queries. The palette is the
|
||||
@@ -450,21 +265,15 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
var skipped = 0
|
||||
var failed = 0
|
||||
var notAttempted = 0
|
||||
// Occurrences whose standalone copy didn't land, by series UID: the series
|
||||
// keeps them instead of excluding them for good.
|
||||
val unexcluded = mutableMapOf<String, MutableList<Instant>>()
|
||||
// Standalone occurrences ahead of the series they were cut from, however the file is ordered.
|
||||
val ordered = events.sortedBy { it.overrideOf == null }
|
||||
for ((index, event) in ordered.withIndex()) {
|
||||
if (index > 0) onProgress(index)
|
||||
for ((index, event) in events.withIndex()) {
|
||||
// A known UID means the event is already in this calendar — skip,
|
||||
// keeping a restore idempotent (no overwrite this pass).
|
||||
if (event.isAlreadyIn(existing)) {
|
||||
if (event.uid != null && event.uid in existing) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
try {
|
||||
dataSource.insertImportedEvent(event.keeping(unexcluded), targetCalendarId, allDayMinutes, palette)
|
||||
dataSource.insertImportedEvent(event, targetCalendarId, allDayMinutes, palette)
|
||||
imported++
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
@@ -474,8 +283,8 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
Log.w(TAG, "Import stopped: the calendar is no longer writable", e)
|
||||
// A known UID would have been skipped whatever happened, so it is
|
||||
// no part of what a retry still has to import.
|
||||
val remaining = ordered.drop(index)
|
||||
val duplicates = remaining.count { it.isAlreadyIn(existing) }
|
||||
val remaining = events.drop(index)
|
||||
val duplicates = remaining.count { it.uid?.let { uid -> uid in existing } == true }
|
||||
skipped += duplicates
|
||||
notAttempted = remaining.size - duplicates
|
||||
break
|
||||
@@ -484,13 +293,9 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
// rest of the file — foreign exports do carry rows it rejects
|
||||
// outright (a malformed RRULE throws straight out of insert).
|
||||
failed++
|
||||
if (event.overrideOf != null && event.overrideAt != null) {
|
||||
unexcluded.getOrPut(event.overrideOf) { mutableListOf() } += event.overrideAt
|
||||
}
|
||||
Log.w(TAG, "Skipped an unimportable event", e)
|
||||
}
|
||||
}
|
||||
if (notAttempted == 0) onProgress(events.size)
|
||||
IcsImportSummary(
|
||||
imported = imported,
|
||||
skippedDuplicate = skipped,
|
||||
@@ -499,7 +304,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
|
||||
override suspend fun createEvent(form: EventForm): Long = write {
|
||||
dataSource.insertEvent(form, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
@@ -507,11 +312,11 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
eventId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
) = write(eventCalendar(eventId, original, updated.calendarId)) {
|
||||
) = write {
|
||||
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
|
||||
override suspend fun deleteEvent(eventId: Long) = write {
|
||||
dataSource.deleteEvent(eventId)
|
||||
}
|
||||
|
||||
@@ -520,7 +325,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
targetCalendarId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
|
||||
): Long = write {
|
||||
dataSource.moveEvent(
|
||||
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -531,7 +336,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
form: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
): Long = write {
|
||||
dataSource.updateOccurrence(
|
||||
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -542,7 +347,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
): Long = write {
|
||||
dataSource.updateEventFromOccurrence(
|
||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -552,14 +357,14 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
|
||||
override val seriesSplits: Flow<SeriesSplit> = splits
|
||||
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) {
|
||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
|
||||
dataSource.deleteOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
override suspend fun deleteEventFromOccurrence(
|
||||
eventId: Long,
|
||||
beginMillis: Long,
|
||||
) = write(eventCalendar(eventId)) {
|
||||
) = write {
|
||||
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
|
||||
}
|
||||
|
||||
@@ -571,18 +376,3 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
private fun <T> Flow<Unit>.reQuery(block: suspend () -> T): Flow<T> = flow {
|
||||
collect { emit(block()) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [existing] UIDs already hold this event: its own UID, or — for a
|
||||
* standalone occurrence of a backed-up or copied series — the series, which
|
||||
* there carries the override itself.
|
||||
*/
|
||||
private fun ParsedIcsEvent.isAlreadyIn(existing: Set<String>): Boolean =
|
||||
(uid != null && uid in existing) || (overrideOf != null && overrideOf in existing)
|
||||
|
||||
/** This series without the exclusions of [unexcluded] occurrences whose standalone copy failed. */
|
||||
private fun ParsedIcsEvent.keeping(unexcluded: Map<String, List<Instant>>): ParsedIcsEvent {
|
||||
val kept = uid?.let(unexcluded::get) ?: return this
|
||||
val stamps = kept.map { formatExdateStamp(it.toEpochMilliseconds(), isAllDay) }.toSet()
|
||||
return copy(exDates = exDates.filterNot { it in stamps })
|
||||
}
|
||||
@@ -684,7 +684,7 @@ private const val TZID_PREFIX = "TZID="
|
||||
* are UTC: the provider stores an all-day DTSTART at UTC midnight, so its date
|
||||
* reads off the UTC calendar day.
|
||||
*/
|
||||
internal fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String =
|
||||
private fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String =
|
||||
formatExdateStamp(
|
||||
local = Instant.ofEpochMilli(occurrenceMillis).atZone(ZoneOffset.UTC).toLocalDateTime(),
|
||||
isAllDay = isAllDay,
|
||||
@@ -851,12 +851,10 @@ internal fun buildImportedEventValues(
|
||||
put(CalendarContract.Events.TITLE, event.summary.trim())
|
||||
put(CalendarContract.Events.ALL_DAY, if (event.isAllDay) 1 else 0)
|
||||
put(CalendarContract.Events.DTSTART, startMillis)
|
||||
if (event.recurrenceRule == null && event.recurrenceDates.isEmpty()) {
|
||||
if (event.recurrenceRule == null) {
|
||||
put(CalendarContract.Events.DTEND, endMillis)
|
||||
} else {
|
||||
event.recurrenceRule?.let { put(CalendarContract.Events.RRULE, it) }
|
||||
event.recurrenceDates.takeIf { it.isNotEmpty() }
|
||||
?.let { put(CalendarContract.Events.RDATE, it.joinToString(",")) }
|
||||
put(CalendarContract.Events.RRULE, event.recurrenceRule)
|
||||
put(
|
||||
CalendarContract.Events.DURATION,
|
||||
importDuration(startMillis, endMillis, event.isAllDay),
|
||||
@@ -868,9 +866,6 @@ internal fun buildImportedEventValues(
|
||||
// timed rows keep the event's own zone.
|
||||
put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId)
|
||||
put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue())
|
||||
if (event.accessLevel != AccessLevel.Default) {
|
||||
put(CalendarContract.Events.ACCESS_LEVEL, event.accessLevel.toProviderValue())
|
||||
}
|
||||
put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus())
|
||||
event.location?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
package de.jeanlucmakiola.calendula.data.calendar
|
||||
|
||||
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
/**
|
||||
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
|
||||
@@ -32,8 +28,6 @@ internal fun ColumnReader.toIcsEvent(
|
||||
val dtStart = getLong(EventExportProjection.IDX_DTSTART)
|
||||
val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() }
|
||||
val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0
|
||||
val timezone = getString(EventExportProjection.IDX_EVENT_TIMEZONE)
|
||||
val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone, dtStart)
|
||||
|
||||
// Unclamped: the writer renders DTEND as stored.
|
||||
val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION)
|
||||
@@ -44,12 +38,17 @@ internal fun ColumnReader.toIcsEvent(
|
||||
start = dtStart.toKotlinInstantFromEpochMillis(),
|
||||
end = end.toKotlinInstantFromEpochMillis(),
|
||||
isAllDay = isAllDay,
|
||||
zoneId = timezone?.takeIf { it.isNotBlank() } ?: "UTC",
|
||||
zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() }
|
||||
?: "UTC",
|
||||
recurrenceRule = rrule,
|
||||
exDates = if (rrule == null && rdates.isEmpty()) {
|
||||
exDates = if (rrule == null) {
|
||||
emptyList()
|
||||
} else {
|
||||
exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone, dtStart)
|
||||
exportExDates(
|
||||
getString(EventExportProjection.IDX_EXDATE),
|
||||
isAllDay,
|
||||
getString(EventExportProjection.IDX_EVENT_TIMEZONE),
|
||||
)
|
||||
},
|
||||
location = getString(EventExportProjection.IDX_LOCATION),
|
||||
description = getString(EventExportProjection.IDX_DESCRIPTION),
|
||||
@@ -64,8 +63,6 @@ internal fun ColumnReader.toIcsEvent(
|
||||
status = eventStatus(EventExportProjection.IDX_STATUS),
|
||||
availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)),
|
||||
calendarName = calendarName,
|
||||
recurrenceDates = rdates,
|
||||
accessLevel = getIntOrNull(EventExportProjection.IDX_ACCESS_LEVEL)?.let(::mapAccessLevel) ?: AccessLevel.Default,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -97,53 +94,16 @@ internal fun exportExDates(
|
||||
exdate: String?,
|
||||
isAllDay: Boolean,
|
||||
eventTimezone: String? = null,
|
||||
seriesStartMillis: Long? = null,
|
||||
): List<String> {
|
||||
if (exdate.isNullOrBlank()) return emptyList()
|
||||
// Several properties are stored one per line, each with its own zone prefix.
|
||||
return exdate.lines().filter { it.isNotBlank() }.flatMap { line ->
|
||||
val zone = exdateListZone(line, eventTimezone)
|
||||
exdateStamps(line).mapNotNull { stamp ->
|
||||
when {
|
||||
isAllDay -> stamp.substringBefore('T')
|
||||
// A bare day on a timed series means the occurrence at the series' time of day.
|
||||
seriesStartMillis != null && BARE_DAY.matches(stamp) -> atSeriesTime(stamp, seriesStartMillis, zone)
|
||||
else -> canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp
|
||||
val zone = exdateListZone(exdate, eventTimezone)
|
||||
return exdateStamps(exdate)
|
||||
.map { stamp ->
|
||||
if (isAllDay) {
|
||||
stamp.substringBefore('T')
|
||||
} else {
|
||||
canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp
|
||||
}
|
||||
}
|
||||
}
|
||||
.filter { (if (isAllDay) BARE_DAY else UTC_STAMP).matches(it) }
|
||||
.distinct()
|
||||
}
|
||||
|
||||
/**
|
||||
* The row's `RDATE` in the same shape [exportExDates] gives `EXDATE` — the list
|
||||
* shares its `<zone>;<stamps>` form. A `PERIOD` entry (`start/end`) keeps only its
|
||||
* start: the occurrence then runs the series' own length. Anything that still
|
||||
* isn't a date or a UTC stamp is dropped, since a file can't name it.
|
||||
*/
|
||||
internal fun exportRecurrenceDates(
|
||||
rdate: String?,
|
||||
isAllDay: Boolean,
|
||||
eventTimezone: String? = null,
|
||||
seriesStartMillis: Long? = null,
|
||||
): List<String> {
|
||||
if (rdate.isNullOrBlank()) return emptyList()
|
||||
// The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end.
|
||||
val starts = rdate.lines().joinToString("\n") { line ->
|
||||
val stamps = line.withoutExdateParameters()
|
||||
line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') }
|
||||
}
|
||||
return exportExDates(starts, isAllDay, eventTimezone, seriesStartMillis)
|
||||
}
|
||||
|
||||
/** [day] (`yyyyMMdd`) at the wall-clock time the series starts at in [zone], as a UTC stamp. */
|
||||
private fun atSeriesTime(day: String, seriesStartMillis: Long, zone: ZoneId): String? {
|
||||
val date = runCatching { LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE) }.getOrNull() ?: return null
|
||||
val time = Instant.ofEpochMilli(seriesStartMillis).atZone(zone).toLocalTime()
|
||||
return formatExdateStamp(date.atTime(time).atZone(zone).toInstant().toEpochMilli(), isAllDay = false)
|
||||
}
|
||||
|
||||
private val BARE_DAY = Regex("""\d{8}""")
|
||||
private val UTC_STAMP = Regex("""\d{8}T\d{6}Z""")
|
||||
|
||||
@@ -152,13 +152,14 @@ internal object EventDetailProjection {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every Events row of a whole-calendar backup or copy. Unlike
|
||||
* Master/one-off Events rows for a whole-calendar backup. Unlike
|
||||
* [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across
|
||||
* backups) and `DURATION` (recurring rows carry it instead of DTEND), plus
|
||||
* `EXDATE` so a series exports the occurrences deleted from it. Exception rows
|
||||
* are read too and told apart by their series-link columns; see
|
||||
* [de.jeanlucmakiola.calendula.domain.ics.flattenOverrides] for how they are
|
||||
* written out.
|
||||
* `EXDATE` so a series exports the occurrences deleted from it. Modified-
|
||||
* occurrence and cancelled-exception rows are filtered out by the query
|
||||
* (`ORIGINAL_ID IS NULL`), so RECURRENCE-ID overrides aren't exported — a
|
||||
* documented v1 limit (import skips them too). EXDATE is unaffected by that
|
||||
* filter: it lives on the master row, not on an exception of its own.
|
||||
*/
|
||||
internal object EventExportProjection {
|
||||
val COLUMNS: Array<String> = arrayOf(
|
||||
@@ -177,15 +178,6 @@ internal object EventExportProjection {
|
||||
CalendarContract.Events.STATUS,
|
||||
CalendarContract.Events.AVAILABILITY,
|
||||
CalendarContract.Events.CALENDAR_ID,
|
||||
CalendarContract.Events.EVENT_COLOR,
|
||||
CalendarContract.Events._SYNC_ID,
|
||||
CalendarContract.Events.ORIGINAL_ID,
|
||||
CalendarContract.Events.ORIGINAL_SYNC_ID,
|
||||
CalendarContract.Events.ORIGINAL_INSTANCE_TIME,
|
||||
CalendarContract.Events.RDATE,
|
||||
CalendarContract.Events.ACCESS_LEVEL,
|
||||
CalendarContract.Events.EVENT_COLOR_KEY,
|
||||
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||
)
|
||||
|
||||
const val IDX_ID = 0
|
||||
@@ -203,15 +195,6 @@ internal object EventExportProjection {
|
||||
const val IDX_STATUS = 12
|
||||
const val IDX_AVAILABILITY = 13
|
||||
const val IDX_CALENDAR_ID = 14
|
||||
const val IDX_EVENT_COLOR = 15
|
||||
const val IDX_SYNC_ID = 16
|
||||
const val IDX_ORIGINAL_ID = 17
|
||||
const val IDX_ORIGINAL_SYNC_ID = 18
|
||||
const val IDX_ORIGINAL_INSTANCE_TIME = 19
|
||||
const val IDX_RDATE = 20
|
||||
const val IDX_ACCESS_LEVEL = 21
|
||||
const val IDX_EVENT_COLOR_KEY = 22
|
||||
const val IDX_SELF_ATTENDEE_STATUS = 23
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.calendar
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.provider.CalendarContract
|
||||
|
||||
/** Ids per `IN (…)` list: they go into the SQL literally, which SQLite bounds. */
|
||||
private const val EVENT_ID_BATCH = 50
|
||||
|
||||
/**
|
||||
* Reminder minutes of [eventIds], keyed by event, a batched query at a time
|
||||
* rather than one per event. [alertsOnly] keeps just the notification ones.
|
||||
*/
|
||||
internal fun ContentResolver.reminderMinutesByEvent(
|
||||
eventIds: Collection<Long>,
|
||||
alertsOnly: Boolean,
|
||||
): Map<Long, List<Int>> {
|
||||
if (eventIds.isEmpty()) return emptyMap()
|
||||
val out = mutableMapOf<Long, MutableList<Int>>()
|
||||
val method = if (alertsOnly) {
|
||||
"${CalendarContract.Reminders.METHOD} = ${CalendarContract.Reminders.METHOD_ALERT} AND "
|
||||
} else {
|
||||
""
|
||||
}
|
||||
eventIds.distinct().chunked(EVENT_ID_BATCH).forEach { batch ->
|
||||
query(
|
||||
CalendarContract.Reminders.CONTENT_URI,
|
||||
arrayOf(CalendarContract.Reminders.EVENT_ID, CalendarContract.Reminders.MINUTES),
|
||||
"$method${CalendarContract.Reminders.EVENT_ID} IN (${batch.joinToString(",")})",
|
||||
null,
|
||||
null,
|
||||
)?.use { c ->
|
||||
while (c.moveToNext()) out.getOrPut(c.getLong(0)) { mutableListOf() } += c.getInt(1)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.calendar
|
||||
|
||||
import android.accounts.Account
|
||||
import android.accounts.AccountManager
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.CalendarContract
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.channelFlow
|
||||
import kotlinx.coroutines.flow.conflate
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/** The account behind a calendar row (`ACCOUNT_NAME` / `ACCOUNT_TYPE`). */
|
||||
data class SyncAccount(val name: String, val type: String) {
|
||||
/** Whether a sync adapter can stand behind it: device-only calendars have none. */
|
||||
val isSyncable: Boolean
|
||||
get() = name.isNotBlank() && type.isNotBlank() && type != CalendarContract.ACCOUNT_TYPE_LOCAL
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the system to run a calendar sync adapter sooner (#303, #240). The sync
|
||||
* itself stays the adapter's job; this only schedules it.
|
||||
*/
|
||||
interface SyncRequester {
|
||||
/** Account types with a calendar sync adapter installed; for any other a request does nothing. */
|
||||
fun adapterAccountTypes(): Set<String>
|
||||
|
||||
/**
|
||||
* The accounts of [types] a request may name, or null when any may. From
|
||||
* Android 13 a request for an account the app can't see is dropped without a word.
|
||||
*/
|
||||
fun addressableAccounts(types: Set<String>): Set<SyncAccount>?
|
||||
|
||||
/**
|
||||
* Schedule a sync of [account]; may throw if the system refuses. [userInitiated]
|
||||
* marks it manual, which also overrides master-sync-off — only for a user's tap.
|
||||
*/
|
||||
fun requestSync(account: SyncAccount, userInitiated: Boolean)
|
||||
|
||||
/** Where [account]'s calendar sync stands, or null when the system won't say. */
|
||||
fun syncActivity(account: SyncAccount): SyncActivity?
|
||||
|
||||
/** Fires whenever any sync on the device becomes pending, starts or ends. */
|
||||
fun syncActivityChanges(): Flow<Unit>
|
||||
}
|
||||
|
||||
/** A calendar sync adapter's state for one account, from `READ_SYNC_STATS`. */
|
||||
enum class SyncActivity { Idle, Pending, Active }
|
||||
|
||||
/** How waiting on requested syncs ended: seen through, or not confirmed in time. */
|
||||
enum class SyncWait { Completed, Unconfirmed }
|
||||
|
||||
/**
|
||||
* Waits until the syncs of [accounts] have run (#240): each account must have
|
||||
* been seen pending or active and be idle again, or — for one that never showed
|
||||
* up within [graceMillis] — be idle. A sync already running at the first look
|
||||
* isn't the requested one, so it has to finish before the account counts. Unconfirmed after [timeoutMillis], or at
|
||||
* once when the system won't report sync state.
|
||||
*/
|
||||
suspend fun SyncRequester.awaitSyncs(
|
||||
accounts: Set<SyncAccount>,
|
||||
timeoutMillis: Long = SYNC_WAIT_MILLIS,
|
||||
graceMillis: Long = SYNC_GRACE_MILLIS,
|
||||
pollMillis: Long = SYNC_POLL_MILLIS,
|
||||
): SyncWait {
|
||||
if (accounts.isEmpty()) return SyncWait.Completed
|
||||
val seen = HashSet<SyncAccount>()
|
||||
// One already running when asked is someone else's sync: it only counts once idle again.
|
||||
var priorRuns: MutableSet<SyncAccount>? = null
|
||||
val graceOver = AtomicBoolean(false)
|
||||
return withTimeoutOrNull(timeoutMillis) {
|
||||
channelFlow {
|
||||
launch { syncActivityChanges().collect { send(Unit) } }
|
||||
launch {
|
||||
delay(graceMillis)
|
||||
graceOver.set(true)
|
||||
send(Unit)
|
||||
}
|
||||
// The listener alone can miss a change made before it was registered.
|
||||
while (true) {
|
||||
send(Unit)
|
||||
delay(pollMillis)
|
||||
}
|
||||
}.conflate().map {
|
||||
val states = accounts.associateWith { syncActivity(it) ?: return@map SyncWait.Unconfirmed }
|
||||
val prior = priorRuns ?: states.filterValues { it == SyncActivity.Active }.keys.toMutableSet()
|
||||
.also { priorRuns = it }
|
||||
states.forEach { (account, state) ->
|
||||
if (state != SyncActivity.Active) prior -= account
|
||||
if (state != SyncActivity.Idle && account !in prior) seen += account
|
||||
}
|
||||
val done = states.all { (account, state) ->
|
||||
state == SyncActivity.Idle && account !in prior && (account in seen || graceOver.get())
|
||||
}
|
||||
if (done) SyncWait.Completed else null
|
||||
}.filterNotNull().first()
|
||||
} ?: SyncWait.Unconfirmed
|
||||
}
|
||||
|
||||
const val SYNC_WAIT_MILLIS = 60_000L
|
||||
const val SYNC_GRACE_MILLIS = 5_000L
|
||||
const val SYNC_POLL_MILLIS = 2_000L
|
||||
|
||||
@Singleton
|
||||
class AndroidSyncRequester @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
) : SyncRequester {
|
||||
// Lists only adapters in packages visible to the app — hence the SyncAdapter <queries> entry.
|
||||
override fun adapterAccountTypes(): Set<String> =
|
||||
ContentResolver.getSyncAdapterTypes()
|
||||
.filter { it.authority == CalendarContract.AUTHORITY }
|
||||
.mapTo(mutableSetOf()) { it.accountType }
|
||||
|
||||
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null
|
||||
val manager = AccountManager.get(context)
|
||||
return types.flatMapTo(mutableSetOf()) { type ->
|
||||
manager.getAccountsByType(type).map { SyncAccount(it.name, it.type) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
|
||||
val extras = Bundle().apply {
|
||||
putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
|
||||
if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
|
||||
}
|
||||
ContentResolver.requestSync(
|
||||
Account(account.name, account.type),
|
||||
CalendarContract.AUTHORITY,
|
||||
extras,
|
||||
)
|
||||
}
|
||||
|
||||
override fun syncActivity(account: SyncAccount): SyncActivity? = try {
|
||||
val android = Account(account.name, account.type)
|
||||
when {
|
||||
ContentResolver.isSyncActive(android, CalendarContract.AUTHORITY) -> SyncActivity.Active
|
||||
ContentResolver.isSyncPending(android, CalendarContract.AUTHORITY) -> SyncActivity.Pending
|
||||
else -> SyncActivity.Idle
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
null
|
||||
}
|
||||
|
||||
override fun syncActivityChanges(): Flow<Unit> = callbackFlow {
|
||||
val handle = try {
|
||||
ContentResolver.addStatusChangeListener(
|
||||
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING,
|
||||
) { trySend(Unit) }
|
||||
} catch (e: SecurityException) {
|
||||
null
|
||||
}
|
||||
awaitClose { handle?.let(ContentResolver::removeStatusChangeListener) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */
|
||||
fun List<CalendarSource>.syncAccounts(): Set<SyncAccount> =
|
||||
filter { it.isVisibleInSystem }
|
||||
.map { SyncAccount(it.accountName, it.accountType) }
|
||||
.filterTo(linkedSetOf()) { it.isSyncable }
|
||||
|
||||
/**
|
||||
* Who a sync request can go to: [reachable] by name, [needsAccess] only once the
|
||||
* user lets the app see the account (Android 13+, see [accountAccessIntent]).
|
||||
* [dismissed] are hidden accounts the user said not to ask about.
|
||||
*/
|
||||
data class SyncTargets(
|
||||
val reachable: Set<SyncAccount>,
|
||||
val needsAccess: Set<SyncAccount>,
|
||||
val dismissed: Set<SyncAccount> = emptySet(),
|
||||
) {
|
||||
companion object {
|
||||
val None = SyncTargets(emptySet(), emptySet())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The system account picker, limited to [account]: once picked it becomes
|
||||
* visible to the app, so sync requests can name it.
|
||||
*/
|
||||
fun accountAccessIntent(account: SyncAccount, description: String): Intent =
|
||||
AccountManager.newChooseAccountIntent(
|
||||
null,
|
||||
listOf(Account(account.name, account.type)),
|
||||
arrayOf(account.type),
|
||||
description,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Outcome of a user-triggered sync request (#240). [Completed] is only ever set
|
||||
* once the requested syncs were seen through, see [awaitSyncs].
|
||||
*/
|
||||
enum class SyncRequestResult { Requested, Completed, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed }
|
||||
|
||||
/** A sync request's [result] and the [accounts] it actually reached. */
|
||||
data class SyncRequest(val result: SyncRequestResult, val accounts: Set<SyncAccount> = emptySet())
|
||||
@@ -11,11 +11,9 @@ import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
|
||||
import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource
|
||||
import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec
|
||||
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
|
||||
@@ -51,12 +49,6 @@ abstract class DataBindModule {
|
||||
impl: CalendarRepositoryImpl,
|
||||
): CalendarRepository
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindSyncRequester(
|
||||
impl: AndroidSyncRequester,
|
||||
): SyncRequester
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindReminderInstanceSource(
|
||||
|
||||
@@ -5,10 +5,6 @@ import android.net.Uri
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.floret.android.TreeListing
|
||||
import de.jeanlucmakiola.floret.android.deleteTreeFiles
|
||||
import de.jeanlucmakiola.floret.android.listTreeFiles
|
||||
import de.jeanlucmakiola.floret.android.writeTreeFile
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import javax.inject.Inject
|
||||
@@ -33,27 +29,34 @@ class IcsExporter @Inject constructor(
|
||||
} ?: throw IOException("Could not open output stream for export (scheme=${uri.scheme})")
|
||||
}
|
||||
|
||||
/** The files in the persisted SAF tree [folder], the automatic-backup destination. Throws when unusable. */
|
||||
fun listFolder(folder: Uri): TreeListing {
|
||||
writableFolder(folder)
|
||||
return context.contentResolver.listTreeFiles(folder)
|
||||
}
|
||||
|
||||
/** Write the `.ics` [bytes] as [fileName] into [folder]; returns the name the file ended up with. */
|
||||
fun writeToFolder(folder: Uri, listing: TreeListing, fileName: String, bytes: ByteArray): String =
|
||||
context.contentResolver.writeTreeFile(folder, listing, fileName, MIME_CALENDAR, bytes)
|
||||
|
||||
/** Delete [names] from the listed folder; returns the ones that didn't go. */
|
||||
fun deleteFromFolder(listing: TreeListing, names: Collection<String>): Set<String> =
|
||||
context.contentResolver.deleteTreeFiles(listing, names)
|
||||
|
||||
private fun writableFolder(folder: Uri): DocumentFile {
|
||||
/**
|
||||
* Write [content] to [fileName] inside the persisted SAF tree [folder],
|
||||
* overwriting it if it already exists (the automatic-backup destination).
|
||||
* Requires a persisted write grant on [folder]. Throws on failure.
|
||||
*/
|
||||
fun writeToFolder(folder: Uri, fileName: String, content: String) {
|
||||
val dir = DocumentFile.fromTreeUri(context, folder)
|
||||
?: throw IOException("Backup folder is not accessible")
|
||||
if (!dir.exists() || !dir.canWrite()) {
|
||||
throw IOException("Backup folder is missing or not writable")
|
||||
}
|
||||
return dir
|
||||
// Reuse the canonical file if present and clean up any "name (1).ics"
|
||||
// duplicates SAF may have created if two runs ever raced — so we always
|
||||
// converge on a single overwritten file.
|
||||
val base = fileName.substringBeforeLast('.')
|
||||
val ext = fileName.substringAfterLast('.', "")
|
||||
var target: DocumentFile? = null
|
||||
for (child in dir.listFiles()) {
|
||||
val name = child.name ?: continue
|
||||
when {
|
||||
name == fileName -> target = child
|
||||
name.startsWith("$base (") && name.endsWith(".$ext") -> child.delete()
|
||||
}
|
||||
}
|
||||
val file = target
|
||||
?: dir.createFile(MIME_CALENDAR, fileName)
|
||||
?: throw IOException("Could not create backup file in the chosen folder")
|
||||
writeDocument(file.uri, content)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,8 +7,6 @@ import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||
import de.jeanlucmakiola.floret.prefs.stringSetPref
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -30,14 +28,9 @@ class CalendarPrefs @Inject constructor(
|
||||
) {
|
||||
private val prefs = PrefStore(store)
|
||||
|
||||
val hiddenCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.hiddenCalendarIds)
|
||||
val hiddenCalendarIds: Flow<Set<Long>> = prefs.flow(HIDDEN_IDS)
|
||||
|
||||
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(CalendarPrefKeys.hiddenCalendarIds, ids)
|
||||
|
||||
/** Rewrite the drawer's hidden set atomically from its current value. */
|
||||
suspend fun updateHiddenCalendarIds(transform: (Set<Long>) -> Set<Long>) {
|
||||
prefs.update(CalendarPrefKeys.hiddenCalendarIds, transform)
|
||||
}
|
||||
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(HIDDEN_IDS, ids)
|
||||
|
||||
/**
|
||||
* Switch-offs the provider does not know about yet, because writing
|
||||
@@ -48,10 +41,10 @@ class CalendarPrefs @Inject constructor(
|
||||
* second visibility model: `CalendarVisibilityReconciler` drains it entry by
|
||||
* entry as soon as the app may write, and nothing adds to it while it may.
|
||||
*/
|
||||
val pendingDisabledCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.pendingDisabledCalendarIds)
|
||||
val pendingDisabledCalendarIds: Flow<Set<Long>> = prefs.flow(DISABLED_IDS)
|
||||
|
||||
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it + ids }
|
||||
prefs.update(DISABLED_IDS) { it + ids }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +52,7 @@ class CalendarPrefs @Inject constructor(
|
||||
* them, so a run that fails part-way never re-applies what already landed.
|
||||
*/
|
||||
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it - ids.toSet() }
|
||||
prefs.update(DISABLED_IDS) { it - ids.toSet() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,50 +60,28 @@ class CalendarPrefs @Inject constructor(
|
||||
* owed. Null until the reconciler has evaluated it (which needs the calendar
|
||||
* permission), false once it has been shown or was never needed.
|
||||
*/
|
||||
val visibilityNoticePending: Flow<Boolean?> = prefs.flow(CalendarPrefKeys.visibilityNoticePending)
|
||||
val visibilityNoticePending: Flow<Boolean?> = prefs.flow(VISIBILITY_NOTICE)
|
||||
|
||||
suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(CalendarPrefKeys.visibilityNoticePending, pending)
|
||||
suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(VISIBILITY_NOTICE, pending)
|
||||
|
||||
/**
|
||||
* The calendar the user last created an event in; preselected in the
|
||||
* event form. Null until the first event is created.
|
||||
*/
|
||||
val lastUsedCalendarId: Flow<Long?> = prefs.flow(CalendarPrefKeys.lastUsedCalendarId)
|
||||
val lastUsedCalendarId: Flow<Long?> = prefs.flow(LAST_USED_CALENDAR)
|
||||
|
||||
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(CalendarPrefKeys.lastUsedCalendarId, id)
|
||||
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id)
|
||||
|
||||
/**
|
||||
* Synced accounts the user chose never to be asked to grant sync-request
|
||||
* access for (#240): no grant row, no "other accounts" receipt.
|
||||
*/
|
||||
val syncAccessDismissed: Flow<Set<SyncAccount>> = prefs.flow(CalendarPrefKeys.syncAccessDismissed)
|
||||
|
||||
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
|
||||
prefs.update(CalendarPrefKeys.syncAccessDismissed) { if (dismissed) it + account else it - account }
|
||||
}
|
||||
}
|
||||
|
||||
/** Every key [CalendarPrefs] stores; the names are on-disk data. */
|
||||
internal object CalendarPrefKeys {
|
||||
val hiddenCalendarIds: Pref<Set<Long>> = idSetPref("hidden_calendar_ids")
|
||||
val pendingDisabledCalendarIds: Pref<Set<Long>> = idSetPref("disabled_calendar_ids")
|
||||
val visibilityNoticePending: Pref<Boolean?> = nullableBooleanPref("visibility_notice_pending")
|
||||
val lastUsedCalendarId: Pref<Long?> = nullableLongPref("last_used_calendar_id")
|
||||
val syncAccessDismissed: Pref<Set<SyncAccount>> = stringSetPref("sync_access_dismissed").map(
|
||||
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
|
||||
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
|
||||
)
|
||||
|
||||
private const val FIELD_SEPARATOR = '\u001F'
|
||||
|
||||
private fun String.toSyncAccount(): SyncAccount? {
|
||||
val split = indexOf(FIELD_SEPARATOR)
|
||||
return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split))
|
||||
private companion object {
|
||||
val HIDDEN_IDS = idSetPref("hidden_calendar_ids")
|
||||
val DISABLED_IDS = idSetPref("disabled_calendar_ids")
|
||||
val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending")
|
||||
val LAST_USED_CALENDAR = nullableLongPref("last_used_calendar_id")
|
||||
}
|
||||
}
|
||||
|
||||
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||
)
|
||||
@@ -2,11 +2,8 @@ package de.jeanlucmakiola.calendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.floret.prefs.Pref
|
||||
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||
import java.time.LocalDate
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@@ -26,25 +23,11 @@ class ReminderStatePrefs @Inject constructor(
|
||||
private val prefs = PrefStore(store)
|
||||
|
||||
/** The watermark, or `null` before the first scan has ever run. */
|
||||
suspend fun lastScanMillis(): Long? = prefs.get(ReminderStateKeys.lastScanMillis)
|
||||
suspend fun lastScanMillis(): Long? = prefs.get(LAST_SCAN)
|
||||
|
||||
suspend fun setLastScanMillis(millis: Long) = prefs.set(ReminderStateKeys.lastScanMillis, millis)
|
||||
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
|
||||
|
||||
/**
|
||||
* The day the last daily summary listed (#459): recorded at once, so neither
|
||||
* a pass failing after posting nor a later time picked the same evening
|
||||
* lists it twice.
|
||||
*/
|
||||
suspend fun lastDigestDay(): LocalDate? =
|
||||
prefs.get(ReminderStateKeys.lastDigestDay)?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||
|
||||
suspend fun setLastDigestDay(day: LocalDate) = prefs.set(ReminderStateKeys.lastDigestDay, day.toString())
|
||||
|
||||
suspend fun clearLastDigestDay() = prefs.set(ReminderStateKeys.lastDigestDay, null)
|
||||
}
|
||||
|
||||
/** The keys [ReminderStatePrefs] stores. */
|
||||
internal object ReminderStateKeys {
|
||||
val lastScanMillis: Pref<Long?> = nullableLongPref("reminder_last_scan_millis")
|
||||
val lastDigestDay: Pref<String?> = nullableStringPref("reminder_last_digest_day")
|
||||
private companion object {
|
||||
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,10 @@
|
||||
package de.jeanlucmakiola.calendula.data.prefs
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadTimes
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupSelection
|
||||
import de.jeanlucmakiola.calendula.domain.backup.COMBINED_SERIES
|
||||
import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP
|
||||
import de.jeanlucmakiola.calendula.domain.backup.LEGACY_BACKUP_FILE
|
||||
import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey
|
||||
import de.jeanlucmakiola.calendula.domain.backup.normalizeBackupKeep
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupLedger
|
||||
import de.jeanlucmakiola.calendula.domain.backup.parseBackupLedger
|
||||
import de.jeanlucmakiola.calendula.domain.backup.persistBackupLedger
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupFingerprints
|
||||
import de.jeanlucmakiola.calendula.domain.backup.parseBackupFingerprints
|
||||
import de.jeanlucmakiola.calendula.domain.backup.persistBackupFingerprints
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.parseAlertStyles
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.toStoredAlertStyles
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DEFAULT_DIGEST_TIME_MINUTES
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.storageValue
|
||||
@@ -52,7 +29,6 @@ import de.jeanlucmakiola.floret.prefs.enumPref
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import de.jeanlucmakiola.floret.prefs.intPref
|
||||
import de.jeanlucmakiola.floret.prefs.longPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||
import de.jeanlucmakiola.floret.prefs.set
|
||||
@@ -187,15 +163,9 @@ class SettingsPrefs @Inject constructor(
|
||||
val defaultFormFields: Flow<Set<EventFormField>> = prefs.flow(SettingsKeys.defaultFormFields)
|
||||
val recentTimeZones: Flow<List<String>> = prefs.flow(SettingsKeys.recentTimeZones)
|
||||
val autofocusEventTitle: Flow<Boolean> = prefs.flow(SettingsKeys.autofocusEventTitle)
|
||||
val defaultNewEventCalendar: Flow<DefaultCalendarRef?> = prefs.flow(SettingsKeys.defaultNewEventCalendar)
|
||||
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
|
||||
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
|
||||
val perCalendarHiddenViews: Flow<Map<Long, Set<CalendarView>>> = prefs.flow(SettingsKeys.perCalendarHiddenViews)
|
||||
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
|
||||
val mutedReminderCalendarIds: Flow<Set<Long>> = prefs.flow(SettingsKeys.mutedReminderCalendarIds)
|
||||
val reminderAlertStyles: Flow<Map<Long, ReminderAlertStyle>> = prefs.flow(SettingsKeys.reminderAlertStyles)
|
||||
val notificationCategoryHintDismissed: Flow<Boolean> = prefs.flow(SettingsKeys.notificationCategoryHintDismissed)
|
||||
val reminderChannelVersions: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.reminderChannelVersions)
|
||||
val allowColorOnUnsupportedCalendars: Flow<Boolean> =
|
||||
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
|
||||
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
|
||||
@@ -206,30 +176,10 @@ class SettingsPrefs @Inject constructor(
|
||||
prefs.flow(SettingsKeys.perCalendarReminderOverride)
|
||||
val perCalendarAllDayReminderOverride: Flow<Map<Long, List<Int>>> =
|
||||
prefs.flow(SettingsKeys.perCalendarAllDayReminderOverride)
|
||||
val defaultFixedTimeReminder: Flow<FixedTimeReminder?> = prefs.flow(SettingsKeys.defaultFixedTimeReminder)
|
||||
val perCalendarFixedTimeReminderOverride: Flow<Map<Long, FixedTimeReminder?>> =
|
||||
prefs.flow(SettingsKeys.perCalendarFixedTimeReminderOverride)
|
||||
|
||||
/**
|
||||
* Every "N days before at HH:MM" the defaults name, so an offset landing on
|
||||
* one reads back as that reminder rather than a lead time (#459).
|
||||
*/
|
||||
val knownFixedTimeReminders: Flow<Set<FixedTimeReminder>> = prefs.snapshot {
|
||||
setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() +
|
||||
it[SettingsKeys.recentFixedTimeReminders]
|
||||
}
|
||||
val dailyDigest: Flow<DailyDigestSettings> = prefs.snapshot { it.dailyDigest }
|
||||
val autoBackupEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupEnabled)
|
||||
val autoBackupIntervalMinutes: Flow<Long> = prefs.flow(SettingsKeys.autoBackupIntervalMinutes)
|
||||
val autoBackupFolderUri: Flow<String?> = prefs.flow(SettingsKeys.autoBackupFolderUri)
|
||||
val autoBackupStatus: Flow<BackupStatus> = prefs.snapshot { it.autoBackupStatus }
|
||||
val autoBackupSelection: Flow<BackupSelection> = prefs.snapshot { it.autoBackupSelection }
|
||||
val autoBackupCombined: Flow<Boolean> = prefs.snapshot { it.autoBackupCombined }
|
||||
val autoBackupKeep: Flow<Int> = prefs.flow(SettingsKeys.autoBackupKeep)
|
||||
val autoBackupLedger: Flow<BackupLedger> = prefs.flow(SettingsKeys.autoBackupLedger)
|
||||
val autoBackupOnChange: Flow<Boolean> = prefs.flow(SettingsKeys.autoBackupOnChange)
|
||||
val autoBackupFingerprints: Flow<BackupFingerprints> = prefs.flow(SettingsKeys.autoBackupFingerprints)
|
||||
val specialDatesEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.specialDatesEnabled)
|
||||
val specialDatesTypes: Flow<Set<SpecialDateType>> = prefs.snapshot { it.specialDatesTypes }
|
||||
val specialDatesCalendars: Flow<Map<SpecialDateType, Long>> = prefs.snapshot { it.specialDatesCalendars }
|
||||
@@ -307,10 +257,6 @@ class SettingsPrefs @Inject constructor(
|
||||
|
||||
suspend fun setAutofocusEventTitle(enabled: Boolean) = prefs.set(SettingsKeys.autofocusEventTitle, enabled)
|
||||
|
||||
/** [calendar] null goes back to Automatic. */
|
||||
suspend fun setDefaultNewEventCalendar(calendar: DefaultCalendarRef?) =
|
||||
prefs.set(SettingsKeys.defaultNewEventCalendar, calendar)
|
||||
|
||||
suspend fun setDefaultEventDurationMinutes(minutes: Int) =
|
||||
prefs.set(SettingsKeys.defaultEventDurationMinutes, minutes)
|
||||
|
||||
@@ -325,50 +271,8 @@ class SettingsPrefs @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Show [calendarId] in every view again (#270), e.g. once it is deleted. */
|
||||
suspend fun clearCalendarHiddenViews(calendarId: Long) {
|
||||
prefs.update(SettingsKeys.perCalendarHiddenViews) { current -> current - calendarId }
|
||||
}
|
||||
|
||||
/** Hide or show [calendarId] in one [view], against the stored set rather than a snapshot of it. */
|
||||
suspend fun setCalendarHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) =
|
||||
applyCalendarHiddenChanges(calendarId, mapOf(view to hidden))
|
||||
|
||||
/** Hide (true) or show (false) [calendarId] in each view of [changes], in one write; other views keep theirs. */
|
||||
suspend fun applyCalendarHiddenChanges(calendarId: Long, changes: Map<CalendarView, Boolean>) {
|
||||
if (changes.isEmpty()) return
|
||||
prefs.update(SettingsKeys.perCalendarHiddenViews) { current ->
|
||||
val views = current[calendarId].orEmpty()
|
||||
val next = views + changes.filterValues { it }.keys - changes.filterValues { !it }.keys
|
||||
current.withHiddenViews(calendarId, next)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
|
||||
|
||||
/**
|
||||
* Reserve a new reminder channel version for each calendar in [floors], above
|
||||
* both its stored high-water mark and its floor, and return them. Versions
|
||||
* only grow: the system would restore a deleted channel's old settings if
|
||||
* its id came back (#518).
|
||||
*/
|
||||
suspend fun reserveReminderChannelVersions(floors: Map<Long, Int>): Map<Long, Int> {
|
||||
val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current ->
|
||||
current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) }
|
||||
}
|
||||
return floors.keys.associateWith { stored.getValue(it) }
|
||||
}
|
||||
|
||||
suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true)
|
||||
|
||||
suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) {
|
||||
prefs.update(SettingsKeys.reminderAlertStyles) { it + (calendarId to style) }
|
||||
}
|
||||
|
||||
suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) =
|
||||
prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled)
|
||||
|
||||
@@ -420,154 +324,12 @@ class SettingsPrefs @Inject constructor(
|
||||
suspend fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) =
|
||||
prefs.applyOverride(SettingsKeys.perCalendarAllDayReminderOverride, calendarId, override)
|
||||
|
||||
/** The replaced default stays a known pattern, so events that got it keep reading as it. */
|
||||
suspend fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) {
|
||||
prefs.edit {
|
||||
val old = it[SettingsKeys.defaultFixedTimeReminder]
|
||||
if (old != reminder) retireFixedTimeReminder(it, old)
|
||||
it[SettingsKeys.defaultFixedTimeReminder] = reminder
|
||||
}
|
||||
}
|
||||
|
||||
/** [override] [FixedTimeOverride.Inherit] drops the calendar's entry; a replaced value stays known. */
|
||||
suspend fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) {
|
||||
prefs.edit {
|
||||
val current = it[SettingsKeys.perCalendarFixedTimeReminderOverride]
|
||||
val old = current[calendarId]
|
||||
if (old != (override as? FixedTimeOverride.At)?.reminder) retireFixedTimeReminder(it, old)
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride] = when (override) {
|
||||
FixedTimeOverride.Inherit -> current - calendarId
|
||||
FixedTimeOverride.Off -> current + (calendarId to null)
|
||||
is FixedTimeOverride.At -> current + (calendarId to override.reminder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remember fixed-time reminders saved by hand (#459), so their rows read
|
||||
* back as them; the defaults are known anyway and take no slot.
|
||||
*/
|
||||
suspend fun rememberFixedTimeReminders(reminders: Collection<FixedTimeReminder>) {
|
||||
prefs.edit {
|
||||
val defaults = setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
|
||||
val fresh = reminders.filterNot { reminder -> reminder in defaults }
|
||||
if (fresh.isNotEmpty()) {
|
||||
it[SettingsKeys.recentFixedTimeReminders] = (fresh + it[SettingsKeys.recentFixedTimeReminders]).distinct()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep a default being replaced known, unless it still is a default elsewhere. */
|
||||
private fun retireFixedTimeReminder(preferences: MutablePreferences, reminder: FixedTimeReminder?) {
|
||||
if (reminder == null) return
|
||||
val defaults = listOfNotNull(preferences[SettingsKeys.defaultFixedTimeReminder]) +
|
||||
preferences[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
|
||||
if (defaults.count { it == reminder } > 1) return
|
||||
preferences[SettingsKeys.recentFixedTimeReminders] =
|
||||
(listOf(reminder) + preferences[SettingsKeys.recentFixedTimeReminders]).distinct()
|
||||
}
|
||||
|
||||
suspend fun setDailyDigestEnabled(enabled: Boolean) = editDigest { it[SettingsKeys.dailyDigestEnabled] = enabled }
|
||||
|
||||
suspend fun setDailyDigestTimeMinutes(minutesOfDay: Int) =
|
||||
editDigest { it[SettingsKeys.dailyDigestTimeMinutes] = minutesOfDay }
|
||||
|
||||
suspend fun setDailyDigestDay(day: DigestDay) = editDigest { it[SettingsKeys.dailyDigestDay] = day }
|
||||
|
||||
/**
|
||||
* Change when the summary arrives, stamping the moment: a summary whose time
|
||||
* had already passed today is not owed by the change itself.
|
||||
*/
|
||||
private suspend fun editDigest(change: (MutablePreferences) -> Unit) {
|
||||
prefs.edit {
|
||||
change(it)
|
||||
it[SettingsKeys.dailyDigestArmedAt] = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
suspend fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) {
|
||||
prefs.update(SettingsKeys.digestExcludedCalendarIds) { if (included) it - calendarId else it + calendarId }
|
||||
}
|
||||
|
||||
suspend fun setAutoBackupEnabled(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupEnabled, enabled)
|
||||
|
||||
suspend fun setAutoBackupIntervalMinutes(minutes: Long) =
|
||||
prefs.set(SettingsKeys.autoBackupIntervalMinutes, minutes)
|
||||
|
||||
/**
|
||||
* Also pins the file layout the first time it is written: an install that
|
||||
* already had a folder before #411 keeps its single combined file, a new
|
||||
* one starts on one file per calendar (see [Preferences.autoBackupCombined]).
|
||||
*/
|
||||
suspend fun setAutoBackupFolderUri(uri: String?) {
|
||||
prefs.edit {
|
||||
it.pinBackupLayout()
|
||||
// The ledger says which files in the old folder are ours; in a new
|
||||
// one a file of the same name may be the user's.
|
||||
if (it[SettingsKeys.autoBackupFolderUri] != uri) {
|
||||
it[SettingsKeys.autoBackupLedger] = emptyMap()
|
||||
it[SettingsKeys.autoBackupFingerprints] = emptyMap()
|
||||
}
|
||||
it[SettingsKeys.autoBackupFolderUri] = uri
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setAutoBackupCombined(combined: Boolean) {
|
||||
prefs.edit {
|
||||
it.pinBackupLayout()
|
||||
it[SettingsKeys.autoBackupCombinedStored] = combined
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setAutoBackupKeep(keep: Int) = prefs.set(SettingsKeys.autoBackupKeep, keep)
|
||||
|
||||
suspend fun setAutoBackupOnChange(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupOnChange, enabled)
|
||||
|
||||
/**
|
||||
* Atomic, so a run's ledger writes never undo one made meanwhile (pinning
|
||||
* the layout). Dropped when the folder is no longer [folder]: a run still
|
||||
* finishing must not carry the old folder's names into the new one's ledger.
|
||||
* [fingerprints] updates the series' hashes (#516) in the same edit.
|
||||
*/
|
||||
suspend fun updateAutoBackupLedger(
|
||||
folder: String,
|
||||
fingerprints: ((BackupFingerprints) -> BackupFingerprints)? = null,
|
||||
transform: (BackupLedger) -> BackupLedger,
|
||||
) {
|
||||
prefs.edit {
|
||||
if (it[SettingsKeys.autoBackupFolderUri] == folder) {
|
||||
it[SettingsKeys.autoBackupLedger] = transform(it[SettingsKeys.autoBackupLedger])
|
||||
if (fingerprints != null) {
|
||||
it[SettingsKeys.autoBackupFingerprints] = fingerprints(it[SettingsKeys.autoBackupFingerprints])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Like [updateAutoBackupLedger], for the series' hashes (#516) alone. */
|
||||
suspend fun updateAutoBackupFingerprints(folder: String, transform: (BackupFingerprints) -> BackupFingerprints) {
|
||||
prefs.edit {
|
||||
if (it[SettingsKeys.autoBackupFolderUri] == folder) {
|
||||
it[SettingsKeys.autoBackupFingerprints] = transform(it[SettingsKeys.autoBackupFingerprints])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Record a pre-#411 install's old file as its combined series' stable copy (see [pinBackupLayout]). */
|
||||
suspend fun adoptLegacyBackupFile() {
|
||||
prefs.edit { if (it.autoBackupLegacyInstall) it.adoptLegacyBackupFile() }
|
||||
}
|
||||
|
||||
/** Switch [calendar] in or out of the automatic backup (#147). */
|
||||
suspend fun setAutoBackupCalendar(calendar: CalendarSource, included: Boolean) {
|
||||
prefs.edit {
|
||||
val next = it.autoBackupSelection.with(calendar, included)
|
||||
it[SettingsKeys.autoBackupIncluded] = next.included
|
||||
it[SettingsKeys.autoBackupExcluded] = next.excluded
|
||||
}
|
||||
}
|
||||
suspend fun setAutoBackupFolderUri(uri: String?) = prefs.set(SettingsKeys.autoBackupFolderUri, uri)
|
||||
|
||||
/** Record an automatic run's outcome; resets the failure streak on success. */
|
||||
suspend fun recordAutoBackupRun(success: Boolean, atMillis: Long) {
|
||||
@@ -611,7 +373,6 @@ class SettingsPrefs @Inject constructor(
|
||||
/** 09:00 as minutes from midnight; the default all-day reminder fire time. */
|
||||
internal const val DEFAULT_ALLDAY_REMINDER_TIME = 540
|
||||
internal const val MINUTES_PER_DAY = 1_440
|
||||
internal const val MAX_RECENT_FIXED_TIME_REMINDERS = 12
|
||||
/** Default snooze delay for the notification "Snooze" action. */
|
||||
const val DEFAULT_SNOOZE_MINUTES = 10
|
||||
const val DEFAULT_MULTI_DAY_COUNT = 3
|
||||
@@ -809,14 +570,6 @@ object SettingsKeys {
|
||||
*/
|
||||
val autofocusEventTitle: Pref<Boolean> = booleanPref("autofocus_event_title", true)
|
||||
|
||||
/**
|
||||
* The calendar new events open in (#429); null is Automatic (the last-used
|
||||
* calendar). Kept when the calendar stops being a target, which only makes
|
||||
* it fall back for as long as that lasts.
|
||||
*/
|
||||
val defaultNewEventCalendar: Pref<DefaultCalendarRef?> =
|
||||
nullableStringPref("default_new_event_calendar").map(DefaultCalendarRef::decode) { it?.encode() }
|
||||
|
||||
/**
|
||||
* How long a new **timed** event lasts, in minutes (#54). Per-calendar
|
||||
* overrides in [perCalendarEventDuration] take precedence; all-day events
|
||||
@@ -835,46 +588,12 @@ object SettingsKeys {
|
||||
val perCalendarEventDuration: Pref<Map<Long, Int>> =
|
||||
nullableStringPref("per_calendar_event_duration").map(::parseDurationOverrides) { it.toStoredDurations() }
|
||||
|
||||
/**
|
||||
* Views each calendar is hidden in (#270): a display-only filter on top of
|
||||
* `Calendars.VISIBLE` and the drawer's filter, so reminders and search never
|
||||
* see it. A calendar absent shows in every view. Serialised as
|
||||
* `id=Month,Agenda;id=Week`.
|
||||
*/
|
||||
val perCalendarHiddenViews: Pref<Map<Long, Set<CalendarView>>> =
|
||||
nullableStringPref("per_calendar_hidden_views").map(::parseHiddenViews) { it.toStoredHiddenViews() }
|
||||
|
||||
/**
|
||||
* Whether Calendula posts reminder notifications (v1.4). On by default — for
|
||||
* users whose only calendar app this is, reminders are essential.
|
||||
*/
|
||||
val remindersEnabled: Pref<Boolean> = booleanPref("reminders_enabled", true)
|
||||
|
||||
/**
|
||||
* Calendars whose reminders Calendula doesn't post (#272), independent of
|
||||
* `Calendars.VISIBLE`: the events still show, only the notifications stop.
|
||||
*/
|
||||
val mutedReminderCalendarIds: Pref<Set<Long>> = idSetPref("muted_reminder_calendar_ids")
|
||||
|
||||
/** Per-calendar alert styles (#171); a calendar absent from the map uses plain notifications. */
|
||||
val reminderAlertStyles: Pref<Map<Long, ReminderAlertStyle>> =
|
||||
nullableStringPref("reminder_alert_styles").map(::parseAlertStyles) { it.toStoredAlertStyles() }
|
||||
|
||||
/**
|
||||
* Whether the one-time hint that some skins (Samsung) start new notification
|
||||
* categories switched off has been dismissed (#145).
|
||||
*/
|
||||
val notificationCategoryHintDismissed: Pref<Boolean> = booleanPref("notification_category_hint_dismissed", false)
|
||||
|
||||
/**
|
||||
* The highest reminder channel version handed out per calendar (#518): a
|
||||
* sound picked in the app recreates the channel under a new one. The
|
||||
* channels themselves say which version is current; this only keeps ids
|
||||
* from being reused. Serialised as `id=version;id=version`.
|
||||
*/
|
||||
val reminderChannelVersions: Pref<Map<Long, Int>> =
|
||||
nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() }
|
||||
|
||||
/**
|
||||
* Whether to offer a custom event colour on calendars that publish no colour
|
||||
* palette; synced ones without a palette (some CalDAV) may drop or overwrite
|
||||
@@ -929,8 +648,7 @@ object SettingsKeys {
|
||||
* before the start of the day — day-scale ("1 day before"), so separate from
|
||||
* the timed default.
|
||||
*/
|
||||
val defaultAllDayReminderMinutes: Pref<List<Int>> =
|
||||
reminderListPref("default_allday_reminder_minutes", wholeDays = true)
|
||||
val defaultAllDayReminderMinutes: Pref<List<Int>> = reminderListPref("default_allday_reminder_minutes")
|
||||
|
||||
/**
|
||||
* Wall-clock time, as minutes from local midnight, at which **all-day**
|
||||
@@ -963,49 +681,7 @@ object SettingsKeys {
|
||||
|
||||
/** Per-calendar overrides of [defaultAllDayReminderMinutes], as [perCalendarReminderOverride]. */
|
||||
val perCalendarAllDayReminderOverride: Pref<Map<Long, List<Int>>> =
|
||||
reminderOverridePref("per_calendar_allday_reminder_override", wholeDays = true)
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" reminder added to new **timed** events
|
||||
* (#459), or null for none — the factory default. Stored as `days@minute`.
|
||||
*/
|
||||
val defaultFixedTimeReminder: Pref<FixedTimeReminder?> =
|
||||
nullableStringPref("default_fixed_time_reminder").map(FixedTimeReminder::parse) { it?.toToken() }
|
||||
|
||||
/**
|
||||
* Per-calendar overrides of [defaultFixedTimeReminder]: present with a
|
||||
* value replaces it, present as null turns it off, absent inherits.
|
||||
* Serialised as `id=days@minute` or `id=none`, joined by `;`.
|
||||
*/
|
||||
val perCalendarFixedTimeReminderOverride: Pref<Map<Long, FixedTimeReminder?>> =
|
||||
nullableStringPref("per_calendar_fixed_time_reminder").map(::parseFixedTimeOverrides) {
|
||||
it.toStoredFixedTimeOverrides()
|
||||
}
|
||||
|
||||
/** The daily summary notification (#459): opt-in, and which day it lists at what time. */
|
||||
val dailyDigestEnabled: Pref<Boolean> = booleanPref("daily_digest_enabled", false)
|
||||
val dailyDigestTimeMinutes: Pref<Int> =
|
||||
intPref("daily_digest_time_minutes", DEFAULT_DIGEST_TIME_MINUTES).coerced {
|
||||
it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1)
|
||||
}
|
||||
val dailyDigestDay: Pref<DigestDay> = enumPref("daily_digest_day", DigestDay.Tomorrow)
|
||||
|
||||
/** Calendars left out of the daily summary; every other one is in. */
|
||||
val digestExcludedCalendarIds: Pref<Set<Long>> = idSetPref("digest_excluded_calendar_ids")
|
||||
|
||||
/** When the summary's switch, time or day last changed; a moment before it is never owed. */
|
||||
val dailyDigestArmedAt: Pref<Long> = longPref("daily_digest_armed_at", 0L)
|
||||
|
||||
/**
|
||||
* Fixed-time reminders last saved by hand, and defaults since replaced,
|
||||
* newest first — with the current defaults, the patterns a stored offset is
|
||||
* recognised as. Capped, so the oldest falls out of recognition.
|
||||
*/
|
||||
val recentFixedTimeReminders: Pref<List<FixedTimeReminder>> =
|
||||
nullableStringPref("recent_fixed_time_reminders").map(
|
||||
{ stored -> stored?.split(LIST_SEP).orEmpty().mapNotNull(FixedTimeReminder::parse).distinct() },
|
||||
{ reminders -> reminders.take(SettingsPrefs.MAX_RECENT_FIXED_TIME_REMINDERS).joinToString(LIST_SEP) { it.toToken() } },
|
||||
)
|
||||
reminderOverridePref("per_calendar_allday_reminder_override")
|
||||
|
||||
/** Whether periodic automatic `.ics` export of local calendars is on (issue #8). */
|
||||
val autoBackupEnabled: Pref<Boolean> = booleanPref("auto_backup_enabled", false)
|
||||
@@ -1024,34 +700,6 @@ object SettingsKeys {
|
||||
val autoBackupLastSuccess: Pref<Boolean> = booleanPref("auto_backup_last_success", true)
|
||||
val autoBackupFailures: Pref<Int> = intPref("auto_backup_failures", 0)
|
||||
|
||||
/**
|
||||
* The automatic backup's calendar choice as deviations from the default
|
||||
* (#147), read together as [Preferences.autoBackupSelection].
|
||||
*/
|
||||
val autoBackupIncluded: Pref<Set<Long>> = idSetPref("auto_backup_included_calendars")
|
||||
val autoBackupExcluded: Pref<Set<Long>> = idSetPref("auto_backup_excluded_calendars")
|
||||
|
||||
/**
|
||||
* Whether the automatic backup writes one combined file instead of one per
|
||||
* calendar (#411). Unset until first pinned; read as [Preferences.autoBackupCombined].
|
||||
*/
|
||||
val autoBackupCombinedStored: Pref<Boolean?> = nullableBooleanPref("auto_backup_combined")
|
||||
|
||||
/** How many files of each backup series to keep (#411). */
|
||||
val autoBackupKeep: Pref<Int> =
|
||||
intPref("auto_backup_keep", DEFAULT_BACKUP_KEEP).coerced(::normalizeBackupKeep)
|
||||
|
||||
/** The files the automatic backup wrote, per series; the only ones it ever prunes (#411). */
|
||||
val autoBackupLedger: Pref<BackupLedger> =
|
||||
nullableStringPref("auto_backup_files").map(::parseBackupLedger, ::persistBackupLedger)
|
||||
|
||||
/** 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)
|
||||
|
||||
/** Content hash of each series' stable copy, so a change run skips untouched ones (#516). */
|
||||
val autoBackupFingerprints: Pref<BackupFingerprints> =
|
||||
nullableStringPref("auto_backup_fingerprints").map(::parseBackupFingerprints, ::persistBackupFingerprints)
|
||||
|
||||
/** Master switch for the contact special-dates mirror (issue #15). Opt-in. */
|
||||
val specialDatesEnabled: Pref<Boolean> = booleanPref("special_dates_enabled", false)
|
||||
|
||||
@@ -1101,42 +749,6 @@ val Preferences.autoBackupStatus: BackupStatus
|
||||
consecutiveFailures = this[SettingsKeys.autoBackupFailures],
|
||||
)
|
||||
|
||||
val Preferences.autoBackupSelection: BackupSelection
|
||||
get() = BackupSelection(
|
||||
included = this[SettingsKeys.autoBackupIncluded],
|
||||
excluded = this[SettingsKeys.autoBackupExcluded],
|
||||
)
|
||||
|
||||
/**
|
||||
* 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
|
||||
* files. Choosing a folder pins the answer (see [SettingsPrefs.setAutoBackupFolderUri]).
|
||||
*/
|
||||
val Preferences.autoBackupCombined: Boolean
|
||||
get() = this[SettingsKeys.autoBackupCombinedStored] ?: autoBackupLegacyInstall
|
||||
|
||||
/**
|
||||
* Store the layout the install is on, if it's still derived. Pinning forgets
|
||||
* it was a pre-#411 install, so its old file is recorded as the combined
|
||||
* series' own stable copy at the same time.
|
||||
*/
|
||||
private fun MutablePreferences.pinBackupLayout() {
|
||||
if (this[SettingsKeys.autoBackupCombinedStored] != null) return
|
||||
val legacy = autoBackupLegacyInstall
|
||||
if (legacy) adoptLegacyBackupFile()
|
||||
this[SettingsKeys.autoBackupCombinedStored] = legacy
|
||||
}
|
||||
|
||||
private fun MutablePreferences.adoptLegacyBackupFile() {
|
||||
val key = latestLedgerKey(COMBINED_SERIES)
|
||||
val ledger = this[SettingsKeys.autoBackupLedger]
|
||||
this[SettingsKeys.autoBackupLedger] = ledger + (key to (ledger[key].orEmpty() + LEGACY_BACKUP_FILE).distinct())
|
||||
}
|
||||
|
||||
/** An install that set up automatic backup before #411 and hasn't been pinned since. */
|
||||
val Preferences.autoBackupLegacyInstall: Boolean
|
||||
get() = this[SettingsKeys.autoBackupCombinedStored] == null && this[SettingsKeys.autoBackupFolderUri] != null
|
||||
|
||||
val Preferences.specialDatesTypes: Set<SpecialDateType>
|
||||
get() = SettingsKeys.specialDateTypeEnabled.filterValues { this[it] }.keys
|
||||
|
||||
@@ -1173,24 +785,11 @@ private fun <T> Pref<T>.coerced(clamp: (T) -> T): Pref<T> = map(clamp, clamp)
|
||||
private fun agendaRangePref(name: String): Pref<AgendaRange> =
|
||||
nullableStringPref(name).map({ parseAgendaRange(it, AgendaRange.Month) }, { it.storageValue() })
|
||||
|
||||
/**
|
||||
* [wholeDays] reads an all-day list as the whole days it fires at, so a sub-day
|
||||
* value stored before the all-day pickers were limited to days shows truthfully.
|
||||
*/
|
||||
private fun reminderListPref(name: String, wholeDays: Boolean = false): Pref<List<Int>> =
|
||||
nullableStringPref(name).map(
|
||||
{ stored -> stored.toReminderList().let { if (wholeDays) wholeDayLeadTimes(it) else it } },
|
||||
{ it.toStoredReminders() },
|
||||
)
|
||||
private fun reminderListPref(name: String): Pref<List<Int>> =
|
||||
nullableStringPref(name).map({ it.toReminderList() }, { it.toStoredReminders() })
|
||||
|
||||
private fun reminderOverridePref(name: String, wholeDays: Boolean = false): Pref<Map<Long, List<Int>>> =
|
||||
nullableStringPref(name).map(
|
||||
{ stored ->
|
||||
reminderOverrideCodec.parse(stored)
|
||||
.let { map -> if (wholeDays) map.mapValues { wholeDayLeadTimes(it.value) } else map }
|
||||
},
|
||||
reminderOverrideCodec::serialize,
|
||||
)
|
||||
private fun reminderOverridePref(name: String): Pref<Map<Long, List<Int>>> =
|
||||
nullableStringPref(name).map(reminderOverrideCodec::parse, reminderOverrideCodec::serialize)
|
||||
|
||||
private suspend fun PrefStore.applyOverride(
|
||||
pref: Pref<Map<Long, List<Int>>>,
|
||||
@@ -1218,11 +817,9 @@ private fun parseFormFields(stored: String?): Set<EventFormField> = when (stored
|
||||
private fun parseViewOrder(stored: String?): List<CalendarView> =
|
||||
completeViewOrder(
|
||||
stored?.split(',').orEmpty()
|
||||
.mapNotNull { it.trim().toCalendarViewOrNull() },
|
||||
.mapNotNull { name -> CalendarView.entries.firstOrNull { it.name == name.trim() } },
|
||||
)
|
||||
|
||||
private fun String.toCalendarViewOrNull(): CalendarView? = CalendarView.entries.firstOrNull { it.name == this }
|
||||
|
||||
/** Parse the quick-switch config; "!"-prefixed names are disabled. */
|
||||
private fun parseQuickSwitch(stored: String?): QuickSwitchConfig {
|
||||
if (stored == null) return QuickSwitchConfig.Default
|
||||
@@ -1230,7 +827,7 @@ private fun parseQuickSwitch(stored: String?): QuickSwitchConfig {
|
||||
val token = raw.trim()
|
||||
val disabled = token.startsWith("!")
|
||||
val name = if (disabled) token.drop(1) else token
|
||||
name.toCalendarViewOrNull()?.let { it to disabled }
|
||||
CalendarView.entries.firstOrNull { it.name == name }?.let { it to disabled }
|
||||
}
|
||||
val order = completeViewOrder(parsed.map { it.first })
|
||||
// Only views explicitly stored disabled are excluded; anything appended
|
||||
@@ -1282,57 +879,6 @@ data class BackupStatus(
|
||||
val consecutiveFailures: Int,
|
||||
)
|
||||
|
||||
/** The daily summary's settings, read together. */
|
||||
internal val Preferences.dailyDigest: DailyDigestSettings
|
||||
get() = DailyDigestSettings(
|
||||
enabled = this[SettingsKeys.dailyDigestEnabled],
|
||||
timeMinutes = this[SettingsKeys.dailyDigestTimeMinutes],
|
||||
day = this[SettingsKeys.dailyDigestDay],
|
||||
excludedCalendarIds = this[SettingsKeys.digestExcludedCalendarIds],
|
||||
armedAtMillis = this[SettingsKeys.dailyDigestArmedAt],
|
||||
)
|
||||
|
||||
/** A calendar's choice for the fixed-time default, as a picker returns it. */
|
||||
sealed interface FixedTimeOverride {
|
||||
data object Inherit : FixedTimeOverride
|
||||
data object Off : FixedTimeOverride
|
||||
data class At(val reminder: FixedTimeReminder) : FixedTimeOverride
|
||||
}
|
||||
|
||||
/** [calendarId]'s entry read as a [FixedTimeOverride]. */
|
||||
fun Map<Long, FixedTimeReminder?>.fixedTimeOverrideFor(calendarId: Long): FixedTimeOverride = when {
|
||||
!containsKey(calendarId) -> FixedTimeOverride.Inherit
|
||||
else -> getValue(calendarId)?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off
|
||||
}
|
||||
|
||||
/** The fixed-time reminder a new timed event on [calendarId] gets, or null for none. */
|
||||
fun resolveDefaultFixedTimeReminder(
|
||||
global: FixedTimeReminder?,
|
||||
overrides: Map<Long, FixedTimeReminder?>,
|
||||
calendarId: Long?,
|
||||
): FixedTimeReminder? =
|
||||
if (calendarId != null && overrides.containsKey(calendarId)) overrides[calendarId] else global
|
||||
|
||||
private fun parseFixedTimeOverrides(stored: String?): Map<Long, FixedTimeReminder?> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val value = parts[1].trim()
|
||||
if (value == NONE) return@mapNotNull calendarId to null
|
||||
val reminder = FixedTimeReminder.parse(value) ?: return@mapNotNull null
|
||||
calendarId to reminder
|
||||
}.toMap()
|
||||
|
||||
private fun Map<Long, FixedTimeReminder?>.toStoredFixedTimeOverrides(): String? =
|
||||
if (isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, reminder) ->
|
||||
"$id$KEY_VALUE_SEP${reminder?.toToken() ?: NONE}"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lead times to prefill on a new event: the matching per-calendar override
|
||||
* if [calendarId] has one for this event kind, otherwise the global default for
|
||||
@@ -1431,45 +977,6 @@ private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
|
||||
calendarId to minutes
|
||||
}.toMap()
|
||||
|
||||
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
|
||||
calendarId to version
|
||||
}.toMap()
|
||||
|
||||
private fun Map<Long, Int>.toStoredVersions(): String? =
|
||||
if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" }
|
||||
|
||||
/**
|
||||
* Parse the per-calendar hidden-views map (`id=View,View` entries joined by `;`).
|
||||
* Unknown view names and malformed entries are dropped; an entry left with no
|
||||
* views is dropped with them.
|
||||
*/
|
||||
internal fun parseHiddenViews(stored: String?): Map<Long, Set<CalendarView>> =
|
||||
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(KEY_VALUE_SEP)
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val views = parts[1].split(LIST_SEP)
|
||||
.mapNotNullTo(mutableSetOf()) { it.trim().toCalendarViewOrNull() }
|
||||
if (views.isEmpty()) null else calendarId to views
|
||||
}.toMap()
|
||||
|
||||
private fun Map<Long, Set<CalendarView>>.withHiddenViews(
|
||||
calendarId: Long,
|
||||
views: Set<CalendarView>,
|
||||
): Map<Long, Set<CalendarView>> = if (views.isEmpty()) this - calendarId else this + (calendarId to views)
|
||||
|
||||
internal fun Map<Long, Set<CalendarView>>.toStoredHiddenViews(): String? =
|
||||
entries.filter { it.value.isNotEmpty() }.sortedBy { it.key }
|
||||
.joinToString(ENTRY_SEP) { (id, views) ->
|
||||
"$id$KEY_VALUE_SEP" + views.sortedBy { it.ordinal }.joinToString(LIST_SEP) { it.name }
|
||||
}
|
||||
.ifEmpty { null }
|
||||
|
||||
private fun Map<Long, Int>.toStoredDurations(): String =
|
||||
entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) ->
|
||||
"$id$KEY_VALUE_SEP$minutes"
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.MainActivity
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.datetime.isoDayNumber
|
||||
import kotlinx.datetime.toKotlinLocalDate
|
||||
import java.time.DayOfWeek
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts the daily summary (#459): one notification listing a day's events, on
|
||||
* its own channel, replacing the one before it. Tapping opens that day.
|
||||
*/
|
||||
@Singleton
|
||||
class DailyDigestNotifier @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Post the summary of [day] listing [listed], or withdraw the last one when
|
||||
* there is nothing to list — yesterday's would otherwise stand in for it.
|
||||
*/
|
||||
suspend fun post(day: LocalDate, listed: List<ReminderEventInstance>) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
if (listed.isEmpty()) {
|
||||
manager.cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||
return
|
||||
}
|
||||
ensureChannel()
|
||||
val zone = ZoneId.systemDefault()
|
||||
val locale = Locale.getDefault()
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
val today = LocalDate.now(zone)
|
||||
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
|
||||
// The date rides along: the summary stays up into the day it lists,
|
||||
// when "Tomorrow" alone would point at the wrong one.
|
||||
val date = DateTimeFormatter.ofPattern(
|
||||
android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEdMMM"),
|
||||
locale,
|
||||
).format(day)
|
||||
val dayLabel = when (day) {
|
||||
today -> context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_today), date)
|
||||
today.plusDays(1) ->
|
||||
context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_tomorrow), date)
|
||||
else -> date
|
||||
}
|
||||
val allDay = context.getString(R.string.event_detail_all_day)
|
||||
val lines = listed.map { entry ->
|
||||
// Read against the listed day, so a timed event on it shows its bare
|
||||
// range and one crossing midnight its dates.
|
||||
val time = if (entry.isAllDay) allDay else reminderTimeText(
|
||||
beginMillis = entry.beginMillis,
|
||||
endMillis = entry.endMillis,
|
||||
isAllDay = entry.isAllDay,
|
||||
zone = zone,
|
||||
locale = locale,
|
||||
is24Hour = is24Hour,
|
||||
today = day,
|
||||
firstDayOfWeek = firstDayOfWeek,
|
||||
todayLabel = allDay,
|
||||
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
context.getString(R.string.digest_line, time, entry.title.ifBlank { context.getString(R.string.event_untitled) })
|
||||
}
|
||||
val title = context.resources.getQuantityString(R.plurals.digest_title, listed.size, dayLabel, listed.size)
|
||||
val style = NotificationCompat.InboxStyle().setBigContentTitle(title)
|
||||
lines.take(MAX_LINES).forEach(style::addLine)
|
||||
if (lines.size > MAX_LINES) {
|
||||
val more = lines.size - MAX_LINES
|
||||
style.setSummaryText(context.resources.getQuantityString(R.plurals.digest_more, more, more))
|
||||
}
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(listed.joinToString(", ") { it.title.ifBlank { context.getString(R.string.event_untitled) } })
|
||||
.setStyle(style)
|
||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||
.setAutoCancel(true)
|
||||
// Gone once its day is over; "Tomorrow" would read wrong by then anyway.
|
||||
.setTimeoutAfter(
|
||||
(day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - System.currentTimeMillis())
|
||||
.coerceAtLeast(1L),
|
||||
)
|
||||
.setContentIntent(openDay(day))
|
||||
.build()
|
||||
try {
|
||||
manager.notify(TAG_DIGEST, NOTIFICATION_ID, notification)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Could not post the daily summary", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the summary's own channel is switched off in the system settings. */
|
||||
fun isChannelOff(): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)
|
||||
.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||
|
||||
/** Withdraw the summary showing, if any. */
|
||||
fun cancel() {
|
||||
NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||
}
|
||||
|
||||
/** The summary's channel id, created if missing — for the settings deep-link. */
|
||||
fun channelId(): String {
|
||||
ensureChannel()
|
||||
return CHANNEL_ID
|
||||
}
|
||||
|
||||
/** Creates the channel, or renames it after a language change; the user's settings on it stay. */
|
||||
private fun ensureChannel() {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.digest_channel_name),
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply { description = context.getString(R.string.digest_channel_description) },
|
||||
)
|
||||
}
|
||||
|
||||
private fun openDay(day: LocalDate): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
REQUEST_CODE,
|
||||
MainActivity.openDayIntent(context, day.toKotlinLocalDate()),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val TAG = "DailyDigestNotifier"
|
||||
const val CHANNEL_ID = "daily_digest"
|
||||
const val TAG_DIGEST = "daily_digest"
|
||||
const val NOTIFICATION_ID = 2
|
||||
const val REQUEST_CODE = 0xD16E
|
||||
const val MAX_LINES = 6
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* What the full-screen alerts (#171) share within the process: the reminder
|
||||
* [ReminderRingService] is ringing for, and the reminders just dismissed or
|
||||
* snoozed, so an alert screen showing one closes whichever way it was handled.
|
||||
*/
|
||||
@Singleton
|
||||
class FullScreenAlerts @Inject constructor() {
|
||||
|
||||
/** Written only by [ReminderRingService], on the main thread, for as long as it rings. */
|
||||
@Volatile
|
||||
var ringing: ReminderAlert? = null
|
||||
internal set
|
||||
|
||||
/** Rings handed to [ReminderRingService] that have not reached it yet, with how many starts each. */
|
||||
private val pending = ConcurrentHashMap<Long, Pair<ReminderAlert, Int>>()
|
||||
|
||||
/** Set when the service is stopped from outside but its ring should go back to the shade. */
|
||||
@Volatile
|
||||
internal var handBackOnDestroy = false
|
||||
|
||||
internal fun addPending(alert: ReminderAlert) {
|
||||
pending.compute(alert.key) { _, entry -> alert to ((entry?.second ?: 0) + 1) }
|
||||
}
|
||||
|
||||
internal fun removePending(alert: ReminderAlert) {
|
||||
pending.computeIfPresent(alert.key) { _, entry -> if (entry.second <= 1) null else entry.first to entry.second - 1 }
|
||||
}
|
||||
|
||||
internal fun isPending(alert: ReminderAlert): Boolean = pending.containsKey(alert.key)
|
||||
|
||||
internal val anyPending: Boolean get() = pending.isNotEmpty()
|
||||
|
||||
/**
|
||||
* Whether a ring going or on its way [match]es, so a stop is worth sending.
|
||||
* Pending first: the service sets [ringing] before it lets a start go.
|
||||
*/
|
||||
fun mayRing(match: RingMatch): Boolean =
|
||||
pending.values.any { match.matches(it.first) } || ringing?.let(match::matches) == true
|
||||
|
||||
private val handledKeys = MutableSharedFlow<Long>(
|
||||
extraBufferCapacity = 8,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
/** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */
|
||||
val handled: SharedFlow<Long> = handledKeys.asSharedFlow()
|
||||
|
||||
fun markHandled(alert: ReminderAlert) {
|
||||
handledKeys.tryEmit(alert.key)
|
||||
}
|
||||
}
|
||||
|
||||
/** What becomes of a ring once its settings are re-read. */
|
||||
enum class RingVerdict { Ring, HandBack, Drop }
|
||||
|
||||
/** Which ring a stop is for. */
|
||||
sealed interface RingMatch {
|
||||
fun matches(alert: ReminderAlert): Boolean
|
||||
|
||||
data class Key(val key: Long) : RingMatch {
|
||||
override fun matches(alert: ReminderAlert) = alert.key == key
|
||||
}
|
||||
|
||||
data class Occurrence(val occurrenceKey: Long) : RingMatch {
|
||||
override fun matches(alert: ReminderAlert) = alert.occurrenceKey == occurrenceKey
|
||||
}
|
||||
|
||||
data class Calendar(val calendarId: Long) : RingMatch {
|
||||
override fun matches(alert: ReminderAlert) = alert.calendarId == calendarId
|
||||
}
|
||||
|
||||
data object Any : RingMatch {
|
||||
override fun matches(alert: ReminderAlert) = true
|
||||
}
|
||||
}
|
||||
+11
-20
@@ -13,8 +13,8 @@ import javax.inject.Inject
|
||||
/**
|
||||
* Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus
|
||||
* the internal re-show when a snooze elapses. All three are app-internal
|
||||
* intents (notification action buttons, the full-screen alert's buttons and
|
||||
* our own [ReminderSnoozeScheduler] alarm), so the receiver is not exported.
|
||||
* intents (notification action buttons and our own [ReminderSnoozeScheduler]
|
||||
* alarm), so the receiver is not exported.
|
||||
*
|
||||
* - **Dismiss** just cancels the notification — the scan's watermark has moved
|
||||
* past this reminder, so nothing re-posts it.
|
||||
@@ -74,9 +74,6 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
*/
|
||||
const val ACTION_OPEN = "de.jeanlucmakiola.calendula.reminders.OPEN"
|
||||
|
||||
/** Not handled here either: the slot of the full-screen alert's own intent (#171). */
|
||||
const val ACTION_ALERT_SCREEN = "de.jeanlucmakiola.calendula.reminders.ALERT_SCREEN"
|
||||
|
||||
private const val EXTRA_ALERT_KEY = "alert_key"
|
||||
private const val EXTRA_EVENT_ID = "event_id"
|
||||
private const val EXTRA_CALENDAR_ID = "calendar_id"
|
||||
@@ -97,21 +94,16 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
Intent(context, ReminderActionReceiver::class.java).apply {
|
||||
this.action = action
|
||||
data = "calendula://reminder/${identity(alert, action)}".toUri()
|
||||
putAlert(alert)
|
||||
putExtra(EXTRA_ALERT_KEY, alert.key)
|
||||
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
||||
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
||||
putExtra(EXTRA_BEGIN, alert.beginMillis)
|
||||
putExtra(EXTRA_END, alert.endMillis)
|
||||
putExtra(EXTRA_TITLE, alert.title)
|
||||
putExtra(EXTRA_LOCATION, alert.location)
|
||||
putExtra(EXTRA_ALL_DAY, alert.isAllDay)
|
||||
}
|
||||
|
||||
/** Carries [alert] as extras, for [alertFrom] to read back. */
|
||||
fun Intent.putAlert(alert: ReminderAlert): Intent = apply {
|
||||
putExtra(EXTRA_ALERT_KEY, alert.key)
|
||||
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
||||
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
||||
putExtra(EXTRA_BEGIN, alert.beginMillis)
|
||||
putExtra(EXTRA_END, alert.endMillis)
|
||||
putExtra(EXTRA_TITLE, alert.title)
|
||||
putExtra(EXTRA_LOCATION, alert.location)
|
||||
putExtra(EXTRA_ALL_DAY, alert.isAllDay)
|
||||
}
|
||||
|
||||
/**
|
||||
* A stable request code per (alert, action), so one notification's
|
||||
* PendingIntents stay distinct. The shift keeps the action slot intact;
|
||||
@@ -123,7 +115,6 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
ACTION_DISMISS -> 2
|
||||
ACTION_SHOW -> 3
|
||||
ACTION_OPEN -> 4
|
||||
ACTION_ALERT_SCREEN -> 5
|
||||
else -> 0
|
||||
}
|
||||
return (identity(alert, action).toInt() shl 3) + actionOffset
|
||||
@@ -132,7 +123,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
private fun identity(alert: ReminderAlert, action: String): Long =
|
||||
if (action == ACTION_SHOW) alert.occurrenceKey else alert.key
|
||||
|
||||
fun alertFrom(intent: Intent): ReminderAlert? {
|
||||
private fun alertFrom(intent: Intent): ReminderAlert? {
|
||||
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
|
||||
return ReminderAlert(
|
||||
key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L),
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
|
||||
/** The single channel every reminder posted on before they moved per calendar (#145). */
|
||||
const val LEGACY_REMINDER_CHANNEL_ID = "reminders"
|
||||
|
||||
/** The silent channel ringing full-screen alerts post on (#171); outside the per-calendar namespace. */
|
||||
const val RING_CHANNEL_ID = "reminders_ring"
|
||||
|
||||
private const val CHANNEL_PREFIX = "reminders.calendar."
|
||||
private const val GROUP_PREFIX = "reminders.account."
|
||||
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
|
||||
|
||||
private const val VERSION_SEPARATOR = ".v"
|
||||
|
||||
/**
|
||||
* The notification channel [calendarId]'s reminders post on. A sound picked in
|
||||
* the app moves it to a new [version] (#518), since a channel's sound is fixed
|
||||
* once created; version 0 is the unversioned id #145 introduced.
|
||||
*/
|
||||
fun reminderChannelId(calendarId: Long, version: Int = 0): String =
|
||||
if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version"
|
||||
|
||||
/** The calendar and version a reminder channel id names, or null for any other id. */
|
||||
fun parseReminderChannelId(channelId: String): Pair<Long, Int>? {
|
||||
if (!isReminderChannelId(channelId)) return null
|
||||
val rest = channelId.removePrefix(CHANNEL_PREFIX)
|
||||
val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null
|
||||
if (VERSION_SEPARATOR !in rest) return calendar to 0
|
||||
val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return calendar to version
|
||||
}
|
||||
|
||||
/**
|
||||
* Each calendar's current channel version: the highest one that exists, so a
|
||||
* new version only takes over once it is written. A calendar with none falls
|
||||
* back to its [highWater] mark — re-creating that id restores its own settings.
|
||||
*/
|
||||
fun currentReminderChannelVersions(existingChannelIds: Collection<String>, highWater: Map<Long, Int>): Map<Long, Int> {
|
||||
val existing = existingChannelIds.mapNotNull(::parseReminderChannelId)
|
||||
.groupBy({ it.first }, { it.second })
|
||||
.mapValues { (_, versions) -> versions.max() }
|
||||
return highWater + existing
|
||||
}
|
||||
|
||||
/** Whether [channelId] is one of the per-calendar reminder channels. */
|
||||
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
|
||||
|
||||
/** Whether [groupId] is one of the per-account reminder channel groups. */
|
||||
fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX)
|
||||
|
||||
/**
|
||||
* One account's channel group, labelled as the calendar manager labels it. The
|
||||
* app's own device calendars share a single group ([isLocal]); [ambiguous]
|
||||
* marks a [label] another group shows too, so it should name the source app.
|
||||
*/
|
||||
data class ReminderChannelGroupSpec(
|
||||
val id: String,
|
||||
val label: String,
|
||||
val accountType: String,
|
||||
val isLocal: Boolean,
|
||||
val ambiguous: Boolean,
|
||||
)
|
||||
|
||||
data class ReminderChannelSpec(
|
||||
val id: String,
|
||||
val calendarId: Long,
|
||||
val name: String,
|
||||
/** Null only for a channel created before its calendar could be looked up. */
|
||||
val groupId: String?,
|
||||
/**
|
||||
* Whether a sync creates it up front. A calendar that syncs no events never
|
||||
* fires, so its channel only appears once something posts on it.
|
||||
*/
|
||||
val upFront: Boolean = true,
|
||||
)
|
||||
|
||||
/** What a channel already looks like in the system, as far as the plan compares it. */
|
||||
data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?)
|
||||
|
||||
data class ReminderChannelPlan(
|
||||
val groups: List<ReminderChannelGroupSpec>,
|
||||
val channels: List<ReminderChannelSpec>,
|
||||
/**
|
||||
* The [channels] a sync writes: missing up-front ones, and existing ones
|
||||
* whose name or (localized) description changed, or that still lack a group.
|
||||
*/
|
||||
val channelsToWrite: List<ReminderChannelSpec>,
|
||||
/** The [groups] holding a channel that exists or is about to be written. */
|
||||
val groupsInUse: List<ReminderChannelGroupSpec>,
|
||||
val staleChannelIds: List<String>,
|
||||
val staleGroupIds: List<String>,
|
||||
/** Stale channels kept for now, because a notification on them is still showing. */
|
||||
val keptChannelIds: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What the reminder channels should look like for [calendars]: one channel per
|
||||
* calendar inside a group per account, which of them need writing, and the
|
||||
* reminder channels and groups in [existing] / [existingGroupIds] no calendar
|
||||
* claims any more. Ids outside the reminder namespace (the backup channel, the
|
||||
* legacy channel) are never touched.
|
||||
*/
|
||||
fun planReminderChannels(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: Collection<ExistingReminderChannel>,
|
||||
existingGroupIds: Collection<String>,
|
||||
unnamed: String,
|
||||
description: String,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan {
|
||||
val (local, synced) = calendars.partition { it.isLocal }
|
||||
val groups = buildList {
|
||||
if (local.isNotEmpty()) {
|
||||
add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false))
|
||||
}
|
||||
synced.groupByAccount().forEach { group ->
|
||||
add(
|
||||
ReminderChannelGroupSpec(
|
||||
id = accountGroupId(group.key.type, group.key.name),
|
||||
label = group.label,
|
||||
accountType = group.accountType,
|
||||
isLocal = false,
|
||||
ambiguous = group.ambiguous,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
val existingById = existing.associateBy { it.id }
|
||||
val channels = calendars.map { calendar ->
|
||||
ReminderChannelSpec(
|
||||
id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0),
|
||||
calendarId = calendar.id,
|
||||
name = calendar.displayName.ifBlank { unnamed },
|
||||
groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName),
|
||||
upFront = calendar.isLocal || calendar.syncsEvents,
|
||||
)
|
||||
}
|
||||
val wantedChannels = channels.mapTo(HashSet()) { it.id }
|
||||
val wantedGroups = groups.mapTo(HashSet()) { it.id }
|
||||
val toWrite = channels.filter { spec ->
|
||||
val current = existingById[spec.id]
|
||||
if (current == null) {
|
||||
spec.upFront
|
||||
} else {
|
||||
current.name != spec.name || current.description != description ||
|
||||
(current.groupId == null && spec.groupId != null)
|
||||
}
|
||||
}
|
||||
val usedGroupIds = channels
|
||||
.filter { it.id in existingById || it in toWrite }
|
||||
.mapNotNullTo(HashSet()) { it.groupId }
|
||||
val (kept, stale) = existingById.keys
|
||||
.filter { isReminderChannelId(it) && it !in wantedChannels }
|
||||
.partition { it in showingChannelIds }
|
||||
val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId }
|
||||
return ReminderChannelPlan(
|
||||
groups = groups,
|
||||
channels = channels,
|
||||
channelsToWrite = toWrite,
|
||||
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||
staleChannelIds = stale,
|
||||
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups },
|
||||
keptChannelIds = kept,
|
||||
)
|
||||
}
|
||||
|
||||
private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name"
|
||||
|
||||
/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */
|
||||
data class ReminderChannelState(val blocked: Boolean, val groupId: String?)
|
||||
|
||||
/** Reminder notifications the system blocks, while Calendula would post them. */
|
||||
data class ReminderChannelStatus(
|
||||
val appBlocked: Boolean = false,
|
||||
val blockedCalendarIds: Set<Long> = emptySet(),
|
||||
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
|
||||
val groupBlockedCalendarIds: Set<Long> = emptySet(),
|
||||
/** The shared ring channel (#171) is switched off, so ringing calendars only sound once. */
|
||||
val ringBlocked: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* What the system blocks of [calendarIds]' reminders: all of them while the
|
||||
* app's notifications are off, otherwise those whose channel, or the group it
|
||||
* sits in, is switched off. A calendar without a channel yet isn't blocked.
|
||||
*/
|
||||
fun reminderChannelStatus(
|
||||
calendarIds: Collection<Long>,
|
||||
appEnabled: Boolean,
|
||||
channels: Map<String, ReminderChannelState>,
|
||||
blockedGroupIds: Set<String>,
|
||||
versions: Map<Long, Int> = emptyMap(),
|
||||
): ReminderChannelStatus {
|
||||
fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)]
|
||||
val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds }
|
||||
val blocked = if (!appEnabled) {
|
||||
calendarIds.toSet()
|
||||
} else {
|
||||
calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked
|
||||
}
|
||||
return ReminderChannelStatus(
|
||||
appBlocked = !appEnabled,
|
||||
blockedCalendarIds = blocked,
|
||||
groupBlockedCalendarIds = groupBlocked,
|
||||
ringBlocked = appEnabled && channels[RING_CHANNEL_ID]?.blocked == true,
|
||||
)
|
||||
}
|
||||
@@ -1,416 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationChannelGroup
|
||||
import android.app.NotificationManager
|
||||
import android.app.NotificationManager.IMPORTANCE_DEFAULT
|
||||
import android.app.NotificationManager.IMPORTANCE_LOW
|
||||
import android.app.NotificationManager.IMPORTANCE_MIN
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.util.Locale
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* The reminder notification channels: one per calendar, grouped by account
|
||||
* (#145), created up front so each calendar can be muted or given its own sound
|
||||
* in the system settings before it ever fires.
|
||||
*
|
||||
* A channel the user has touched keeps their settings; [sync] only creates the
|
||||
* missing ones, renames changed ones, and deletes those whose calendar is gone.
|
||||
* A sound picked in the app ([setSound], #518) recreates the channel under the
|
||||
* calendar's next version; the old one goes once nothing shows on it.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderChannels @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) {
|
||||
private val manager: NotificationManager
|
||||
get() = context.getSystemService(NotificationManager::class.java)
|
||||
|
||||
/** What the last [sync] saw, so an unchanged provider costs no channel writes. */
|
||||
@Volatile
|
||||
private var lastSync: Any? = null
|
||||
|
||||
/**
|
||||
* Bring the channels in line with the provider's calendars. An empty
|
||||
* snapshot changes nothing: that is a provider hiccup far more often than
|
||||
* every calendar gone at once.
|
||||
*/
|
||||
@Synchronized
|
||||
fun sync() {
|
||||
val calendars = calendarDataSource.calendars()
|
||||
if (calendars.isEmpty()) return
|
||||
val manager = manager
|
||||
val existing = manager.notificationChannels
|
||||
val existingIds = existing.mapTo(HashSet()) { it.id }
|
||||
val versions = currentVersions(existingIds).also { knownVersions = it }
|
||||
if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||
val groups = manager.notificationChannelGroups
|
||||
val groupIds = groups.map { it.id }
|
||||
// Active notifications are only read when there is something stale to protect.
|
||||
val plan = plan(calendars, existing, groupIds, versions).let { draft ->
|
||||
if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds))
|
||||
}
|
||||
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
|
||||
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
|
||||
val groupNames = groups.associate { it.id to it.name?.toString() }
|
||||
write(
|
||||
groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) },
|
||||
channels = plan.channelsToWrite,
|
||||
existing = existing,
|
||||
)
|
||||
if (RING_CHANNEL_ID in existingIds) ensureRingChannel()
|
||||
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
|
||||
val legacyGone = retireLegacyChannel()
|
||||
// A kept channel still has to go once its notification does, so don't cache.
|
||||
lastSync = if (plan.keptChannelIds.isEmpty()) {
|
||||
syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): Any = listOf(
|
||||
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||
Locale.getDefault(),
|
||||
channelIds,
|
||||
versions,
|
||||
)
|
||||
|
||||
/**
|
||||
* The current versions last resolved under the lock ([sync], [channelFor]).
|
||||
* Only [recreate], under the same lock, moves a calendar higher and updates
|
||||
* it, so a hit whose channel still exists is current.
|
||||
*/
|
||||
@Volatile
|
||||
private var knownVersions: Map<Long, Int> = emptyMap()
|
||||
|
||||
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
|
||||
currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() })
|
||||
|
||||
/** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */
|
||||
private fun showingChannelIds(candidates: Collection<String>): Set<String> = runCatching {
|
||||
manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId }
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "Could not read active notifications", e)
|
||||
candidates.toSet()
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel to post [calendarId]'s reminder on, created first if a sync
|
||||
* has not got to it yet. Null when the calendar no longer exists. Should the
|
||||
* calendar lookup fail or come back empty, the channel is still created,
|
||||
* plainly named and ungrouped, for the next sync to name and file — a
|
||||
* reminder is never lost to its channel. A ringing [style] posts on the
|
||||
* shared ring channel instead, once the calendar is known to exist.
|
||||
*/
|
||||
@Synchronized
|
||||
fun channelFor(calendarId: Long, style: ReminderAlertStyle = ReminderAlertStyle.Notification): String? {
|
||||
val calendarChannel = calendarChannelFor(calendarId) ?: return null
|
||||
return if (style == ReminderAlertStyle.FullScreenRing) ringChannel() else calendarChannel
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel a ringing full-screen alert (#171) posts on, shared by every
|
||||
* calendar. Silent: the ring service owns the sound and vibration, so the
|
||||
* channel adds neither. High importance keeps the heads-up a denied
|
||||
* full-screen intent degrades to.
|
||||
*/
|
||||
private fun ringChannel(): String {
|
||||
ensureRingChannel()
|
||||
return RING_CHANNEL_ID
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the ring channel, or renames it after a language change. Called
|
||||
* as soon as a calendar is set to ring, so the channel can be checked in
|
||||
* system settings (and switched on, where a skin starts it off) before the
|
||||
* first ring.
|
||||
*/
|
||||
@Synchronized
|
||||
fun ensureRingChannel() {
|
||||
val manager = manager
|
||||
val name = context.getString(R.string.reminder_ring_channel_name)
|
||||
val description = context.getString(R.string.reminder_ring_channel_description)
|
||||
val current = manager.getNotificationChannel(RING_CHANNEL_ID)
|
||||
if (current != null && current.name?.toString() == name && current.description == description) return
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
RING_CHANNEL_ID,
|
||||
name,
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
this.description = description
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a ring may sound for [calendarId]: neither its own channel, its
|
||||
* account's group nor the ring channel is blocked, since the service plays
|
||||
* the sound itself.
|
||||
*/
|
||||
fun canRing(calendarId: Long): Boolean {
|
||||
val status = status(listOf(calendarId))
|
||||
return !status.appBlocked && calendarId !in status.blockedCalendarIds && !status.ringBlocked
|
||||
}
|
||||
|
||||
private fun calendarChannelFor(calendarId: Long): String? {
|
||||
val manager = manager
|
||||
knownVersions[calendarId]?.let { version ->
|
||||
val known = reminderChannelId(calendarId, version)
|
||||
if (manager.getNotificationChannel(known) != null) return known
|
||||
}
|
||||
val existing = manager.notificationChannels
|
||||
val versions = currentVersions(existing.map { it.id }).also { knownVersions = it }
|
||||
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
|
||||
if (existing.any { it.id == id }) return id
|
||||
val calendars = try {
|
||||
calendarDataSource.calendars()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not look up calendar $calendarId for its channel", e)
|
||||
emptyList()
|
||||
}
|
||||
val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)
|
||||
if (calendars.isEmpty()) {
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
return id
|
||||
}
|
||||
val plan = plan(calendars, existing, emptyList(), versions)
|
||||
val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null
|
||||
try {
|
||||
val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id }
|
||||
write(
|
||||
groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups },
|
||||
channels = listOf(spec),
|
||||
existing = existing,
|
||||
)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not file the channel of calendar $calendarId", e)
|
||||
write(emptyList(), listOf(fallback), existing)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Run [block] with [calendarId]'s channel held: no sound pick or sync can
|
||||
* move or retire it until [block] returns. Null, without running [block],
|
||||
* when the calendar is gone or its channel can't be made; [block]'s own
|
||||
* failures propagate.
|
||||
*/
|
||||
@Synchronized
|
||||
fun <T> withChannel(calendarId: Long, block: (String) -> T): T? {
|
||||
val channelId = try {
|
||||
channelFor(calendarId)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No channel for calendar $calendarId", e)
|
||||
null
|
||||
}
|
||||
return channelId?.let(block)
|
||||
}
|
||||
|
||||
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||
val manager = manager
|
||||
val appEnabled = manager.areNotificationsEnabled()
|
||||
val existing = manager.notificationChannels
|
||||
val channels = existing.associate {
|
||||
it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group)
|
||||
}
|
||||
val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }
|
||||
return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys))
|
||||
}
|
||||
|
||||
/** A "Silent" (low) channel keeps its sound but never plays it. */
|
||||
private fun NotificationChannel.audibleSound(): Uri? =
|
||||
sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW }
|
||||
|
||||
/**
|
||||
* The sound each of [calendarIds]' channels plays; null is silent. A
|
||||
* calendar whose channel doesn't exist yet is left out.
|
||||
*/
|
||||
fun sounds(calendarIds: Collection<Long>): Map<Long, Uri?> {
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val versions = currentVersions(byId.keys)
|
||||
return calendarIds.mapNotNull { id ->
|
||||
byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() }
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
/**
|
||||
* Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is
|
||||
* fixed once created, so each moves to a new channel version carrying over
|
||||
* everything else, and the old one retires in the sync that follows (#518). Calendars without a
|
||||
* channel are skipped unless [createMissing]. Returns whether every move
|
||||
* went through.
|
||||
*/
|
||||
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean): Boolean {
|
||||
if (createMissing) calendarIds.forEach(::channelFor)
|
||||
val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id }
|
||||
val current = currentVersions(existingIds)
|
||||
val floors = calendarIds
|
||||
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
|
||||
.associateWith { (current[it] ?: 0) + 1 }
|
||||
if (floors.isEmpty()) return false
|
||||
val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
|
||||
// Retire the old versions now, or each calendar shows twice in system settings until the next scan.
|
||||
try {
|
||||
sync()
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Old channel versions left to the next sync", e)
|
||||
}
|
||||
return applied
|
||||
}
|
||||
|
||||
/**
|
||||
* Create each calendar's [versions] from its current channel. The old one is
|
||||
* left to the next [sync], which retires it once nothing shows on it.
|
||||
*/
|
||||
@Synchronized
|
||||
private fun recreate(versions: Map<Long, Int>, sound: Uri?): Boolean {
|
||||
val manager = manager
|
||||
val byId = manager.notificationChannels.associateBy { it.id }
|
||||
val current = currentReminderChannelVersions(byId.keys, emptyMap())
|
||||
var allApplied = true
|
||||
versions.forEach { (calendarId, version) ->
|
||||
val from = current[calendarId]?.takeIf { it < version }
|
||||
val old = from?.let { byId[reminderChannelId(calendarId, it)] }
|
||||
if (old == null) {
|
||||
allApplied = false
|
||||
return@forEach
|
||||
}
|
||||
try {
|
||||
// Picking a sound asks for one, which a "Silent" (low) channel would never play.
|
||||
val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) {
|
||||
IMPORTANCE_DEFAULT
|
||||
} else {
|
||||
old.importance
|
||||
}
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply {
|
||||
description = old.description
|
||||
old.group?.let { group = it }
|
||||
inheritFrom(old)
|
||||
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
|
||||
},
|
||||
)
|
||||
knownVersions = knownVersions + (calendarId to version)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not move calendar $calendarId to a new sound", e)
|
||||
allApplied = false
|
||||
}
|
||||
}
|
||||
lastSync = null
|
||||
return allApplied
|
||||
}
|
||||
|
||||
private fun plan(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: List<NotificationChannel>,
|
||||
existingGroupIds: List<String>,
|
||||
versions: Map<Long, Int>,
|
||||
showingChannelIds: Set<String> = emptySet(),
|
||||
): ReminderChannelPlan = planReminderChannels(
|
||||
calendars = calendars,
|
||||
existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) },
|
||||
existingGroupIds = existingGroupIds,
|
||||
unnamed = context.getString(R.string.calendar_unnamed),
|
||||
description = context.getString(R.string.reminder_channel_description),
|
||||
versions = versions,
|
||||
showingChannelIds = showingChannelIds,
|
||||
)
|
||||
|
||||
private fun write(
|
||||
groups: List<ReminderChannelGroupSpec>,
|
||||
channels: List<ReminderChannelSpec>,
|
||||
existing: List<NotificationChannel>,
|
||||
) {
|
||||
val manager = manager
|
||||
if (groups.isNotEmpty()) {
|
||||
manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) })
|
||||
}
|
||||
if (channels.isEmpty()) return
|
||||
val byId = existing.associateBy { it.id }
|
||||
val description = context.getString(R.string.reminder_channel_description)
|
||||
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
|
||||
// Importance only applies on creation; an existing channel keeps its own.
|
||||
manager.createNotificationChannels(
|
||||
channels.map { spec ->
|
||||
val current = byId[spec.id]
|
||||
NotificationChannel(
|
||||
spec.id,
|
||||
spec.name,
|
||||
current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
this.description = description
|
||||
spec.groupId?.let { group = it }
|
||||
if (current == null && template != null) inheritFrom(template)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry a channel's sound, vibration, lights and badge over to a new one: the
|
||||
* legacy channel to a per-calendar one on upgrade, or a calendar's channel to
|
||||
* its next version (#518). Lock-screen visibility and a DND override can't
|
||||
* follow: the system resets both on channels an app creates.
|
||||
*/
|
||||
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
|
||||
setSound(template.sound, template.audioAttributes)
|
||||
// The pattern setter also flips vibration on or off, so it goes first.
|
||||
vibrationPattern = template.vibrationPattern
|
||||
enableVibration(template.shouldVibrate())
|
||||
enableLights(template.shouldShowLights())
|
||||
lightColor = template.lightColor
|
||||
setShowBadge(template.canShowBadge())
|
||||
// Only honoured with Do Not Disturb access, so usually left to the user.
|
||||
setBypassDnd(template.canBypassDnd())
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the pre-#145 channel once the per-calendar ones carry its settings,
|
||||
* but not while a reminder posted on it is still on screen — deleting the
|
||||
* channel would take that notification with it. Returns whether it is gone.
|
||||
*/
|
||||
private fun retireLegacyChannel(): Boolean {
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
|
||||
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID))
|
||||
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
|
||||
return !showing
|
||||
}
|
||||
|
||||
private fun groupLabel(group: ReminderChannelGroupSpec): String {
|
||||
if (group.isLocal) return context.getString(R.string.calendars_local_header)
|
||||
val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) }
|
||||
if (!group.ambiguous) return name
|
||||
return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderChannels"
|
||||
|
||||
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
+29
-3
@@ -4,7 +4,6 @@ import android.content.Context
|
||||
import android.provider.CalendarContract
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.calendar.instancesUri
|
||||
import de.jeanlucmakiola.calendula.data.calendar.reminderMinutesByEvent
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -73,8 +72,28 @@ class ProviderReminderInstanceSource @Inject constructor(
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
override fun reminderMinutes(eventIds: Collection<Long>): Map<Long, List<Int>> =
|
||||
context.contentResolver.reminderMinutesByEvent(eventIds, alertsOnly = true)
|
||||
override fun reminderMinutes(eventIds: Collection<Long>): Map<Long, List<Int>> {
|
||||
if (eventIds.isEmpty()) return emptyMap()
|
||||
val out = mutableMapOf<Long, MutableList<Int>>()
|
||||
// Batched: the ids go into the selection literally, and an unbounded
|
||||
// `IN (...)` would grow the SQL past what SQLite takes.
|
||||
eventIds.distinct().chunked(EVENT_ID_BATCH).forEach { batch ->
|
||||
context.contentResolver.query(
|
||||
CalendarContract.Reminders.CONTENT_URI,
|
||||
REMINDER_PROJECTION,
|
||||
"${CalendarContract.Reminders.METHOD} = " +
|
||||
"${CalendarContract.Reminders.METHOD_ALERT} AND " +
|
||||
"${CalendarContract.Reminders.EVENT_ID} IN (${batch.joinToString(",")})",
|
||||
null,
|
||||
null,
|
||||
)?.use { c ->
|
||||
while (c.moveToNext()) {
|
||||
out.getOrPut(c.getLong(0)) { mutableListOf() } += c.getInt(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
override fun longestReminderMinutes(): Int = context.contentResolver.query(
|
||||
CalendarContract.Reminders.CONTENT_URI,
|
||||
@@ -86,6 +105,8 @@ class ProviderReminderInstanceSource @Inject constructor(
|
||||
)?.use { c -> if (c.moveToFirst()) c.getInt(0) else 0 } ?: 0
|
||||
|
||||
private companion object {
|
||||
const val EVENT_ID_BATCH = 50
|
||||
|
||||
val OCCURRENCE_PROJECTION = arrayOf(
|
||||
CalendarContract.Instances.EVENT_ID,
|
||||
CalendarContract.Instances.CALENDAR_ID,
|
||||
@@ -95,5 +116,10 @@ class ProviderReminderInstanceSource @Inject constructor(
|
||||
CalendarContract.Instances.EVENT_LOCATION,
|
||||
CalendarContract.Instances.ALL_DAY,
|
||||
)
|
||||
|
||||
val REMINDER_PROJECTION = arrayOf(
|
||||
CalendarContract.Reminders.EVENT_ID,
|
||||
CalendarContract.Reminders.MINUTES,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.net.toUri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
@@ -19,14 +18,7 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor
|
||||
import de.jeanlucmakiola.calendula.ui.reminders.ReminderAlertActivity
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderLink
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderMapQuery
|
||||
import de.jeanlucmakiola.floret.android.resolvableMapsSearchIntent
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.datetime.isoDayNumber
|
||||
import java.time.DayOfWeek
|
||||
@@ -37,9 +29,8 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts one notification per occurrence on its calendar's channel
|
||||
* ([ReminderChannels], #145), or as a full-screen alert where the calendar
|
||||
* asks for one (#171). Tapping opens the event's detail screen.
|
||||
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||
* the event's detail screen.
|
||||
*
|
||||
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||
@@ -52,8 +43,6 @@ class ReminderNotifier @Inject constructor(
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val channels: ReminderChannels,
|
||||
private val alerts: FullScreenAlerts,
|
||||
) {
|
||||
|
||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||
@@ -64,96 +53,20 @@ class ReminderNotifier @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* The single choke point for "this calendar posts no reminders": switched
|
||||
* off (also covering a snooze armed before the switch-off, and a read-only
|
||||
* install whose switch lives in [CalendarPrefs]), or its notifications
|
||||
* turned off in Calendula's own settings (#272).
|
||||
* The single choke point for "this calendar is switched off", covering the
|
||||
* two paths that reach [post] around the scan's own filter: a snooze armed
|
||||
* before the switch-off, and a read-only install whose switch lives in
|
||||
* [CalendarPrefs].
|
||||
*/
|
||||
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||
|
||||
/**
|
||||
* Post [alert] in its calendar's alert style (#171), unless the calendar is
|
||||
* silenced or gone. [ring] false posts a ringing style as a full-screen
|
||||
* alert that sounds once instead; [quiet] posts a plain notification that
|
||||
* makes no sound. Both are how a ring hands a reminder back to the shade.
|
||||
*/
|
||||
suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) {
|
||||
/** Post [alert], unless its calendar is switched off. */
|
||||
suspend fun post(alert: ReminderAlert) {
|
||||
if (isSilenced(alert.calendarId)) return
|
||||
var style = when {
|
||||
quiet -> ReminderAlertStyle.Notification
|
||||
else -> effectiveStyle(alert).let {
|
||||
if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it
|
||||
}
|
||||
}
|
||||
// Rung already and handed back to the shade: a catch-up post leaves it there.
|
||||
if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return
|
||||
ensureChannel()
|
||||
val title = displayTitle(alert)
|
||||
val text = contentText(alert)
|
||||
if (style == ReminderAlertStyle.FullScreenRing) {
|
||||
val ringChannel = channelFor(alert, style)
|
||||
if (ringChannel != null &&
|
||||
ReminderRingService.start(context, alerts, alert, build(alert, ringChannel, title, text, style, quiet = false))
|
||||
) {
|
||||
// An earlier reminder for this occurrence gives way to the ring.
|
||||
NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID)
|
||||
cancelLegacy(alert)
|
||||
return
|
||||
}
|
||||
// No ring channel, or Android refused the ring: still full-screen, sounding once on the calendar's channel.
|
||||
if (ringChannel != null) stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||
style = ReminderAlertStyle.FullScreen
|
||||
} else if (ring) {
|
||||
// A fresh reminder replaces a ring for its occurrence from before the style changed.
|
||||
stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||
}
|
||||
// Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post.
|
||||
val posted = channels.withChannel(alert.calendarId) { channelId ->
|
||||
notify(alert, build(alert, channelId, title, text, style, quiet))
|
||||
}
|
||||
if (posted == null) {
|
||||
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a ring for [alert] should go on, now that settings may have changed since it started. */
|
||||
suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when {
|
||||
!settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) ||
|
||||
calendarDataSource.isCalendarVisible(alert.calendarId) == null -> RingVerdict.Drop
|
||||
effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack
|
||||
else -> RingVerdict.Ring
|
||||
}
|
||||
|
||||
/** Whether a live ring for [alert] may go on: its notification can still be seen, and its calendar still notifies. */
|
||||
suspend fun canStillRing(alert: ReminderAlert): Boolean =
|
||||
canPost() && channels.canRing(alert.calendarId) && !isSilenced(alert.calendarId)
|
||||
|
||||
/** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */
|
||||
private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle {
|
||||
val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId)
|
||||
return if (chosen == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) {
|
||||
ReminderAlertStyle.FullScreen
|
||||
} else {
|
||||
chosen
|
||||
}
|
||||
}
|
||||
|
||||
private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try {
|
||||
channels.channelFor(alert.calendarId, style).also {
|
||||
if (it == null) Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
|
||||
null
|
||||
}
|
||||
|
||||
private suspend fun contentText(alert: ReminderAlert): String =
|
||||
listOfNotNull(timeText(alert), alert.location).joinToString(" · ")
|
||||
|
||||
/** When [alert]'s occurrence happens, as its notification words it. */
|
||||
suspend fun timeText(alert: ReminderAlert): String {
|
||||
val is24Hour = settingsPrefs.timeFormat.first()
|
||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||
val zone = ZoneId.systemDefault()
|
||||
@@ -161,7 +74,7 @@ class ReminderNotifier @Inject constructor(
|
||||
// resolveFirstDay yields a kotlinx.datetime day; bridge it to java.time by
|
||||
// its shared ISO number (1..7) for the date math in reminderTimeText.
|
||||
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
|
||||
return reminderTimeText(
|
||||
val time = reminderTimeText(
|
||||
beginMillis = alert.beginMillis,
|
||||
endMillis = alert.endMillis,
|
||||
isAllDay = alert.isAllDay,
|
||||
@@ -174,35 +87,19 @@ class ReminderNotifier @Inject constructor(
|
||||
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The reminder's notification in [style]. A ringing one belongs to
|
||||
* [ReminderRingService]: ongoing and opening the alert screen. A full-screen
|
||||
* one adds the alert screen as a full-screen intent where Android allows
|
||||
* it, degrading to a heads-up where it does not, and is dismissed by a
|
||||
* swipe, so its screen closes too.
|
||||
*/
|
||||
private fun build(
|
||||
alert: ReminderAlert,
|
||||
channelId: String,
|
||||
title: String,
|
||||
text: String,
|
||||
style: ReminderAlertStyle,
|
||||
quiet: Boolean,
|
||||
): Notification {
|
||||
val ringing = style == ReminderAlertStyle.FullScreenRing
|
||||
val fullScreen = style.isFullScreen
|
||||
val builder = NotificationCompat.Builder(context, channelId)
|
||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setWhen(alert.beginMillis)
|
||||
.setShowWhen(false)
|
||||
.setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT)
|
||||
.setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH)
|
||||
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setAutoCancel(true)
|
||||
.setOnlyAlertOnce(shownKey(alert) == alert.key)
|
||||
.addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) })
|
||||
.setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert))
|
||||
.setContentIntent(detailIntent(alert))
|
||||
.addAction(
|
||||
R.drawable.ic_notification_snooze,
|
||||
context.getString(R.string.reminder_action_snooze),
|
||||
@@ -213,27 +110,7 @@ class ReminderNotifier @Inject constructor(
|
||||
context.getString(R.string.reminder_action_dismiss),
|
||||
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
||||
)
|
||||
// Room for one more button: a meeting link beats the place, being the likelier next step.
|
||||
// A ring leaves it to the alert screen, so opening something can't leave it sounding.
|
||||
if (!ringing) {
|
||||
linkIntent(alert)?.let {
|
||||
builder.addAction(R.drawable.ic_notification_link, context.getString(R.string.reminder_action_open_link), it)
|
||||
} ?: mapIntent(alert)?.let {
|
||||
builder.addAction(R.drawable.ic_notification_map, context.getString(R.string.event_detail_open_in_maps), it)
|
||||
}
|
||||
}
|
||||
if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS))
|
||||
if (ringing) {
|
||||
builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
} else {
|
||||
builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key)
|
||||
}
|
||||
if (quiet) builder.setSilent(true)
|
||||
if (fullScreen && context.canUseFullScreenIntent()) builder.setFullScreenIntent(alertScreenIntent(alert), true)
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
private fun notify(alert: ReminderAlert, notification: Notification) {
|
||||
.build()
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
cancelLegacy(alert)
|
||||
try {
|
||||
@@ -254,25 +131,10 @@ class ReminderNotifier @Inject constructor(
|
||||
if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID)
|
||||
// Posted before reminders shared a notification, under the reminder's own key.
|
||||
manager.cancel(alert.key.toString(), NOTIFICATION_ID)
|
||||
stopRing(RingMatch.Key(alert.key))
|
||||
alerts.markHandled(alert)
|
||||
}
|
||||
|
||||
/** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */
|
||||
fun stopRing(match: RingMatch, handBack: Boolean = false) {
|
||||
if (alerts.mayRing(match)) ReminderRingService.stop(context, alerts, match, handBack)
|
||||
}
|
||||
|
||||
/** Whether a different reminder for [alert]'s occurrence is on screen now. */
|
||||
fun isSuperseded(alert: ReminderAlert): Boolean {
|
||||
val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey }
|
||||
if (ringing != null) return ringing.key != alert.key
|
||||
return shownKey(alert).let { it != null && it != alert.key }
|
||||
}
|
||||
|
||||
/** Whether [alert] itself is still on screen, as a notification or ringing. */
|
||||
fun isShowing(alert: ReminderAlert): Boolean =
|
||||
alerts.ringing?.key == alert.key || shownKey(alert) == alert.key
|
||||
fun isSuperseded(alert: ReminderAlert): Boolean = shownKey(alert).let { it != null && it != alert.key }
|
||||
|
||||
/** The key of the reminder showing for [alert]'s occurrence, if any. */
|
||||
private fun shownKey(alert: ReminderAlert): Long? {
|
||||
@@ -291,7 +153,7 @@ class ReminderNotifier @Inject constructor(
|
||||
private fun cancelLegacy(alert: ReminderAlert) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
manager.activeNotifications
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID }
|
||||
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||
.filter { it.notification.`when` == alert.beginMillis }
|
||||
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||
@@ -309,13 +171,6 @@ class ReminderNotifier @Inject constructor(
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
private fun alertScreenIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_ALERT_SCREEN),
|
||||
ReminderAlertActivity.intent(context, alert),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
// Shares the per-(alert, action) request-code scheme with the buttons.
|
||||
@@ -326,44 +181,21 @@ class ReminderNotifier @Inject constructor(
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
/**
|
||||
* Opens the first web link in [alert]'s location, e.g. a meeting, started
|
||||
* directly like [mapIntent]. Null without a link or an app to open it.
|
||||
*/
|
||||
private fun linkIntent(alert: ReminderAlert): PendingIntent? {
|
||||
val link = reminderLink(alert.location) ?: return null
|
||||
val intent = Intent(Intent.ACTION_VIEW, link.toUri())
|
||||
.addCategory(Intent.CATEGORY_BROWSABLE)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (intent.resolveActivity(context.packageManager) == null) return null
|
||||
return PendingIntent.getActivity(
|
||||
context,
|
||||
/* requestCode = */ 0,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens [alert]'s location in maps like the detail screen does, started
|
||||
* directly (no receiver trampoline). Leaves the notification up for a later
|
||||
* snooze or dismiss. Null without a place to look up (a bare meeting link
|
||||
* isn't one) or an app to open it.
|
||||
*/
|
||||
private fun mapIntent(alert: ReminderAlert): PendingIntent? {
|
||||
val query = reminderMapQuery(alert.location) ?: return null
|
||||
val intent = context.resolvableMapsSearchIntent(query) ?: return null
|
||||
return PendingIntent.getActivity(
|
||||
context,
|
||||
// An implicit activity intent: filterEquals already keeps it apart from the others.
|
||||
/* requestCode = */ 0,
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
/** Channel creation is idempotent; re-running refreshes the localized name. */
|
||||
private fun ensureChannel() {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
context.getString(R.string.reminder_channel_name),
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = context.getString(R.string.reminder_channel_description)
|
||||
}
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReminderNotifier"
|
||||
const val CHANNEL_ID = "reminders"
|
||||
|
||||
// One id, distinct tags: the tag (occurrence) already keys the
|
||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.RingtoneManager
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.IntentCompat
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert
|
||||
import de.jeanlucmakiola.floret.ring.RingVibrator
|
||||
import de.jeanlucmakiola.floret.ring.RingWakeLock
|
||||
import de.jeanlucmakiola.floret.ring.TonePlayer
|
||||
import de.jeanlucmakiola.floret.ring.isInCall
|
||||
import de.jeanlucmakiola.floret.ring.startRingForeground
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Rings a reminder whose calendar asks for "Ring until dismissed" (#171): the
|
||||
* alarm sound looped with vibration, for as long as the reminder is neither
|
||||
* dismissed nor snoozed, up to [RING_TIMEOUT_MILLIS]. Then it goes quiet and
|
||||
* hands the reminder back to the shade as an ordinary notification.
|
||||
*
|
||||
* One reminder rings at a time. A new one takes over, and the one it replaces
|
||||
* goes back to the shade, silently, unless it was for the same occurrence.
|
||||
* Starts and stops both arrive as commands, so they are handled on the main
|
||||
* thread in the order they were sent.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class ReminderRingService : Service() {
|
||||
|
||||
@Inject lateinit var alerts: FullScreenAlerts
|
||||
@Inject lateinit var notifier: ReminderNotifier
|
||||
|
||||
@Inject @ApplicationScope
|
||||
lateinit var appScope: CoroutineScope
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
private val tones by lazy { TonePlayer(this) }
|
||||
private val vibrator by lazy { RingVibrator(this) }
|
||||
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, RING_TIMEOUT_MILLIS) }
|
||||
|
||||
private var ringing: Job? = null
|
||||
private var timeout: Job? = null
|
||||
private var notificationId = RING_NOTIFICATION_ID
|
||||
private var lastStartId: Int? = null
|
||||
|
||||
/** The start the system would redeliver, so a takeover can mark it done. */
|
||||
private var ringStartId: Int? = null
|
||||
|
||||
/** Whether the ring's players were ever built, so a stop-only service builds none. */
|
||||
private var rang = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
lastStartId = startId
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
stop(intent)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val alert = intent?.let(ReminderActionReceiver::alertFrom)
|
||||
if (intent == null || alert == null) {
|
||||
stopIfIdle()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
try {
|
||||
return startRing(intent, alert, startId)
|
||||
} finally {
|
||||
// Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped.
|
||||
if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startRing(intent: Intent, alert: ReminderAlert, startId: Int): Int {
|
||||
val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java)
|
||||
if (notification == null) {
|
||||
stopIfIdle()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val previous = alerts.ringing
|
||||
// A different reminder posts under the other id, so it is a new
|
||||
// notification whose full-screen intent opens; an update would not.
|
||||
val replacing = previous != null && previous.key != alert.key
|
||||
val shown = notificationId
|
||||
if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID
|
||||
val foreground = runCatching { startRingForeground(notificationId, notification) }
|
||||
if (foreground.isFailure) {
|
||||
// A restart after a process death may be refused a foreground start:
|
||||
// the reminder still shows full-screen, sounding once.
|
||||
Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull())
|
||||
notificationId = shown
|
||||
handBack(alert, quiet = false)
|
||||
stopIfIdle()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (replacing) NotificationManagerCompat.from(this).cancel(shown)
|
||||
// A duplicate start for this very ring leaves the original in charge of redelivery.
|
||||
if (previous?.key == alert.key) return START_NOT_STICKY
|
||||
// Only the newest start is redelivered after a process death; the older
|
||||
// ones are done, so a handled reminder never rings again.
|
||||
ringStartId?.let { stopSelfResult(it) }
|
||||
ringStartId = startId
|
||||
alerts.ringing = alert
|
||||
if (previous != null) {
|
||||
// Its screen closes either way; another occurrence goes back to the shade.
|
||||
if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous)
|
||||
}
|
||||
val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis())
|
||||
ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis())
|
||||
return START_REDELIVER_INTENT
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (rang) releaseRing()
|
||||
// Stopped from outside: its screen must not stay up for a ring that is gone.
|
||||
alerts.ringing?.let { if (alerts.handBackOnDestroy) handBack(it) else alerts.markHandled(it) }
|
||||
alerts.handBackOnDestroy = false
|
||||
alerts.ringing = null
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** Rings for what is left of the ring's time, so a ring restarted after a process death does not begin again. */
|
||||
private fun ring(alert: ReminderAlert, remaining: Long) {
|
||||
releaseRing()
|
||||
rang = true
|
||||
wakeLock.acquire()
|
||||
timeout = scope.launch {
|
||||
delay(remaining.coerceAtLeast(0L))
|
||||
giveUp()
|
||||
}
|
||||
ringing = scope.launch {
|
||||
// Settings changed while this ring was on its way apply before it makes a sound.
|
||||
val verdict = try {
|
||||
withContext(Dispatchers.IO) { notifier.ringVerdict(alert) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e)
|
||||
RingVerdict.Ring
|
||||
}
|
||||
if (verdict != RingVerdict.Ring) {
|
||||
// Never heard yet, so it alerts once in its new style.
|
||||
if (verdict == RingVerdict.HandBack) handBack(alert, quiet = false)
|
||||
end()
|
||||
return@launch
|
||||
}
|
||||
sound(alert)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tone and vibration, paused for a phone call and back after it, until the
|
||||
* user hides the ring's notification, which would leave no way to stop it.
|
||||
*/
|
||||
private suspend fun sound(alert: ReminderAlert) {
|
||||
var sounding = false
|
||||
var tick = 0
|
||||
while (true) {
|
||||
if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !stillRings(alert)) {
|
||||
handBack(alert)
|
||||
end()
|
||||
return
|
||||
}
|
||||
val inCall = isInCall()
|
||||
if (inCall && sounding) {
|
||||
tones.stop()
|
||||
vibrator.stop()
|
||||
sounding = false
|
||||
} else if (!inCall && !sounding) {
|
||||
vibrator.start()
|
||||
tones.play(scope, ringSources())
|
||||
sounding = true
|
||||
}
|
||||
delay(CALL_CHECK_MILLIS)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun stillRings(alert: ReminderAlert): Boolean = try {
|
||||
withContext(Dispatchers.IO) { notifier.canStillRing(alert) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e)
|
||||
true
|
||||
}
|
||||
|
||||
private fun stop(intent: Intent) {
|
||||
val current = alerts.ringing
|
||||
if (current != null && matchFrom(intent).matches(current)) {
|
||||
if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current)
|
||||
end()
|
||||
} else {
|
||||
stopIfIdle()
|
||||
}
|
||||
}
|
||||
|
||||
/** Rung long enough: back to the shade quietly. */
|
||||
private fun giveUp() {
|
||||
timeout = null
|
||||
alerts.ringing?.let(::handBack)
|
||||
end()
|
||||
}
|
||||
|
||||
/** Ends the ring, closes its screen, and stops the service unless a newer command is on its way. */
|
||||
private fun end() {
|
||||
alerts.ringing?.let(alerts::markHandled)
|
||||
releaseRing()
|
||||
alerts.ringing = null
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopIfIdle()
|
||||
}
|
||||
|
||||
/** Declines while a newer command is still on its way. */
|
||||
private fun stopIfIdle() {
|
||||
if (alerts.ringing == null) lastStartId?.let { stopSelfResult(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* [alert] back in the shade, in the app's scope so a service stopped
|
||||
* meanwhile cannot cancel it, and its alert screen closed. A newer reminder
|
||||
* for the occurrence that took its place meanwhile is left alone.
|
||||
*/
|
||||
private fun handBack(alert: ReminderAlert, quiet: Boolean = true) {
|
||||
alerts.markHandled(alert)
|
||||
appScope.launch {
|
||||
try {
|
||||
if (!notifier.isSuperseded(alert)) notifier.post(alert, quiet = quiet, ring = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseRing() {
|
||||
ringing?.cancel()
|
||||
ringing = null
|
||||
timeout?.cancel()
|
||||
timeout = null
|
||||
tones.stop()
|
||||
vibrator.stop()
|
||||
wakeLock.release()
|
||||
}
|
||||
|
||||
/** The device's alarm sound; "None", or none opening, leaves the vibration. */
|
||||
private fun ringSources() = listOfNotNull(
|
||||
RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM),
|
||||
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM),
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ReminderRingService"
|
||||
private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING"
|
||||
private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP"
|
||||
private const val EXTRA_NOTIFICATION = "notification"
|
||||
private const val EXTRA_SINCE = "since"
|
||||
private const val CALL_CHECK_MILLIS = 1_000L
|
||||
|
||||
/** How many call checks between re-reading whether the ring's notification can still be seen. */
|
||||
private const val VISIBILITY_CHECK_TICKS = 5
|
||||
private const val EXTRA_MATCH_KIND = "match_kind"
|
||||
private const val EXTRA_MATCH_VALUE = "match_value"
|
||||
private const val EXTRA_HAND_BACK = "hand_back"
|
||||
private const val WAKE_LOCK_TAG = "calendula:reminder-ring"
|
||||
|
||||
/** Clear of the reminders' tagged id 1 and the backup notice's 2. */
|
||||
private const val RING_NOTIFICATION_ID = 171
|
||||
private const val OTHER_RING_NOTIFICATION_ID = 172
|
||||
|
||||
/** How long a reminder rings unanswered before it goes quiet. */
|
||||
const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000
|
||||
|
||||
/**
|
||||
* Rings [alert] under [notification]. False when Android refused to
|
||||
* start the service from where the reminder fired.
|
||||
*/
|
||||
fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean {
|
||||
val intent = Intent(context, ReminderRingService::class.java)
|
||||
.setAction(ACTION_RING)
|
||||
.putAlert(alert)
|
||||
.putExtra(EXTRA_NOTIFICATION, notification)
|
||||
.putExtra(EXTRA_SINCE, System.currentTimeMillis())
|
||||
alerts.addPending(alert)
|
||||
return try {
|
||||
RingWakeLock.handOff(context, WAKE_LOCK_TAG)
|
||||
context.startForegroundService(intent)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e)
|
||||
alerts.removePending(alert)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the ring if it is for a reminder [match]es, in order with the
|
||||
* starts sent before it. [handBack] puts it back in the shade quietly.
|
||||
* A command rather than `stopService`, which would also drop a start
|
||||
* still on its way; sent while the ring's foreground service keeps the
|
||||
* app allowed to.
|
||||
*/
|
||||
fun stop(context: Context, alerts: FullScreenAlerts, match: RingMatch, handBack: Boolean = false) {
|
||||
val (kind, value) = when (match) {
|
||||
is RingMatch.Key -> 0 to match.key
|
||||
is RingMatch.Occurrence -> 1 to match.occurrenceKey
|
||||
is RingMatch.Calendar -> 2 to match.calendarId
|
||||
RingMatch.Any -> 3 to 0L
|
||||
}
|
||||
val intent = Intent(context, ReminderRingService::class.java)
|
||||
.setAction(ACTION_STOP)
|
||||
.putExtra(EXTRA_MATCH_KIND, kind)
|
||||
.putExtra(EXTRA_MATCH_VALUE, value)
|
||||
.putExtra(EXTRA_HAND_BACK, handBack)
|
||||
try {
|
||||
context.startService(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not stop the ring", e)
|
||||
// Refused from the background: nothing must ring on regardless,
|
||||
// unless a start is still on its way, which this would crash.
|
||||
if (!alerts.anyPending) {
|
||||
alerts.handBackOnDestroy = handBack
|
||||
context.stopService(Intent(context, ReminderRingService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun matchFrom(intent: Intent): RingMatch {
|
||||
val value = intent.getLongExtra(EXTRA_MATCH_VALUE, 0L)
|
||||
return when (intent.getIntExtra(EXTRA_MATCH_KIND, 3)) {
|
||||
0 -> RingMatch.Key(value)
|
||||
1 -> RingMatch.Occurrence(value)
|
||||
2 -> RingMatch.Calendar(value)
|
||||
else -> RingMatch.Any
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,9 @@ import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.digestEntries
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.planReminders
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.scheduleDigest
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders
|
||||
@@ -47,12 +43,9 @@ class ReminderScanner @Inject constructor(
|
||||
private val source: ReminderInstanceSource,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val notifier: ReminderNotifier,
|
||||
private val digestNotifier: DailyDigestNotifier,
|
||||
private val channels: ReminderChannels,
|
||||
private val snoozes: ReminderSnoozeScheduler,
|
||||
private val alarms: ReminderAlarmScheduler,
|
||||
private val state: ReminderStatePrefs,
|
||||
private val calendarPrefs: CalendarPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@IoDispatcher private val io: kotlinx.coroutines.CoroutineDispatcher,
|
||||
) {
|
||||
@@ -84,37 +77,18 @@ class ReminderScanner @Inject constructor(
|
||||
val now = System.currentTimeMillis()
|
||||
if (!hasReadCalendar()) return
|
||||
|
||||
val lastFired = reminderWatermark(state.lastScanMillis(), now)
|
||||
val horizon = now + MAX_ALARM_INTERVAL_MILLIS
|
||||
val digestSettings = settingsPrefs.dailyDigest.first()
|
||||
val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null
|
||||
val nextReminder = try {
|
||||
if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
|
||||
} catch (e: Exception) {
|
||||
// The watermark stays, so the next pass owes these reminders again;
|
||||
// keep that pass, and the summary's next moment, armed.
|
||||
alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS))
|
||||
throw e
|
||||
if (!settingsPrefs.remindersEnabled.first()) {
|
||||
// Reminders off: drop the wake-up, but keep the watermark moving
|
||||
// so switching them back on doesn't replay the backlog.
|
||||
alarms.cancelScan()
|
||||
state.setLastScanMillis(now)
|
||||
return
|
||||
}
|
||||
|
||||
// Advance even when nothing could be posted, so muting notifications
|
||||
// doesn't build a backlog — and while both are off, so switching one
|
||||
// back on doesn't replay it.
|
||||
state.setLastScanMillis(now)
|
||||
val next = listOfNotNull(nextReminder, nextDigest).minOrNull()
|
||||
if (next == null) alarms.cancelScan() else alarms.scheduleScan(minOf(next, horizon))
|
||||
}
|
||||
|
||||
/** Post the event reminders that are due; returns the next wake-up they need. */
|
||||
private suspend fun reminders(lastFired: Long, now: Long, horizon: Long): Long {
|
||||
syncChannels()
|
||||
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
|
||||
// Reach into the past too: an all-day "at time of event" encodes to a
|
||||
// negative offset, and a catch-up pass needs the occurrences it missed.
|
||||
// Calendars muted in-app (#272) plan nothing, so they arm no wake-ups.
|
||||
val muted = settingsPrefs.mutedReminderCalendarIds.first()
|
||||
val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead)
|
||||
.filter { it.calendarId !in muted }
|
||||
val planned = planReminders(
|
||||
instances = occurrences,
|
||||
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
|
||||
@@ -125,9 +99,9 @@ class ReminderScanner @Inject constructor(
|
||||
|
||||
val schedule = scheduleReminders(
|
||||
planned = planned,
|
||||
lastFiredMillis = lastFired,
|
||||
lastFiredMillis = reminderWatermark(state.lastScanMillis(), now),
|
||||
nowMillis = now,
|
||||
horizonMillis = horizon,
|
||||
horizonMillis = now + MAX_ALARM_INTERVAL_MILLIS,
|
||||
)
|
||||
|
||||
if (notifier.canPost()) {
|
||||
@@ -137,61 +111,10 @@ class ReminderScanner @Inject constructor(
|
||||
notifier.post(alert)
|
||||
}
|
||||
}
|
||||
return schedule.nextAlarmMillis
|
||||
}
|
||||
|
||||
/**
|
||||
* Post the daily summary if it is owed (#459); returns its next moment. It
|
||||
* leaves out calendars excluded from it, not those muted for reminders —
|
||||
* a calendar too noisy to ping per event can still belong in the overview.
|
||||
*/
|
||||
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val listed = try {
|
||||
state.lastDigestDay()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not read the last daily summary", e)
|
||||
null
|
||||
}
|
||||
val schedule = scheduleDigest(
|
||||
timeMinutes = settings.timeMinutes,
|
||||
day = settings.day,
|
||||
zone = zone,
|
||||
// A moment that passed before the summary was last changed is not owed.
|
||||
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
|
||||
nowMillis = now,
|
||||
lastListedDay = listed,
|
||||
)
|
||||
val day = schedule.dueDay
|
||||
// A blocked channel would swallow it; the day stays owed until allowed.
|
||||
if (day != null && notifier.canPost() && !digestNotifier.isChannelOff()) {
|
||||
// A failed summary must not cost the event reminders this pass owes.
|
||||
try {
|
||||
// A day either side: all-day occurrences sit at UTC midnight, which
|
||||
// can fall outside the local day they stand for.
|
||||
val from = day.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first()
|
||||
digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left))
|
||||
state.setLastDigestDay(day)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Daily summary failed", e)
|
||||
}
|
||||
}
|
||||
return schedule.nextAlarmMillis
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider change re-scans, so a calendar added, renamed or removed keeps
|
||||
* its channel in step here. Skipped while reminders are off, when the
|
||||
* channels have nothing to do. A failure never costs the reminders.
|
||||
*/
|
||||
private fun syncChannels() {
|
||||
try {
|
||||
channels.sync()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Reminder channel sync failed", e)
|
||||
}
|
||||
// Advance even when nothing could be posted, so muting notifications
|
||||
// doesn't build a backlog.
|
||||
state.setLastScanMillis(now)
|
||||
alarms.scheduleScan(schedule.nextAlarmMillis)
|
||||
}
|
||||
|
||||
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||
@@ -235,8 +158,5 @@ class ReminderScanner @Inject constructor(
|
||||
const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000
|
||||
|
||||
const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L
|
||||
|
||||
/** How soon a pass whose reminders failed is tried again. */
|
||||
const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
@@ -42,12 +40,6 @@ data class EventForm(
|
||||
val description: String = "",
|
||||
/** Reminder lead times in minutes before the start, deduplicated. */
|
||||
val reminders: List<Int> = emptyList(),
|
||||
/**
|
||||
* "N days before at HH:MM" reminders of a timed event (#459), written as lead
|
||||
* times measured from [start] at save time. Ignored while [isAllDay], so a
|
||||
* round trip through all-day keeps them.
|
||||
*/
|
||||
val fixedReminders: List<FixedTimeReminder> = emptyList(),
|
||||
val availability: Availability = Availability.Busy,
|
||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||
/** Confirmed / Tentative / Cancelled (#388). */
|
||||
@@ -294,7 +286,7 @@ fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
|
||||
if (location.isNotBlank()) add(EventFormField.Location)
|
||||
if (description.isNotBlank()) add(EventFormField.Description)
|
||||
if (timezone != null) add(EventFormField.Timezone)
|
||||
if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders)
|
||||
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
|
||||
if (rrule != null) add(EventFormField.Recurrence)
|
||||
if (availability != Availability.Busy) add(EventFormField.Availability)
|
||||
if (status != EventStatus.Confirmed) add(EventFormField.Status)
|
||||
@@ -328,40 +320,17 @@ fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
|
||||
/**
|
||||
* A create form seeded from this occurrence, to save a copy as a new,
|
||||
* independent event (#52). The recurrence is dropped — a duplicate is a single
|
||||
* event. The source calendar is only requested: the editor keeps it while it can
|
||||
* take new events and otherwise resolves the calendar like a new event, which
|
||||
* lets a read-only event be copied into an editable one. [instance]'s own times
|
||||
* carry over.
|
||||
* event. The source calendar is kept only when [canModify], otherwise the id is
|
||||
* cleared so the create resolves to a writable calendar, which lets a read-only
|
||||
* event be copied into an editable one. [instance]'s own times carry over.
|
||||
*/
|
||||
fun EventDetail.toDuplicateForm(
|
||||
zone: TimeZone,
|
||||
knownFixed: Set<FixedTimeReminder> = emptySet(),
|
||||
): EventForm =
|
||||
fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
|
||||
toEditForm(
|
||||
beginMillis = instance.start.toEpochMilliseconds(),
|
||||
endMillis = instance.end.toEpochMilliseconds(),
|
||||
zone = zone,
|
||||
).withFixedTimeRemindersRead(knownFixed, zone).copy(
|
||||
).copy(
|
||||
rrule = null,
|
||||
calendarId = instance.calendarId.takeIf { canModify },
|
||||
status = status.forNewEvent(),
|
||||
)
|
||||
|
||||
/**
|
||||
* This form with its timed reminders read back into lead times and
|
||||
* [EventForm.fixedReminders] ([splitTimedReminders]), the wall clock taken in
|
||||
* [deviceZone]. All-day forms come back untouched.
|
||||
*/
|
||||
fun EventForm.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, deviceZone: TimeZone): EventForm {
|
||||
if (isAllDay || reminders.isEmpty()) return this
|
||||
val split = splitTimedReminders(
|
||||
reminders, startInstant(resolvedZone(deviceZone)), deviceZone, known, wallClock = rrule != null,
|
||||
)
|
||||
return copy(reminders = split.leadMinutes, fixedReminders = (fixedReminders + split.fixed).distinct())
|
||||
}
|
||||
|
||||
/** The offsets [EventForm.fixedReminders] store for this form's start; empty for an all-day form. */
|
||||
fun EventForm.fixedReminderOffsets(deviceZone: TimeZone): List<Int> {
|
||||
if (isAllDay || fixedReminders.isEmpty()) return emptyList()
|
||||
val start = startInstant(resolvedZone(deviceZone))
|
||||
return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) }
|
||||
}
|
||||
@@ -13,9 +13,9 @@ import kotlin.time.Instant
|
||||
* back to the same defaults the in-app "new event" uses — a timed start at the
|
||||
* next full hour, and a placeholder hour for a missing end that the form then
|
||||
* stretches to the default-duration setting (the intent is opened as
|
||||
* `ImportSource.InsertOpenEnded`, #54). [calendarId] is the calendar the
|
||||
* intent names, if any; the editor preselects it while it is a target and otherwise
|
||||
* resolves the calendar like a plain new event (#429).
|
||||
* `ImportSource.InsertOpenEnded`, #54). [EventForm.calendarId] is left null so
|
||||
* it resolves to the last-used / first-writable calendar, exactly like the
|
||||
* `.ics` single-event and plain new-event paths.
|
||||
*
|
||||
* Pure (no Android types) so it is unit-testable; the intent parsing that reads
|
||||
* the extras lives in `MainActivity.insertFormOrNull`.
|
||||
@@ -28,7 +28,6 @@ fun buildInsertEventForm(
|
||||
description: String?,
|
||||
location: String? = null,
|
||||
rrule: String? = null,
|
||||
calendarId: Long? = null,
|
||||
zone: TimeZone,
|
||||
now: Instant,
|
||||
): EventForm {
|
||||
@@ -45,7 +44,7 @@ fun buildInsertEventForm(
|
||||
startAt.toFormTime(zone) to endAt.toFormTime(zone)
|
||||
}
|
||||
return EventForm(
|
||||
calendarId = calendarId,
|
||||
calendarId = null,
|
||||
title = title.orEmpty(),
|
||||
isAllDay = isAllDay,
|
||||
start = start,
|
||||
|
||||
@@ -309,7 +309,3 @@ enum class FailureReason {
|
||||
EventNotFound,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/** [this] without the events of [hidden] calendars. */
|
||||
fun List<EventInstance>.withoutCalendars(hidden: Set<Long>): List<EventInstance> =
|
||||
if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden }
|
||||
@@ -1,76 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain
|
||||
|
||||
/**
|
||||
* The calendar chosen as default for new events (#429). Provider ids are
|
||||
* device-local and get reassigned when an account is re-added or a backup is
|
||||
* restored onto another device, so the account and name ride along: see [find].
|
||||
*/
|
||||
data class DefaultCalendarRef(
|
||||
val id: Long,
|
||||
val accountType: String,
|
||||
val accountName: String,
|
||||
val displayName: String,
|
||||
) {
|
||||
/**
|
||||
* The calendar this refers to: the exact one, else the account's calendar of
|
||||
* that name (the id changed), else the id within the account (it was renamed).
|
||||
*/
|
||||
fun find(calendars: List<CalendarSource>): CalendarSource? {
|
||||
val inAccount = calendars.filter { it.accountType == accountType && it.accountName == accountName }
|
||||
return inAccount.firstOrNull { it.id == id && it.displayName == displayName }
|
||||
?: inAccount.singleOrNull { it.displayName == displayName }
|
||||
?: inAccount.firstOrNull { it.id == id }
|
||||
}
|
||||
|
||||
fun encode(): String = listOf(id.toString(), accountType, accountName, displayName).joinToString(SEPARATOR)
|
||||
|
||||
companion object {
|
||||
private const val SEPARATOR = "\u001F"
|
||||
|
||||
fun of(calendar: CalendarSource) =
|
||||
DefaultCalendarRef(calendar.id, calendar.accountType, calendar.accountName, calendar.displayName)
|
||||
|
||||
fun decode(stored: String?): DefaultCalendarRef? {
|
||||
val parts = stored?.split(SEPARATOR, limit = 4)?.takeIf { it.size == 4 } ?: return null
|
||||
val id = parts[0].toLongOrNull() ?: return null
|
||||
return DefaultCalendarRef(id, parts[1], parts[2], parts[3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What decides a new event's calendar when the user hasn't picked one (#429).
|
||||
* [requested] is a calendar named by whoever opened the form (an insert intent,
|
||||
* a duplicate's source), [default] the "default calendar" setting and
|
||||
* [lastUsed] the calendar the last new event went into.
|
||||
*/
|
||||
data class NewEventCalendarHints(
|
||||
val requested: Long? = null,
|
||||
val default: DefaultCalendarRef? = null,
|
||||
val lastUsed: Long? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* The calendar the event form targets: [picked] when set, otherwise the first of
|
||||
* the requested, default and last-used calendar that is still an event target,
|
||||
* then the first target.
|
||||
*/
|
||||
fun resolveEventCalendar(
|
||||
picked: Long?,
|
||||
hints: NewEventCalendarHints,
|
||||
calendars: List<CalendarSource>,
|
||||
): Long? {
|
||||
fun Long.ifTarget() = takeIf { id -> calendars.any { it.id == id && it.isEventTarget } }
|
||||
return picked
|
||||
?: hints.requested?.ifTarget()
|
||||
?: effectiveDefaultCalendar(hints.default, calendars)?.id
|
||||
?: hints.lastUsed?.ifTarget()
|
||||
?: calendars.firstOrNull { it.isEventTarget }?.id
|
||||
}
|
||||
|
||||
/**
|
||||
* The default calendar setting as it applies now: null ("Automatic") when unset,
|
||||
* or when the stored calendar is gone, read-only or switched off.
|
||||
*/
|
||||
fun effectiveDefaultCalendar(default: DefaultCalendarRef?, calendars: List<CalendarSource>): CalendarSource? =
|
||||
default?.find(calendars)?.takeIf { it.isEventTarget }
|
||||
@@ -1,402 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.backup
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||
import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides
|
||||
import de.jeanlucmakiola.calendula.domain.isNotSynced
|
||||
import de.jeanlucmakiola.floret.android.safeFileName
|
||||
import java.security.MessageDigest
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
/**
|
||||
* Whether this calendar can be backed up at all. Any calendar the provider
|
||||
* holds can be *read* (#147), whatever its visibility or access level. Left out:
|
||||
* the managed special-dates mirrors, rebuilt from contacts so a restore would
|
||||
* only duplicate them, and calendars whose events aren't synced to the device.
|
||||
*/
|
||||
val CalendarSource.isBackupCandidate: Boolean
|
||||
get() = !isManaged && !isNotSynced
|
||||
|
||||
/**
|
||||
* Whether a backup includes this calendar until the user says otherwise: the
|
||||
* app's own writable local calendars, which have no other copy anywhere. Synced
|
||||
* calendars already live on their server, so they are opt-in.
|
||||
*/
|
||||
val CalendarSource.isBackedUpByDefault: Boolean
|
||||
get() = isLocal && canModifyContents && !isManaged
|
||||
|
||||
/**
|
||||
* Which calendars the automatic backup covers, stored as deviations from
|
||||
* [isBackedUpByDefault] so a calendar created later still follows the default:
|
||||
* [included] opts a calendar in, [excluded] opts one out.
|
||||
*/
|
||||
data class BackupSelection(
|
||||
val included: Set<Long> = emptySet(),
|
||||
val excluded: Set<Long> = emptySet(),
|
||||
) {
|
||||
fun selects(calendar: CalendarSource): Boolean = when {
|
||||
!calendar.isBackupCandidate -> false
|
||||
calendar.id in included -> true
|
||||
calendar.id in excluded -> false
|
||||
else -> calendar.isBackedUpByDefault
|
||||
}
|
||||
|
||||
/** The selection with [calendar] switched [on]; a choice matching the default leaves no trace. */
|
||||
fun with(calendar: CalendarSource, on: Boolean): BackupSelection {
|
||||
val id = calendar.id
|
||||
val default = calendar.isBackedUpByDefault
|
||||
return BackupSelection(
|
||||
included = if (on && !default) included + id else included - id,
|
||||
excluded = if (!on && default) excluded + id else excluded - id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One backup file series: the calendars it holds and the name its files start with. */
|
||||
data class BackupTarget(
|
||||
/** Stable identity of the series in the [BackupLedger]: the calendar id, or [COMBINED_SERIES]. */
|
||||
val key: String,
|
||||
val calendarIds: Set<Long>,
|
||||
val baseName: String,
|
||||
/** The calendar name written into the file, or null for a combined file. */
|
||||
val calendarName: String?,
|
||||
)
|
||||
|
||||
/** What one run writes and which earlier files it removes afterwards. */
|
||||
data class BackupFilePlan(
|
||||
val target: BackupTarget,
|
||||
val fileName: String,
|
||||
/** Earlier files of this series that stay, oldest first. */
|
||||
val keep: List<String>,
|
||||
/** Earlier files of this series beyond the retention count, oldest first. */
|
||||
val prune: List<String>,
|
||||
/**
|
||||
* The stable, undated copy overwritten every run (`<base>.ics`), for tools
|
||||
* that follow one path. Null when a file of that name is in the folder but
|
||||
* isn't one this backup wrote: the user's own file is never overwritten.
|
||||
*/
|
||||
val latestName: String?,
|
||||
/** This series' earlier stable copies under a name it no longer uses (a rename), to delete. */
|
||||
val staleLatest: List<String> = emptyList(),
|
||||
/**
|
||||
* Stable copies this series held that another series of the run now takes
|
||||
* over: kept on record until that series has claimed them.
|
||||
*/
|
||||
val handOff: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* The files the automatic backup has written, per series key, oldest first.
|
||||
* Pruning only ever deletes names recorded here, so a series is its files, not
|
||||
* whatever currently matches a calendar's name: renames, same-named calendars
|
||||
* and the user's own files in the folder can't pull in the wrong ones. A
|
||||
* series' stable copy is recorded apart, under [latestLedgerKey].
|
||||
*/
|
||||
typealias BackupLedger = Map<String, List<String>>
|
||||
|
||||
const val COMBINED_SERIES = "combined"
|
||||
|
||||
/** The combined file's series name; also the fixed name used before #411. */
|
||||
const val COMBINED_BACKUP_BASE = "calendula-backup"
|
||||
|
||||
/**
|
||||
* The single file every automatic backup overwrote before #411: the combined
|
||||
* series' stable copy now, so an old setup keeps its path.
|
||||
*/
|
||||
val LEGACY_BACKUP_FILE: String = latestFileName(COMBINED_BACKUP_BASE)
|
||||
|
||||
private const val LATEST_PREFIX = "latest-"
|
||||
|
||||
/** Where the ledger records the stable copy of the series [key]. */
|
||||
fun latestLedgerKey(key: String): String = "$LATEST_PREFIX$key"
|
||||
|
||||
/** The retention choices the settings offer, newest kept first. */
|
||||
val BACKUP_KEEP_OPTIONS: List<Int> = listOf(1, 2, 3, 5, 7, 10)
|
||||
|
||||
const val DEFAULT_BACKUP_KEEP = 3
|
||||
|
||||
/** Room for the id suffix and the stamp within a file system's 255-byte name limit. */
|
||||
private const val MAX_BASE_BYTES = 120
|
||||
private const val ICS_EXTENSION = ".ics"
|
||||
private const val STAMP_PATTERN = "yyyy-MM-dd_HH-mm-ss"
|
||||
private val STAMP_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern(STAMP_PATTERN)
|
||||
|
||||
/**
|
||||
* The file series the automatic backup writes: one combined file, or one per
|
||||
* calendar named after it. Calendars whose names clash case-insensitively (a
|
||||
* local and a synced "Personal") must not write the same file, and a path
|
||||
* 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
|
||||
* 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
|
||||
* 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
|
||||
* nothing. A calendar named like the combined file is always suffixed.
|
||||
*/
|
||||
fun backupTargets(
|
||||
calendars: List<CalendarSource>,
|
||||
combined: Boolean,
|
||||
ledger: BackupLedger = emptyMap(),
|
||||
existing: Set<String>? = null,
|
||||
): List<BackupTarget> {
|
||||
if (calendars.isEmpty()) return emptyList()
|
||||
if (combined) {
|
||||
return listOf(
|
||||
BackupTarget(COMBINED_SERIES, calendars.map { it.id }.toSet(), COMBINED_BACKUP_BASE, calendarName = null),
|
||||
)
|
||||
}
|
||||
val present = if (existing == null) ledger else ledger.mapValues { (_, names) -> names.filter { it in existing } }
|
||||
val bases = calendars.associateTo(LinkedHashMap()) {
|
||||
it.id to safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar")
|
||||
}
|
||||
while (true) {
|
||||
val clashing = bases.entries.groupBy({ it.value.lowercase() }, { it.key })
|
||||
.filter { (lower, ids) -> ids.size > 1 || lower == COMBINED_BACKUP_BASE.lowercase() }
|
||||
if (clashing.isEmpty()) break
|
||||
clashing.forEach { (lower, ids) ->
|
||||
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" }
|
||||
}
|
||||
}
|
||||
return calendars.map { calendar ->
|
||||
BackupTarget(
|
||||
key = calendar.id.toString(),
|
||||
calendarIds = setOf(calendar.id),
|
||||
baseName = bases.getValue(calendar.id),
|
||||
calendarName = calendar.displayName,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Which of the clashing [ids] keeps its name in [bases], or null when all take their suffix. */
|
||||
private fun BackupLedger.keeperOf(ids: List<Long>, bases: Map<Long, String>): Long? {
|
||||
fun base(id: Long) = bases.getValue(id)
|
||||
return ids.filter { holdsLatest(it.toString(), base(it)) }.minOrNull()
|
||||
?: ids.filter { holdsDated(it.toString(), base(it)) }.minOrNull()
|
||||
?: ids.filterNot { holdsLatest(it.toString(), "${base(it)}-$it") || holdsDated(it.toString(), "${base(it)}-$it") }
|
||||
.minOrNull()
|
||||
}
|
||||
|
||||
private fun BackupLedger.holdsLatest(key: String, base: String): Boolean =
|
||||
this[latestLedgerKey(key)].orEmpty().any { it.equals(latestFileName(base), ignoreCase = true) }
|
||||
|
||||
/** Dated files of [base], including ones a provider renamed (`… (1).ics`). */
|
||||
private fun BackupLedger.holdsDated(key: String, base: String): Boolean {
|
||||
val dated = Regex(
|
||||
"${Regex.escape(base)}_\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}.*\\.ics",
|
||||
RegexOption.IGNORE_CASE,
|
||||
)
|
||||
return this[key].orEmpty().any { dated.matches(it) }
|
||||
}
|
||||
|
||||
/** `Work_2026-11-13_14-30-05.ics`: the series name and the local time of the run. */
|
||||
fun backupFileName(baseName: String, at: LocalDateTime): String =
|
||||
"${baseName}_${at.format(STAMP_FORMAT)}$ICS_EXTENSION"
|
||||
|
||||
/**
|
||||
* Plan one run: a new dated file per target, and which of the series' recorded
|
||||
* files ([ledger]) fall out of the newest [keep], the new one included. Recorded
|
||||
* files no longer in the folder ([existing]) are forgotten. Each target also
|
||||
* gets its stable copy, which retention never touches. A stable name is only
|
||||
* written when the file is absent or this series owns it — or a series of this
|
||||
* run that is moving off it (a rename hand-off).
|
||||
*/
|
||||
fun planBackupFiles(
|
||||
targets: List<BackupTarget>,
|
||||
ledger: BackupLedger,
|
||||
existing: Set<String>,
|
||||
at: LocalDateTime,
|
||||
keep: Int,
|
||||
): List<BackupFilePlan> {
|
||||
val retain = keep.coerceAtLeast(1)
|
||||
val runKeys = targets.map { it.key }.toSet()
|
||||
val owners = ledger.filterKeys { it.startsWith(LATEST_PREFIX) }
|
||||
.flatMap { (key, names) -> names.map { it to key.removePrefix(LATEST_PREFIX) } }
|
||||
.toMap()
|
||||
val currentLatest = targets.map { latestFileName(it.baseName) }.toSet()
|
||||
return targets.map { target ->
|
||||
val fileName = backupFileName(target.baseName, at)
|
||||
val latest = latestFileName(target.baseName)
|
||||
val earlier = ledger[target.key].orEmpty()
|
||||
.filter { it in existing && it != fileName && it != latest }
|
||||
.distinct()
|
||||
val kept = earlier.takeLast(retain - 1)
|
||||
val owner = owners[latest]
|
||||
val writable = latest !in existing || (owner != null && owner in runKeys)
|
||||
BackupFilePlan(
|
||||
target = target,
|
||||
fileName = fileName,
|
||||
keep = kept,
|
||||
prune = earlier.dropLast(kept.size),
|
||||
latestName = latest.takeIf { writable },
|
||||
staleLatest = ledger[latestLedgerKey(target.key)].orEmpty()
|
||||
.filter { it in existing && it != latest && it !in currentLatest },
|
||||
handOff = ledger[latestLedgerKey(target.key)].orEmpty()
|
||||
.filter { it in existing && it != latest && it in currentLatest },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable copies the current layout replaced, per ledger key: a calendar's own
|
||||
* copy once the combined file holds it, or the combined copy once each calendar
|
||||
* has its own. Left in place they would keep serving old data under a path
|
||||
* something may follow. A calendar taken out of the backup keeps its copy.
|
||||
*/
|
||||
fun replacedLatestCopies(
|
||||
targets: List<BackupTarget>,
|
||||
ledger: BackupLedger,
|
||||
existing: Set<String>,
|
||||
): Map<String, List<String>> {
|
||||
val runKeys = targets.map { it.key }.toSet()
|
||||
val covered = targets.flatMap { it.calendarIds }.map { it.toString() }.toSet()
|
||||
val currentLatest = targets.map { latestFileName(it.baseName) }.toSet()
|
||||
val combinedRun = COMBINED_SERIES in runKeys
|
||||
return ledger.filterKeys { it.startsWith(LATEST_PREFIX) }
|
||||
.mapKeys { it.key.removePrefix(LATEST_PREFIX) }
|
||||
.filterKeys { key ->
|
||||
key !in runKeys && (if (key == COMBINED_SERIES) !combinedRun else combinedRun && key in covered)
|
||||
}
|
||||
.mapValues { (_, names) -> names.filter { it in existing && it !in currentLatest } }
|
||||
.filterValues { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/**
|
||||
* The ledger with [key]'s files set to [files] (empty drops the entry). Entries
|
||||
* of deleted calendars go ([liveKeys]); their files stay, unrecorded. Others
|
||||
* stay, so a calendar taken out of the backup still has its files pruned if it
|
||||
* is put back.
|
||||
*/
|
||||
fun withLedgerEntry(
|
||||
previous: BackupLedger,
|
||||
key: String,
|
||||
files: List<String>,
|
||||
liveKeys: Set<String>,
|
||||
): BackupLedger {
|
||||
val next = previous.filterKeys { entry ->
|
||||
val series = entry.removePrefix(LATEST_PREFIX)
|
||||
series in liveKeys || series == COMBINED_SERIES
|
||||
}.toMutableMap()
|
||||
next[key] = files.distinct()
|
||||
// A stable copy has one owner: claiming it takes it off any other series.
|
||||
if (key.startsWith(LATEST_PREFIX)) {
|
||||
next.keys.filter { it != key && it.startsWith(LATEST_PREFIX) }.forEach { other ->
|
||||
next[other] = next.getValue(other) - files.toSet()
|
||||
}
|
||||
}
|
||||
return next.filterValues { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** Stable copies recorded under any series but [key] — a hand-off that has already been claimed. */
|
||||
fun BackupLedger.latestHeldElsewhere(key: String): Set<String> =
|
||||
filterKeys { it.startsWith(LATEST_PREFIX) && it != latestLedgerKey(key) }.values.flatten().toSet()
|
||||
|
||||
/** `Work.ics`: the series' stable copy. */
|
||||
fun latestFileName(baseName: String): String = "$baseName$ICS_EXTENSION"
|
||||
|
||||
private const val LEDGER_ENTRY_SEP = "|"
|
||||
private const val LEDGER_KEY_SEP = "/"
|
||||
|
||||
/** Stores the ledger; both separators are characters no name this app writes can hold. */
|
||||
fun persistBackupLedger(ledger: BackupLedger): String? =
|
||||
ledger.filterValues { it.isNotEmpty() }.takeIf { it.isNotEmpty() }
|
||||
?.entries?.sortedBy { it.key }
|
||||
?.joinToString(LEDGER_ENTRY_SEP) { (key, names) -> (listOf(key) + names).joinToString(LEDGER_KEY_SEP) }
|
||||
|
||||
fun parseBackupLedger(stored: String?): BackupLedger =
|
||||
stored?.split(LEDGER_ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split(LEDGER_KEY_SEP)
|
||||
val names = parts.drop(1).filter { it.isNotEmpty() }
|
||||
parts.first().takeIf { it.isNotEmpty() && names.isNotEmpty() }?.let { it to names }
|
||||
}.toMap()
|
||||
|
||||
/** Closest offered retention count to [stored], so a stray value still shows a row. */
|
||||
fun normalizeBackupKeep(stored: Int): Int =
|
||||
BACKUP_KEEP_OPTIONS.minBy { kotlin.math.abs(it - stored) }
|
||||
|
||||
/**
|
||||
* Content hash of a series' file, per series key (#516), so a run started by a
|
||||
* change can tell whether the calendars it covers changed at all.
|
||||
*/
|
||||
typealias BackupFingerprints = Map<String, String>
|
||||
|
||||
/**
|
||||
* Hash of a series' file, leaving out the run's `DTSTAMP`s so equal events give
|
||||
* an equal hash, and bound to the stable copy's [fileName], so a copy under
|
||||
* another name never passes as current.
|
||||
*/
|
||||
fun backupFingerprint(ics: String, fileName: String): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
digest.update(fileName.toByteArray(Charsets.UTF_8))
|
||||
digest.update(LINE_BREAK)
|
||||
ics.lineSequence().filterNot { it.startsWith(DTSTAMP_PREFIX) }
|
||||
.forEach {
|
||||
digest.update(it.toByteArray(Charsets.UTF_8))
|
||||
digest.update(LINE_BREAK)
|
||||
}
|
||||
return digest.digest().take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/** [previous] with [key] set to [fingerprint]; entries of deleted calendars go, as in [withLedgerEntry]. */
|
||||
fun withFingerprint(
|
||||
previous: BackupFingerprints,
|
||||
key: String,
|
||||
fingerprint: String,
|
||||
liveKeys: Set<String>,
|
||||
): BackupFingerprints =
|
||||
previous.filterKeys { it in liveKeys || it == COMBINED_SERIES } + (key to fingerprint)
|
||||
|
||||
private const val FINGERPRINT_BYTES = 16
|
||||
private const val DTSTAMP_PREFIX = "DTSTAMP:"
|
||||
private val LINE_BREAK = byteArrayOf('\n'.code.toByte())
|
||||
private const val FINGERPRINT_SEP = "="
|
||||
|
||||
fun persistBackupFingerprints(fingerprints: BackupFingerprints): String? =
|
||||
fingerprints.takeIf { it.isNotEmpty() }
|
||||
?.entries?.sortedBy { it.key }
|
||||
?.joinToString(LEDGER_ENTRY_SEP) { (key, hash) -> "$key$FINGERPRINT_SEP$hash" }
|
||||
|
||||
fun parseBackupFingerprints(stored: String?): BackupFingerprints =
|
||||
stored?.split(LEDGER_ENTRY_SEP).orEmpty().mapNotNull { entry ->
|
||||
val key = entry.substringBefore(FINGERPRINT_SEP, "")
|
||||
val hash = entry.substringAfter(FINGERPRINT_SEP, "")
|
||||
if (key.isEmpty() || hash.isEmpty()) null else key to hash
|
||||
}.toMap()
|
||||
|
||||
/**
|
||||
* Whether a run started by a change (#516) rewrites this series' stable copy:
|
||||
* 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,
|
||||
* 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.
|
||||
*/
|
||||
fun BackupFilePlan.needsRefresh(
|
||||
fingerprint: String,
|
||||
stored: BackupFingerprints,
|
||||
listed: Set<String>,
|
||||
complete: Boolean,
|
||||
): Boolean {
|
||||
val latest = latestName ?: return false
|
||||
if (latest !in listed) return complete
|
||||
return stored[target.key] != fingerprint
|
||||
}
|
||||
|
||||
/**
|
||||
* The events in a fixed order, their lists sorted, so the same content always
|
||||
* writes the same file and hashes the same, however the provider returned it.
|
||||
* Standalone occurrences stay first, as [flattenOverrides] puts them.
|
||||
*/
|
||||
fun List<IcsEvent>.inBackupOrder(): List<IcsEvent> =
|
||||
map {
|
||||
it.copy(
|
||||
reminderMinutes = it.reminderMinutes.sorted(),
|
||||
exDates = it.exDates.sorted(),
|
||||
recurrenceDates = it.recurrenceDates.sorted(),
|
||||
)
|
||||
}.sortedWith(
|
||||
compareBy<IcsEvent>(
|
||||
{ it.overrideOf == null }, { it.start }, { it.uid }, { it.overrideAt }, { it.calendarName },
|
||||
{ it.toString() },
|
||||
),
|
||||
)
|
||||
@@ -1,74 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.ics
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import kotlin.time.Duration.Companion.days
|
||||
|
||||
/**
|
||||
* The events a calendar copy (#325) inserts into its target, in the shape
|
||||
* `importEvents` takes: the source's rows flattened as [flattenOverrides] does
|
||||
* for a backup, minus cancelled series and one-offs, which would arrive live
|
||||
* (an insert can't be cancelled), and declined invitations and occurrences. Attendees and organizer are never read.
|
||||
*
|
||||
* Idempotent per snapshot: `importEvents` skips a UID the target already holds,
|
||||
* and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run
|
||||
* keeps the earlier copy of an occurrence changed since rather than adding a
|
||||
* second one beside it.
|
||||
*/
|
||||
fun planCalendarCopy(
|
||||
rows: CalendarRows,
|
||||
exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String,
|
||||
): List<ParsedIcsEvent> {
|
||||
val declinedSeries = rows.series.filter { it.declined }
|
||||
val declinedIds = declinedSeries.map { it.eventId }.toSet()
|
||||
val declinedSyncIds = declinedSeries.filter { it.syncId != null }.map { it.calendarId to it.syncId }.toSet()
|
||||
fun OverrideRow.ofDeclinedSeries() =
|
||||
originalId in declinedIds || (originalSyncId != null && (calendarId to originalSyncId) in declinedSyncIds)
|
||||
val live = CalendarRows(
|
||||
series = rows.series.filterNot { it.event.status == EventStatus.Cancelled },
|
||||
// A declined occurrence is as good as deleted here, and so is one of a
|
||||
// declined series the user didn't accept on its own.
|
||||
overrides = rows.overrides.map {
|
||||
if (it.declined || (it.ofDeclinedSeries() && !it.accepted)) {
|
||||
it.copy(event = it.event.copy(status = EventStatus.Cancelled))
|
||||
} else {
|
||||
it
|
||||
}
|
||||
},
|
||||
)
|
||||
// A declined series still hands its accepted occurrences on before it goes.
|
||||
// The flattened series follow the standalone occurrences, one per row in order.
|
||||
val flat = flattenOverrides(live, exdateStamp)
|
||||
val standalone = flat.size - live.series.size
|
||||
return flat.filterIndexed { i, _ -> i < standalone || live.series[i - standalone].eventId !in declinedIds }
|
||||
.map { it.toParsedIcsEvent() }
|
||||
}
|
||||
|
||||
/**
|
||||
* [IcsEvent] read back as if [IcsWriter] had written it and [IcsParser] had read
|
||||
* it, without the text in between. Unlike that round trip it keeps a one-off's
|
||||
* own time zone (the writer pins it to UTC) and the event's colour (not part of
|
||||
* the file format).
|
||||
*/
|
||||
fun IcsEvent.toParsedIcsEvent(): ParsedIcsEvent = ParsedIcsEvent(
|
||||
uid = uid,
|
||||
summary = summary,
|
||||
start = start,
|
||||
// RFC 5545 §3.6.1: an all-day event lasts at least its one day; zero-length
|
||||
// it expands into no instance at all.
|
||||
end = if (isAllDay && end <= start) start + 1.days else end,
|
||||
isAllDay = isAllDay,
|
||||
zoneId = zoneId,
|
||||
recurrenceRule = recurrenceRule?.takeIf { it.isNotBlank() }?.removePrefix("RRULE:"),
|
||||
recurrenceDates = recurrenceDates.filter { it.isNotBlank() }.distinct(),
|
||||
location = location,
|
||||
description = description,
|
||||
// The writer emits only lead times; a negative one would be an alarm after the start.
|
||||
reminderMinutes = reminderMinutes.filter { it >= 0 }.distinct(),
|
||||
status = status,
|
||||
availability = availability,
|
||||
accessLevel = accessLevel,
|
||||
color = color,
|
||||
overrideOf = overrideOf,
|
||||
overrideAt = overrideAt,
|
||||
exDates = if (recurs) exDates.filter { it.isNotBlank() }.distinct() else emptyList(),
|
||||
)
|
||||
@@ -1,99 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.ics
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A master or one-off Events row of a calendar being backed up or copied, with
|
||||
* the provider keys its exception rows point back through.
|
||||
*/
|
||||
data class MasterRow(
|
||||
val eventId: Long,
|
||||
val calendarId: Long,
|
||||
val syncId: String?,
|
||||
val event: IcsEvent,
|
||||
/** The user declined this invitation. */
|
||||
val declined: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* An exception row: a modified or cancelled occurrence of the series named by
|
||||
* [originalId] / [originalSyncId] in [calendarId], standing in for the
|
||||
* occurrence that would have started at [originalInstance].
|
||||
*/
|
||||
data class OverrideRow(
|
||||
val calendarId: Long,
|
||||
val originalId: Long?,
|
||||
val originalSyncId: String?,
|
||||
val originalInstance: Instant,
|
||||
val event: IcsEvent,
|
||||
/** The user declined this occurrence. */
|
||||
val declined: Boolean = false,
|
||||
/** The user accepted (or tentatively accepted) this occurrence on its own. */
|
||||
val accepted: Boolean = false,
|
||||
) {
|
||||
val isCancelled: Boolean get() = event.status == EventStatus.Cancelled
|
||||
}
|
||||
|
||||
/** Every event row a backup or copy reads: series/one-offs and their exception rows. */
|
||||
data class CalendarRows(
|
||||
val series: List<MasterRow>,
|
||||
val overrides: List<OverrideRow>,
|
||||
)
|
||||
|
||||
/**
|
||||
* [rows] as plain events with no exception rows left, the shape both a backup
|
||||
* file and a copied calendar need: neither can hold an exception row, since one
|
||||
* only attaches to its series through a `_sync_id` (and an `.ics` restore skips
|
||||
* `RECURRENCE-ID` overrides).
|
||||
*
|
||||
* Every override excludes its occurrence from the series (`EXDATE`), and a
|
||||
* modified one comes along as a standalone event at its own times, marked
|
||||
* [IcsEvent.overrideOf] its series — what Calendula itself writes for "only this
|
||||
* event" on an unsynced series. Its UID is derived from the series' UID and the
|
||||
* occurrence, so it is the same on every run. Overrides whose series isn't
|
||||
* among the rows are left out; the provider doesn't show them either.
|
||||
*
|
||||
* Standalone occurrences come first; `importEvents` enforces that order for
|
||||
* any file, so an import cut short leaves at worst an occurrence missing its
|
||||
* series, never a series missing an occurrence.
|
||||
*
|
||||
* [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's
|
||||
* shape, the same one Calendula's own exclusions use. A cancelled series'
|
||||
* modified occurrences stay cancelled.
|
||||
*/
|
||||
fun flattenOverrides(
|
||||
rows: CalendarRows,
|
||||
exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String,
|
||||
): List<IcsEvent> {
|
||||
val byId = rows.series.associateBy { it.eventId }
|
||||
// Sync ids are only unique within an account, so the link is per calendar.
|
||||
val bySyncId = rows.series.filter { it.syncId != null }.associateBy { it.calendarId to it.syncId }
|
||||
val excluded = mutableMapOf<Long, MutableList<String>>()
|
||||
val detached = mutableListOf<Pair<Long, IcsEvent>>()
|
||||
for (override in rows.overrides) {
|
||||
val parent = override.originalId?.let(byId::get)?.takeIf { it.calendarId == override.calendarId }
|
||||
?: override.originalSyncId?.let { bySyncId[override.calendarId to it] }
|
||||
?: continue
|
||||
// An exception to a one-off overrides nothing a plain event could carry.
|
||||
if (!parent.event.recurs) continue
|
||||
val occurrence = override.originalInstance.toEpochMilliseconds()
|
||||
excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay)
|
||||
if (override.isCancelled || parent.event.status == EventStatus.Cancelled) continue
|
||||
detached += override.calendarId to override.event.copy(
|
||||
uid = "$occurrence-${parent.event.uid}",
|
||||
recurrenceRule = null,
|
||||
recurrenceDates = emptyList(),
|
||||
exDates = emptyList(),
|
||||
overrideOf = parent.event.uid,
|
||||
overrideAt = override.originalInstance,
|
||||
)
|
||||
}
|
||||
// Two exception rows for one occurrence would derive the same UID; the same
|
||||
// series in two calendars legitimately does.
|
||||
return detached.distinctBy { (calendarId, event) -> calendarId to event.uid }.map { it.second } +
|
||||
rows.series.map { s ->
|
||||
val extra = excluded[s.eventId].orEmpty()
|
||||
if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.domain.ics
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.Availability
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import kotlin.time.Instant
|
||||
@@ -37,25 +36,8 @@ data class IcsEvent(
|
||||
val availability: Availability = Availability.Busy,
|
||||
/** Source calendar name, emitted as `X-CALENDULA-CALENDAR` so a combined backup can fan back out. */
|
||||
val calendarName: String? = null,
|
||||
/** Extra occurrences (`RDATE`), in the same shape as [exDates]. */
|
||||
val recurrenceDates: List<String> = emptyList(),
|
||||
/** Carried by a calendar copy, not written to a file. */
|
||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||
/** The event's own colour, null when it shows its calendar's; carried by a calendar copy, not written to a file. */
|
||||
val color: Int? = null,
|
||||
/**
|
||||
* For a modified occurrence written out on its own ([flattenOverrides]): the
|
||||
* UID of the series it replaces an occurrence of, as `X-CALENDULA-OVERRIDE-OF`.
|
||||
*/
|
||||
val overrideOf: String? = null,
|
||||
/** The occurrence of [overrideOf] this event replaces, as `X-CALENDULA-OVERRIDE-AT`. */
|
||||
val overrideAt: Instant? = null,
|
||||
)
|
||||
|
||||
/** Whether this is a series: by rule, or by listed dates alone. */
|
||||
val IcsEvent.recurs: Boolean
|
||||
get() = !recurrenceRule.isNullOrBlank() || recurrenceDates.isNotEmpty()
|
||||
|
||||
/**
|
||||
* The UID to export for a provider event. A row that already carries a UID
|
||||
* (`Events.UID_2445`) keeps it; otherwise we synthesise a **stable** one from
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.domain.ics
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.Availability
|
||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||
import de.jeanlucmakiola.calendula.domain.zoneOrNull
|
||||
@@ -46,17 +45,6 @@ data class ParsedIcsEvent(
|
||||
val exDates: List<String> = emptyList(),
|
||||
/** True when this came from a `VTODO` rather than a `VEVENT`. */
|
||||
val isTask: Boolean = false,
|
||||
/**
|
||||
* The UID of the series this standalone occurrence replaces one occurrence
|
||||
* of (`X-CALENDULA-OVERRIDE-OF`). An import skips it where that series
|
||||
* already is, since the series there carries its own override.
|
||||
*/
|
||||
val overrideOf: String? = null,
|
||||
/** The occurrence of [overrideOf] this event replaces (`X-CALENDULA-OVERRIDE-AT`). */
|
||||
val overrideAt: Instant? = null,
|
||||
/** Extra occurrences (`RDATE`), in the same shape as [exDates]. */
|
||||
val recurrenceDates: List<String> = emptyList(),
|
||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -224,10 +212,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
var calendarColor: Int? = null
|
||||
val reminders = mutableListOf<Int>()
|
||||
val exDateLines = mutableListOf<IcsContentLine>()
|
||||
val rDateLines = mutableListOf<IcsContentLine>()
|
||||
var skipAsOverride = false
|
||||
var overrideOf: String? = null
|
||||
var overrideAt: Instant? = null
|
||||
|
||||
var i = 0
|
||||
while (i < body.size) {
|
||||
@@ -248,7 +233,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
"DURATION" -> duration = line.value.trim()
|
||||
"RRULE" -> rrule = line.value.trim().ifEmpty { null }
|
||||
"EXDATE" -> exDateLines.add(line)
|
||||
"RDATE" -> rDateLines.add(line)
|
||||
"LOCATION" -> location = unescapeText(line.value).ifEmpty { null }
|
||||
"DESCRIPTION" -> description = unescapeText(line.value).ifEmpty { null }
|
||||
"STATUS" -> status = mapIcsStatus(line.value)
|
||||
@@ -257,8 +241,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
else Availability.Busy
|
||||
"RECURRENCE-ID" -> skipAsOverride = true
|
||||
"ATTENDEE" -> warnings.add(IcsParseWarning.AttendeesIgnored)
|
||||
"X-CALENDULA-OVERRIDE-OF" -> overrideOf = unescapeText(line.value).trim().ifEmpty { null }
|
||||
"X-CALENDULA-OVERRIDE-AT" -> overrideAt = parseBasicDateTime(line.value.trim())?.toInstant(TimeZone.UTC)
|
||||
"X-CALENDULA-CALENDAR" ->
|
||||
calendarName = unescapeText(line.value).trim().ifEmpty { calendarName }
|
||||
// Fossify names the source calendar per event; it never writes
|
||||
@@ -297,7 +279,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
val recurrence = sanitizeRrule(rrule)
|
||||
if (recurrence.repaired) warnings.add(IcsParseWarning.RecurrenceRuleRepaired)
|
||||
val end = resolveEnd(start, dtEnd, duration)
|
||||
val recurrenceDates = normalizeExDates(rDateLines, start)
|
||||
return ParsedIcsEvent(
|
||||
uid = uid,
|
||||
summary = summary,
|
||||
@@ -313,15 +294,12 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
availability = availability,
|
||||
calendarName = calendarName ?: category,
|
||||
color = eventColor ?: calendarColor,
|
||||
exDates = if (recurrence.rule == null && recurrenceDates.isEmpty()) {
|
||||
exDates = if (recurrence.rule == null) {
|
||||
emptyList()
|
||||
} else {
|
||||
normalizeExDates(exDateLines, start)
|
||||
},
|
||||
recurrenceDates = recurrenceDates,
|
||||
isTask = isTask,
|
||||
overrideOf = overrideOf,
|
||||
overrideAt = overrideAt,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -356,16 +334,13 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
||||
* still means the day it spells out; resolving it to an instant first and
|
||||
* reading *that* back in UTC would roll a midnight east of UTC onto the day
|
||||
* before and exclude an occurrence that doesn't exist.
|
||||
*
|
||||
* `RDATE` shares the value form and is read here too.
|
||||
*/
|
||||
private fun normalizeExDates(lines: List<IcsContentLine>, start: IcsDateTime): List<String> {
|
||||
if (lines.isEmpty()) return emptyList()
|
||||
val startZone = zoneOrNull(start.zoneId) ?: deviceZone
|
||||
val startTime = start.instant.toLocalDateTime(startZone).time
|
||||
return lines
|
||||
// An RDATE PERIOD (`start/end`) counts by its start.
|
||||
.flatMap { line -> line.value.split(',').map { line to it.trim().substringBefore('/') } }
|
||||
.flatMap { line -> line.value.split(',').map { line to it.trim() } }
|
||||
.mapNotNull { (line, token) ->
|
||||
when {
|
||||
token.isEmpty() -> null
|
||||
|
||||
@@ -25,14 +25,12 @@ const val ICS_PROD_ID: String = "-//Jean-Luc Makiola//Calendula//EN"
|
||||
*/
|
||||
class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
|
||||
/** [calendarName], when given, names the whole file (`X-WR-CALNAME`), as a one-calendar backup does. */
|
||||
fun writeCalendar(events: List<IcsEvent>, dtStamp: Instant, calendarName: String? = null): String {
|
||||
fun writeCalendar(events: List<IcsEvent>, dtStamp: Instant): String {
|
||||
val lines = buildList {
|
||||
add("BEGIN:VCALENDAR")
|
||||
add("VERSION:2.0")
|
||||
add("PRODID:$prodId")
|
||||
add("CALSCALE:GREGORIAN")
|
||||
calendarName?.takeIf { it.isNotBlank() }?.let { add("X-WR-CALNAME:${escapeText(it)}") }
|
||||
events.forEach { appendEvent(it, dtStamp) }
|
||||
add("END:VCALENDAR")
|
||||
}
|
||||
@@ -47,7 +45,6 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
appendTimes(event)
|
||||
event.recurrenceRule?.takeIf { it.isNotBlank() }
|
||||
?.let { add("RRULE:${it.removePrefix("RRULE:")}") }
|
||||
appendRecurrenceDates(event)
|
||||
appendExDates(event)
|
||||
event.location?.takeIf { it.isNotBlank() }
|
||||
?.let { add("LOCATION:${escapeText(it)}") }
|
||||
@@ -57,9 +54,6 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
add("TRANSP:${transpValue(event.availability)}")
|
||||
event.calendarName?.takeIf { it.isNotBlank() }
|
||||
?.let { add("X-CALENDULA-CALENDAR:${escapeText(it)}") }
|
||||
event.overrideOf?.takeIf { it.isNotBlank() }
|
||||
?.let { add("X-CALENDULA-OVERRIDE-OF:${escapeText(it)}") }
|
||||
event.overrideAt?.let { add("X-CALENDULA-OVERRIDE-AT:${it.toUtcBasic()}") }
|
||||
event.reminderMinutes.filter { it >= 0 }.distinct().forEach { minutes ->
|
||||
appendAlarm(minutes, event.summary)
|
||||
}
|
||||
@@ -72,7 +66,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
add("DTEND;VALUE=DATE:${event.end.toLocalDateTime(TimeZone.UTC).date.toBasic()}")
|
||||
}
|
||||
// Recurring: anchor to wall-clock in the event's own zone.
|
||||
event.recurs -> {
|
||||
event.recurrenceRule?.isNotBlank() == true -> {
|
||||
val zone = zoneOrNull(event.zoneId)
|
||||
if (zone != null) {
|
||||
add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}")
|
||||
@@ -89,14 +83,6 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Extra occurrences: the same UTC stamps / `VALUE=DATE` days as [appendExDates]. */
|
||||
private fun MutableList<String>.appendRecurrenceDates(event: IcsEvent) {
|
||||
val stamps = event.recurrenceDates.filter { it.isNotBlank() }.distinct()
|
||||
if (stamps.isEmpty()) return
|
||||
val prefix = if (event.isAllDay) "RDATE;VALUE=DATE:" else "RDATE:"
|
||||
add(prefix + stamps.joinToString(","))
|
||||
}
|
||||
|
||||
/**
|
||||
* The series' deleted occurrences. RFC 5545 ties `EXDATE`'s value type to
|
||||
* `DTSTART`'s, so an all-day series needs the explicit `VALUE=DATE` — without
|
||||
@@ -104,7 +90,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
||||
* recurring event: an exclusion names an occurrence, and a one-off has none.
|
||||
*/
|
||||
private fun MutableList<String>.appendExDates(event: IcsEvent) {
|
||||
if (!event.recurs) return
|
||||
if (event.recurrenceRule.isNullOrBlank()) return
|
||||
val stamps = event.exDates.filter { it.isNotBlank() }.distinct()
|
||||
if (stamps.isEmpty()) return
|
||||
val prefix = if (event.isAllDay) "EXDATE;VALUE=DATE:" else "EXDATE:"
|
||||
|
||||
@@ -10,7 +10,7 @@ import kotlinx.datetime.toLocalDateTime
|
||||
|
||||
/**
|
||||
* Prefill the create form from a single parsed `.ics` event (the "open one
|
||||
* event" path). [calendarId] is left null so the form preselects the default
|
||||
* event" path). [calendarId] is left null so the form preselects the last-used
|
||||
* calendar, exactly like a fresh create — the user confirms the target and
|
||||
* reviews everything before saving. Mirrors `EventDetail.toEditForm`'s all-day
|
||||
* handling (provider all-day times are UTC midnights with an exclusive end).
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
|
||||
/** Which day the daily summary (#459) lists, counted from the day it arrives. */
|
||||
enum class DigestDay(val daysAhead: Long) { Today(0), Tomorrow(1) }
|
||||
|
||||
/** 20:00, when the daily summary arrives until changed. */
|
||||
const val DEFAULT_DIGEST_TIME_MINUTES = 1_200
|
||||
|
||||
/**
|
||||
* The daily summary's settings. Calendars in [excludedCalendarIds] are left out
|
||||
* of it; [armedAtMillis] is when its switch, time or day last changed.
|
||||
*/
|
||||
data class DailyDigestSettings(
|
||||
val enabled: Boolean = false,
|
||||
val timeMinutes: Int = DEFAULT_DIGEST_TIME_MINUTES,
|
||||
val day: DigestDay = DigestDay.Tomorrow,
|
||||
val excludedCalendarIds: Set<Long> = emptySet(),
|
||||
val armedAtMillis: Long = 0L,
|
||||
)
|
||||
|
||||
/**
|
||||
* What one scan concluded for the summary: list [dueDay] now (null when nothing
|
||||
* is owed), and wake up again at [nextAlarmMillis].
|
||||
*/
|
||||
data class DigestSchedule(
|
||||
val dueDay: LocalDate?,
|
||||
val nextAlarmMillis: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* When the summary is owed: a moment in `(lastFiredMillis, nowMillis]` is due.
|
||||
* Only the latest such moment counts — a phone off for three evenings gets one
|
||||
* summary, not three — and only while the day it lists has not passed and is
|
||||
* not [lastListedDay]: each day is listed once.
|
||||
*/
|
||||
fun scheduleDigest(
|
||||
timeMinutes: Int,
|
||||
day: DigestDay,
|
||||
zone: ZoneId,
|
||||
lastFiredMillis: Long,
|
||||
nowMillis: Long,
|
||||
lastListedDay: LocalDate? = null,
|
||||
): DigestSchedule {
|
||||
val time = LocalTime.of(timeMinutes / 60, timeMinutes % 60)
|
||||
val fireAt = { date: LocalDate -> date.atTime(time).atZone(zone).toInstant().toEpochMilli() }
|
||||
val today = Instant.ofEpochMilli(nowMillis).atZone(zone).toLocalDate()
|
||||
val latestDate = if (fireAt(today) <= nowMillis) today else today.minusDays(1)
|
||||
val listed = latestDate.plusDays(day.daysAhead)
|
||||
val dueAt = fireAt(latestDate)
|
||||
val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) && it != lastListedDay }
|
||||
return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
|
||||
}
|
||||
|
||||
/**
|
||||
* The occurrences the summary for [day] lists: all-day ones covering it (their
|
||||
* UTC dates), then timed ones overlapping it in [zone], each group in start
|
||||
* order. Calendars in [excludedCalendarIds] are left out.
|
||||
*/
|
||||
fun digestEntries(
|
||||
instances: List<ReminderEventInstance>,
|
||||
day: LocalDate,
|
||||
zone: ZoneId,
|
||||
excludedCalendarIds: Set<Long>,
|
||||
): List<ReminderEventInstance> {
|
||||
val dayStart = day.atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val dayEnd = day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
val utcDay = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||
return instances
|
||||
.asSequence()
|
||||
.filter { it.calendarId !in excludedCalendarIds }
|
||||
.filter {
|
||||
if (it.isAllDay) {
|
||||
it.beginMillis <= utcDay && maxOf(it.endMillis, it.beginMillis + 1) > utcDay
|
||||
} else {
|
||||
it.beginMillis < dayEnd && maxOf(it.endMillis, it.beginMillis + 1) > dayStart
|
||||
}
|
||||
}
|
||||
.distinctBy { occurrenceKey(it.eventId, it.beginMillis) }
|
||||
.sortedWith(compareBy({ !it.isAllDay }, { it.beginMillis }, { it.title }))
|
||||
.toList()
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.LocalTime
|
||||
import kotlinx.datetime.TimeZone
|
||||
import kotlinx.datetime.minus
|
||||
import kotlinx.datetime.toInstant
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* A timed event's reminder "[daysBefore] days before, at [minuteOfDay]" (#459).
|
||||
*
|
||||
* The provider only knows lead times, so it is stored as an ordinary `Reminders`
|
||||
* row whose offset is the distance from that wall-clock moment to the start
|
||||
* ([offsetMinutes]) — it fires on every device and in every app. The pattern is
|
||||
* only known to Calendula while it can be read back ([classifyTimedReminder]); the
|
||||
* editor then re-derives the offset whenever the start moves.
|
||||
*/
|
||||
data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) {
|
||||
|
||||
init {
|
||||
require(daysBefore in 1..MAX_DAYS_BEFORE) { "daysBefore out of range: $daysBefore" }
|
||||
require(minuteOfDay in 0 until MINUTES_PER_DAY) { "minuteOfDay out of range: $minuteOfDay" }
|
||||
}
|
||||
|
||||
/** The wall clock this reminder names for an event starting at [start], read in [zone]. */
|
||||
private fun alarmWallClock(start: Instant, zone: TimeZone): LocalDateTime {
|
||||
val day = start.toLocalDateTime(zone).date.minus(daysBefore, DateTimeUnit.DAY)
|
||||
return LocalDateTime(day, LocalTime(minuteOfDay / 60, minuteOfDay % 60))
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider offset to store for an event starting at [start]: the real
|
||||
* minutes to that moment, or with [wallClock] the minutes on the clock face.
|
||||
* A recurring series stores one offset for every occurrence, so it takes the
|
||||
* wall-clock reading — otherwise an occurrence opened next to a DST change
|
||||
* would bake that hour into all the others.
|
||||
*/
|
||||
fun offsetMinutes(start: Instant, zone: TimeZone, wallClock: Boolean = false): Int {
|
||||
val alarm = alarmWallClock(start, zone)
|
||||
return if (wallClock) {
|
||||
(start.toLocalDateTime(zone).toInstant(TimeZone.UTC) - alarm.toInstant(TimeZone.UTC)).inWholeMinutes.toInt()
|
||||
} else {
|
||||
(start - alarm.toInstant(zone)).inWholeMinutes.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored form, `days@minuteOfDay`. */
|
||||
fun toToken(): String = "$daysBefore$TOKEN_SEP$minuteOfDay"
|
||||
|
||||
companion object {
|
||||
/** Two weeks, well inside the four weeks Google Calendar takes for a reminder. */
|
||||
const val MAX_DAYS_BEFORE = 14
|
||||
private const val TOKEN_SEP = "@"
|
||||
|
||||
/** [toToken] read back; null for anything malformed or out of range. */
|
||||
fun parse(token: String?): FixedTimeReminder? {
|
||||
val parts = token?.trim()?.split(TOKEN_SEP) ?: return null
|
||||
if (parts.size != 2) return null
|
||||
val days = parts[0].toIntOrNull() ?: return null
|
||||
val minute = parts[1].toIntOrNull() ?: return null
|
||||
if (days !in 1..MAX_DAYS_BEFORE || minute !in 0 until MINUTES_PER_DAY) return null
|
||||
return FixedTimeReminder(days, minute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" a raw offset lands on for an event starting at
|
||||
* [start], or null when it fires on the start's own day (or after it), or
|
||||
* further back than [FixedTimeReminder.MAX_DAYS_BEFORE]. [wallClock] reads the
|
||||
* offset as [FixedTimeReminder.offsetMinutes] wrote it.
|
||||
*/
|
||||
fun fixedTimeReminderAt(
|
||||
offsetMinutes: Int,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
wallClock: Boolean = false,
|
||||
): FixedTimeReminder? {
|
||||
if (offsetMinutes <= 0) return null
|
||||
val startLocal = start.toLocalDateTime(zone)
|
||||
val alarm = if (wallClock) {
|
||||
(startLocal.toInstant(TimeZone.UTC) - offsetMinutes.minutes).toLocalDateTime(TimeZone.UTC)
|
||||
} else {
|
||||
(start - offsetMinutes.minutes).toLocalDateTime(zone)
|
||||
}
|
||||
val startDate = startLocal.date
|
||||
val days = startDate.toEpochDays() - alarm.date.toEpochDays()
|
||||
if (days !in 1..FixedTimeReminder.MAX_DAYS_BEFORE) return null
|
||||
return FixedTimeReminder(days.toInt(), alarm.hour * 60 + alarm.minute)
|
||||
}
|
||||
|
||||
/** A timed event's reminders, read back: plain lead times and the fixed-time ones. */
|
||||
data class TimedReminders(
|
||||
val leadMinutes: List<Int>,
|
||||
val fixed: List<FixedTimeReminder>,
|
||||
)
|
||||
|
||||
/**
|
||||
* The fixed-time reminder [offsetMinutes] stands for on an event starting at
|
||||
* [start], or null when it reads as a plain lead time. The provider can't say
|
||||
* which an offset was meant as, so only the patterns in [known] — the configured
|
||||
* defaults, past and present, and the ones saved by hand on this device — are
|
||||
* recognised: guessing from the offset's shape alone would turn ordinary leads
|
||||
* ("12 hours before") into fixed-time ones. Where a lead and a known pattern
|
||||
* coincide ("1 day before" on an event at the default's own time) the pattern
|
||||
* wins. A wrong reading fires at the same moment; only a later change of the
|
||||
* start's time of day then treats the reminder the other way.
|
||||
*/
|
||||
fun classifyTimedReminder(
|
||||
offsetMinutes: Int,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
known: Set<FixedTimeReminder>,
|
||||
wallClock: Boolean = false,
|
||||
): FixedTimeReminder? = fixedTimeReminderAt(offsetMinutes, start, zone, wallClock)?.takeIf { it in known }
|
||||
|
||||
/** Sort a timed event's raw offsets into lead times and fixed-time reminders ([classifyTimedReminder]). */
|
||||
fun splitTimedReminders(
|
||||
offsets: List<Int>,
|
||||
start: Instant,
|
||||
zone: TimeZone,
|
||||
known: Set<FixedTimeReminder>,
|
||||
wallClock: Boolean = false,
|
||||
): TimedReminders {
|
||||
val leads = mutableListOf<Int>()
|
||||
val fixed = mutableListOf<FixedTimeReminder>()
|
||||
offsets.distinct().forEach { offset ->
|
||||
val pattern = classifyTimedReminder(offset, start, zone, known, wallClock)
|
||||
if (pattern != null) fixed += pattern else leads += offset
|
||||
}
|
||||
return TimedReminders(leads.sorted(), fixed.distinct().sortedWith(FIXED_ORDER))
|
||||
}
|
||||
|
||||
/** Most days before first, then by time — the order they fire in. */
|
||||
val FIXED_ORDER: Comparator<FixedTimeReminder> =
|
||||
compareByDescending<FixedTimeReminder> { it.daysBefore }.thenBy { it.minuteOfDay }
|
||||
|
||||
private const val MINUTES_PER_DAY = 1_440
|
||||
@@ -1,43 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
/** How a calendar's reminders get the user's attention (#171). */
|
||||
enum class ReminderAlertStyle(val storageValue: String) {
|
||||
/** An ordinary notification on the calendar's channel. */
|
||||
Notification("notification"),
|
||||
|
||||
/** A full-screen alert that sounds the calendar's notification sound once and stays until handled. */
|
||||
FullScreen("full_screen"),
|
||||
|
||||
/** A full-screen alert that rings and vibrates like an alarm until handled. */
|
||||
FullScreenRing("full_screen_ring"),
|
||||
;
|
||||
|
||||
val isFullScreen: Boolean get() = this != Notification
|
||||
|
||||
companion object {
|
||||
fun fromStorage(value: String): ReminderAlertStyle? = entries.firstOrNull { it.storageValue == value }
|
||||
}
|
||||
}
|
||||
|
||||
/** [calendarId]'s alert style; a calendar without one uses plain notifications. */
|
||||
fun Map<Long, ReminderAlertStyle>.alertStyleFor(calendarId: Long): ReminderAlertStyle =
|
||||
this[calendarId] ?: ReminderAlertStyle.Notification
|
||||
|
||||
/**
|
||||
* Parse `id=style` entries joined by `;`. Malformed entries and unknown styles
|
||||
* are dropped, so a garbled value degrades to plain notifications.
|
||||
*/
|
||||
fun parseAlertStyles(stored: String?): Map<Long, ReminderAlertStyle> =
|
||||
stored?.split(";").orEmpty().mapNotNull { entry ->
|
||||
val parts = entry.split("=")
|
||||
if (parts.size != 2) return@mapNotNull null
|
||||
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
|
||||
val style = ReminderAlertStyle.fromStorage(parts[1].trim()) ?: return@mapNotNull null
|
||||
calendarId to style
|
||||
}.toMap()
|
||||
|
||||
/** The stored form of [parseAlertStyles]; plain-notification entries are left out. */
|
||||
fun Map<Long, ReminderAlertStyle>.toStoredAlertStyles(): String =
|
||||
entries.filter { it.value != ReminderAlertStyle.Notification }
|
||||
.sortedBy { it.key }
|
||||
.joinToString(";") { (id, style) -> "$id=${style.storageValue}" }
|
||||
@@ -1,18 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
// Same link shape the detail screen linkifies (ui/detail/WebLinks.kt).
|
||||
private val webLinkRegex = Regex("""https?://[^\s<>"]+""", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* What a reminder's "Open in maps" button looks up for [location] — the same
|
||||
* text the detail screen's location card opens in maps — or null when there is
|
||||
* no place to find: blank, or nothing but web (meeting) links.
|
||||
*/
|
||||
fun reminderMapQuery(location: String?): String? {
|
||||
val trimmed = location?.trim()?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return trimmed.takeIf { webLinkRegex.replace(it, "").any(Char::isLetterOrDigit) }
|
||||
}
|
||||
|
||||
/** The first web (meeting) link in [location], for the reminder's "Open link" button; null without one. */
|
||||
fun reminderLink(location: String?): String? =
|
||||
location?.let { webLinkRegex.find(it)?.value?.trimEnd('.', ',', ';', ')', '>') }
|
||||
@@ -35,7 +35,6 @@ import androidx.compose.runtime.saveable.listSaver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberHeld
|
||||
import de.jeanlucmakiola.calendula.ui.common.screen
|
||||
import de.jeanlucmakiola.calendula.ui.common.ViewScreen
|
||||
@@ -53,14 +52,6 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen
|
||||
import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip
|
||||
import de.jeanlucmakiola.calendula.ui.common.StayingPut
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer
|
||||
import de.jeanlucmakiola.calendula.ui.common.DrawerSync
|
||||
import de.jeanlucmakiola.calendula.ui.common.SyncViewModel
|
||||
import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberSyncChipOutcome
|
||||
import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncTargets
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.messageRes
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFab
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarTopBar
|
||||
import de.jeanlucmakiola.calendula.ui.common.ChromeHost
|
||||
@@ -106,8 +97,6 @@ import de.jeanlucmakiola.calendula.ui.month.MonthScreen
|
||||
import de.jeanlucmakiola.calendula.ui.search.SearchScreen
|
||||
import de.jeanlucmakiola.calendula.ui.settings.SettingsScreen
|
||||
import de.jeanlucmakiola.calendula.ui.week.TimelineScreen
|
||||
import de.jeanlucmakiola.calendula.ui.filter.FilterViewModel
|
||||
import de.jeanlucmakiola.calendula.ui.filter.ViewCalendarsPicker
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -203,15 +192,10 @@ fun CalendarHost(
|
||||
var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
|
||||
val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() }
|
||||
|
||||
// The drawer's "Hide in this view" picker (#517). It is its own window over
|
||||
// everything here, so each external request below closes it first.
|
||||
var showViewCalendars by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
// A tapped reminder notification asks for a specific occurrence.
|
||||
val requestedDetailKey = requests.detailKey
|
||||
LaunchedEffect(requestedDetailKey) {
|
||||
if (requestedDetailKey != null) {
|
||||
showViewCalendars = false
|
||||
detailKey = requestedDetailKey
|
||||
requests.detailKey = null
|
||||
}
|
||||
@@ -227,7 +211,6 @@ fun CalendarHost(
|
||||
// top bar. Sits below the detail/edit overlays so tapping a result reveals
|
||||
// the detail on top and backing out returns to the results.
|
||||
var showSearch by rememberSaveable { mutableStateOf(false) }
|
||||
val filterViewModel: FilterViewModel = hiltViewModel()
|
||||
val onOpenSearch = { showSearch = true }
|
||||
|
||||
// Calendar manager (reached from Settings) — its own overlay so it slides
|
||||
@@ -333,7 +316,6 @@ fun CalendarHost(
|
||||
requests.importUri = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
showViewCalendars = false
|
||||
importUri = requestedImportUri
|
||||
importForceMany = false
|
||||
importSession++
|
||||
@@ -351,7 +333,6 @@ fun CalendarHost(
|
||||
requests.insert = null
|
||||
return@LaunchedEffect
|
||||
}
|
||||
showViewCalendars = false
|
||||
if (importForm == null) {
|
||||
openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true)
|
||||
} else {
|
||||
@@ -368,7 +349,6 @@ fun CalendarHost(
|
||||
fun dismissCoveringOverlays(keepCreate: Boolean = false) {
|
||||
showSettings = false
|
||||
showSearch = false
|
||||
showViewCalendars = false
|
||||
showCalendars = false
|
||||
showBackup = false
|
||||
detailKey = null
|
||||
@@ -461,17 +441,6 @@ fun CalendarHost(
|
||||
val eventActions: EventActionsViewModel = hiltViewModel()
|
||||
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
|
||||
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
|
||||
// "Sync now" in the drawer (#240): its outcome shows in the drawer row, or in
|
||||
// the move chip when it lands with the drawer closed.
|
||||
val sync: SyncViewModel = hiltViewModel()
|
||||
val loadedSyncTargets by sync.targets.collectAsStateWithLifecycle()
|
||||
val syncTargets = loadedSyncTargets ?: SyncTargets.None
|
||||
val syncInFlight by sync.inFlight.collectAsStateWithLifecycle()
|
||||
val syncResult by sync.result.collectAsStateWithLifecycle()
|
||||
val selectionFailureMessage = eventActionFailureMessage(selectionFailure)
|
||||
val syncRowMessage = syncResult?.let { stringResource(it.messageRes()) }
|
||||
val launchAccessPicker = rememberSyncAccessPicker(sync)
|
||||
var showSyncAccess by rememberSaveable { mutableStateOf(false) }
|
||||
val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() }
|
||||
// A tap opens the edit form instead of the detail screen when the user chose
|
||||
// so (#178) — only for events whose calendar takes writes. Both are read at
|
||||
@@ -516,8 +485,9 @@ fun CalendarHost(
|
||||
movableCalendarIds = movableCalendarIds,
|
||||
dragEnabled = dragToReschedule,
|
||||
move = { reschedule.move(it) },
|
||||
drops = reschedule.drops,
|
||||
inFlight = reschedule.inFlight,
|
||||
undoStarted = reschedule.undoStarted,
|
||||
abandoned = reschedule.abandoned,
|
||||
edit = onEditEvent,
|
||||
)
|
||||
}
|
||||
@@ -569,9 +539,6 @@ fun CalendarHost(
|
||||
val stayingPut = remember { StayingPut() }
|
||||
val chromeHost = remember { ChromeHost() }
|
||||
val drawerState = rememberDrawerState(DrawerValue.Closed)
|
||||
RefreshSyncAccessOnOpen(drawerState, sync)
|
||||
val syncChip = rememberSyncChipOutcome(drawerState, sync)
|
||||
val syncChipMessage = syncChip.value?.let { stringResource(it.messageRes()) }
|
||||
val density = LocalDensity.current
|
||||
val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) +
|
||||
with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() }
|
||||
@@ -592,15 +559,6 @@ fun CalendarHost(
|
||||
// (#239); nothing else in the calendar surfaces navigates here.
|
||||
LocalManageCalendars provides remember { { showCalendars = true } },
|
||||
) {
|
||||
if (showViewCalendars) {
|
||||
val filterState by filterViewModel.state.collectAsStateWithLifecycle()
|
||||
ViewCalendarsPicker(
|
||||
view = view,
|
||||
state = filterState,
|
||||
onSetHidden = { id, hidden -> filterViewModel.setHiddenIn(id, view, hidden) },
|
||||
onDismiss = { showViewCalendars = false },
|
||||
)
|
||||
}
|
||||
// One drawer, top bar and FAB for every screen (#184): a switch changes
|
||||
// what they say, from what the screen on show publishes, rather than
|
||||
// swapping them for another screen's.
|
||||
@@ -631,21 +589,6 @@ fun CalendarHost(
|
||||
onOpenSettings()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
sync = remember(syncTargets, syncInFlight, syncRowMessage) {
|
||||
DrawerSync(
|
||||
canSync = syncTargets.reachable.isNotEmpty(),
|
||||
inFlight = syncInFlight,
|
||||
outcome = syncRowMessage,
|
||||
needsAccess = syncTargets.needsAccess.isNotEmpty(),
|
||||
// Stays open, so the row's progress and the result are seen.
|
||||
onSync = { sync.requestSync() },
|
||||
onGrantAccess = { showSyncAccess = true },
|
||||
)
|
||||
},
|
||||
onHideInView = {
|
||||
showViewCalendars = true
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
@@ -671,12 +614,10 @@ fun CalendarHost(
|
||||
// A fresh event, like a duplicate from the detail screen (#52).
|
||||
openImportForm(form, ImportSource.Insert)
|
||||
},
|
||||
chipShown = moveOutcome != null || selectionFailure != null || syncChip.value != null,
|
||||
chipShown = moveOutcome != null || selectionFailure != null,
|
||||
onDismissChip = {
|
||||
reschedule.consumeOutcome()
|
||||
eventActions.consumeFailure()
|
||||
// Only the chip on show: a receipt queued behind it still gets its turn.
|
||||
if (moveOutcome == null && selectionFailure == null) syncChip.value = null
|
||||
},
|
||||
)
|
||||
CalendarFab(chromeHost, todayInToolbar, fabSelection)
|
||||
@@ -739,21 +680,10 @@ fun CalendarHost(
|
||||
EventMoveHost(
|
||||
reschedule,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
notice = selectionFailureMessage ?: syncChipMessage,
|
||||
onNoticeShown = {
|
||||
if (selectionFailureMessage != null) eventActions.consumeFailure() else syncChip.value = null
|
||||
},
|
||||
actionFailure = eventActionFailureMessage(selectionFailure),
|
||||
onActionFailureShown = eventActions::consumeFailure,
|
||||
)
|
||||
|
||||
if (showSyncAccess) {
|
||||
SyncAccessSheet(
|
||||
accounts = loadedSyncTargets?.needsAccess?.toList(),
|
||||
onGrant = launchAccessPicker,
|
||||
onDismissAccount = sync::dismissAccess,
|
||||
onDismiss = { showSyncAccess = false },
|
||||
)
|
||||
}
|
||||
|
||||
// The delete prompt and failure chip of a selected event's actions (#141).
|
||||
EventSelectionHost(host = chromeHost, viewModel = eventActions)
|
||||
|
||||
|
||||
@@ -15,9 +15,6 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
import de.jeanlucmakiola.calendula.ui.common.instancesWithout
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -49,8 +46,6 @@ class AgendaViewModel @Inject constructor(
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, viewModelScope)
|
||||
|
||||
// The saved agenda range plus the range-bar visibility toggle.
|
||||
private val agendaSettings = combine(
|
||||
settingsPrefs.agendaScreenRange,
|
||||
@@ -143,7 +138,7 @@ class AgendaViewModel @Inject constructor(
|
||||
)
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(window, hiddenHere),
|
||||
repository.instances(window),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildState(params, calendars, instances, today)
|
||||
|
||||
@@ -10,16 +10,15 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.FileUpload
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
@@ -50,13 +49,11 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BACKUP_KEEP_OPTIONS
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupSelection
|
||||
import de.jeanlucmakiola.calendula.domain.backup.isBackedUpByDefault
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarCheckGroups
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
||||
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.DialogUnitDropdown
|
||||
@@ -64,9 +61,8 @@ import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.locale.relativeTimeAgo
|
||||
import java.time.LocalDate
|
||||
|
||||
@@ -79,10 +75,8 @@ private val RESTORE_MIME_TYPES = arrayOf(
|
||||
)
|
||||
|
||||
/**
|
||||
* Backup & restore (#69): `.ics` export and restore, with
|
||||
* optional automatic backup, and the app's settings as JSON (#481). Shares
|
||||
* [CalendarsViewModel] with the manager; the settings block works whatever
|
||||
* state the calendar list is in.
|
||||
* Backup & restore (#69): `.ics` export and restore for local calendars, with
|
||||
* optional automatic backup. Shares [CalendarsViewModel] with the manager.
|
||||
*
|
||||
* A full-screen destination hoisted in `CalendarHost`; [onBack] pops it,
|
||||
* [onImport] hands a picked file to the app's normal .ics import flow.
|
||||
@@ -93,27 +87,19 @@ fun BackupScreen(
|
||||
onImport: (Uri) -> Unit,
|
||||
visible: Boolean = true,
|
||||
viewModel: CalendarsViewModel = hiltViewModel(),
|
||||
copyViewModel: CopyEventsViewModel = hiltViewModel(),
|
||||
settingsBackup: SettingsBackupViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.backupState.collectAsStateWithLifecycle()
|
||||
val copyRun by copyViewModel.run.collectAsStateWithLifecycle()
|
||||
var showCopy by rememberSaveable { mutableStateOf(false) }
|
||||
val backupResult by viewModel.backupResult.collectAsStateWithLifecycle()
|
||||
val autoBackup by viewModel.autoBackup.collectAsStateWithLifecycle()
|
||||
|
||||
val context = LocalContext.current
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
// The one-calendar shortcut; the per-calendar selector owns its own launcher.
|
||||
var shortcutExportId by rememberSaveable { mutableStateOf<Long?>(null) }
|
||||
// Exports everything eligible (null); the per-calendar selector owns its
|
||||
// own launcher.
|
||||
val createBackup = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("text/calendar"),
|
||||
) { uri ->
|
||||
val id = shortcutExportId
|
||||
if (uri != null && id != null) viewModel.exportBackup(uri, setOf(id))
|
||||
shortcutExportId = null
|
||||
}
|
||||
) { uri -> uri?.let { viewModel.exportBackup(it, null) } }
|
||||
var showExportPicker by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
// Restore runs the picked file through the normal .ics import flow.
|
||||
@@ -126,9 +112,6 @@ fun BackupScreen(
|
||||
contract = ActivityResultContracts.OpenDocumentTree(),
|
||||
) { uri -> uri?.let(viewModel::setAutoBackupFolder) }
|
||||
var showInterval by remember { mutableStateOf(false) }
|
||||
var showBackupCalendars by rememberSaveable { mutableStateOf(false) }
|
||||
var selectionBefore by remember { mutableStateOf<BackupSelection?>(null) }
|
||||
var showKeep by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
val backupFailedText = stringResource(R.string.calendars_backup_failed)
|
||||
LaunchedEffect(backupResult) {
|
||||
@@ -149,72 +132,36 @@ fun BackupScreen(
|
||||
}
|
||||
}
|
||||
|
||||
val settings = rememberSettingsBackupActions(settingsBackup)
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_section_backup),
|
||||
onBack = onBack,
|
||||
// Loading and failure fill the screen and centre themselves, which they
|
||||
// can only do in an unscrolled column — the scrolling one measures them
|
||||
// against an unbounded height and leaves them hanging under the header.
|
||||
scrollable = state is BackupUiState.Ready,
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
// Loading and failure get a fixed-height slot in the scrolling column (it
|
||||
// can't centre them in an unbounded height); the settings block below
|
||||
// works in every state.
|
||||
when (val s = state) {
|
||||
BackupUiState.Loading -> {
|
||||
StateSlot { BackupLoading() }
|
||||
SettingsBackupSection(settings)
|
||||
}
|
||||
is BackupUiState.Failure -> {
|
||||
StateSlot { CalendarFailure(reason = s.reason, onRetry = onBack) }
|
||||
SettingsBackupSection(settings)
|
||||
}
|
||||
BackupUiState.Loading -> BackupLoading()
|
||||
is BackupUiState.Failure -> CalendarFailure(reason = s.reason, onRetry = onBack)
|
||||
is BackupUiState.Ready -> BackupContent(
|
||||
exportable = s.exportable,
|
||||
canImport = s.canImport,
|
||||
canCopy = s.canCopy,
|
||||
copyRun = copyRun,
|
||||
onCopy = { showCopy = true },
|
||||
autoBackup = autoBackup,
|
||||
viewModel = viewModel,
|
||||
onRestore = { runCatching { openBackup.launch(RESTORE_MIME_TYPES) } },
|
||||
onPickFolder = { runCatching { pickFolder.launch(null) } },
|
||||
onExportOnly = {
|
||||
shortcutExportId = s.exportable.singleOrNull()?.id
|
||||
onExportAll = {
|
||||
runCatching { createBackup.launch(defaultBackupName()) }
|
||||
},
|
||||
onExportPick = { showExportPicker = true },
|
||||
onEditInterval = { showInterval = true },
|
||||
onEditCalendars = {
|
||||
selectionBefore = autoBackup.selection
|
||||
showBackupCalendars = true
|
||||
},
|
||||
onEditKeep = { showKeep = true },
|
||||
settings = settings,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Not gated on Ready: a running copy keeps its progress and Cancel whatever the list does.
|
||||
if (showCopy) {
|
||||
val calendars by copyViewModel.calendars.collectAsStateWithLifecycle()
|
||||
val selection by copyViewModel.selection.collectAsStateWithLifecycle()
|
||||
CopyEventsScreen(
|
||||
calendars = calendars,
|
||||
selection = selection,
|
||||
run = copyRun,
|
||||
onSelectSource = copyViewModel::setSource,
|
||||
onSelectTarget = copyViewModel::setTarget,
|
||||
onStart = copyViewModel::start,
|
||||
onCancel = copyViewModel::cancel,
|
||||
onClearFinished = copyViewModel::clearFinished,
|
||||
onDismiss = {
|
||||
showCopy = false
|
||||
copyViewModel.clearFinished()
|
||||
},
|
||||
)
|
||||
}
|
||||
// Gated on Ready rather than resetting the flag when the state leaves it:
|
||||
// flipping it here would be a write during composition.
|
||||
(state as? BackupUiState.Ready)?.let { ready ->
|
||||
@@ -225,36 +172,7 @@ fun BackupScreen(
|
||||
onDismiss = { showExportPicker = false },
|
||||
)
|
||||
}
|
||||
if (showBackupCalendars) {
|
||||
AutoBackupCalendarPicker(
|
||||
calendars = ready.exportable,
|
||||
selection = autoBackup.selection,
|
||||
onCheckedChange = viewModel::setAutoBackupCalendar,
|
||||
onDismiss = {
|
||||
showBackupCalendars = false
|
||||
viewModel.autoBackupCalendarsChosen(selectionBefore ?: autoBackup.selection)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showKeep) {
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.calendars_auto_backup_keep),
|
||||
header = {
|
||||
GroupedHint(
|
||||
stringResource(R.string.calendars_auto_backup_keep_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
},
|
||||
predictiveBack = true,
|
||||
options = BACKUP_KEEP_OPTIONS,
|
||||
selected = autoBackup.keep,
|
||||
label = { backupKeepLabel(it) },
|
||||
onSelect = viewModel::setAutoBackupKeep,
|
||||
onDismiss = { showKeep = false },
|
||||
)
|
||||
}
|
||||
SettingsBackupDialogs(settings, settingsBackup, snackbarHostState)
|
||||
if (showInterval) {
|
||||
BackupIntervalDialog(
|
||||
currentMinutes = autoBackup.intervalMinutes,
|
||||
@@ -264,14 +182,6 @@ fun BackupScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StateSlot(content: @Composable () -> Unit) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = STATE_MIN_HEIGHT),
|
||||
contentAlignment = Alignment.Center,
|
||||
) { content() }
|
||||
}
|
||||
|
||||
/** The screen's loading state, centred in the scaffold's content column. */
|
||||
@Composable
|
||||
private fun BackupLoading() {
|
||||
@@ -287,7 +197,7 @@ private fun BackupLoading() {
|
||||
private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.ics"
|
||||
|
||||
/**
|
||||
* The working screen: export (when any calendar can be backed up), restore,
|
||||
* The working screen: export (when there are local calendars to export), restore,
|
||||
* and the automatic-backup block. Restore is always on screen — when nothing can
|
||||
* receive the events it says so and routes to the calendar manager rather than
|
||||
* disappearing, which is what #304 reported as an invisible button.
|
||||
@@ -296,19 +206,13 @@ private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.i
|
||||
private fun BackupContent(
|
||||
exportable: List<CalendarSource>,
|
||||
canImport: Boolean,
|
||||
canCopy: Boolean,
|
||||
copyRun: CopyRunState,
|
||||
onCopy: () -> Unit,
|
||||
autoBackup: AutoBackupUiState,
|
||||
viewModel: CalendarsViewModel,
|
||||
onRestore: () -> Unit,
|
||||
onPickFolder: () -> Unit,
|
||||
onExportOnly: () -> Unit,
|
||||
onExportAll: () -> Unit,
|
||||
onExportPick: () -> Unit,
|
||||
onEditInterval: () -> Unit,
|
||||
onEditCalendars: () -> Unit,
|
||||
onEditKeep: () -> Unit,
|
||||
settings: SettingsBackupActions,
|
||||
) {
|
||||
val manageCalendars = LocalManageCalendars.current
|
||||
// Restore never depends on export eligibility, and never disappears: when no
|
||||
@@ -325,12 +229,10 @@ private fun BackupContent(
|
||||
GroupedHint(restoreSummary, style = MaterialTheme.typography.bodySmall)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_restore_action),
|
||||
position = if (copyRun != CopyRunState.Idle) Position.Top else Position.Alone,
|
||||
position = Position.Alone,
|
||||
leading = { LeadingAvatar(Icons.Default.FileUpload) },
|
||||
onClick = onRestoreClick,
|
||||
)
|
||||
if (copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Bottom, onCopy)
|
||||
SettingsBackupSection(settings)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -340,7 +242,7 @@ private fun BackupContent(
|
||||
position = Position.Top,
|
||||
leading = { LeadingAvatar(Icons.Default.FileDownload) },
|
||||
// A single exportable calendar skips the selector.
|
||||
onClick = if (exportable.size == 1) onExportOnly else onExportPick,
|
||||
onClick = if (exportable.size == 1) onExportAll else onExportPick,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_restore_action),
|
||||
@@ -349,8 +251,6 @@ private fun BackupContent(
|
||||
leading = { LeadingAvatar(Icons.Default.FileUpload) },
|
||||
onClick = onRestoreClick,
|
||||
)
|
||||
// A running or finished copy keeps its row, the way back to its sheet.
|
||||
if (canCopy || copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Middle, onCopy)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_auto_backup),
|
||||
summary = stringResource(R.string.calendars_auto_backup_hint),
|
||||
@@ -372,84 +272,22 @@ private fun BackupContent(
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_auto_backup_interval),
|
||||
summary = backupIntervalLabel(autoBackup.intervalMinutes),
|
||||
position = Position.Middle,
|
||||
position = Position.Bottom,
|
||||
onClick = onEditInterval,
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.calendars_auto_backup_on_change),
|
||||
summary = stringResource(R.string.calendars_auto_backup_on_change_summary),
|
||||
checked = autoBackup.onChange,
|
||||
onCheckedChange = viewModel::setAutoBackupOnChange,
|
||||
position = Position.Middle,
|
||||
)
|
||||
val selectedCount = exportable.count(autoBackup.selection::selects)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_auto_backup_calendars),
|
||||
summary = if (selectedCount == 0) {
|
||||
stringResource(R.string.calendars_auto_backup_calendars_none)
|
||||
} else {
|
||||
pluralStringResource(R.plurals.calendars_auto_backup_calendars_count, selectedCount, selectedCount)
|
||||
},
|
||||
position = Position.Middle,
|
||||
onClick = onEditCalendars,
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.calendars_auto_backup_combined),
|
||||
summary = stringResource(
|
||||
if (autoBackup.combined) {
|
||||
R.string.calendars_auto_backup_combined_on
|
||||
} else {
|
||||
R.string.calendars_auto_backup_combined_off
|
||||
},
|
||||
),
|
||||
checked = autoBackup.combined,
|
||||
onCheckedChange = viewModel::setAutoBackupCombined,
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_auto_backup_keep),
|
||||
summary = backupKeepLabel(autoBackup.keep),
|
||||
position = Position.Bottom,
|
||||
onClick = onEditKeep,
|
||||
)
|
||||
GroupedHint(
|
||||
if (selectedCount == 0) {
|
||||
stringResource(R.string.calendars_auto_backup_nothing_selected)
|
||||
} else {
|
||||
backupStatusText(autoBackup.status)
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
GroupedHint(backupStatusText(autoBackup.status), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
SettingsBackupSection(settings)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CopyEventsRow(copyRun: CopyRunState, position: Position, onClick: () -> Unit) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_copy_action),
|
||||
summary = when (copyRun) {
|
||||
is CopyRunState.Running -> copyProgressText(copyRun)
|
||||
is CopyRunState.Done -> stringResource(copyRun.titleRes)
|
||||
CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled)
|
||||
CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed)
|
||||
CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary)
|
||||
},
|
||||
position = position,
|
||||
leading = { LeadingAvatar(Icons.Default.ContentCopy) },
|
||||
onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose which calendars to include in a one-time `.ics` export. Starts on the
|
||||
* calendars a backup covers by default, or on all of them when none is; the Export action opens the SAF save dialog and hands back
|
||||
* Choose which local calendars to include in a one-time `.ics` export. Defaults
|
||||
* to all selected; the Export action opens the SAF save dialog and hands back
|
||||
* the picked file with the chosen calendar ids.
|
||||
*/
|
||||
@Composable
|
||||
private fun ExportCalendarPicker(
|
||||
calendars: List<CalendarSource>,
|
||||
onExport: (Uri, Set<Long>) -> Unit,
|
||||
onExport: (Uri, Set<Long>?) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
// Deliberately not keyed on [calendars]: that list is observer-driven, so
|
||||
@@ -460,8 +298,7 @@ private fun ExportCalendarPicker(
|
||||
restore = { it.toSet() },
|
||||
),
|
||||
) {
|
||||
val defaults = calendars.filter { it.isBackedUpByDefault }.ifEmpty { calendars }
|
||||
mutableStateOf(defaults.map { it.id }.toSet())
|
||||
mutableStateOf(calendars.map { it.id }.toSet())
|
||||
}
|
||||
val createBackup = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("text/calendar"),
|
||||
@@ -478,16 +315,29 @@ private fun ExportCalendarPicker(
|
||||
predictiveBack = true,
|
||||
) {
|
||||
GroupedHint(stringResource(R.string.calendars_export_hint), style = MaterialTheme.typography.bodySmall)
|
||||
CalendarCheckGroups(
|
||||
calendars = calendars,
|
||||
isChecked = { it.id in selected },
|
||||
onCheckedChange = { calendar, checked ->
|
||||
selected = if (checked) selected + calendar.id else selected - calendar.id
|
||||
},
|
||||
)
|
||||
calendars.forEachIndexed { index, calendar ->
|
||||
val isSelected = calendar.id in selected
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = calendar.description,
|
||||
position = positionOf(index, calendars.size),
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Checkbox(
|
||||
checked = isSelected,
|
||||
onCheckedChange = { checked ->
|
||||
selected = if (checked) selected + calendar.id else selected - calendar.id
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
selected = if (isSelected) selected - calendar.id else selected + calendar.id
|
||||
},
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = {
|
||||
runCatching { createBackup.launch(defaultBackupName()) }
|
||||
runCatching { createBackup.launch("calendula-backup-${LocalDate.now()}.ics") }
|
||||
},
|
||||
enabled = selected.isNotEmpty(),
|
||||
modifier = Modifier
|
||||
@@ -499,39 +349,6 @@ private fun ExportCalendarPicker(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose which calendars the automatic backup covers (#147). Each tick is saved
|
||||
* at once, as a deviation from the default, so there is nothing to confirm.
|
||||
*/
|
||||
@Composable
|
||||
private fun AutoBackupCalendarPicker(
|
||||
calendars: List<CalendarSource>,
|
||||
selection: BackupSelection,
|
||||
onCheckedChange: (CalendarSource, Boolean) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
FullScreenPicker(
|
||||
title = stringResource(R.string.calendars_auto_backup_calendars),
|
||||
onDismiss = onDismiss,
|
||||
predictiveBack = true,
|
||||
) {
|
||||
GroupedHint(
|
||||
stringResource(R.string.calendars_auto_backup_calendars_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
CalendarCheckGroups(
|
||||
calendars = calendars,
|
||||
isChecked = selection::selects,
|
||||
onCheckedChange = onCheckedChange,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** "Only the latest" / "The latest 3". */
|
||||
@Composable
|
||||
private fun backupKeepLabel(keep: Int): String =
|
||||
pluralStringResource(R.plurals.calendars_auto_backup_keep_count, keep, keep)
|
||||
|
||||
/** Readable name of the persisted backup folder, resolved from its tree Uri. */
|
||||
@Composable
|
||||
private fun rememberFolderName(uriString: String?): String? {
|
||||
@@ -616,6 +433,5 @@ private fun BackupIntervalDialog(
|
||||
)
|
||||
}
|
||||
|
||||
private val STATE_MIN_HEIGHT = 360.dp
|
||||
private const val MINUTES_PER_DAY = 1_440L
|
||||
private const val MINUTES_PER_WEEK = 10_080L
|
||||
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.ui.calendars
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.backup.isBackupCandidate
|
||||
import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.domain.isEventTarget
|
||||
|
||||
@@ -24,52 +23,31 @@ sealed interface BackupUiState {
|
||||
data class Ready(
|
||||
val exportable: List<CalendarSource>,
|
||||
val canImport: Boolean,
|
||||
/** Some calendar can be copied into a different one (#325). */
|
||||
val canCopy: Boolean = false,
|
||||
) : BackupUiState
|
||||
}
|
||||
|
||||
/**
|
||||
* What the screen can offer for this calendar list.
|
||||
*
|
||||
* Export can read any calendar (#147) — the local ones are only its default;
|
||||
* managed special-dates mirrors are rebuilt from contacts, so they are excluded
|
||||
* ([isBackupCandidate]). Restore can target anything the import picker offers
|
||||
* ([isEventTarget]).
|
||||
* Export covers the app's own local calendars; managed special-dates mirrors are
|
||||
* rebuilt from contacts, so they are excluded. Restore can target anything the
|
||||
* import picker offers ([isEventTarget]).
|
||||
*
|
||||
* A failure is raised only when *neither* is possible — deliberately not
|
||||
* [calendarListFailure] on its own, which would call an all-hidden device a
|
||||
* failure while its calendars are still perfectly exportable. Since export
|
||||
* reads hidden and read-only calendars too, both halves are dead only when there
|
||||
* is no calendar at all, or every one is managed or not synced to the device
|
||||
* ([FailureReason.NoImportTarget] unless the list itself says why).
|
||||
* failure while its local calendars are still perfectly exportable. When both
|
||||
* halves are dead the list itself usually says why (no calendars, everything
|
||||
* switched off); [FailureReason.NoImportTarget] covers the remaining case, where
|
||||
* calendars exist and are visible but every one of them is read-only, managed or
|
||||
* not synced to the device.
|
||||
*/
|
||||
fun backupUiState(calendars: List<CalendarSource>): BackupUiState {
|
||||
val exportable = calendars.filter { it.isBackupCandidate }
|
||||
val exportable = calendars.filter { it.isLocal && it.canModifyContents && !it.isManaged }
|
||||
val canImport = calendars.any { it.isEventTarget }
|
||||
if (exportable.isEmpty() && !canImport) {
|
||||
return BackupUiState.Failure(
|
||||
calendarListFailure(calendars) ?: FailureReason.NoImportTarget,
|
||||
)
|
||||
}
|
||||
return BackupUiState.Ready(
|
||||
exportable = exportable,
|
||||
canImport = canImport,
|
||||
canCopy = copySources(calendars).isNotEmpty(),
|
||||
)
|
||||
return BackupUiState.Ready(exportable = exportable, canImport = canImport)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calendars a copy can read from: any a backup can (#325), synced and read-only
|
||||
* ones included, as long as some other calendar can take their events.
|
||||
*/
|
||||
fun copySources(calendars: List<CalendarSource>): List<CalendarSource> {
|
||||
val targets = calendars.filter { it.isEventTarget }
|
||||
val onlyTarget = targets.singleOrNull()?.id
|
||||
if (targets.isEmpty()) return emptyList()
|
||||
return calendars.filter { it.isBackupCandidate && it.id != onlyTarget }
|
||||
}
|
||||
|
||||
/** Calendars a copy from [sourceId] can write into: the import targets, minus the source itself. */
|
||||
fun copyTargets(calendars: List<CalendarSource>, sourceId: Long?): List<CalendarSource> =
|
||||
calendars.filter { it.isEventTarget && it.id != sourceId }
|
||||
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.calendars
|
||||
import android.accounts.AccountManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.icu.text.ListFormatter
|
||||
import android.provider.Settings
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.background
|
||||
@@ -46,7 +45,6 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -56,7 +54,6 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
@@ -75,10 +72,6 @@ import de.jeanlucmakiola.calendula.domain.stateLabels
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
|
||||
import de.jeanlucmakiola.calendula.ui.common.AccountKey
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
|
||||
import de.jeanlucmakiola.calendula.ui.common.icon
|
||||
import de.jeanlucmakiola.calendula.ui.common.label
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
@@ -92,11 +85,6 @@ import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.ui.common.SyncAccountRow
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
@@ -104,7 +92,6 @@ import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.identity.predictiveBack
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.InlineTextField
|
||||
import de.jeanlucmakiola.floret.components.MultiOptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
@@ -143,21 +130,14 @@ fun CalendarsScreen(
|
||||
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
|
||||
val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle()
|
||||
val error by viewModel.error.collectAsStateWithLifecycle()
|
||||
val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle()
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.refreshAccess() }
|
||||
val loadedHiddenViews by viewModel.hiddenViews.collectAsStateWithLifecycle()
|
||||
val hiddenViews = loadedHiddenViews.orEmpty()
|
||||
|
||||
// null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar.
|
||||
// [editorSession] bumps on every open so the editor's field state resets for
|
||||
// a fresh open while still surviving configuration changes within one open.
|
||||
var editorId by rememberSaveable { mutableStateOf<Long?>(null) }
|
||||
var editorSession by rememberSaveable { mutableStateOf(0) }
|
||||
// A synced calendar has no editor; tapping it opens its hidden-views picker.
|
||||
var hidingId by rememberSaveable { mutableStateOf<Long?>(null) }
|
||||
|
||||
// The editor and the picker seed from the stored hidden views, so both wait for the first read.
|
||||
if (editorId != null && loadedHiddenViews != null) {
|
||||
if (editorId != null) {
|
||||
val editing = calendars.firstOrNull { it.id == editorId }
|
||||
CalendarEditor(
|
||||
sessionKey = editorSession,
|
||||
@@ -165,15 +145,13 @@ fun CalendarsScreen(
|
||||
initialName = editing?.displayName.orEmpty(),
|
||||
initialColor = editing?.color ?: CalendarColorPalette.all.first(),
|
||||
initialDescription = editing?.description.orEmpty(),
|
||||
showHiddenViews = true,
|
||||
initialHiddenViews = editing?.let { hiddenViews[it.id] }.orEmpty(),
|
||||
deleteLocked = editing != null && editing.id in deleteLockedIds,
|
||||
onSave = { name, color, description, views ->
|
||||
onSave = { name, color, description ->
|
||||
val id = editorId
|
||||
if (id == null || id == NEW_CALENDAR_ID) {
|
||||
viewModel.createCalendar(name, color, description, views)
|
||||
viewModel.createCalendar(name, color, description)
|
||||
} else {
|
||||
viewModel.updateCalendar(id, name, color, description, views)
|
||||
viewModel.updateCalendar(id, name, color, description)
|
||||
}
|
||||
editorId = null
|
||||
},
|
||||
@@ -187,7 +165,6 @@ fun CalendarsScreen(
|
||||
CalendarsList(
|
||||
local = calendars.filter { it.isLocal },
|
||||
synced = calendars.filterNot { it.isLocal },
|
||||
hiddenViews = hiddenViews,
|
||||
error = error,
|
||||
onConsumeError = viewModel::consumeError,
|
||||
onOpenBackup = onOpenBackup,
|
||||
@@ -195,28 +172,9 @@ fun CalendarsScreen(
|
||||
visible = visible,
|
||||
onAdd = { editorSession++; editorId = NEW_CALENDAR_ID },
|
||||
onEdit = { calendar -> editorSession++; editorId = calendar.id },
|
||||
onEditHiddenViews = { calendar -> hidingId = calendar.id },
|
||||
onSetVisible = viewModel::setCalendarVisible,
|
||||
onSetAccountVisible = viewModel::setAccountVisible,
|
||||
syncAccessDismissed = syncAccessDismissed,
|
||||
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
|
||||
)
|
||||
hidingId?.let { id ->
|
||||
val calendar = calendars.firstOrNull { it.id == id }
|
||||
// Gone while the picker was up; an empty list is one still loading, not a deletion.
|
||||
if (calendar == null && calendars.isNotEmpty()) {
|
||||
LaunchedEffect(id) { hidingId = null }
|
||||
} else if (calendar != null && loadedHiddenViews != null) {
|
||||
key(id) {
|
||||
HiddenViewsPicker(
|
||||
calendarName = calendar.displayName.orUnnamed(),
|
||||
hidden = hiddenViews[id].orEmpty(),
|
||||
onToggle = { view, hide -> viewModel.setHiddenIn(id, view, hide) },
|
||||
onDismiss = { hidingId = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,7 +182,6 @@ fun CalendarsScreen(
|
||||
private fun CalendarsList(
|
||||
local: List<CalendarSource>,
|
||||
synced: List<CalendarSource>,
|
||||
hiddenViews: Map<Long, Set<CalendarView>>,
|
||||
error: Boolean,
|
||||
onConsumeError: () -> Unit,
|
||||
onOpenBackup: () -> Unit,
|
||||
@@ -232,11 +189,8 @@ private fun CalendarsList(
|
||||
visible: Boolean,
|
||||
onAdd: () -> Unit,
|
||||
onEdit: (CalendarSource) -> Unit,
|
||||
onEditHiddenViews: (CalendarSource) -> Unit,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
|
||||
syncAccessDismissed: List<SyncAccount>,
|
||||
onAskSyncAccessAgain: (SyncAccount) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
@@ -287,7 +241,6 @@ private fun CalendarsList(
|
||||
local.forEachIndexed { index, calendar ->
|
||||
CalendarManagerRow(
|
||||
calendar = calendar,
|
||||
hiddenViews = hiddenViews[calendar.id].orEmpty(),
|
||||
last = index == local.lastIndex,
|
||||
onSetVisible = onSetVisible,
|
||||
onClick = { onEdit(calendar) },
|
||||
@@ -362,28 +315,12 @@ private fun CalendarsList(
|
||||
ordered.forEachIndexed { index, calendar ->
|
||||
CalendarManagerRow(
|
||||
calendar = calendar,
|
||||
hiddenViews = hiddenViews[calendar.id].orEmpty(),
|
||||
last = index == ordered.lastIndex,
|
||||
onSetVisible = onSetVisible,
|
||||
onClick = { onEditHiddenViews(calendar) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (syncAccessDismissed.isNotEmpty()) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedSectionHeader(stringResource(R.string.calendars_sync_access_header))
|
||||
GroupedHint(stringResource(R.string.calendars_sync_access_hint), style = MaterialTheme.typography.bodySmall)
|
||||
syncAccessDismissed.forEachIndexed { index, account ->
|
||||
SyncAccountRow(
|
||||
account = account,
|
||||
position = positionOf(index, syncAccessDismissed.size),
|
||||
actionLabel = stringResource(R.string.calendars_sync_access_ask_again),
|
||||
onAction = { onAskSyncAccessAgain(account) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -402,32 +339,19 @@ internal fun CalendarEditor(
|
||||
initialName: String,
|
||||
initialColor: Int,
|
||||
initialDescription: String,
|
||||
onSave: (name: String, color: Int, description: String?, hiddenChanges: Map<CalendarView, Boolean>) -> Unit,
|
||||
onSave: (name: String, color: Int, description: String?) -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
deleteLocked: Boolean = false,
|
||||
showHiddenViews: Boolean = false,
|
||||
initialHiddenViews: Set<CalendarView> = emptySet(),
|
||||
) {
|
||||
var name by rememberSaveable(sessionKey) { mutableStateOf(initialName) }
|
||||
val seededHiddenViews = rememberSaveable(sessionKey) { initialHiddenViews }
|
||||
var hiddenViews by rememberSaveable(sessionKey) { mutableStateOf(initialHiddenViews) }
|
||||
var pickHiddenViews by rememberSaveable(sessionKey) { mutableStateOf(false) }
|
||||
var color by rememberSaveable(sessionKey) { mutableStateOf(initialColor) }
|
||||
var description by rememberSaveable(sessionKey) { mutableStateOf(initialDescription) }
|
||||
var confirmDelete by remember { mutableStateOf(false) }
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
|
||||
val valid = name.isNotBlank()
|
||||
val commit = {
|
||||
if (valid) {
|
||||
// Only the views toggled here are written, so a save never resets ones it didn't load.
|
||||
val changes = IMPLEMENTED_VIEWS
|
||||
.filter { (it in hiddenViews) != (it in seededHiddenViews) }
|
||||
.associateWith { it in hiddenViews }
|
||||
onSave(name.trim(), color, description.trim().ifEmpty { null }, changes)
|
||||
}
|
||||
}
|
||||
val commit = { if (valid) onSave(name.trim(), color, description.trim().ifEmpty { null }) }
|
||||
|
||||
FullScreenPicker(
|
||||
title = stringResource(
|
||||
@@ -479,16 +403,6 @@ internal fun CalendarEditor(
|
||||
}
|
||||
}
|
||||
|
||||
if (showHiddenViews) {
|
||||
Spacer(Modifier.height(20.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.calendars_hide_in_views),
|
||||
summary = hiddenViewsSummary(hiddenViews),
|
||||
position = Position.Alone,
|
||||
onClick = { pickHiddenViews = true },
|
||||
)
|
||||
}
|
||||
|
||||
if (!isNew && !deleteLocked) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
DeleteCalendarRow(onClick = { confirmDelete = true })
|
||||
@@ -496,17 +410,6 @@ internal fun CalendarEditor(
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
|
||||
if (pickHiddenViews) {
|
||||
HiddenViewsPicker(
|
||||
calendarName = name.trim().orUnnamed(),
|
||||
hidden = hiddenViews,
|
||||
onToggle = { view, hide ->
|
||||
hiddenViews = if (hide) hiddenViews + view else hiddenViews - view
|
||||
},
|
||||
onDismiss = { pickHiddenViews = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (confirmDelete) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
@@ -733,7 +636,7 @@ private fun EditorSectionLabel(text: String) {
|
||||
* plain writable one (#76), then its own description.
|
||||
*/
|
||||
@Composable
|
||||
private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<CalendarView>): String? {
|
||||
private fun calendarRowSummary(calendar: CalendarSource): String? {
|
||||
val states = calendar.stateLabels().map { label ->
|
||||
stringResource(
|
||||
when (label) {
|
||||
@@ -743,8 +646,7 @@ private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<Calend
|
||||
},
|
||||
)
|
||||
}
|
||||
val hidden = if (hiddenViews.isEmpty()) null else hiddenViewsSummary(hiddenViews)
|
||||
val parts = states + listOfNotNull(hidden, calendar.description?.takeIf { it.isNotBlank() })
|
||||
val parts = states + listOfNotNull(calendar.description?.takeIf { it.isNotBlank() })
|
||||
return parts.joinToString(" · ").ifEmpty { null }
|
||||
}
|
||||
|
||||
@@ -760,7 +662,6 @@ private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set<Calend
|
||||
@Composable
|
||||
private fun CalendarManagerRow(
|
||||
calendar: CalendarSource,
|
||||
hiddenViews: Set<CalendarView>,
|
||||
last: Boolean,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
onClick: (() -> Unit)? = null,
|
||||
@@ -768,7 +669,7 @@ private fun CalendarManagerRow(
|
||||
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = calendarRowSummary(calendar, hiddenViews),
|
||||
summary = calendarRowSummary(calendar),
|
||||
position = if (last) Position.Bottom else Position.Middle,
|
||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
dimmed = disabled,
|
||||
@@ -788,51 +689,6 @@ private fun CalendarManagerRow(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Which views one calendar stays out of (#270); display only, so reminders and
|
||||
* search keep the calendar. [onToggle] decides when a toggle lands: at once for
|
||||
* a synced calendar, on Save inside the local editor.
|
||||
*/
|
||||
@Composable
|
||||
private fun HiddenViewsPicker(
|
||||
calendarName: String,
|
||||
hidden: Set<CalendarView>,
|
||||
onToggle: (CalendarView, Boolean) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
// Seeded once and then ahead of the store: the picker is the only writer while
|
||||
// it is open, so following each write back would only flicker a quick second tap.
|
||||
var shown by remember { mutableStateOf(hidden) }
|
||||
MultiOptionPicker(
|
||||
title = stringResource(R.string.calendars_hide_in_views),
|
||||
options = IMPLEMENTED_VIEWS,
|
||||
selected = shown,
|
||||
label = { it.label() },
|
||||
onToggle = { view, hide ->
|
||||
shown = if (hide) shown + view else shown - view
|
||||
onToggle(view, hide)
|
||||
},
|
||||
onDismiss = onDismiss,
|
||||
leading = { Icon(it.icon, contentDescription = null) },
|
||||
header = {
|
||||
GroupedHint(
|
||||
stringResource(R.string.calendars_hide_in_views_hint, calendarName),
|
||||
verticalPadding = 8.dp,
|
||||
)
|
||||
},
|
||||
predictiveBack = true,
|
||||
)
|
||||
}
|
||||
|
||||
/** "Shown in every view", or the views [hidden] names, in the app's view order. */
|
||||
@Composable
|
||||
private fun hiddenViewsSummary(hidden: Set<CalendarView>): String {
|
||||
if (hidden.isEmpty()) return stringResource(R.string.calendars_hide_in_views_none)
|
||||
val names = IMPLEMENTED_VIEWS.filter { it in hidden }.map { it.label() }
|
||||
val locale = LocalConfiguration.current.locales[0]
|
||||
return stringResource(R.string.calendars_hidden_in, ListFormatter.getInstance(locale).format(names))
|
||||
}
|
||||
|
||||
/** Fade a leading element to the M3 disabled emphasis when [disabled]. */
|
||||
private fun dimIf(disabled: Boolean): Modifier =
|
||||
if (disabled) Modifier.alpha(0.38f) else Modifier
|
||||
|
||||
@@ -3,29 +3,21 @@ package de.jeanlucmakiola.calendula.ui.calendars
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
||||
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.backup.BackupSelection
|
||||
import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.joinAll
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -64,23 +56,6 @@ class CalendarsViewModel @Inject constructor(
|
||||
initialValue = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Accounts the drawer was told not to ask sync-request access for (#240),
|
||||
* limited to those still behind a visible calendar and still unreachable.
|
||||
*/
|
||||
val syncAccessDismissed: StateFlow<List<SyncAccount>> =
|
||||
repository.syncTargets
|
||||
.map { it.dismissed.toList() }
|
||||
.catch { emit(emptyList()) }
|
||||
.stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList())
|
||||
|
||||
/** Re-read account access, which can change outside the app; called on resume. */
|
||||
fun refreshAccess() = repository.refreshSyncAccess()
|
||||
|
||||
fun askSyncAccessAgain(account: SyncAccount) {
|
||||
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The Backup & restore screen's own view of that list, with the loading and
|
||||
* failure states [calendars] flattens away — it starts empty and catches to
|
||||
@@ -98,20 +73,12 @@ class CalendarsViewModel @Inject constructor(
|
||||
|
||||
/** Automatic-backup settings + last-run status, for the Backup section UI. */
|
||||
val autoBackup: StateFlow<AutoBackupUiState> = combine(
|
||||
combine(
|
||||
settingsPrefs.autoBackupEnabled,
|
||||
settingsPrefs.autoBackupIntervalMinutes,
|
||||
settingsPrefs.autoBackupFolderUri,
|
||||
settingsPrefs.autoBackupStatus,
|
||||
) { enabled, interval, folder, status ->
|
||||
AutoBackupUiState(enabled, interval, folder, status)
|
||||
},
|
||||
settingsPrefs.autoBackupSelection,
|
||||
settingsPrefs.autoBackupCombined,
|
||||
settingsPrefs.autoBackupKeep,
|
||||
settingsPrefs.autoBackupOnChange,
|
||||
) { base, selection, combined, keep, onChange ->
|
||||
base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange)
|
||||
settingsPrefs.autoBackupEnabled,
|
||||
settingsPrefs.autoBackupIntervalMinutes,
|
||||
settingsPrefs.autoBackupFolderUri,
|
||||
settingsPrefs.autoBackupStatus,
|
||||
) { enabled, interval, folder, status ->
|
||||
AutoBackupUiState(enabled, interval, folder, status)
|
||||
}
|
||||
.flowOn(io)
|
||||
.stateWhileSubscribed(
|
||||
@@ -137,19 +104,6 @@ class CalendarsViewModel @Inject constructor(
|
||||
initialValue = emptySet(),
|
||||
)
|
||||
|
||||
/** The views each calendar is hidden in (#270); null until first read. */
|
||||
val hiddenViews: StateFlow<Map<Long, Set<CalendarView>>?> =
|
||||
settingsPrefs.perCalendarHiddenViews
|
||||
.hidingNothingOnError()
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = null,
|
||||
)
|
||||
|
||||
fun setHiddenIn(id: Long, view: CalendarView, hidden: Boolean) = write {
|
||||
settingsPrefs.setCalendarHiddenIn(id, view, hidden)
|
||||
}
|
||||
|
||||
private val _error = MutableStateFlow(false)
|
||||
val error: StateFlow<Boolean> = _error.asStateFlow()
|
||||
|
||||
@@ -161,22 +115,18 @@ class CalendarsViewModel @Inject constructor(
|
||||
fun consumeBackupResult() { _backupResult.value = null }
|
||||
|
||||
/**
|
||||
* Serialise every event of [calendarIds] into the chosen SAF document [uri]
|
||||
* as one `VCALENDAR`. Result (event count, or failure) lands
|
||||
* Serialise every event of the writable local calendars into the chosen SAF
|
||||
* document [uri] as one `VCALENDAR`. Result (event count, or failure) lands
|
||||
* in [backupResult] for a one-shot message.
|
||||
*/
|
||||
fun exportBackup(uri: Uri, calendarIds: Set<Long>) {
|
||||
fun exportBackup(uri: Uri, calendarIds: Set<Long>? = null) {
|
||||
viewModelScope.launch {
|
||||
_backupResult.value = try {
|
||||
val count = withContext(io) {
|
||||
val events = repository.exportEvents(calendarIds)
|
||||
// A one-calendar file is named after it, as the automatic backup's are.
|
||||
val name = calendarIds.singleOrNull()?.let { id ->
|
||||
repository.calendars().first().firstOrNull { it.id == id }?.displayName
|
||||
}
|
||||
icsExporter.writeDocument(
|
||||
uri = uri,
|
||||
content = IcsWriter().writeCalendar(events, Clock.System.now(), name),
|
||||
content = IcsWriter().writeCalendar(events, Clock.System.now()),
|
||||
)
|
||||
events.size
|
||||
}
|
||||
@@ -189,41 +139,16 @@ class CalendarsViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun createCalendar(
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
hiddenChanges: Map<CalendarView, Boolean>,
|
||||
) = write {
|
||||
val id = repository.createLocalCalendar(displayName, color, description)
|
||||
settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges)
|
||||
fun createCalendar(displayName: String, color: Int, description: String?) = write {
|
||||
repository.createLocalCalendar(displayName, color, description)
|
||||
}
|
||||
|
||||
fun updateCalendar(
|
||||
id: Long,
|
||||
displayName: String,
|
||||
color: Int,
|
||||
description: String?,
|
||||
hiddenChanges: Map<CalendarView, Boolean>,
|
||||
) = write {
|
||||
fun updateCalendar(id: Long, displayName: String, color: Int, description: String?) = write {
|
||||
repository.updateCalendar(id, displayName, color, description)
|
||||
settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges)
|
||||
}
|
||||
|
||||
fun deleteCalendar(id: Long) = write {
|
||||
repository.deleteCalendar(id)
|
||||
// Tidy-up only: the delete already landed, so a failure here isn't its failure.
|
||||
bestEffort { settingsPrefs.clearCalendarHiddenViews(id) }
|
||||
}
|
||||
|
||||
private suspend fun bestEffort(block: suspend () -> Unit) {
|
||||
try {
|
||||
block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("CalendarsViewModel", "Hidden-views write failed", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -279,58 +204,13 @@ class CalendarsViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** Selection writes since the calendar picker opened; the run after it waits for them. */
|
||||
private val selectionWrites = mutableListOf<Job>()
|
||||
|
||||
fun setAutoBackupCalendar(calendar: CalendarSource, included: Boolean) {
|
||||
selectionWrites += viewModelScope.launch { settingsPrefs.setAutoBackupCalendar(calendar, included) }
|
||||
}
|
||||
|
||||
fun setAutoBackupCombined(combined: Boolean) {
|
||||
viewModelScope.launch {
|
||||
if (settingsPrefs.autoBackupCombined.first() == combined) return@launch
|
||||
settingsPrefs.setAutoBackupCombined(combined)
|
||||
runBackupIfActive()
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutoBackupOnChange(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
settingsPrefs.setAutoBackupOnChange(enabled)
|
||||
reschedule()
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutoBackupKeep(keep: Int) {
|
||||
viewModelScope.launch {
|
||||
if (settingsPrefs.autoBackupKeep.first() == keep) return@launch
|
||||
settingsPrefs.setAutoBackupKeep(keep)
|
||||
runBackupIfActive()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After the calendar choice is closed, back up what is now selected rather
|
||||
* than at the next interval — only if it changed, since every run rotates
|
||||
* an older backup out.
|
||||
*/
|
||||
fun autoBackupCalendarsChosen(before: BackupSelection) {
|
||||
val pending = selectionWrites.toList()
|
||||
selectionWrites.clear()
|
||||
viewModelScope.launch {
|
||||
pending.joinAll()
|
||||
if (settingsPrefs.autoBackupSelection.first() != before) runBackupIfActive()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runBackupIfActive() {
|
||||
if (settingsPrefs.autoBackupEnabled.first() && settingsPrefs.autoBackupFolderUri.first() != null) {
|
||||
BackupScheduler.runNow(context)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun reschedule() {
|
||||
BackupScheduler.reconcile(context, settingsPrefs)
|
||||
BackupScheduler.apply(
|
||||
context = context,
|
||||
enabled = settingsPrefs.autoBackupEnabled.first(),
|
||||
intervalMinutes = settingsPrefs.autoBackupIntervalMinutes.first(),
|
||||
hasFolder = settingsPrefs.autoBackupFolderUri.first() != null,
|
||||
)
|
||||
}
|
||||
|
||||
private inline fun write(crossinline block: suspend () -> Unit) {
|
||||
@@ -352,10 +232,6 @@ data class AutoBackupUiState(
|
||||
val intervalMinutes: Long = SettingsPrefs.DEFAULT_BACKUP_INTERVAL,
|
||||
val folderUri: String? = null,
|
||||
val status: BackupStatus = BackupStatus(lastRun = 0L, lastSuccess = true, consecutiveFailures = 0),
|
||||
val selection: BackupSelection = BackupSelection(),
|
||||
val combined: Boolean = false,
|
||||
val keep: Int = DEFAULT_BACKUP_KEEP,
|
||||
val onChange: Boolean = false,
|
||||
)
|
||||
|
||||
/** Outcome of a whole-calendar backup, surfaced once to the screen. */
|
||||
|
||||
@@ -1,386 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.calendars
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.rounded.ArrowDownward
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearWavyProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups
|
||||
import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats
|
||||
import de.jeanlucmakiola.calendula.ui.common.ResultBadge
|
||||
import de.jeanlucmakiola.calendula.ui.common.ResultMessage
|
||||
import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes
|
||||
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
|
||||
import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
|
||||
/**
|
||||
* Copy every event of one calendar into another (#325), in the import flow's
|
||||
* steps: pick the source, pick the target and copy, watch it run, see the result.
|
||||
* The run lives in [CopyEventsViewModel], so the screen can be closed and
|
||||
* reopened mid-copy.
|
||||
*/
|
||||
@Composable
|
||||
fun CopyEventsScreen(
|
||||
calendars: CopyCalendars,
|
||||
selection: CopySelection,
|
||||
run: CopyRunState,
|
||||
onSelectSource: (Long) -> Unit,
|
||||
onSelectTarget: (Long) -> Unit,
|
||||
onStart: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
onClearFinished: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty()
|
||||
val sources = remember(list) { copySources(list) }
|
||||
val source = sources.firstOrNull { it.id == selection.sourceId }
|
||||
val targets = remember(list, source?.id) { copyTargets(list, source?.id) }
|
||||
val target = targets.firstOrNull { it.id == selection.targetId }
|
||||
var step by rememberSaveable { mutableStateOf(CopyStep.Source) }
|
||||
val idle = run == CopyRunState.Idle
|
||||
// The run's ends, held once seen so a calendar gone or a list reloading mid-run doesn't blank them.
|
||||
val runSource = rememberLastSeen(selection.sourceId, list)
|
||||
val runTarget = rememberLastSeen(selection.targetId, list)
|
||||
// A source that stopped qualifying sends the target step back to the start.
|
||||
// Keyed on the chosen id too: right after a pick the selection may not have arrived yet.
|
||||
LaunchedEffect(step, selection.sourceId, source, calendars) {
|
||||
val gone = selection.sourceId != null && source == null && calendars is CopyCalendars.Ready
|
||||
if (step == CopyStep.Target && gone) step = CopyStep.Source
|
||||
}
|
||||
|
||||
FullScreenPicker(
|
||||
title = stringResource(
|
||||
when {
|
||||
!idle -> R.string.calendars_copy_action
|
||||
step == CopyStep.Source -> R.string.calendars_copy_from_title
|
||||
else -> R.string.calendars_copy_to_title
|
||||
},
|
||||
),
|
||||
onDismiss = { if (idle && step == CopyStep.Target) step = CopyStep.Source else onDismiss() },
|
||||
// The target step's back only steps back, so it mustn't preview closing the screen.
|
||||
predictiveBack = !(idle && step == CopyStep.Target),
|
||||
scrollable = idle,
|
||||
actions = {
|
||||
if (idle && step == CopyStep.Target) {
|
||||
Button(
|
||||
onClick = onStart,
|
||||
enabled = source != null && target != null,
|
||||
modifier = Modifier.padding(end = 12.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.calendars_copy_start))
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (!idle) {
|
||||
val copyMore = {
|
||||
onClearFinished()
|
||||
step = CopyStep.Source
|
||||
}
|
||||
CopyRun(
|
||||
run = run,
|
||||
source = runSource,
|
||||
target = runTarget,
|
||||
onCancel = onCancel,
|
||||
// A retry only where the picker would still offer both ends; otherwise pick again.
|
||||
onRetry = if (source != null && target != null) onStart else copyMore,
|
||||
onCopyMore = copyMore,
|
||||
onClose = onDismiss,
|
||||
)
|
||||
return@FullScreenPicker
|
||||
}
|
||||
when (calendars) {
|
||||
CopyCalendars.Loading -> {
|
||||
Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
return@FullScreenPicker
|
||||
}
|
||||
CopyCalendars.Failure -> {
|
||||
CalendarFailure(reason = FailureReason.ProviderUnavailable, onRetry = onDismiss)
|
||||
return@FullScreenPicker
|
||||
}
|
||||
is CopyCalendars.Ready -> Unit
|
||||
}
|
||||
if (sources.isEmpty()) {
|
||||
GroupedHint(stringResource(R.string.calendars_copy_none))
|
||||
return@FullScreenPicker
|
||||
}
|
||||
when (step) {
|
||||
CopyStep.Source -> {
|
||||
IconInfoCard(
|
||||
icon = Icons.Outlined.Info,
|
||||
iconContentDescription = null,
|
||||
modifier = Modifier.padding(horizontal = GroupedListInset),
|
||||
) {
|
||||
Text(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
CalendarPickerGroups(
|
||||
calendars = sources,
|
||||
selectedId = source?.id,
|
||||
onSelect = {
|
||||
onSelectSource(it)
|
||||
step = CopyStep.Target
|
||||
},
|
||||
)
|
||||
}
|
||||
CopyStep.Target -> {
|
||||
CopyRouteCard(source, target, Modifier.padding(horizontal = GroupedListInset))
|
||||
Spacer(Modifier.height(16.dp))
|
||||
CalendarPickerGroups(
|
||||
calendars = targets,
|
||||
selectedId = target?.id,
|
||||
onSelect = onSelectTarget,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum class CopyStep { Source, Target }
|
||||
|
||||
/** Progress while the copy runs, then its outcome; both under the route it took. */
|
||||
@Composable
|
||||
private fun ColumnScope.CopyRun(
|
||||
run: CopyRunState,
|
||||
source: CalendarSource?,
|
||||
target: CalendarSource?,
|
||||
onCancel: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
onCopyMore: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
// Centred where it fits, scrolling where it doesn't (landscape, large fonts).
|
||||
BoxWithConstraints(Modifier.fillMaxWidth().weight(1f)) {
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.heightIn(min = maxHeight)
|
||||
.padding(horizontal = GroupedListInset)
|
||||
.padding(top = 8.dp, bottom = 24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
CopyRouteCard(source, target, pickable = false)
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
when (run) {
|
||||
is CopyRunState.Running -> CopyProgress(run)
|
||||
is CopyRunState.Done -> CopyDone(run)
|
||||
CopyRunState.Cancelled -> {
|
||||
FloretResultBadge(
|
||||
Icons.Default.Close,
|
||||
MaterialTheme.colorScheme.secondaryContainer,
|
||||
MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
ResultMessage(stringResource(R.string.calendars_copy_cancelled))
|
||||
}
|
||||
CopyRunState.Failed -> {
|
||||
ResultBadge(error = true)
|
||||
ResultMessage(stringResource(R.string.calendars_copy_failed))
|
||||
}
|
||||
CopyRunState.Idle -> Unit
|
||||
}
|
||||
}
|
||||
when (run) {
|
||||
is CopyRunState.Running -> TextButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.dialog_cancel))
|
||||
}
|
||||
is CopyRunState.Done -> CopyEndButtons(
|
||||
primary = stringResource(R.string.import_close),
|
||||
onPrimary = onClose,
|
||||
secondary = stringResource(R.string.calendars_copy_more),
|
||||
onSecondary = onCopyMore,
|
||||
)
|
||||
CopyRunState.Cancelled, CopyRunState.Failed -> CopyEndButtons(
|
||||
primary = stringResource(R.string.state_retry),
|
||||
onPrimary = onRetry,
|
||||
secondary = stringResource(R.string.import_close),
|
||||
onSecondary = onClose,
|
||||
)
|
||||
CopyRunState.Idle -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The calendar with [id] in [list], or the last one seen under that id while it is missing. */
|
||||
@Composable
|
||||
private fun rememberLastSeen(id: Long?, list: List<CalendarSource>): CalendarSource? {
|
||||
val held = remember(id) { mutableStateOf<CalendarSource?>(null) }
|
||||
list.firstOrNull { it.id == id }?.let { held.value = it }
|
||||
return held.value
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun CopyProgress(run: CopyRunState.Running) {
|
||||
val total = run.total
|
||||
if (total == null || total == 0) {
|
||||
LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearWavyProgressIndicator(progress = { run.done.toFloat() / total }, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
text = copyProgressText(run),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** "Reading events…" until the source is read, then "120 of 2,400 events". */
|
||||
@Composable
|
||||
fun copyProgressText(run: CopyRunState.Running): String {
|
||||
val total = run.total ?: return stringResource(R.string.calendars_copy_reading)
|
||||
return pluralStringResource(R.plurals.calendars_copy_progress, total, run.done, total)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CopyDone(run: CopyRunState.Done) {
|
||||
val summary = run.summary
|
||||
// As on the import: only a run the target cut short reads as an error.
|
||||
ResultBadge(error = run.stopped)
|
||||
ResultMessage(
|
||||
title = stringResource(run.titleRes),
|
||||
notes = importSummaryNotes(
|
||||
summary,
|
||||
stoppedNote = if (run.stopped) {
|
||||
pluralStringResource(R.plurals.calendars_copy_stopped, summary.notAttempted, summary.notAttempted)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
ImportSummaryStats(summary)
|
||||
}
|
||||
|
||||
/** The way on ([secondary], e.g. Copy more) above the way out (Close). */
|
||||
@Composable
|
||||
private fun CopyEndButtons(primary: String, onPrimary: () -> Unit, secondary: String, onSecondary: () -> Unit) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
OnboardingPrimaryButton(text = primary, onClick = onPrimary)
|
||||
TextButton(onClick = onSecondary, modifier = Modifier.fillMaxWidth()) { Text(secondary) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the events come from and go to, with an arrow between. A missing end
|
||||
* reads "Choose a calendar" while [pickable], or as unnamed on the run screens.
|
||||
*/
|
||||
@Composable
|
||||
private fun CopyRouteCard(
|
||||
source: CalendarSource?,
|
||||
target: CalendarSource?,
|
||||
modifier: Modifier = Modifier,
|
||||
pickable: Boolean = true,
|
||||
) {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
) {
|
||||
Column(Modifier.padding(16.dp)) {
|
||||
CopyRouteEnd(stringResource(R.string.calendars_copy_from), source, pickable)
|
||||
Box(Modifier.width(40.dp).padding(vertical = 4.dp), contentAlignment = Alignment.Center) {
|
||||
Surface(shape = CircleShape, color = MaterialTheme.colorScheme.primaryContainer) {
|
||||
Icon(
|
||||
Icons.Rounded.ArrowDownward,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.padding(6.dp).size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
CopyRouteEnd(stringResource(R.string.calendars_copy_to), target, pickable)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CopyRouteEnd(label: String, calendar: CalendarSource?, pickable: Boolean) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (calendar != null) {
|
||||
CalendarColorChip(calendar.color)
|
||||
} else {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {}
|
||||
}
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column {
|
||||
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(
|
||||
calendar?.displayName?.orUnnamed()
|
||||
?: if (pickable) stringResource(R.string.calendars_copy_choose) else "".orUnnamed(),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = if (calendar != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (calendar != null) {
|
||||
Text(
|
||||
if (calendar.isLocal) stringResource(R.string.calendars_local_header) else calendar.accountName,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.calendars
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Copy events from one calendar into another (#325). Scoped to the activity, so
|
||||
* a copy keeps running across rotation and while the Backup screen is closed;
|
||||
* finishing the activity or losing the process stops it like [cancel] does,
|
||||
* and a re-run picks up where it ended.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class CopyEventsViewModel @Inject constructor(
|
||||
private val repository: CalendarRepository,
|
||||
private val savedState: SavedStateHandle,
|
||||
) : ViewModel() {
|
||||
|
||||
val calendars: StateFlow<CopyCalendars> =
|
||||
repository.calendars()
|
||||
.map<List<CalendarSource>, CopyCalendars> { CopyCalendars.Ready(it) }
|
||||
.catch { emit(CopyCalendars.Failure) }
|
||||
.stateWhileSubscribed(scope = viewModelScope, initialValue = CopyCalendars.Loading)
|
||||
|
||||
val selection: StateFlow<CopySelection> = combine(
|
||||
savedState.getStateFlow<Long?>(KEY_SOURCE, null),
|
||||
savedState.getStateFlow<Long?>(KEY_TARGET, null),
|
||||
) { source, target -> CopySelection(source, target) }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, CopySelection())
|
||||
|
||||
private val _run = MutableStateFlow<CopyRunState>(CopyRunState.Idle)
|
||||
val run: StateFlow<CopyRunState> = _run.asStateFlow()
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
private val busy: Boolean get() = job?.isCompleted == false
|
||||
|
||||
private fun current() = CopySelection(savedState[KEY_SOURCE], savedState[KEY_TARGET])
|
||||
|
||||
private fun select(selection: CopySelection) {
|
||||
savedState[KEY_SOURCE] = selection.sourceId
|
||||
savedState[KEY_TARGET] = selection.targetId
|
||||
}
|
||||
|
||||
fun setSource(id: Long) {
|
||||
if (busy) return
|
||||
select(current().withSource(id))
|
||||
clearFinished()
|
||||
}
|
||||
|
||||
fun setTarget(id: Long) {
|
||||
if (busy) return
|
||||
select(current().copy(targetId = id))
|
||||
clearFinished()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
val source = current().sourceId ?: return
|
||||
val target = current().targetId ?: return
|
||||
if (busy) return
|
||||
_run.value = CopyRunState.Running(done = 0, total = null)
|
||||
job = viewModelScope.launch {
|
||||
try {
|
||||
val summary = repository.copyEvents(source, target) { done, total ->
|
||||
if (done == 0 || done == total || done % (total / 200).coerceAtLeast(1) == 0) {
|
||||
_run.value = CopyRunState.Running(done, total)
|
||||
}
|
||||
}
|
||||
_run.value = CopyRunState.Done(summary)
|
||||
} catch (e: CancellationException) {
|
||||
_run.value = CopyRunState.Cancelled
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Copy events failed", e)
|
||||
_run.value = CopyRunState.Failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
/** Back to idle once a finished run's outcome has been seen. */
|
||||
fun clearFinished() {
|
||||
if (!busy) _run.value = CopyRunState.Idle
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val KEY_SOURCE = "copy_source"
|
||||
const val KEY_TARGET = "copy_target"
|
||||
const val TAG = "CopyEvents"
|
||||
}
|
||||
}
|
||||
|
||||
/** The calendars a copy runs between. */
|
||||
data class CopySelection(val sourceId: Long? = null, val targetId: Long? = null) {
|
||||
/** A target equal to the new source is dropped: a calendar is never copied into itself. */
|
||||
fun withSource(id: Long): CopySelection =
|
||||
CopySelection(sourceId = id, targetId = targetId?.takeIf { it != id })
|
||||
}
|
||||
|
||||
/** The calendar list the copy screen picks from. */
|
||||
sealed interface CopyCalendars {
|
||||
data object Loading : CopyCalendars
|
||||
data object Failure : CopyCalendars
|
||||
data class Ready(val calendars: List<CalendarSource>) : CopyCalendars
|
||||
}
|
||||
|
||||
sealed interface CopyRunState {
|
||||
data object Idle : CopyRunState
|
||||
|
||||
/** [total] is null while the source calendar is still being read. */
|
||||
data class Running(val done: Int, val total: Int?) : CopyRunState
|
||||
|
||||
data class Done(val summary: IcsImportSummary) : CopyRunState {
|
||||
/** The target stopped taking events part way, so some were never tried. */
|
||||
val stopped: Boolean get() = summary.notAttempted > 0
|
||||
|
||||
/** How the run ended, the same words on the row and on the result screen. */
|
||||
@get:StringRes
|
||||
val titleRes: Int get() = when {
|
||||
stopped -> R.string.calendars_copy_stopped_title
|
||||
summary.failed > 0 -> R.string.calendars_copy_partial
|
||||
else -> R.string.calendars_copy_done
|
||||
}
|
||||
}
|
||||
data object Cancelled : CopyRunState
|
||||
data object Failed : CopyRunState
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.calendars
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.FileUpload
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.backup.SettingsImportSummary
|
||||
import de.jeanlucmakiola.calendula.data.backup.SkippedSetting
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
||||
import de.jeanlucmakiola.floret.backup.BackupProblem
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||
import java.time.LocalDate
|
||||
|
||||
// What the import picker accepts: providers label .json inconsistently.
|
||||
private val SETTINGS_MIME_TYPES = arrayOf("application/json", "text/plain", "application/octet-stream")
|
||||
|
||||
/** The Settings block's pickers and the import waiting for its confirmation. */
|
||||
class SettingsBackupActions internal constructor(
|
||||
val busy: Boolean,
|
||||
internal val pendingImport: MutableState<String?>,
|
||||
val export: () -> Unit,
|
||||
val import: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun rememberSettingsBackupActions(viewModel: SettingsBackupViewModel): SettingsBackupActions {
|
||||
val busy by viewModel.busy.collectAsStateWithLifecycle()
|
||||
val pendingImport = rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val createFile = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.CreateDocument("application/json"),
|
||||
) { uri -> uri?.let(viewModel::export) }
|
||||
val openFile = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument(),
|
||||
) { uri -> pendingImport.value = uri?.toString() }
|
||||
return SettingsBackupActions(
|
||||
busy = busy,
|
||||
pendingImport = pendingImport,
|
||||
export = { runCatching { createFile.launch("calendula-settings-${LocalDate.now()}.json") } },
|
||||
import = { runCatching { openFile.launch(SETTINGS_MIME_TYPES) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Settings export and import (#481), below the events' backup. */
|
||||
@Composable
|
||||
fun SettingsBackupSection(actions: SettingsBackupActions) {
|
||||
GroupedSectionHeader(stringResource(R.string.settings_backup_header))
|
||||
GroupedHint(stringResource(R.string.settings_backup_hint), style = MaterialTheme.typography.bodySmall)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_backup_export),
|
||||
summary = stringResource(R.string.settings_backup_export_summary),
|
||||
position = Position.Top,
|
||||
leading = { LeadingAvatar(Icons.Default.FileDownload) },
|
||||
dimmed = actions.busy,
|
||||
onClick = { if (!actions.busy) actions.export() },
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_backup_import),
|
||||
summary = stringResource(R.string.settings_backup_import_summary),
|
||||
position = Position.Bottom,
|
||||
leading = { LeadingAvatar(Icons.Default.FileUpload) },
|
||||
dimmed = actions.busy,
|
||||
onClick = { if (!actions.busy) actions.import() },
|
||||
)
|
||||
if (actions.busy) {
|
||||
LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = GroupedListInset, vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The import's confirmation and summary dialogs, and the snackbars for
|
||||
* everything else.
|
||||
*/
|
||||
@Composable
|
||||
fun SettingsBackupDialogs(
|
||||
actions: SettingsBackupActions,
|
||||
viewModel: SettingsBackupViewModel,
|
||||
snackbarHostState: SnackbarHostState,
|
||||
) {
|
||||
val result by viewModel.result.collectAsStateWithLifecycle()
|
||||
val exported = stringResource(R.string.settings_backup_export_done)
|
||||
val exportFailed = stringResource(R.string.settings_backup_export_failed)
|
||||
val importFailed = BackupProblem.entries.associateWith { stringResource(it.messageRes()) }
|
||||
|
||||
LaunchedEffect(result) {
|
||||
val message = when (val r = result) {
|
||||
is SettingsBackupResult.Exported -> exported
|
||||
is SettingsBackupResult.ExportFailed -> exportFailed
|
||||
is SettingsBackupResult.ImportFailed -> importFailed.getValue(r.problem)
|
||||
is SettingsBackupResult.Imported, null -> return@LaunchedEffect
|
||||
}
|
||||
snackbarHostState.showSnackbar(message)
|
||||
viewModel.consumeResult()
|
||||
}
|
||||
|
||||
(result as? SettingsBackupResult.Imported)?.let { imported ->
|
||||
ImportSummaryDialog(imported.summary, onDismiss = viewModel::consumeResult)
|
||||
}
|
||||
|
||||
actions.pendingImport.value?.let { uri ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { actions.pendingImport.value = null },
|
||||
title = { Text(stringResource(R.string.settings_backup_import_confirm_title)) },
|
||||
text = { Text(stringResource(R.string.settings_backup_import_confirm_message)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
actions.pendingImport.value = null
|
||||
viewModel.import(uri.toUri())
|
||||
},
|
||||
) { Text(stringResource(R.string.settings_backup_import_confirm_action)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { actions.pendingImport.value = null }) {
|
||||
Text(stringResource(R.string.dialog_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ImportSummaryDialog(summary: SettingsImportSummary, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.settings_backup_imported_title)) },
|
||||
text = {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
Text(stringResource(R.string.settings_backup_imported_body))
|
||||
if (summary.calendarsMatched > 0) {
|
||||
Text(
|
||||
pluralStringResource(
|
||||
R.plurals.settings_backup_imported_calendars,
|
||||
summary.calendarsMatched,
|
||||
summary.calendarsMatched,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (summary.skipped.isNotEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.settings_backup_imported_skipped),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
summary.skipped.forEach { skipped ->
|
||||
Text(
|
||||
"• " + skipped.label(),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_ok)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SkippedSetting.label(): String = when (this) {
|
||||
is SkippedSetting.Calendar -> stringResource(
|
||||
if (ambiguous) R.string.settings_backup_skipped_calendar_ambiguous else R.string.settings_backup_skipped_calendar,
|
||||
displayName,
|
||||
accountName,
|
||||
)
|
||||
SkippedSetting.CalendarsUnavailable -> stringResource(R.string.settings_backup_skipped_calendars_unavailable)
|
||||
is SkippedSetting.CustomFont -> stringResource(
|
||||
when (role) {
|
||||
FontRole.BRAND -> R.string.settings_backup_skipped_font_headings
|
||||
FontRole.PLAIN -> R.string.settings_backup_skipped_font_body
|
||||
},
|
||||
)
|
||||
SkippedSetting.SpecialDates -> stringResource(R.string.settings_backup_skipped_special_dates)
|
||||
SkippedSetting.AutoBackupFolder -> stringResource(R.string.settings_backup_skipped_auto_backup)
|
||||
is SkippedSetting.Language -> stringResource(R.string.settings_backup_skipped_language, AppLanguage.displayName(tag))
|
||||
}
|
||||
|
||||
private fun BackupProblem.messageRes(): Int = when (this) {
|
||||
BackupProblem.NOT_A_BACKUP -> R.string.settings_backup_import_failed_not_backup
|
||||
BackupProblem.NEWER_VERSION -> R.string.settings_backup_import_failed_newer
|
||||
BackupProblem.INVALID_DATA -> R.string.settings_backup_import_failed_invalid
|
||||
BackupProblem.TOO_LARGE -> R.string.settings_backup_import_failed_too_large
|
||||
BackupProblem.UNREADABLE -> R.string.settings_backup_import_failed_unreadable
|
||||
BackupProblem.NOT_APPLIED -> R.string.settings_backup_import_failed
|
||||
}
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.calendars
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import de.jeanlucmakiola.calendula.data.backup.SettingsBackupEngine
|
||||
import de.jeanlucmakiola.calendula.data.backup.SettingsImportSummary
|
||||
import de.jeanlucmakiola.floret.android.DocumentTooLargeException
|
||||
import de.jeanlucmakiola.floret.android.readDocumentBytes
|
||||
import de.jeanlucmakiola.floret.android.writeDocumentBytes
|
||||
import de.jeanlucmakiola.floret.backup.BackupProblem
|
||||
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* The outcome of a settings export or import, held until the screen has shown
|
||||
* it. Plain classes, not data ones: two equal outcomes in a row must each count.
|
||||
*/
|
||||
sealed interface SettingsBackupResult {
|
||||
class Exported : SettingsBackupResult
|
||||
class ExportFailed : SettingsBackupResult
|
||||
class Imported(val summary: SettingsImportSummary) : SettingsBackupResult
|
||||
class ImportFailed(val problem: BackupProblem) : SettingsBackupResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings export/import on the Backup & restore screen (#481). The file is a
|
||||
* single SAF document the user picked; the engine knows nothing about it.
|
||||
* The result is state rather than an event, so an import that changes the
|
||||
* app language — and recreates the activity — still shows its summary.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class SettingsBackupViewModel @Inject constructor(
|
||||
private val engine: SettingsBackupEngine,
|
||||
@ApplicationContext private val context: Context,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _busy = MutableStateFlow(false)
|
||||
val busy: StateFlow<Boolean> = _busy.asStateFlow()
|
||||
|
||||
private val _result = MutableStateFlow<SettingsBackupResult?>(null)
|
||||
val result: StateFlow<SettingsBackupResult?> = _result.asStateFlow()
|
||||
|
||||
fun export(uri: Uri) = launchWork {
|
||||
try {
|
||||
val text = engine.export()
|
||||
withContext(io) { context.contentResolver.writeDocumentBytes(uri, text.toByteArray(Charsets.UTF_8)) }
|
||||
SettingsBackupResult.Exported()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
SettingsBackupResult.ExportFailed()
|
||||
}
|
||||
}
|
||||
|
||||
/** Call only once the user has confirmed replacing their settings. */
|
||||
fun import(uri: Uri) = launchWork {
|
||||
val text = try {
|
||||
withContext(io) {
|
||||
context.contentResolver.readDocumentBytes(uri, engine.maxImportBytes).toString(Charsets.UTF_8)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: DocumentTooLargeException) {
|
||||
return@launchWork SettingsBackupResult.ImportFailed(BackupProblem.TOO_LARGE)
|
||||
} catch (e: Exception) {
|
||||
return@launchWork SettingsBackupResult.ImportFailed(BackupProblem.UNREADABLE)
|
||||
}
|
||||
try {
|
||||
when (val imported = engine.import(text)) {
|
||||
is BackupResult.Success -> SettingsBackupResult.Imported(imported.value)
|
||||
is BackupResult.Failure -> SettingsBackupResult.ImportFailed(imported.problem)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
SettingsBackupResult.ImportFailed(BackupProblem.NOT_APPLIED)
|
||||
}
|
||||
}
|
||||
|
||||
fun consumeResult() {
|
||||
_result.value = null
|
||||
}
|
||||
|
||||
private fun launchWork(work: suspend () -> SettingsBackupResult) {
|
||||
if (_busy.value) return
|
||||
_busy.value = true
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_result.value = work()
|
||||
} finally {
|
||||
_busy.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -73,13 +72,11 @@ fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||
@Composable
|
||||
fun sourceAppName(accountType: String): String {
|
||||
val context = LocalContext.current
|
||||
return remember(accountType) { sourceAppLabel(context, accountType) }
|
||||
}
|
||||
|
||||
/** [sourceAppName] outside composition, e.g. for notification channel groups. */
|
||||
fun sourceAppLabel(context: Context, accountType: String): String {
|
||||
val pm = context.packageManager
|
||||
return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
return remember(accountType) {
|
||||
val pm = context.packageManager
|
||||
val packages = sourceAppPackages(context, accountType)
|
||||
packages.firstNotNullOfOrNull { pkg ->
|
||||
runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull()
|
||||
} ?: accountType
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,8 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DateRange
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.ManageAccounts
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material3.DrawerState
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LoadingIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalDrawerSheet
|
||||
import androidx.compose.material3.Text
|
||||
@@ -42,8 +38,6 @@ import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.colorResource
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.filter.CalendarFilterList
|
||||
@@ -67,8 +61,6 @@ import kotlinx.datetime.LocalDate
|
||||
*
|
||||
* [currentDate] seeds the jump-to-date picker (the visible day/week-start/month
|
||||
* anchor); [onJumpToDate] navigates the active view to the chosen day.
|
||||
* [sync] adds "Sync now" beside it while there is a synced calendar (#240),
|
||||
* and a row to grant account access while some account can't be reached yet.
|
||||
*/
|
||||
@Composable
|
||||
fun CalendarDrawer(
|
||||
@@ -78,9 +70,7 @@ fun CalendarDrawer(
|
||||
onSelectView: (CalendarView) -> Unit,
|
||||
onJumpToDate: (LocalDate) -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
onHideInView: () -> Unit,
|
||||
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
|
||||
sync: DrawerSync? = null,
|
||||
) {
|
||||
var showDatePicker by remember { mutableStateOf(false) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -113,17 +103,16 @@ fun CalendarDrawer(
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_jump_to_date),
|
||||
position = if (sync?.hasRows == true) Position.Top else Position.Alone,
|
||||
position = Position.Alone,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.DateRange) },
|
||||
onClick = { showDatePicker = true },
|
||||
)
|
||||
if (sync != null) SyncRows(sync)
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
DrawerSectionHeader(stringResource(R.string.filter_title))
|
||||
CalendarFilterList(currentView = currentView, onHideInView = onHideInView)
|
||||
CalendarFilterList()
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
GroupedRow(
|
||||
@@ -149,64 +138,6 @@ fun CalendarDrawer(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress
|
||||
* and ignores taps, [outcome] the last request's result while the drawer stays
|
||||
* open), and a grant row while some account [needsAccess].
|
||||
*/
|
||||
data class DrawerSync(
|
||||
val canSync: Boolean,
|
||||
val inFlight: Boolean,
|
||||
val outcome: String?,
|
||||
val needsAccess: Boolean,
|
||||
val onSync: () -> Unit,
|
||||
val onGrantAccess: () -> Unit,
|
||||
) {
|
||||
val hasRows: Boolean get() = canSync || needsAccess
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncRows(sync: DrawerSync) {
|
||||
if (sync.canSync) {
|
||||
SyncNowRow(sync, if (sync.needsAccess) Position.Middle else Position.Bottom)
|
||||
}
|
||||
if (sync.needsAccess) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_sync_access),
|
||||
summary = stringResource(R.string.drawer_sync_access_summary),
|
||||
position = Position.Bottom,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.ManageAccounts) },
|
||||
onClick = sync.onGrantAccess,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun SyncNowRow(sync: DrawerSync, position: Position) {
|
||||
val inFlightText = stringResource(R.string.sync_in_progress)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.drawer_sync_now),
|
||||
summary = if (sync.inFlight) inFlightText else sync.outcome,
|
||||
position = position,
|
||||
modifier = if (sync.inFlight) {
|
||||
Modifier.semantics { stateDescription = inFlightText }
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
dimmed = sync.inFlight,
|
||||
minHeight = 56.dp,
|
||||
leading = { DrawerLeadingIcon(Icons.Filled.Sync) },
|
||||
trailing = if (sync.inFlight) {
|
||||
{ LoadingIndicator(Modifier.size(32.dp)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = sync.onSync.takeIf { !sync.inFlight },
|
||||
)
|
||||
}
|
||||
|
||||
/** Leading slot for the drawer's plain icons: the same 40.dp footprint
|
||||
* [CalendarColorChip] takes, so every leading glyph shares one vertical axis. */
|
||||
@Composable
|
||||
|
||||
@@ -15,7 +15,6 @@ import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.Cloud
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -56,13 +55,28 @@ fun ColumnScope.CalendarPickerGroups(
|
||||
onSelect: (Long) -> Unit,
|
||||
onManageCalendars: (() -> Unit)? = null,
|
||||
) {
|
||||
CalendarAccountSections(calendars) { calendar, position ->
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
position = position,
|
||||
checked = calendar.id == selectedId,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
onClick = { onSelect(calendar.id) },
|
||||
val local = remember(calendars) { calendars.filter { it.isLocal } }
|
||||
val syncedGroups = remember(calendars) {
|
||||
calendars.filterNot { it.isLocal }.groupByAccount()
|
||||
}
|
||||
|
||||
if (local.isNotEmpty()) {
|
||||
CalendarPickerGroup(
|
||||
title = stringResource(R.string.calendars_local_header),
|
||||
leading = { LeadingAvatar(Icons.Default.PhoneAndroid) },
|
||||
calendars = local,
|
||||
selectedId = selectedId,
|
||||
onSelect = onSelect,
|
||||
)
|
||||
}
|
||||
syncedGroups.forEachIndexed { index, group ->
|
||||
if (local.isNotEmpty() || index > 0) Spacer(Modifier.height(16.dp))
|
||||
CalendarPickerGroup(
|
||||
title = accountGroupTitle(group),
|
||||
leading = { SourceLogo(group.accountType) },
|
||||
calendars = group.calendars,
|
||||
selectedId = selectedId,
|
||||
onSelect = onSelect,
|
||||
)
|
||||
}
|
||||
if (onManageCalendars != null) {
|
||||
@@ -84,68 +98,14 @@ fun ColumnScope.CalendarPickerGroups(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-select take on [CalendarPickerGroups]: the same sections, with a
|
||||
* checkbox per calendar instead of a single check.
|
||||
*/
|
||||
/** One account's category header (avatar + name) atop its selectable calendars. */
|
||||
@Composable
|
||||
fun ColumnScope.CalendarCheckGroups(
|
||||
calendars: List<CalendarSource>,
|
||||
isChecked: (CalendarSource) -> Boolean,
|
||||
onCheckedChange: (CalendarSource, Boolean) -> Unit,
|
||||
) {
|
||||
CalendarAccountSections(calendars) { calendar, position ->
|
||||
val checked = isChecked(calendar)
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = calendar.description,
|
||||
position = position,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Checkbox(checked = checked, onCheckedChange = { onCheckedChange(calendar, it) })
|
||||
},
|
||||
onClick = { onCheckedChange(calendar, !checked) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The app's own calendars, then one section per synced account, each under its category header. */
|
||||
@Composable
|
||||
private fun CalendarAccountSections(
|
||||
calendars: List<CalendarSource>,
|
||||
row: @Composable (CalendarSource, Position) -> Unit,
|
||||
) {
|
||||
val local = remember(calendars) { calendars.filter { it.isLocal } }
|
||||
val syncedGroups = remember(calendars) {
|
||||
calendars.filterNot { it.isLocal }.groupByAccount()
|
||||
}
|
||||
|
||||
if (local.isNotEmpty()) {
|
||||
CalendarAccountSection(
|
||||
title = stringResource(R.string.calendars_local_header),
|
||||
leading = { LeadingAvatar(Icons.Default.PhoneAndroid) },
|
||||
calendars = local,
|
||||
row = row,
|
||||
)
|
||||
}
|
||||
syncedGroups.forEachIndexed { index, group ->
|
||||
if (local.isNotEmpty() || index > 0) Spacer(Modifier.height(16.dp))
|
||||
CalendarAccountSection(
|
||||
title = accountGroupTitle(group),
|
||||
leading = { SourceLogo(group.accountType) },
|
||||
calendars = group.calendars,
|
||||
row = row,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One account's category header (avatar + name) atop its calendars. */
|
||||
@Composable
|
||||
private fun CalendarAccountSection(
|
||||
private fun CalendarPickerGroup(
|
||||
title: String,
|
||||
leading: @Composable () -> Unit,
|
||||
calendars: List<CalendarSource>,
|
||||
row: @Composable (CalendarSource, Position) -> Unit,
|
||||
selectedId: Long?,
|
||||
onSelect: (Long) -> Unit,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = title,
|
||||
@@ -153,7 +113,13 @@ private fun CalendarAccountSection(
|
||||
leading = leading,
|
||||
)
|
||||
calendars.forEachIndexed { index, calendar ->
|
||||
row(calendar, if (index == calendars.lastIndex) Position.Bottom else Position.Middle)
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
position = if (index == calendars.lastIndex) Position.Bottom else Position.Middle,
|
||||
checked = calendar.id == selectedId,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
onClick = { onSelect(calendar.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ import java.util.Locale
|
||||
* out in [locale]'s own order, with the year shown only when [date] falls outside
|
||||
* [currentYear].
|
||||
*
|
||||
* Pass [skeleton] *without* a year field, e.g. "LLLL" for a month. A skeleton
|
||||
* is a field list, so wanting the year is just asking for one more field; the
|
||||
* locale still decides where it lands ("July 2026" vs "2026年7月").
|
||||
* Pass [skeleton] *without* a year field — "LLLL" for a month, "EEEdMMM" for a
|
||||
* day. A skeleton is a field list, so wanting the year is just asking for one
|
||||
* more field; the locale still decides where it lands ("July 2026" vs "2026年7月").
|
||||
*
|
||||
* Dropping the year in the current year is the one bit of policy here: the title
|
||||
* sits directly above a grid that already says which year it is, and the year's
|
||||
|
||||
@@ -15,7 +15,6 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.toDuplicateForm
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -44,7 +43,6 @@ class EventActionsViewModel @Inject constructor(
|
||||
private val icsExporter: IcsExporter,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Every calendar by id, for what a selected event's bar may offer. */
|
||||
@@ -66,7 +64,8 @@ class EventActionsViewModel @Inject constructor(
|
||||
/** A create form copying [event], or null when it can't be read. */
|
||||
suspend fun duplicateForm(event: EventInstance): EventForm? {
|
||||
val detail = load(event) ?: return null
|
||||
return detail.toDuplicateForm(zoneSource.current(), settingsPrefs.knownFixedTimeReminders.first())
|
||||
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
|
||||
return detail.toDuplicateForm(canModify, zoneSource.current())
|
||||
}
|
||||
|
||||
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
|
||||
|
||||
@@ -51,8 +51,8 @@ private val FAB_BAND = 88.dp
|
||||
fun EventMoveHost(
|
||||
viewModel: RescheduleViewModel,
|
||||
modifier: Modifier = Modifier,
|
||||
notice: String? = null,
|
||||
onNoticeShown: () -> Unit = {},
|
||||
actionFailure: String? = null,
|
||||
onActionFailureShown: () -> Unit = {},
|
||||
) {
|
||||
val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle()
|
||||
val outcome by viewModel.outcome.collectAsStateWithLifecycle()
|
||||
@@ -81,7 +81,7 @@ fun EventMoveHost(
|
||||
}
|
||||
// A failed selection action (#141) shares the chip rather than stacking on it.
|
||||
val message = when (outcome) {
|
||||
null -> notice
|
||||
null -> actionFailure
|
||||
is MoveOutcome.Moved -> if (resizedLabel != null) {
|
||||
stringResource(R.string.event_resize_done, resizedLabel)
|
||||
} else {
|
||||
@@ -90,9 +90,6 @@ fun EventMoveHost(
|
||||
MoveOutcome.Undone -> stringResource(R.string.event_move_undone)
|
||||
MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied)
|
||||
MoveOutcome.Gone -> stringResource(R.string.event_move_gone)
|
||||
MoveOutcome.Stale -> stringResource(R.string.event_move_stale)
|
||||
MoveOutcome.Skipped -> stringResource(R.string.event_move_skipped)
|
||||
MoveOutcome.QueueFull -> stringResource(R.string.event_move_queue_full)
|
||||
MoveOutcome.BlockedSeriesEnd -> stringResource(R.string.event_move_blocked_series_end)
|
||||
MoveOutcome.BlockedCancelledSeries -> stringResource(R.string.event_move_blocked_cancelled_series)
|
||||
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
|
||||
@@ -116,10 +113,10 @@ fun EventMoveHost(
|
||||
viewModel.consumeOutcome()
|
||||
}
|
||||
// A failure waits for the chip to be free, then has its own turn.
|
||||
LaunchedEffect(notice, outcome == null) {
|
||||
if (notice == null || outcome != null) return@LaunchedEffect
|
||||
LaunchedEffect(actionFailure, outcome == null) {
|
||||
if (actionFailure == null || outcome != null) return@LaunchedEffect
|
||||
delay(CHIP_MILLIS)
|
||||
onNoticeShown()
|
||||
onActionFailureShown()
|
||||
}
|
||||
|
||||
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
|
||||
@@ -138,7 +135,7 @@ fun EventMoveHost(
|
||||
// write anyway, so offering it would be a button that does nothing.
|
||||
val undo = content.undo?.takeIf { !writeInFlight }
|
||||
SnackChip(
|
||||
visible = outcome != null || notice != null,
|
||||
visible = outcome != null || actionFailure != null,
|
||||
message = content.message,
|
||||
maxWidth = chipMaxWidth,
|
||||
actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null },
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import kotlinx.coroutines.delay
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -19,7 +16,6 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
|
||||
@@ -41,18 +37,24 @@ class EventMoveScope(
|
||||
val dragEnabled: Boolean,
|
||||
/**
|
||||
* Hand a drop to the writer. Returns nothing on purpose: a drop is answered
|
||||
* before its write resolves, so [drops] — not a return value — is what tells
|
||||
* a held copy whether anything landed.
|
||||
* before its write resolves, so [abandoned] — not a return value — is what
|
||||
* tells a held copy that nothing landed.
|
||||
*/
|
||||
val move: (MoveRequest) -> Unit,
|
||||
/**
|
||||
* Each drop's progress by its token — see `RescheduleViewModel.drops`. A flow
|
||||
* rather than a value so this scope stays the same object across a move —
|
||||
* every visible block reads it as a composition local.
|
||||
* True while a dropped event is being written, including the time its scope
|
||||
* dialog is up. A flow rather than a value so this scope stays the same
|
||||
* object across a move — every visible block reads it as a composition local.
|
||||
*/
|
||||
val drops: StateFlow<DropStates>,
|
||||
/** The undo write that just began — see `RescheduleViewModel.undoStarted`. */
|
||||
val undoStarted: StateFlow<UndoStart?>,
|
||||
val inFlight: StateFlow<Boolean>,
|
||||
/** Ticks when an undo write begins — see `RescheduleViewModel.undoStarted`. */
|
||||
val undoStarted: StateFlow<Int>,
|
||||
/**
|
||||
* Ticks when a drop ends with nothing landing — see
|
||||
* `RescheduleViewModel.abandoned`. [move] answers before the write is
|
||||
* resolved, so this is what tells a held copy to stop waiting.
|
||||
*/
|
||||
val abandoned: StateFlow<Int>,
|
||||
/** Open an event in the edit form — the pointer-free route to the same change. */
|
||||
val edit: (EventInstance) -> Unit,
|
||||
) {
|
||||
@@ -61,42 +63,30 @@ class EventMoveScope(
|
||||
|
||||
val LocalEventMove = compositionLocalOf<EventMoveScope?> { null }
|
||||
|
||||
private val moveTokens = AtomicLong()
|
||||
private val NEVER_IN_FLIGHT = MutableStateFlow(false)
|
||||
|
||||
/** A fresh identity for one drop or undo, unique for the process. */
|
||||
fun nextMoveToken(): Long = moveTokens.incrementAndGet()
|
||||
private val NEVER_UNDONE = MutableStateFlow(0)
|
||||
|
||||
/** How many abandoned drops [DropStates] remembers — far more than can be on screen at once. */
|
||||
private const val ABANDONED_KEPT = 32
|
||||
|
||||
/** Per-drop progress, by token — see `RescheduleViewModel.drops`. */
|
||||
@Immutable
|
||||
data class DropStates(
|
||||
val pending: Set<Long> = emptySet(),
|
||||
val abandoned: Set<Long> = emptySet(),
|
||||
) {
|
||||
fun started(token: Long): DropStates = copy(pending = pending + token)
|
||||
|
||||
fun ended(token: Long, landed: Boolean): DropStates = copy(
|
||||
pending = pending - token,
|
||||
// Insertion-ordered, so the oldest go first.
|
||||
abandoned = if (landed) abandoned else (abandoned + token).let { kept ->
|
||||
if (kept.size > ABANDONED_KEPT) kept.drop(kept.size - ABANDONED_KEPT).toSet() else kept
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private val NO_DROPS = MutableStateFlow(DropStates())
|
||||
|
||||
private val NEVER_UNDONE = MutableStateFlow<UndoStart?>(null)
|
||||
private val NEVER_ABANDONED = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* Every drop's progress — empty wherever moving is off. A drag overlay keeps
|
||||
* the token of its own drop and holds its copy while that token is pending.
|
||||
* Whether a dropped event is still being written — false wherever moving is off.
|
||||
* The drag overlays hold a landed block on its target for this window.
|
||||
*/
|
||||
@Composable
|
||||
fun dropStates(): DropStates {
|
||||
val flow = LocalEventMove.current?.drops ?: NO_DROPS
|
||||
fun moveInFlight(): Boolean {
|
||||
val flow = LocalEventMove.current?.inFlight ?: NEVER_IN_FLIGHT
|
||||
return flow.collectAsStateWithLifecycle().value
|
||||
}
|
||||
|
||||
/**
|
||||
* How many drops have ended with nothing landing. Read as a plain count so a
|
||||
* drag overlay can capture it at the moment of the drop and tell, later, whether
|
||||
* *its own* drop was one of them.
|
||||
*/
|
||||
@Composable
|
||||
fun abandonedMoves(): Int {
|
||||
val flow = LocalEventMove.current?.abandoned ?: NEVER_ABANDONED
|
||||
return flow.collectAsStateWithLifecycle().value
|
||||
}
|
||||
|
||||
@@ -105,53 +95,17 @@ fun dropStates(): DropStates {
|
||||
* this composable came on screen.
|
||||
*/
|
||||
@Composable
|
||||
fun OnUndoStarted(onUndo: (UndoStart) -> Unit) {
|
||||
fun OnUndoStarted(onUndo: () -> Unit) {
|
||||
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
|
||||
val start by flow.collectAsStateWithLifecycle()
|
||||
var seen by remember { mutableStateOf(start) }
|
||||
LaunchedEffect(start) {
|
||||
val started = start
|
||||
if (started == null || started == seen) return@LaunchedEffect
|
||||
seen = started
|
||||
onUndo(started)
|
||||
val tick by flow.collectAsStateWithLifecycle()
|
||||
var seen by remember { mutableIntStateOf(tick) }
|
||||
LaunchedEffect(tick) {
|
||||
if (tick == seen) return@LaunchedEffect
|
||||
seen = tick
|
||||
onUndo()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The life of a drop parked by a newer pickup (#494): held while its [token]
|
||||
* is pending, then a beat after the grid [seated] it — or [timeoutMillis] if it
|
||||
* never does — handed over and faded, then released. Returns the copy's alpha.
|
||||
* An abandoned drop skips the wait; nothing is coming to seat it.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberHeldSettle(
|
||||
token: Long,
|
||||
seated: Boolean,
|
||||
timeoutMillis: Long,
|
||||
onHandOver: () -> Unit,
|
||||
onRelease: () -> Unit,
|
||||
): Float {
|
||||
val drops = dropStates()
|
||||
val pending = token in drops.pending
|
||||
val abandoned = token in drops.abandoned
|
||||
val handOver by rememberUpdatedState(onHandOver)
|
||||
val release by rememberUpdatedState(onRelease)
|
||||
var fading by remember(token) { mutableStateOf(false) }
|
||||
LaunchedEffect(token, pending, abandoned, seated) {
|
||||
if (pending) return@LaunchedEffect
|
||||
if (!abandoned) delay(if (seated) SETTLE_GRACE_MILLIS else timeoutMillis)
|
||||
fading = true
|
||||
handOver()
|
||||
delay(SETTLE_FADE_MILLIS.toLong())
|
||||
release()
|
||||
}
|
||||
return animateFloatAsState(
|
||||
targetValue = if (fading) 0f else 1f,
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "held-settle",
|
||||
).value
|
||||
}
|
||||
|
||||
/** Opacity the source block keeps while its floating copy travels. */
|
||||
const val GHOST_ALPHA: Float = 0.3f
|
||||
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.Saver
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.floret.components.CustomExpandRow
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/** "1 day before at 20:00", in the app's 12/24-hour convention. */
|
||||
@Composable
|
||||
fun fixedTimeReminderLabel(reminder: FixedTimeReminder): String = stringResource(
|
||||
R.string.reminder_fixed_time,
|
||||
pluralStringResource(R.plurals.reminder_days, reminder.daysBefore, reminder.daysBefore),
|
||||
formatMinuteOfDay(reminder.minuteOfDay, LocalUse24HourFormat.current, currentLocale()),
|
||||
)
|
||||
|
||||
/**
|
||||
* The "N days before at HH:MM" editor (#459): a day count and a time, read as
|
||||
* one sentence. Seeded from [initial]; [onValueChange] follows every edit (null
|
||||
* while the day count is out of range). With a [confirmLabel] it carries its own
|
||||
* confirm, reporting through [onConfirm]; without one the host picker commits
|
||||
* from its actions slot. [connected] gives it the shape that meets a row above it.
|
||||
*/
|
||||
@Composable
|
||||
fun FixedTimeReminderEditor(
|
||||
initial: FixedTimeReminder,
|
||||
modifier: Modifier = Modifier,
|
||||
confirmLabel: String? = null,
|
||||
onConfirm: (FixedTimeReminder) -> Unit = {},
|
||||
onValueChange: (FixedTimeReminder?) -> Unit = {},
|
||||
connected: Boolean = true,
|
||||
) {
|
||||
var daysText by rememberSaveable { mutableStateOf(initial.daysBefore.toString()) }
|
||||
var minuteOfDay by rememberSaveable { mutableStateOf(initial.minuteOfDay) }
|
||||
var pickingTime by rememberSaveable { mutableStateOf(false) }
|
||||
val days = daysText.toIntOrNull()?.takeIf { it in 1..FixedTimeReminder.MAX_DAYS_BEFORE }
|
||||
val value = days?.let { FixedTimeReminder(it, minuteOfDay) }
|
||||
LaunchedEffect(value) { onValueChange(value) }
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
shape = if (connected) {
|
||||
RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 22.dp, bottomEnd = 22.dp)
|
||||
} else {
|
||||
RoundedCornerShape(22.dp)
|
||||
},
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
DialogAmountField(value = daysText, onValueChange = { daysText = it }, placeholder = "1")
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.reminder_fixed_days_before_at),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
FilledTonalButton(onClick = { pickingTime = true }) {
|
||||
Text(formatMinuteOfDay(minuteOfDay, LocalUse24HourFormat.current, currentLocale()))
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
text = value?.let { fixedTimeReminderLabel(it) }
|
||||
?: stringResource(R.string.reminder_fixed_days_range, FixedTimeReminder.MAX_DAYS_BEFORE),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (confirmLabel != null) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
FilledTonalButton(
|
||||
enabled = value != null,
|
||||
onClick = { value?.let(onConfirm) },
|
||||
) { Text(confirmLabel) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pickingTime) {
|
||||
TimePickerAlert(
|
||||
initial = LocalTime(minuteOfDay / 60, minuteOfDay % 60),
|
||||
onConfirm = {
|
||||
minuteOfDay = it.hour * 60 + it.minute
|
||||
pickingTime = false
|
||||
},
|
||||
onDismiss = { pickingTime = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picker for a fixed-time default (#459), full-screen: off, or a reminder at a
|
||||
* set time edited in place — and, on a per-calendar picker ([inheritedLabel]
|
||||
* non-null), deferring to the global default, [inherited], which also seeds the
|
||||
* editor. Applies live; the user leaves via back.
|
||||
*/
|
||||
@Composable
|
||||
fun FixedTimeReminderPicker(
|
||||
title: String,
|
||||
selected: FixedTimeOverride,
|
||||
onSelect: (FixedTimeOverride) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
inheritedLabel: String? = null,
|
||||
inherited: FixedTimeReminder? = null,
|
||||
) {
|
||||
var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) }
|
||||
var editing by rememberSaveable { mutableStateOf(false) }
|
||||
// Mirrors [selected] until the first pick, as ReminderDefaultPicker does.
|
||||
var userEdited by rememberSaveable { mutableStateOf(false) }
|
||||
LaunchedEffect(selected) {
|
||||
if (!userEdited) current = selected
|
||||
}
|
||||
fun apply(choice: FixedTimeOverride) {
|
||||
userEdited = true
|
||||
current = choice
|
||||
onSelect(choice)
|
||||
}
|
||||
val chosen = (current as? FixedTimeOverride.At)?.reminder
|
||||
|
||||
FullScreenPicker(title = title, onDismiss = onDismiss) {
|
||||
GroupedHint(text = stringResource(R.string.settings_fixed_reminder_hint))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val rowCount = if (inheritedLabel != null) 3 else 2
|
||||
if (inheritedLabel != null) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_use_default),
|
||||
summary = inheritedLabel,
|
||||
position = Position.Top,
|
||||
checked = current is FixedTimeOverride.Inherit,
|
||||
onClick = { apply(FixedTimeOverride.Inherit) },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_none),
|
||||
position = if (rowCount == 3) Position.Middle else Position.Top,
|
||||
checked = current is FixedTimeOverride.Off,
|
||||
onClick = { apply(FixedTimeOverride.Off) },
|
||||
)
|
||||
CustomExpandRow(
|
||||
title = stringResource(R.string.reminder_fixed_at_set_time),
|
||||
summary = chosen?.let { fixedTimeReminderLabel(it) },
|
||||
position = Position.Bottom,
|
||||
expanded = editing,
|
||||
onExpandedChange = { editing = it },
|
||||
checked = chosen != null,
|
||||
) {
|
||||
FixedTimeReminderEditor(
|
||||
initial = chosen ?: inherited ?: DEFAULT_FIXED_TIME_REMINDER,
|
||||
confirmLabel = stringResource(R.string.reminder_custom_set),
|
||||
onConfirm = {
|
||||
apply(FixedTimeOverride.At(it))
|
||||
editing = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the editor offers first: the evening before. */
|
||||
val DEFAULT_FIXED_TIME_REMINDER = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60)
|
||||
|
||||
private val FixedTimeOverrideSaver = Saver<FixedTimeOverride, String>(
|
||||
save = {
|
||||
when (it) {
|
||||
FixedTimeOverride.Inherit -> "inherit"
|
||||
FixedTimeOverride.Off -> "off"
|
||||
is FixedTimeOverride.At -> it.reminder.toToken()
|
||||
}
|
||||
},
|
||||
restore = {
|
||||
when (it) {
|
||||
"inherit" -> FixedTimeOverride.Inherit
|
||||
"off" -> FixedTimeOverride.Off
|
||||
else -> FixedTimeReminder.parse(it)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Off
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -6,7 +6,6 @@ import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -39,8 +38,8 @@ import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.time.Clock
|
||||
|
||||
/**
|
||||
* Reminder-default picker, full-screen and **multi-select**: each preset
|
||||
* lead time ([reminderPresets] for [isAllDay]) (plus any chosen custom value) is a checkbox row that toggles
|
||||
* Reminder-default picker, full-screen and **multi-select**: each [presets]
|
||||
* lead time (plus any chosen custom value) is a checkbox row that toggles
|
||||
* independently, so a default can carry several reminders ("1 week before" *and*
|
||||
* "on the day"). Two exclusive checkmark rows sit above the list: an explicit
|
||||
* "No reminder" (both pickers, so the empty state stays visible and reachable)
|
||||
@@ -60,7 +59,7 @@ import kotlin.time.Clock
|
||||
@Composable
|
||||
fun ReminderDefaultPicker(
|
||||
title: String,
|
||||
isAllDay: Boolean,
|
||||
presets: List<Int>,
|
||||
selected: ReminderOverride,
|
||||
allowInherit: Boolean,
|
||||
onSelect: (ReminderOverride) -> Unit,
|
||||
@@ -88,17 +87,14 @@ fun ReminderDefaultPicker(
|
||||
// Custom (non-preset) lead times seen this session, so unchecking one keeps
|
||||
// its row (unchecked) until the picker closes instead of vanishing mid-tap,
|
||||
// which would strand a hand-entered value with no way to re-check it.
|
||||
val presets = reminderPresets(isAllDay)
|
||||
val units = customReminderUnits(isAllDay)
|
||||
val seenCustom = remember { mutableSetOf<Int>() }
|
||||
seenCustom += selectedMinutes.filter { it !in presets }
|
||||
// Presets plus every custom value seen this session, each as its own row.
|
||||
val rows = presets + seenCustom
|
||||
val rows = presets + seenCustom.sorted()
|
||||
|
||||
var customExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var amountText by rememberSaveable { mutableStateOf("") }
|
||||
var pickedUnit by rememberSaveable { mutableStateOf(units.first()) }
|
||||
val unit = pickedUnit.takeIf { it in units } ?: units.first()
|
||||
var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) }
|
||||
|
||||
fun apply(override: ReminderOverride) {
|
||||
userEdited = true
|
||||
@@ -129,66 +125,37 @@ fun ReminderDefaultPicker(
|
||||
onClick = { apply(ReminderOverride.None) },
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedLeadTimeRows(
|
||||
minutes = rows,
|
||||
splitSubDay = splitsSubDay(presets),
|
||||
row = { minute, position ->
|
||||
val checked = minute in selectedMinutes
|
||||
GroupedRow(
|
||||
title = reminderLeadTimeLabel(minute),
|
||||
summary = leadTimeSummary?.invoke(minute),
|
||||
position = position,
|
||||
selected = checked,
|
||||
trailing = { Checkbox(checked = checked, onCheckedChange = { toggle(minute) }) },
|
||||
onClick = { toggle(minute) },
|
||||
)
|
||||
},
|
||||
trailing = { position ->
|
||||
CustomExpandRow(
|
||||
title = stringResource(R.string.event_edit_reminder_custom),
|
||||
position = position,
|
||||
expanded = customExpanded,
|
||||
onExpandedChange = { customExpanded = it },
|
||||
) {
|
||||
CustomReminderEditor(
|
||||
amountText = amountText,
|
||||
onAmountChange = { amountText = it },
|
||||
units = units,
|
||||
unit = unit,
|
||||
onUnitChange = { pickedUnit = it },
|
||||
onConfirm = { minutes ->
|
||||
emit(selectedMinutes + minutes)
|
||||
amountText = ""
|
||||
customExpanded = false
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lead-time rows laid out as [groupReminderLeadTimes] groups, each a connected
|
||||
* card, with [trailing] (the Custom row) closing the last one.
|
||||
*/
|
||||
@Composable
|
||||
internal fun GroupedLeadTimeRows(
|
||||
minutes: Collection<Int>,
|
||||
splitSubDay: Boolean,
|
||||
row: @Composable (minute: Int, position: Position) -> Unit,
|
||||
trailing: @Composable (position: Position) -> Unit,
|
||||
) {
|
||||
val groups = groupReminderLeadTimes(minutes, splitSubDay)
|
||||
groups.forEachIndexed { groupIndex, group ->
|
||||
val isLast = groupIndex == groups.lastIndex
|
||||
val rowCount = group.size + if (isLast) 1 else 0
|
||||
group.forEachIndexed { index, minute ->
|
||||
key(minute) { row(minute, positionOf(index, rowCount)) }
|
||||
val rowCount = rows.size + 1 // + the custom row
|
||||
rows.forEachIndexed { index, minute ->
|
||||
val checked = minute in selectedMinutes
|
||||
GroupedRow(
|
||||
title = reminderLeadTimeLabel(minute),
|
||||
summary = leadTimeSummary?.invoke(minute),
|
||||
position = positionOf(index, rowCount),
|
||||
selected = checked,
|
||||
trailing = { Checkbox(checked = checked, onCheckedChange = { toggle(minute) }) },
|
||||
onClick = { toggle(minute) },
|
||||
)
|
||||
}
|
||||
CustomExpandRow(
|
||||
title = stringResource(R.string.event_edit_reminder_custom),
|
||||
position = positionOf(rows.size, rowCount),
|
||||
expanded = customExpanded,
|
||||
onExpandedChange = { customExpanded = it },
|
||||
) {
|
||||
CustomReminderEditor(
|
||||
amountText = amountText,
|
||||
onAmountChange = { amountText = it },
|
||||
unit = unit,
|
||||
onUnitChange = { unit = it },
|
||||
onConfirm = { minutes ->
|
||||
emit(selectedMinutes + minutes)
|
||||
amountText = ""
|
||||
customExpanded = false
|
||||
},
|
||||
)
|
||||
}
|
||||
if (!isLast) Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
trailing(if (groups.isEmpty()) Position.Alone else Position.Bottom)
|
||||
}
|
||||
|
||||
|
||||
@@ -203,7 +170,6 @@ internal fun GroupedLeadTimeRows(
|
||||
private fun CustomReminderEditor(
|
||||
amountText: String,
|
||||
onAmountChange: (String) -> Unit,
|
||||
units: List<ReminderUnit>,
|
||||
unit: ReminderUnit,
|
||||
onUnitChange: (ReminderUnit) -> Unit,
|
||||
onConfirm: (Int) -> Unit,
|
||||
@@ -212,10 +178,9 @@ private fun CustomReminderEditor(
|
||||
CustomAmountEditor(
|
||||
amountText = amountText,
|
||||
onAmountChange = onAmountChange,
|
||||
unitLabels = units.map { stringResource(reminderUnitLabel(it)) },
|
||||
placeholder = customReminderPlaceholder(unit),
|
||||
selectedUnit = units.indexOf(unit),
|
||||
onUnitChange = { onUnitChange(units[it]) },
|
||||
unitLabels = ReminderUnit.entries.map { stringResource(reminderUnitLabel(it)) },
|
||||
selectedUnit = unit.ordinal,
|
||||
onUnitChange = { onUnitChange(ReminderUnit.entries[it]) },
|
||||
preview = amount?.let { reminderLeadTimeLabel(it * unit.minutesFactor) }
|
||||
?: stringResource(R.string.reminder_custom_amount),
|
||||
setLabel = stringResource(R.string.reminder_custom_set),
|
||||
|
||||
@@ -8,46 +8,8 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.MINUTES_DEFAULT
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderUnit
|
||||
|
||||
private val DAY = ReminderUnit.Days.minutesFactor
|
||||
private val WEEK = ReminderUnit.Weeks.minutesFactor
|
||||
|
||||
private val DAY_SCALE_PRESETS =
|
||||
listOf(DAY, 2 * DAY, 3 * DAY, 4 * DAY, 5 * DAY, WEEK, 2 * WEEK, 3 * WEEK)
|
||||
|
||||
/** Common reminder lead times offered as quick picks in the form and settings. */
|
||||
val REMINDER_PRESETS = listOf(0, 10, 30, 60) + DAY_SCALE_PRESETS
|
||||
|
||||
/** Day-scale lead times for all-day events, all-day defaults and contact special dates. */
|
||||
val ALLDAY_REMINDER_PRESETS = listOf(0) + DAY_SCALE_PRESETS
|
||||
|
||||
fun reminderPresets(isAllDay: Boolean): List<Int> =
|
||||
if (isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS
|
||||
|
||||
/**
|
||||
* Units the Custom step offers. All-day reminders fire on whole days at the
|
||||
* all-day reminder time, so minutes and hours would be dropped on save.
|
||||
*/
|
||||
fun customReminderUnits(isAllDay: Boolean): List<ReminderUnit> =
|
||||
if (isAllDay) listOf(ReminderUnit.Days, ReminderUnit.Weeks) else ReminderUnit.entries
|
||||
|
||||
/** Placeholder for the Custom amount field: a typical amount in [unit]. */
|
||||
fun customReminderPlaceholder(unit: ReminderUnit): String =
|
||||
if (unit == ReminderUnit.Minutes) "10" else "1"
|
||||
|
||||
/** Whether a picker over [presets] splits its rows into sub-day and day-scale groups. */
|
||||
fun splitsSubDay(presets: Collection<Int>): Boolean = presets.any { it in 1 until DAY }
|
||||
|
||||
/**
|
||||
* Sorts lead times and, when [splitSubDay] (see [splitsSubDay]), splits them into a sub-day group and
|
||||
* a day-scale group so a long picker list reads as two connected sections.
|
||||
* Empty groups are dropped.
|
||||
*/
|
||||
fun groupReminderLeadTimes(minutes: Collection<Int>, splitSubDay: Boolean): List<List<Int>> {
|
||||
val sorted = minutes.sorted()
|
||||
if (!splitSubDay) return listOfNotNull(sorted.takeIf { it.isNotEmpty() })
|
||||
val (subDay, dayScale) = sorted.partition { it < DAY }
|
||||
return listOf(subDay, dayScale).filter { it.isNotEmpty() }
|
||||
}
|
||||
val REMINDER_PRESETS = listOf(0, 10, 30, 60, 1_440)
|
||||
|
||||
@StringRes
|
||||
fun reminderUnitLabel(unit: ReminderUnit): Int = when (unit) {
|
||||
@@ -73,10 +35,10 @@ fun reminderLeadTimeLabel(minutes: Int): String = when {
|
||||
minutes == MINUTES_DEFAULT -> stringResource(R.string.reminder_default)
|
||||
minutes == 0 -> stringResource(R.string.reminder_at_time)
|
||||
minutes < 0 -> stringResource(R.string.reminder_after, durationLabel(-minutes))
|
||||
minutes % WEEK == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_weeks, minutes / WEEK, minutes / WEEK)
|
||||
minutes % DAY == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_days, minutes / DAY, minutes / DAY)
|
||||
minutes % 10_080 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_weeks, minutes / 10_080, minutes / 10_080)
|
||||
minutes % 1_440 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_days, minutes / 1_440, minutes / 1_440)
|
||||
minutes % 60 == 0 ->
|
||||
pluralStringResource(R.plurals.reminder_hours, minutes / 60, minutes / 60)
|
||||
else -> pluralStringResource(R.plurals.reminder_minutes, minutes, minutes)
|
||||
|
||||
@@ -23,19 +23,15 @@ import de.jeanlucmakiola.calendula.domain.resolvedZone
|
||||
import de.jeanlucmakiola.calendula.domain.shiftedByDays
|
||||
import de.jeanlucmakiola.calendula.domain.shiftedTo
|
||||
import de.jeanlucmakiola.calendula.domain.toEditForm
|
||||
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDate
|
||||
@@ -44,21 +40,12 @@ import kotlinx.datetime.atStartOfDayIn
|
||||
import kotlinx.datetime.plus
|
||||
import kotlinx.datetime.toLocalDateTime
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.Instant
|
||||
import kotlin.time.TimeMark
|
||||
import kotlin.time.TimeSource
|
||||
import javax.inject.Inject
|
||||
|
||||
private const val MILLIS_PER_MINUTE = 60_000
|
||||
private const val MINUTES_PER_DAY = 24 * 60
|
||||
|
||||
/** How many drops may wait behind the one in flight before more are refused. */
|
||||
private const val MAX_QUEUED = 8
|
||||
|
||||
/** How long after a write its event's drawn times may still be the old ones. */
|
||||
private val RECENT_WRITE = 3.seconds
|
||||
|
||||
/** Where a dragged event should land. */
|
||||
sealed interface MoveTarget {
|
||||
/** A new start instant — a timeline drag, which moves time and day at once. */
|
||||
@@ -87,10 +74,6 @@ data class MoveRequest(
|
||||
val beginMillis: Long,
|
||||
val endMillis: Long,
|
||||
val target: MoveTarget,
|
||||
/** Whether the dragged occurrence is all-day, which decides the zone its day is read in. */
|
||||
val isAllDay: Boolean,
|
||||
/** The drop's own identity, from [nextMoveToken], which the view holding its copy waits on. */
|
||||
val token: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -109,13 +92,8 @@ data class MoveUndo(
|
||||
val moved: EventForm,
|
||||
/** The form as it stood before the move. */
|
||||
val restored: EventForm,
|
||||
/** The token of the drop this undoes, so the view that drew it carries the right chip back. */
|
||||
val dropToken: Long,
|
||||
)
|
||||
|
||||
/** An undo write that just began: its own [token], and the [dropToken] of the drop it undoes. */
|
||||
data class UndoStart(val token: Long, val dropToken: Long)
|
||||
|
||||
sealed interface MoveOutcome {
|
||||
/**
|
||||
* Written. [startMillis] is where the dragged occurrence now begins, for the
|
||||
@@ -137,19 +115,6 @@ sealed interface MoveOutcome {
|
||||
/** The event vanished (sync, another device) between the read and the write. */
|
||||
data object Gone : MoveOutcome
|
||||
|
||||
/** Drops that waited behind a scope dialog, cancelled rather than run after it (#494). */
|
||||
data object Skipped : MoveOutcome
|
||||
|
||||
/** More drops waiting than the queue holds; this one was not taken. */
|
||||
data object QueueFull : MoveOutcome
|
||||
|
||||
/**
|
||||
* The drop's recurring occurrence may no longer be where it was picked up —
|
||||
* its series was just written — and can't be followed there, so it is not
|
||||
* written (#494).
|
||||
*/
|
||||
data object Stale : MoveOutcome
|
||||
|
||||
/** The drop would push the series past its own `UNTIL`, generating nothing. */
|
||||
data object BlockedSeriesEnd : MoveOutcome
|
||||
|
||||
@@ -175,7 +140,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
private val repository: CalendarRepository,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _scopePrompt = MutableStateFlow<MoveScopePrompt?>(null)
|
||||
@@ -188,32 +152,36 @@ class RescheduleViewModel @Inject constructor(
|
||||
|
||||
private val _inFlight = MutableStateFlow(false)
|
||||
|
||||
/** True while any drop or undo runs or waits — what the confirmation chip holds for. */
|
||||
/**
|
||||
* True from the moment a drop is accepted until its write settles — the
|
||||
* window the dropped block holds its landing position for.
|
||||
*/
|
||||
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
||||
|
||||
private val _drops = MutableStateFlow(DropStates())
|
||||
private val _abandoned = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* Each drop's own state, by its [MoveRequest.token]: pending from the moment
|
||||
* it is accepted until its write settles, and abandoned once it ends with
|
||||
* nothing on the target day — refused, failed, or its scope dialog dismissed.
|
||||
* Per drop, so a queued drop's held copy waits on its own write and is never
|
||||
* let go by another drop's failure (#253, #494).
|
||||
* Ticks when a drop ends with nothing on the target day: refused outright,
|
||||
* refused before the write, written and failed, or its scope dialog
|
||||
* dismissed. [move] answers before any of that is known, so without this
|
||||
* signal the view that drew the drop held its copy out for the full settle
|
||||
* timeout waiting for a grid that was never going to draw it (#253).
|
||||
*/
|
||||
val drops: StateFlow<DropStates> = _drops.asStateFlow()
|
||||
val abandoned: StateFlow<Int> = _abandoned.asStateFlow()
|
||||
|
||||
private val _undoStarted = MutableStateFlow<UndoStart?>(null)
|
||||
private val _undoStarted = MutableStateFlow(0)
|
||||
|
||||
/**
|
||||
* An undo write the moment it begins, before the provider has anything to
|
||||
* Ticks the moment an undo write begins, before the provider has anything to
|
||||
* re-read, so the view that drew the drop can carry its chip back rather than
|
||||
* let it reappear on the old day. Its fate then reads off [drops].
|
||||
* let it reappear on the old day.
|
||||
*/
|
||||
val undoStarted: StateFlow<UndoStart?> = _undoStarted.asStateFlow()
|
||||
val undoStarted: StateFlow<Int> = _undoStarted.asStateFlow()
|
||||
|
||||
/**
|
||||
* Set while a drop is being prepared, waits on its scope dialog, or is
|
||||
* written. Drops arriving in that window wait in [queue] and run in order.
|
||||
* Set from the moment a drop is accepted until its write settles. Two drops
|
||||
* of the same recurring event inside that window would compute their shift
|
||||
* from the same pre-move occurrence, and the shifts would compound.
|
||||
*/
|
||||
private var busy = false
|
||||
set(value) {
|
||||
@@ -221,22 +189,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
_inFlight.value = value
|
||||
}
|
||||
|
||||
/** Whether a move has been announced since the pipeline was last idle — see [report]. */
|
||||
private var movedThisRun = false
|
||||
|
||||
/** Outcomes waiting for the chip, shown one after another as each is consumed. */
|
||||
private val notices = ArrayDeque<MoveOutcome>()
|
||||
|
||||
/**
|
||||
* When each event's series (by id) or single occurrence (by id and begin)
|
||||
* was last written. The grid draws the old times until it re-reads, so a
|
||||
* drop on a recurring event written moments ago may carry stale times (#494).
|
||||
*/
|
||||
private val written = mutableMapOf<Pair<Long, Long?>, TimeMark>()
|
||||
|
||||
/** Drops that arrived while another was in flight, oldest first (#494). */
|
||||
private val queue = ArrayDeque<MoveRequest>()
|
||||
|
||||
/**
|
||||
* The calendars whose events may be dragged. Nothing below the UI guards
|
||||
* this, so a block outside this set registers no drag gesture at all.
|
||||
@@ -267,50 +219,38 @@ class RescheduleViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Take a drop: run it now, or queue it behind the ones in flight. False means
|
||||
* nothing will be written — the queue is full — and the drop is marked
|
||||
* abandoned in [drops], so its held copy is let go by the one signal rather
|
||||
* than by every caller remembering to.
|
||||
* Take a drop, unless one is already being written. False means nothing will
|
||||
* be written; [abandoned] ticks for that refusal too, so a held copy is let
|
||||
* go by the one signal rather than by every caller remembering to.
|
||||
*
|
||||
* The Boolean is diagnostic — the tests read it, [EventMoveScope] does not
|
||||
* hand it on. It answers before the write is resolved anyway.
|
||||
* hand it on. A caller that gated on it would be back to releasing its copy
|
||||
* from two places, and it answers before the write is resolved anyway.
|
||||
*/
|
||||
fun move(request: MoveRequest): Boolean {
|
||||
if (queue.size >= MAX_QUEUED) {
|
||||
_drops.update { it.ended(request.token, landed = false) }
|
||||
report(MoveOutcome.QueueFull)
|
||||
if (busy || _scopePrompt.value != null) {
|
||||
_abandoned.value += 1
|
||||
return false
|
||||
}
|
||||
if (_scopePrompt.value != null) {
|
||||
_drops.update { it.ended(request.token, landed = false) }
|
||||
report(MoveOutcome.Skipped)
|
||||
return false
|
||||
}
|
||||
_drops.update { it.started(request.token) }
|
||||
if (busy) queue.addLast(request) else run(request)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun run(request: MoveRequest) {
|
||||
busy = true
|
||||
viewModelScope.launch {
|
||||
val prepared = prepare(request)
|
||||
if (prepared == null) {
|
||||
settle(request.token, landed = false)
|
||||
_abandoned.value += 1
|
||||
busy = false
|
||||
return@launch
|
||||
}
|
||||
// A cancelled series only moves as a whole (#388).
|
||||
val seriesOnly = !prepared.original.canSaveApartFromSeries()
|
||||
if (!prepared.isRecurring || (seriesOnly && prepared.canRealign)) {
|
||||
settle(request.token, write(prepared, RecurringWriteScope.AllEvents))
|
||||
write(prepared, RecurringWriteScope.AllEvents)
|
||||
busy = false
|
||||
} else if (seriesOnly) {
|
||||
report(MoveOutcome.BlockedCancelledSeries)
|
||||
settle(request.token, landed = false)
|
||||
_outcome.value = MoveOutcome.BlockedCancelledSeries
|
||||
_abandoned.value += 1
|
||||
busy = false
|
||||
} else {
|
||||
// Still busy: the scope dialog is now the thing in flight. Drops
|
||||
// waiting behind it are cancelled, not held behind a question
|
||||
// about another event.
|
||||
skipQueued()
|
||||
// Still busy: the scope dialog is now the thing in flight.
|
||||
pending = prepared
|
||||
_scopePrompt.value = MoveScopePrompt(
|
||||
occurrenceOnly = !prepared.canRealign,
|
||||
@@ -318,6 +258,7 @@ class RescheduleViewModel @Inject constructor(
|
||||
)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Answer the scope dialog. */
|
||||
@@ -328,92 +269,35 @@ class RescheduleViewModel @Inject constructor(
|
||||
pending = null
|
||||
_scopePrompt.value = null
|
||||
viewModelScope.launch {
|
||||
settle(prepared.request.token, write(prepared, scope))
|
||||
write(prepared, scope)
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Dismiss the scope dialog without writing. */
|
||||
fun cancelScope() {
|
||||
val prepared = pending ?: return
|
||||
pending = null
|
||||
busy = false
|
||||
_scopePrompt.value = null
|
||||
settle(prepared.request.token, landed = false)
|
||||
}
|
||||
|
||||
/** End the drop [token], then run the next queued one, if any. */
|
||||
private fun settle(token: Long, landed: Boolean) {
|
||||
_drops.update { it.ended(token, landed) }
|
||||
// Straight on to the next, so busy never reads false between two drops.
|
||||
val next = queue.removeFirstOrNull()
|
||||
if (next != null) {
|
||||
run(next)
|
||||
} else {
|
||||
busy = false
|
||||
movedThisRun = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun skipQueued() {
|
||||
if (queue.isEmpty()) return
|
||||
val skipped = queue.map { it.token }
|
||||
queue.clear()
|
||||
_drops.update { states -> skipped.fold(states) { acc, token -> acc.ended(token, landed = false) } }
|
||||
report(MoveOutcome.Skipped)
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue [outcome] for the chip. While drops run back to back only the first
|
||||
* move is announced, so its Undo stays on offer; every failure gets its own
|
||||
* turn after it, since the grid shows what moved but only the chip says what
|
||||
* didn't. A later write to the announced move's event takes that Undo away,
|
||||
* as putting the event back would undo the later move too.
|
||||
*/
|
||||
private fun report(outcome: MoveOutcome, eventId: Long? = null) {
|
||||
if (outcome is MoveOutcome.Moved) {
|
||||
if (movedThisRun) {
|
||||
dropUndoFor(eventId)
|
||||
return
|
||||
}
|
||||
movedThisRun = true
|
||||
} else if (outcome == (notices.lastOrNull() ?: _outcome.value)) {
|
||||
return
|
||||
}
|
||||
if (_outcome.value == null) _outcome.value = outcome else notices.addLast(outcome)
|
||||
}
|
||||
|
||||
private fun dropUndoFor(eventId: Long?) {
|
||||
fun MoveOutcome.withoutUndo(): MoveOutcome =
|
||||
if (this is MoveOutcome.Moved && undo?.eventId == eventId) copy(undo = null) else this
|
||||
_outcome.value = _outcome.value?.withoutUndo()
|
||||
val rest = notices.map { it.withoutUndo() }
|
||||
notices.clear()
|
||||
notices.addAll(rest)
|
||||
}
|
||||
|
||||
private fun markWritten(eventId: Long, beginMillis: Long?) {
|
||||
written[eventId to beginMillis] = TimeSource.Monotonic.markNow()
|
||||
}
|
||||
|
||||
private fun writtenRecently(eventId: Long, beginMillis: Long): Boolean {
|
||||
written.entries.removeAll { it.value.elapsedNow() > RECENT_WRITE }
|
||||
return (eventId to null) in written || (eventId to beginMillis) in written
|
||||
_abandoned.value += 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a completed move back where it came from. The outcome stands until the
|
||||
* inverse write reports back, so the one chip changes what it says rather
|
||||
* than closing and reopening. False when another write is already running —
|
||||
* the chip hides its action for that window, so this is the backstop. An
|
||||
* undo is a journey of its own: [undoStarted] names its token, and [drops]
|
||||
* reports whether it landed.
|
||||
* the chip hides its action for that window, so this is the backstop.
|
||||
*
|
||||
* [abandoned] ticks once an inverse that *started* fails to land: [undoStarted]
|
||||
* has sent the chip back on its journey by then and nothing else will seat it.
|
||||
* A refusal ticks nothing — it launched no journey of its own, and the counter
|
||||
* is global, so a tick here would release some other drop's held copy before
|
||||
* the grid has drawn it.
|
||||
*/
|
||||
fun undo(undo: MoveUndo): Boolean {
|
||||
if (busy) return false
|
||||
val token = nextMoveToken()
|
||||
_drops.update { it.started(token) }
|
||||
busy = true
|
||||
_undoStarted.value = UndoStart(token, undo.dropToken)
|
||||
markWritten(undo.eventId, null)
|
||||
_undoStarted.value += 1
|
||||
viewModelScope.launch {
|
||||
_outcome.value = try {
|
||||
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
|
||||
@@ -427,43 +311,34 @@ class RescheduleViewModel @Inject constructor(
|
||||
} catch (e: Exception) {
|
||||
MoveOutcome.Failed
|
||||
}
|
||||
settle(token, landed = _outcome.value is MoveOutcome.Undone)
|
||||
// Read off the outcome, the way [write] does — no second copy of the
|
||||
// same fact to drift from it.
|
||||
if (_outcome.value !is MoveOutcome.Undone) _abandoned.value += 1
|
||||
busy = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Clear the outcome once the screen has shown it, bringing on the next one waiting. */
|
||||
/** Clear the outcome once the screen has shown it. */
|
||||
fun consumeOutcome() {
|
||||
_outcome.value = notices.removeFirstOrNull()
|
||||
_outcome.value = null
|
||||
}
|
||||
|
||||
private suspend fun prepare(dropped: MoveRequest): PreparedMove? {
|
||||
val zone = zoneSource.current()
|
||||
private suspend fun prepare(request: MoveRequest): PreparedMove? {
|
||||
val detail = try {
|
||||
repository.eventDetail(dropped.eventId)
|
||||
repository.eventDetail(request.eventId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: NoSuchEventException) {
|
||||
report(MoveOutcome.Gone)
|
||||
_outcome.value = MoveOutcome.Gone
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
report(MoveOutcome.Failed)
|
||||
_outcome.value = MoveOutcome.Failed
|
||||
return null
|
||||
}
|
||||
// The drop carries the times the grid drew, which an earlier write may
|
||||
// have moved on since (#494).
|
||||
val request = if (detail.rrule == null || detail.isException) {
|
||||
followed(dropped, detail, zone)
|
||||
} else if (writtenRecently(dropped.eventId, dropped.beginMillis)) {
|
||||
report(MoveOutcome.Stale)
|
||||
return null
|
||||
} else {
|
||||
dropped
|
||||
}
|
||||
|
||||
// Read fixed-time reminders out, so the move keeps them on their wall clock (#459).
|
||||
val zone = zoneSource.current()
|
||||
val original = detail.toEditForm(request.beginMillis, request.endMillis, zone)
|
||||
.withFixedTimeRemindersRead(settingsPrefs.knownFixedTimeReminders.first(), zone)
|
||||
val shifted = when (val target = request.target) {
|
||||
is MoveTarget.Start -> original.shiftedTo(target.instant, zone)
|
||||
is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone)
|
||||
@@ -475,7 +350,7 @@ class RescheduleViewModel @Inject constructor(
|
||||
// The UNTIL check is deferred to the write, which knows how far the move
|
||||
// reaches and so which date has to clear it.
|
||||
if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
|
||||
report(MoveOutcome.Failed)
|
||||
_outcome.value = MoveOutcome.Failed
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -520,14 +395,14 @@ class RescheduleViewModel @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
/** Write [prepared] in [scope]; true when it landed. */
|
||||
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope): Boolean {
|
||||
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope) {
|
||||
val request = prepared.request
|
||||
if (endsBeforeItStarts(prepared, scope)) {
|
||||
report(MoveOutcome.BlockedSeriesEnd)
|
||||
return false
|
||||
_outcome.value = MoveOutcome.BlockedSeriesEnd
|
||||
_abandoned.value += 1
|
||||
return
|
||||
}
|
||||
val outcome = try {
|
||||
_outcome.value = try {
|
||||
when {
|
||||
!prepared.isRecurring || scope == RecurringWriteScope.AllEvents ->
|
||||
repository.updateEvent(request.eventId, prepared.original, prepared.updated)
|
||||
@@ -562,37 +437,9 @@ class RescheduleViewModel @Inject constructor(
|
||||
} catch (e: Exception) {
|
||||
MoveOutcome.Failed
|
||||
}
|
||||
if (outcome is MoveOutcome.Moved) {
|
||||
markWritten(request.eventId, request.beginMillis.takeIf { scope == RecurringWriteScope.ThisEvent && prepared.isRecurring })
|
||||
}
|
||||
report(outcome, request.eventId)
|
||||
return outcome is MoveOutcome.Moved
|
||||
}
|
||||
|
||||
/**
|
||||
* A one-off [dropped] rebased onto where its event now is, so the last drop
|
||||
* wins: absolute targets stand as they are, and a whole-day shift is re-aimed
|
||||
* at the day it was dropped on. Unchanged when the event hasn't moved.
|
||||
*/
|
||||
private fun followed(dropped: MoveRequest, detail: EventDetail, zone: TimeZone): MoveRequest {
|
||||
val now = detail.instance
|
||||
val target = when (val target = dropped.target) {
|
||||
is MoveTarget.ByDays -> {
|
||||
// Each day read the way its own kind anchors it: all-day at UTC.
|
||||
val aimed = Instant.fromEpochMilliseconds(dropped.beginMillis)
|
||||
.toLocalDateTime(if (dropped.isAllDay) TimeZone.UTC else zone).date
|
||||
.plus(target.days, DateTimeUnit.DAY)
|
||||
val from = now.start.toLocalDateTime(if (now.isAllDay) TimeZone.UTC else zone).date
|
||||
MoveTarget.ByDays((aimed.toEpochDays() - from.toEpochDays()).toInt())
|
||||
}
|
||||
else -> target
|
||||
}
|
||||
return dropped.copy(
|
||||
beginMillis = now.start.toEpochMilliseconds(),
|
||||
endMillis = now.end.toEpochMilliseconds(),
|
||||
target = target,
|
||||
isAllDay = now.isAllDay,
|
||||
)
|
||||
// Nothing landed, so the copy the view is holding has nothing to fade
|
||||
// into — let it go now rather than at the end of the settle timeout.
|
||||
if (_outcome.value !is MoveOutcome.Moved) _abandoned.value += 1
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -659,7 +506,6 @@ class RescheduleViewModel @Inject constructor(
|
||||
eventId = prepared.request.eventId,
|
||||
moved = prepared.updated,
|
||||
restored = prepared.original,
|
||||
dropToken = prepared.request.token,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.PriorityHigh
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge
|
||||
|
||||
/** floret's [FloretResultBadge] as a check on success, or an exclamation mark in the error colours. */
|
||||
@Composable
|
||||
fun ResultBadge(error: Boolean) {
|
||||
val scheme = MaterialTheme.colorScheme
|
||||
if (error) {
|
||||
FloretResultBadge(Icons.Default.PriorityHigh, scheme.errorContainer, scheme.onErrorContainer)
|
||||
} else {
|
||||
FloretResultBadge(Icons.Default.Check, scheme.primaryContainer, scheme.onPrimaryContainer)
|
||||
}
|
||||
}
|
||||
|
||||
/** A result screen's headline under its badge, then its notes; an error note takes the error colour. */
|
||||
@Composable
|
||||
fun ResultMessage(title: String, notes: List<ResultNote> = emptyList()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
notes.forEach { note ->
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
note.text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (note.error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
data class ResultNote(val text: String, val error: Boolean = false)
|
||||
|
||||
/** The notes an import summary carries: failures, skipped duplicates, then [stoppedNote] when part was never tried. */
|
||||
@Composable
|
||||
fun importSummaryNotes(summary: IcsImportSummary, stoppedNote: String?): List<ResultNote> = buildList {
|
||||
if (summary.failed > 0) add(ResultNote(stringResource(R.string.import_done_failed_note)))
|
||||
if (summary.skippedDuplicate > 0) add(ResultNote(stringResource(R.string.import_done_dedup_note)))
|
||||
if (stoppedNote != null) add(ResultNote(stoppedNote, error = true))
|
||||
}
|
||||
|
||||
/** Added / skipped / failed as big-number tiles, the latter two only when non-zero. */
|
||||
@Composable
|
||||
fun ImportSummaryStats(summary: IcsImportSummary, modifier: Modifier = Modifier) {
|
||||
Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
ResultStatCard(
|
||||
count = summary.imported,
|
||||
label = stringResource(R.string.import_done_added_label),
|
||||
contentDescription = pluralStringResource(R.plurals.import_done_imported, summary.imported, summary.imported),
|
||||
container = MaterialTheme.colorScheme.secondaryContainer,
|
||||
onContainer = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
if (summary.skippedDuplicate > 0) {
|
||||
ResultStatCard(
|
||||
count = summary.skippedDuplicate,
|
||||
label = stringResource(R.string.import_done_skipped_label),
|
||||
contentDescription = pluralStringResource(
|
||||
R.plurals.import_done_skipped,
|
||||
summary.skippedDuplicate,
|
||||
summary.skippedDuplicate,
|
||||
),
|
||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
onContainer = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (summary.failed > 0) {
|
||||
ResultStatCard(
|
||||
count = summary.failed,
|
||||
label = stringResource(R.string.import_done_failed_label),
|
||||
contentDescription = pluralStringResource(R.plurals.import_done_failed, summary.failed, summary.failed),
|
||||
container = MaterialTheme.colorScheme.errorContainer,
|
||||
onContainer = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A big-number tonal tile summarising one outcome. */
|
||||
@Composable
|
||||
private fun RowScope.ResultStatCard(
|
||||
count: Int,
|
||||
label: String,
|
||||
contentDescription: String,
|
||||
container: Color,
|
||||
onContainer: Color,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clearAndSetSemantics { this.contentDescription = contentDescription },
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = container,
|
||||
) {
|
||||
Column(
|
||||
Modifier.padding(vertical = 20.dp, horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Text(count.toString(), style = MaterialTheme.typography.displaySmall, color = onContainer)
|
||||
Text(label, style = MaterialTheme.typography.labelLarge, color = onContainer.copy(alpha = 0.85f))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.MutableState
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.util.Log
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.DrawerState
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.LoadingIndicator
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.DrawerValue
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* Launches the system account picker for an account sync requests can't reach
|
||||
* yet (#240), one launch at a time. Access is re-read on every resume, which covers
|
||||
* the picker's return and grants or revokes made in system settings.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSyncAccessPicker(sync: SyncViewModel): (SyncAccount) -> Unit {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
open = false
|
||||
}
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() }
|
||||
val description = stringResource(R.string.sync_access_picker_description)
|
||||
return remember(launcher, description) {
|
||||
{ account ->
|
||||
if (!open) {
|
||||
try {
|
||||
launcher.launch(accountAccessIntent(account, description))
|
||||
open = true
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Log.w("SyncAccessPicker", "No account picker", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads account access whenever [drawerState] opens; the app may stay resumed in multi-window. */
|
||||
@Composable
|
||||
fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) {
|
||||
LaunchedEffect(drawerState.targetValue) {
|
||||
if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes "Sync now"'s outcome (#240): one that lands while the drawer is open
|
||||
* shows in its row and is dropped when the drawer closes; one that lands while
|
||||
* it is closed is handed to the returned state, for the chip.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSyncChipOutcome(drawerState: DrawerState, sync: SyncViewModel): MutableState<SyncRequestResult?> {
|
||||
val chip = rememberSaveable { mutableStateOf<SyncRequestResult?>(null) }
|
||||
LaunchedEffect(drawerState, sync) {
|
||||
var shownInRow = false
|
||||
combine(sync.result, snapshotFlow { drawerState.targetValue == DrawerValue.Closed }) { result, closed ->
|
||||
result to closed
|
||||
}.collect { (result, closed) ->
|
||||
when {
|
||||
result == null -> shownInRow = false
|
||||
!closed -> shownInRow = true
|
||||
else -> {
|
||||
if (!shownInRow) chip.value = result
|
||||
shownInRow = false
|
||||
sync.consumeResult()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return chip
|
||||
}
|
||||
|
||||
/**
|
||||
* The accounts sync requests can't reach yet (#240), one row each: tapping one
|
||||
* opens the system picker for just that account, "Don't ask" stops offering it.
|
||||
* Closes itself once no account is left.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
fun SyncAccessSheet(
|
||||
accounts: List<SyncAccount>?,
|
||||
onGrant: (SyncAccount) -> Unit,
|
||||
onDismissAccount: (SyncAccount) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
LaunchedEffect(accounts?.isEmpty()) { if (accounts?.isEmpty() == true) onDismiss() }
|
||||
FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) {
|
||||
GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp)
|
||||
if (accounts == null) {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { LoadingIndicator() }
|
||||
}
|
||||
accounts.orEmpty().forEachIndexed { index, account ->
|
||||
SyncAccountRow(
|
||||
account = account,
|
||||
position = positionOf(index, accounts.orEmpty().size),
|
||||
actionLabel = stringResource(R.string.sync_access_dont_ask),
|
||||
onAction = { onDismissAccount(account) },
|
||||
onClick = { onGrant(account) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One synced account with a text action, as the access sheet and the calendar manager list them. */
|
||||
@Composable
|
||||
fun SyncAccountRow(
|
||||
account: SyncAccount,
|
||||
position: Position,
|
||||
actionLabel: String,
|
||||
onAction: () -> Unit,
|
||||
onClick: (() -> Unit)? = null,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = account.name,
|
||||
summary = sourceAppName(account.type),
|
||||
position = position,
|
||||
minHeight = 64.dp,
|
||||
leading = { SourceLogo(account.type) },
|
||||
trailing = { TextButton(onClick = onAction) { Text(actionLabel) } },
|
||||
onClick = onClick,
|
||||
)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncTargets
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncWait
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* The drawer's "Sync now" (#240): asks the sync adapters of every visible synced
|
||||
* calendar to run now, then follows them through the system's sync state.
|
||||
* [inFlight] holds until every reached account has synced or the wait gives up;
|
||||
* [result] then says [SyncRequestResult.Completed] only when that was seen.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class SyncViewModel @Inject constructor(
|
||||
private val repository: CalendarRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
/** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */
|
||||
val targets: StateFlow<SyncTargets?> = repository.syncTargets
|
||||
// A failed read hides the rows for now, then reads again rather than for good.
|
||||
.retryWhen { e, attempt ->
|
||||
if (e is CancellationException) return@retryWhen false
|
||||
emit(SyncTargets.None)
|
||||
delay((RETRY_BASE_MILLIS shl attempt.coerceAtMost(5).toInt()).coerceAtMost(RETRY_MAX_MILLIS))
|
||||
true
|
||||
}
|
||||
.stateWhileSubscribed(scope = viewModelScope, initialValue = null)
|
||||
|
||||
/** Re-read account access: on resume (which includes the picker returning) and drawer open. */
|
||||
fun refreshAccess() = repository.refreshSyncAccess()
|
||||
|
||||
private val _inFlight = MutableStateFlow(false)
|
||||
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
||||
|
||||
private val _result = MutableStateFlow<SyncRequestResult?>(null)
|
||||
|
||||
/** The last request's outcome, until [consumeResult]. */
|
||||
val result: StateFlow<SyncRequestResult?> = _result.asStateFlow()
|
||||
|
||||
fun requestSync() {
|
||||
if (_inFlight.value) return
|
||||
_inFlight.value = true
|
||||
_result.value = null
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val request = repository.requestSync()
|
||||
val waited = if (request.accounts.isEmpty()) null else repository.awaitSyncs(request.accounts)
|
||||
_result.value = if (waited == SyncWait.Completed && request.result == SyncRequestResult.Requested) {
|
||||
SyncRequestResult.Completed
|
||||
} else {
|
||||
request.result
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync now failed", e)
|
||||
_result.value = SyncRequestResult.Failed
|
||||
} finally {
|
||||
_inFlight.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop asking for [account]'s access (#240); undone from the calendar manager. */
|
||||
fun dismissAccess(account: SyncAccount) {
|
||||
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = true) }
|
||||
}
|
||||
|
||||
fun consumeResult() {
|
||||
_result.value = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RETRY_BASE_MILLIS = 1_000L
|
||||
const val RETRY_MAX_MILLIS = 30_000L
|
||||
const val TAG = "SyncViewModel"
|
||||
}
|
||||
}
|
||||
|
||||
/** The text for a sync request's outcome, in the drawer row or the chip. */
|
||||
@StringRes
|
||||
fun SyncRequestResult.messageRes(): Int = when (this) {
|
||||
SyncRequestResult.Requested -> R.string.sync_requested
|
||||
SyncRequestResult.Completed -> R.string.sync_completed
|
||||
SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed
|
||||
SyncRequestResult.NeedsAccess -> R.string.sync_request_needs_access
|
||||
SyncRequestResult.SomeNeedAccess -> R.string.sync_request_some_need_access
|
||||
SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync
|
||||
SyncRequestResult.Failed -> R.string.sync_request_failed
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -61,6 +60,7 @@ import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.datetime.DateTimeUnit
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.atStartOfDayIn
|
||||
@@ -139,17 +139,9 @@ data class StripDrag(val event: EventInstance, val dayShift: Int = 0, val overGr
|
||||
sealed interface StripDrop {
|
||||
val event: EventInstance
|
||||
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long
|
||||
data class Days(override val event: EventInstance, val days: Int) : StripDrop
|
||||
|
||||
data class Days(override val event: EventInstance, val days: Int, override val token: Long) : StripDrop
|
||||
|
||||
data class Timed(
|
||||
override val event: EventInstance,
|
||||
val start: Instant,
|
||||
val end: Instant,
|
||||
override val token: Long,
|
||||
) : StripDrop
|
||||
data class Timed(override val event: EventInstance, val start: Instant, val end: Instant) : StripDrop
|
||||
}
|
||||
|
||||
/** The event a long press left selected (#141). */
|
||||
@@ -305,9 +297,7 @@ data class TimelineDrop(
|
||||
val date: LocalDate,
|
||||
val startMin: Int,
|
||||
/** Minutes from the event's start to the dragged block's top edge. */
|
||||
val clipOffsetMin: Int,
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long,
|
||||
val clipOffsetMin: Int = 0,
|
||||
)
|
||||
|
||||
/** The id a drafted block's stand-in event carries, which no provider row has (#153). */
|
||||
@@ -350,37 +340,8 @@ internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone):
|
||||
/** Which end of an event a resize handle moves (#141). */
|
||||
enum class ResizeEdge { Top, Bottom }
|
||||
|
||||
/** A drop parked by a newer pickup while its write still runs — see [TimelineDragController.held]. */
|
||||
data class HeldDrop(
|
||||
val copy: TimelineDrag,
|
||||
val token: Long,
|
||||
val instanceId: Long,
|
||||
/** The event row and start the drop came from, as [TimelineDragController.ghosts] matches them. */
|
||||
val origin: Pair<Long, Instant>,
|
||||
/** A resize's new end, which has to have landed too before the drop counts as seated. */
|
||||
val end: Instant?,
|
||||
/** Whether the grid now draws the drop at its landing slot. */
|
||||
val seated: Boolean = false,
|
||||
val handedOver: Boolean = false,
|
||||
) {
|
||||
fun ghosts(block: TimedBlock): Boolean = block.event.instanceId == instanceId ||
|
||||
(block.event.eventId == origin.first && block.event.start == origin.second)
|
||||
}
|
||||
|
||||
/** A strip drop parked by a newer one while its write still runs — see [TimelineDragController.heldStrips]. */
|
||||
data class HeldStrip(val drag: StripDrag, val token: Long, val seated: Boolean = false)
|
||||
|
||||
/** An event's new start and end, as a resize leaves them. */
|
||||
data class ResizedSpan(val start: Instant, val end: Instant)
|
||||
|
||||
/** Where a finished resize asks its event to begin and end. */
|
||||
data class TimelineResizeDrop(
|
||||
val event: EventInstance,
|
||||
val start: Instant,
|
||||
val end: Instant,
|
||||
/** The drop's identity, which its held copy waits on. */
|
||||
val token: Long,
|
||||
)
|
||||
data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val end: Instant)
|
||||
|
||||
/**
|
||||
* [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s
|
||||
@@ -391,16 +352,17 @@ data class TimelineResizeDrop(
|
||||
* it was drawn (see [repicked]). An end takes a pass the grid draws at the drop
|
||||
* point, so the block settles under the finger.
|
||||
*/
|
||||
internal fun resizedSpan(
|
||||
internal fun resizedDrop(
|
||||
event: EventInstance,
|
||||
edge: ResizeEdge?,
|
||||
date: LocalDate,
|
||||
startMin: Int,
|
||||
spanMin: Int,
|
||||
zone: TimeZone,
|
||||
): ResizedSpan {
|
||||
): TimelineResizeDrop {
|
||||
val drawn = wallClockSpan(event, zone)
|
||||
return ResizedSpan(
|
||||
return TimelineResizeDrop(
|
||||
event = event,
|
||||
start = if (edge == ResizeEdge.Top) {
|
||||
event.start.toFormTime(zone).repicked(
|
||||
wallClockTime(date, startMin),
|
||||
@@ -551,14 +513,6 @@ class TimelineDragController {
|
||||
*/
|
||||
private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null)
|
||||
|
||||
/**
|
||||
* Earlier drops still being written when another block was picked up. They
|
||||
* keep their copy and their ghost until their own token settles, rather than
|
||||
* vanishing and flashing back at the old slot (#494).
|
||||
*/
|
||||
var held: List<HeldDrop> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
/** How long a block drafted on an empty slot starts out, in minutes (#153). */
|
||||
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
|
||||
|
||||
@@ -657,8 +611,14 @@ class TimelineDragController {
|
||||
var settlingSelected: Boolean = false
|
||||
private set
|
||||
|
||||
/** The token of the drop [settling] waits on. */
|
||||
var settledToken: Long = 0L
|
||||
/**
|
||||
* The abandoned-move counter, read at the drop so the mark can't be a
|
||||
* composition behind the tick it is compared against.
|
||||
*/
|
||||
var abandonedTicks: StateFlow<Int>? = null
|
||||
|
||||
/** What [abandonedTicks] stood at when the settling drop was let go. */
|
||||
var settledAbandonedMark: Int = 0
|
||||
private set
|
||||
|
||||
private var source: TimedBlock? = null
|
||||
@@ -701,12 +661,8 @@ class TimelineDragController {
|
||||
var stripSeated: Boolean by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** Strip drops parked by a newer strip drop while their writes still run (#494). */
|
||||
var heldStrips: List<HeldStrip> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
/** The token of the drop [stripSettling] waits on. */
|
||||
var stripToken: Long = 0L
|
||||
/** What [abandonedTicks] stood at when [stripSettling] was let go. */
|
||||
var stripAbandonedMark: Int = 0
|
||||
private set
|
||||
|
||||
/** The shown day the finger picked the strip bar up on. */
|
||||
@@ -731,7 +687,7 @@ class TimelineDragController {
|
||||
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
|
||||
dragKept = zone.repeatedHourOffsetAt(block.event.start)
|
||||
this.titleLines = titleLines
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
liftedInstanceId = block.event.instanceId
|
||||
grab = pointerInRoot - blockInRoot
|
||||
@@ -770,7 +726,7 @@ class TimelineDragController {
|
||||
dragDuration = draftMinutes.minutes
|
||||
dragKept = null
|
||||
titleLines = 1
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
liftedInstanceId = event.instanceId
|
||||
grab = Offset(0f, geometry.hourPx * STRIP_GRAB_MINUTES / 60f)
|
||||
@@ -793,18 +749,16 @@ class TimelineDragController {
|
||||
val zone = dragZone
|
||||
cancel()
|
||||
if (held.overGrid && landed != null && zone != null && !landed.edgeOnly) {
|
||||
val token = settle(landed)
|
||||
val start = dropStartInstant(landed.event, landed.date, landed.startMin, clipOffsetMin = 0, zone)
|
||||
return StripDrop.Timed(held.event, start, start + draftMinutes.minutes, token)
|
||||
settle(landed)
|
||||
val start = TimelineDrop(landed.event, landed.date, landed.startMin).startInstant(zone)
|
||||
return StripDrop.Timed(held.event, start, start + draftMinutes.minutes)
|
||||
}
|
||||
if (held.overGrid || held.dayShift == 0) return null
|
||||
// One still settling keeps its place on the strip until its own write lands (#494).
|
||||
stripSettling?.let { heldStrips = heldStrips + HeldStrip(it, stripToken, stripSeated) }
|
||||
stripSettling = held
|
||||
stripSeated = false
|
||||
stripToken = nextMoveToken()
|
||||
stripAbandonedMark = abandonedTicks?.value ?: 0
|
||||
drops++
|
||||
return StripDrop.Days(held.event, held.dayShift, stripToken)
|
||||
return StripDrop.Days(held.event, held.dayShift)
|
||||
}
|
||||
|
||||
/** Let the held strip drop go, once the strip shows the event at its new days or the move failed. */
|
||||
@@ -818,21 +772,6 @@ class TimelineDragController {
|
||||
if (stripSettling != null) stripSeated = true
|
||||
}
|
||||
|
||||
/** Note that the strip draws the parked strip drop [token] at its new days. */
|
||||
fun seatHeldStrip(token: Long) {
|
||||
if (heldStrips.any { it.token == token && !it.seated }) {
|
||||
heldStrips = heldStrips.map { if (it.token == token) it.copy(seated = true) else it }
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the parked strip drop [token] go. */
|
||||
fun releaseHeldStrip(token: Long) {
|
||||
heldStrips = heldStrips.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/** Every strip drop still shown at its new days: the parked ones, then the latest. */
|
||||
fun stripPreviews(): List<StripDrag> = heldStrips.map { it.drag } + listOfNotNull(stripDrag ?: stripSettling)
|
||||
|
||||
fun move(pointerInRoot: Offset) {
|
||||
pointer = pointerInRoot
|
||||
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
|
||||
@@ -867,36 +806,12 @@ class TimelineDragController {
|
||||
* an event that crosses midnight (#253).
|
||||
*/
|
||||
fun ghosts(block: TimedBlock): Boolean {
|
||||
if (held.any { !it.handedOver && it.ghosts(block) }) return true
|
||||
if (liftedInstanceId == null) return false
|
||||
if (block.event.instanceId == liftedInstanceId) return true
|
||||
val (eventId, start) = settledOrigin ?: return false
|
||||
return block.event.eventId == eventId && block.event.start == start
|
||||
}
|
||||
|
||||
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
|
||||
private fun parkSettling() {
|
||||
val landed = settling
|
||||
val origin = settledOrigin
|
||||
if (landed != null && origin != null && !landed.event.isDraft) {
|
||||
held = held + HeldDrop(landed, settledToken, landed.event.instanceId, origin, settledEnd, settledOnGrid)
|
||||
}
|
||||
settling = null
|
||||
settledOnGrid = false
|
||||
settledOrigin = null
|
||||
settledEnd = null
|
||||
}
|
||||
|
||||
/** Stop ghosting the held drop [token]'s source while its copy fades. */
|
||||
fun handOverHeld(token: Long) {
|
||||
held = held.map { if (it.token == token) it.copy(handedOver = true) else it }
|
||||
}
|
||||
|
||||
/** Drop the held copy [token] once it has faded. */
|
||||
fun releaseHeld(token: Long) {
|
||||
held = held.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/**
|
||||
* What a day column now holds, so a settled drop can tell when the grid has
|
||||
* caught up with it. Matched on the landing slot plus either the event row
|
||||
@@ -904,23 +819,16 @@ class TimelineDragController {
|
||||
* blank title matches nothing: every untitled event has one (#253).
|
||||
*/
|
||||
fun noteGrid(date: LocalDate, blocks: List<TimedBlock>) {
|
||||
if (held.any { !it.seated && drawsDrop(it.copy, it.end, date, blocks) }) {
|
||||
held = held.map { if (!it.seated && drawsDrop(it.copy, it.end, date, blocks)) it.copy(seated = true) else it }
|
||||
}
|
||||
val landed = settling ?: return
|
||||
if (settledOnGrid) return
|
||||
settledOnGrid = drawsDrop(landed, settledEnd, date, blocks)
|
||||
}
|
||||
|
||||
/** Whether [blocks], [date]'s column, draws the drop [landed] where it landed. */
|
||||
private fun drawsDrop(landed: TimelineDrag, end: Instant?, date: LocalDate, blocks: List<TimedBlock>): Boolean {
|
||||
// Where this day would draw it, which for a drop clipped at midnight is
|
||||
// the day's own start rather than the edge the finger held (#253) — and
|
||||
// which for a tail dragged clear of its day is the day before it.
|
||||
val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt()
|
||||
val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset)
|
||||
.firstOrNull() ?: return false
|
||||
return blocks.any { block ->
|
||||
.firstOrNull() ?: return
|
||||
val end = settledEnd
|
||||
settledOnGrid = blocks.any { block ->
|
||||
block.startMin == slice.startMin &&
|
||||
// A resize may keep its start, so its end has to have landed too.
|
||||
(end == null || block.event.end == end) &&
|
||||
@@ -947,15 +855,12 @@ class TimelineDragController {
|
||||
if (landed == null || landed.slot == origin) return null
|
||||
// A draft dropped on a day off screen would vanish, so it stays where it was (#153).
|
||||
if (landed.edgeOnly && landed.event.isDraft) return null
|
||||
val token = settle(landed)
|
||||
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset, token)
|
||||
settle(landed)
|
||||
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset)
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep [landed]'s copy on the target as [settling] until [release]; [end] is a
|
||||
* resize's. Returns the drop's fresh token.
|
||||
*/
|
||||
private fun settle(landed: TimelineDrag, end: Instant? = null): Long {
|
||||
/** Keep [landed]'s copy on the target as [settling] until [release]; [end] is a resize's. */
|
||||
private fun settle(landed: TimelineDrag, end: Instant? = null) {
|
||||
// Landed on midnight to midnight, the event moves to the all-day strip (#296).
|
||||
val leavesGrid = !landed.event.isDraft && landed.eventSpanMin > 0 &&
|
||||
landed.eventStartMin.mod(MINUTES_PER_DAY) == 0 &&
|
||||
@@ -968,10 +873,9 @@ class TimelineDragController {
|
||||
settling = if (landed.edgeOnly || leavesGrid) landed.copy(pieces = emptyList()) else landed
|
||||
liftedInstanceId = landed.event.instanceId
|
||||
settledOrigin = landed.event.eventId to landed.event.start
|
||||
settledToken = nextMoveToken()
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
settledEnd = end
|
||||
drops++
|
||||
return settledToken
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -991,7 +895,7 @@ class TimelineDragController {
|
||||
resize = session
|
||||
clipOffsetMin = 0
|
||||
this.titleLines = titleLines
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
pointerMoved = true
|
||||
liftedInstanceId = block.event.instanceId
|
||||
@@ -1022,10 +926,10 @@ class TimelineDragController {
|
||||
val event = source?.event ?: return null
|
||||
val edge = resize?.edge
|
||||
if (edge != null) {
|
||||
val drop = resizedSpan(event, edge, date, startMin, spanMin, zone)
|
||||
val drop = resizedDrop(event, edge, date, startMin, spanMin, zone)
|
||||
return event.copy(start = drop.start, end = drop.end)
|
||||
}
|
||||
val start = dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||
val start = TimelineDrop(event, date, startMin, clipOffsetMin).startInstant(zone)
|
||||
return event.copy(start = start, end = start + dragDuration)
|
||||
}
|
||||
|
||||
@@ -1039,8 +943,9 @@ class TimelineDragController {
|
||||
val edge = resize?.edge
|
||||
cancel()
|
||||
if (landed == null || landed.slot == origin) return null
|
||||
val span = resizedSpan(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
||||
return TimelineResizeDrop(landed.event, span.start, span.end, settle(landed, end = span.end))
|
||||
val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
||||
settle(landed, end = drop.end)
|
||||
return drop
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1294,6 +1199,7 @@ fun rememberTimelineDragController(): TimelineDragController {
|
||||
controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() }
|
||||
controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() }
|
||||
controller.slopPx = LocalViewConfiguration.current.touchSlop
|
||||
controller.abandonedTicks = LocalEventMove.current?.abandoned
|
||||
return controller
|
||||
}
|
||||
|
||||
@@ -1323,16 +1229,7 @@ fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
|
||||
* visibly settles there.
|
||||
*/
|
||||
fun TimelineDrop.startInstant(zone: TimeZone): Instant =
|
||||
dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||
|
||||
/** Where [event] starts when its block's top edge lands [startMin] past [date]'s midnight — see [TimelineDrop]. */
|
||||
internal fun dropStartInstant(
|
||||
event: EventInstance,
|
||||
date: LocalDate,
|
||||
startMin: Int,
|
||||
clipOffsetMin: Int,
|
||||
zone: TimeZone,
|
||||
): Instant = wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
||||
wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
||||
|
||||
/**
|
||||
* The wall-clock minutes an event lasting [duration] covers when it starts
|
||||
@@ -1404,7 +1301,6 @@ private const val SETTLE_TIMEOUT_MILLIS = 900L
|
||||
*/
|
||||
const val SETTLE_FADE_MILLIS: Int = 250
|
||||
|
||||
|
||||
/**
|
||||
* The floating block, drawn over the whole calendar so it is free of the day
|
||||
* column's clip and of the scroll viewport's rounded corners.
|
||||
@@ -1412,10 +1308,12 @@ const val SETTLE_FADE_MILLIS: Int = 250
|
||||
@Composable
|
||||
fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val use24Hour = LocalUse24HourFormat.current
|
||||
val locale = currentLocale()
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val drops = dropStates()
|
||||
val moveInFlight = controller.settledToken in drops.pending
|
||||
val stripInFlight = controller.stripToken in drops.pending
|
||||
val moveInFlight = moveInFlight()
|
||||
|
||||
// Both live here rather than beside the controller: they read [drag], which
|
||||
// changes every frame, and this composable is the one that is meant to.
|
||||
@@ -1429,11 +1327,12 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
// recurring drop's scope dialog is up — and then until the grid draws the
|
||||
// drop itself.
|
||||
var handingOver by remember(controller.settling) { mutableStateOf(false) }
|
||||
val abandoned = controller.settledToken in drops.abandoned
|
||||
val abandoned = abandonedMoves()
|
||||
LaunchedEffect(controller.settling, moveInFlight, controller.settledOnGrid, abandoned) {
|
||||
if (controller.settling == null || moveInFlight) return@LaunchedEffect
|
||||
// An abandoned drop: nothing will land and there is nothing to wait for.
|
||||
if (!abandoned) {
|
||||
// Past the mark this drop was let go on, it was abandoned: nothing will
|
||||
// land and there is nothing to wait for.
|
||||
if (abandoned == controller.settledAbandonedMark) {
|
||||
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||
}
|
||||
handingOver = true
|
||||
@@ -1443,10 +1342,9 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
}
|
||||
|
||||
// The same hold for a bar moved along the all-day strip.
|
||||
val stripAbandoned = controller.stripToken in drops.abandoned
|
||||
LaunchedEffect(controller.stripSettling, stripInFlight, controller.stripSeated, stripAbandoned) {
|
||||
if (controller.stripSettling == null || stripInFlight) return@LaunchedEffect
|
||||
if (!stripAbandoned) {
|
||||
LaunchedEffect(controller.stripSettling, moveInFlight, controller.stripSeated, abandoned) {
|
||||
if (controller.stripSettling == null || moveInFlight) return@LaunchedEffect
|
||||
if (abandoned == controller.stripAbandonedMark) {
|
||||
delay(if (controller.stripSeated) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||
}
|
||||
controller.releaseStrip()
|
||||
@@ -1460,12 +1358,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
.clearAndSetSemantics { }
|
||||
.onGloballyPositioned { origin = it.positionInRoot() },
|
||||
) {
|
||||
controller.held.forEach { parked ->
|
||||
key(parked.token) { HeldTimelineCopy(controller, parked, origin) }
|
||||
}
|
||||
controller.heldStrips.forEach { parked ->
|
||||
key(parked.token) { HeldStripSettle(controller, parked) }
|
||||
}
|
||||
val drag = controller.drag ?: controller.settling ?: return@Box
|
||||
// Landed: the copy sinks back to the grid's own plane while the write runs.
|
||||
val landed = controller.drag == null
|
||||
@@ -1479,58 +1371,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "drag-handover",
|
||||
)
|
||||
TimelineCopy(drag, controller.geometry, origin, lift, copyAlpha)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [TimelineDragController.ghosts] for [block], derived so the block recomposes
|
||||
* only when its own answer changes rather than on every lift, park and release.
|
||||
*/
|
||||
@Composable
|
||||
fun TimelineDragController.ghostsDerived(block: TimedBlock): Boolean {
|
||||
val ghosted by remember(this, block) { derivedStateOf { ghosts(block) } }
|
||||
return ghosted
|
||||
}
|
||||
|
||||
/** A drop parked by a newer pickup: held at its landing slot until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldTimelineCopy(controller: TimelineDragController, parked: HeldDrop, origin: Offset) {
|
||||
val alpha = rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = parked.seated,
|
||||
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = { controller.handOverHeld(parked.token) },
|
||||
onRelease = { controller.releaseHeld(parked.token) },
|
||||
)
|
||||
TimelineCopy(parked.copy, controller.geometry, origin, lift = 0f, copyAlpha = alpha)
|
||||
}
|
||||
|
||||
/** A strip drop parked by a newer one: shown at its new days until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldStripSettle(controller: TimelineDragController, parked: HeldStrip) {
|
||||
rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = parked.seated,
|
||||
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = {},
|
||||
onRelease = { controller.releaseHeldStrip(parked.token) },
|
||||
)
|
||||
}
|
||||
|
||||
/** [drag]'s pieces drawn over the calendar, clipped to the timeline's viewport. */
|
||||
@Composable
|
||||
private fun TimelineCopy(
|
||||
drag: TimelineDrag,
|
||||
geometry: TimelineGeometry,
|
||||
origin: Offset,
|
||||
lift: Float,
|
||||
copyAlpha: Float,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val use24Hour = LocalUse24HourFormat.current
|
||||
val locale = currentLocale()
|
||||
val paint = eventPaint(drag.event, dark)
|
||||
val title = drag.event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||
// Read off the event rather than the held block, so grabbing either half
|
||||
@@ -1546,7 +1386,7 @@ private fun TimelineCopy(
|
||||
// so no column clip or rounded corner cuts it, but it still belongs to
|
||||
// the timeline: a piece a whole day tall reaches far past both ends of
|
||||
// the viewport, and unclipped it paints over the headers above (#267).
|
||||
val port = geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
||||
val port = controller.geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
||||
// How much of each piece the viewport actually shows. A multi-day event
|
||||
// has a piece per day, and the widest one is a full 24 hours — taller
|
||||
// than the screen, its top at a midnight scrolled out of sight. Picking
|
||||
@@ -1598,6 +1438,7 @@ private fun TimelineCopy(
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One piece of a dragged block, floating over the calendar. */
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.common
|
||||
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.domain.withoutCalendars
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.retryWhen
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import java.io.IOException
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** The calendars hidden in [view] under a per-calendar hidden-views map (#270). */
|
||||
fun Map<Long, Set<CalendarView>>.calendarsHiddenIn(view: CalendarView): Set<Long> =
|
||||
filterValues { view in it }.keys
|
||||
|
||||
/**
|
||||
* The calendars hidden in [view], shared by everything one view model shows so
|
||||
* the setting is read once rather than per page. A failed read hides nothing
|
||||
* rather than failing the view; the replay expires with the last subscriber, so
|
||||
* a returning view filters against a fresh read.
|
||||
*/
|
||||
fun Flow<Map<Long, Set<CalendarView>>>.calendarsHiddenIn(
|
||||
view: CalendarView,
|
||||
scope: CoroutineScope,
|
||||
): Flow<Set<Long>> =
|
||||
hidingNothingOnError()
|
||||
.map { it.calendarsHiddenIn(view) }
|
||||
.distinctUntilChanged()
|
||||
// The grace period outlasts a flatMapLatest swap, so paging doesn't re-read it.
|
||||
.shareIn(scope, SharingStarted.WhileSubscribed(5_000, replayExpirationMillis = 0), replay = 1)
|
||||
|
||||
/**
|
||||
* A failed read of the per-view setting hides nothing rather than failing what
|
||||
* shows it, and keeps reading, so the next change still lands.
|
||||
*/
|
||||
fun Flow<Map<Long, Set<CalendarView>>>.hidingNothingOnError(): Flow<Map<Long, Set<CalendarView>>> =
|
||||
retryWhen { cause, attempt ->
|
||||
if (cause !is IOException) return@retryWhen false
|
||||
emit(emptyMap())
|
||||
// Backs off, so a file that keeps failing (corrupt) isn't re-read every second.
|
||||
delay((RETRY_BASE_DELAY_MS shl attempt.coerceAtMost(6).toInt()).coerceAtMost(RETRY_MAX_DELAY_MS))
|
||||
true
|
||||
}
|
||||
|
||||
private const val RETRY_BASE_DELAY_MS = 1_000L
|
||||
private const val RETRY_MAX_DELAY_MS = 60_000L
|
||||
|
||||
/**
|
||||
* [CalendarRepository.instances] as one view shows them: also without the
|
||||
* [hidden] calendars the user keeps out of it. Display only — reminders, search
|
||||
* and widgets read the repository directly.
|
||||
*/
|
||||
fun CalendarRepository.instancesWithout(
|
||||
range: ClosedRange<Instant>,
|
||||
hidden: Flow<Set<Long>>,
|
||||
): Flow<List<EventInstance>> =
|
||||
combine(instances(range), hidden) { instances, ids -> instances.withoutCalendars(ids) }
|
||||
@@ -90,7 +90,6 @@ import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
|
||||
import de.jeanlucmakiola.calendula.domain.zoneDescriptor
|
||||
import de.jeanlucmakiola.calendula.domain.zoneOrNull
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.android.mapsSearchIntents
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||
import de.jeanlucmakiola.floret.identity.predictiveBack
|
||||
@@ -109,7 +108,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||
import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone
|
||||
import de.jeanlucmakiola.calendula.ui.common.recurrenceText
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.TimeZone
|
||||
@@ -534,8 +532,7 @@ private fun EventDetailContent(
|
||||
.sortedBy { it.minutes }
|
||||
.forEach { reminder ->
|
||||
Text(
|
||||
text = state.fixedReminders[reminder.minutes]?.let { fixedTimeReminderLabel(it) }
|
||||
?: reminderLeadTimeLabel(reminder.minutes),
|
||||
text = reminderLeadTimeLabel(reminder.minutes),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(vertical = 2.dp),
|
||||
)
|
||||
@@ -887,6 +884,9 @@ private fun startOrSayNoApp(context: Context, intent: Intent) {
|
||||
|
||||
/** Open a maps intent for [query]; fall back to a web maps URL if no app handles geo:. */
|
||||
private fun openInMaps(context: Context, query: String) {
|
||||
val opened = mapsSearchIntents(query).any { runCatching { context.startActivity(it) }.isSuccess }
|
||||
if (!opened) Toast.makeText(context, R.string.link_open_failed, Toast.LENGTH_SHORT).show()
|
||||
val encoded = Uri.encode(query)
|
||||
val geo = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=$encoded"))
|
||||
if (runCatching { context.startActivity(geo) }.isFailure) {
|
||||
openWebLink(context, "https://www.google.com/maps/search/?api=1&query=$encoded")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.detail
|
||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.RichText
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
|
||||
/**
|
||||
* UI state for the event-detail screen (spec S4).
|
||||
@@ -27,10 +26,6 @@ sealed interface EventDetailUiState {
|
||||
val phoneLinks: EventPhoneLinks = EventPhoneLinks(),
|
||||
/** The description as drawn — HTML rendered (#271); null when there is none. */
|
||||
val description: RichText? = null,
|
||||
/** Reminder offsets that read as "N days before at HH:MM" (#459), by raw minutes. */
|
||||
val fixedReminders: Map<Int, FixedTimeReminder> = emptyMap(),
|
||||
/** The fixed-time patterns the reminders were read against. */
|
||||
val knownFixed: Set<FixedTimeReminder> = emptySet(),
|
||||
) : EventDetailUiState
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.jeanlucmakiola.calendula.ui.detail
|
||||
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.classifyTimedReminder
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -48,7 +46,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
private val icsExporter: IcsExporter,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
private val zoneSource: ZoneSource,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _target = MutableStateFlow<Target?>(null)
|
||||
@@ -145,7 +142,7 @@ class EventDetailViewModel @Inject constructor(
|
||||
*/
|
||||
fun duplicateForm(): EventForm? {
|
||||
val loaded = state.value as? EventDetailUiState.Success ?: return null
|
||||
return loaded.detail.toDuplicateForm(zoneSource.current(), loaded.knownFixed)
|
||||
return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current())
|
||||
}
|
||||
|
||||
private suspend fun loadDetail(target: Target): EventDetailUiState = try {
|
||||
@@ -160,17 +157,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
}
|
||||
val calendar = repository.calendars().first()
|
||||
.firstOrNull { it.id == corrected.instance.calendarId }
|
||||
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
|
||||
val fixedReminders = if (corrected.instance.isAllDay) {
|
||||
emptyMap()
|
||||
} else {
|
||||
val zone = zoneSource.current()
|
||||
corrected.reminders.map { it.minutes }.distinct().mapNotNull { minutes ->
|
||||
classifyTimedReminder(
|
||||
minutes, corrected.instance.start, zone, knownFixed, wallClock = corrected.rrule != null,
|
||||
)?.let { minutes to it }
|
||||
}.toMap()
|
||||
}
|
||||
val description = corrected.description
|
||||
?.let(::descriptionRichText)
|
||||
?.takeIf { it.text.isNotBlank() }
|
||||
@@ -187,8 +173,6 @@ class EventDetailViewModel @Inject constructor(
|
||||
description = description?.text,
|
||||
),
|
||||
description = description,
|
||||
fixedReminders = fixedReminders,
|
||||
knownFixed = knownFixed,
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -125,10 +125,6 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.EventAttendee
|
||||
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.ui.common.DEFAULT_FIXED_TIME_REMINDER
|
||||
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderEditor
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.domain.startInstant
|
||||
import de.jeanlucmakiola.calendula.domain.endInstant
|
||||
import de.jeanlucmakiola.calendula.domain.resolvedZone
|
||||
@@ -157,7 +153,6 @@ import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventAccent
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFill
|
||||
import de.jeanlucmakiola.floret.components.DialogAmountField
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.DialogUnitDropdown
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldIcon
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel
|
||||
@@ -170,12 +165,9 @@ import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.groupedShape as floretGroupedShape
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.calendula.ui.common.reminderPresets
|
||||
import de.jeanlucmakiola.calendula.ui.common.customReminderUnits
|
||||
import de.jeanlucmakiola.calendula.ui.common.customReminderPlaceholder
|
||||
import de.jeanlucmakiola.calendula.ui.common.splitsSubDay
|
||||
import de.jeanlucmakiola.calendula.ui.common.GroupedLeadTimeRows
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderUnit
|
||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||
import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay
|
||||
@@ -882,10 +874,8 @@ private fun EventEditContent(
|
||||
OptionalFormSection(visible = EventFormField.Reminders in state.visibleFields) {
|
||||
Spacer(Modifier.height(gap))
|
||||
RemindersSection(
|
||||
reminders = form.firingReminders(),
|
||||
fixedReminders = if (form.isAllDay) emptyList() else form.fixedReminders,
|
||||
reminders = form.reminders,
|
||||
onRemove = viewModel::removeReminder,
|
||||
onRemoveFixed = viewModel::removeFixedReminder,
|
||||
onAdd = { sheet = EditSheet.Reminder },
|
||||
)
|
||||
}
|
||||
@@ -1294,25 +1284,9 @@ private fun LocationCard(
|
||||
* connected corners, the last row being "Add reminder".
|
||||
*/
|
||||
@Composable
|
||||
private fun RemindersSection(
|
||||
reminders: List<Int>,
|
||||
fixedReminders: List<FixedTimeReminder>,
|
||||
onRemove: (Int) -> Unit,
|
||||
onRemoveFixed: (FixedTimeReminder) -> Unit,
|
||||
onAdd: () -> Unit,
|
||||
) {
|
||||
val rows = fixedReminders.size + reminders.size + 1
|
||||
fixedReminders.forEachIndexed { index, reminder ->
|
||||
GroupedItemCard(
|
||||
position = positionOf(index, rows),
|
||||
icon = Icons.Default.Notifications,
|
||||
title = fixedTimeReminderLabel(reminder),
|
||||
removeContentDescription = stringResource(R.string.event_edit_remove_reminder),
|
||||
onRemove = { onRemoveFixed(reminder) },
|
||||
)
|
||||
}
|
||||
reminders.forEachIndexed { i, minutes ->
|
||||
val index = fixedReminders.size + i
|
||||
private fun RemindersSection(reminders: List<Int>, onRemove: (Int) -> Unit, onAdd: () -> Unit) {
|
||||
val rows = reminders.size + 1
|
||||
reminders.forEachIndexed { index, minutes ->
|
||||
GroupedItemCard(
|
||||
position = positionOf(index, rows),
|
||||
icon = Icons.Default.Notifications,
|
||||
@@ -1323,7 +1297,7 @@ private fun RemindersSection(
|
||||
}
|
||||
AddActionCard(
|
||||
label = stringResource(R.string.event_edit_add_reminder),
|
||||
position = positionOf(rows - 1, rows),
|
||||
position = positionOf(reminders.size, rows),
|
||||
onClick = onAdd,
|
||||
)
|
||||
}
|
||||
@@ -1514,17 +1488,11 @@ private fun EditSheetHost(
|
||||
)
|
||||
}
|
||||
EditSheet.Reminder -> ReminderPickerDialog(
|
||||
isAllDay = form.isAllDay,
|
||||
alreadyChosen = form.firingReminders(),
|
||||
offerFixedTime = !form.isAllDay,
|
||||
alreadyChosen = form.reminders,
|
||||
onSelect = { minutes ->
|
||||
viewModel.addReminder(minutes)
|
||||
onClose()
|
||||
},
|
||||
onSelectFixed = { reminder ->
|
||||
viewModel.addFixedReminder(reminder)
|
||||
onClose()
|
||||
},
|
||||
onDismiss = onClose,
|
||||
)
|
||||
EditSheet.Recurrence -> RecurrencePickerDialog(
|
||||
@@ -1612,20 +1580,13 @@ private fun FieldPickerDialog(
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ReminderPickerDialog(
|
||||
isAllDay: Boolean,
|
||||
alreadyChosen: List<Int>,
|
||||
offerFixedTime: Boolean,
|
||||
onSelect: (Int) -> Unit,
|
||||
onSelectFixed: (FixedTimeReminder) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var customMode by rememberSaveable { mutableStateOf(false) }
|
||||
var fixedMode by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingFixed by remember { mutableStateOf<FixedTimeReminder?>(null) }
|
||||
var amountText by rememberSaveable { mutableStateOf("") }
|
||||
val units = customReminderUnits(isAllDay)
|
||||
var pickedUnit by rememberSaveable { mutableStateOf(units.first()) }
|
||||
val unit = pickedUnit.takeIf { it in units } ?: units.first()
|
||||
var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) }
|
||||
val customMinutes = amountText.toIntOrNull()
|
||||
?.takeIf { it in 1..999 }
|
||||
?.let { it * unit.minutesFactor }
|
||||
@@ -1634,55 +1595,29 @@ private fun ReminderPickerDialog(
|
||||
title = stringResource(R.string.event_edit_add_reminder),
|
||||
onDismiss = onDismiss,
|
||||
actions = {
|
||||
// The quick-pick list adds on tap; only the custom steps need Add.
|
||||
// The quick-pick list adds on tap; only the custom step needs Add.
|
||||
if (customMode) {
|
||||
TextButton(
|
||||
enabled = customMinutes != null && customMinutes !in alreadyChosen,
|
||||
onClick = { customMinutes?.let(onSelect) },
|
||||
) { Text(stringResource(R.string.event_edit_add)) }
|
||||
} else if (fixedMode) {
|
||||
TextButton(
|
||||
enabled = pendingFixed != null,
|
||||
onClick = { pendingFixed?.let(onSelectFixed) },
|
||||
) { Text(stringResource(R.string.event_edit_add)) }
|
||||
}
|
||||
},
|
||||
) {
|
||||
if (fixedMode) {
|
||||
GroupedHint(text = stringResource(R.string.event_edit_reminder_fixed_hint))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
FixedTimeReminderEditor(
|
||||
initial = DEFAULT_FIXED_TIME_REMINDER,
|
||||
onValueChange = { pendingFixed = it },
|
||||
connected = false,
|
||||
)
|
||||
} else if (!customMode) {
|
||||
val presets = reminderPresets(isAllDay)
|
||||
GroupedLeadTimeRows(
|
||||
minutes = presets.filterNot { it in alreadyChosen },
|
||||
splitSubDay = splitsSubDay(presets),
|
||||
row = { minutes, position ->
|
||||
GroupedRow(
|
||||
title = reminderLeadTimeLabel(minutes),
|
||||
position = position,
|
||||
onClick = { onSelect(minutes) },
|
||||
)
|
||||
},
|
||||
trailing = { position ->
|
||||
if (offerFixedTime) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_fixed_at_set_time),
|
||||
summary = stringResource(R.string.event_edit_reminder_fixed_summary),
|
||||
position = if (position == Position.Alone) Position.Top else Position.Middle,
|
||||
onClick = { fixedMode = true },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.event_edit_reminder_custom),
|
||||
position = if (offerFixedTime) Position.Bottom else position,
|
||||
onClick = { customMode = true },
|
||||
)
|
||||
},
|
||||
if (!customMode) {
|
||||
val presets = REMINDER_PRESETS.filterNot { it in alreadyChosen }
|
||||
val rowCount = presets.size + 1
|
||||
presets.forEachIndexed { index, minutes ->
|
||||
GroupedRow(
|
||||
title = reminderLeadTimeLabel(minutes),
|
||||
position = positionOf(index, rowCount),
|
||||
onClick = { onSelect(minutes) },
|
||||
)
|
||||
}
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.event_edit_reminder_custom),
|
||||
position = positionOf(rowCount - 1, rowCount),
|
||||
onClick = { customMode = true },
|
||||
)
|
||||
} else {
|
||||
Row(
|
||||
@@ -1692,13 +1627,13 @@ private fun ReminderPickerDialog(
|
||||
DialogAmountField(
|
||||
value = amountText,
|
||||
onValueChange = { amountText = it },
|
||||
placeholder = customReminderPlaceholder(unit),
|
||||
placeholder = "10",
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
DialogUnitDropdown(
|
||||
label = stringResource(reminderUnitLabel(unit)),
|
||||
entries = units.map { stringResource(reminderUnitLabel(it)) },
|
||||
onPick = { pickedUnit = units[it] },
|
||||
entries = ReminderUnit.entries.map { stringResource(reminderUnitLabel(it)) },
|
||||
onPick = { unit = ReminderUnit.entries[it] },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
* form means the screen hasn't been opened yet.
|
||||
*/
|
||||
data class EventEditUiState(
|
||||
/** The form with its calendar id resolved, see [de.jeanlucmakiola.calendula.domain.resolveEventCalendar]. */
|
||||
/** The form with its calendar id resolved (picked > last used > first writable). */
|
||||
val form: EventForm,
|
||||
/** Calendars that accept writes — the only valid targets. */
|
||||
val calendars: List<CalendarSource>,
|
||||
|
||||
@@ -7,20 +7,13 @@ import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
|
||||
import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadMinutes
|
||||
import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadTimes
|
||||
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultFixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FIXED_ORDER
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||
import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets
|
||||
import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead
|
||||
import de.jeanlucmakiola.calendula.domain.canSaveApartFromSeries
|
||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||
import de.jeanlucmakiola.calendula.domain.Availability
|
||||
@@ -40,8 +33,6 @@ import de.jeanlucmakiola.calendula.domain.withStart
|
||||
import de.jeanlucmakiola.calendula.domain.withTimes
|
||||
import de.jeanlucmakiola.calendula.domain.withTimezone
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.NewEventCalendarHints
|
||||
import de.jeanlucmakiola.calendula.domain.resolveEventCalendar
|
||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
||||
import de.jeanlucmakiola.calendula.domain.isEventTarget
|
||||
@@ -148,13 +139,12 @@ enum class ImportSource(internal val ownsDuration: Boolean) {
|
||||
data class ImportReminderPrompt(
|
||||
val currentReminderCount: Int,
|
||||
val defaultReminders: List<Int>,
|
||||
val defaultFixedReminders: List<FixedTimeReminder> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Holds the event form being composed. The form's calendar id resolves through
|
||||
* [resolveEventCalendar] (user pick > requested > default > last used > first
|
||||
* target); the resolved value is what the UI shows and what gets saved.
|
||||
* Holds the event form being composed. The form's calendar id resolves to
|
||||
* (user pick > last used > first writable); the resolved value is what the UI
|
||||
* shows and what gets saved.
|
||||
*/
|
||||
@HiltViewModel
|
||||
class EventEditViewModel @Inject constructor(
|
||||
@@ -191,9 +181,6 @@ class EventEditViewModel @Inject constructor(
|
||||
// A one-time offer, raised when a .ics import opens, to replace the file's
|
||||
// reminders with the settings default (#49). Null while there's nothing to ask.
|
||||
private val _importReminderPrompt = MutableStateFlow<ImportReminderPrompt?>(null)
|
||||
// A calendar named by an insert intent or a duplicate's source (#429); wins
|
||||
// over the default calendar while it is an event target.
|
||||
private val _requestedCalendarId = MutableStateFlow<Long?>(null)
|
||||
// The form as the user received it: the loaded event, or a new form with its
|
||||
// prefill and auto-applied defaults. Anything else is an unsaved change.
|
||||
private val _baseline = MutableStateFlow<EventForm?>(null)
|
||||
@@ -221,8 +208,6 @@ class EventEditViewModel @Inject constructor(
|
||||
val zone: TimeZone,
|
||||
/** The event as loaded, on the tapped occurrence's times — what Share exports. */
|
||||
val detail: EventDetail,
|
||||
/** The fixed-time patterns its reminders were read against, so a re-read splits alike. */
|
||||
val knownFixed: Set<FixedTimeReminder>,
|
||||
) {
|
||||
val original: EventForm get() = snapshot.form
|
||||
}
|
||||
@@ -240,13 +225,7 @@ class EventEditViewModel @Inject constructor(
|
||||
val allDay: List<Int>,
|
||||
val timedOverrides: Map<Long, List<Int>>,
|
||||
val allDayOverrides: Map<Long, List<Int>>,
|
||||
val fixed: FixedTimeReminder?,
|
||||
val fixedOverrides: Map<Long, FixedTimeReminder?>,
|
||||
) {
|
||||
/** The fixed-time reminders a new event on [calendarId] gets (#459); none on an all-day one. */
|
||||
fun resolveFixedFor(calendarId: Long?, isAllDay: Boolean): List<FixedTimeReminder> =
|
||||
if (isAllDay) emptyList() else listOfNotNull(resolveDefaultFixedTimeReminder(fixed, fixedOverrides, calendarId))
|
||||
|
||||
/** The default reminders for an event on [calendarId] of the given kind. */
|
||||
fun resolveFor(calendarId: Long?, isAllDay: Boolean): List<Int> = resolveDefaultReminder(
|
||||
timedGlobal = timed,
|
||||
@@ -260,7 +239,7 @@ class EventEditViewModel @Inject constructor(
|
||||
|
||||
private data class ExternalInputs(
|
||||
val writable: List<CalendarSource>,
|
||||
val hints: NewEventCalendarHints,
|
||||
val lastUsed: Long?,
|
||||
val defaultFields: Set<EventFormField>,
|
||||
val allowColorOnUnsupported: Boolean,
|
||||
val autofocusTitle: Boolean,
|
||||
@@ -273,8 +252,8 @@ class EventEditViewModel @Inject constructor(
|
||||
/**
|
||||
* The calendars a new event can be saved to ([isEventTarget]): writable,
|
||||
* switched on, not a contact-filled mirror, not a non-syncing subscription.
|
||||
* A preselect landing on an excluded calendar falls back as
|
||||
* [resolveEventCalendar] describes.
|
||||
* A last-used preselect landing on an excluded calendar falls back to the
|
||||
* first remaining one (handled by [resolvedCalendarId] and [state]).
|
||||
*
|
||||
* This is the list of *targets*. An event already living in an excluded
|
||||
* calendar keeps it — [state] adds it back to the picker.
|
||||
@@ -283,20 +262,16 @@ class EventEditViewModel @Inject constructor(
|
||||
calendars.filter { it.isEventTarget }
|
||||
}
|
||||
|
||||
private val calendarHints: Flow<NewEventCalendarHints> = combine(
|
||||
_requestedCalendarId,
|
||||
settingsPrefs.defaultNewEventCalendar,
|
||||
prefs.lastUsedCalendarId,
|
||||
::NewEventCalendarHints,
|
||||
)
|
||||
|
||||
/** The target calendar id, resolved exactly as the form shows it. */
|
||||
private val resolvedCalendarId: Flow<Long?> = combine(
|
||||
_form.map { it?.calendarId },
|
||||
calendarHints,
|
||||
allCalendars,
|
||||
::resolveEventCalendar,
|
||||
).distinctUntilChanged()
|
||||
writableCalendars,
|
||||
prefs.lastUsedCalendarId,
|
||||
) { picked, writable, lastUsed ->
|
||||
picked
|
||||
?: lastUsed?.takeIf { id -> writable.any { it.id == id } }
|
||||
?: writable.firstOrNull()?.id
|
||||
}.distinctUntilChanged()
|
||||
|
||||
/** The resolved calendar's published event palette, refetched when it changes. */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@@ -310,7 +285,7 @@ class EventEditViewModel @Inject constructor(
|
||||
combine(_form, _saveState, _showProblems, _revealed, _editTarget, ::LocalInputs),
|
||||
combine(
|
||||
writableCalendars,
|
||||
calendarHints,
|
||||
prefs.lastUsedCalendarId,
|
||||
settingsPrefs.defaultFormFields,
|
||||
settingsPrefs.allowColorOnUnsupportedCalendars,
|
||||
settingsPrefs.autofocusEventTitle,
|
||||
@@ -321,14 +296,10 @@ class EventEditViewModel @Inject constructor(
|
||||
settingsPrefs.recentTimeZones.flowOn(io),
|
||||
) { local, external, palette, allCalendars, recentTimeZones ->
|
||||
val form = local.form ?: return@combine null
|
||||
val resolvedId = resolveEventCalendar(form.calendarId, external.hints, allCalendars)
|
||||
// A colour is scoped to the calendar it came from, so one that came with
|
||||
// a requested calendar the form couldn't take goes, as on [setCalendar].
|
||||
val requestRefused = form.calendarId == null && resolvedId != null &&
|
||||
external.hints.requested.let { it != null && it != resolvedId }
|
||||
val resolved = form.copy(calendarId = resolvedId).let {
|
||||
if (requestRefused) it.copy(colorKey = null, color = null) else it
|
||||
}
|
||||
val resolvedId = form.calendarId
|
||||
?: external.lastUsed?.takeIf { id -> external.writable.any { it.id == id } }
|
||||
?: external.writable.firstOrNull()?.id
|
||||
val resolved = form.copy(calendarId = resolvedId)
|
||||
val resolvedCalendar = allCalendars.firstOrNull { it.id == resolvedId }
|
||||
// Editing an event in a managed calendar locks its synced fields. Keyed
|
||||
// off the calendar's durable marker, not a stored id, so it holds after a
|
||||
@@ -436,9 +407,8 @@ class EventEditViewModel @Inject constructor(
|
||||
* Seed a fresh event from a prefilled [form] — a parsed single-event `.ics`
|
||||
* file ([ImportSource.File]) or an external `ACTION_INSERT` intent (another
|
||||
* app/widget creating an event, e.g. Google Maps' "add to calendar";
|
||||
* [ImportSource.Insert]; #30, #49). A set [EventForm.calendarId] is the
|
||||
* calendar the caller asked for: it is preselected while it is an event
|
||||
* target, and the form otherwise resolves its calendar like a new event (#429).
|
||||
* [ImportSource.Insert]; #30, #49). [EventForm.calendarId] is null so the
|
||||
* calendar still resolves to the last-used/first-writable one.
|
||||
*
|
||||
* Reminders are handled per [source], because the two paths mean different
|
||||
* things by "no reminders":
|
||||
@@ -461,18 +431,17 @@ class EventEditViewModel @Inject constructor(
|
||||
fun openImported(form: EventForm, source: ImportSource) {
|
||||
if (_form.value != null || _editTarget.value != null) return
|
||||
_revealed.value = form.populatedFields()
|
||||
_requestedCalendarId.value = form.calendarId
|
||||
open(form.copy(calendarId = null))
|
||||
open(form)
|
||||
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
|
||||
when (source) {
|
||||
ImportSource.Insert, ImportSource.InsertOpenEnded ->
|
||||
if (form.reminders.isNotEmpty() || form.fixedReminders.isNotEmpty()) _remindersTouched.value = true
|
||||
if (form.reminders.isNotEmpty()) _remindersTouched.value = true
|
||||
else applyDefaultReminder()
|
||||
|
||||
ImportSource.File -> {
|
||||
// Respect the file's own reminders; never silently overwrite them.
|
||||
_remindersTouched.value = true
|
||||
maybePromptImportedReminderDefault()
|
||||
maybePromptImportedReminderDefault(form)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,35 +465,27 @@ class EventEditViewModel @Inject constructor(
|
||||
val form = _form.value ?: return@launch
|
||||
if (_editTarget.value != null || _remindersTouched.value) return@launch
|
||||
val reminders = defaults.resolveFor(targetId, form.isAllDay)
|
||||
val fixed = defaults.resolveFixedFor(targetId, form.isAllDay)
|
||||
// The duration default resolves in parallel, so both must compose
|
||||
// onto the current form, not a pre-suspend copy.
|
||||
applyDefault { it.copy(reminders = reminders, fixedReminders = fixed) }
|
||||
applyDefault { it.copy(reminders = reminders) }
|
||||
// Surface the section so an auto-applied default is visible and
|
||||
// removable, even when Reminders isn't a default-shown field.
|
||||
if (reminders.isNotEmpty() || fixed.isNotEmpty()) {
|
||||
if (reminders.isNotEmpty()) {
|
||||
_revealed.value = _revealed.value + EventFormField.Reminders
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Snapshot the settings-default reminder flows into one value. */
|
||||
/** Snapshot the four settings-default reminder flows into one value. */
|
||||
private suspend fun reminderDefaults(): ReminderDefaults = combine(
|
||||
combine(
|
||||
settingsPrefs.defaultReminderMinutes,
|
||||
settingsPrefs.defaultAllDayReminderMinutes,
|
||||
settingsPrefs.perCalendarReminderOverride,
|
||||
settingsPrefs.perCalendarAllDayReminderOverride,
|
||||
::Quadruple,
|
||||
),
|
||||
settingsPrefs.defaultFixedTimeReminder,
|
||||
settingsPrefs.perCalendarFixedTimeReminderOverride,
|
||||
) { (timed, allDay, timedOv, allDayOv), fixed, fixedOv ->
|
||||
ReminderDefaults(timed, allDay, timedOv, allDayOv, fixed, fixedOv)
|
||||
settingsPrefs.defaultReminderMinutes,
|
||||
settingsPrefs.defaultAllDayReminderMinutes,
|
||||
settingsPrefs.perCalendarReminderOverride,
|
||||
settingsPrefs.perCalendarAllDayReminderOverride,
|
||||
) { timed, allDay, timedOv, allDayOv ->
|
||||
ReminderDefaults(timed, allDay, timedOv, allDayOv)
|
||||
}.first()
|
||||
|
||||
private data class Quadruple<A, B, C, D>(val a: A, val b: B, val c: C, val d: D)
|
||||
|
||||
/**
|
||||
* Stretch a new timed event to the configured default length (#54) — the
|
||||
* resolved calendar's per-calendar duration, otherwise the global default —
|
||||
@@ -566,26 +527,19 @@ class EventEditViewModel @Inject constructor(
|
||||
* settings default — but only when there's a real choice: a default is
|
||||
* configured and it isn't already exactly what the file carried.
|
||||
*/
|
||||
private fun maybePromptImportedReminderDefault() {
|
||||
private fun maybePromptImportedReminderDefault(form: EventForm) {
|
||||
val opened = session
|
||||
viewModelScope.launch {
|
||||
val targetId = resolvedCalendarId.first()
|
||||
val defaults = reminderDefaults()
|
||||
val default = reminderDefaults().resolveFor(targetId, form.isAllDay)
|
||||
// Bail if the form closed or became an edit while we resolved.
|
||||
if (opened != session) return@launch
|
||||
val current = _form.value ?: return@launch
|
||||
if (_editTarget.value != null) return@launch
|
||||
// The form may have switched all-day meanwhile; offer that kind's default.
|
||||
val default = defaults.resolveFor(targetId, current.isAllDay)
|
||||
val fixed = defaults.resolveFixedFor(targetId, current.isAllDay)
|
||||
val firing = current.firingReminders()
|
||||
val firingFixed = if (current.isAllDay) emptyList() else current.fixedReminders
|
||||
if (default.isEmpty() && fixed.isEmpty()) return@launch
|
||||
if (default == firing && fixed == firingFixed) return@launch
|
||||
if (default.isEmpty() || default == current.reminders) return@launch
|
||||
_importReminderPrompt.value = ImportReminderPrompt(
|
||||
currentReminderCount = firing.size + firingFixed.size,
|
||||
currentReminderCount = current.reminders.size,
|
||||
defaultReminders = default,
|
||||
defaultFixedReminders = fixed,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -595,7 +549,7 @@ class EventEditViewModel @Inject constructor(
|
||||
val prompt = _importReminderPrompt.value ?: return
|
||||
_importReminderPrompt.value = null
|
||||
// Already frozen as touched by openImported; this just swaps the values.
|
||||
edit { it.copy(reminders = prompt.defaultReminders, fixedReminders = prompt.defaultFixedReminders) }
|
||||
edit { it.copy(reminders = prompt.defaultReminders) }
|
||||
_revealed.value = _revealed.value + EventFormField.Reminders
|
||||
}
|
||||
|
||||
@@ -625,15 +579,14 @@ class EventEditViewModel @Inject constructor(
|
||||
if (opened == session) _loadFailed.value = true
|
||||
return@launch
|
||||
}
|
||||
val knownFixed = settingsPrefs.knownFixedTimeReminders.first()
|
||||
if (opened != session) return@launch
|
||||
val zone = zoneSource.current()
|
||||
val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME }
|
||||
?: detail.instance.start.toEpochMilliseconds()
|
||||
val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME }
|
||||
?: detail.instance.end.toEpochMilliseconds()
|
||||
val snapshot = detail.toEditSnapshot(begin, end, zone).withFixedTimeRemindersRead(knownFixed, zone)
|
||||
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end), knownFixed)
|
||||
val snapshot = detail.toEditSnapshot(begin, end, zone)
|
||||
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end))
|
||||
// Sections holding data must show even when not in the defaults.
|
||||
_revealed.value = snapshot.form.populatedFields()
|
||||
open(snapshot.form)
|
||||
@@ -656,7 +609,6 @@ class EventEditViewModel @Inject constructor(
|
||||
_remindersTouched.value = false
|
||||
_durationTouched.value = false
|
||||
_importReminderPrompt.value = null
|
||||
_requestedCalendarId.value = null
|
||||
}
|
||||
|
||||
/** Unfold one optional field, picked in the "more fields" dialog. */
|
||||
@@ -715,11 +667,6 @@ class EventEditViewModel @Inject constructor(
|
||||
* The event falls back to the new calendar's colour until re-picked.
|
||||
*/
|
||||
fun setCalendar(id: Long) {
|
||||
// Confirming the calendar the form shows pins it and changes nothing else.
|
||||
if (id == state.value?.form?.calendarId) {
|
||||
pinShownCalendar()
|
||||
return
|
||||
}
|
||||
edit { it.copy(calendarId = id, colorKey = null, color = null) }
|
||||
// A fresh event re-inherits the new calendar's default reminder and
|
||||
// length unless the user has already hand-edited them (guarded inside).
|
||||
@@ -731,79 +678,25 @@ class EventEditViewModel @Inject constructor(
|
||||
fun setAccessLevel(value: AccessLevel) = edit { it.copy(accessLevel = value) }
|
||||
|
||||
/** Pick a palette colour (round-trips via its key); [argb] is its swatch. */
|
||||
fun setColorKey(key: String, argb: Int) {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = key, color = argb) }
|
||||
}
|
||||
fun setColorKey(key: String, argb: Int) = edit { it.copy(colorKey = key, color = argb) }
|
||||
|
||||
/** Pick a raw colour (local / opted-in calendars), clearing any palette key. */
|
||||
fun setColorRaw(argb: Int) {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = null, color = argb) }
|
||||
}
|
||||
fun setColorRaw(argb: Int) = edit { it.copy(colorKey = null, color = argb) }
|
||||
|
||||
/** Clear the colour so the event inherits its calendar's. */
|
||||
fun clearColor() {
|
||||
pinShownCalendar()
|
||||
edit { it.copy(colorKey = null, color = null) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix a still-resolving form to the calendar and colour it shows, so a colour
|
||||
* picked for that calendar stays with it. Not a change of its own.
|
||||
*/
|
||||
private fun pinShownCalendar() {
|
||||
val shown = state.value?.form ?: return
|
||||
if (_form.value?.calendarId != null) return
|
||||
applyDefault { it.copy(calendarId = shown.calendarId, colorKey = shown.colorKey, color = shown.color) }
|
||||
}
|
||||
fun clearColor() = edit { it.copy(colorKey = null, color = null) }
|
||||
|
||||
/** Bare RRULE value from the recurrence picker; null = does not repeat. */
|
||||
fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) }
|
||||
|
||||
fun addReminder(minutes: Int) {
|
||||
_remindersTouched.value = true
|
||||
edit {
|
||||
// A lead firing with a set-time reminder would be one row once saved.
|
||||
if (minutes in it.fixedReminderOffsets(zoneSource.current())) it
|
||||
else it.copy(reminders = (it.reminders + minutes).distinct().sorted())
|
||||
}
|
||||
edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) }
|
||||
}
|
||||
|
||||
/**
|
||||
* On an all-day event a reminder is shown as the whole day it fires on, so
|
||||
* removing it drops every stored lead time that lands on that day.
|
||||
*/
|
||||
fun removeReminder(minutes: Int) {
|
||||
_remindersTouched.value = true
|
||||
edit { form ->
|
||||
val removed = if (form.isAllDay) {
|
||||
form.reminders.filter { wholeDayLeadMinutes(it) == wholeDayLeadMinutes(minutes) }
|
||||
} else {
|
||||
listOf(minutes)
|
||||
}
|
||||
form.copy(reminders = form.reminders - removed.toSet())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an "N days before at HH:MM" reminder (#459); timed events only. A lead
|
||||
* time landing on the same moment is replaced by it — the two would be one
|
||||
* row once saved.
|
||||
*/
|
||||
fun addFixedReminder(reminder: FixedTimeReminder) {
|
||||
_remindersTouched.value = true
|
||||
edit { form ->
|
||||
if (form.isAllDay) return@edit form
|
||||
val withFixed = form.copy(fixedReminders = (form.fixedReminders + reminder).distinct().sortedWith(FIXED_ORDER))
|
||||
val offsets = withFixed.fixedReminderOffsets(zoneSource.current()).toSet()
|
||||
withFixed.copy(reminders = form.reminders.filterNot { it in offsets })
|
||||
}
|
||||
}
|
||||
|
||||
fun removeFixedReminder(reminder: FixedTimeReminder) {
|
||||
_remindersTouched.value = true
|
||||
edit { it.copy(fixedReminders = it.fixedReminders - reminder) }
|
||||
edit { it.copy(reminders = it.reminders - minutes) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -922,7 +815,6 @@ class EventEditViewModel @Inject constructor(
|
||||
val fresh = try {
|
||||
repository.eventDetail(target.eventId)
|
||||
.toEditSnapshot(target.beginMillis, target.endMillis, target.zone)
|
||||
.withFixedTimeRemindersRead(target.knownFixed, target.zone)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: NoSuchEventException) {
|
||||
@@ -937,17 +829,6 @@ class EventEditViewModel @Inject constructor(
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
// Remembered before the write, so the rows read back as these
|
||||
// reminders from the first re-read on (#459).
|
||||
if (!form.isAllDay && form.fixedReminders.isNotEmpty()) {
|
||||
try {
|
||||
settingsPrefs.rememberFixedTimeReminders(form.fixedReminders)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not remember the set-time reminders", e)
|
||||
}
|
||||
}
|
||||
val result = try {
|
||||
if (target == null) {
|
||||
repository.createEvent(form)
|
||||
@@ -1069,15 +950,3 @@ class EventEditViewModel @Inject constructor(
|
||||
_form.value = _form.value?.let(block)
|
||||
}
|
||||
}
|
||||
|
||||
/** [EditSnapshot.form] with its timed reminders read back into lead times and fixed-time ones. */
|
||||
private fun EditSnapshot.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, zone: TimeZone): EditSnapshot =
|
||||
copy(form = form.withFixedTimeRemindersRead(known, zone))
|
||||
|
||||
/**
|
||||
* Reminders as they fire: an all-day event fires on whole days, so a sub-day lead
|
||||
* time kept from the timed form reads as its day. The form keeps the raw values,
|
||||
* so switching all-day off again restores any the user did not remove.
|
||||
*/
|
||||
internal fun EventForm.firingReminders(): List<Int> =
|
||||
if (isAllDay) wholeDayLeadTimes(reminders) else reminders
|
||||
@@ -1,33 +1,19 @@
|
||||
package de.jeanlucmakiola.calendula.ui.filter
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.wrapContentHeight
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FilterList
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.state.ToggleableState
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
@@ -36,26 +22,20 @@ import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
|
||||
/**
|
||||
* Calendar-visibility filter (M3), rendered inline in the navigation drawer.
|
||||
* Every calendar grouped by account, each with a colour swatch and a visibility
|
||||
* switch; toggling writes straight to DataStore and every calendar view
|
||||
* re-filters live. Three states (Loading / Failure / Success). A calendar hidden
|
||||
* in [currentView] through its per-view setting (#270) says so on its row, and
|
||||
* the entry below the list opens that setting for the view (#517).
|
||||
* re-filters live. Three states (Loading / Failure / Success).
|
||||
*/
|
||||
@Composable
|
||||
fun CalendarFilterList(
|
||||
currentView: CalendarView,
|
||||
onHideInView: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: FilterViewModel = hiltViewModel(),
|
||||
) {
|
||||
@@ -63,19 +43,12 @@ fun CalendarFilterList(
|
||||
when (val s = state) {
|
||||
FilterUiState.Loading -> FilterLoading(modifier)
|
||||
is FilterUiState.Failure -> FilterMessage(s.reason, modifier)
|
||||
is FilterUiState.Success -> {
|
||||
val hiddenInView = remember(s, currentView) { s.hiddenOnlyIn(currentView) }
|
||||
FilterList(
|
||||
groups = s.groups,
|
||||
hidden = s.hidden,
|
||||
hiddenInView = hiddenInView,
|
||||
hiddenOnlyHere = hiddenInView.size,
|
||||
onHideInView = onHideInView,
|
||||
onToggleCalendar = viewModel::toggleCalendar,
|
||||
onToggleGroup = viewModel::toggleGroup,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
is FilterUiState.Success -> FilterList(
|
||||
groups = s.groups,
|
||||
hidden = s.hidden,
|
||||
onSetVisible = viewModel::setVisible,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,95 +61,44 @@ fun CalendarFilterList(
|
||||
private fun FilterList(
|
||||
groups: List<CalendarAccountGroup>,
|
||||
hidden: Set<Long>,
|
||||
hiddenInView: Set<Long>,
|
||||
hiddenOnlyHere: Int,
|
||||
onHideInView: () -> Unit,
|
||||
onToggleCalendar: (Long) -> Unit,
|
||||
onToggleGroup: (List<Long>) -> Unit,
|
||||
onSetVisible: (Long, Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
groups.forEach { group ->
|
||||
val ids = group.calendars.map { it.id }
|
||||
GroupHeader(
|
||||
title = accountGroupTitle(group),
|
||||
state = groupVisibility(ids, hidden),
|
||||
onToggle = { onToggleGroup(ids) },
|
||||
Text(
|
||||
text = accountGroupTitle(group),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(
|
||||
start = GroupedListInset,
|
||||
end = GroupedListInset,
|
||||
top = 12.dp,
|
||||
bottom = 4.dp,
|
||||
),
|
||||
)
|
||||
group.calendars.forEachIndexed { index, cal ->
|
||||
val visible = cal.id !in hidden
|
||||
GroupedRow(
|
||||
title = cal.displayName.orUnnamed(),
|
||||
summary = if (cal.id in hiddenInView) stringResource(R.string.filter_hidden_in_view) else null,
|
||||
position = positionOf(index, group.calendars.size),
|
||||
minHeight = 56.dp,
|
||||
leading = { CalendarColorChip(cal.color) },
|
||||
trailing = {
|
||||
Checkbox(
|
||||
checked = visible,
|
||||
onCheckedChange = { onToggleCalendar(cal.id) },
|
||||
onCheckedChange = { onSetVisible(cal.id, it) },
|
||||
)
|
||||
},
|
||||
onClick = { onToggleCalendar(cal.id) },
|
||||
onClick = { onSetVisible(cal.id, !visible) },
|
||||
)
|
||||
}
|
||||
}
|
||||
// The per-view hide (#517): the drawer filter above hides everywhere, this only here.
|
||||
Spacer(Modifier.height(8.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.view_calendars_title),
|
||||
summary = if (hiddenOnlyHere > 0) {
|
||||
pluralStringResource(R.plurals.drawer_hidden_in_view_count, hiddenOnlyHere, hiddenOnlyHere)
|
||||
} else {
|
||||
stringResource(R.string.drawer_hidden_in_view_none)
|
||||
},
|
||||
position = Position.Alone,
|
||||
minHeight = 56.dp,
|
||||
// Tinted, not "selected": it is an entry point, not a chosen option.
|
||||
container = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.secondaryContainer else null,
|
||||
contentColor = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.onSecondaryContainer else null,
|
||||
leading = {
|
||||
Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.Filled.FilterList, contentDescription = null)
|
||||
}
|
||||
},
|
||||
onClick = onHideInView,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An account's header doubling as the group's parent checkbox (#143): checked
|
||||
* when every calendar shows, indeterminate when some do. Tapping it shows all,
|
||||
* or hides all when the group is fully shown.
|
||||
*/
|
||||
@Composable
|
||||
private fun GroupHeader(
|
||||
title: String,
|
||||
state: ToggleableState,
|
||||
onToggle: () -> Unit,
|
||||
) {
|
||||
val label = stringResource(
|
||||
if (state.nextGroupVisible()) R.string.filter_group_show_all else R.string.filter_group_hide_all,
|
||||
)
|
||||
// The header itself is the toggle; the rows' checkboxes show the result.
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = GroupedListInset / 2)
|
||||
.clip(MaterialTheme.shapes.large)
|
||||
.clickable(onClickLabel = label, role = Role.Button) { onToggle() }
|
||||
.heightIn(min = 48.dp)
|
||||
.wrapContentHeight(Alignment.CenterVertically)
|
||||
.padding(horizontal = GroupedListInset / 2),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
private fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
@@ -197,7 +119,7 @@ internal fun FilterLoading(modifier: Modifier = Modifier) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) {
|
||||
private fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) {
|
||||
val msg = when (reason) {
|
||||
FailureReason.NoCalendarsConfigured -> R.string.state_failure_no_calendars
|
||||
FailureReason.AllCalendarsHidden -> R.string.state_failure_all_hidden
|
||||
|
||||
@@ -2,8 +2,6 @@ package de.jeanlucmakiola.calendula.ui.filter
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
|
||||
/**
|
||||
* State for the calendar-filter sheet (M3). The user toggles per-calendar
|
||||
@@ -13,22 +11,9 @@ import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
sealed interface FilterUiState {
|
||||
data object Loading : FilterUiState
|
||||
data class Failure(val reason: FailureReason) : FilterUiState
|
||||
/**
|
||||
* A calendar shows when its id is *not* in [hidden]; [hiddenViews] are the
|
||||
* views each calendar is hidden in regardless (#270).
|
||||
*/
|
||||
/** A calendar shows when its id is *not* in [hidden]. */
|
||||
data class Success(
|
||||
val groups: List<CalendarAccountGroup>,
|
||||
val hidden: Set<Long>,
|
||||
val hiddenViews: Map<Long, Set<CalendarView>> = emptyMap(),
|
||||
) : FilterUiState {
|
||||
/**
|
||||
* The listed calendars [view] hides on its own (#517); ones already
|
||||
* hidden everywhere from the drawer, or not listed, aren't included.
|
||||
*/
|
||||
fun hiddenOnlyIn(view: CalendarView): Set<Long> {
|
||||
val listed = groups.flatMapTo(mutableSetOf()) { group -> group.calendars.map { it.id } }
|
||||
return hiddenViews.calendarsHiddenIn(view).filterTo(mutableSetOf()) { it in listed && it !in hidden }
|
||||
}
|
||||
}
|
||||
) : FilterUiState
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
package de.jeanlucmakiola.calendula.ui.filter
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||
import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
@@ -27,7 +23,6 @@ import javax.inject.Inject
|
||||
class FilterViewModel @Inject constructor(
|
||||
private val repository: CalendarRepository,
|
||||
private val prefs: CalendarPrefs,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
@@ -35,9 +30,7 @@ class FilterViewModel @Inject constructor(
|
||||
combine(
|
||||
repository.calendars(),
|
||||
prefs.hiddenCalendarIds,
|
||||
// Only feeds a note on the rows; a failed read leaves it off rather than failing the list.
|
||||
settingsPrefs.perCalendarHiddenViews.hidingNothingOnError(),
|
||||
) { calendars, hidden, hiddenViews ->
|
||||
) { calendars, hidden ->
|
||||
// Calendars switched off device-wide don't belong in the drawer's
|
||||
// hide/show list; they live only in Settings → Calendars.
|
||||
val enabled = calendars.filter { it.isVisibleInSystem }
|
||||
@@ -45,7 +38,7 @@ class FilterViewModel @Inject constructor(
|
||||
if (failure != null) {
|
||||
FilterUiState.Failure(failure)
|
||||
} else {
|
||||
FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews)
|
||||
FilterUiState.Success(enabled.groupByAccount(), hidden)
|
||||
}
|
||||
}
|
||||
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
|
||||
@@ -55,32 +48,13 @@ class FilterViewModel @Inject constructor(
|
||||
initialValue = FilterUiState.Loading,
|
||||
)
|
||||
|
||||
/** Hide or show one calendar in [view] only (#517), the same setting as Settings → Calendars. */
|
||||
fun setHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) {
|
||||
/** Show or hide a single calendar; persists the new hidden set. */
|
||||
fun setVisible(calendarId: Long, visible: Boolean) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
settingsPrefs.setCalendarHiddenIn(calendarId, view, hidden)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("FilterViewModel", "Could not change hidden views of $calendarId", e)
|
||||
}
|
||||
val current = prefs.hiddenCalendarIds.first()
|
||||
val next = if (visible) current - calendarId else current + calendarId
|
||||
if (next != current) prefs.setHiddenCalendarIds(next)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flip one calendar, or a whole group from its header (#143). Both decide
|
||||
* against the stored set rather than the last drawn state, so quick repeated
|
||||
* taps still alternate.
|
||||
*/
|
||||
fun toggleCalendar(calendarId: Long) {
|
||||
viewModelScope.launch {
|
||||
prefs.updateHiddenCalendarIds { if (calendarId in it) it - calendarId else it + calendarId }
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleGroup(calendarIds: List<Long>) {
|
||||
viewModelScope.launch { prefs.updateHiddenCalendarIds { toggledGroup(it, calendarIds) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.filter
|
||||
|
||||
import androidx.compose.ui.state.ToggleableState
|
||||
|
||||
/** The drawer group header's checkbox state: on, off, or some of [calendarIds] shown. */
|
||||
internal fun groupVisibility(calendarIds: Collection<Long>, hidden: Set<Long>): ToggleableState {
|
||||
val shown = calendarIds.count { it !in hidden }
|
||||
return when (shown) {
|
||||
0 -> ToggleableState.Off
|
||||
calendarIds.size -> ToggleableState.On
|
||||
else -> ToggleableState.Indeterminate
|
||||
}
|
||||
}
|
||||
|
||||
/** What tapping the header does: a fully shown group hides, anything else shows all. */
|
||||
internal fun ToggleableState.nextGroupVisible(): Boolean = this != ToggleableState.On
|
||||
|
||||
/** [hidden] after tapping the header of the group holding [calendarIds]. */
|
||||
internal fun toggledGroup(hidden: Set<Long>, calendarIds: Collection<Long>): Set<Long> =
|
||||
if (groupVisibility(calendarIds, hidden).nextGroupVisible()) hidden - calendarIds.toSet() else hidden + calendarIds
|
||||
@@ -1,65 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.filter
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.MultiOptionRows
|
||||
|
||||
/**
|
||||
* The calendars hidden in [view] (#517), opened from the drawer while on it: the
|
||||
* per-view setting from Settings → Calendars (#270), seen from the view's side.
|
||||
* Toggles apply at once.
|
||||
*/
|
||||
@Composable
|
||||
fun ViewCalendarsPicker(
|
||||
view: CalendarView,
|
||||
state: FilterUiState,
|
||||
onSetHidden: (calendarId: Long, hidden: Boolean) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
FullScreenPicker(
|
||||
title = stringResource(R.string.view_calendars_title),
|
||||
onDismiss = onDismiss,
|
||||
predictiveBack = true,
|
||||
) {
|
||||
when (state) {
|
||||
FilterUiState.Loading -> FilterLoading()
|
||||
is FilterUiState.Failure -> FilterMessage(state.reason)
|
||||
is FilterUiState.Success -> {
|
||||
// Seeded once, then ahead of the store: the picker is the only
|
||||
// writer while open, so a quick second tap still flips.
|
||||
var hidden by remember(view) { mutableStateOf(state.hiddenViews.calendarsHiddenIn(view)) }
|
||||
GroupedHint(stringResource(R.string.view_calendars_hint), verticalPadding = 8.dp)
|
||||
state.groups.forEach { group ->
|
||||
GroupedSectionHeader(accountGroupTitle(group))
|
||||
MultiOptionRows(
|
||||
options = group.calendars,
|
||||
selected = group.calendars.filterTo(mutableSetOf()) { it.id in hidden },
|
||||
label = { it.displayName.orUnnamed() },
|
||||
onToggle = { calendar, hide ->
|
||||
hidden = if (hide) hidden + calendar.id else hidden - calendar.id
|
||||
onSetHidden(calendar.id, hide)
|
||||
},
|
||||
summary = { calendar ->
|
||||
if (calendar.id in state.hidden) stringResource(R.string.view_calendars_hidden_everywhere) else null
|
||||
},
|
||||
leading = { CalendarColorChip(it.color) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
package de.jeanlucmakiola.calendula.ui.imports
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
@@ -11,9 +17,13 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.PriorityHigh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
@@ -21,31 +31,34 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||
import de.jeanlucmakiola.calendula.domain.ics.IcsParseWarning
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups
|
||||
import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats
|
||||
import de.jeanlucmakiola.calendula.ui.common.ResultBadge
|
||||
import de.jeanlucmakiola.calendula.ui.common.ResultMessage
|
||||
import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes
|
||||
import de.jeanlucmakiola.floret.identity.predictiveBack
|
||||
|
||||
/**
|
||||
@@ -198,6 +211,18 @@ private fun ManyContent(
|
||||
|
||||
@Composable
|
||||
private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) {
|
||||
// A little expressive pop on the success badge — springs in on first show.
|
||||
val badgeScale = remember { Animatable(0.7f) }
|
||||
LaunchedEffect(Unit) {
|
||||
badgeScale.animateTo(
|
||||
targetValue = 1f,
|
||||
animationSpec = spring(
|
||||
dampingRatio = Spring.DampingRatioMediumBouncy,
|
||||
stiffness = Spring.StiffnessLow,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Part of the file never reached the calendar, so the screen doesn't get to
|
||||
// read as a plain success.
|
||||
val stopped = state.summary.notAttempted > 0
|
||||
@@ -207,28 +232,160 @@ private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) {
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
ResultBadge(error = stopped)
|
||||
ResultMessage(
|
||||
title = stringResource(
|
||||
Box(
|
||||
Modifier
|
||||
.size(112.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = badgeScale.value
|
||||
scaleY = badgeScale.value
|
||||
}
|
||||
.clip(CircleShape)
|
||||
.background(
|
||||
if (stopped) {
|
||||
MaterialTheme.colorScheme.errorContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.primaryContainer
|
||||
},
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
if (stopped) Icons.Default.PriorityHigh else Icons.Default.Check,
|
||||
contentDescription = null,
|
||||
tint = if (stopped) {
|
||||
MaterialTheme.colorScheme.onErrorContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onPrimaryContainer
|
||||
},
|
||||
modifier = Modifier.size(56.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Text(
|
||||
stringResource(
|
||||
if (stopped) R.string.import_done_stopped_title else R.string.import_done_title,
|
||||
),
|
||||
// The counts cover the part of the file that was tried, so say how much never was.
|
||||
notes = importSummaryNotes(
|
||||
state.summary,
|
||||
stoppedNote = if (stopped) {
|
||||
pluralStringResource(R.plurals.import_done_stopped, state.summary.notAttempted, state.summary.notAttempted)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
if (state.summary.failed > 0) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.import_done_failed_note),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
if (state.summary.skippedDuplicate > 0) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
stringResource(R.string.import_done_dedup_note),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
// The one note that isn't about individual events: the counts below cover
|
||||
// the part of the file that was tried, so say how much never was.
|
||||
if (stopped) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
pluralStringResource(
|
||||
R.plurals.import_done_stopped,
|
||||
state.summary.notAttempted,
|
||||
state.summary.notAttempted,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
ImportSummaryStats(state.summary)
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
ImportStatCard(
|
||||
count = state.summary.imported,
|
||||
label = stringResource(R.string.import_done_added_label),
|
||||
contentDescription = pluralStringResource(
|
||||
R.plurals.import_done_imported,
|
||||
state.summary.imported,
|
||||
state.summary.imported,
|
||||
),
|
||||
container = MaterialTheme.colorScheme.secondaryContainer,
|
||||
onContainer = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
if (state.summary.skippedDuplicate > 0) {
|
||||
ImportStatCard(
|
||||
count = state.summary.skippedDuplicate,
|
||||
label = stringResource(R.string.import_done_skipped_label),
|
||||
contentDescription = pluralStringResource(
|
||||
R.plurals.import_done_skipped,
|
||||
state.summary.skippedDuplicate,
|
||||
state.summary.skippedDuplicate,
|
||||
),
|
||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
onContainer = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (state.summary.failed > 0) {
|
||||
ImportStatCard(
|
||||
count = state.summary.failed,
|
||||
label = stringResource(R.string.import_done_failed_label),
|
||||
contentDescription = pluralStringResource(
|
||||
R.plurals.import_done_failed,
|
||||
state.summary.failed,
|
||||
state.summary.failed,
|
||||
),
|
||||
container = MaterialTheme.colorScheme.errorContainer,
|
||||
onContainer = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
OnboardingPrimaryButton(
|
||||
text = stringResource(R.string.import_close),
|
||||
Button(
|
||||
onClick = onClose,
|
||||
)
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.import_close))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A big-number tonal tile summarising one import outcome (added / skipped / failed). */
|
||||
@Composable
|
||||
private fun RowScope.ImportStatCard(
|
||||
count: Int,
|
||||
label: String,
|
||||
contentDescription: String,
|
||||
container: Color,
|
||||
onContainer: Color,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clearAndSetSemantics { this.contentDescription = contentDescription },
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = container,
|
||||
) {
|
||||
Column(
|
||||
Modifier.padding(vertical = 20.dp, horizontal = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Text(
|
||||
count.toString(),
|
||||
style = MaterialTheme.typography.displaySmall,
|
||||
color = onContainer,
|
||||
)
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = onContainer.copy(alpha = 0.85f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||
import de.jeanlucmakiola.calendula.ui.common.nextMoveToken
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -106,22 +107,11 @@ data class MonthChipDrag(
|
||||
val time: String? = null,
|
||||
)
|
||||
|
||||
/** A drop parked by a newer pickup while its write still runs — see [MonthDragController.held]. */
|
||||
data class HeldChip(
|
||||
val copy: MonthChipDrag,
|
||||
val token: Long,
|
||||
val handedOver: Boolean = false,
|
||||
/** Where the grid now draws the drop, in root coordinates, once a row seats it. */
|
||||
val seat: Offset? = null,
|
||||
)
|
||||
|
||||
/** Where a finished chip drag asks its event to go, as a whole-day shift. */
|
||||
data class MonthChipDrop(
|
||||
val event: EventInstance,
|
||||
val grabDate: LocalDate,
|
||||
val targetDate: LocalDate,
|
||||
/** The drop's identity, which its held copy waits on — see [MonthDragController.settledToken]. */
|
||||
val token: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -177,22 +167,19 @@ class MonthDragController {
|
||||
private set
|
||||
|
||||
/**
|
||||
* This controller's recent drops by token, kept past [release] for
|
||||
* [beginUndo] — the confirmation chip carries Undo long after the copy is
|
||||
* gone, and it may be any of them the chip offers to undo.
|
||||
* The last drop this controller made, kept past [release] for [beginUndo] —
|
||||
* the confirmation chip carries Undo long after the copy is gone.
|
||||
*/
|
||||
private val undoable = LinkedHashMap<Long, MonthChipDrag>()
|
||||
private var undoable: MonthChipDrag? = null
|
||||
|
||||
/**
|
||||
* Earlier drops still being written when another chip was picked up. They
|
||||
* keep their copy and their ghost until their own token settles, rather than
|
||||
* vanishing and flashing back on the old day (#494).
|
||||
* The abandoned-move counter, read at the drop so the mark can't be a
|
||||
* composition behind the tick it is compared against.
|
||||
*/
|
||||
var held: List<HeldChip> by mutableStateOf(emptyList())
|
||||
private set
|
||||
var abandonedTicks: StateFlow<Int>? = null
|
||||
|
||||
/** The token of the drop (or undo) [settling] is waiting on. */
|
||||
var settledToken: Long = 0L
|
||||
/** What [abandonedTicks] stood at when the settling chip was let go. */
|
||||
var settledAbandonedMark: Int = 0
|
||||
private set
|
||||
|
||||
private var event: EventInstance? = null
|
||||
@@ -221,7 +208,7 @@ class MonthDragController {
|
||||
this.event = event
|
||||
this.grabDate = grabDate
|
||||
this.time = time
|
||||
parkSettling()
|
||||
settling = null
|
||||
isDragging = true
|
||||
liftedInstanceId = event.instanceId
|
||||
grab = pointerInRoot - chipInRoot
|
||||
@@ -247,39 +234,6 @@ class MonthDragController {
|
||||
settledGhost = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [event]'s chip belongs to a held drop and must stay a ghost: its
|
||||
* source, or once a row seats it, the chip the grid draws on its target day.
|
||||
*/
|
||||
fun isHeldChip(event: EventInstance, days: List<LocalDate>?): Boolean = held.any { parked ->
|
||||
!parked.handedOver && (
|
||||
parked.copy.event.instanceId == event.instanceId ||
|
||||
(
|
||||
parked.seat != null && days != null && parked.copy.targetDate in days &&
|
||||
isSameEvent(event, parked.copy.event)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
|
||||
private fun parkSettling() {
|
||||
val landed = settling
|
||||
if (landed != null) held = held + HeldChip(landed, settledToken)
|
||||
settling = null
|
||||
settledInRoot = null
|
||||
settledGhost = false
|
||||
}
|
||||
|
||||
/** Stop ghosting the held drop [token]'s source while its copy fades. */
|
||||
fun handOverHeld(token: Long) {
|
||||
held = held.map { if (it.token == token) it.copy(handedOver = true) else it }
|
||||
}
|
||||
|
||||
/** Drop the held copy [token] once it has faded. */
|
||||
fun releaseHeld(token: Long) {
|
||||
held = held.filterNot { it.token == token }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [days] holds the chip the grid has drawn for the settled drop —
|
||||
* the seat the copy is on its way to, which must ghost until it gets there.
|
||||
@@ -296,13 +250,6 @@ class MonthDragController {
|
||||
* nearest where the chip was let go is the one the finger was over.
|
||||
*/
|
||||
fun noteSettled(token: Any) {
|
||||
val row = rows[token]
|
||||
if (row != null && held.any { it.seat == null }) {
|
||||
held = held.map { parked ->
|
||||
val target = parked.copy.targetDate
|
||||
if (parked.seat != null || target == null) parked else parked.copy(seat = row.seatOf(parked.copy.event, target))
|
||||
}
|
||||
}
|
||||
val landed = settling ?: return
|
||||
val target = landed.targetDate ?: return
|
||||
val at = rows[token]?.seatOf(landed.event, target) ?: return
|
||||
@@ -318,16 +265,16 @@ class MonthDragController {
|
||||
* there is no drop of this controller's left to undo, or the grid doesn't
|
||||
* seat the moved event where the chip would have to start from.
|
||||
*/
|
||||
fun beginUndo(token: Long, dropToken: Long): Boolean {
|
||||
val last = undoable.remove(dropToken) ?: return false
|
||||
parkSettling()
|
||||
fun beginUndo(): Boolean {
|
||||
val last = undoable ?: return false
|
||||
undoable = null
|
||||
val from = last.targetDate ?: return false
|
||||
val at = rows.values.firstNotNullOfOrNull { it.seatOf(last.event, from) } ?: return false
|
||||
settling = last.copy(grabDate = from, targetDate = last.grabDate, topLeftInRoot = at)
|
||||
liftedInstanceId = last.event.instanceId
|
||||
settledGhost = true
|
||||
settledInRoot = null
|
||||
settledToken = token
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -347,11 +294,10 @@ class MonthDragController {
|
||||
)
|
||||
liftedInstanceId = landed.event.instanceId
|
||||
settledGhost = true
|
||||
settledToken = nextMoveToken()
|
||||
undoable[settledToken] = requireNotNull(settling)
|
||||
if (undoable.size > UNDOABLE_KEPT) undoable.remove(undoable.keys.first())
|
||||
undoable = settling
|
||||
settledAbandonedMark = abandonedTicks?.value ?: 0
|
||||
drops++
|
||||
return MonthChipDrop(landed.event, landed.grabDate, target, settledToken)
|
||||
return MonthChipDrop(landed.event, landed.grabDate, target)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -409,10 +355,9 @@ class MonthDragController {
|
||||
|
||||
@Composable
|
||||
fun rememberMonthDragController(): MonthDragController {
|
||||
return remember { MonthDragController() }
|
||||
val controller = remember { MonthDragController() }
|
||||
controller.abandonedTicks = LocalEventMove.current?.abandoned
|
||||
return controller
|
||||
}
|
||||
|
||||
val LocalMonthDrag = compositionLocalOf<MonthDragController?> { null }
|
||||
|
||||
/** How many recent drops a month controller keeps for an undo to carry back. */
|
||||
private const val UNDOABLE_KEPT = 8
|
||||
@@ -125,11 +125,11 @@ import de.jeanlucmakiola.calendula.ui.common.eventTitleOverflow
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
|
||||
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
|
||||
import de.jeanlucmakiola.calendula.ui.common.dropStates
|
||||
import de.jeanlucmakiola.calendula.ui.common.moveInFlight
|
||||
import de.jeanlucmakiola.calendula.ui.common.abandonedMoves
|
||||
import de.jeanlucmakiola.calendula.ui.common.OnUndoStarted
|
||||
import de.jeanlucmakiola.calendula.ui.common.ghostAlpha
|
||||
import de.jeanlucmakiola.calendula.ui.common.DragSnapHaptics
|
||||
import de.jeanlucmakiola.calendula.ui.common.rememberHeldSettle
|
||||
import de.jeanlucmakiola.calendula.ui.common.SETTLE_FADE_MILLIS
|
||||
import de.jeanlucmakiola.calendula.ui.common.SETTLE_GRACE_MILLIS
|
||||
import de.jeanlucmakiola.calendula.ui.common.EventMoveScope
|
||||
@@ -515,7 +515,7 @@ fun MonthScreen(
|
||||
val chipDrag = rememberMonthDragController()
|
||||
// Undo moves the event back, so the chip travels back too. The
|
||||
// signal comes from the write, not from the chip that offers it.
|
||||
OnUndoStarted { start -> chipDrag.beginUndo(start.token, start.dropToken) }
|
||||
OnUndoStarted { chipDrag.beginUndo() }
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(innerPadding)
|
||||
@@ -591,11 +591,11 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L
|
||||
@Composable
|
||||
private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Boolean) {
|
||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
val density = LocalDensity.current
|
||||
val timeFit = rememberMonthChipTimeFit(showStartTimes)
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val drops = dropStates()
|
||||
val moveInFlight = controller.settledToken in drops.pending
|
||||
val abandoned = controller.settledToken in drops.abandoned
|
||||
val moveInFlight = moveInFlight()
|
||||
// Here rather than beside the controller: this reads [drag], which changes
|
||||
// every frame, and this composable is the one that is meant to.
|
||||
DragSnapHaptics(controller.drag?.targetDate, controller.drops)
|
||||
@@ -608,12 +608,14 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
val glide = remember { Animatable(Offset.Zero, Offset.VectorConverter) }
|
||||
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
|
||||
val seat = controller.settledInRoot
|
||||
val abandoned = abandonedMoves()
|
||||
LaunchedEffect(controller.settling, moveInFlight, seat, abandoned) {
|
||||
val landed = controller.settling
|
||||
if (landed == null || moveInFlight) return@LaunchedEffect
|
||||
if (seat == null) {
|
||||
// An abandoned drop has no seat coming.
|
||||
if (!abandoned) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
|
||||
// Past the mark this drop was let go on, it was abandoned and no
|
||||
// seat is ever coming.
|
||||
if (abandoned == controller.settledAbandonedMark) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
|
||||
} else {
|
||||
if (!gliding) glide.snapTo(landed.topLeftInRoot)
|
||||
gliding = true
|
||||
@@ -633,9 +635,6 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
.clearAndSetSemantics { }
|
||||
.onGloballyPositioned { origin = it.positionInRoot() },
|
||||
) {
|
||||
controller.held.forEach { parked ->
|
||||
key(parked.token) { HeldMonthChip(controller, parked, origin, timeFit) }
|
||||
}
|
||||
val drag = controller.drag ?: controller.settling ?: return@Box
|
||||
// Landed: the copy sinks back to the grid's own plane while the write runs.
|
||||
val lift by animateFloatAsState(
|
||||
@@ -647,93 +646,42 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
|
||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||
label = "chip-handover",
|
||||
)
|
||||
MonthChipCopy(
|
||||
drag = drag,
|
||||
// Read at layout, so the glide doesn't recompose every frame.
|
||||
at = { if (gliding) glide.value else drag.topLeftInRoot },
|
||||
origin = origin,
|
||||
lift = lift,
|
||||
alpha = copyAlpha,
|
||||
MonthBar(
|
||||
event = drag.event,
|
||||
dark = dark,
|
||||
continuesLeft = false,
|
||||
continuesRight = false,
|
||||
// The time the source chip carried, drawn only if this one-column
|
||||
// cut-out of it has the room — which a slice of a multi-day bar has
|
||||
// not, however wide the bar was.
|
||||
time = drag.time,
|
||||
timeFit = timeFit,
|
||||
chipWidth = with(density) { drag.sizePx.width.toDp() },
|
||||
modifier = Modifier
|
||||
// Absolute: these are root coordinates, and the direction-aware
|
||||
// offset would mirror them across the screen in an RTL layout.
|
||||
.absoluteOffset {
|
||||
val at = if (gliding) glide.value else drag.topLeftInRoot
|
||||
IntOffset(
|
||||
(at.x - origin.x).roundToInt(),
|
||||
(at.y - origin.y).roundToInt(),
|
||||
)
|
||||
}
|
||||
.width(with(density) { drag.sizePx.width.toDp() })
|
||||
.height(with(density) { drag.sizePx.height.toDp() })
|
||||
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = 1f + 0.04f * lift
|
||||
scaleY = 1f + 0.04f * lift
|
||||
shadowElevation = 8.dp.toPx() * lift
|
||||
alpha = copyAlpha
|
||||
shape = EventChipShape
|
||||
clip = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A drop parked by a newer pickup: held on its landing day until its own write settles. */
|
||||
@Composable
|
||||
private fun HeldMonthChip(
|
||||
controller: MonthDragController,
|
||||
parked: HeldChip,
|
||||
origin: Offset,
|
||||
timeFit: MonthChipTimeFit?,
|
||||
) {
|
||||
val reduceMotion = rememberReduceMotion()
|
||||
val glide = remember { Animatable(parked.copy.topLeftInRoot, Offset.VectorConverter) }
|
||||
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
|
||||
val seat = parked.seat
|
||||
val landed = parked.token !in dropStates().pending
|
||||
// Carried onto its seat once the write is in, as the settling chip is.
|
||||
LaunchedEffect(seat, landed) {
|
||||
if (seat == null || !landed) return@LaunchedEffect
|
||||
if (reduceMotion) glide.snapTo(seat) else glide.animateTo(seat, glideSpec)
|
||||
}
|
||||
val alpha = rememberHeldSettle(
|
||||
token = parked.token,
|
||||
seated = seat != null,
|
||||
timeoutMillis = MONTH_SETTLE_TIMEOUT_MILLIS,
|
||||
onHandOver = { controller.handOverHeld(parked.token) },
|
||||
onRelease = { controller.releaseHeld(parked.token) },
|
||||
)
|
||||
MonthChipCopy(parked.copy, { glide.value }, origin, lift = 0f, alpha = alpha, timeFit = timeFit)
|
||||
}
|
||||
|
||||
/** [drag]'s chip floating over the grid with its top left at [at], in root coordinates. */
|
||||
@Composable
|
||||
private fun MonthChipCopy(
|
||||
drag: MonthChipDrag,
|
||||
at: () -> Offset,
|
||||
origin: Offset,
|
||||
lift: Float,
|
||||
alpha: Float,
|
||||
timeFit: MonthChipTimeFit?,
|
||||
) {
|
||||
val density = LocalDensity.current
|
||||
val dark = LocalFloretDarkTheme.current
|
||||
MonthBar(
|
||||
event = drag.event,
|
||||
dark = dark,
|
||||
continuesLeft = false,
|
||||
continuesRight = false,
|
||||
// The time the source chip carried, drawn only if this one-column
|
||||
// cut-out of it has the room — which a slice of a multi-day bar has
|
||||
// not, however wide the bar was.
|
||||
time = drag.time,
|
||||
timeFit = timeFit,
|
||||
chipWidth = with(density) { drag.sizePx.width.toDp() },
|
||||
modifier = Modifier
|
||||
// Absolute: these are root coordinates, and the direction-aware
|
||||
// offset would mirror them across the screen in an RTL layout.
|
||||
.absoluteOffset {
|
||||
val topLeft = at()
|
||||
IntOffset(
|
||||
(topLeft.x - origin.x).roundToInt(),
|
||||
(topLeft.y - origin.y).roundToInt(),
|
||||
)
|
||||
}
|
||||
.width(with(density) { drag.sizePx.width.toDp() })
|
||||
.height(with(density) { drag.sizePx.height.toDp() })
|
||||
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
|
||||
.graphicsLayer {
|
||||
scaleX = 1f + 0.04f * lift
|
||||
scaleY = 1f + 0.04f * lift
|
||||
shadowElevation = 8.dp.toPx() * lift
|
||||
this.alpha = alpha
|
||||
shape = EventChipShape
|
||||
clip = false
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Content for both scrolling styles. No swipe detector and no [AnimatedContent]:
|
||||
* vertical scrolling owns the gesture, and the list never swaps wholesale — it
|
||||
@@ -2310,7 +2258,7 @@ private fun MonthWeekRow(
|
||||
// Once the grid holds the settled chip, tell the controller where this row
|
||||
// has seated it, so the copy in flight can glide onto it. Keyed on the week,
|
||||
// which is what changes when the re-read lands.
|
||||
LaunchedEffect(week, dragController?.settling, dragController?.held) {
|
||||
LaunchedEffect(week, dragController?.settling) {
|
||||
dragController?.noteSettled(rowToken)
|
||||
}
|
||||
|
||||
@@ -2743,8 +2691,6 @@ private fun monthChipDragModifier(
|
||||
beginMillis = drop.event.start.toEpochMilliseconds(),
|
||||
endMillis = drop.event.end.toEpochMilliseconds(),
|
||||
target = MoveTarget.ByDays(delta),
|
||||
isAllDay = drop.event.isAllDay,
|
||||
token = drop.token,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -2890,17 +2836,8 @@ private fun MonthBar(
|
||||
val moveAction = eventMoveAction(event)
|
||||
// The source stays put as a ghost while its floating copy travels.
|
||||
val monthDrag = LocalMonthDrag.current
|
||||
// Derived, so a chip recomposes only when its own answer changes rather than
|
||||
// on every lift, park and release anywhere in the grid.
|
||||
val lifted by remember(monthDrag, event, days) {
|
||||
derivedStateOf {
|
||||
monthDrag != null && (
|
||||
monthDrag.liftedInstanceId == event.instanceId ||
|
||||
monthDrag.isSettledChip(event, days) ||
|
||||
monthDrag.isHeldChip(event, days)
|
||||
)
|
||||
}
|
||||
}
|
||||
val lifted = monthDrag?.liftedInstanceId == event.instanceId ||
|
||||
monthDrag?.isSettledChip(event, days) == true
|
||||
val ghost = ghostAlpha(lifted)
|
||||
val shape = monthBarShape(continuesLeft, continuesRight)
|
||||
Box(
|
||||
|
||||
@@ -19,10 +19,7 @@ import de.jeanlucmakiola.calendula.domain.calendarListFailure
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarSpan
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.PageStateCache
|
||||
import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn
|
||||
import de.jeanlucmakiola.calendula.ui.common.instancesWithout
|
||||
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
|
||||
import de.jeanlucmakiola.calendula.ui.week.coversDay
|
||||
@@ -71,8 +68,6 @@ class MonthViewModel @Inject constructor(
|
||||
|
||||
private val zone = TimeZone.currentSystemDefault()
|
||||
|
||||
private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Month, viewModelScope)
|
||||
|
||||
/** First day of the week, from the Settings preference (AUTO → locale). */
|
||||
val weekStart: StateFlow<DayOfWeek> = settingsPrefs.firstDayOfWeek(viewModelScope)
|
||||
|
||||
@@ -157,7 +152,7 @@ class MonthViewModel @Inject constructor(
|
||||
) { (ym, ws) ->
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(monthGridRange(ym, ws, zone), hiddenHere),
|
||||
repository.instances(monthGridRange(ym, ws, zone)),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildState(ym, ws, calendars, instances, today)
|
||||
@@ -229,7 +224,7 @@ class MonthViewModel @Inject constructor(
|
||||
val range = dayRange(first, last, zone)
|
||||
combine(
|
||||
repository.calendars(),
|
||||
repository.instancesWithout(range, hiddenHere),
|
||||
repository.instances(range),
|
||||
today,
|
||||
) { calendars, instances, today ->
|
||||
buildContinuousState(window, ws, style, calendars, instances, today)
|
||||
|
||||
@@ -89,7 +89,7 @@ internal fun CalendarsStep(
|
||||
initialName = "",
|
||||
initialColor = CalendarColorPalette.all.first(),
|
||||
initialDescription = "",
|
||||
onSave = { name, color, description, _ ->
|
||||
onSave = { name, color, description ->
|
||||
if (!submitted) {
|
||||
submitted = true
|
||||
onCreateLocal(name, color, description)
|
||||
|
||||
@@ -15,7 +15,6 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.backup.isBackedUpByDefault
|
||||
import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch
|
||||
import de.jeanlucmakiola.calendula.domain.orderedForManager
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
@@ -340,7 +339,12 @@ class OnboardingViewModel @Inject constructor(
|
||||
}
|
||||
prefs.setAutoBackupFolderUri(folder.toString())
|
||||
prefs.setAutoBackupEnabled(true)
|
||||
BackupScheduler.reconcile(context, prefs)
|
||||
BackupScheduler.apply(
|
||||
context = context,
|
||||
enabled = true,
|
||||
intervalMinutes = prefs.autoBackupIntervalMinutes.first(),
|
||||
hasFolder = true,
|
||||
)
|
||||
// Immediate feedback: the first backup lands while onboarding runs.
|
||||
BackupScheduler.runNow(context)
|
||||
prefs.setOnboardingDone(OnboardingStep.Backup)
|
||||
@@ -479,7 +483,7 @@ private fun List<CalendarSource>.allHidden(): Boolean =
|
||||
* A read-only subscription is not a backup, so it does not count.
|
||||
*/
|
||||
private fun List<CalendarSource>.backupApplies(): Boolean {
|
||||
val exportable = any { it.isBackedUpByDefault }
|
||||
val exportable = any { it.isLocal && it.canModifyContents && !it.isManaged }
|
||||
val syncedTarget = any { !it.isLocal && it.canModifyContents }
|
||||
return exportable && !syncedTarget
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.reminders
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.calendula.data.reminders.FullScreenAlerts
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderAlert
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderRingService
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||
import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme
|
||||
import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.isDark
|
||||
import de.jeanlucmakiola.floret.prefs.isPureBlack
|
||||
import de.jeanlucmakiola.floret.ring.showOverLockScreen
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* The full-screen reminder alert (#171), opened by the reminder's full-screen
|
||||
* intent over the lock screen, or, for a ringing one, from its heads-up.
|
||||
* It stays until the reminder is dismissed or snoozed — here, from the
|
||||
* notification, or by the ring giving up — and back does not close it.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class ReminderAlertActivity : ComponentActivity() {
|
||||
|
||||
@Inject lateinit var notifier: ReminderNotifier
|
||||
@Inject lateinit var alerts: FullScreenAlerts
|
||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||
@Inject lateinit var calendarDataSource: CalendarDataSource
|
||||
|
||||
@Inject @IoDispatcher
|
||||
lateinit var io: CoroutineDispatcher
|
||||
|
||||
private var state by mutableStateOf<ReminderAlertUiState>(ReminderAlertUiState.Loading)
|
||||
private var alert: ReminderAlert? = null
|
||||
private var loading: Job? = null
|
||||
private var screenOn: Job? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
showOverLockScreen()
|
||||
enableEdgeToEdge()
|
||||
show(intent)
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.CREATED) {
|
||||
alerts.handled.collect { key -> if (key == alert?.key) finish() }
|
||||
}
|
||||
}
|
||||
val cachedTheme = WindowThemeCache.read(this) ?: ThemeMode.SYSTEM
|
||||
val cachedDynamicColor = WindowThemeCache.readDynamicColor(this) ?: true
|
||||
setContent {
|
||||
val themeMode by settingsPrefs.themeMode.collectAsStateWithLifecycle(cachedTheme)
|
||||
val dynamicColor by settingsPrefs.dynamicColor.collectAsStateWithLifecycle(cachedDynamicColor)
|
||||
val soften by settingsPrefs.softenCalendarColors.collectAsStateWithLifecycle(true)
|
||||
CalendulaTheme(
|
||||
darkTheme = themeMode.isDark(isSystemInDarkTheme()),
|
||||
dynamicColor = dynamicColor,
|
||||
pureBlack = themeMode.isPureBlack,
|
||||
) {
|
||||
CompositionLocalProvider(LocalSoftenColors provides soften) {
|
||||
BackHandler(enabled = true) { /* Handled by Dismiss or Snooze, not by leaving. */ }
|
||||
when (val current = state) {
|
||||
ReminderAlertUiState.Loading ->
|
||||
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {}
|
||||
is ReminderAlertUiState.Showing -> ReminderAlertScreen(
|
||||
state = current,
|
||||
onSnooze = { act(ReminderActionReceiver.ACTION_SNOOZE) },
|
||||
onDismiss = { act(ReminderActionReceiver.ACTION_DISMISS) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
show(intent)
|
||||
}
|
||||
|
||||
/** Tapped from a stale notification, or handled while this window was away. */
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
val current = alert
|
||||
if (current != null && !notifier.isShowing(current)) finish()
|
||||
}
|
||||
|
||||
private fun show(intent: Intent) {
|
||||
val next = ReminderActionReceiver.alertFrom(intent)
|
||||
if (next == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
alert = next
|
||||
// A ring still going, this one's or another's, keeps the screen up as long as it rings.
|
||||
val ringing = alerts.ringing != null
|
||||
keepScreenOn(if (ringing) ReminderRingService.RING_TIMEOUT_MILLIS else ONCE_SCREEN_ON_MILLIS)
|
||||
loading?.cancel()
|
||||
state = ReminderAlertUiState.Loading
|
||||
loading = lifecycleScope.launch {
|
||||
val calendar = try {
|
||||
withContext(io) { calendarDataSource.calendars().firstOrNull { it.id == next.calendarId } }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The alert still shows, only without its calendar.
|
||||
Log.w(TAG, "Could not read the calendar of event ${next.eventId}", e)
|
||||
null
|
||||
}
|
||||
state = ReminderAlertUiState.Showing(
|
||||
title = next.title,
|
||||
time = notifier.timeText(next),
|
||||
location = next.location?.takeIf { it.isNotBlank() },
|
||||
calendarName = calendar?.displayName,
|
||||
calendarColor = calendar?.color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** An alert nobody answers lets the display sleep again; it stays on the lock screen. */
|
||||
private fun keepScreenOn(millis: Long) {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
screenOn?.cancel()
|
||||
screenOn = lifecycleScope.launch {
|
||||
delay(millis)
|
||||
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
}
|
||||
}
|
||||
|
||||
private fun act(action: String) {
|
||||
val current = alert ?: return
|
||||
sendBroadcast(ReminderActionReceiver.intent(this, action, current))
|
||||
finish()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ReminderAlertActivity"
|
||||
private const val ONCE_SCREEN_ON_MILLIS = 60_000L
|
||||
|
||||
fun intent(context: Context, alert: ReminderAlert): Intent =
|
||||
Intent(context, ReminderAlertActivity::class.java)
|
||||
.setData("calendula://reminder-alert/${alert.key}".toUri())
|
||||
.putAlert(alert)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION)
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.reminders
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Event
|
||||
import androidx.compose.material.icons.outlined.LocationOn
|
||||
import androidx.compose.material.icons.outlined.Snooze
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventFill
|
||||
import de.jeanlucmakiola.calendula.ui.common.eventInk
|
||||
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||
import de.jeanlucmakiola.floret.ring.RingBadge
|
||||
|
||||
/**
|
||||
* The alert itself, after the incoming-call screen: the calendar's pulsing
|
||||
* badge, what and when in the middle, and the two ways out at the bottom,
|
||||
* large enough to hit half awake.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ReminderAlertScreen(
|
||||
state: ReminderAlertUiState.Showing,
|
||||
onSnooze: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.safeDrawingPadding()
|
||||
.padding(horizontal = 24.dp, vertical = 32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
// Centred, but scrolls rather than pushing the buttons off a short landscape screen.
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.heightIn(min = maxHeight),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
state.calendarName?.let {
|
||||
Text(
|
||||
text = it,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.size(24.dp))
|
||||
}
|
||||
CalendarBadge(state.calendarColor)
|
||||
Spacer(Modifier.size(32.dp))
|
||||
Text(
|
||||
text = state.title.ifBlank { stringResource(R.string.event_untitled) },
|
||||
style = MaterialTheme.typography.displaySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
textAlign = TextAlign.Center,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.size(12.dp))
|
||||
Text(
|
||||
text = state.time,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
state.location?.let { location ->
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.LocationOn,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.size(4.dp))
|
||||
Text(
|
||||
text = location,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.size(24.dp))
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
AlertButton(
|
||||
label = stringResource(R.string.reminder_action_dismiss),
|
||||
icon = Icons.Rounded.Close,
|
||||
tonal = false,
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
AlertButton(
|
||||
label = stringResource(R.string.reminder_action_snooze),
|
||||
icon = Icons.Outlined.Snooze,
|
||||
tonal = true,
|
||||
onClick = onSnooze,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The calendar's colour as the badge fill, or the theme's primary container without one. */
|
||||
@Composable
|
||||
private fun CalendarBadge(color: Int?) {
|
||||
if (color == null) {
|
||||
RingBadge(icon = Icons.Outlined.Event, size = 120.dp)
|
||||
return
|
||||
}
|
||||
val fill = eventFill(color, LocalFloretDarkTheme.current, LocalSoftenColors.current)
|
||||
RingBadge(
|
||||
icon = Icons.Outlined.Event,
|
||||
containerColor = fill,
|
||||
contentColor = eventInk(fill, alpha = 1f),
|
||||
size = 120.dp,
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||
@Composable
|
||||
private fun AlertButton(
|
||||
label: String,
|
||||
icon: ImageVector,
|
||||
tonal: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val height = ButtonDefaults.LargeContainerHeight
|
||||
val content: @Composable () -> Unit = {
|
||||
Icon(icon, contentDescription = null, modifier = Modifier.size(ButtonDefaults.iconSizeFor(height)))
|
||||
Spacer(Modifier.size(ButtonDefaults.iconSpacingFor(height)))
|
||||
Text(label, style = ButtonDefaults.textStyleFor(height), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
val buttonModifier = modifier.heightIn(min = height)
|
||||
val padding = ButtonDefaults.contentPaddingFor(height)
|
||||
if (tonal) {
|
||||
FilledTonalButton(
|
||||
onClick = onClick,
|
||||
modifier = buttonModifier,
|
||||
shapes = ButtonDefaults.shapesFor(height),
|
||||
contentPadding = padding,
|
||||
) { content() }
|
||||
} else {
|
||||
Button(
|
||||
onClick = onClick,
|
||||
modifier = buttonModifier,
|
||||
shapes = ButtonDefaults.shapesFor(height),
|
||||
contentPadding = padding,
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.reminders
|
||||
|
||||
sealed interface ReminderAlertUiState {
|
||||
/** The calendar is still being read; the surface is already up. */
|
||||
data object Loading : ReminderAlertUiState
|
||||
|
||||
data class Showing(
|
||||
/** Raw title; blank shows as "(no title)". */
|
||||
val title: String,
|
||||
val time: String,
|
||||
val location: String?,
|
||||
/** Null when the calendar could not be read. */
|
||||
val calendarName: String?,
|
||||
val calendarColor: Int?,
|
||||
) : ReminderAlertUiState
|
||||
}
|
||||
-486
@@ -1,486 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.reminders.RING_CHANNEL_ID
|
||||
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.android.openNotificationSettings
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.positionOf
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
|
||||
import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings
|
||||
|
||||
/**
|
||||
* Per-calendar notifications and reminder overrides (#145, #272), reached from
|
||||
* Settings → Notifications. Calendars are listed by account as connected groups;
|
||||
* a calendar unfolds its options in place, one tone darker, inside its group.
|
||||
*/
|
||||
@Composable
|
||||
internal fun CalendarRemindersScreen(
|
||||
state: SettingsUiState,
|
||||
viewModel: SettingsViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
visible: Boolean = true,
|
||||
) {
|
||||
var expandedCalendars by rememberSaveable { mutableStateOf(emptyList<Long>()) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
var alertStylePicker by remember { mutableStateOf<Long?>(null) }
|
||||
var alertSoundPicker by remember { mutableStateOf<Long?>(null) }
|
||||
val canFullScreen = rememberCanUseFullScreenIntent()
|
||||
val context = LocalContext.current
|
||||
var fixedOverrideFor by remember { mutableStateOf<Long?>(null) }
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
onBack = onBack,
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
GroupedHint(stringResource(R.string.settings_calendar_reminders_hint), style = MaterialTheme.typography.bodySmall)
|
||||
state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group ->
|
||||
if (groupIndex > 0) Spacer(Modifier.height(8.dp))
|
||||
GroupedSectionHeader(accountGroupTitle(group))
|
||||
val calendars = group.calendars
|
||||
calendars.forEachIndexed { index, calendar ->
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
val notifying = calendar.id !in state.mutedReminderCalendarIds
|
||||
val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds
|
||||
CalendarReminderEntry(
|
||||
calendar = calendar,
|
||||
state = state,
|
||||
position = positionOf(index, calendars.size),
|
||||
expanded = expanded,
|
||||
notifying = notifying,
|
||||
blocked = blocked,
|
||||
heldBack = fullScreenHeldBack(
|
||||
style = state.reminderAlertStyles.alertStyleFor(calendar.id),
|
||||
notifying = notifying,
|
||||
blocked = blocked,
|
||||
ringBlocked = channelStatus.ringBlocked,
|
||||
canFullScreen = canFullScreen,
|
||||
),
|
||||
onToggleExpand = {
|
||||
expandedCalendars = if (expanded) {
|
||||
expandedCalendars - calendar.id
|
||||
} else {
|
||||
expandedCalendars + calendar.id
|
||||
}
|
||||
},
|
||||
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
|
||||
soundLabel = soundPicker.loadedSounds?.let { soundLabel(it[calendar.id]) },
|
||||
onPickSound = { soundPicker.pick(calendar.id) },
|
||||
onOpenSettings = { soundPicker.openCalendarSettings(calendar.id) },
|
||||
onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) },
|
||||
onEditAlertStyle = { alertStylePicker = calendar.id },
|
||||
onEditAlertSound = { alertSoundPicker = calendar.id },
|
||||
onAllowFullScreen = { context.openFullScreenIntentSettings() },
|
||||
onOpenSpecialDates = onOpenSpecialDates,
|
||||
onEditOverride = { overrideDialog = it },
|
||||
onEditFixedOverride = { fixedOverrideFor = calendar.id },
|
||||
onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
alertStylePicker?.let { calendarId ->
|
||||
val current = state.reminderAlertStyles.alertStyleFor(calendarId)
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.settings_alert_style),
|
||||
options = listOf(ReminderAlertStyle.Notification, ReminderAlertStyle.FullScreen),
|
||||
selected = if (current.isFullScreen) ReminderAlertStyle.FullScreen else ReminderAlertStyle.Notification,
|
||||
label = { alertStyleLabel(it) },
|
||||
summary = {
|
||||
stringResource(
|
||||
if (it.isFullScreen) {
|
||||
R.string.settings_alert_style_full_screen_summary
|
||||
} else {
|
||||
R.string.settings_alert_style_notification_summary
|
||||
},
|
||||
)
|
||||
},
|
||||
onSelect = { picked ->
|
||||
if (picked.isFullScreen != current.isFullScreen) {
|
||||
viewModel.setCalendarAlertStyle(calendarId, picked)
|
||||
// Guide the user straight to the switch Android 14+ may hold back.
|
||||
if (picked.isFullScreen && !canFullScreen) context.openFullScreenIntentSettings()
|
||||
}
|
||||
},
|
||||
onDismiss = { alertStylePicker = null },
|
||||
)
|
||||
}
|
||||
alertSoundPicker?.let { calendarId ->
|
||||
OptionPicker(
|
||||
title = stringResource(R.string.settings_alert_sound),
|
||||
options = listOf(ReminderAlertStyle.FullScreen, ReminderAlertStyle.FullScreenRing),
|
||||
selected = state.reminderAlertStyles.alertStyleFor(calendarId),
|
||||
label = { alertSoundLabel(it) },
|
||||
summary = {
|
||||
stringResource(
|
||||
if (it == ReminderAlertStyle.FullScreenRing) {
|
||||
R.string.settings_alert_sound_ring_summary
|
||||
} else {
|
||||
R.string.settings_alert_sound_once_summary
|
||||
},
|
||||
)
|
||||
},
|
||||
onSelect = { viewModel.setCalendarAlertStyle(calendarId, it) },
|
||||
onDismiss = { alertSoundPicker = null },
|
||||
)
|
||||
}
|
||||
fixedOverrideFor?.let { calendarId ->
|
||||
FixedTimeReminderPicker(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
selected = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendarId),
|
||||
onSelect = { viewModel.setCalendarFixedTimeReminderOverride(calendarId, it) },
|
||||
onDismiss = { fixedOverrideFor = null },
|
||||
inheritedLabel = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
|
||||
inherited = state.defaultFixedTimeReminder,
|
||||
)
|
||||
}
|
||||
overrideDialog?.let { target ->
|
||||
val map = if (target.isAllDay) {
|
||||
state.perCalendarAllDayReminderOverride
|
||||
} else {
|
||||
state.perCalendarReminderOverride
|
||||
}
|
||||
ReminderDefaultPicker(
|
||||
title = stringResource(
|
||||
if (target.isAllDay) {
|
||||
R.string.settings_default_reminder_allday
|
||||
} else {
|
||||
R.string.settings_default_reminder
|
||||
},
|
||||
),
|
||||
isAllDay = target.isAllDay,
|
||||
selected = map.reminderOverrideFor(target.calendarId),
|
||||
allowInherit = true,
|
||||
onSelect = {
|
||||
if (target.isAllDay) {
|
||||
viewModel.setCalendarAllDayReminderOverride(target.calendarId, it)
|
||||
} else {
|
||||
viewModel.setCalendarReminderOverride(target.calendarId, it)
|
||||
}
|
||||
},
|
||||
onDismiss = { overrideDialog = null },
|
||||
leadTimeSummary = if (target.isAllDay) {
|
||||
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One calendar in its account group, with its options unfolding beneath it:
|
||||
* the notification switch and channel deep-link for every calendar, then the
|
||||
* default-reminder overrides where it takes them — or, for a special-dates
|
||||
* calendar, a link to the section that owns them.
|
||||
*/
|
||||
@Composable
|
||||
private fun CalendarReminderEntry(
|
||||
calendar: CalendarSource,
|
||||
state: SettingsUiState,
|
||||
position: Position,
|
||||
expanded: Boolean,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
heldBack: FullScreenHeldBack,
|
||||
onToggleExpand: () -> Unit,
|
||||
onSetNotifying: (Boolean) -> Unit,
|
||||
soundLabel: String?,
|
||||
onPickSound: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenRingSettings: () -> Unit,
|
||||
onEditAlertStyle: () -> Unit,
|
||||
onEditAlertSound: () -> Unit,
|
||||
onAllowFullScreen: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
onEditFixedOverride: () -> Unit,
|
||||
onSetInDigest: (Boolean) -> Unit,
|
||||
) {
|
||||
val opensGroup = position == Position.Top || position == Position.Alone
|
||||
val closesGroup = position == Position.Bottom || position == Position.Alone
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = when {
|
||||
// Still in the summary, so only its reminders are off.
|
||||
!notifying && state.dailyDigest.enabled && calendar.id !in state.dailyDigest.excludedCalendarIds ->
|
||||
stringResource(R.string.settings_calendar_reminders_off)
|
||||
!notifying -> stringResource(R.string.settings_calendar_notifications_off)
|
||||
blocked -> stringResource(R.string.settings_notifications_blocked)
|
||||
heldBack.any -> stringResource(R.string.settings_full_screen_held_back)
|
||||
else -> null
|
||||
},
|
||||
position = when {
|
||||
!expanded -> position
|
||||
opensGroup -> Position.Top
|
||||
else -> Position.Middle
|
||||
},
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
onClick = onToggleExpand,
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
val managed = calendar.id in state.managedCalendarIds
|
||||
val takesOverrides = calendar.canModifyContents && !managed
|
||||
val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id)
|
||||
val digestOn = state.dailyDigest.enabled
|
||||
val nested = MaterialTheme.colorScheme.surfaceContainerHighest
|
||||
// The options round off their calendar; mid-group they keep the row gap.
|
||||
Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_notifications),
|
||||
checked = notifying,
|
||||
onCheckedChange = onSetNotifying,
|
||||
summary = stringResource(R.string.settings_calendar_notifications_hint),
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = soundLabel,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onClick = onPickSound,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_more),
|
||||
summary = if (blocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_calendar_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSettings,
|
||||
)
|
||||
val lastAlertRow = !(managed || takesOverrides || digestOn)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_alert_style),
|
||||
summary = alertStyleLabel(alertStyle),
|
||||
position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle,
|
||||
container = nested,
|
||||
onClick = onEditAlertStyle,
|
||||
)
|
||||
if (alertStyle.isFullScreen) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_alert_sound),
|
||||
summary = alertSoundLabel(alertStyle),
|
||||
position = if (lastAlertRow && !heldBack.any) Position.Bottom else Position.Middle,
|
||||
container = nested,
|
||||
onClick = onEditAlertSound,
|
||||
)
|
||||
}
|
||||
if (heldBack.ring) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_ring_channel_name),
|
||||
summary = stringResource(R.string.settings_ring_blocked_hint),
|
||||
position = if (lastAlertRow && !heldBack.permission) Position.Bottom else Position.Middle,
|
||||
container = nested,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenRingSettings,
|
||||
)
|
||||
}
|
||||
if (heldBack.permission) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_full_screen_permission),
|
||||
summary = stringResource(R.string.settings_full_screen_permission_hint),
|
||||
position = if (lastAlertRow) Position.Bottom else Position.Middle,
|
||||
container = nested,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onAllowFullScreen,
|
||||
)
|
||||
}
|
||||
if (digestOn) {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_in_digest),
|
||||
checked = calendar.id !in state.dailyDigest.excludedCalendarIds,
|
||||
onCheckedChange = onSetInDigest,
|
||||
summary = stringResource(R.string.settings_calendar_in_digest_hint),
|
||||
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
|
||||
container = nested,
|
||||
)
|
||||
}
|
||||
if (managed) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
trailing = { ChevronIcon() },
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
} else if (takesOverrides) {
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = false,
|
||||
choice = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultReminderMinutes,
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_fixed_reminder),
|
||||
summary = when (val fixed = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendar.id)) {
|
||||
FixedTimeOverride.Inherit -> stringResource(
|
||||
R.string.settings_calendar_reminder_inherits,
|
||||
fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
|
||||
)
|
||||
FixedTimeOverride.Off -> stringResource(R.string.reminder_none)
|
||||
is FixedTimeOverride.At -> fixedTimeReminderLabel(fixed.reminder)
|
||||
},
|
||||
position = Position.Middle,
|
||||
container = nested,
|
||||
onClick = onEditFixedOverride,
|
||||
)
|
||||
OverrideRow(
|
||||
calendarId = calendar.id,
|
||||
isAllDay = true,
|
||||
choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id),
|
||||
globalDefault = state.defaultAllDayReminderMinutes,
|
||||
position = Position.Bottom,
|
||||
container = nested,
|
||||
onEditOverride = onEditOverride,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OverrideRow(
|
||||
calendarId: Long,
|
||||
isAllDay: Boolean,
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
position: Position,
|
||||
container: Color,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
GroupedRow(
|
||||
title = stringResource(
|
||||
if (isAllDay) R.string.settings_default_reminder_allday else R.string.settings_default_reminder,
|
||||
),
|
||||
summary = calendarOverrideSummary(choice, globalDefault),
|
||||
position = position,
|
||||
container = container,
|
||||
onClick = { onEditOverride(OverrideTarget(calendarId, isAllDay)) },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChevronIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/** Which calendar + event kind a per-calendar reminder-override dialog targets. */
|
||||
private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean)
|
||||
|
||||
/** Row summary for a calendar: its override, or the inherited global default. */
|
||||
@Composable
|
||||
private fun calendarOverrideSummary(
|
||||
choice: ReminderOverride,
|
||||
globalDefault: List<Int>,
|
||||
): String = when (choice) {
|
||||
ReminderOverride.Inherit ->
|
||||
stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault))
|
||||
ReminderOverride.None -> stringResource(R.string.reminder_none)
|
||||
is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes)
|
||||
}
|
||||
|
||||
/** What keeps a full-screen calendar from alerting as chosen: the missing permission, or the blocked ring channel. */
|
||||
private data class FullScreenHeldBack(val permission: Boolean, val ring: Boolean) {
|
||||
val any: Boolean get() = permission || ring
|
||||
}
|
||||
|
||||
private fun fullScreenHeldBack(
|
||||
style: ReminderAlertStyle,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
ringBlocked: Boolean,
|
||||
canFullScreen: Boolean,
|
||||
): FullScreenHeldBack {
|
||||
val live = notifying && !blocked
|
||||
return FullScreenHeldBack(
|
||||
permission = live && style.isFullScreen && !canFullScreen,
|
||||
ring = live && style == ReminderAlertStyle.FullScreenRing && ringBlocked,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun alertStyleLabel(style: ReminderAlertStyle): String = stringResource(
|
||||
if (style.isFullScreen) R.string.settings_alert_style_full_screen else R.string.settings_alert_style_notification,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun alertSoundLabel(style: ReminderAlertStyle): String = stringResource(
|
||||
if (style == ReminderAlertStyle.FullScreenRing) R.string.settings_alert_sound_ring else R.string.settings_alert_sound_once,
|
||||
)
|
||||
|
||||
/** Whether Android lets full-screen alerts open, re-read on every `ON_RESUME`. */
|
||||
@Composable
|
||||
private fun rememberCanUseFullScreenIntent(): Boolean = rememberOnResume { it.canUseFullScreenIntent() }
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user