Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f181ae7ac9 | ||
|
|
04f3b7ec8f | ||
|
|
31ba82a295 | ||
|
|
99a584a82d | ||
|
|
2e71e4dc5f | ||
|
|
955dccff2b | ||
|
|
7361e8d98e | ||
|
|
9178828b41 | ||
|
|
0b6cdf992e | ||
|
|
014d31f9b9 | ||
|
|
4287862f47 | ||
|
|
6cf6a6fdbf | ||
|
|
d2b6637f72 | ||
|
|
0b223f53fc | ||
|
|
c52c6c54cc | ||
|
|
fa999f8cf0 | ||
|
|
515c7c3d26 | ||
|
|
9b5880b719 | ||
|
|
994fc1026f |
No files matched your search
@@ -177,12 +177,12 @@ 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)
|
||||
|
||||
@@ -41,10 +41,15 @@
|
||||
-->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
|
||||
<!-- WorkManager declares this for network constraints, which the app doesn't use (#448). -->
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" 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" />
|
||||
|
||||
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
||||
returns null and the calendar manager's per-account "manage" button can't
|
||||
@@ -322,6 +327,20 @@
|
||||
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"
|
||||
|
||||
@@ -1,198 +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.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.floret.backup.BackupDocument
|
||||
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||
import de.jeanlucmakiola.floret.backup.PrefsSection
|
||||
import de.jeanlucmakiola.floret.backup.invalidBackup
|
||||
import de.jeanlucmakiola.floret.backup.optBoolean
|
||||
import de.jeanlucmakiola.floret.backup.optIntList
|
||||
import de.jeanlucmakiola.floret.backup.optObject
|
||||
import de.jeanlucmakiola.floret.backup.optObjectList
|
||||
import de.jeanlucmakiola.floret.backup.optInt
|
||||
import de.jeanlucmakiola.floret.backup.optString
|
||||
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 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 ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys
|
||||
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],
|
||||
)
|
||||
}
|
||||
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))) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(),
|
||||
)
|
||||
}
|
||||
|
||||
/** 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"
|
||||
@@ -1,240 +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.apply(
|
||||
context = context,
|
||||
enabled = after[SettingsKeys.autoBackupEnabled],
|
||||
intervalMinutes = after[SettingsKeys.autoBackupIntervalMinutes],
|
||||
hasFolder = after[SettingsKeys.autoBackupFolderUri] != null,
|
||||
)
|
||||
}
|
||||
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,106 +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,
|
||||
SettingsKeys.defaultEventDurationMinutes,
|
||||
SettingsKeys.remindersEnabled,
|
||||
SettingsKeys.allowColorOnUnsupportedCalendars,
|
||||
SettingsKeys.defaultReminderMinutes,
|
||||
SettingsKeys.defaultAllDayReminderMinutes,
|
||||
SettingsKeys.allDayReminderTimeMinutes,
|
||||
SettingsKeys.snoozeMinutes,
|
||||
SettingsKeys.autoBackupEnabled,
|
||||
SettingsKeys.autoBackupIntervalMinutes,
|
||||
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,
|
||||
)
|
||||
|
||||
/** 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,
|
||||
// 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,
|
||||
// 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,214 +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.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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -28,9 +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)
|
||||
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(HIDDEN_IDS, ids)
|
||||
|
||||
/**
|
||||
* Switch-offs the provider does not know about yet, because writing
|
||||
@@ -41,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 }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,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() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,30 +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)
|
||||
|
||||
}
|
||||
|
||||
/** 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")
|
||||
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. */
|
||||
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||
internal 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,7 +2,6 @@ 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 javax.inject.Inject
|
||||
@@ -24,13 +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 key [ReminderStatePrefs] stores. */
|
||||
internal object ReminderStateKeys {
|
||||
val lastScanMillis: Pref<Long?> = nullableLongPref("reminder_last_scan_millis")
|
||||
private companion object {
|
||||
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import androidx.datastore.preferences.core.Preferences
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
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.ui.agenda.AgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.storageValue
|
||||
@@ -166,6 +169,9 @@ class SettingsPrefs @Inject constructor(
|
||||
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
|
||||
val perCalendarEventDuration: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarEventDuration)
|
||||
val remindersEnabled: Flow<Boolean> = prefs.flow(SettingsKeys.remindersEnabled)
|
||||
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 allowColorOnUnsupportedCalendars: Flow<Boolean> =
|
||||
prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars)
|
||||
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
|
||||
@@ -273,6 +279,16 @@ class SettingsPrefs @Inject constructor(
|
||||
|
||||
suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled)
|
||||
|
||||
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)
|
||||
|
||||
@@ -594,6 +610,22 @@ object SettingsKeys {
|
||||
*/
|
||||
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)
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+20
-11
@@ -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 and our own [ReminderSnoozeScheduler]
|
||||
* alarm), so the receiver is not exported.
|
||||
* intents (notification action buttons, the full-screen alert's 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,6 +74,9 @@ 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"
|
||||
@@ -94,16 +97,21 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
Intent(context, ReminderActionReceiver::class.java).apply {
|
||||
this.action = action
|
||||
data = "calendula://reminder/${identity(alert, action)}".toUri()
|
||||
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)
|
||||
putAlert(alert)
|
||||
}
|
||||
|
||||
/** 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;
|
||||
@@ -115,6 +123,7 @@ 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
|
||||
@@ -123,7 +132,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
||||
private fun identity(alert: ReminderAlert, action: String): Long =
|
||||
if (action == ACTION_SHOW) alert.occurrenceKey else alert.key
|
||||
|
||||
private fun alertFrom(intent: Intent): ReminderAlert? {
|
||||
fun alertFrom(intent: Intent): ReminderAlert? {
|
||||
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
|
||||
return ReminderAlert(
|
||||
key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L),
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
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"
|
||||
|
||||
/** The notification channel [calendarId]'s reminders post on. */
|
||||
fun reminderChannelId(calendarId: Long): String = CHANNEL_PREFIX + calendarId
|
||||
|
||||
/** 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>,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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,
|
||||
): 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 channels = calendars.map { calendar ->
|
||||
ReminderChannelSpec(
|
||||
id = reminderChannelId(calendar.id),
|
||||
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 existingById = existing.associateBy { it.id }
|
||||
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 }
|
||||
return ReminderChannelPlan(
|
||||
groups = groups,
|
||||
channels = channels,
|
||||
channelsToWrite = toWrite,
|
||||
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||
staleChannelIds = existingById.keys.filter { isReminderChannelId(it) && it !in wantedChannels },
|
||||
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups },
|
||||
)
|
||||
}
|
||||
|
||||
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>,
|
||||
): ReminderChannelStatus {
|
||||
val groupBlocked = calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.groupId in blockedGroupIds }
|
||||
val blocked = if (!appEnabled) {
|
||||
calendarIds.toSet()
|
||||
} else {
|
||||
calendarIds.filterTo(HashSet()) { channels[reminderChannelId(it)]?.blocked == true } + groupBlocked
|
||||
}
|
||||
return ReminderChannelStatus(
|
||||
appBlocked = !appEnabled,
|
||||
blockedCalendarIds = blocked,
|
||||
groupBlockedCalendarIds = groupBlocked,
|
||||
ringBlocked = appEnabled && channels[RING_CHANNEL_ID]?.blocked == true,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationChannelGroup
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
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.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||
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.
|
||||
*/
|
||||
@Singleton
|
||||
class ReminderChannels @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
) {
|
||||
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 }
|
||||
if (syncKey(calendars, existingIds) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||
val groups = manager.notificationChannelGroups
|
||||
val plan = plan(calendars, existing, groups.map { it.id })
|
||||
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 }
|
||||
lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids)
|
||||
}
|
||||
|
||||
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>): Any = listOf(
|
||||
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||
Locale.getDefault(),
|
||||
channelIds,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 id = reminderChannelId(calendarId)
|
||||
val manager = manager
|
||||
if (manager.getNotificationChannel(id) != null) return id
|
||||
val existing = manager.notificationChannels
|
||||
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())
|
||||
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
|
||||
}
|
||||
|
||||
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||
val manager = manager
|
||||
val appEnabled = manager.areNotificationsEnabled()
|
||||
val channels = manager.notificationChannels.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)
|
||||
}
|
||||
|
||||
private fun plan(
|
||||
calendars: List<CalendarSource>,
|
||||
existing: List<NotificationChannel>,
|
||||
existingGroupIds: List<String>,
|
||||
): 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),
|
||||
)
|
||||
|
||||
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 the old single channel's sound, vibration, lights and badge over to
|
||||
* a new per-calendar one (the system resets lock-screen visibility itself), so an upgrade keeps how reminders sounded.
|
||||
*/
|
||||
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 = runCatching {
|
||||
manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "Could not read active notifications", e)
|
||||
true
|
||||
}
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
@@ -18,7 +17,11 @@ 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 kotlinx.coroutines.flow.first
|
||||
import kotlinx.datetime.isoDayNumber
|
||||
import java.time.DayOfWeek
|
||||
@@ -29,8 +32,9 @@ import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||
* the event's detail screen.
|
||||
* 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.
|
||||
*
|
||||
* 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
|
||||
@@ -43,6 +47,8 @@ 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. */
|
||||
@@ -53,20 +59,96 @@ class ReminderNotifier @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* 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].
|
||||
* 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).
|
||||
*/
|
||||
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||
|
||||
/** Post [alert], unless its calendar is switched off. */
|
||||
suspend fun post(alert: ReminderAlert) {
|
||||
/**
|
||||
* 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) {
|
||||
if (isSilenced(alert.calendarId)) return
|
||||
ensureChannel()
|
||||
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
|
||||
val channelId = channelFor(alert, style)
|
||||
// The ring channel could not be made: still full-screen, sounding once.
|
||||
?: if (style == ReminderAlertStyle.FullScreenRing) {
|
||||
style = ReminderAlertStyle.FullScreen
|
||||
channelFor(alert, style) ?: return
|
||||
} else {
|
||||
return
|
||||
}
|
||||
val title = displayTitle(alert)
|
||||
val text = contentText(alert)
|
||||
if (style == ReminderAlertStyle.FullScreenRing) {
|
||||
if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, 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
|
||||
}
|
||||
// Android refused the ring: still full-screen, sounding once on the calendar's channel.
|
||||
stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||
val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return
|
||||
notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet = false))
|
||||
return
|
||||
}
|
||||
// A fresh reminder replaces a ring for its occurrence from before the style changed.
|
||||
if (ring) stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||
notify(alert, build(alert, channelId, title, text, style, quiet))
|
||||
}
|
||||
|
||||
/** 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()
|
||||
@@ -74,7 +156,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)
|
||||
val time = reminderTimeText(
|
||||
return reminderTimeText(
|
||||
beginMillis = alert.beginMillis,
|
||||
endMillis = alert.endMillis,
|
||||
isAllDay = alert.isAllDay,
|
||||
@@ -87,19 +169,35 @@ class ReminderNotifier @Inject constructor(
|
||||
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||
)
|
||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setWhen(alert.beginMillis)
|
||||
.setShowWhen(false)
|
||||
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setAutoCancel(true)
|
||||
.setOnlyAlertOnce(shownKey(alert) == alert.key)
|
||||
.setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT)
|
||||
.setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH)
|
||||
.addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) })
|
||||
.setContentIntent(detailIntent(alert))
|
||||
.setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert))
|
||||
.addAction(
|
||||
R.drawable.ic_notification_snooze,
|
||||
context.getString(R.string.reminder_action_snooze),
|
||||
@@ -110,7 +208,18 @@ class ReminderNotifier @Inject constructor(
|
||||
context.getString(R.string.reminder_action_dismiss),
|
||||
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
||||
)
|
||||
.build()
|
||||
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) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
cancelLegacy(alert)
|
||||
try {
|
||||
@@ -131,10 +240,25 @@ 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 = shownKey(alert).let { it != null && it != alert.key }
|
||||
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
|
||||
|
||||
/** The key of the reminder showing for [alert]'s occurrence, if any. */
|
||||
private fun shownKey(alert: ReminderAlert): Long? {
|
||||
@@ -153,7 +277,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 == CHANNEL_ID }
|
||||
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_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) }
|
||||
@@ -171,6 +295,13 @@ 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.
|
||||
@@ -181,21 +312,8 @@ class ReminderNotifier @Inject constructor(
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ class ReminderScanner @Inject constructor(
|
||||
private val source: ReminderInstanceSource,
|
||||
private val calendarDataSource: CalendarDataSource,
|
||||
private val notifier: ReminderNotifier,
|
||||
private val channels: ReminderChannels,
|
||||
private val snoozes: ReminderSnoozeScheduler,
|
||||
private val alarms: ReminderAlarmScheduler,
|
||||
private val state: ReminderStatePrefs,
|
||||
@@ -85,10 +86,14 @@ class ReminderScanner @Inject constructor(
|
||||
return
|
||||
}
|
||||
|
||||
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 })
|
||||
@@ -117,6 +122,19 @@ class ReminderScanner @Inject constructor(
|
||||
alarms.scheduleScan(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)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
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}" }
|
||||
@@ -10,7 +10,6 @@ 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
|
||||
@@ -77,9 +76,7 @@ private val RESTORE_MIME_TYPES = arrayOf(
|
||||
|
||||
/**
|
||||
* Backup & restore (#69): `.ics` export and restore for local calendars, 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.
|
||||
* 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.
|
||||
@@ -90,7 +87,6 @@ fun BackupScreen(
|
||||
onImport: (Uri) -> Unit,
|
||||
visible: Boolean = true,
|
||||
viewModel: CalendarsViewModel = hiltViewModel(),
|
||||
settingsBackup: SettingsBackupViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.backupState.collectAsStateWithLifecycle()
|
||||
val backupResult by viewModel.backupResult.collectAsStateWithLifecycle()
|
||||
@@ -136,27 +132,20 @@ 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,
|
||||
@@ -169,7 +158,6 @@ fun BackupScreen(
|
||||
},
|
||||
onExportPick = { showExportPicker = true },
|
||||
onEditInterval = { showInterval = true },
|
||||
settings = settings,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -185,7 +173,6 @@ fun BackupScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
SettingsBackupDialogs(settings, settingsBackup, snackbarHostState)
|
||||
if (showInterval) {
|
||||
BackupIntervalDialog(
|
||||
currentMinutes = autoBackup.intervalMinutes,
|
||||
@@ -195,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() {
|
||||
@@ -234,7 +213,6 @@ private fun BackupContent(
|
||||
onExportAll: () -> Unit,
|
||||
onExportPick: () -> Unit,
|
||||
onEditInterval: () -> Unit,
|
||||
settings: SettingsBackupActions,
|
||||
) {
|
||||
val manageCalendars = LocalManageCalendars.current
|
||||
// Restore never depends on export eligibility, and never disappears: when no
|
||||
@@ -255,7 +233,6 @@ private fun BackupContent(
|
||||
leading = { LeadingAvatar(Icons.Default.FileUpload) },
|
||||
onClick = onRestoreClick,
|
||||
)
|
||||
SettingsBackupSection(settings)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -300,7 +277,6 @@ private fun BackupContent(
|
||||
)
|
||||
GroupedHint(backupStatusText(autoBackup.status), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
SettingsBackupSection(settings)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -457,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
|
||||
@@ -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,5 +1,6 @@
|
||||
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
|
||||
@@ -72,11 +73,13 @@ fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||
@Composable
|
||||
fun sourceAppName(accountType: String): String {
|
||||
val context = LocalContext.current
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
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))
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
AlertButton(
|
||||
label = stringResource(R.string.reminder_action_snooze),
|
||||
icon = Icons.Outlined.Snooze,
|
||||
tonal = true,
|
||||
onClick = onSnooze,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
AlertButton(
|
||||
label = stringResource(R.string.reminder_action_dismiss),
|
||||
icon = Icons.Rounded.Close,
|
||||
tonal = false,
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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
|
||||
}
|
||||
+327
-56
@@ -9,28 +9,39 @@ import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
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.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
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.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.DurationPicker
|
||||
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
|
||||
@@ -39,17 +50,23 @@ import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
|
||||
import de.jeanlucmakiola.calendula.ui.common.durationLabel
|
||||
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||
import de.jeanlucmakiola.floret.android.hasPermission
|
||||
import de.jeanlucmakiola.floret.android.openNotificationSettings
|
||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||
import de.jeanlucmakiola.floret.components.ExpandIcon
|
||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
|
||||
import de.jeanlucmakiola.floret.components.IconInfoCard
|
||||
import de.jeanlucmakiola.floret.components.OptionPicker
|
||||
import de.jeanlucmakiola.floret.components.Position
|
||||
import de.jeanlucmakiola.floret.components.SelectedCheck
|
||||
import de.jeanlucmakiola.floret.identity.collapseExit
|
||||
import de.jeanlucmakiola.floret.identity.expandEnter
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
|
||||
import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings
|
||||
import de.jeanlucmakiola.floret.reminders.minutesOrEmpty
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.datetime.LocalTime
|
||||
|
||||
/**
|
||||
@@ -84,8 +101,21 @@ internal fun NotificationsScreen(
|
||||
var showAllDayReminderTime by remember { mutableStateOf(false) }
|
||||
var showSnooze by remember { mutableStateOf(false) }
|
||||
var overrideDialog by remember { mutableStateOf<OverrideTarget?>(null) }
|
||||
var alertStylePicker by remember { mutableStateOf<Long?>(null) }
|
||||
var alertSoundPicker by remember { mutableStateOf<Long?>(null) }
|
||||
val canFullScreen = rememberCanUseFullScreenIntent()
|
||||
var calendarSectionExpanded by remember { mutableStateOf(false) }
|
||||
var expandedCalendars by remember { mutableStateOf(emptySet<Long>()) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
|
||||
val calendarIds = state.reminderCalendars.map { it.id }
|
||||
LifecycleResumeEffect(calendarIds) {
|
||||
viewModel.refreshChannelStatus(calendarIds)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
val openCalendarSound: (Long) -> Unit = { calendarId ->
|
||||
scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) }
|
||||
}
|
||||
|
||||
CollapsingScaffold(
|
||||
title = stringResource(R.string.settings_section_notifications),
|
||||
@@ -93,6 +123,19 @@ internal fun NotificationsScreen(
|
||||
predictiveBack = true,
|
||||
visible = visible,
|
||||
) {
|
||||
if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) {
|
||||
NotificationCategoryHint(
|
||||
onOpen = {
|
||||
viewModel.dismissNotificationCategoryHint()
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
},
|
||||
onDismiss = viewModel::dismissNotificationCategoryHint,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_reminders),
|
||||
checked = state.remindersEnabled,
|
||||
@@ -100,6 +143,22 @@ internal fun NotificationsScreen(
|
||||
summary = stringResource(R.string.settings_reminders_hint),
|
||||
position = Position.Top,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = if (channelStatus.appBlocked) {
|
||||
stringResource(R.string.settings_notifications_blocked_hint)
|
||||
} else {
|
||||
stringResource(R.string.settings_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = {
|
||||
scope.launch {
|
||||
viewModel.syncReminderChannels()
|
||||
context.openNotificationSettings()
|
||||
}
|
||||
},
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = reminderChoiceLabel(state.defaultReminderMinutes),
|
||||
@@ -149,10 +208,8 @@ internal fun NotificationsScreen(
|
||||
onClick = { showSnooze = true },
|
||||
)
|
||||
|
||||
// Per-calendar overrides, folded behind one header. Each writable
|
||||
// calendar may keep, drop or replace the global default, separately for
|
||||
// timed and all-day events.
|
||||
if (state.writableCalendars.isNotEmpty()) {
|
||||
// Per-calendar notifications and reminder overrides (#145, #272).
|
||||
if (state.reminderCalendars.isNotEmpty()) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_calendar_reminders_title),
|
||||
@@ -167,30 +224,26 @@ internal fun NotificationsScreen(
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
state.writableCalendars.forEach { calendar ->
|
||||
state.reminderCalendars.forEach { calendar ->
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// Special-dates calendars own their reminders in their
|
||||
// own section — link there instead.
|
||||
if (calendar.id in state.managedCalendarIds) {
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
return@forEach
|
||||
}
|
||||
val expanded = calendar.id in expandedCalendars
|
||||
val notifying = calendar.id !in state.mutedReminderCalendarIds
|
||||
val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds
|
||||
val heldBack = fullScreenHeldBack(
|
||||
style = state.reminderAlertStyles.alertStyleFor(calendar.id),
|
||||
notifying = notifying,
|
||||
blocked = blocked,
|
||||
ringBlocked = channelStatus.ringBlocked,
|
||||
canFullScreen = canFullScreen,
|
||||
)
|
||||
GroupedRow(
|
||||
title = calendar.displayName.orUnnamed(),
|
||||
summary = when {
|
||||
!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 = if (expanded) Position.Top else Position.Alone,
|
||||
leading = { CalendarColorChip(calendar.color) },
|
||||
trailing = { ExpandIcon(expanded) },
|
||||
@@ -207,22 +260,21 @@ internal fun NotificationsScreen(
|
||||
enter = expandEnter(),
|
||||
exit = collapseExit(),
|
||||
) {
|
||||
Column {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) },
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) },
|
||||
)
|
||||
}
|
||||
CalendarNotificationRows(
|
||||
calendar = calendar,
|
||||
state = state,
|
||||
notifying = notifying,
|
||||
blocked = blocked,
|
||||
heldBack = heldBack,
|
||||
onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) },
|
||||
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
|
||||
onOpenSound = { openCalendarSound(calendar.id) },
|
||||
onEditAlertStyle = { alertStylePicker = calendar.id },
|
||||
onEditAlertSound = { alertSoundPicker = calendar.id },
|
||||
onAllowFullScreen = { context.openFullScreenIntentSettings() },
|
||||
onOpenSpecialDates = onOpenSpecialDates,
|
||||
onEditOverride = { overrideDialog = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -230,6 +282,51 @@ internal fun NotificationsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
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 },
|
||||
)
|
||||
}
|
||||
if (showSnooze) {
|
||||
DurationPicker(
|
||||
title = stringResource(R.string.settings_snooze_duration),
|
||||
@@ -309,6 +406,149 @@ internal fun NotificationsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One calendar's expanded rows: its 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 CalendarNotificationRows(
|
||||
calendar: CalendarSource,
|
||||
state: SettingsUiState,
|
||||
notifying: Boolean,
|
||||
blocked: Boolean,
|
||||
heldBack: FullScreenHeldBack,
|
||||
onOpenRingSettings: () -> Unit,
|
||||
onSetNotifying: (Boolean) -> Unit,
|
||||
onOpenSound: () -> Unit,
|
||||
onEditAlertStyle: () -> Unit,
|
||||
onEditAlertSound: () -> Unit,
|
||||
onAllowFullScreen: () -> Unit,
|
||||
onOpenSpecialDates: () -> Unit,
|
||||
onEditOverride: (OverrideTarget) -> Unit,
|
||||
) {
|
||||
val managed = calendar.id in state.managedCalendarIds
|
||||
val takesOverrides = calendar.canModifyContents && !managed
|
||||
val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id)
|
||||
val needsPermission = heldBack.permission
|
||||
val ringHeldBack = heldBack.ring
|
||||
Column {
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_calendar_notifications),
|
||||
checked = notifying,
|
||||
onCheckedChange = onSetNotifying,
|
||||
summary = stringResource(R.string.settings_calendar_notifications_hint),
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_notification_sound),
|
||||
summary = when {
|
||||
blocked -> stringResource(R.string.settings_notifications_blocked_hint)
|
||||
alertStyle == ReminderAlertStyle.FullScreenRing ->
|
||||
stringResource(R.string.settings_calendar_notification_sound_ring_hint)
|
||||
else -> stringResource(R.string.settings_calendar_notification_sound_hint)
|
||||
},
|
||||
position = Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenSound,
|
||||
)
|
||||
val lastAlertRow = !(managed || takesOverrides)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_alert_style),
|
||||
summary = alertStyleLabel(alertStyle),
|
||||
position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle,
|
||||
onClick = onEditAlertStyle,
|
||||
)
|
||||
if (alertStyle.isFullScreen) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_alert_sound),
|
||||
summary = alertSoundLabel(alertStyle),
|
||||
position = if (lastAlertRow && !needsPermission && !ringHeldBack) Position.Bottom else Position.Middle,
|
||||
onClick = onEditAlertSound,
|
||||
)
|
||||
}
|
||||
if (ringHeldBack) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.reminder_ring_channel_name),
|
||||
summary = stringResource(R.string.settings_ring_blocked_hint),
|
||||
position = if (lastAlertRow && !needsPermission) Position.Bottom else Position.Middle,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onOpenRingSettings,
|
||||
)
|
||||
}
|
||||
if (needsPermission) {
|
||||
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,
|
||||
trailing = { ExternalLinkIcon() },
|
||||
onClick = onAllowFullScreen,
|
||||
)
|
||||
}
|
||||
if (managed) {
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
|
||||
position = Position.Bottom,
|
||||
trailing = {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
onClick = onOpenSpecialDates,
|
||||
)
|
||||
} else if (takesOverrides) {
|
||||
val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder),
|
||||
summary = calendarOverrideSummary(timed, state.defaultReminderMinutes),
|
||||
position = Position.Middle,
|
||||
onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = false)) },
|
||||
)
|
||||
val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_default_reminder_allday),
|
||||
summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes),
|
||||
position = Position.Bottom,
|
||||
onClick = { onEditOverride(OverrideTarget(calendar.id, isAllDay = true)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Samsung's One UI can start a new notification category switched off (#145). */
|
||||
private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
|
||||
/** The one-time Samsung note, with a way into the app's notification settings. */
|
||||
@Composable
|
||||
private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) {
|
||||
IconInfoCard(
|
||||
icon = Icons.Outlined.Info,
|
||||
iconContentDescription = null,
|
||||
iconAlignment = Alignment.Top,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_notification_category_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) }
|
||||
TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ExternalLinkIcon() {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
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)
|
||||
|
||||
@@ -328,6 +568,39 @@ private fun calendarOverrideSummary(
|
||||
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` like [rememberBatteryOptimizationExempt]. */
|
||||
@Composable
|
||||
private fun rememberCanUseFullScreenIntent(): Boolean = rememberOnResume { it.canUseFullScreenIntent() }
|
||||
|
||||
/** Snooze delays offered for the notification "Snooze" action, in minutes. */
|
||||
private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
||||
|
||||
@@ -336,20 +609,18 @@ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
||||
* `ON_RESUME` so a change made in system settings shows up at once.
|
||||
*/
|
||||
@Composable
|
||||
private fun rememberBatteryOptimizationExempt(): Boolean {
|
||||
private fun rememberBatteryOptimizationExempt(): Boolean = rememberOnResume(::isIgnoringBatteryOptimizations)
|
||||
|
||||
/** [read], re-read on every `ON_RESUME` so a change made in system settings shows up at once. */
|
||||
@Composable
|
||||
private fun rememberOnResume(read: (Context) -> Boolean): Boolean {
|
||||
val context = LocalContext.current
|
||||
var exempt by remember { mutableStateOf(isIgnoringBatteryOptimizations(context)) }
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
exempt = isIgnoringBatteryOptimizations(context)
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
var value by remember { mutableStateOf(read(context)) }
|
||||
LifecycleResumeEffect(context) {
|
||||
value = read(context)
|
||||
onPauseOrDispose {}
|
||||
}
|
||||
return exempt
|
||||
return value
|
||||
}
|
||||
|
||||
private fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.jeanlucmakiola.calendula.ui.settings
|
||||
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -96,8 +97,16 @@ data class SettingsUiState(
|
||||
val perCalendarReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */
|
||||
val perCalendarAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
||||
/** Writable calendars, shown as per-calendar reminder-override rows. */
|
||||
/** Switched-on calendars you can edit: the per-calendar event-duration rows. */
|
||||
val writableCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Switched-on calendars, each with its own notification switch and channel (#145, #272). */
|
||||
val reminderCalendars: List<CalendarSource> = emptyList(),
|
||||
/** Calendars whose reminders Calendula doesn't post (#272). */
|
||||
val mutedReminderCalendarIds: Set<Long> = emptySet(),
|
||||
/** Per-calendar alert styles (#171); absent means a plain notification. */
|
||||
val reminderAlertStyles: Map<Long, ReminderAlertStyle> = emptyMap(),
|
||||
/** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */
|
||||
val notificationCategoryHintDismissed: Boolean = true,
|
||||
/**
|
||||
* Whether the event-colour picker is offered on calendars that publish no
|
||||
* colour palette (the colour may then not survive their next sync).
|
||||
|
||||
@@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.settings
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -20,6 +21,7 @@ import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||
@@ -33,8 +35,13 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
|
||||
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier
|
||||
import de.jeanlucmakiola.calendula.data.reminders.RingMatch
|
||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
@@ -45,7 +52,9 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale
|
||||
import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle
|
||||
import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -62,11 +71,14 @@ import javax.inject.Inject
|
||||
@HiltViewModel
|
||||
class SettingsViewModel @Inject constructor(
|
||||
private val prefs: SettingsPrefs,
|
||||
calendarPrefs: CalendarPrefs,
|
||||
repository: CalendarRepository,
|
||||
private val specialDatesEngine: SpecialDatesSyncEngine,
|
||||
specialDatesSpec: SpecialDatesCalendarSpec,
|
||||
private val launcherNameManager: LauncherNameManager,
|
||||
private val reminderScanner: ReminderScanner,
|
||||
private val reminderChannels: ReminderChannels,
|
||||
private val reminderNotifier: ReminderNotifier,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
@ApplicationContext private val appContext: Context,
|
||||
) : ViewModel() {
|
||||
@@ -74,16 +86,16 @@ class SettingsViewModel @Inject constructor(
|
||||
private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
|
||||
/**
|
||||
* Writable calendars that are switched on — the only ones that take a
|
||||
* per-calendar reminder override, since a switched-off one plans no
|
||||
* reminders at all (#75).
|
||||
* Calendars that are switched on — the only ones that plan reminders at
|
||||
* all (#75), so the only ones with notification settings.
|
||||
*/
|
||||
private val writableCalendars: Flow<List<CalendarSource>> = repository.calendars()
|
||||
.map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } }
|
||||
.catch { emit(emptyList()) }
|
||||
private val visibleCalendars: Flow<List<CalendarSource>> =
|
||||
combine(repository.calendars(), calendarPrefs.pendingDisabledCalendarIds) { calendars, pending ->
|
||||
calendars.filter { it.isVisibleInSystem && it.id !in pending }
|
||||
}.catch { emit(emptyList()) }
|
||||
|
||||
val state: StateFlow<SettingsUiState> =
|
||||
combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
combine(prefs.data, visibleCalendars) { stored, calendars -> stored.toUiState(calendars) }
|
||||
.stateWhileSubscribed(
|
||||
scope = viewModelScope,
|
||||
initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable),
|
||||
@@ -125,7 +137,11 @@ class SettingsViewModel @Inject constructor(
|
||||
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
|
||||
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
|
||||
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
|
||||
writableCalendars = calendars,
|
||||
writableCalendars = calendars.filter { it.canModifyContents },
|
||||
reminderCalendars = calendars,
|
||||
mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds],
|
||||
reminderAlertStyles = this[SettingsKeys.reminderAlertStyles],
|
||||
notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed],
|
||||
allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars],
|
||||
managedCalendarIds = specialDatesCalendars.values.toSet(),
|
||||
)
|
||||
@@ -353,10 +369,87 @@ class SettingsViewModel @Inject constructor(
|
||||
fun setRemindersEnabled(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
prefs.setRemindersEnabled(enabled)
|
||||
if (!enabled) reminderNotifier.stopRing(RingMatch.Any)
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans, since a muted calendar armed no wake-up for its next reminder.
|
||||
* Unmuting scans once more before the write, so the watermark starts at the
|
||||
* unmute and nothing that came due while muted is replayed.
|
||||
*/
|
||||
fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
if (enabled) reminderScanner.scan()
|
||||
prefs.setCalendarRemindersEnabled(calendarId, enabled)
|
||||
if (!enabled) reminderNotifier.stopRing(RingMatch.Calendar(calendarId))
|
||||
reminderScanner.scan()
|
||||
}
|
||||
}
|
||||
|
||||
fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) {
|
||||
viewModelScope.launch {
|
||||
prefs.setCalendarAlertStyle(calendarId, style)
|
||||
// Up front, so it can be checked in system settings before the first ring.
|
||||
if (style == ReminderAlertStyle.FullScreenRing) {
|
||||
onChannels { ensureRingChannel() }
|
||||
refreshChannelStatus(state.value.reminderCalendars.map { it.id })
|
||||
}
|
||||
// A ring for it goes quiet but stays in the shade.
|
||||
if (style != ReminderAlertStyle.FullScreenRing) {
|
||||
reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val _channelStatus = MutableStateFlow(ReminderChannelStatus())
|
||||
|
||||
/** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */
|
||||
val channelStatus: StateFlow<ReminderChannelStatus> = _channelStatus.asStateFlow()
|
||||
|
||||
private var channelStatusJob: Job? = null
|
||||
|
||||
fun refreshChannelStatus(calendarIds: Collection<Long>) {
|
||||
channelStatusJob?.cancel()
|
||||
channelStatusJob = viewModelScope.launch {
|
||||
onChannels { status(calendarIds) }?.let { _channelStatus.value = it }
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() }
|
||||
|
||||
/**
|
||||
* The channel whose system screen to open for [calendarId] (#340), created
|
||||
* if needed; null when only the app's own screen can help — the app or the
|
||||
* calendar's account group is blocked there, or the channel couldn't be made.
|
||||
*/
|
||||
suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels {
|
||||
val channelId = channelFor(calendarId) ?: return@onChannels null
|
||||
val status = status(listOf(calendarId))
|
||||
channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds }
|
||||
}
|
||||
|
||||
/** Create the per-calendar channels before showing the app's channel list, even with reminders off. */
|
||||
suspend fun syncReminderChannels() {
|
||||
val ringing = state.value.reminderAlertStyles.containsValue(ReminderAlertStyle.FullScreenRing)
|
||||
onChannels {
|
||||
sync()
|
||||
if (ringing) ensureRingChannel()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> onChannels(block: ReminderChannels.() -> T): T? = withContext(io) {
|
||||
try {
|
||||
reminderChannels.block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w("SettingsViewModel", "Reminder channel update failed", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) }
|
||||
|
||||
fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) }
|
||||
|
||||
@@ -376,6 +376,8 @@
|
||||
<string name="reminder_onboarding_skip_button">Not now</string>
|
||||
<string name="reminder_action_snooze">Snooze</string>
|
||||
<string name="reminder_action_dismiss">Dismiss</string>
|
||||
<string name="reminder_ring_channel_name">Ringing reminders</string>
|
||||
<string name="reminder_ring_channel_description">Full-screen reminders that ring until you dismiss them. Calendula plays their sound itself.</string>
|
||||
<!-- Day context prefix in a reminder for an event on another day (v2.15.0) -->
|
||||
<string name="reminder_day_today">Today</string>
|
||||
<string name="reminder_day_tomorrow">Tomorrow</string>
|
||||
@@ -731,7 +733,32 @@
|
||||
<string name="reminder_custom_amount">Amount</string>
|
||||
<string name="reminder_custom_set">Set</string>
|
||||
<string name="settings_calendar_reminders_title">Per-calendar reminders</string>
|
||||
<string name="settings_calendar_reminders_hint">Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own.</string>
|
||||
<string name="settings_calendar_reminders_hint">Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit.</string>
|
||||
<string name="settings_calendar_notifications">Notifications</string>
|
||||
<string name="settings_calendar_notifications_hint">Notify at this calendar\'s reminder times</string>
|
||||
<string name="settings_calendar_notifications_off">Notifications off</string>
|
||||
<string name="settings_notification_sound">Notification sound</string>
|
||||
<string name="settings_notification_sound_hint">Sound, vibration and pop-ups for each calendar, in system settings</string>
|
||||
<string name="settings_notifications_blocked">Blocked in system settings</string>
|
||||
<string name="settings_notifications_blocked_hint">Blocked in system settings — tap to allow</string>
|
||||
<string name="settings_notification_category_hint">On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on.</string>
|
||||
<string name="settings_notification_category_hint_open">Open settings</string>
|
||||
<string name="settings_calendar_notification_sound_hint">Sound, vibration and pop-ups for this calendar, in system settings</string>
|
||||
<string name="settings_alert_style">Alert style</string>
|
||||
<string name="settings_alert_style_notification">Notification</string>
|
||||
<string name="settings_alert_style_notification_summary">A notification that pops up and waits in the shade</string>
|
||||
<string name="settings_alert_style_full_screen">Full-screen alert</string>
|
||||
<string name="settings_alert_style_full_screen_summary">Fills the screen, even on the lock screen, until you dismiss or snooze it</string>
|
||||
<string name="settings_alert_sound">Full-screen sound</string>
|
||||
<string name="settings_alert_sound_once">Play sound once</string>
|
||||
<string name="settings_alert_sound_once_summary">This calendar\'s notification sound, once</string>
|
||||
<string name="settings_alert_sound_ring">Ring until dismissed</string>
|
||||
<string name="settings_alert_sound_ring_summary">Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound</string>
|
||||
<string name="settings_calendar_notification_sound_ring_hint">Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade.</string>
|
||||
<string name="settings_full_screen_held_back">Full-screen alerts held back</string>
|
||||
<string name="settings_ring_blocked_hint">Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow</string>
|
||||
<string name="settings_full_screen_permission">Allow full-screen alerts</string>
|
||||
<string name="settings_full_screen_permission_hint">Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them.</string>
|
||||
<string name="settings_calendar_reminder_inherits">Default (%1$s)</string>
|
||||
<string name="settings_reliable_delivery">Reliable delivery</string>
|
||||
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Calendula so they arrive on time.</string>
|
||||
@@ -910,41 +937,6 @@
|
||||
<item>Weeks</item>
|
||||
</string-array>
|
||||
<string name="calendars_backup_failed">Couldn\'t export the backup.</string>
|
||||
<string name="settings_backup_header">Settings</string>
|
||||
<string name="settings_backup_hint">Save Calendula\'s settings to a file and restore them after reinstalling or on a new phone. Events aren\'t part of it.</string>
|
||||
<string name="settings_backup_export">Export settings</string>
|
||||
<string name="settings_backup_export_summary">Save every setting to a .json file</string>
|
||||
<string name="settings_backup_import">Import settings</string>
|
||||
<string name="settings_backup_import_summary">Replace the current settings with a saved file</string>
|
||||
<string name="settings_backup_export_done">Settings exported.</string>
|
||||
<string name="settings_backup_export_failed">Couldn\'t export the settings.</string>
|
||||
<string name="settings_backup_import_confirm_title">Replace your settings?</string>
|
||||
<string name="settings_backup_import_confirm_message">Every setting is replaced with the one in the file. Your events and calendars stay as they are, apart from contact special dates, which follow the imported setting.</string>
|
||||
<string name="settings_backup_import_confirm_action">Replace</string>
|
||||
<string name="settings_backup_import_failed_not_backup">That file isn\'t a Calendula settings backup.</string>
|
||||
<string name="settings_backup_import_failed_newer">That backup is from a newer Calendula. Update the app to import it.</string>
|
||||
<string name="settings_backup_import_failed_invalid">That settings backup is damaged and wasn\'t imported.</string>
|
||||
<string name="settings_backup_import_failed_too_large">That file is too large to be a settings backup.</string>
|
||||
<string name="settings_backup_import_failed_unreadable">Couldn\'t read that file.</string>
|
||||
<string name="settings_backup_import_failed">Couldn\'t import the settings.</string>
|
||||
<string name="settings_backup_imported_title">Settings imported</string>
|
||||
<string name="settings_backup_imported_body">Your settings now match the ones in the file.</string>
|
||||
<plurals name="settings_backup_imported_calendars">
|
||||
<item quantity="one">Calendar settings were applied to %d calendar.</item>
|
||||
<item quantity="other">Calendar settings were applied to %d calendars.</item>
|
||||
</plurals>
|
||||
<string name="settings_backup_imported_skipped">Not imported</string>
|
||||
<!-- %1$s: calendar name, %2$s: its account -->
|
||||
<string name="settings_backup_skipped_calendar">%1$s (%2$s): no matching calendar on this phone</string>
|
||||
<!-- %1$s: calendar name, %2$s: its account -->
|
||||
<string name="settings_backup_skipped_calendar_ambiguous">%1$s (%2$s): more than one calendar on this phone has that name</string>
|
||||
<string name="settings_backup_skipped_calendars_unavailable">Calendar settings: Calendula can\'t read your calendars, so they were left as they are</string>
|
||||
<string name="settings_backup_skipped_font_headings">Custom headings font: choose the font file again</string>
|
||||
<string name="settings_backup_skipped_font_body">Custom body font: choose the font file again</string>
|
||||
<string name="settings_backup_skipped_special_dates">Contact special dates: turn them on again to allow access to contacts</string>
|
||||
<string name="settings_backup_skipped_auto_backup">Automatic backup: choose the backup folder again</string>
|
||||
<!-- %1$s: the language's name -->
|
||||
<string name="settings_backup_skipped_language">%1$s isn\'t available in this version</string>
|
||||
<plurals name="calendars_backup_done">
|
||||
<item quantity="one">Exported %d event.</item>
|
||||
<item quantity="other">Exported %d events.</item>
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
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.prefs.Pref
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/**
|
||||
* Every key of the settings store is either backed up or deliberately left
|
||||
* out. A new key fails here until [SettingsBackupSchema] says which.
|
||||
*/
|
||||
class SettingsBackupSchemaTest {
|
||||
|
||||
private val schema = SettingsBackupSchema
|
||||
|
||||
private fun keysOf(holder: Any): List<String> = holder.javaClass.declaredFields
|
||||
.filter { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.name != "INSTANCE" }
|
||||
.flatMap { field ->
|
||||
field.isAccessible = true
|
||||
when (val value = field.get(null)) {
|
||||
is Pref<*> -> listOf(value.name)
|
||||
is Map<*, *> -> value.values.filterIsInstance<Pref<*>>().map { it.name }
|
||||
else -> emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every stored key is classified`() {
|
||||
val stored = (keysOf(SettingsKeys) + keysOf(CalendarPrefKeys) + keysOf(ReminderStateKeys)).toSet()
|
||||
val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name }
|
||||
|
||||
assertThat(stored).isNotEmpty()
|
||||
assertThat(classified).containsAtLeastElementsIn(stored)
|
||||
assertThat(stored).containsAtLeastElementsIn(classified)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no key is classified twice`() {
|
||||
val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name }
|
||||
|
||||
assertThat(classified).containsNoDuplicates()
|
||||
}
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
package de.jeanlucmakiola.calendula.data.backup
|
||||
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.mutablePreferencesOf
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.data.appname.LauncherName
|
||||
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
|
||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||
import de.jeanlucmakiola.floret.backup.BackupProblem
|
||||
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||
import de.jeanlucmakiola.floret.prefs.get
|
||||
import de.jeanlucmakiola.floret.prefs.set
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SettingsBackupTest {
|
||||
|
||||
private fun calendar(id: Long, name: String, account: String = "me@example.org", managed: Boolean = false) =
|
||||
CalendarSource(
|
||||
id = id,
|
||||
displayName = name,
|
||||
accountName = account,
|
||||
accountType = "com.google",
|
||||
color = 0,
|
||||
isVisibleInSystem = true,
|
||||
isManaged = managed,
|
||||
)
|
||||
|
||||
private val work = calendar(1, "Work")
|
||||
private val home = calendar(2, "Home")
|
||||
private val birthdays = calendar(3, "Birthdays", account = "Calendula", managed = true)
|
||||
|
||||
private fun environment(
|
||||
calendars: List<CalendarSource>? = listOf(work, home, birthdays),
|
||||
managed: List<ManagedCalendarRow> = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
|
||||
contacts: Boolean = true,
|
||||
fonts: Set<FontRole> = emptySet(),
|
||||
folder: Boolean = false,
|
||||
languages: List<String> = listOf("de", "en-US", "fr"),
|
||||
) = ImportEnvironment(calendars, managed, contacts, fonts, folder, languages)
|
||||
|
||||
private fun roundTrip(source: MutablePreferences, calendars: List<CalendarSource> = listOf(work, home, birthdays)): SettingsBackup {
|
||||
val backup = buildSettingsBackup(
|
||||
snapshot = source,
|
||||
calendars = calendars,
|
||||
managed = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
|
||||
language = LanguageChoice("de"),
|
||||
launcherName = LauncherName.CALENDAR,
|
||||
)
|
||||
val decoded = decodeSettingsBackup(encodeSettingsBackup(backup, 1_700_000_000_000, "2.25.0"))
|
||||
return (decoded as BackupResult.Success).value
|
||||
}
|
||||
|
||||
private fun import(backup: SettingsBackup, current: MutablePreferences, env: ImportEnvironment = environment()) =
|
||||
planSettingsImport(backup, current, env).also { it.applyTo(current) }
|
||||
|
||||
@Test
|
||||
fun `plain settings survive the round trip`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.themeMode] = ThemeMode.BLACK
|
||||
source[SettingsKeys.multiDayCount] = 5
|
||||
source[SettingsKeys.defaultView] = CalendarView.Month
|
||||
source[SettingsKeys.defaultReminderMinutes] = listOf(10, 60)
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
import(roundTrip(source), target)
|
||||
|
||||
assertThat(target[SettingsKeys.themeMode]).isEqualTo(ThemeMode.BLACK)
|
||||
assertThat(target[SettingsKeys.multiDayCount]).isEqualTo(5)
|
||||
assertThat(target[SettingsKeys.defaultView]).isEqualTo(CalendarView.Month)
|
||||
assertThat(target[SettingsKeys.defaultReminderMinutes]).containsExactly(10, 60).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a setting the file leaves at its default resets here`() {
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.showWeekNumbers] = true
|
||||
|
||||
import(roundTrip(mutablePreferencesOf()), target)
|
||||
|
||||
assertThat(target[SettingsKeys.showWeekNumbers]).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `device state is neither exported nor touched`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.autoBackupFolderUri] = "content://tree/backup"
|
||||
source[SettingsKeys.recentTimeZones] = listOf("Europe/Berlin")
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.autoBackupLastRun] = 42L
|
||||
|
||||
val backup = roundTrip(source)
|
||||
import(backup, target)
|
||||
|
||||
assertThat(backup.prefs.keys.map { it.name }).doesNotContain("auto_backup_folder_uri")
|
||||
assertThat(target[SettingsKeys.autoBackupFolderUri]).isNull()
|
||||
assertThat(target[SettingsKeys.autoBackupLastRun]).isEqualTo(42L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `per-calendar settings follow the calendar to its new id`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
|
||||
source[CalendarPrefKeys.lastUsedCalendarId] = 2L
|
||||
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
|
||||
source[SettingsKeys.perCalendarReminderOverride] = mapOf(2L to emptyList())
|
||||
val moved = listOf(calendar(11, "Work"), calendar(12, "Home"))
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(roundTrip(source), target, environment(calendars = moved, managed = emptyList()))
|
||||
|
||||
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).containsExactly(11L)
|
||||
assertThat(target[CalendarPrefKeys.lastUsedCalendarId]).isEqualTo(12L)
|
||||
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(11L, 30)
|
||||
assertThat(target[SettingsKeys.perCalendarReminderOverride]).containsExactly(12L, emptyList<Int>())
|
||||
assertThat(plan.calendars).hasSize(2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a calendar missing here is reported, and its old id is not reused`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 45)
|
||||
|
||||
val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(1, "Other"))))
|
||||
|
||||
assertThat(target[SettingsKeys.perCalendarEventDuration]).isEmpty()
|
||||
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two calendars with the same name and account match neither`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(5, "Work"), calendar(6, "Work"))))
|
||||
|
||||
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
|
||||
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every per-calendar key travels with its calendar`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
|
||||
source[CalendarPrefKeys.lastUsedCalendarId] = 1L
|
||||
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
|
||||
source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5))
|
||||
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0))
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList()))
|
||||
|
||||
// One assertion per key in the schema: a new per-calendar key fails here until it is carried.
|
||||
SettingsBackupSchema.perCalendar.forEach { pref ->
|
||||
assertThat(target.asMap().keys.map { it.name }).contains(pref.name)
|
||||
}
|
||||
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a mirror type the import switches off is left out`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.specialDatesEnabled] = true
|
||||
source[SettingsKeys.specialDateTypeEnabled.getValue(SpecialDateType.Birthday)] = false
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(roundTrip(source), target)
|
||||
|
||||
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
|
||||
assertThat(plan.pendingSpecialDates).isEmpty()
|
||||
assertThat(plan.skipped).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an out-of-range calendar length is clamped, not refused`() {
|
||||
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
|
||||
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":5000}]}"""
|
||||
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
import(backup, target)
|
||||
|
||||
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unreadable calendars leave the per-calendar settings alone`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.perCalendarEventDuration] = mapOf(4L to 45)
|
||||
|
||||
val plan = import(roundTrip(source), target, environment(calendars = null))
|
||||
|
||||
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(4L, 45)
|
||||
assertThat(plan.skipped).containsExactly(SkippedSetting.CalendarsUnavailable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mirror calendars are left out when the import turns the mirror off`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(roundTrip(source), target)
|
||||
|
||||
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
|
||||
assertThat(plan.pendingSpecialDates).isEmpty()
|
||||
assertThat(plan.skipped).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a stale id in the prefs is dropped on export`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L, 99L)
|
||||
|
||||
assertThat(roundTrip(source).calendars.map { it.calendar.displayName }).containsExactly("Work")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a mirror calendar is matched by its date type`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.specialDatesEnabled] = true
|
||||
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0, 10080))
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val renamed = listOf(calendar(7, "Geburtstage", account = "Calendula", managed = true))
|
||||
import(roundTrip(source), target, environment(calendars = renamed, managed = listOf(ManagedCalendarRow(7, SpecialDateType.Birthday))))
|
||||
|
||||
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(7L, listOf(0, 10080))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a mirror calendar that doesn't exist yet waits for the sync`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.specialDatesEnabled] = true
|
||||
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0))
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(roundTrip(source), target, environment(managed = emptyList()))
|
||||
plan.pendingSpecialDates.forEach { target.addCalendarSettings(8L, it) }
|
||||
|
||||
assertThat(plan.skipped).isEmpty()
|
||||
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(8L, listOf(0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a custom font without its file keeps the current font`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.brandFont] = FONT_CUSTOM_TOKEN
|
||||
source[SettingsKeys.plainFont] = FONT_CUSTOM_TOKEN
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.brandFont] = "lora"
|
||||
|
||||
val plan = import(roundTrip(source), target, environment(fonts = setOf(FontRole.PLAIN)))
|
||||
|
||||
assertThat(target[SettingsKeys.brandFont]).isEqualTo("lora")
|
||||
assertThat(target[SettingsKeys.plainFont]).isEqualTo(FONT_CUSTOM_TOKEN)
|
||||
assertThat(plan.skipped).containsExactly(SkippedSetting.CustomFont(FontRole.BRAND))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `contact dates without the permission stay as they are`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.specialDatesEnabled] = true
|
||||
val target = mutablePreferencesOf()
|
||||
|
||||
val plan = import(roundTrip(source), target, environment(contacts = false))
|
||||
|
||||
assertThat(target[SettingsKeys.specialDatesEnabled]).isFalse()
|
||||
assertThat(plan.skipped).contains(SkippedSetting.SpecialDates)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `automatic backup without a folder here stays off, its interval comes along`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.autoBackupEnabled] = true
|
||||
source[SettingsKeys.autoBackupIntervalMinutes] = 120L
|
||||
val target = mutablePreferencesOf()
|
||||
|
||||
val plan = import(roundTrip(source), target)
|
||||
|
||||
assertThat(target[SettingsKeys.autoBackupEnabled]).isFalse()
|
||||
assertThat(target[SettingsKeys.autoBackupIntervalMinutes]).isEqualTo(120L)
|
||||
assertThat(plan.skipped).contains(SkippedSetting.AutoBackupFolder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `automatic backup keeps going where a folder is already set`() {
|
||||
val source = mutablePreferencesOf()
|
||||
source[SettingsKeys.autoBackupEnabled] = true
|
||||
val target = mutablePreferencesOf()
|
||||
|
||||
import(roundTrip(source), target, environment(folder = true))
|
||||
|
||||
assertThat(target[SettingsKeys.autoBackupEnabled]).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the language resolves against what this build ships`() {
|
||||
val backup = roundTrip(mutablePreferencesOf())
|
||||
|
||||
assertThat(planSettingsImport(backup.copy(language = LanguageChoice("en-US")), mutablePreferencesOf(), environment()).language)
|
||||
.isEqualTo(LanguageChoice("en-US"))
|
||||
assertThat(planSettingsImport(backup.copy(language = LanguageChoice(null)), mutablePreferencesOf(), environment()).language)
|
||||
.isEqualTo(LanguageChoice(null))
|
||||
val missing = planSettingsImport(backup.copy(language = LanguageChoice("ja")), mutablePreferencesOf(), environment())
|
||||
assertThat(missing.language).isNull()
|
||||
assertThat(missing.skipped).containsExactly(SkippedSetting.Language("ja"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `app-level choices travel along`() {
|
||||
val backup = roundTrip(mutablePreferencesOf())
|
||||
|
||||
assertThat(backup.language).isEqualTo(LanguageChoice("de"))
|
||||
assertThat(backup.launcherName).isEqualTo(LauncherName.CALENDAR)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown fields from a later build are ignored`() {
|
||||
val text = """
|
||||
{"format":"calendula-settings","version":1,"exportedAt":1,"future":{"x":1},
|
||||
"settings":{"multi_day_count":4,"some_new_key":true},
|
||||
"calendars":[{"account_name":"a","account_type":"t","display_name":"d","colour":"red"}],
|
||||
"app":{"launcher_name":"SOMETHING_NEW"}}
|
||||
""".trimIndent()
|
||||
|
||||
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
|
||||
|
||||
assertThat(backup.prefs.values).containsExactly(4)
|
||||
assertThat(backup.calendars).hasSize(1)
|
||||
assertThat(backup.launcherName).isNull()
|
||||
assertThat(backup.language).isNull()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a malformed known field rejects the whole file`() {
|
||||
listOf(
|
||||
"""{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{"multi_day_count":"4"}}""",
|
||||
"""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a"}]}""",
|
||||
"""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a","account_type":"t","display_name":"d","reminders":["x"]}]}""",
|
||||
).forEach { text ->
|
||||
val result = decodeSettingsBackup(text) as BackupResult.Failure
|
||||
assertThat(result.problem).isEqualTo(BackupProblem.INVALID_DATA)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a file without its settings section is refused`() {
|
||||
val result = decodeSettingsBackup("""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[]}""")
|
||||
|
||||
assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.INVALID_DATA)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an import without per-calendar settings leaves no empty keys behind`() {
|
||||
val target = mutablePreferencesOf()
|
||||
target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
|
||||
|
||||
import(roundTrip(mutablePreferencesOf()), target)
|
||||
|
||||
SettingsBackupSchema.perCalendar.forEach { pref ->
|
||||
assertThat(target.asMap().keys.map { it.name }).doesNotContain(pref.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two file entries naming the same calendar are both skipped`() {
|
||||
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
|
||||
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","hidden":true},
|
||||
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":90}]}"""
|
||||
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
|
||||
|
||||
val target = mutablePreferencesOf()
|
||||
val plan = import(backup, target)
|
||||
|
||||
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
|
||||
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reminder lists are cleaned the way the setters store them`() {
|
||||
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
|
||||
{"account_name":"a","account_type":"t","display_name":"d","reminders":[60,-5,30,30]}]}"""
|
||||
|
||||
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
|
||||
|
||||
assertThat(backup.calendars.single().reminders).containsExactly(30, 60).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a newer schema is refused`() {
|
||||
val result = decodeSettingsBackup("""{"format":"calendula-settings","version":2,"exportedAt":1}""")
|
||||
|
||||
assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.NEWER_VERSION)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
|
||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
|
||||
@@ -601,6 +602,31 @@ class SettingsPrefsTest {
|
||||
assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calendar notifications default on and toggle per calendar`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty()
|
||||
prefs.setCalendarRemindersEnabled(7L, false)
|
||||
prefs.setCalendarRemindersEnabled(9L, false)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L)
|
||||
prefs.setCalendarRemindersEnabled(7L, true)
|
||||
assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calendar alert styles default to notifications and persist per calendar`(
|
||||
@TempDir tempDir: Path,
|
||||
) = runTest {
|
||||
val prefs = testSettings(tempDir)
|
||||
assertThat(prefs.reminderAlertStyles.first()).isEmpty()
|
||||
prefs.setCalendarAlertStyle(7L, ReminderAlertStyle.FullScreenRing)
|
||||
prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.FullScreen)
|
||||
prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.Notification)
|
||||
assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `garbage per-calendar duration entries are dropped, the rest survive`(
|
||||
@TempDir tempDir: Path,
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package de.jeanlucmakiola.calendula.data.reminders
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ReminderChannelPlanTest {
|
||||
|
||||
private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource(
|
||||
id = id,
|
||||
displayName = "Cal $id",
|
||||
accountName = account,
|
||||
accountType = type,
|
||||
color = 0,
|
||||
isVisibleInSystem = true,
|
||||
isLocal = local,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `one channel per calendar, grouped by account`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "com.google"),
|
||||
calendar(3, "dav", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(2)
|
||||
assertThat(plan.channels.map { it.id })
|
||||
.containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3))
|
||||
assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId)
|
||||
assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId)
|
||||
assertThat(plan.staleChannelIds).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `device calendars share one group`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "Calendula", "LOCAL", local = true),
|
||||
calendar(2, "Other", "LOCAL", local = true),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups).hasSize(1)
|
||||
assertThat(plan.groups.single().isLocal).isTrue()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `same account name under two types is ambiguous`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "me@example.org", "com.google"),
|
||||
calendar(2, "me@example.org", "bitfire.at.davdroid"),
|
||||
calendar(3, "work", "bitfire.at.davdroid"),
|
||||
),
|
||||
existing = emptyList(),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType })
|
||||
.containsExactly("com.google", "bitfire.at.davdroid")
|
||||
assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stale reminder channels and groups go, foreign ones stay`() {
|
||||
val current = calendar(1, "me@example.org", "com.google")
|
||||
fun plan(calendars: List<CalendarSource>, existing: List<String> = emptyList(), groups: List<String> = emptyList()) =
|
||||
planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC)
|
||||
val keptGroup = plan(listOf(current)).groups.single().id
|
||||
val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id
|
||||
val result = plan(
|
||||
calendars = listOf(current),
|
||||
existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"),
|
||||
groups = listOf(keptGroup, goneGroup, "other"),
|
||||
)
|
||||
assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9))
|
||||
assertThat(result.staleGroupIds).containsExactly(goneGroup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `only missing or renamed channels are written`() {
|
||||
val plan = planReminderChannels(
|
||||
calendars = listOf(
|
||||
calendar(1, "a", "com.google"),
|
||||
calendar(2, "a", "com.google"),
|
||||
calendar(3, "a", "com.google").copy(displayName = ""),
|
||||
calendar(4, "a", "com.google"),
|
||||
),
|
||||
existing = listOf(
|
||||
ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"),
|
||||
ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"),
|
||||
ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"),
|
||||
),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L)
|
||||
assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non-syncing calendars keep a channel but get none up front`() {
|
||||
val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false)
|
||||
val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC)
|
||||
assertThat(fresh.channelsToWrite).isEmpty()
|
||||
assertThat(fresh.groupsInUse).isEmpty()
|
||||
val posted = planReminderChannels(
|
||||
calendars = listOf(quiet),
|
||||
existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)),
|
||||
existingGroupIds = emptyList(),
|
||||
unnamed = "Unnamed",
|
||||
description = DESC,
|
||||
)
|
||||
assertThat(posted.staleChannelIds).isEmpty()
|
||||
assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L)
|
||||
assertThat(posted.groupsInUse).hasSize(1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blocked calendars follow app, channel and group`() {
|
||||
val channels = mapOf(
|
||||
reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"),
|
||||
reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"),
|
||||
reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"),
|
||||
)
|
||||
val ids = listOf(1L, 2L, 3L, 4L)
|
||||
val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2"))
|
||||
assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L)
|
||||
assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L)
|
||||
assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds)
|
||||
.containsExactly(1L)
|
||||
val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet())
|
||||
assertThat(appOff.appBlocked).isTrue()
|
||||
assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a switched-off ring channel is reported while the app may notify`() {
|
||||
val ringOff = mapOf(RING_CHANNEL_ID to ReminderChannelState(blocked = true, groupId = null))
|
||||
assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, ringOff, emptySet()).ringBlocked).isTrue()
|
||||
assertThat(reminderChannelStatus(listOf(1L), appEnabled = false, ringOff, emptySet()).ringBlocked).isFalse()
|
||||
assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, emptyMap(), emptySet()).ringBlocked).isFalse()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DESC = "Reminders"
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package de.jeanlucmakiola.calendula.domain.reminders
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ReminderAlertStyleTest {
|
||||
|
||||
@Test
|
||||
fun `styles round-trip through their stored form`() {
|
||||
val styles = mapOf(9L to ReminderAlertStyle.FullScreenRing, 3L to ReminderAlertStyle.FullScreen)
|
||||
|
||||
assertThat(parseAlertStyles(styles.toStoredAlertStyles())).isEqualTo(styles)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `plain notifications are not stored`() {
|
||||
val stored = mapOf(1L to ReminderAlertStyle.Notification, 2L to ReminderAlertStyle.FullScreen).toStoredAlertStyles()
|
||||
|
||||
assertThat(stored).isEqualTo("2=full_screen")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `garbled entries are dropped, the rest survive`() {
|
||||
assertThat(parseAlertStyles("x=full_screen;4=loud;5;6=full_screen_ring"))
|
||||
.containsExactly(6L, ReminderAlertStyle.FullScreenRing)
|
||||
assertThat(parseAlertStyles(null)).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a calendar without a style uses notifications`() {
|
||||
val styles = mapOf(1L to ReminderAlertStyle.FullScreen)
|
||||
|
||||
assertThat(styles.alertStyleFor(1L)).isEqualTo(ReminderAlertStyle.FullScreen)
|
||||
assertThat(styles.alertStyleFor(2L)).isEqualTo(ReminderAlertStyle.Notification)
|
||||
assertThat(ReminderAlertStyle.Notification.isFullScreen).isFalse()
|
||||
assertThat(ReminderAlertStyle.FullScreenRing.isFullScreen).isTrue()
|
||||
}
|
||||
}
|
||||
+46
-11
@@ -391,6 +391,52 @@ gate also covers a snooze re-shown from our own alarm after its calendar was
|
||||
switched off. The drawer's filter sheet (`CalendarPrefs.hiddenCalendarIds`) is a
|
||||
separate in-app declutter that never touches reminders.
|
||||
|
||||
**A channel per calendar (#145).** `ReminderChannels` keeps one notification
|
||||
channel per calendar, grouped by account (one that syncs no events only gets
|
||||
its channel once something posts on it), so a calendar can be
|
||||
muted or given its own sound in the system settings before it ever fires. Every
|
||||
scan with reminders on syncs them (skipped when nothing changed): missing
|
||||
channels are created, renamed ones updated, and channels of deleted calendars
|
||||
removed — but never on an empty snapshot, which is a provider hiccup more often
|
||||
than every calendar gone. Switched-off calendars keep theirs, so toggling one
|
||||
never cancels a showing reminder or loses its settings. `post` creates a missing
|
||||
channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and
|
||||
importance of the pre-#145 single `reminders` channel, which is deleted once
|
||||
nothing showing still sits on it. Settings → Notifications only deep-links into
|
||||
the system's channel screens (#340); the app never sets a sound itself. Separate
|
||||
from both, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar
|
||||
off switch (#272): the scan plans nothing for those calendars (so they arm no
|
||||
wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again
|
||||
for snoozes. The settings screen re-reads `ReminderChannels.status` on every
|
||||
resume and marks a calendar "Blocked in system settings" when the app, its
|
||||
channel or its account group is switched off there.
|
||||
|
||||
**Full-screen alerts (#171).** Settings → Notifications gives each calendar an
|
||||
alert style (`SettingsPrefs.reminderAlertStyles`): a plain notification, a
|
||||
full-screen alert that sounds once, or one that rings until handled. Only
|
||||
`ReminderNotifier.post` reads it, and `ReminderChannels.channelFor(id, style)`
|
||||
picks the channel. "Sound once" stays on the calendar's own channel, so its
|
||||
sound is still the one chosen in system settings, and adds a full-screen intent
|
||||
to `ReminderAlertActivity`. "Ring" starts `ReminderRingService`, which goes
|
||||
foreground on the shared silent `reminders_ring` channel and loops the alarm
|
||||
sound with vibration through floret-kit's `ring` module — the same player
|
||||
Clockula's alarms use. One reminder rings at a time; a newer one takes over and
|
||||
hands the older back to the shade quietly, as does a ring left unanswered for
|
||||
ten minutes, and switching the calendar away from ringing. Dismiss and Snooze,
|
||||
from the screen, the notification or a swipe, all go through
|
||||
`ReminderActionReceiver`, so the ring stops and the screen closes
|
||||
(`FullScreenAlerts`) however the reminder was handled. Starts and stops reach
|
||||
the service as commands, so a dismiss sent while a newer ring is on its way
|
||||
applies in order rather than killing it, and the service re-reads the settings
|
||||
once a ring arrives, so a style change or mute that raced a scan still wins. A
|
||||
blocked calendar, account group or ring channel never rings (Settings flags a
|
||||
blocked ring channel next to each ringing calendar, beside #145's blocked status), the tone pauses
|
||||
for a phone call, and a ring restarted after a process death only rings out
|
||||
what was left of its ten minutes. When Android 14+
|
||||
withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a
|
||||
heads-up; Settings shows a row leading to the system switch. When Android
|
||||
refuses the ring service, the reminder falls back to sounding once.
|
||||
|
||||
Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast.
|
||||
Keeping both would double-post wherever the provider works, and Etar's way out —
|
||||
a latch that disables its own scheduling once a real broadcast arrives — cannot
|
||||
@@ -492,17 +538,6 @@ one the calendar accepts. The single-event review form deliberately keeps no col
|
||||
first question is which calendar to use, and answering it clears the colour
|
||||
anyway.
|
||||
|
||||
## Settings backup
|
||||
|
||||
Backup & restore also exports the app's settings as versioned JSON (#481),
|
||||
with the envelope and the generic preference section from floret-kit's
|
||||
`core-backup`. Every stored key is either carried or deliberately left out
|
||||
(`SettingsBackupSchema`, enforced by a test); per-calendar settings travel
|
||||
under the calendar's account and name, since provider ids are per device. An
|
||||
import replaces rather than merges, in one DataStore edit, then re-runs what
|
||||
reads settings outside DataStore. Format and per-key decisions:
|
||||
docs/SETTINGS_BACKUP.md.
|
||||
|
||||
## Testing
|
||||
|
||||
JUnit 5 + Truth + Turbine on the JVM. The seams that make it work:
|
||||
|
||||
+2
-3
@@ -96,9 +96,8 @@ The settings screen contains links to the source code, the licence, the issue tr
|
||||
- `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing.
|
||||
- `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart.
|
||||
- `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting.
|
||||
- `WAKE_LOCK`, `FOREGROUND_SERVICE`, `ACCESS_NETWORK_STATE`: required by the Android system component used for scheduled background work (WorkManager).
|
||||
|
||||
`ACCESS_NETWORK_STATE` allows reading *whether* a network connection exists. It does **not** permit using one. Without `INTERNET`, no connection is possible.
|
||||
- `USE_FULL_SCREEN_INTENT`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`, `VIBRATE`: for calendars you set to full-screen alerts — showing the alert over the lock screen and, with “Ring until dismissed”, ringing and vibrating until you dismiss or snooze it.
|
||||
- `WAKE_LOCK`: keeps the phone awake while a full-screen alert rings, and lets the Android component that runs scheduled background work (WorkManager) finish it.
|
||||
|
||||
## 7. Distribution channels
|
||||
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
# Settings backup format
|
||||
|
||||
Backup & restore → Settings exports Calendula's settings to a JSON file and
|
||||
imports one back (#481). Events are not part of it; they have the `.ics`
|
||||
backup. This file is the schema's source of truth. The envelope and the
|
||||
`settings` section come from floret-kit's `core-backup`
|
||||
(`BackupFormat`, `PrefsSection`); `data/backup/SettingsBackup*.kt` implements
|
||||
the rest.
|
||||
|
||||
## Top level
|
||||
|
||||
```json
|
||||
{
|
||||
"format": "calendula-settings",
|
||||
"version": 1,
|
||||
"exportedAt": 1700000000000,
|
||||
"appVersion": "2.25.0",
|
||||
"settings": { … },
|
||||
"calendars": [ … ],
|
||||
"app": { … }
|
||||
}
|
||||
```
|
||||
|
||||
- `format` must be exactly `"calendula-settings"`, or the file is not a
|
||||
settings backup.
|
||||
- `version` is `1`. A higher version is refused as "from a newer Calendula";
|
||||
a change that an older build could misread bumps it.
|
||||
- `exportedAt` (epoch ms) and `appVersion` are informational.
|
||||
- The file is limited to 8 MiB; a leading byte-order mark is ignored.
|
||||
- The `settings` section is required: a file without it would reset every setting.
|
||||
|
||||
## Parsing rules
|
||||
|
||||
- **Unknown fields are ignored**, at any level, so a file from a later build
|
||||
imports as far as this one understands it.
|
||||
- **Known fields are strict.** A known key holding the wrong JSON type rejects
|
||||
the whole file before anything is written.
|
||||
- **Values are not range-checked.** They are stored as they are and go through
|
||||
the same reads every setting already does (clamps, enum fallbacks), so an
|
||||
out-of-range or unknown value degrades to the nearest valid one or the
|
||||
default.
|
||||
|
||||
## Import semantics
|
||||
|
||||
An import **replaces** every setting the backup covers; it does not merge. A
|
||||
backed-up setting the file doesn't carry is reset to its default (that is what
|
||||
the exporting install had). Everything is written in one DataStore edit. After
|
||||
that the import refreshes what reads settings outside DataStore: the
|
||||
contact-dates mirror (turned on and synced, or off and torn down, as the
|
||||
settings toggle does), the reminder scan, the automatic-backup schedule, the
|
||||
launcher name and the app language. Theme and widgets follow the stored
|
||||
values on their own. A summary lists what could not be imported.
|
||||
|
||||
## `settings`
|
||||
|
||||
The settings stored under their own on-disk key names, in their stored form,
|
||||
e.g. `"theme_mode": "DARK"`, `"multi_day_count": 4`,
|
||||
`"default_reminder_minutes": "10,60"`. Only keys that have been set are
|
||||
written. `SettingsBackupSchema.plain` lists them: appearance, fonts,
|
||||
views, the agenda screen, the event form, reminders, automatic backup
|
||||
(switch and interval) and contact special dates (switch, types, title
|
||||
templates, year).
|
||||
|
||||
Three are taken only where this device can honour them, otherwise the current
|
||||
value stays and the summary says why:
|
||||
|
||||
- `brand_font` / `plain_font` set to `custom`: the font file is not in the
|
||||
backup, so it is taken only if this install already has one for that role.
|
||||
- `special_dates_enabled` on: needs the contacts permission here.
|
||||
- `auto_backup_enabled` on: needs a backup folder chosen on this install.
|
||||
|
||||
## `calendars`
|
||||
|
||||
Per-calendar settings are stored by provider id, which means nothing on
|
||||
another device. Each calendar with any of them is written with a portable
|
||||
identity instead:
|
||||
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `account_name` | String | Required. |
|
||||
| `account_type` | String | Required. |
|
||||
| `display_name` | String | Required. |
|
||||
| `special_dates` | String? | `Birthday`/`Anniversary`/`Custom` for a contact-dates mirror calendar. |
|
||||
| `hidden` | Boolean | Hidden in the drawer's filter. |
|
||||
| `last_used` | Boolean | Preselected for new events. |
|
||||
| `event_duration_minutes` | Int? | Per-calendar default length, clamped to 1–1440 like the setting. |
|
||||
| `reminders` | Int[]? | Timed reminder override; `[]` is "no reminder". |
|
||||
| `all_day_reminders` | Int[]? | All-day reminder override. |
|
||||
|
||||
On import an entry matches the one calendar here with the same account name,
|
||||
account type and display name. No match, or more than one, skips it and the
|
||||
summary names it, as does a calendar the file itself lists twice under one
|
||||
identity. Reminder lists are stored the way the setters store them (no
|
||||
negative values, each once, ascending). A mirror calendar matches by `special_dates` instead, since
|
||||
its name is localised, and only when the imported settings keep the mirror on
|
||||
and the type (otherwise the import tears that calendar down). When the mirror has not created it yet,
|
||||
it is matched after the import's sync. Every mirror's all-day reminders are
|
||||
applied through the mirror so its existing events follow; one the file doesn't
|
||||
override inherits the default again. An id in the prefs whose calendar no
|
||||
longer exists is left out of the export.
|
||||
|
||||
If this device's calendars can't be read, the per-calendar settings here are
|
||||
left untouched and the summary says so; an export in that state fails rather
|
||||
than writing a file without them.
|
||||
|
||||
## `app`
|
||||
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `language` | String? | The app language tag; `null` follows the system. Absent: left as is. A language this build doesn't ship is skipped. |
|
||||
| `launcher_name` | String? | `CALENDULA` or `CALENDAR`. Unknown: left as is. |
|
||||
|
||||
## Not exported
|
||||
|
||||
`SettingsBackupSchema.excluded`, each for a reason: this install's own state,
|
||||
bookkeeping, or meaningless on another device.
|
||||
|
||||
- Font stamps (`*_font_stamp`): cache keys for the local font file.
|
||||
- `agenda_widget_range`, `widget_size`: legacy defaults for unconfigured
|
||||
widgets. Widget configuration is not part of the backup at all.
|
||||
- `recent_time_zones`: usage history.
|
||||
- Onboarding progress and `visibility_notice_pending`.
|
||||
- `auto_backup_folder_uri`: a SAF grant does not survive a reinstall or
|
||||
another device.
|
||||
- Run status: `auto_backup_last_*`, `auto_backup_failures`,
|
||||
`special_dates_last_run`, `special_dates_stalled_reason`,
|
||||
`special_dates_last_foreground_sync`.
|
||||
- `special_dates_calendar_*`: the mirror re-adopts its calendars by their
|
||||
provider marker.
|
||||
- `disabled_calendar_ids`: switch-offs not yet written to this device's
|
||||
provider. Whether a calendar is switched on lives in the provider.
|
||||
- `reminder_last_scan_millis`: the reminder delivery watermark.
|
||||
|
||||
`SettingsBackupSchemaTest` fails for any stored key that is in none of the
|
||||
three lists, so a new setting has to be placed before it ships.
|
||||
+1
-1
Submodule floret-kit updated: da7dbc3e04...2fc730dd44.
Reference in new issue
Block a user