Compare commits

...
34 Commits
Author SHA1 Message Date
makiolaj 7ee9abb7b0 docs(#550): publish signing cert fingerprint in README
Beta — Codeberg pre-release / detect (push) Successful in 3s
Beta — Codeberg pre-release / beta (push) Skipped
2026-12-02 20:12:54 +01:00
makiolaj 31fba6a986 Merge feat/389-flexible-days into release/2.26.0
Beta — Codeberg pre-release / detect (push) Successful in 3s
Beta — Codeberg pre-release / beta (push) Skipped
2026-12-02 18:21:33 +01:00
makiolaj 9fc48cbc97 Merge feat/166-calendar-groups into release/2.26.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt
2026-12-02 18:21:33 +01:00
makiolaj d340100dc0 Merge feat/199-custom-colours into release/2.26.0
# Conflicts:
#	floret-kit
2026-12-02 18:21:28 +01:00
makiolaj e8758e1e9a Merge feat/451-plain-icon into release/2.26.0 2026-12-02 18:21:11 +01:00
makiolaj a250b9dc67 Merge feat/524-date-tap-view into release/2.26.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/MainActivity.kt
2026-12-02 18:21:11 +01:00
makiolaj b070cfd74c Merge feat/520-monthly-weekday-position into release/2.26.0 2026-12-02 18:21:05 +01:00
makiolaj 49c8e2d75d Merge feat/541-per-calendar-allday-time into release/2.26.0 2026-12-02 18:21:05 +01:00
makiolaj 5b8285bb71 Merge feat/493-week-numbering-setting into release/2.26.0 2026-12-02 18:21:05 +01:00
makiolaj 7e3ab23f9b fix(#199): review - custom colour joins the recents on save 2026-12-02 18:10:47 +01:00
makiolaj 04671a607d fix(#451): review - restore always rewrites the launcher aliases 2026-12-02 18:10:03 +01:00
makiolaj 966de3011e fix(#520): review - realign on start change, keep DTSTART on unchanged rule, last weekday prefill 2026-12-02 18:10:02 +01:00
makiolaj a49de22d4d fix(#389): review - range pick stops at shown days, unclaimed pinch falls back to zoom 2026-12-02 18:09:44 +01:00
makiolaj 9560f230b8 fix(#166): review - group editor waits for the calendars before seeding members 2026-12-02 18:09:26 +01:00
makiolaj 40863ed126 fix(#493): review - live date in the numbering preview, pref round-trip test 2026-12-02 18:08:53 +01:00
Jean-Luc Makiola 9956adbc0c Merge pull request 'Clone submodules in Renovate' (#555) from chore/renovate-submodules into main
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 5s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 1m3s
Beta — Codeberg pre-release / detect (push) Successful in 3s
Beta — Codeberg pre-release / beta (push) Skipped
2026-12-02 17:34:29 +01:00
Jean-Luc Makiola dd28c9029b Merge pull request 'chore(deps): update gradle to v9.9.0' (#537) from renovate/gradle-9.x into main 2026-12-02 17:34:19 +01:00
makiolaj 21e58318f2 Clone submodules in Renovate so Gradle wrapper bumps are complete 2026-12-02 17:06:46 +01:00
makiolaj d5f79f07e5 Update the Gradle wrapper jar and checksum for 9.9.0 2026-12-02 17:04:21 +01:00
makiolaj 709bc24035 Start a pinch mid-resize from where it lands, clear the session day count on a Settings change (#389) 2026-11-30 22:12:39 +01:00
makiolaj 0eded5e4b0 Long press and drag in the month to open a run of days (#389) 2026-11-30 22:09:28 +01:00
makiolaj 713e9377db Pinch sideways to change the number of days shown (#389) 2026-11-30 22:04:47 +01:00
makiolaj f7329e45e3 Calendar groups first in the manager, switched-off calendars kept but not offered (#166) 2026-11-30 22:02:52 +01:00
makiolaj 32213d46f8 Take the preset palette from floret-kit (#198) 2026-11-30 21:58:36 +01:00
makiolaj 04281e79a7 Calendar groups in the drawer (#166) 2026-11-30 21:55:53 +01:00
makiolaj f0492cae3a Custom colour picker with recents, reshaped preset palette (#199, #198) 2026-11-30 21:52:43 +01:00
makiolaj e8e8338ba9 Label the default launcher icon Bloom (#451) 2026-11-30 21:44:20 +01:00
makiolaj 09f5a7c21a Free position and weekday choice for monthly repeats, move start onto the first match (#520) 2026-11-30 21:43:53 +01:00
makiolaj eeeb55988d Plain launcher icon option (#451) 2026-11-30 19:39:34 +01:00
makiolaj 5d45bb64f0 Setting for what other apps' date taps open (#524) 2026-11-30 19:38:16 +01:00
makiolaj 7fa30ab155 Monthly repeats by weekday position (#520) 2026-11-30 19:31:43 +01:00
makiolaj 80197bf6d9 Per-calendar all-day reminder time (#541) 2026-11-30 19:29:17 +01:00
makiolaj 70a20b07dc Week numbering setting: Automatic, ISO, US (#493) 2026-11-30 19:22:45 +01:00
renovate-bot 6daec632d8 chore(deps): update gradle to v9.9.0 2026-11-30 05:03:23 +00:00
89 changed files with 3873 additions and 468 deletions

No files matched your search

+14
View File
@@ -150,6 +150,20 @@ Play builds are signed with Google's key rather than mine, so switching between
Play and any other channel means uninstalling first. You lose the app settings.
Your events live in the system calendar and aren't affected.
### Verifying the APK
Every channel except Google Play ships APKs signed with the same key. The
official F-Droid build is reproducible and publishes that signed APK as-is.
SHA-256 of the signing certificate:
```
5cdaee8eb31cb0df9157c646ae3ec8b3dc43b5bb72624e088c9ddea0c4eb5ec1
```
Check it with `apksigner verify --print-certs calendula_vX.Y.Z.apk`. The
repository fingerprint above (`C2C0…3425`) belongs to the self-hosted repo's
index, not to the app.
### Build from source
It's a plain Gradle build with no proprietary dependencies. See
@@ -9,6 +9,7 @@ import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.toEditForm
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import kotlinx.datetime.TimeZone
import org.junit.Rule
import org.junit.Test
@@ -50,13 +51,13 @@ class MoveEventExceptionsTest {
try {
val src = insertSyncedSeries(a)
ds.deleteOccurrence(src, start + 2 * day)
val occurrence = ds.eventDetail(src, 540)!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
val occurrence = ds.eventDetail(src, AllDayReminderTimes(540))!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
ds.updateOccurrence(src, start + 3 * day, occurrence, occurrence.copy(title = "edited"), 540)
val expected = listOf("0:series", "1:series", "3:edited", "4:series")
assertThat(occurrences(a)).isEqualTo(expected)
val form = ds.eventDetail(src, 540)!!.toEditForm(start, start + hour, zone)
ds.moveEvent(src, b, form, form, 540)
val form = ds.eventDetail(src, AllDayReminderTimes(540))!!.toEditForm(start, start + hour, zone)
ds.moveEvent(src, b, form, form, AllDayReminderTimes(540))
assertThat(occurrences(a)).isEmpty()
assertThat(occurrences(b)).isEqualTo(expected)
+39 -7
View File
@@ -116,8 +116,8 @@
</intent-filter>
<!-- A launcher/clock date tap fires ACTION_VIEW on the provider's
time Uri (content://com.android.calendar/time/<epochMillis>);
some surfaces use the time/epoch mime type. We open the day view
on that date (MainActivity.calendarTimeDateOrNull). -->
some surfaces use the time/epoch mime type. We open the day view,
or the default view per setting, on that date (viewTimeRequest). -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
@@ -256,11 +256,11 @@
</activity>
<!-- Launcher entry for MainActivity, split into two aliases so the app's
launcher name can be switched at runtime between "Calendula" and
"Calendar" (issue #44). Exactly one is enabled at a time; the app
flips them via PackageManager.setComponentEnabledSetting
(LauncherNameManager). The shortcuts meta-data lives here, not on
<!-- Launcher entry for MainActivity: one alias per launcher name
("Calendula" / "Calendar", #44) x icon (bloom / plain, #451).
Exactly one is enabled at a time (LauncherManager). The first two
keep their pre-#451 names so existing launcher positions and pinned
shortcuts survive. The shortcuts meta-data lives here, not on
MainActivity, because static shortcuts are published by whichever
component owns the MAIN/LAUNCHER filter. -->
<activity-alias
@@ -295,6 +295,38 @@
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity-alias>
<activity-alias
android:name=".PlainIconAlias"
android:enabled="false"
android:exported="true"
android:icon="@mipmap/ic_launcher_plain"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_plain_round"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity-alias>
<activity-alias
android:name=".CalendarNamePlainIconAlias"
android:enabled="false"
android:exported="true"
android:icon="@mipmap/ic_launcher_plain"
android:label="@string/app_name_calendar_alias"
android:roundIcon="@mipmap/ic_launcher_plain_round"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity-alias>
<!-- Standalone surface for a captured crash report. MainActivity routes
here on a startup crash-loop, so it stays clear of the app's Hilt
@@ -49,7 +49,10 @@ import de.jeanlucmakiola.calendula.ui.common.LocalTimelineZoom
import de.jeanlucmakiola.calendula.ui.common.rememberTimelineZoom
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.LocalWeekNumbering
import de.jeanlucmakiola.calendula.ui.CALENDAR_PROVIDER_HOST
import de.jeanlucmakiola.calendula.ui.WidgetNavRequest
import de.jeanlucmakiola.calendula.ui.viewTimeRequest
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.detail.EventDetailViewModel.Companion.NO_OCCURRENCE_TIME
import de.jeanlucmakiola.calendula.ui.edit.ImportSource
@@ -73,9 +76,7 @@ import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant
import javax.inject.Inject
@AndroidEntryPoint
@@ -248,6 +249,7 @@ class MainActivity : AppCompatActivity() {
LocalTimelineZoom provides timelineZoom,
LocalMultiDayCount provides settings.multiDayCount,
LocalSoftenColors provides settings.softenColors,
LocalWeekNumbering provides settings.weekNumbering,
) {
RootScreen(
modifier = Modifier.fillMaxSize(),
@@ -473,26 +475,22 @@ class MainActivity : AppCompatActivity() {
}?.takeIf { it > 0 }
/**
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
* "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/
* <epochMillis>`. Null for any other intent. The matching manifest filter is
* what lets users pick Calendula from the system calendar chooser (issue #9).
* A launcher/clock date tap: the AOSP calendar "view time" intent. The
* matching manifest filter is what lets users pick Calendula from the system
* calendar chooser (issue #9). Our own daily summary speaks it too (#459).
*/
private fun Intent.calendarTimeDateOrNull(): LocalDate? {
if (action != Intent.ACTION_VIEW) return null
val uri = data ?: return null
if (uri.host != CALENDAR_PROVIDER_HOST) return null
val segments = uri.pathSegments
if (segments.firstOrNull() != "time") return null
val millis = segments.getOrNull(1)?.toLongOrNull() ?: return null
return Instant.fromEpochMilliseconds(millis)
.toLocalDateTime(TimeZone.currentSystemDefault()).date
}
private fun Intent.viewTimeRequestOrNull(): WidgetNavRequest.OpenDate? = viewTimeRequest(
action = action,
host = data?.host,
pathSegments = data?.pathSegments.orEmpty(),
zone = TimeZone.currentSystemDefault(),
ownDayTap = getBooleanExtra(EXTRA_OWN_DAY_TAP, false),
)
private fun Intent.navRequestOrNull(): WidgetNavRequest? {
// An external date tap (launcher/clock) opens the day view over the default
// home view, and backs out to it.
calendarTimeDateOrNull()?.let { return WidgetNavRequest.OpenDate(it.toString(), fromWidget = false) }
// An external date tap (launcher/clock) opens the day view or the default
// view on that date (#524), and backs out to the default view.
viewTimeRequestOrNull()?.let { return it }
// A widget header tap: open a top-level view with no date drill-in. The
// empty string carried by [openViewIntent] means "the default home view".
if (hasExtra(EXTRA_OPEN_VIEW)) {
@@ -590,9 +588,6 @@ class MainActivity : AppCompatActivity() {
}
companion object {
// The calendar provider's authority/host. A date tap arrives as
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
private const val SHARED_TEXT_TYPE = "text/plain"
private val CALENDAR_TYPES = setOf("text/calendar", "text/x-vcalendar", "application/ics")
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
@@ -608,6 +603,9 @@ class MainActivity : AppCompatActivity() {
private const val EXTRA_DATE_ISO = "de.jeanlucmakiola.calendula.extra.DATE_ISO"
private const val EXTRA_CREATE = "de.jeanlucmakiola.calendula.extra.CREATE"
// Marks the daily summary's own "view time" tap, which keeps the day view (#524).
private const val EXTRA_OWN_DAY_TAP = "de.jeanlucmakiola.calendula.extra.OWN_DAY_TAP"
// A widget header tap asking to open a top-level view (no date drill-in).
// Its value is the target [CalendarView] name, or "" for the default view.
private const val EXTRA_OPEN_VIEW = "de.jeanlucmakiola.calendula.extra.OPEN_VIEW"
@@ -677,6 +675,7 @@ class MainActivity : AppCompatActivity() {
.toEpochMilliseconds()
return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri())
.setClass(context, MainActivity::class.java)
.putExtra(EXTRA_OWN_DAY_TAP, true)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
@@ -1,109 +0,0 @@
package de.jeanlucmakiola.calendula.data.appname
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
/** The launcher label the app shows for itself (issue #44). */
enum class LauncherName { CALENDULA, CALENDAR }
/** The two launcher aliases declared in the manifest. */
enum class LauncherAlias { DEFAULT, CALENDAR }
/** One component-enable change in a [aliasWritePlan]. */
data class AliasStateChange(val alias: LauncherAlias, val enabled: Boolean)
/**
* Interpret the `CalendarNameAlias` component-enabled state as a [LauncherName].
* Only [PackageManager.COMPONENT_ENABLED_STATE_ENABLED] means the "Calendar"
* name is active; `DEFAULT` (never toggled) and `DISABLED` both resolve to the
* manifest default, "Calendula".
*/
fun launcherNameFor(calendarAliasState: Int): LauncherName =
if (calendarAliasState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
LauncherName.CALENDAR
} else {
LauncherName.CALENDULA
}
/**
* The ordered enable/disable steps to switch the launcher name to [target].
* Always **enables the target alias first, then disables the other** — the two
* `setComponentEnabledSetting` calls are not atomic, and this ordering means the
* only transient the launcher can observe is a harmless two-entry state, never a
* zero-entry one (which would briefly drop the app from the launcher).
*/
fun aliasWritePlan(target: LauncherName): List<AliasStateChange> = when (target) {
LauncherName.CALENDAR -> listOf(
AliasStateChange(LauncherAlias.CALENDAR, enabled = true),
AliasStateChange(LauncherAlias.DEFAULT, enabled = false),
)
LauncherName.CALENDULA -> listOf(
AliasStateChange(LauncherAlias.DEFAULT, enabled = true),
AliasStateChange(LauncherAlias.CALENDAR, enabled = false),
)
}
/**
* Switches the app's launcher label between "Calendula" and "Calendar" by
* enabling/disabling the two `<activity-alias>` components (issue #44). The
* component-enabled state is the single source of truth — there is no persisted
* preference — so [current] reads it straight from [PackageManager] and the two
* always agree.
*
* The decision logic lives in the pure [launcherNameFor] / [aliasWritePlan]
* functions above (JVM-tested); this class is only the thin framework seam.
*/
@Singleton
class LauncherNameManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
private val packageManager: PackageManager get() = context.packageManager
// The class portion is namespace-qualified (suffix-free), the package portion
// is the applicationId (which carries the .debug / .releasetest suffix). The
// manifest's ".CalendarNameAlias" resolves its class against the namespace, so
// the real component is <namespace>.CalendarNameAlias registered under the
// suffixed applicationId. Do NOT use ComponentName(context, ".CalendarNameAlias")
// — its leading-dot form prepends the applicationId to the class too, producing
// "<appId>.CalendarNameAlias" and failing on every debug / releaseTest build.
private fun component(alias: LauncherAlias): ComponentName {
val simpleName = when (alias) {
LauncherAlias.DEFAULT -> "DefaultNameAlias"
LauncherAlias.CALENDAR -> "CalendarNameAlias"
}
return ComponentName(context.packageName, "$NAMESPACE.$simpleName")
}
/** The launcher name currently in effect. */
fun current(): LauncherName =
launcherNameFor(packageManager.getComponentEnabledSetting(component(LauncherAlias.CALENDAR)))
/** Switch the launcher name to [name] (no-op cost if already active). */
fun set(name: LauncherName) {
for (change in aliasWritePlan(name)) {
val state = if (change.enabled) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
}
packageManager.setComponentEnabledSetting(
component(change.alias),
state,
PackageManager.DONT_KILL_APP,
)
}
}
private companion object {
/**
* The app's namespace (R-class package) — NOT `applicationId`, which
* carries the build-type suffix. Kept in sync with `namespace` in
* `app/build.gradle.kts`.
*/
const val NAMESPACE = "de.jeanlucmakiola.calendula"
}
}
@@ -1,11 +1,14 @@
package de.jeanlucmakiola.calendula.data.backup
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.calendula.data.appname.LauncherName
import de.jeanlucmakiola.calendula.data.launcher.LauncherEntry
import de.jeanlucmakiola.calendula.data.launcher.LauncherIcon
import de.jeanlucmakiola.calendula.data.launcher.LauncherName
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
@@ -54,6 +57,8 @@ data class CalendarSettings(
/** Timed reminder override; an empty list is "no reminder". */
val reminders: List<Int>? = null,
val allDayReminders: List<Int>? = null,
/** Its own all-day reminder time (#541), in minutes from midnight. */
val allDayReminderTimeMinutes: Int? = null,
/** The views it is hidden in only (#270). */
val hiddenInViews: Set<CalendarView> = emptySet(),
/** False when Calendula posts none of its reminders (#272). */
@@ -71,12 +76,13 @@ data class CalendarSettings(
/** 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. */
/** Everything a settings backup holds. Null [language]/[launcherName]/[launcherIcon]: 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,
val launcherIcon: LauncherIcon? = null,
)
internal val plainSection = PrefsSection(SettingsBackupSchema.plain)
@@ -91,13 +97,14 @@ fun buildSettingsBackup(
calendars: List<CalendarSource>,
managed: List<ManagedCalendarRow>,
language: LanguageChoice?,
launcherName: LauncherName?,
launcher: LauncherEntry?,
): 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 allDayTimes = snapshot[SettingsKeys.perCalendarAllDayReminderTime]
val hiddenViews = snapshot[SettingsKeys.perCalendarHiddenViews]
val muted = snapshot[SettingsKeys.mutedReminderCalendarIds]
val alertStyles = snapshot[SettingsKeys.reminderAlertStyles]
@@ -105,7 +112,7 @@ fun buildSettingsBackup(
val notInDigest = snapshot[SettingsKeys.digestExcludedCalendarIds]
val backupIncluded = snapshot[SettingsKeys.autoBackupIncluded]
val backupExcluded = snapshot[SettingsKeys.autoBackupExcluded]
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys +
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys + allDayTimes.keys +
hiddenViews.keys + muted + alertStyles.keys + fixedTime.keys + notInDigest + backupIncluded + backupExcluded
val byId = calendars.associateBy { it.id }
val managedType = managed.associate { it.id to it.type }
@@ -123,6 +130,7 @@ fun buildSettingsBackup(
eventDurationMinutes = durations[id],
reminders = reminders[id],
allDayReminders = allDay[id],
allDayReminderTimeMinutes = allDayTimes[id],
hiddenInViews = hiddenViews[id].orEmpty(),
notifications = id !in muted,
alertStyle = alertStyles[id]?.takeUnless { it == ReminderAlertStyle.Notification },
@@ -139,7 +147,8 @@ fun buildSettingsBackup(
prefs = plainSection.snapshot(snapshot),
calendars = entries,
language = language,
launcherName = launcherName,
launcherName = launcher?.name,
launcherIcon = launcher?.icon,
)
}
@@ -152,6 +161,7 @@ fun encodeSettingsBackup(backup: SettingsBackup, exportedAtMillis: Long, appVers
buildJsonObject {
backup.language?.let { put(KEY_LANGUAGE, it.tag?.let(::JsonPrimitive) ?: JsonNull) }
backup.launcherName?.let { put(KEY_LAUNCHER_NAME, JsonPrimitive(it.name)) }
backup.launcherIcon?.let { put(KEY_LAUNCHER_ICON, JsonPrimitive(it.name)) }
},
)
}
@@ -179,6 +189,8 @@ fun decodeSettingsBackup(text: String): BackupResult<SettingsBackup> {
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 } },
launcherIcon = app?.optString(KEY_LAUNCHER_ICON)
?.let { icon -> LauncherIcon.entries.firstOrNull { it.name == icon } },
)
}
}
@@ -193,6 +205,7 @@ private fun CalendarSettings.toJson(): JsonObject = buildJsonObject {
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))) }
allDayReminderTimeMinutes?.let { put(KEY_ALL_DAY_REMINDER_TIME, JsonPrimitive(it)) }
if (hiddenInViews.isNotEmpty()) {
put(KEY_HIDDEN_IN_VIEWS, JsonArray(hiddenInViews.sortedBy { it.ordinal }.map { JsonPrimitive(it.name) }))
}
@@ -224,6 +237,8 @@ private fun JsonObject.toCalendarSettings(): CalendarSettings {
eventDurationMinutes = optInt(KEY_EVENT_DURATION),
reminders = optIntList(KEY_REMINDERS)?.cleanReminders(),
allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS)?.cleanReminders(),
allDayReminderTimeMinutes = optInt(KEY_ALL_DAY_REMINDER_TIME)
?.takeIf { it in 0 until SettingsPrefs.MINUTES_PER_DAY },
hiddenInViews = optStringList(KEY_HIDDEN_IN_VIEWS).orEmpty()
.mapNotNullTo(mutableSetOf()) { name -> CalendarView.entries.firstOrNull { it.name == name } },
notifications = optBoolean(KEY_NOTIFICATIONS) ?: true,
@@ -247,6 +262,7 @@ 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_LAUNCHER_ICON = "launcher_icon"
private const val KEY_ACCOUNT_NAME = "account_name"
private const val KEY_ACCOUNT_TYPE = "account_type"
private const val KEY_DISPLAY_NAME = "display_name"
@@ -256,6 +272,7 @@ private const val KEY_LAST_USED = "last_used"
private const val KEY_EVENT_DURATION = "event_duration_minutes"
private const val KEY_REMINDERS = "reminders"
private const val KEY_ALL_DAY_REMINDERS = "all_day_reminders"
private const val KEY_ALL_DAY_REMINDER_TIME = "all_day_reminder_time_minutes"
private const val KEY_HIDDEN_IN_VIEWS = "hidden_in_views"
private const val KEY_NOTIFICATIONS = "notifications"
private const val KEY_ALERT_STYLE = "alert_style"
@@ -8,7 +8,8 @@ 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.launcher.LauncherEntry
import de.jeanlucmakiola.calendula.data.launcher.LauncherManager
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
@@ -52,7 +53,7 @@ class SettingsBackupEngine @Inject constructor(
private val specialDates: SpecialDatesSyncEngine,
private val settingsPrefs: SettingsPrefs,
private val reminderScanner: ReminderScanner,
private val launcherNames: LauncherNameManager,
private val launcher: LauncherManager,
@ApplicationContext private val context: Context,
@IoDispatcher private val io: CoroutineDispatcher,
) {
@@ -67,7 +68,7 @@ class SettingsBackupEngine @Inject constructor(
calendars = list,
managed = if (list.any { it.isManaged }) calendars.findManagedCalendars() else emptyList(),
language = LanguageChoice(AppLanguage.currentTag(context, supported)),
launcherName = launcherNames.current(),
launcher = launcher.current(),
)
encodeSettingsBackup(backup, System.currentTimeMillis(), BuildConfig.VERSION_NAME)
}
@@ -135,8 +136,15 @@ class SettingsBackupEngine @Inject constructor(
val active = after[SettingsKeys.autoBackupEnabled] && after[SettingsKeys.autoBackupFolderUri] != null
if (active && before.autoBackupScheduled != after.autoBackupScheduled) BackupScheduler.runNow(context)
}
plan.launcherName?.let { name ->
step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) }
if (plan.launcherName != null || plan.launcherIcon != null) {
step("launcher") {
val current = launcher.current()
val target = LauncherEntry(
name = plan.launcherName ?: current.name,
icon = plan.launcherIcon ?: current.icon,
)
launcher.set(target)
}
}
plan.language?.let { choice ->
step("language") {
@@ -28,6 +28,7 @@ internal object SettingsBackupSchema {
SettingsKeys.pastEventDisplay,
SettingsKeys.dimCompletedEvents,
SettingsKeys.showWeekNumbers,
SettingsKeys.weekNumbering,
SettingsKeys.monthShowStartTimes,
SettingsKeys.monthViewStyle,
SettingsKeys.timelineScale,
@@ -42,12 +43,15 @@ internal object SettingsBackupSchema {
SettingsKeys.agendaShowRangeBar,
SettingsKeys.agendaShowToday,
SettingsKeys.defaultView,
SettingsKeys.externalDateView,
SettingsKeys.quickSwitchConfig,
SettingsKeys.drawerViewOrder,
SettingsKeys.defaultFormFields,
SettingsKeys.autofocusEventTitle,
// Names its calendar by account and display name, so it finds it again on another device.
SettingsKeys.defaultNewEventCalendar,
// Names its members the same way (#166).
CalendarPrefKeys.calendarGroups,
SettingsKeys.defaultEventDurationMinutes,
SettingsKeys.remindersEnabled,
SettingsKeys.allowColorOnUnsupportedCalendars,
@@ -79,6 +83,7 @@ internal object SettingsBackupSchema {
SettingsKeys.perCalendarEventDuration,
SettingsKeys.perCalendarReminderOverride,
SettingsKeys.perCalendarAllDayReminderOverride,
SettingsKeys.perCalendarAllDayReminderTime,
SettingsKeys.perCalendarHiddenViews,
SettingsKeys.mutedReminderCalendarIds,
SettingsKeys.reminderAlertStyles,
@@ -100,6 +105,7 @@ internal object SettingsBackupSchema {
// Usage history, not a setting.
SettingsKeys.recentTimeZones,
SettingsKeys.recentFixedTimeReminders,
SettingsKeys.recentCustomColors,
// A dismissed hint of this install.
SettingsKeys.notificationCategoryHintDismissed,
// This device's notification channels.
@@ -2,7 +2,8 @@ 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.launcher.LauncherIcon
import de.jeanlucmakiola.calendula.data.launcher.LauncherName
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
@@ -72,6 +73,7 @@ data class SettingsImportPlan(
val pendingSpecialDates: List<CalendarSettings>,
val language: LanguageChoice?,
val launcherName: LauncherName?,
val launcherIcon: LauncherIcon?,
val skipped: List<SkippedSetting>,
)
@@ -154,6 +156,7 @@ fun planSettingsImport(
pendingSpecialDates = pending,
language = language,
launcherName = backup.launcherName,
launcherIcon = backup.launcherIcon,
skipped = skipped,
)
}
@@ -190,6 +193,9 @@ fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
this[SettingsKeys.perCalendarAllDayReminderOverride] =
this[SettingsKeys.perCalendarAllDayReminderOverride] + (id to it)
}
entry.allDayReminderTimeMinutes?.let {
this[SettingsKeys.perCalendarAllDayReminderTime] = this[SettingsKeys.perCalendarAllDayReminderTime] + (id to it)
}
if (entry.hiddenInViews.isNotEmpty()) {
this[SettingsKeys.perCalendarHiddenViews] = this[SettingsKeys.perCalendarHiddenViews] + (id to entry.hiddenInViews)
}
@@ -1,35 +1,33 @@
package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.floret.components.PresetColors
/**
* The colours offered when creating or editing a calendar; ARGB ints for a raw
* `CALENDAR_COLOR` / `EVENT_COLOR`.
*
* Hues rather than final fills: every surface that draws a calendar colour runs
* it through the app's own tone pass first, so these are chosen to stay
* distinguishable after it. Shared with Agendula, whose list palette these are —
* the two apps are the same family and a calendar and a task list picked from
* different-looking sets read as different products.
* `CALENDAR_COLOR` / `EVENT_COLOR`. The values are floret-kit's [PresetColors],
* shared with Agendula; distinctness after this app's tone pass is checked by
* `CalendarColorPaletteTest`.
*
* The named entries exist for callers that need one specific hue (the managed
* special-dates calendars), so they can't drift from the swatches on offer.
*/
object CalendarColorPalette {
val Mauve = 0xFF7A5C6B.toInt()
val Red = 0xFFD7484A.toInt()
val Orange = 0xFFE8743B.toInt()
val Amber = 0xFFE0A32E.toInt()
val Olive = 0xFF7CA83E.toInt()
val Green = 0xFF35A06A.toInt()
val Teal = 0xFF19938C.toInt()
val Cyan = 0xFF2A9BC4.toInt()
val Blue = 0xFF3C74C8.toInt()
val Indigo = 0xFF6A5CC0.toInt()
val Purple = 0xFF9455B8.toInt()
val Pink = 0xFFC94F8E.toInt()
val Mauve = PresetColors.Mauve
val Red = PresetColors.Red
val Orange = PresetColors.Orange
val Amber = PresetColors.Amber
val Olive = PresetColors.Olive
val Green = PresetColors.Green
val Teal = PresetColors.Teal
val Cyan = PresetColors.Cyan
val Blue = PresetColors.Blue
val Indigo = PresetColors.Indigo
val Purple = PresetColors.Purple
val Pink = PresetColors.Pink
/** The full palette, in swatch-grid order. */
val all: List<Int> = listOf(
Mauve, Red, Orange, Amber, Olive, Green,
Teal, Cyan, Blue, Indigo, Purple, Pink,
)
val all: List<Int> = PresetColors.all
/** The preset [argb] is, or null when it is a custom colour (never rewritten to match). */
fun presetOf(argb: Int?): Int? = PresetColors.presetOf(argb)
}
@@ -15,6 +15,7 @@ import android.os.Looper
import android.provider.CalendarContract
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.Attendee
import de.jeanlucmakiola.calendula.domain.AttendeeRelationship
import de.jeanlucmakiola.calendula.domain.AttendeeType
@@ -65,11 +66,11 @@ interface CalendarDataSource {
fun eventInstances(eventId: Long, beginMillis: Long, endMillis: Long): List<EventInstance> =
instances(beginMillis, endMillis).filter { it.eventId == eventId }
/**
* [allDayReminderTimeMinutes]: the hour all-day reminders fire at, needed to
* [allDayTimes]: the hour all-day reminders fire at, per calendar, needed to
* decode their stored offsets back to whole-day lead times (see
* [fromProviderAllDayMinutes]).
*/
fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail?
fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail?
/**
* Master/one-off events that may match [query], across all calendars: every
@@ -98,11 +99,11 @@ interface CalendarDataSource {
* (local, synced, read-only): the masters/one-offs and the modified and
* cancelled exception rows, each with the keys that link it to its series
* and tagged with its calendar's name. A plain read: which calendars may be
* read for what is the caller's call. [allDayReminderTimeMinutes]: needed to
* write all-day reminders as whole-day lead times rather than raw provider
* offsets (see [toIcsEvent]).
* read for what is the caller's call. [allDayTimes]: needed to write all-day
* reminders as whole-day lead times rather than raw provider offsets (see
* [toIcsEvent]).
*/
fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows
fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows
/**
* The non-empty `Events.UID_2445` values present in [calendarId] — used to
@@ -243,14 +244,14 @@ interface CalendarDataSource {
* [original]→[updated] field edits applied, then the source
* deleted. The source is removed only once the copy fully succeeds; a failure
* before that rolls the new event back, leaving the original untouched.
* [allDayReminderTimeMinutes]: see [insertEvent].
* [allDayTimes]: as [eventDetail] reads and [insertEvent] writes them.
*/
fun moveEvent(
eventId: Long,
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long
/**
@@ -750,7 +751,7 @@ class AndroidCalendarDataSource @Inject constructor(
}
}
override fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail? {
override fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail? {
val attendees = queryAttendees(eventId)
val reminders = queryReminders(eventId)
return resolver.query(
@@ -758,10 +759,14 @@ class AndroidCalendarDataSource @Inject constructor(
EventDetailProjection.COLUMNS,
null, null, null,
)?.use { c ->
if (!c.moveToFirst()) null
else CursorColumnReader(c).toEventDetailCore(
attendees, reminders, allDayReminderTimeMinutes,
)
if (!c.moveToFirst()) {
null
} else {
val reader = CursorColumnReader(c)
reader.toEventDetailCore(
attendees, reminders, allDayTimes.forCalendar(reader.getLong(EventDetailProjection.IDX_CALENDAR_ID)),
)
}
}
}
@@ -786,7 +791,7 @@ class AndroidCalendarDataSource @Inject constructor(
?: emptyList()
}
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
override fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows {
if (calendarIds.isEmpty()) return CalendarRows(emptyList(), emptyList())
// The name tags each event for a combined backup's restore to fan back
// out; an id that no longer exists drops out here.
@@ -797,7 +802,7 @@ class AndroidCalendarDataSource @Inject constructor(
"${CalendarContract.Events.DELETED} = 0"
val series = mutableListOf<MasterRow>()
val overrides = mutableListOf<OverrideRow>()
forEachExportRow(selection, allDayReminderTimeMinutes) { event ->
forEachExportRow(selection, allDayTimes) { event ->
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
val calendar = calendars[calendarId]
// An adapter may stamp the calendar colour on every row; a palette key means it was chosen.
@@ -844,7 +849,7 @@ class AndroidCalendarDataSource @Inject constructor(
*/
private fun forEachExportRow(
selection: String,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
row: ColumnReader.(event: (calendarName: String?) -> IcsEvent) -> Unit,
) {
val eventIds = resolver.query(
@@ -869,7 +874,9 @@ class AndroidCalendarDataSource @Inject constructor(
reader.toIcsEvent(
reminderMinutes = reminders[eventId].orEmpty(),
calendarName = calendarName,
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
allDayReminderTimeMinutes = allDayTimes.forCalendar(
reader.getLong(EventExportProjection.IDX_CALENDAR_ID),
),
)
}
}
@@ -1116,8 +1123,9 @@ class AndroidCalendarDataSource @Inject constructor(
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long {
val allDayReminderTimeMinutes = allDayTimes.forCalendar(targetCalendarId)
// CALENDAR_ID can't be updated in place, so re-create the event on the
// target calendar and delete the source. Everything that identifies or
// hangs off the event is copied first; the source row is removed only
@@ -1138,7 +1146,7 @@ class AndroidCalendarDataSource @Inject constructor(
try {
copyReminderRows(fromEventId = eventId, toEventId = newEventId)
insertAttendees(newEventId, editableAttendees(eventId))
copyExceptions(eventId, newEventId, targetCalendarId, allDayReminderTimeMinutes, detached)
copyExceptions(eventId, newEventId, targetCalendarId, allDayTimes, detached)
// Apply the user's field edits exactly as a same-calendar "all
// events" save would: the moved master carries the source's values,
// so the dirty diff against [original] writes only what changed
@@ -1224,20 +1232,20 @@ class AndroidCalendarDataSource @Inject constructor(
fromEventId: Long,
toEventId: Long,
targetCalendarId: Long,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
detached: MutableList<Long>,
) {
val exceptions = queryExceptionRows(fromEventId)
if (exceptions.isEmpty()) return
val zone = TimeZone.currentSystemDefault()
exceptions.filterNot { it.isCancelled }.forEach { ex ->
val detail = eventDetail(ex.exceptionEventId, allDayReminderTimeMinutes)
val detail = eventDetail(ex.exceptionEventId, allDayTimes)
?: throw WriteFailedException("read modified occurrence id=${ex.exceptionEventId}")
val endMillis = ex.dtEndMillis ?: (ex.dtStartMillis + parseRfc2445DurationMillis(ex.duration))
val form = detail.toEditForm(ex.dtStartMillis, endMillis, zone)
.copy(calendarId = targetCalendarId, colorKey = null)
.toDetachedOccurrence()
detached += insertEvent(form, allDayReminderTimeMinutes)
detached += insertEvent(form, allDayTimes.forCalendar(targetCalendarId))
}
val values = querySeriesRow(toEventId).exdateValues(exceptions.map { it.originalInstanceMillis })
updateEventRow(toEventId, values, "exdate moved exceptions event id=$toEventId")
@@ -12,6 +12,7 @@ import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides
@@ -56,9 +57,12 @@ class CalendarRepositoryImpl @Inject constructor(
private val syncRequester: SyncRequester,
) : CalendarRepository {
/** The configured wall-clock fire time for all-day reminders, read per write. */
private suspend fun allDayReminderTimeMinutes(): Int =
settingsPrefs.allDayReminderTimeMinutes.first()
/** The configured wall-clock fire times for all-day reminders, global and per calendar (#541), read per call. */
private suspend fun allDayReminderTimes(): AllDayReminderTimes = settingsPrefs.allDayReminderTimes.first()
/** [calendarId]'s all-day reminder time: its own, or the global one. */
private suspend fun allDayReminderTimeMinutes(calendarId: Long?): Int =
allDayReminderTimes().let { times -> calendarId?.let(times::forCalendar) ?: times.default }
// DROP_OLDEST: tryEmit never fails, so a tick that lands while a subscriber
// still holds the previous one is never lost (#364).
@@ -363,7 +367,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
dataSource.eventDetail(eventId, allDayReminderTimes())
?: throw NoSuchEventException(eventId)
}
@@ -412,7 +416,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun exportEvents(calendarIds: Set<Long>) = withContext(io) {
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp)
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimes()), ::formatExdateStamp)
}
override suspend fun copyEvents(
@@ -422,7 +426,7 @@ class CalendarRepositoryImpl @Inject constructor(
): IcsImportSummary {
val events = withContext(io) {
planCalendarCopy(
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()),
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimes()),
::formatExdateStamp,
)
}
@@ -445,7 +449,7 @@ class CalendarRepositoryImpl @Inject constructor(
// uncurated one — an imported colour is matched against every key the
// account accepts, not the subset the picker shows.
val palette = dataSource.publishedEventColors(targetCalendarId)
val allDayMinutes = allDayReminderTimeMinutes()
val allDayMinutes = allDayReminderTimeMinutes(targetCalendarId)
var imported = 0
var skipped = 0
var failed = 0
@@ -500,7 +504,7 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
dataSource.insertEvent(form, allDayReminderTimeMinutes())
dataSource.insertEvent(form, allDayReminderTimeMinutes(form.calendarId))
}
override suspend fun updateEvent(
@@ -508,7 +512,9 @@ class CalendarRepositoryImpl @Inject constructor(
original: EventForm,
updated: EventForm,
) = write(eventCalendar(eventId, original, updated.calendarId)) {
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
dataSource.updateEvent(
eventId, original, updated, allDayReminderTimeMinutes(updated.calendarId ?: original.calendarId),
)
}
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
@@ -522,7 +528,7 @@ class CalendarRepositoryImpl @Inject constructor(
updated: EventForm,
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
dataSource.moveEvent(
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
eventId, targetCalendarId, original, updated, allDayReminderTimes(),
)
}
@@ -533,7 +539,7 @@ class CalendarRepositoryImpl @Inject constructor(
form: EventForm,
): Long = write(eventCalendar(eventId, original)) {
dataSource.updateOccurrence(
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
eventId, beginMillis, original, form, allDayReminderTimeMinutes(form.calendarId ?: original.calendarId),
)
}
@@ -544,7 +550,7 @@ class CalendarRepositoryImpl @Inject constructor(
updated: EventForm,
): Long = write(eventCalendar(eventId, original)) {
dataSource.updateEventFromOccurrence(
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(updated.calendarId ?: original.calendarId),
)
}.also { newId -> if (newId != eventId) splits.tryEmit(SeriesSplit(eventId, newId)) }
@@ -16,6 +16,7 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.contacts.anchorDate
import de.jeanlucmakiola.calendula.domain.contacts.managedUid
import de.jeanlucmakiola.calendula.domain.contacts.renderSpecialDateTitle
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.toRRule
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
@@ -122,7 +123,7 @@ class SpecialDatesSyncEngine @Inject constructor(
}
calendars.applyManagedCalendarReminders(
calendarId = calendarId,
allDayReminderTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
allDayReminderTimeMinutes = prefs.allDayReminderTimes.first().forCalendar(calendarId),
minutes = minutes,
)
}
@@ -190,7 +191,9 @@ class SpecialDatesSyncEngine @Inject constructor(
val diff = diffManagedEvents(built.map { it.desired }, calendars.queryManagedEvents(calendarId))
val formByUid = built.associate { it.desired.uid to it.form }
diff.insertUids.forEach { uid ->
calendars.insertManagedEvent(formByUid.getValue(uid), uid, reminderCtx.allDayTimeMinutes)
calendars.insertManagedEvent(
formByUid.getValue(uid), uid, reminderCtx.allDayTimes.forCalendar(calendarId),
)
}
diff.updates.forEach { calendars.updateManagedFields(it.eventId, it.columns) }
diff.deleteEventIds.forEach { calendars.deleteEvent(it) }
@@ -235,13 +238,13 @@ class SpecialDatesSyncEngine @Inject constructor(
private suspend fun readReminderContext(): ReminderContext = ReminderContext(
allDayGlobal = prefs.defaultAllDayReminderMinutes.first(),
allDayOverrides = prefs.perCalendarAllDayReminderOverride.first(),
allDayTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
allDayTimes = prefs.allDayReminderTimes.first(),
)
private data class ReminderContext(
val allDayGlobal: List<Int>,
val allDayOverrides: Map<Long, List<Int>>,
val allDayTimeMinutes: Int,
val allDayTimes: AllDayReminderTimes,
) {
/** Same semantics as `resolveDefaultReminder`: present-empty = explicit none. */
fun resolveAllDay(calendarId: Long): List<Int> =
@@ -0,0 +1,76 @@
package de.jeanlucmakiola.calendula.data.launcher
import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.LauncherAliasSwitcher
import javax.inject.Inject
import javax.inject.Singleton
/** The launcher label the app shows for itself (issue #44). */
enum class LauncherName { CALENDULA, CALENDAR }
/** The launcher icon the app shows for itself (issue #451). */
enum class LauncherIcon { BLOOM, PLAIN }
/** What the launcher shows: a name and an icon, chosen independently. */
data class LauncherEntry(
val name: LauncherName = LauncherName.CALENDULA,
val icon: LauncherIcon = LauncherIcon.BLOOM,
)
/**
* The four `<activity-alias>` launcher entries, one per name × icon. The two
* bloom-icon aliases keep their pre-#451 component names, so users on those
* keep their launcher position and pinned shortcuts across the update.
*/
enum class LauncherAlias(val className: String, val entry: LauncherEntry) {
DEFAULT("DefaultNameAlias", LauncherEntry(LauncherName.CALENDULA, LauncherIcon.BLOOM)),
CALENDAR("CalendarNameAlias", LauncherEntry(LauncherName.CALENDAR, LauncherIcon.BLOOM)),
PLAIN("PlainIconAlias", LauncherEntry(LauncherName.CALENDULA, LauncherIcon.PLAIN)),
CALENDAR_PLAIN("CalendarNamePlainIconAlias", LauncherEntry(LauncherName.CALENDAR, LauncherIcon.PLAIN)),
;
companion object {
/** The alias that shows [entry]. */
fun of(entry: LauncherEntry): LauncherAlias = entries.first { it.entry == entry }
}
}
/**
* Switches the launcher name and icon by enabling exactly one [LauncherAlias].
* The component-enabled state is the single source of truth, so there is no
* stored preference to drift from it.
*/
@Singleton
class LauncherManager @Inject constructor(
@ApplicationContext context: Context,
) {
private val switcher = LauncherAliasSwitcher(
context = context,
namespace = NAMESPACE,
aliases = LauncherAlias.entries.associateWith { it.className },
default = LauncherAlias.DEFAULT,
)
/** What the launcher currently shows. Blocking. */
fun current(): LauncherEntry = switcher.current().entry
/** Switch to [entry] (cheap if already active). Blocking. */
@Synchronized
fun set(entry: LauncherEntry) {
switcher.set(LauncherAlias.of(entry))
}
/** Change only the name, keeping the icon. Blocking. */
@Synchronized
fun setName(name: LauncherName) = set(current().copy(name = name))
/** Change only the icon, keeping the name. Blocking. */
@Synchronized
fun setIcon(icon: LauncherIcon) = set(current().copy(icon = icon))
private companion object {
/** The app's namespace, not its suffixed applicationId. Kept in sync with `app/build.gradle.kts`. */
const val NAMESPACE = "de.jeanlucmakiola.calendula"
}
}
@@ -9,6 +9,9 @@ import de.jeanlucmakiola.floret.prefs.nullableLongPref
import de.jeanlucmakiola.floret.prefs.nullableStringPref
import de.jeanlucmakiola.floret.prefs.stringSetPref
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.decodeCalendarGroups
import de.jeanlucmakiola.calendula.domain.encodeCalendarGroups
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
@@ -79,6 +82,13 @@ class CalendarPrefs @Inject constructor(
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(CalendarPrefKeys.lastUsedCalendarId, id)
/** The drawer's calendar groups (#166), in the order they were created. */
val calendarGroups: Flow<List<CalendarGroup>> = prefs.flow(CalendarPrefKeys.calendarGroups)
suspend fun updateCalendarGroups(transform: (List<CalendarGroup>) -> List<CalendarGroup>) {
prefs.update(CalendarPrefKeys.calendarGroups, transform)
}
/**
* Synced accounts the user chose never to be asked to grant sync-request
* access for (#240): no grant row, no "other accounts" receipt.
@@ -96,6 +106,8 @@ internal object CalendarPrefKeys {
val pendingDisabledCalendarIds: Pref<Set<Long>> = idSetPref("disabled_calendar_ids")
val visibilityNoticePending: Pref<Boolean?> = nullableBooleanPref("visibility_notice_pending")
val lastUsedCalendarId: Pref<Long?> = nullableLongPref("last_used_calendar_id")
val calendarGroups: Pref<List<CalendarGroup>> =
nullableStringPref("calendar_groups").map(::decodeCalendarGroups, ::encodeCalendarGroups)
val syncAccessDismissed: Pref<Set<SyncAccount>> = stringSetPref("sync_access_dismissed").map(
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
@@ -28,6 +28,7 @@ import de.jeanlucmakiola.calendula.domain.reminders.toStoredAlertStyles
import de.jeanlucmakiola.calendula.domain.reminders.DEFAULT_DIGEST_TIME_MINUTES
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.DigestDay
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange
@@ -44,6 +45,8 @@ import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep
import de.jeanlucmakiola.calendula.ui.theme.FONT_SYSTEM_TOKEN
import de.jeanlucmakiola.calendula.widget.WidgetSize
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.components.hexDigitsOf
import de.jeanlucmakiola.floret.components.parseHexColor
import de.jeanlucmakiola.floret.prefs.AppearancePrefs
import de.jeanlucmakiola.floret.prefs.Pref
import de.jeanlucmakiola.floret.prefs.PrefStore
@@ -90,6 +93,20 @@ sealed interface WeekStartPref {
*/
enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
/**
* How week numbers are counted (#493). AUTO follows the device region; ISO and
* US pin ISO 8601 or the US system. Only the number: rows still start on the
* day [WeekStartPref] picks.
*/
enum class WeekNumberingPref { AUTO, ISO, US }
/** The [WeekFields] that count weeks under this preference; AUTO reads [region]. */
fun WeekNumberingPref.weekFields(region: Locale): WeekFields = when (this) {
WeekNumberingPref.AUTO -> WeekFields.of(region)
WeekNumberingPref.ISO -> WeekFields.ISO
WeekNumberingPref.US -> WeekFields.SUNDAY_START
}
/**
* How the Agenda screen treats events that have already finished today: [SHOW]
* leaves them as-is (the historical behaviour), [DIM] fades them, [HIDE] drops
@@ -97,6 +114,9 @@ enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
*/
enum class PastEventDisplay { SHOW, DIM, HIDE }
/** What a date another app opens in Calendula lands on (#524): the day view, or the default view on that date. */
enum class ExternalDateView { DAY, DEFAULT }
/** Parse a stored [PastEventDisplay.name]; unknown/null falls back to [default]. */
fun parsePastEventDisplay(
stored: String?,
@@ -171,6 +191,7 @@ class SettingsPrefs @Inject constructor(
val pastEventDisplay: Flow<PastEventDisplay> = prefs.flow(SettingsKeys.pastEventDisplay)
val dimCompletedEvents: Flow<Boolean> = prefs.flow(SettingsKeys.dimCompletedEvents)
val showWeekNumbers: Flow<Boolean> = prefs.flow(SettingsKeys.showWeekNumbers)
val weekNumbering: Flow<WeekNumberingPref> = prefs.flow(SettingsKeys.weekNumbering)
val monthShowStartTimes: Flow<Boolean> = prefs.flow(SettingsKeys.monthShowStartTimes)
val monthViewStyle: Flow<MonthViewStyle> = prefs.flow(SettingsKeys.monthViewStyle)
val timelineScale: Flow<TimelineScale> = prefs.flow(SettingsKeys.timelineScale)
@@ -183,10 +204,12 @@ class SettingsPrefs @Inject constructor(
val agendaShowRangeBar: Flow<Boolean> = prefs.flow(SettingsKeys.agendaShowRangeBar)
val agendaShowToday: Flow<Boolean> = prefs.flow(SettingsKeys.agendaShowToday)
val defaultView: Flow<CalendarView> = prefs.flow(SettingsKeys.defaultView)
val externalDateView: Flow<ExternalDateView> = prefs.flow(SettingsKeys.externalDateView)
val quickSwitchConfig: Flow<QuickSwitchConfig> = prefs.flow(SettingsKeys.quickSwitchConfig)
val drawerViewOrder: Flow<List<CalendarView>> = prefs.flow(SettingsKeys.drawerViewOrder)
val defaultFormFields: Flow<Set<EventFormField>> = prefs.flow(SettingsKeys.defaultFormFields)
val recentTimeZones: Flow<List<String>> = prefs.flow(SettingsKeys.recentTimeZones)
val recentCustomColors: Flow<List<Int>> = prefs.flow(SettingsKeys.recentCustomColors)
val autofocusEventTitle: Flow<Boolean> = prefs.flow(SettingsKeys.autofocusEventTitle)
val defaultNewEventCalendar: Flow<DefaultCalendarRef?> = prefs.flow(SettingsKeys.defaultNewEventCalendar)
val defaultEventDurationMinutes: Flow<Int> = prefs.flow(SettingsKeys.defaultEventDurationMinutes)
@@ -202,6 +225,12 @@ class SettingsPrefs @Inject constructor(
val defaultReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultReminderMinutes)
val defaultAllDayReminderMinutes: Flow<List<Int>> = prefs.flow(SettingsKeys.defaultAllDayReminderMinutes)
val allDayReminderTimeMinutes: Flow<Int> = prefs.flow(SettingsKeys.allDayReminderTimeMinutes)
val perCalendarAllDayReminderTime: Flow<Map<Long, Int>> = prefs.flow(SettingsKeys.perCalendarAllDayReminderTime)
/** The global all-day reminder time with each calendar's own (#541). */
val allDayReminderTimes: Flow<AllDayReminderTimes> = prefs.snapshot {
AllDayReminderTimes(it[SettingsKeys.allDayReminderTimeMinutes], it[SettingsKeys.perCalendarAllDayReminderTime])
}
val snoozeMinutes: Flow<Int> = prefs.flow(SettingsKeys.snoozeMinutes)
val perCalendarReminderOverride: Flow<Map<Long, List<Int>>> =
prefs.flow(SettingsKeys.perCalendarReminderOverride)
@@ -269,6 +298,7 @@ class SettingsPrefs @Inject constructor(
suspend fun setPastEventDisplay(mode: PastEventDisplay) = prefs.set(SettingsKeys.pastEventDisplay, mode)
suspend fun setDimCompletedEvents(enabled: Boolean) = prefs.set(SettingsKeys.dimCompletedEvents, enabled)
suspend fun setShowWeekNumbers(enabled: Boolean) = prefs.set(SettingsKeys.showWeekNumbers, enabled)
suspend fun setWeekNumbering(pref: WeekNumberingPref) = prefs.set(SettingsKeys.weekNumbering, pref)
suspend fun setMonthShowStartTimes(enabled: Boolean) = prefs.set(SettingsKeys.monthShowStartTimes, enabled)
suspend fun setMonthViewStyle(style: MonthViewStyle) = prefs.set(SettingsKeys.monthViewStyle, style)
suspend fun setTimelineScale(scale: TimelineScale) = prefs.set(SettingsKeys.timelineScale, scale)
@@ -290,6 +320,7 @@ class SettingsPrefs @Inject constructor(
suspend fun setAgendaShowRangeBar(enabled: Boolean) = prefs.set(SettingsKeys.agendaShowRangeBar, enabled)
suspend fun setAgendaShowToday(enabled: Boolean) = prefs.set(SettingsKeys.agendaShowToday, enabled)
suspend fun setDefaultView(view: CalendarView) = prefs.set(SettingsKeys.defaultView, view)
suspend fun setExternalDateView(view: ExternalDateView) = prefs.set(SettingsKeys.externalDateView, view)
/**
* Atomic read-modify-write of the quick-switch config: [transform] sees the
@@ -311,6 +342,11 @@ class SettingsPrefs @Inject constructor(
prefs.update(SettingsKeys.recentTimeZones) { (listOf(zoneId) + it).distinct() }
}
/** Moves [argb] to the front of the custom-colour recents shared by the colour pickers. */
suspend fun addRecentCustomColor(argb: Int) {
prefs.update(SettingsKeys.recentCustomColors) { withRecentColor(it, argb) }
}
suspend fun setAutofocusEventTitle(enabled: Boolean) = prefs.set(SettingsKeys.autofocusEventTitle, enabled)
/** [calendar] null goes back to Automatic. */
@@ -418,6 +454,17 @@ class SettingsPrefs @Inject constructor(
suspend fun setAllDayReminderTimeMinutes(minutesOfDay: Int) =
prefs.set(SettingsKeys.allDayReminderTimeMinutes, minutesOfDay)
/** [minutesOfDay] null drops the calendar's own all-day reminder time, so it follows the global one again. */
suspend fun setCalendarAllDayReminderTime(calendarId: Long, minutesOfDay: Int?) {
prefs.update(SettingsKeys.perCalendarAllDayReminderTime) { current ->
if (minutesOfDay == null) {
current - calendarId
} else {
current + (calendarId to minutesOfDay.coerceIn(0, MINUTES_PER_DAY - 1))
}
}
}
suspend fun setSnoozeMinutes(minutes: Int) = prefs.set(SettingsKeys.snoozeMinutes, minutes)
suspend fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) =
@@ -647,6 +694,8 @@ class SettingsPrefs @Inject constructor(
setOf(EventFormField.Location, EventFormField.Description)
/** Enough to cover the zones a user actually recurs to, without a wall of rows. */
internal const val MAX_RECENT_TIME_ZONES = 5
/** One row of swatches in the colour pickers. */
internal const val MAX_RECENT_CUSTOM_COLORS = 8
/** Default automatic-backup interval: daily. */
const val DEFAULT_BACKUP_INTERVAL = 1_440L
/** Floor for the automatic-backup interval (also above WorkManager's 15-min limit). */
@@ -708,11 +757,14 @@ object SettingsKeys {
val dimCompletedEvents: Pref<Boolean> = booleanPref("dim_completed_events", false)
/**
* Whether the Month grid shows the ISO week number in a left gutter (#25).
* Whether the Month grid shows the week number in a left gutter (#25).
* The Week view shows its number unconditionally.
*/
val showWeekNumbers: Pref<Boolean> = booleanPref("show_week_numbers", false)
/** How every week number in the app is counted (#493). */
val weekNumbering: Pref<WeekNumberingPref> = enumPref("week_numbering", WeekNumberingPref.AUTO)
/** Whether Month chips may show the start time before the title when wide enough (#219, #476). */
val monthShowStartTimes: Pref<Boolean> = booleanPref("month_show_start_times", true)
@@ -792,6 +844,9 @@ object SettingsKeys {
*/
val defaultView: Pref<CalendarView> = enumPref("default_view", CalendarView.Week)
/** What a launcher or clock date tap opens (#524); our own notifications and widgets keep the day view. */
val externalDateView: Pref<ExternalDateView> = enumPref("external_date_view", ExternalDateView.DAY)
/**
* Quick-switch button customisation (#24): the ordered full view list plus
* which views are enabled in the cycle. Stored comma-joined by enum name, a
@@ -830,6 +885,15 @@ object SettingsKeys {
zones.take(SettingsPrefs.MAX_RECENT_TIME_ZONES).joinToString(",")
}
/**
* Custom colours the user picked recently, most recent first, as `RRGGBB`
* hex joined by commas; unreadable entries are dropped on read.
*/
val recentCustomColors: Pref<List<Int>> =
nullableStringPref("recent_custom_colors").map(::parseRecentColors) { colors ->
colors.take(SettingsPrefs.MAX_RECENT_CUSTOM_COLORS).joinToString(LIST_SEP, transform = ::hexDigitsOf)
}
/**
* Whether opening the new-event form focuses the title field and raises the
* keyboard straight away (issue #10). Only the create form auto-focuses.
@@ -971,6 +1035,16 @@ object SettingsKeys {
it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1)
}
/**
* Per-calendar overrides of [allDayReminderTimeMinutes] (#541): app-side
* only, nothing of it reaches the provider. A calendar absent follows the
* global time. Serialised as `id=minutes;id=minutes`.
*/
val perCalendarAllDayReminderTime: Pref<Map<Long, Int>> =
nullableStringPref("per_calendar_allday_reminder_time").map(
{ parseIdIntMap(it, 0 until SettingsPrefs.MINUTES_PER_DAY) },
) { it.toStoredIdInts() }
/**
* How long the notification "Snooze" action defers a reminder, in minutes,
* re-posted via an exact alarm (the calendar provider won't re-fire).
@@ -1251,6 +1325,25 @@ private fun parseRecentTimeZones(stored: String?): List<String> =
.distinct()
.take(SettingsPrefs.MAX_RECENT_TIME_ZONES)
private fun parseRecentColors(stored: String?): List<Int> =
stored?.split(LIST_SEP).orEmpty()
.mapNotNull(::parseHexColor)
.distinct()
.take(SettingsPrefs.MAX_RECENT_CUSTOM_COLORS)
/**
* [recents] with [argb] (made opaque) moved to the front: an earlier copy is
* dropped rather than repeated, and the list stays at most
* [SettingsPrefs.MAX_RECENT_CUSTOM_COLORS] long.
*/
internal fun withRecentColor(recents: List<Int>, argb: Int): List<Int> {
val opaque = argb or OPAQUE_ALPHA
return (listOf(opaque) + recents.filter { (it or OPAQUE_ALPHA) != opaque })
.take(SettingsPrefs.MAX_RECENT_CUSTOM_COLORS)
}
private const val OPAQUE_ALPHA = 0xFF shl 24
private fun parseFormFields(stored: String?): Set<EventFormField> = when (stored) {
null -> SettingsPrefs.DEFAULT_FORM_FIELDS
else -> stored.split(',')
@@ -1465,14 +1558,16 @@ private fun List<Int>.toStoredReminders(): String =
* degrades to "inherits the global default" instead of throwing.
*/
private fun parseDurationOverrides(stored: String?): Map<Long, Int> =
parseIdIntMap(stored, SettingsPrefs.MIN_EVENT_DURATION..SettingsPrefs.MAX_EVENT_DURATION)
/** Parse an `id=value` map joined by `;`, dropping malformed entries and values outside [valid]. */
private fun parseIdIntMap(stored: String?, valid: IntRange): Map<Long, Int> =
stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry ->
val parts = entry.split(KEY_VALUE_SEP)
if (parts.size != 2) return@mapNotNull null
val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null
val minutes = parts[1].trim().toIntOrNull()
?.takeIf { it in SettingsPrefs.MIN_EVENT_DURATION..SettingsPrefs.MAX_EVENT_DURATION }
?: return@mapNotNull null
calendarId to minutes
val value = parts[1].trim().toIntOrNull()?.takeIf { it in valid } ?: return@mapNotNull null
calendarId to value
}.toMap()
private fun parseChannelVersions(stored: String?): Map<Long, Int> =
@@ -1519,3 +1614,5 @@ private fun Map<Long, Int>.toStoredDurations(): String =
"$id$KEY_VALUE_SEP$minutes"
}
private fun Map<Long, Int>.toStoredIdInts(): String? = toStoredDurations().ifEmpty { null }
@@ -120,7 +120,7 @@ class ReminderScanner @Inject constructor(
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
.withoutProviderDefaults(),
zone = ZoneId.systemDefault(),
allDayTimeMinutes = settingsPrefs.allDayReminderTimeMinutes.first(),
allDayTimes = settingsPrefs.allDayReminderTimes.first(),
)
val schedule = scheduleReminders(
@@ -0,0 +1,92 @@
package de.jeanlucmakiola.calendula.domain
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.longOrNull
/**
* A user-named set of calendars shown or hidden together from the drawer
* (#166). Members may come from several accounts and groups may overlap; each
* member is named by account and display name ([DefaultCalendarRef]), so a
* group survives provider id changes and a restore on another device.
*/
data class CalendarGroup(
val id: String,
val name: String,
val members: List<DefaultCalendarRef>,
) {
/** The members that exist in [calendars], each once; missing ones are dropped. */
fun resolve(calendars: List<CalendarSource>): List<CalendarSource> =
members.mapNotNull { it.find(calendars) }.distinctBy { it.id }
}
/** [groups] as stored; null (no key) when there are none. */
fun encodeCalendarGroups(groups: List<CalendarGroup>): String? {
if (groups.isEmpty()) return null
return JsonArray(
groups.map { group ->
buildJsonObject {
put(KEY_ID, JsonPrimitive(group.id))
put(KEY_NAME, JsonPrimitive(group.name))
put(
KEY_MEMBERS,
JsonArray(
group.members.map { ref ->
buildJsonObject {
put(KEY_CALENDAR_ID, JsonPrimitive(ref.id))
put(KEY_ACCOUNT_TYPE, JsonPrimitive(ref.accountType))
put(KEY_ACCOUNT_NAME, JsonPrimitive(ref.accountName))
put(KEY_DISPLAY_NAME, JsonPrimitive(ref.displayName))
}
},
),
)
}
},
).toString()
}
/** The stored groups; an unreadable value reads as none, an unreadable entry or member is skipped. */
fun decodeCalendarGroups(stored: String?): List<CalendarGroup> {
if (stored.isNullOrBlank()) return emptyList()
val array = runCatching { Json.parseToJsonElement(stored) }.getOrNull() as? JsonArray ?: return emptyList()
return array.mapNotNull { element ->
val group = element as? JsonObject ?: return@mapNotNull null
val id = group.string(KEY_ID) ?: return@mapNotNull null
val name = group.string(KEY_NAME) ?: return@mapNotNull null
val members = (group[KEY_MEMBERS] as? JsonArray).orEmpty().mapNotNull { member ->
val ref = member as? JsonObject ?: return@mapNotNull null
DefaultCalendarRef(
id = (ref[KEY_CALENDAR_ID] as? JsonPrimitive)?.longOrNull ?: return@mapNotNull null,
accountType = ref.string(KEY_ACCOUNT_TYPE) ?: return@mapNotNull null,
accountName = ref.string(KEY_ACCOUNT_NAME) ?: return@mapNotNull null,
displayName = ref.string(KEY_DISPLAY_NAME) ?: return@mapNotNull null,
)
}
CalendarGroup(id, name, members)
}.distinctBy { it.id }
}
/**
* These groups with group [id] saved as [name] over [calendars], or appended
* when new. Members are rewritten from [calendars], which drops ones gone meanwhile.
*/
fun List<CalendarGroup>.withGroup(id: String, name: String, calendars: List<CalendarSource>): List<CalendarGroup> {
val group = CalendarGroup(id, name, calendars.distinctBy { it.id }.map(DefaultCalendarRef::of))
return if (any { it.id == id }) map { if (it.id == id) group else it } else this + group
}
private fun JsonObject.string(key: String): String? =
(this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
private const val KEY_ID = "id"
private const val KEY_NAME = "name"
private const val KEY_MEMBERS = "members"
private const val KEY_CALENDAR_ID = "calendar_id"
private const val KEY_ACCOUNT_TYPE = "account_type"
private const val KEY_ACCOUNT_NAME = "account_name"
private const val KEY_DISPLAY_NAME = "display_name"
@@ -3,23 +3,26 @@ package de.jeanlucmakiola.calendula.domain
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDateTime
import de.jeanlucmakiola.calendula.domain.ics.toUtcBasic
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.minus
import kotlinx.datetime.number
import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
/**
* The recurrence shapes the simple picker can express (v1.3): a frequency,
* an interval, weekly weekday picks, and an optional end. Anything beyond
* that (ordinal BYDAY like "2TH", BYMONTHDAY, EXDATE rules, …) stays a raw
* RRULE string the picker shows as "custom" and leaves untouched unless the
* user replaces it.
* an interval, weekly weekday picks, a monthly weekday position (#520) and an
* optional end. Anything beyond that (several ordinal days, BYMONTHDAY,
* BYSETPOS, …) stays a raw RRULE string the picker shows as "custom" and
* leaves untouched unless the user replaces it.
*/
data class SimpleRecurrence(
val freq: RecurrenceFreq,
@@ -30,8 +33,75 @@ data class SimpleRecurrence(
* no BYDAY part — the provider derives the day from DTSTART.
*/
val byDays: Set<DayOfWeek> = emptySet(),
/**
* Monthly only: repeat on the n-th (or last) weekday of the month
* (RRULE `BYDAY=2TU`). Null repeats on DTSTART's day of the month.
*/
val monthlyWeekday: MonthlyWeekday? = null,
)
/**
* "The [ordinal]-th [day] of the month": [ordinal] is 1..5, or [LAST] (-1).
* A fifth weekday only exists in some months; those without one are skipped.
*/
data class MonthlyWeekday(val ordinal: Int, val day: DayOfWeek) {
init {
require(ordinal in 1..MAX_ORDINAL || ordinal == LAST) { "ordinal $ordinal" }
}
/** The RRULE BYDAY token, e.g. "2TU" or "-1SA". */
val token: String get() = "$ordinal${RRULE_DAY_CODES.getValue(day)}"
/**
* The first date on or after [date] at this position: later in [date]'s
* month, or in the next month that has one (a fifth weekday can be months away).
*/
fun firstOnOrAfter(date: LocalDate): LocalDate {
var month = LocalDate(date.year, date.month, 1)
while (true) {
dateIn(month.year, month.month.number)?.takeIf { it >= date }?.let { return it }
month = month.plus(1, DateTimeUnit.MONTH)
}
}
/** This weekday's date in [year]/[month], or null when the month has no such day. */
fun dateIn(year: Int, month: Int): LocalDate? {
val first = LocalDate(year, month, 1)
val offset = (day.isoDayNumber - first.dayOfWeek.isoDayNumber + 7) % 7
val firstMatch = first.day + offset
val lastDay = first.plus(1, DateTimeUnit.MONTH).minus(1, DateTimeUnit.DAY).day
val dom = if (ordinal == LAST) {
firstMatch + (lastDay - firstMatch) / 7 * 7
} else {
firstMatch + (ordinal - 1) * 7
}
return if (dom <= lastDay) LocalDate(year, month, dom) else null
}
companion object {
const val LAST = -1
const val MAX_ORDINAL = 5
/** Parse a single BYDAY item with an ordinal ("2TU", "+3MO", "-1SA"); else null. */
fun parse(token: String): MonthlyWeekday? {
val match = TOKEN.matchEntire(token.trim().uppercase()) ?: return null
val ordinal = match.groupValues[1].removePrefix("+").toIntOrNull() ?: return null
if (ordinal !in 1..MAX_ORDINAL && ordinal != LAST) return null
val day = rruleDay(match.groupValues[2]) ?: return null
return MonthlyWeekday(ordinal, day)
}
/** [date]'s own position: its weekday, counted from the start of its month (1..5). */
fun of(date: LocalDate): MonthlyWeekday = MonthlyWeekday((date.day - 1) / 7 + 1, date.dayOfWeek)
/** The position offered for [date]: its own, with a fifth weekday offered as the last one. */
fun suggestedFor(date: LocalDate): MonthlyWeekday =
of(date).let { if (it.ordinal == MAX_ORDINAL) it.copy(ordinal = LAST) else it }
private val TOKEN = Regex("""([+-]?\d)(MO|TU|WE|TH|FR|SA|SU)""")
}
}
enum class RecurrenceFreq {
Daily,
Weekly,
@@ -69,12 +139,18 @@ fun parseSimpleRecurrence(
?: return null
val interval = parts["INTERVAL"]?.let { it.toIntOrNull()?.takeIf { n -> n >= 1 } ?: return null } ?: 1
// BYDAY is simple only as plain weekday picks on a weekly rule; ordinal
// forms ("2TH" = second Thursday) and BYDAY on other frequencies are not.
val byDays = parts["BYDAY"]?.let { raw ->
if (freq != RecurrenceFreq.Weekly) return null
raw.split(',').map { token -> rruleDay(token.trim()) ?: return null }.toSet()
} ?: emptySet()
// BYDAY is simple as plain weekday picks on a weekly rule, or as one
// ordinal weekday ("2TH" = second Thursday) on a monthly rule.
var byDays = emptySet<DayOfWeek>()
var monthlyWeekday: MonthlyWeekday? = null
parts["BYDAY"]?.let { raw ->
when (freq) {
RecurrenceFreq.Weekly ->
byDays = raw.split(',').map { token -> rruleDay(token.trim()) ?: return null }.toSet()
RecurrenceFreq.Monthly -> monthlyWeekday = MonthlyWeekday.parse(raw) ?: return null
else -> return null
}
}
val until = parts["UNTIL"]
val count = parts["COUNT"]
@@ -84,7 +160,7 @@ fun parseSimpleRecurrence(
count != null -> RecurrenceEnd.Count(count.toIntOrNull()?.takeIf { it >= 1 } ?: return null)
else -> RecurrenceEnd.Never
}
return SimpleRecurrence(freq, interval, end, byDays)
return SimpleRecurrence(freq, interval, end, byDays, monthlyWeekday)
}
/**
@@ -113,6 +189,10 @@ fun SimpleRecurrence.toRRule(zone: TimeZone = TimeZone.currentSystemDefault()):
.joinToString(",") { RRULE_DAY_CODES.getValue(it) },
)
}
if (freq == RecurrenceFreq.Monthly && monthlyWeekday != null) {
append(";BYDAY=")
append(monthlyWeekday.token)
}
when (val e = end) {
RecurrenceEnd.Never -> Unit
is RecurrenceEnd.Until -> {
@@ -148,7 +228,7 @@ internal val RRULE_DAY_CODES: Map<DayOfWeek, String> = mapOf(
)
/** Exact two-letter BYDAY token → weekday; ordinal forms ("2TH") return null. */
private fun rruleDay(token: String): DayOfWeek? =
internal fun rruleDay(token: String): DayOfWeek? =
RRULE_DAY_CODES.entries.firstOrNull { it.value == token.uppercase() }?.key
/**
@@ -178,3 +258,26 @@ private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? {
if (raw.length < 15 || raw[8] != 'T') return date
return parseBasicDateTime(raw)?.toInstant(TimeZone.UTC)?.toLocalDateTime(zone)?.date
}
/**
* The form moved forward to the first day its monthly weekday-position rule
* fires on, keeping time of day and length (#520); unchanged for any other rule
* or when the start already matches.
*/
fun EventForm.alignedToRecurrence(deviceZone: TimeZone): EventForm {
val position = rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday ?: return this
val target = position.firstOnOrAfter(start.date)
return shiftedByDays((target.toEpochDays() - start.date.toEpochDays()).toInt(), deviceZone)
}
/**
* The form repeating by [rrule]. The start only moves onto the rule's first day
* when the weekday position is new, so re-confirming a series' own rule never
* shifts its start.
*/
fun EventForm.withRecurrence(rrule: String?, deviceZone: TimeZone): EventForm {
val before = this.rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday
val after = rrule?.let { parseSimpleRecurrence(it, deviceZone) }?.monthlyWeekday
val next = copy(rrule = rrule)
return if (after != null && after != before) next.alignedToRecurrence(deviceZone) else next
}
@@ -54,16 +54,23 @@ private fun SimpleRecurrence.occurrencesInPeriod(period: Int, start: LocalDate):
when (freq) {
RecurrenceFreq.Daily -> listOf(start.plus(period * interval, DateTimeUnit.DAY))
RecurrenceFreq.Weekly -> weeklyOccurrences(period, start)
RecurrenceFreq.Monthly -> {
val month = start.plus(period * interval, DateTimeUnit.MONTH)
// plus() clamps into the shorter month, but the rule skips such a
// period — so a clamped date means "not this month".
listOfNotNull(dateOrNull(month.year, month.month.number, start.day))
}
RecurrenceFreq.Monthly -> monthlyOccurrences(period, start)
RecurrenceFreq.Yearly ->
listOfNotNull(dateOrNull(start.year + period * interval, start.month.number, start.day))
}
/** One monthly period: the weekday position if set, else the start's day of the month. */
private fun SimpleRecurrence.monthlyOccurrences(period: Int, start: LocalDate): List<LocalDate> {
monthlyWeekday?.let { pos ->
val month = LocalDate(start.year, start.month, 1).plus(period * interval, DateTimeUnit.MONTH)
return listOfNotNull(pos.dateIn(month.year, month.month.number))
}
val month = start.plus(period * interval, DateTimeUnit.MONTH)
// plus() clamps into the shorter month, but the rule skips such a
// period — so a clamped date means "not this month".
return listOfNotNull(dateOrNull(month.year, month.month.number, start.day))
}
/**
* One weekly block: every picked weekday inside the week that begins
* `period * interval` weeks after the start's own week, in weekday order. With
@@ -0,0 +1,13 @@
package de.jeanlucmakiola.calendula.domain.reminders
/**
* The wall-clock times all-day reminders fire at, as minutes from local
* midnight: the global [default], and the calendars that set their own (#541).
*/
data class AllDayReminderTimes(
val default: Int,
val perCalendar: Map<Long, Int> = emptyMap(),
) {
/** [calendarId]'s own time, or the global one when it sets none. */
fun forCalendar(calendarId: Long): Int = perCalendar[calendarId] ?: default
}
@@ -67,8 +67,8 @@ private const val MINUTES_PER_DAY = 1_440
* Pair every instance with each of its event's reminder offsets.
*
* Timed occurrences fire at `begin − minutes`. All-day ones read the offset only
* for *which day* it means ([allDayLeadDays]) and take the hour from
* [allDayTimeMinutes], recomposed against each occurrence's own date in [zone].
* for *which day* it means ([allDayLeadDays]) and take the hour [allDayTimes]
* names for their calendar, recomposed against each occurrence's own date in [zone].
* Duplicate offsets in [minutesByEvent] collapse.
*
* Every offset given is planned. The provider's "use the account default"
@@ -81,7 +81,7 @@ fun planReminders(
instances: List<ReminderEventInstance>,
minutesByEvent: Map<Long, List<Int>>,
zone: ZoneId,
allDayTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): List<PlannedReminder> = instances.flatMap { instance ->
minutesByEvent[instance.eventId].orEmpty()
.distinct()
@@ -90,7 +90,9 @@ fun planReminders(
instance = instance,
minutes = minutes,
alarmMillis = if (instance.isAllDay) {
allDayAlarmMillis(instance.beginMillis, minutes, zone, allDayTimeMinutes)
allDayAlarmMillis(
instance.beginMillis, minutes, zone, allDayTimes.forCalendar(instance.calendarId),
)
} else {
instance.beginMillis - minutes * MILLIS_PER_MINUTE
},
@@ -44,6 +44,7 @@ import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalDensity
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.data.time.currentDate
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
@@ -96,6 +97,10 @@ import de.jeanlucmakiola.calendula.ui.common.drillToDay
import de.jeanlucmakiola.calendula.ui.common.drillToWeek
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarSlideSpec
import de.jeanlucmakiola.calendula.ui.common.selectView
import de.jeanlucmakiola.calendula.ui.common.swapView
import de.jeanlucmakiola.calendula.ui.common.drillToMultiDay
import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount
import de.jeanlucmakiola.calendula.ui.week.MultiDayViewModel
import de.jeanlucmakiola.calendula.ui.common.viewBaseStack
import de.jeanlucmakiola.calendula.ui.detail.EventDetailScreen
import de.jeanlucmakiola.calendula.ui.edit.EventEditViewModel
@@ -187,7 +192,17 @@ fun CalendarHost(
requests.leaveTarget = requests.leaveTarget.afterMove(viewStack, moved)
viewStack = moved
}
val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } }
// A day count pinched or picked in the month (#389) lasts until the
// multi-day view is picked again.
val multiDayViewModel: MultiDayViewModel = hiltViewModel()
val multiDayRange by multiDayViewModel.rangeCount.collectAsStateWithLifecycle()
val onSelectView: (CalendarView) -> Unit = { target ->
if (target == CalendarView.MultiDay) multiDayViewModel.clearRange()
switchTo { it.selectView(target) }
}
val onPinchView: (CalendarView) -> Unit = { target ->
if (target != viewStack.last()) switchTo { it.swapView(target) }
}
val onOpenDay: (LocalDate) -> Unit = { date ->
focus.navigateTo(date)
switchTo { it.drillToDay() }
@@ -196,6 +211,16 @@ fun CalendarHost(
focus.navigateTo(date)
switchTo { it.drillToWeek() }
}
// A run of days picked in the month (#389): one day is the day view.
val onOpenRange: (LocalDate, Int) -> Unit = { start, count ->
if (count == 1) {
onOpenDay(start)
} else {
multiDayViewModel.showRange(start, count)
focus.navigateTo(start)
switchTo { it.drillToMultiDay() }
}
}
// The event-detail screen (S4) is a full-screen destination hoisted here so
// it overlays whichever calendar view is active. We forward the tapped
@@ -431,11 +456,17 @@ fun CalendarHost(
}
when (val req = widgetNavRequest) {
is WidgetNavRequest.OpenDate -> {
// Drop any overlay that would cover the day, so the open doesn't
// Another app's date tap opens the day view or the default view (#524).
val stack = req.stack(
defaultView,
if (req.external) viewModel.externalDateView() else ExternalDateView.DAY,
)
// Drop any overlay that would cover the date, so the open doesn't
// land under Settings/form.
dismissCoveringOverlays()
focus.navigateTo(LocalDate.parse(req.dateIso))
viewStack = listOf(defaultView).drillToDay()
val date = LocalDate.parse(req.dateIso)
if (stack.last() == CalendarView.Day) focus.navigateTo(date) else focus.showDate(date)
viewStack = stack
requests.leaveTarget = req.leaveTarget
requests.nav = null
}
@@ -670,20 +701,26 @@ fun CalendarHost(
showViewCalendars = true
switchScope.launch { drawerState.close() }
},
onManageGroups = {
showCalendars = true
switchScope.launch { drawerState.close() }
},
)
},
) {
Scaffold(
topBar = {
CalendarTopBar(
host = chromeHost,
selectedView = view,
quickSwitchViews = quickSwitchViews,
onCycleView = { onSelectView(viewStack.last().next(quickSwitchViews)) },
onOpenDrawer = { switchScope.launch { drawerState.open() } },
onOpenSearch = onOpenSearch,
showTodayButton = todayInToolbar,
)
CompositionLocalProvider(LocalMultiDayCount provides (multiDayRange ?: LocalMultiDayCount.current)) {
CalendarTopBar(
host = chromeHost,
selectedView = view,
quickSwitchViews = quickSwitchViews,
onCycleView = { onSelectView(viewStack.last().next(quickSwitchViews)) },
onOpenDrawer = { switchScope.launch { drawerState.open() } },
onOpenSearch = onOpenSearch,
showTodayButton = todayInToolbar,
)
}
},
floatingActionButton = {
// While an event is selected the FAB is its action bar's toggle (#141).
@@ -736,10 +773,13 @@ fun CalendarHost(
onEventClick = onEventClick,
onCreateEvent = onCreateEvent,
onCreateDraft = onCreateDraft,
onPinchView = onPinchView,
multiDayViewModel = multiDayViewModel,
)
ViewScreen.Month -> MonthScreen(
onOpenDay = onOpenDay,
onOpenWeek = onOpenWeek,
onOpenRange = onOpenRange,
onEventClick = onEventClick,
onCreateEvent = onCreateEvent,
)
@@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.currentDate
@@ -77,4 +78,9 @@ class CalendarHostViewModel @Inject constructor(
/** Whether tapping an event opens the edit form rather than the detail screen (#178). */
suspend fun tapOpensEditor(): Boolean = tapOpensEditorPref.first()
private val externalDateViewPref = prefs.externalDateView
/** What another app's date tap opens (#524). */
suspend fun externalDateView(): ExternalDateView = externalDateViewPref.first()
}
@@ -1,7 +1,13 @@
package de.jeanlucmakiola.calendula.ui
import android.content.Intent
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.drillToDay
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import java.io.Serializable
import kotlin.time.Instant
/**
* A navigation a home-screen widget asked the app to perform when launched.
@@ -16,8 +22,13 @@ sealed interface WidgetNavRequest : Serializable {
* Open the day view anchored on [dateIso] (an ISO `yyyy-MM-dd` date), over the
* default home view. [fromWidget] makes back leave the app at once (#530); a
* launcher/clock date tap (issue #9) or the daily summary backs out to home.
* [external] marks another app's date tap, which follows [ExternalDateView] (#524).
*/
data class OpenDate(val dateIso: String, val fromWidget: Boolean) : WidgetNavRequest
data class OpenDate(
val dateIso: String,
val fromWidget: Boolean,
val external: Boolean = false,
) : WidgetNavRequest
/** Open one occurrence's detail (a widget event tap), over [source]; back leaves the app (#530). */
data class OpenEvent(
@@ -40,6 +51,33 @@ sealed interface WidgetNavRequest : Serializable {
data class OpenView(val view: CalendarView?) : WidgetNavRequest
}
/** The view stack [this] lands on over [defaultView]: the day view, unless another app's date tap is set to the default view (#524). */
fun WidgetNavRequest.OpenDate.stack(defaultView: CalendarView, externalView: ExternalDateView): List<CalendarView> =
if (external && externalView == ExternalDateView.DEFAULT) listOf(defaultView) else listOf(defaultView).drillToDay()
/**
* The date request of the system "view time" intent (#9): ACTION_VIEW on
* `content://com.android.calendar/time/<epochMillis>`, dated in [zone]. [ownDayTap]
* marks our own daily summary's tap (#459), which stays on the day view. Null for
* any other intent.
*/
fun viewTimeRequest(
action: String?,
host: String?,
pathSegments: List<String>,
zone: TimeZone,
ownDayTap: Boolean,
): WidgetNavRequest.OpenDate? {
if (action != Intent.ACTION_VIEW || host != CALENDAR_PROVIDER_HOST) return null
if (pathSegments.firstOrNull() != "time") return null
val millis = pathSegments.getOrNull(1)?.toLongOrNull() ?: return null
val date = Instant.fromEpochMilliseconds(millis).toLocalDateTime(zone).date
return WidgetNavRequest.OpenDate(date.toString(), fromWidget = false, external = !ownDayTap)
}
/** The calendar provider's authority, which the system's calendar intents address. */
const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
/** What back leaves the app from (#530): a widget's day, or a widget's event detail. */
sealed interface LeaveTarget : Serializable {
/** The view a widget opened, while no overlay covers it. */
@@ -6,6 +6,7 @@ import de.jeanlucmakiola.calendula.ui.common.ScreenActions
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
import de.jeanlucmakiola.calendula.ui.common.ScreenChrome
import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.TakeDateRequest
import kotlinx.coroutines.flow.drop
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
@@ -93,12 +94,31 @@ fun AgendaScreen(
// the top. The top day still goes back to the shared focus.
val focus = LocalViewFocus.current
val opened = rememberSaveable { mutableStateOf(false) }
val restoreTop = remember(viewModel) {
if (restorePosition || opened.value) {
viewModel.lastTopDate
val scope = rememberCoroutineScope()
val listState = rememberLazyListState()
// Past days load above the anchor (#367), so the anchor's row counts as the
// start of the list.
val anchorIndex = remember { mutableIntStateOf(0) }
// Another app's date (#524) is where it opens; one asked for while it is up moves it there.
val requestedDate = TakeDateRequest(viewModel) { date ->
focus?.date = date
if (viewModel.anchor.value == date) {
scope.launch { listState.animateScrollToItem(anchorIndex.intValue) }
} else {
viewModel.goToToday()
null
viewModel.goToDate(date)
}
}
val restoreTop = remember(viewModel) {
when {
requestedDate != null -> {
viewModel.goToDate(requestedDate)
null
}
restorePosition || opened.value -> viewModel.lastTopDate
else -> {
viewModel.goToToday()
null
}
}
}
SideEffect { opened.value = true }
@@ -108,7 +128,6 @@ fun AgendaScreen(
val showToday by viewModel.showToday.collectAsStateWithLifecycle()
val weekStart by viewModel.weekStart.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var showRangePicker by remember { mutableStateOf(false) }
val isOnToday = when (val s = state) {
@@ -120,10 +139,6 @@ fun AgendaScreen(
// The agenda window always starts at the anchor, so moving through it is a
// list scroll, not an anchor change — "today" has to bring the list back to
// the top as well, and stay offered while it is scrolled away (#305).
val listState = rememberLazyListState()
// Past days load above the anchor (#367), so the anchor's row counts as the
// start of the list.
val anchorIndex = remember { mutableIntStateOf(0) }
val scrolledAway by remember {
derivedStateOf {
listState.firstVisibleItemIndex != anchorIndex.intValue ||
@@ -0,0 +1,180 @@
package de.jeanlucmakiola.calendula.ui.calendars
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
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.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.GroupedSurface
import de.jeanlucmakiola.floret.components.InlineTextField
import de.jeanlucmakiola.floret.components.MultiOptionRows
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf
/**
* The calendar groups (#166) in the manager: one row per group opening its
* editor, then "New group". Without groups only that row shows.
*/
@Composable
internal fun CalendarGroupsSection(
groups: List<CalendarGroup>,
calendars: List<CalendarSource>,
onEdit: (CalendarGroup) -> Unit,
onAdd: () -> Unit,
) {
if (groups.isNotEmpty()) GroupedSectionHeader(stringResource(R.string.calendar_groups_header))
val rows = groups.size + 1
groups.forEachIndexed { index, group ->
val count = group.resolve(calendars).size
GroupedRow(
title = group.name.orUnnamed(),
summary = if (count == 0) {
stringResource(R.string.calendar_groups_empty)
} else {
pluralStringResource(R.plurals.calendar_groups_count, count, count)
},
position = positionOf(index, rows),
leading = { LeadingAvatar(Icons.Default.Layers) },
onClick = { onEdit(group) },
)
}
GroupedRow(
title = stringResource(R.string.calendar_groups_new),
position = positionOf(groups.size, rows),
minHeight = 56.dp,
leading = { LeadingAvatar(Icons.Default.Add) },
onClick = onAdd,
)
}
/**
* Create or edit a calendar group: its name over [calendars] by account,
* checked ones being the members; the commit sits in the title bar.
*/
@Composable
internal fun CalendarGroupEditor(
sessionKey: Int,
isNew: Boolean,
initialName: String,
initialMembers: Set<Long>,
calendars: List<CalendarSource>,
onSave: (name: String, members: List<CalendarSource>) -> Unit,
onDelete: () -> Unit,
onClose: () -> Unit,
) {
var name by rememberSaveable(sessionKey) { mutableStateOf(initialName) }
var members by rememberSaveable(sessionKey) { mutableStateOf(initialMembers.toList()) }
var confirmDelete by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
val valid = name.isNotBlank()
val commit = {
if (valid) onSave(name.trim(), calendars.filter { it.id in members })
}
FullScreenPicker(
title = stringResource(if (isNew) R.string.calendar_groups_new else R.string.calendar_groups_edit),
onDismiss = onClose,
predictiveBack = true,
actions = {
Button(
onClick = commit,
enabled = valid,
modifier = Modifier.padding(end = 12.dp),
) { Text(stringResource(R.string.event_edit_save)) }
},
) {
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
Box(
modifier = Modifier.fillMaxWidth().heightIn(min = 72.dp).padding(horizontal = 20.dp),
contentAlignment = Alignment.CenterStart,
) {
InlineTextField(
value = name,
onValueChange = { name = it },
placeholder = stringResource(R.string.calendar_groups_name_hint),
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Done,
onImeAction = commit,
modifier = Modifier.fillMaxWidth().focusRequester(focusRequester),
)
}
}
LaunchedEffect(isNew) { if (isNew) focusRequester.requestFocus() }
calendars.groupByAccount().forEach { account ->
GroupedSectionHeader(accountGroupTitle(account))
MultiOptionRows(
options = account.calendars,
selected = account.calendars.filterTo(mutableSetOf()) { it.id in members },
label = { it.displayName.orUnnamed() },
onToggle = { calendar, checked ->
members = if (checked) members + calendar.id else members - calendar.id
},
leading = { CalendarColorChip(it.color) },
)
}
if (!isNew) {
Spacer(Modifier.height(24.dp))
DeleteCalendarRow(onClick = { confirmDelete = true })
}
Spacer(Modifier.height(24.dp))
}
if (confirmDelete) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text(stringResource(R.string.calendar_groups_delete_title)) },
text = { Text(stringResource(R.string.calendar_groups_delete_message, initialName)) },
confirmButton = {
TextButton(onClick = { confirmDelete = false; onDelete() }) {
Text(
stringResource(R.string.event_detail_delete),
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) {
Text(stringResource(R.string.dialog_cancel))
}
},
)
}
}
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.CalendarStateLabel
import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch
@@ -73,6 +74,10 @@ import de.jeanlucmakiola.calendula.domain.isNotSynced
import de.jeanlucmakiola.calendula.domain.orderedForManager
import de.jeanlucmakiola.calendula.domain.stateLabels
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
import de.jeanlucmakiola.floret.components.sameColor
import de.jeanlucmakiola.calendula.ui.common.CustomColorPicker
import de.jeanlucmakiola.calendula.ui.common.CustomColorRow
import de.jeanlucmakiola.calendula.ui.common.RecentColorsRow
import de.jeanlucmakiola.calendula.ui.common.AccountKey
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.CalendarView
@@ -125,6 +130,9 @@ import de.jeanlucmakiola.floret.components.GroupedSurface
/** Sentinel [editorId] meaning "the editor is composing a new calendar". */
private const val NEW_CALENDAR_ID = Long.MIN_VALUE
/** Sentinel group editor id meaning "the editor is composing a new group". */
private const val NEW_GROUP_ID = ""
/**
* Calendar manager (reached from Settings). Lists the app's own device-only
* calendars with create / rename / recolor / delete, and synced calendars
@@ -141,12 +149,17 @@ fun CalendarsScreen(
viewModel: CalendarsViewModel = hiltViewModel(),
) {
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
val calendarsLoaded by viewModel.calendarsLoaded.collectAsStateWithLifecycle()
val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle()
val error by viewModel.error.collectAsStateWithLifecycle()
val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle()
val recentCustomColors by viewModel.recentCustomColors.collectAsStateWithLifecycle()
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.refreshAccess() }
val loadedHiddenViews by viewModel.hiddenViews.collectAsStateWithLifecycle()
val hiddenViews = loadedHiddenViews.orEmpty()
val calendarGroups by viewModel.calendarGroups.collectAsStateWithLifecycle()
// null = closed; NEW_GROUP_ID = create; any other id = edit that group (#166).
var groupEditorId by rememberSaveable { mutableStateOf<String?>(null) }
// null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar.
// [editorSession] bumps on every open so the editor's field state resets for
@@ -168,6 +181,8 @@ fun CalendarsScreen(
showHiddenViews = true,
initialHiddenViews = editing?.let { hiddenViews[it.id] }.orEmpty(),
deleteLocked = editing != null && editing.id in deleteLockedIds,
recentColors = recentCustomColors,
onCustomColorUsed = viewModel::addRecentCustomColor,
onSave = { name, color, description, views ->
val id = editorId
if (id == null || id == NEW_CALENDAR_ID) {
@@ -200,7 +215,37 @@ fun CalendarsScreen(
onSetAccountVisible = viewModel::setAccountVisible,
syncAccessDismissed = syncAccessDismissed,
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
calendarGroups = calendarGroups.orEmpty(),
onEditGroup = { group -> editorSession++; groupEditorId = group.id },
onAddGroup = { editorSession++; groupEditorId = NEW_GROUP_ID },
)
groupEditorId?.let { id ->
val groups = calendarGroups
val editing = groups?.firstOrNull { it.id == id }
if (groups != null && id != NEW_GROUP_ID && editing == null) {
LaunchedEffect(id) { groupEditorId = null }
} else if (groups != null && calendarsLoaded) {
// Seeded once per open, so it waits for the calendars its members resolve against.
CalendarGroupEditor(
sessionKey = editorSession,
isNew = editing == null,
initialName = editing?.name.orEmpty(),
initialMembers = editing?.resolve(calendars)?.mapTo(mutableSetOf()) { it.id }.orEmpty(),
// Switched-off calendars aren't offered, but stay members.
calendars = calendars.filter { it.isVisibleInSystem },
onSave = { name, members ->
val switchedOff = editing?.resolve(calendars).orEmpty().filterNot { it.isVisibleInSystem }
viewModel.saveGroup(editing?.id, name, members + switchedOff)
groupEditorId = null
},
onDelete = {
editing?.let { viewModel.deleteGroup(it.id) }
groupEditorId = null
},
onClose = { groupEditorId = null },
)
}
}
hidingId?.let { id ->
val calendar = calendars.firstOrNull { it.id == id }
// Gone while the picker was up; an empty list is one still loading, not a deletion.
@@ -237,6 +282,9 @@ private fun CalendarsList(
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
syncAccessDismissed: List<SyncAccount>,
onAskSyncAccessAgain: (SyncAccount) -> Unit,
calendarGroups: List<CalendarGroup>,
onEditGroup: (CalendarGroup) -> Unit,
onAddGroup: () -> Unit,
) {
val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() }
@@ -260,6 +308,14 @@ private fun CalendarsList(
predictiveBack = true,
visible = visible,
) {
CalendarGroupsSection(
groups = calendarGroups,
calendars = local + synced,
onEdit = onEditGroup,
onAdd = onAddGroup,
)
Spacer(Modifier.height(16.dp))
// What the per-calendar / per-account switches below actually do.
GroupedHint(stringResource(R.string.calendars_visibility_hint), style = MaterialTheme.typography.bodySmall)
@@ -408,12 +464,15 @@ internal fun CalendarEditor(
deleteLocked: Boolean = false,
showHiddenViews: Boolean = false,
initialHiddenViews: Set<CalendarView> = emptySet(),
recentColors: List<Int> = emptyList(),
onCustomColorUsed: (Int) -> Unit = {},
) {
var name by rememberSaveable(sessionKey) { mutableStateOf(initialName) }
val seededHiddenViews = rememberSaveable(sessionKey) { initialHiddenViews }
var hiddenViews by rememberSaveable(sessionKey) { mutableStateOf(initialHiddenViews) }
var pickHiddenViews by rememberSaveable(sessionKey) { mutableStateOf(false) }
var color by rememberSaveable(sessionKey) { mutableStateOf(initialColor) }
var pickCustomColor by rememberSaveable(sessionKey) { mutableStateOf(false) }
var description by rememberSaveable(sessionKey) { mutableStateOf(initialDescription) }
var confirmDelete by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
@@ -426,6 +485,7 @@ internal fun CalendarEditor(
.filter { (it in hiddenViews) != (it in seededHiddenViews) }
.associateWith { it in hiddenViews }
onSave(name.trim(), color, description.trim().ifEmpty { null }, changes)
if (!sameColor(color, initialColor) && CalendarColorPalette.presetOf(color) == null) onCustomColorUsed(color)
}
}
@@ -462,7 +522,16 @@ internal fun CalendarEditor(
Spacer(Modifier.height(20.dp))
EditorSectionLabel(stringResource(R.string.calendars_color_label))
CalendarColorGrid(selected = color, onSelect = { color = it })
// A stored colour that is no preset stays as it is and shows as custom.
val customColor = color.takeIf { CalendarColorPalette.presetOf(it) == null }
CalendarColorGrid(
selected = color,
recents = recentColors,
onSelect = { color = it },
onSelectRecent = { color = it },
)
Spacer(Modifier.height(8.dp))
CustomColorRow(customColor = customColor, onClick = { pickCustomColor = true })
Spacer(Modifier.height(20.dp))
EditorSectionLabel(stringResource(R.string.calendars_description_label))
@@ -496,6 +565,17 @@ internal fun CalendarEditor(
Spacer(Modifier.height(24.dp))
}
if (pickCustomColor) {
CustomColorPicker(
initial = color,
onPick = {
color = it
pickCustomColor = false
},
onDismiss = { pickCustomColor = false },
)
}
if (pickHiddenViews) {
HiddenViewsPicker(
calendarName = name.trim().orUnnamed(),
@@ -581,7 +661,12 @@ private fun CalendarNameField(
* colours" preference included.
*/
@Composable
private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) {
private fun CalendarColorGrid(
selected: Int,
recents: List<Int>,
onSelect: (Int) -> Unit,
onSelectRecent: (Int) -> Unit,
) {
val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
@@ -600,7 +685,7 @@ private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) {
ColorSwatch(
fill = eventFill(swatch, dark, soften),
label = stringResource(swatchLabel(swatch)),
selected = swatch == selected,
selected = sameColor(swatch, selected),
onClick = { onSelect(swatch) },
modifier = Modifier.weight(1f),
)
@@ -610,6 +695,12 @@ private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) {
repeat(SWATCHES_PER_ROW - row.size) { Spacer(Modifier.weight(1f)) }
}
}
RecentColorsRow(
recents = recents,
selected = selected.takeIf { CalendarColorPalette.presetOf(it) == null },
onSelect = onSelectRecent,
modifier = Modifier.padding(horizontal = 4.dp),
)
}
}
}
@@ -692,7 +783,7 @@ private fun ManagedNote() {
}
@Composable
private fun DeleteCalendarRow(onClick: () -> Unit) {
internal fun DeleteCalendarRow(onClick: () -> Unit) {
GroupedSurface(
position = Position.Alone,
modifier = Modifier.padding(horizontal = 16.dp),
@@ -13,7 +13,11 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.withGroup
import java.util.UUID
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.backup.BackupSelection
@@ -52,6 +56,7 @@ class CalendarsViewModel @Inject constructor(
private val repository: CalendarRepository,
private val icsExporter: IcsExporter,
private val settingsPrefs: SettingsPrefs,
private val calendarPrefs: CalendarPrefs,
@IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() {
@@ -64,6 +69,14 @@ class CalendarsViewModel @Inject constructor(
initialValue = emptyList(),
)
/** Whether [calendars] holds a real read rather than its empty start or a failed read's empty list. */
val calendarsLoaded: StateFlow<Boolean> =
repository.calendars()
.map { true }
.catch { emit(false) }
.flowOn(io)
.stateWhileSubscribed(scope = viewModelScope, initialValue = false)
/**
* Accounts the drawer was told not to ask sync-request access for (#240),
* limited to those still behind a visible calendar and still unreachable.
@@ -150,6 +163,29 @@ class CalendarsViewModel @Inject constructor(
settingsPrefs.setCalendarHiddenIn(id, view, hidden)
}
/** Recently used custom colours, shared with the event-colour picker. */
val recentCustomColors: StateFlow<List<Int>> =
settingsPrefs.recentCustomColors
.catch { emit(emptyList()) }
.stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList())
fun addRecentCustomColor(argb: Int) = write { settingsPrefs.addRecentCustomColor(argb) }
/** The calendar groups (#166); null until first read. */
val calendarGroups: StateFlow<List<CalendarGroup>?> =
calendarPrefs.calendarGroups
.catch { emit(emptyList()) }
.stateWhileSubscribed(scope = viewModelScope, initialValue = null)
/** Create (null [id]) or rewrite a calendar group with [members]. */
fun saveGroup(id: String?, name: String, members: List<CalendarSource>) = write {
calendarPrefs.updateCalendarGroups { it.withGroup(id ?: UUID.randomUUID().toString(), name, members) }
}
fun deleteGroup(id: String) = write {
calendarPrefs.updateCalendarGroups { groups -> groups.filterNot { it.id == id } }
}
private val _error = MutableStateFlow(false)
val error: StateFlow<Boolean> = _error.asStateFlow()
@@ -79,6 +79,7 @@ fun CalendarDrawer(
onJumpToDate: (LocalDate) -> Unit,
onSettings: () -> Unit,
onHideInView: () -> Unit,
onManageGroups: () -> Unit,
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
sync: DrawerSync? = null,
) {
@@ -123,7 +124,7 @@ fun CalendarDrawer(
Spacer(Modifier.height(16.dp))
DrawerSectionHeader(stringResource(R.string.filter_title))
CalendarFilterList(currentView = currentView, onHideInView = onHideInView)
CalendarFilterList(currentView = currentView, onHideInView = onHideInView, onManageGroups = onManageGroups)
Spacer(Modifier.height(16.dp))
GroupedRow(
@@ -126,6 +126,14 @@ fun List<CalendarView>.selectView(target: CalendarView): List<CalendarView> {
fun viewBaseStack(default: CalendarView, source: CalendarView): List<CalendarView> =
if (source == default) listOf(default) else listOf(default, source)
/**
* Swap the view on top for [target] in place, as a pinch changing the days shown
* does (#389): a home view stays at the bottom and the new one goes over it,
* and one already further down is returned to.
*/
fun List<CalendarView>.swapView(target: CalendarView): List<CalendarView> =
if (size <= 1) selectView(target) else dropLast(1).selectView(target)
/** Push the day view as a drill-in over the current stack (no-op if already on it). */
fun List<CalendarView>.drillToDay(): List<CalendarView> =
if (lastOrNull() == CalendarView.Day) this else this + CalendarView.Day
@@ -142,3 +150,7 @@ val CalendarView.screen: ViewScreen
/** Push the week view over the month after a week-number tap. */
fun List<CalendarView>.drillToWeek(): List<CalendarView> =
if (lastOrNull() == CalendarView.Week) this else this + CalendarView.Week
/** Push the multi-day view over the month after picking a run of days there (#389). */
fun List<CalendarView>.drillToMultiDay(): List<CalendarView> =
if (lastOrNull() == CalendarView.MultiDay) this else this + CalendarView.MultiDay
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -18,7 +17,13 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.selection.selectable
import de.jeanlucmakiola.floret.components.sameColor
import de.jeanlucmakiola.floret.components.formatHexColor
/**
* A wrapping row of round colour swatches; the one matching [selected] is
@@ -39,7 +44,7 @@ fun ColorSwatchRow(
val soften = LocalSoftenColors.current
FlowRow(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
colors.forEach { argb ->
val isSelected = argb == selected
val isSelected = sameColor(argb, selected)
val fill = eventFill(argb, dark, soften)
Box(
contentAlignment = Alignment.Center,
@@ -55,7 +60,8 @@ fun ColorSwatchRow(
Modifier
},
)
.clickable { onSelect(argb) },
.selectable(selected = isSelected, role = Role.RadioButton) { onSelect(argb) }
.semantics { contentDescription = formatHexColor(argb) },
) {
if (isSelected) {
Icon(
@@ -0,0 +1,156 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.floret.components.ColorPicker
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSurface
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.formatHexColor
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
/**
* The recently used custom colours under a "Recent" label; nothing when there
* are none. Shared by the calendar editor and the event-colour picker.
*/
@Composable
fun RecentColorsRow(
recents: List<Int>,
selected: Int?,
onSelect: (Int) -> Unit,
modifier: Modifier = Modifier,
) {
if (recents.isEmpty()) return
Column(modifier) {
Text(
text = stringResource(R.string.color_custom_recent),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
ColorSwatchRow(
colors = recents,
selected = selected,
onSelect = onSelect,
dark = LocalFloretDarkTheme.current,
)
}
}
/**
* The entry that opens [CustomColorPicker]. When the current colour is a custom
* one ([customColor] non-null) the row is the selection: it carries that
* colour's swatch and hex code.
*/
@Composable
fun CustomColorRow(
customColor: Int?,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
GroupedRow(
title = stringResource(R.string.color_custom),
summary = customColor?.let(::formatHexColor),
position = Position.Alone,
selected = customColor != null,
modifier = modifier,
leading = {
if (customColor != null) {
Box(
Modifier
.size(32.dp)
.clip(CircleShape)
.background(
eventFill(customColor, LocalFloretDarkTheme.current, LocalSoftenColors.current),
),
)
} else {
Icon(Icons.Default.Palette, contentDescription = null)
}
},
onClick = onClick,
)
}
/**
* Full-screen custom-colour surface: a preview painted the way the app will
* paint the colour, over the hue/saturation/brightness picker and hex field.
* The colour is committed through Select in the title bar.
*/
@Composable
fun CustomColorPicker(
initial: Int,
onPick: (Int) -> Unit,
onDismiss: () -> Unit,
) {
var color by rememberSaveable { mutableIntStateOf(initial or (0xFF shl 24)) }
FullScreenPicker(
title = stringResource(R.string.color_custom),
onDismiss = onDismiss,
predictiveBack = true,
actions = {
Button(
onClick = { onPick(color) },
modifier = Modifier.padding(end = 12.dp),
) { Text(stringResource(R.string.color_custom_select)) }
},
) {
val fill = eventFill(color, LocalFloretDarkTheme.current, LocalSoftenColors.current)
Box(
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth()
.height(72.dp)
.clip(RoundedCornerShape(22.dp))
.background(fill)
.padding(horizontal = 20.dp),
contentAlignment = Alignment.CenterStart,
) {
Text(
text = stringResource(R.string.color_custom_preview),
style = MaterialTheme.typography.titleMedium,
color = eventInk(fill),
)
}
Spacer(Modifier.height(16.dp))
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
ColorPicker(
color = color,
onColorChange = { color = it },
hueLabel = stringResource(R.string.color_custom_hue),
saturationLabel = stringResource(R.string.color_custom_saturation),
brightnessLabel = stringResource(R.string.color_custom_brightness),
hexLabel = stringResource(R.string.color_custom_hex),
hexError = stringResource(R.string.color_custom_hex_error),
modifier = Modifier.padding(20.dp),
)
}
Spacer(Modifier.height(24.dp))
}
}
@@ -2,18 +2,21 @@ package de.jeanlucmakiola.calendula.ui.common
import android.icu.text.ListFormatter
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.MonthlyWeekday
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
import de.jeanlucmakiola.calendula.domain.occurrencesSpanYears
import de.jeanlucmakiola.calendula.domain.rruleParts
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate
import de.jeanlucmakiola.calendula.domain.upcomingOccurrences
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import kotlinx.datetime.toJavaDayOfWeek
import kotlinx.datetime.toJavaLocalDate
import java.time.DayOfWeek
import java.time.LocalDate
@@ -28,12 +31,23 @@ import java.util.Locale
/**
* Humanise an RFC 5545 RRULE into a localized phrase, e.g.
* "Every week on Tue and Thu until 31 Dec 2026" or "Every day, 10 times".
* Falls back to a generic label for rules we don't render in full (ordinal
* monthly/yearly BYDAY, etc.). Shared by the detail screen and the edit
* Falls back to a generic label for rules we don't render in full (yearly
* or multi-day ordinal BYDAY, etc.). Shared by the detail screen and the edit
* form's repeat card.
*/
@Composable
fun recurrenceText(rrule: String, locale: Locale): AnnotatedString {
val resources = LocalResources.current
return describeRecurrence(rrule, locale) { id, args -> resources.getString(id, *args) }
}
/** [recurrenceText] without Compose; [string] resolves a string resource with format args. */
internal fun describeRecurrence(
rrule: String,
locale: Locale,
string: (id: Int, args: Array<out Any>) -> String,
): AnnotatedString {
fun stringResource(id: Int, vararg args: Any): String = string(id, args)
val parts = rruleParts(rrule).mapNotNull { part -> part.key?.let { it to part.value } }.toMap()
val freq = parts["FREQ"]?.uppercase()
@@ -50,13 +64,20 @@ fun recurrenceText(rrule: String, locale: Locale): AnnotatedString {
else -> return AnnotatedString(stringResource(R.string.event_detail_recurring))
}
// Weekly + BYDAY → "<base> on <days>"; other BYDAY forms keep just the base.
// Weekly + BYDAY → "<base> on <days>"; monthly + one ordinal BYDAY →
// "<base> on the second <day>"; other BYDAY forms keep just the base.
// The day names + their joined block are tracked so only the names (not the
// commas/conjunction) can be italicised in the final string.
val byDay = parts["BYDAY"]
var dayNames: List<String>? = null
var joinedDays: String? = null
val main = if (freq == "WEEKLY" && !byDay.isNullOrBlank()) {
val monthlyWeekday = if (freq == "MONTHLY") byDay?.let(MonthlyWeekday::parse) else null
val main = if (monthlyWeekday != null) {
val name = monthlyWeekday.day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale)
dayNames = listOf(name)
joinedDays = name
stringResource(monthlyWeekdaySummary(monthlyWeekday.ordinal), base, name)
} else if (freq == "WEEKLY" && !byDay.isNullOrBlank()) {
val days = byDay.split(',').mapNotNull { rruleDayName(it.trim(), locale) }
if (days.isNotEmpty()) {
val joined = ListFormatter.getInstance(locale).format(days)
@@ -129,6 +150,16 @@ fun nextOccurrencesText(
/** Enough dates to show a rhythm (and a skipped month), few enough for one line. */
private const val NEXT_OCCURRENCE_COUNT = 3
/** Summary string for a monthly weekday position (1..5 or [MonthlyWeekday.LAST]). */
internal fun monthlyWeekdaySummary(ordinal: Int): Int = when (ordinal) {
1 -> R.string.recurrence_monthly_weekday_first
2 -> R.string.recurrence_monthly_weekday_second
3 -> R.string.recurrence_monthly_weekday_third
4 -> R.string.recurrence_monthly_weekday_fourth
5 -> R.string.recurrence_monthly_weekday_fifth
else -> R.string.recurrence_monthly_weekday_last
}
/** Map an RRULE BYDAY token (e.g. "TU" or "2TH") to a localized short weekday name. */
private fun rruleDayName(token: String, locale: Locale): String? {
val dow = when (token.takeLast(2).uppercase()) {
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
@@ -13,7 +14,8 @@ import kotlinx.datetime.LocalTime
/**
* M3 time picker in an alert dialog, seeded with [initial]. Shared by the event
* form (start/end times) and Settings (the all-day reminder fire time).
* form (start/end times) and Settings (the all-day reminder fire time). With
* [resetLabel], an extra button beside Cancel calls [onReset].
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -21,6 +23,8 @@ fun TimePickerAlert(
initial: LocalTime,
onConfirm: (LocalTime) -> Unit,
onDismiss: () -> Unit,
resetLabel: String? = null,
onReset: () -> Unit = {},
) {
// Honour the app's own time-format preference (the value every time label
// reads), not the system/locale clock — otherwise an explicit 24h setting
@@ -38,7 +42,10 @@ fun TimePickerAlert(
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_cancel)) }
Row {
if (resetLabel != null) TextButton(onClick = onReset) { Text(resetLabel) }
TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_cancel)) }
}
},
text = { TimePicker(state = state) },
)
@@ -15,6 +15,7 @@ import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
@@ -160,12 +161,13 @@ fun rememberTimelinePinchZoom(
viewportHeight: Dp,
hourHeight: Dp,
zoom: TimelineZoom,
axisLock: PinchAxisLock? = null,
): Modifier {
// The gesture loop outlives any single composition, so it reads these
// through state handles rather than capturing what they were when it started.
val currentHourHeight = rememberUpdatedState(hourHeight)
val currentViewport = rememberUpdatedState(viewportHeight)
return Modifier.pointerInput(scrollState, zoom) {
return Modifier.pointerInput(scrollState, zoom, axisLock) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
var claimed = false
@@ -181,7 +183,10 @@ fun rememberTimelinePinchZoom(
val step = event.calculateZoom()
if (!claimed) {
slop *= step
if (abs(slop - 1f) >= PINCH_SLOP) {
// Under a lock, only once it has been decided for this axis.
if (abs(slop - 1f) >= PINCH_SLOP &&
(axisLock == null || axisLock.axis == PinchAxis.Vertical)
) {
claimed = true
zoom.beginPinch()
}
@@ -280,4 +285,45 @@ internal fun anchoredScroll(
* enough to feel immediate, wide enough that the two-finger scroll a user meant
* as a scroll stays one.
*/
private const val PINCH_SLOP = 0.08f
internal const val PINCH_SLOP = 0.08f
/** Which way a two-finger pinch on the timeline runs, decided once per gesture (#389). */
enum class PinchAxis {
/** Side by side: the number of days shown. */
Horizontal,
/** Above each other: the hour scale (#56). */
Vertical,
}
/**
* The axis a pinch locks to, from how far the fingers' spread grew or shrank
* along each axis since they both came down. A horizontal pinch has to win
* clearly; anything less keeps the hour zoom it always was.
*/
fun lockPinchAxis(spreadChangeX: Float, spreadChangeY: Float): PinchAxis =
if (abs(spreadChangeX) > abs(spreadChangeY) * HORIZONTAL_AXIS_BIAS) PinchAxis.Horizontal else PinchAxis.Vertical
/** How much more a pinch has to run sideways than up and down to count as horizontal. */
private const val HORIZONTAL_AXIS_BIAS = 1.25f
/** How far [points] sit from their centroid on average, along each axis. */
fun spreadOf(points: List<Offset>): Offset {
if (points.isEmpty()) return Offset.Zero
val cx = points.sumOf { it.x.toDouble() }.toFloat() / points.size
val cy = points.sumOf { it.y.toDouble() }.toFloat() / points.size
return Offset(
points.sumOf { abs(it.x - cx).toDouble() }.toFloat() / points.size,
points.sumOf { abs(it.y - cy).toDouble() }.toFloat() / points.size,
)
}
/**
* The axis of the pinch in progress, shared by the detectors that each handle
* one: the one that tells them apart sits above the others, sees each event
* first and decides; the hour zoom only takes a pinch decided [PinchAxis.Vertical].
*/
class PinchAxisLock {
/** Null until the gesture under way has been decided. */
var axis: PinchAxis? = null
}
@@ -1,10 +1,12 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
@@ -29,8 +31,20 @@ class ViewFocus(initial: LocalDate) {
date = target
navigationVersion++
}
/** A date another app asked to see (#524), until the screen on show takes it. */
var dateRequest by mutableStateOf<DateRequest?>(null)
/** [navigateTo], also moving a screen that is already on show, the agenda included. */
fun showDate(target: LocalDate) {
navigateTo(target)
dateRequest = DateRequest(target)
}
}
/** One [ViewFocus.showDate]; compared by identity, so asking for the same date twice is two requests. */
class DateRequest(val date: LocalDate)
val ViewFocusSaver: Saver<ViewFocus, String> = Saver(
save = { it.date.toString() },
restore = { ViewFocus(LocalDate.parse(it)) },
@@ -47,3 +61,23 @@ fun <T : Any> EnterOnFocus(key: T, enter: (LocalDate) -> Unit) {
val focus = LocalViewFocus.current
remember(key) { focus?.date?.also(enter) }
}
/**
* Takes a pending [ViewFocus.dateRequest] while this screen is the one on show.
* Returns the date asked for as the screen came on ([key]), for it to open on;
* one arriving while it is already up goes to [onShown] instead.
*/
@Composable
fun <T : Any> TakeDateRequest(key: T, onShown: (LocalDate) -> Unit = {}): LocalDate? {
val focus = LocalViewFocus.current ?: return null
val current = LocalChromeSlot.current?.current ?: true
val request = focus.dateRequest?.takeIf { current }
val atEntry = remember(key) { request }
val shown by rememberUpdatedState(onShown)
LaunchedEffect(request) {
if (request == null) return@LaunchedEffect
focus.dateRequest = null
if (request !== atEntry) shown(request.date)
}
return atEntry?.date
}
@@ -3,19 +3,34 @@ package de.jeanlucmakiola.calendula.ui.common
import android.content.res.Resources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import de.jeanlucmakiola.calendula.data.prefs.WeekNumberingPref
import de.jeanlucmakiola.calendula.data.prefs.weekFields
import de.jeanlucmakiola.floret.time.rowWeekNumber
import kotlinx.datetime.LocalDate
import kotlinx.datetime.toJavaLocalDate
import java.time.temporal.WeekFields
import java.util.Locale
/** The week-numbering setting (#493), provided once at the app root. */
val LocalWeekNumbering = staticCompositionLocalOf { WeekNumberingPref.AUTO }
/**
* The week number of the grid row starting on [rowStart], numbered by the
* device region's rules (#493). The region, not the app language: an English
* UI in the Netherlands still numbers weeks the ISO way. Shared by the Month
* gutter and the Week badge so the two always agree.
* The week number of the 7-day row starting on [rowStart], counted by
* [numbering] (AUTO reads [region]). The row takes the week holding most of its
* days: that of its mid-week day in the numbering system (Thursday for ISO,
* Wednesday for US), so any "Week starts on" choice gets a consistent number.
*/
fun rowWeekNumber(rowStart: LocalDate, numbering: WeekNumberingPref, region: Locale): Int =
rowStart.toJavaLocalDate().rowWeekNumber(numbering.weekFields(region))
/**
* [rowWeekNumber] for the composition's numbering setting. AUTO follows the
* device region, not the app language: an English UI in the Netherlands still
* numbers weeks the ISO way. Shared by the Month gutter and the Week badge.
*/
@Composable
internal fun rememberRowWeekNumber(rowStart: LocalDate): Int {
val fields = remember { WeekFields.of(Resources.getSystem().configuration.locales[0]) }
return remember(rowStart, fields) { rowStart.toJavaLocalDate().rowWeekNumber(fields) }
val numbering = LocalWeekNumbering.current
val region = remember { Resources.getSystem().configuration.locales[0] }
return remember(rowStart, numbering, region) { rowWeekNumber(rowStart, numbering, region) }
}
@@ -138,6 +138,7 @@ import de.jeanlucmakiola.calendula.domain.zoneDescriptor
import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
import de.jeanlucmakiola.calendula.domain.EventFormProblem
import de.jeanlucmakiola.calendula.domain.RecurrenceEnd
import de.jeanlucmakiola.calendula.domain.MonthlyWeekday
import de.jeanlucmakiola.calendula.domain.RecurrenceFreq
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence
@@ -151,6 +152,9 @@ import de.jeanlucmakiola.calendula.ui.common.RecurringScopeDialog
import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups
import de.jeanlucmakiola.calendula.ui.common.CalendarDatePickerDialog
import de.jeanlucmakiola.calendula.ui.common.ColorSwatchRow
import de.jeanlucmakiola.calendula.ui.common.CustomColorPicker
import de.jeanlucmakiola.calendula.ui.common.CustomColorRow
import de.jeanlucmakiola.calendula.ui.common.RecentColorsRow
import de.jeanlucmakiola.calendula.ui.common.TimeZonePickerDialog
import de.jeanlucmakiola.calendula.ui.common.icuTimeZoneRegion
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
@@ -1557,6 +1561,7 @@ private fun EditSheetHost(
selected = form.color,
hasExplicitColor = form.color != null,
syncWarning = colorSyncRisk,
recents = state.recentCustomColors,
onPickKey = { key, argb ->
viewModel.setColorKey(key, argb)
onClose()
@@ -1565,6 +1570,10 @@ private fun EditSheetHost(
viewModel.setColorRaw(argb)
onClose()
},
onPickCustom = { argb ->
viewModel.setCustomColor(argb)
onClose()
},
onClear = {
viewModel.clearColor()
onClose()
@@ -1711,10 +1720,11 @@ private enum class RecurrenceEndMode { Never, Until, Count }
/**
* Recurrence picker, two steps like the reminder picker: the plain
* frequencies as a tappable list (one tap applies and closes), with "Custom"
* switching to an interval-plus-unit editor, weekday toggles (weekly only)
* and an end condition — only that step needs an OK button. A rule the
* simple shape can't express (ordinal BYDAY etc.) stays untouched unless the
* user picks something here.
* switching to an interval-plus-unit editor, weekday toggles (weekly only),
* day of month vs. weekday position (monthly only) and an end condition —
* only that step needs an OK button. A rule the simple shape can't express
* (several ordinal weekdays, BYSETPOS etc.) stays untouched unless the user
* picks something here.
*
* Both steps show the rule as *dates* as well as words: every preset row
* carries the next few occurrences it would produce from [startDate], and the
@@ -1731,7 +1741,7 @@ private fun RecurrencePickerDialog(
val startDay = startDate.dayOfWeek
val parsed = remember(current) { current?.let(::parseSimpleRecurrence) }
val isPlainPreset = parsed != null && parsed.interval == 1 &&
parsed.end == RecurrenceEnd.Never && parsed.byDays.isEmpty()
parsed.end == RecurrenceEnd.Never && parsed.byDays.isEmpty() && parsed.monthlyWeekday == null
var customMode by rememberSaveable { mutableStateOf(false) }
var intervalText by rememberSaveable { mutableStateOf((parsed?.interval ?: 1).toString()) }
var freq by rememberSaveable { mutableStateOf(parsed?.freq ?: RecurrenceFreq.Weekly) }
@@ -1741,6 +1751,15 @@ private fun RecurrencePickerDialog(
(parsed?.byDays?.takeIf { it.isNotEmpty() } ?: setOf(startDay)).toMask(),
)
}
// Monthly: "on day N" or a weekday position, the latter prefilled from the
// rule or else the start date and kept as a BYDAY token ("2TU", "-1SA").
var byWeekday by rememberSaveable { mutableStateOf(parsed?.monthlyWeekday != null) }
var weekdayToken by rememberSaveable {
mutableStateOf((parsed?.monthlyWeekday ?: MonthlyWeekday.suggestedFor(startDate)).token)
}
val weekdayPosition = MonthlyWeekday.parse(weekdayToken) ?: MonthlyWeekday.suggestedFor(startDate)
var showPositionPicker by rememberSaveable { mutableStateOf(false) }
var showWeekdayPicker by rememberSaveable { mutableStateOf(false) }
var endMode by rememberSaveable {
mutableStateOf(
when (parsed?.end) {
@@ -1788,11 +1807,14 @@ private fun RecurrencePickerDialog(
interval = interval,
end = customEnd,
byDays = if (freq == RecurrenceFreq.Weekly) daysMask.toDaySet() else emptySet(),
monthlyWeekday = weekdayPosition.takeIf { freq == RecurrenceFreq.Monthly && byWeekday },
)
} else {
null
}
val customResult: String? = customRule?.toRRule()
// Saving a weekday position moves the start onto its first match, so preview from there.
val previewStart = customRule?.monthlyWeekday?.firstOnOrAfter(startDate) ?: startDate
FullScreenPicker(
title = stringResource(R.string.event_detail_recurrence),
@@ -1863,7 +1885,7 @@ private fun RecurrencePickerDialog(
// Rendered even while incomplete (as an empty line), so the
// controls below don't shift as it comes and goes.
Text(
text = customRule?.let { nextOccurrencesText(it, startDate, locale) }.orEmpty(),
text = customRule?.let { nextOccurrencesText(it, previewStart, locale) }.orEmpty(),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
@@ -1944,6 +1966,52 @@ private fun RecurrencePickerDialog(
}
}
// Monthly: same day of the month, or a free weekday position
// whose position and weekday open their own pickers.
AnimatedVisibility(
visible = freq == RecurrenceFreq.Monthly,
enter = expandEnter(),
exit = collapseExit(),
) {
Column(modifier = Modifier.padding(top = 16.dp)) {
GroupedRow(
title = stringResource(R.string.event_edit_recurrence_monthly_day, startDate.day),
position = Position.Top,
checked = !byWeekday,
onClick = { byWeekday = false },
)
GroupedRow(
title = stringResource(
monthlyWeekdayLabel(weekdayPosition.ordinal),
weekdayPosition.day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale),
),
position = if (byWeekday) Position.Middle else Position.Bottom,
checked = byWeekday,
onClick = { byWeekday = true },
)
AnimatedVisibility(
visible = byWeekday,
enter = expandEnter(),
exit = collapseExit(),
) {
Column {
GroupedRow(
title = stringResource(R.string.event_edit_recurrence_position),
summary = stringResource(weekdayPositionName(weekdayPosition.ordinal)),
position = Position.Middle,
onClick = { showPositionPicker = true },
)
GroupedRow(
title = stringResource(R.string.event_edit_recurrence_weekday),
summary = weekdayName(weekdayPosition.day, locale),
position = Position.Bottom,
onClick = { showWeekdayPicker = true },
)
}
}
}
}
// Ends: a connected never / on-a-date / after-N group, the count
// field folding into the bottom of the run when chosen.
Column(modifier = Modifier.padding(top = 16.dp)) {
@@ -2013,6 +2081,27 @@ private fun RecurrencePickerDialog(
}
}
if (showPositionPicker) {
OptionPicker(
title = stringResource(R.string.event_edit_recurrence_position),
options = MONTHLY_POSITIONS,
selected = weekdayPosition.ordinal,
label = { stringResource(weekdayPositionName(it)) },
onSelect = { weekdayToken = weekdayPosition.copy(ordinal = it).token },
onDismiss = { showPositionPicker = false },
)
}
if (showWeekdayPicker) {
OptionPicker(
title = stringResource(R.string.event_edit_recurrence_weekday),
options = (0 until 7).map { DayOfWeek(((firstDayOfWeek.isoDayNumber - 1 + it) % 7) + 1) },
selected = weekdayPosition.day,
label = { weekdayName(it, locale) },
onSelect = { weekdayToken = weekdayPosition.copy(day = it).token },
onDismiss = { showWeekdayPicker = false },
)
}
if (showUntilPicker) {
CalendarDatePickerDialog(
initial = untilDate
@@ -2096,6 +2185,30 @@ private fun recurrencePresetLabel(freq: RecurrenceFreq): Int = when (freq) {
RecurrenceFreq.Yearly -> R.string.recurrence_yearly
}
private val MONTHLY_POSITIONS = (1..MonthlyWeekday.MAX_ORDINAL).toList() + MonthlyWeekday.LAST
private fun weekdayName(day: DayOfWeek, locale: Locale): String =
day.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL_STANDALONE, locale)
.replaceFirstChar { it.titlecase(locale) }
private fun weekdayPositionName(ordinal: Int): Int = when (ordinal) {
1 -> R.string.recurrence_position_first
2 -> R.string.recurrence_position_second
3 -> R.string.recurrence_position_third
4 -> R.string.recurrence_position_fourth
5 -> R.string.recurrence_position_fifth
else -> R.string.recurrence_position_last
}
private fun monthlyWeekdayLabel(ordinal: Int): Int = when (ordinal) {
1 -> R.string.event_edit_recurrence_monthly_weekday_first
2 -> R.string.event_edit_recurrence_monthly_weekday_second
3 -> R.string.event_edit_recurrence_monthly_weekday_third
4 -> R.string.event_edit_recurrence_monthly_weekday_fourth
5 -> R.string.event_edit_recurrence_monthly_weekday_fifth
else -> R.string.event_edit_recurrence_monthly_weekday_last
}
private fun recurrenceUnitLabel(freq: RecurrenceFreq): Int = when (freq) {
RecurrenceFreq.Daily -> R.string.recurrence_unit_days
RecurrenceFreq.Weekly -> R.string.recurrence_unit_weeks
@@ -2388,11 +2501,13 @@ private fun VisibilityPickerDialog(
}
/**
* Event-colour picker: just the swatches. A non-empty [palette] (the calendar
* account's published colours) picks by key so the colour round-trips through
* sync; otherwise the app's own palette writes a raw colour, with a
* [syncWarning] when that calendar may not keep it. The "Reset" button (shown
* only once a colour is set) drops back to the calendar's own colour.
* Event-colour picker. A non-empty [palette] (the calendar account's published
* colours) picks by key so the colour round-trips through sync; such an account
* rejects any other colour, so there is no custom entry. Otherwise the app's
* own presets, the recent custom colours and a custom entry write a raw colour,
* with a [syncWarning] when that calendar may not keep it. A raw colour that is
* no preset shows as the custom selection. "Reset" (shown only once a colour is
* set) drops back to the calendar's own colour.
*/
@Composable
private fun ColorPickerDialog(
@@ -2400,12 +2515,16 @@ private fun ColorPickerDialog(
selected: Int?,
hasExplicitColor: Boolean,
syncWarning: Boolean,
recents: List<Int>,
onPickKey: (String, Int) -> Unit,
onPickRaw: (Int) -> Unit,
onPickCustom: (Int) -> Unit,
onClear: () -> Unit,
onDismiss: () -> Unit,
) {
val dark = LocalFloretDarkTheme.current
var pickCustom by rememberSaveable { mutableStateOf(false) }
val customColor = selected?.takeIf { palette.isEmpty() && CalendarColorPalette.presetOf(it) == null }
FullScreenPicker(
title = stringResource(R.string.event_edit_color),
onDismiss = onDismiss,
@@ -2440,6 +2559,11 @@ private fun ColorPickerDialog(
},
dark = dark,
)
Text(
text = stringResource(R.string.color_custom_keyed_only),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
ColorSwatchRow(
colors = CalendarColorPalette.all,
@@ -2447,15 +2571,31 @@ private fun ColorPickerDialog(
onSelect = onPickRaw,
dark = dark,
)
if (syncWarning) {
Text(
text = stringResource(R.string.event_edit_color_sync_warning),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
RecentColorsRow(recents = recents, selected = customColor, onSelect = onPickCustom)
}
}
if (palette.isEmpty()) {
Spacer(Modifier.height(4.dp))
CustomColorRow(customColor = customColor, onClick = { pickCustom = true })
if (syncWarning) {
Text(
text = stringResource(R.string.event_edit_color_sync_warning),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp),
)
}
}
}
if (pickCustom) {
CustomColorPicker(
initial = selected ?: recents.firstOrNull() ?: CalendarColorPalette.Blue,
onPick = {
pickCustom = false
onPickCustom(it)
},
onDismiss = { pickCustom = false },
)
}
}
@@ -29,6 +29,8 @@ data class EventEditUiState(
val hiddenFields: List<EventFormField> = emptyList(),
/** Recently picked zones, most recent first — the zone picker's shortlist. */
val recentTimeZones: List<String> = emptyList(),
/** Recently used custom colours, most recent first; shared with the calendar editor. */
val recentCustomColors: List<Int> = emptyList(),
/** True while editing an existing event (the calendar is then fixed). */
val isEditing: Boolean = false,
/**
@@ -31,6 +31,8 @@ import de.jeanlucmakiola.calendula.domain.EventAttendee
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.alignedToRecurrence
import de.jeanlucmakiola.calendula.domain.withRecurrence
import de.jeanlucmakiola.calendula.domain.nextFullHour
import de.jeanlucmakiola.calendula.domain.toFormTime
import de.jeanlucmakiola.calendula.domain.resolvedZone
@@ -318,8 +320,8 @@ class EventEditViewModel @Inject constructor(
).flowOn(io),
colorPalette,
allCalendars,
settingsPrefs.recentTimeZones.flowOn(io),
) { local, external, palette, allCalendars, recentTimeZones ->
combine(settingsPrefs.recentTimeZones, settingsPrefs.recentCustomColors, ::Pair).flowOn(io),
) { local, external, palette, allCalendars, (recentTimeZones, recentCustomColors) ->
val form = local.form ?: return@combine null
val resolvedId = resolveEventCalendar(form.calendarId, external.hints, allCalendars)
// A colour is scoped to the calendar it came from, so one that came with
@@ -359,6 +361,7 @@ class EventEditViewModel @Inject constructor(
visibleFields = visibleFields,
hiddenFields = (offerableFields - visibleFields).sorted(),
recentTimeZones = recentTimeZones,
recentCustomColors = recentCustomColors,
isEditing = local.editTarget != null,
isManaged = isManaged,
autofocusTitle = external.autofocusTitle,
@@ -742,6 +745,12 @@ class EventEditViewModel @Inject constructor(
edit { it.copy(colorKey = null, color = argb) }
}
/** Pick a custom raw colour, which also goes to the front of the custom-colour recents. */
fun setCustomColor(argb: Int) {
setColorRaw(argb)
viewModelScope.launch { withContext(io) { settingsPrefs.addRecentCustomColor(argb) } }
}
/** Clear the colour so the event inherits its calendar's. */
fun clearColor() {
pinShownCalendar()
@@ -758,8 +767,11 @@ class EventEditViewModel @Inject constructor(
applyDefault { it.copy(calendarId = shown.calendarId, colorKey = shown.colorKey, color = shown.color) }
}
/** Bare RRULE value from the recurrence picker; null = does not repeat. */
fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) }
/**
* Bare RRULE value from the recurrence picker; null = does not repeat. A new
* monthly weekday position moves the start onto its first matching day (#520).
*/
fun setRecurrence(rrule: String?) = edit { it.withRecurrence(rrule, zoneSource.current()) }
fun addReminder(minutes: Int) {
_remindersTouched.value = true
@@ -1038,8 +1050,10 @@ class EventEditViewModel @Inject constructor(
_saveState.value = SaveUiState.Idle
}
/** A new start date under a monthly weekday-position rule moves on to the rule's next day (#520). */
private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = edit { form ->
form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start)
val moved = form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start)
if (moved.start.date != form.start.date) moved.alignedToRecurrence(zoneSource.current()) else moved
}
private fun moveEnd(transform: (LocalDateTime) -> LocalDateTime) = edit { form ->
@@ -7,15 +7,20 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.TriStateCheckbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -27,6 +32,9 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@@ -57,6 +65,7 @@ import de.jeanlucmakiola.floret.components.positionOf
fun CalendarFilterList(
currentView: CalendarView,
onHideInView: () -> Unit,
onManageGroups: () -> Unit,
modifier: Modifier = Modifier,
viewModel: FilterViewModel = hiltViewModel(),
) {
@@ -68,6 +77,7 @@ fun CalendarFilterList(
val hiddenInView = remember(s, currentView) { s.hiddenOnlyIn(currentView) }
FilterList(
groups = s.groups,
calendarGroups = s.calendarGroups,
hidden = s.hidden,
hiddenInView = hiddenInView,
hiddenOnlyHere = hiddenInView.size,
@@ -75,6 +85,7 @@ fun CalendarFilterList(
onHideInView = onHideInView,
onToggleCalendar = viewModel::toggleCalendar,
onToggleGroup = viewModel::toggleGroup,
onManageGroups = onManageGroups,
modifier = modifier,
)
}
@@ -89,6 +100,7 @@ fun CalendarFilterList(
@Composable
private fun FilterList(
groups: List<CalendarAccountGroup>,
calendarGroups: List<DrawerCalendarGroup>,
hidden: Set<Long>,
hiddenInView: Set<Long>,
hiddenOnlyHere: Int,
@@ -96,10 +108,14 @@ private fun FilterList(
onHideInView: () -> Unit,
onToggleCalendar: (Long) -> Unit,
onToggleGroup: (List<Long>) -> Unit,
onManageGroups: () -> Unit,
modifier: Modifier = Modifier,
) {
val viewName = currentView.label()
Column(modifier = modifier.fillMaxWidth()) {
if (calendarGroups.isNotEmpty()) {
CalendarGroupRows(calendarGroups, hidden, onToggleGroup, onManageGroups)
}
groups.forEach { group ->
val ids = group.calendars.map { it.id }
GroupHeader(
@@ -149,6 +165,63 @@ private fun FilterList(
}
}
/**
* The user's calendar groups (#166), above the accounts: each row shows and
* hides its member calendars together, decided like an account header (#143).
* A group with no listed calendar is shown but inert.
*/
@Composable
private fun CalendarGroupRows(
calendarGroups: List<DrawerCalendarGroup>,
hidden: Set<Long>,
onToggleGroup: (List<Long>) -> Unit,
onManageGroups: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = GroupedListInset, end = GroupedListInset / 2),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(R.string.calendar_groups_title),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
IconButton(onClick = onManageGroups) {
Icon(
Icons.Filled.Edit,
contentDescription = stringResource(R.string.calendar_groups_manage),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
calendarGroups.forEachIndexed { index, group ->
val empty = group.calendarIds.isEmpty()
val state = if (empty) ToggleableState.Off else groupVisibility(group.calendarIds, hidden)
GroupedRow(
title = group.name.orUnnamed(),
summary = if (empty) stringResource(R.string.calendar_groups_empty) else null,
position = positionOf(index, calendarGroups.size),
minHeight = 56.dp,
dimmed = empty,
leading = {
Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {
Icon(Icons.Filled.Layers, contentDescription = null)
}
},
trailing = { TriStateCheckbox(state = state, onClick = null, enabled = !empty) },
modifier = Modifier.semantics {
role = Role.Checkbox
toggleableState = state
},
onClick = if (empty) null else ({ onToggleGroup(group.calendarIds) }),
)
}
Spacer(Modifier.height(8.dp))
}
/**
* An account's header doubling as the group's parent checkbox (#143): checked
* when every calendar shows, indeterminate when some do. Tapping it shows all,
@@ -21,6 +21,7 @@ sealed interface FilterUiState {
val groups: List<CalendarAccountGroup>,
val hidden: Set<Long>,
val hiddenViews: Map<Long, Set<CalendarView>> = emptyMap(),
val calendarGroups: List<DrawerCalendarGroup> = emptyList(),
) : FilterUiState {
/**
* The listed calendars [view] hides on its own (#517); ones already
@@ -32,3 +33,6 @@ sealed interface FilterUiState {
}
}
}
/** A calendar group (#166) as the drawer toggles it: the listed calendars among its members. */
data class DrawerCalendarGroup(val id: String, val name: String, val calendarIds: List<Long>)
@@ -37,7 +37,8 @@ class FilterViewModel @Inject constructor(
prefs.hiddenCalendarIds,
// Only feeds a note on the rows; a failed read leaves it off rather than failing the list.
settingsPrefs.perCalendarHiddenViews.hidingNothingOnError(),
) { calendars, hidden, hiddenViews ->
prefs.calendarGroups,
) { calendars, hidden, hiddenViews, groups ->
// Calendars switched off device-wide don't belong in the drawer's
// hide/show list; they live only in Settings → Calendars.
val enabled = calendars.filter { it.isVisibleInSystem }
@@ -45,7 +46,13 @@ class FilterViewModel @Inject constructor(
if (failure != null) {
FilterUiState.Failure(failure)
} else {
FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews)
val listed = enabled.mapTo(mutableSetOf()) { it.id }
FilterUiState.Success(
groups = enabled.groupByAccount(),
hidden = hidden,
hiddenViews = hiddenViews,
calendarGroups = drawerCalendarGroups(groups, calendars, listed),
)
}
}
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
@@ -69,7 +76,8 @@ class FilterViewModel @Inject constructor(
}
/**
* Flip one calendar, or a whole group from its header (#143). Both decide
* Flip one calendar, or a whole account from its header (#143) or a
* calendar group (#166). All decide
* against the stored set rather than the last drawn state, so quick repeated
* taps still alternate.
*/
@@ -1,6 +1,8 @@
package de.jeanlucmakiola.calendula.ui.filter
import androidx.compose.ui.state.ToggleableState
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.CalendarSource
/** The drawer group header's checkbox state: on, off, or some of [calendarIds] shown. */
internal fun groupVisibility(calendarIds: Collection<Long>, hidden: Set<Long>): ToggleableState {
@@ -18,3 +20,15 @@ internal fun ToggleableState.nextGroupVisible(): Boolean = this != ToggleableSta
/** [hidden] after tapping the header of the group holding [calendarIds]. */
internal fun toggledGroup(hidden: Set<Long>, calendarIds: Collection<Long>): Set<Long> =
if (groupVisibility(calendarIds, hidden).nextGroupVisible()) hidden - calendarIds.toSet() else hidden + calendarIds
/**
* [groups] as the drawer lists them: members resolved against every calendar,
* so a switched-off one is not mistaken for another, then narrowed to [listed].
*/
internal fun drawerCalendarGroups(
groups: List<CalendarGroup>,
calendars: List<CalendarSource>,
listed: Set<Long>,
): List<DrawerCalendarGroup> = groups.map { group ->
DrawerCalendarGroup(group.id, group.name, group.resolve(calendars).map { it.id }.filter { it in listed })
}
@@ -89,6 +89,38 @@ internal fun isSameEvent(chip: EventInstance, moved: EventInstance): Boolean =
chip.eventId == moved.eventId ||
(moved.title.isNotBlank() && chip.title == moved.title)
/** The most days a range picked in the month opens (#389). */
const val MAX_RANGE_DAYS = 14
/** A run of days picked by dragging from [anchor]; [clamped] when the finger went further than it may reach. */
data class RangePick(val days: ClosedRange<LocalDate>, val clamped: Boolean) {
val count: Int get() = (days.endInclusive.toEpochDays() - days.start.toEpochDays()).toInt() + 1
}
/**
* The days a drag from [anchor] to [current] picks, earliest first, either way
* round, and at most [maxDays] long: past that it stops [maxDays] from [anchor].
* It also stops before the first day that isn't [pickable] (a blanked cell).
*/
fun pickRange(
anchor: LocalDate,
current: LocalDate,
maxDays: Int = MAX_RANGE_DAYS,
pickable: (LocalDate) -> Boolean = { true },
): RangePick {
val span = current.toEpochDays() - anchor.toEpochDays()
val reach = (maxDays - 1).toLong()
val clamped = abs(span) > reach
val step = if (span > 0) 1L else -1L
var end = anchor
repeat(minOf(abs(span), reach).toInt()) {
val next = LocalDate.fromEpochDays(end.toEpochDays() + step)
if (!pickable(next)) return RangePick(if (end < anchor) end..anchor else anchor..end, clamped = false)
end = next
}
return RangePick(if (end < anchor) end..anchor else anchor..end, clamped)
}
/** A chip in flight, in root coordinates so it can be drawn in an overlay. */
data class MonthChipDrag(
val event: EventInstance,
@@ -202,6 +234,36 @@ class MonthDragController {
private var pointer = Offset.Zero
private var sizePx = IntSize.Zero
private var rangeAnchor: LocalDate? = null
private var rangePickable: (LocalDate) -> Boolean = { true }
/** The days a long press and drag on empty space is picking (#389), or null. */
var range: RangePick? by mutableStateOf(null)
private set
/** Start picking days from [date], over the days [pickable] allows. */
fun beginRange(date: LocalDate, pickable: (LocalDate) -> Boolean = { true }) {
rangeAnchor = date
rangePickable = pickable
range = pickRange(date, date)
}
/** Follow the finger to the day under it; the last one stands while it is off the grid. */
fun moveRange(pointerInRoot: Offset) {
val anchor = rangeAnchor ?: return
val day = dateAt(pointerInRoot) ?: return
range = pickRange(anchor, day, pickable = rangePickable)
}
/** End the pick, handing back the days picked. */
fun finishRange(): RangePick? = range.also { cancelRange() }
fun cancelRange() {
rangeAnchor = null
rangePickable = { true }
range = null
}
fun putRow(token: Any, geometry: MonthRowGeometry) {
rows[token] = geometry
}
@@ -379,21 +441,24 @@ class MonthDragController {
bounds.left + column * row.columnWidthPx
}
/** The day under [pointer] in whichever visible row it is over. */
private fun dateAt(pointer: Offset): LocalDate? = rows.values.firstNotNullOfOrNull { row ->
val bounds = row.cell.takeIf { it.isAttached }?.boundsInRoot()
?: return@firstNotNullOfOrNull null
if (!bounds.contains(pointer) || row.columnWidthPx <= 0f) {
null
} else {
val column = ((pointer.x - bounds.left) / row.columnWidthPx)
.toInt()
.coerceIn(0, row.days.lastIndex)
row.days[if (row.isRtl) row.days.lastIndex - column else column]
}
}
private fun recompute() {
val event = event ?: return
val grabbed = grabDate ?: return
val resolved = rows.values.firstNotNullOfOrNull { row ->
val bounds = row.cell.takeIf { it.isAttached }?.boundsInRoot()
?: return@firstNotNullOfOrNull null
if (!bounds.contains(pointer) || row.columnWidthPx <= 0f) {
null
} else {
val column = ((pointer.x - bounds.left) / row.columnWidthPx)
.toInt()
.coerceIn(0, row.days.lastIndex)
row.days[if (row.isRtl) row.days.lastIndex - column else column]
}
}
val resolved = dateAt(pointer)
drag = MonthChipDrag(
event = event,
grabDate = grabbed,
@@ -25,6 +25,7 @@ import de.jeanlucmakiola.calendula.ui.common.ScreenChrome
import de.jeanlucmakiola.calendula.ui.common.LocalViewMorph
import de.jeanlucmakiola.calendula.ui.common.EnterOnFocus
import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.TakeDateRequest
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
import de.jeanlucmakiola.calendula.ui.common.morphDay
import de.jeanlucmakiola.calendula.ui.common.morphEvent
@@ -149,6 +150,7 @@ import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
@@ -189,6 +191,7 @@ import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.calendula.ui.common.next
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.launch
@@ -216,6 +219,9 @@ private fun MonthUiState.Success.withToday(today: LocalDate?): MonthUiState.Succ
if (today == null || today == this.today) this else copy(today = today)
private val LocalOpenWeek = staticCompositionLocalOf<((LocalDate) -> Unit)?> { null }
/** Opens the days picked by a long press and drag (#389). */
private val LocalOpenRange = staticCompositionLocalOf<((LocalDate, Int) -> Unit)?> { null }
/** A brief push from today's full cell into its immediate neighbours. */
@Composable
private fun rememberTodayRipple(active: Boolean): Animatable<Float, androidx.compose.animation.core.AnimationVector1D> {
@@ -268,6 +274,7 @@ private fun Modifier.todayRipple(relativeColumn: Int?, progress: () -> Float): M
fun MonthScreen(
onOpenDay: (LocalDate) -> Unit,
onOpenWeek: (LocalDate) -> Unit,
onOpenRange: (LocalDate, Int) -> Unit,
onEventClick: (EventInstance) -> Unit,
onCreateEvent: (LocalDate, Int?) -> Unit,
modifier: Modifier = Modifier,
@@ -480,6 +487,8 @@ fun MonthScreen(
jumpToMonth(target.yearMonth)
}
}
// Another app's date asked for while the month is already up (#524); on entry the focus did it.
TakeDateRequest(viewModel, onShown = jumpToDate)
PublishChrome(
ScreenChrome(
@@ -530,6 +539,7 @@ fun MonthScreen(
LocalTodayPulse provides todayPulse,
LocalMonthToday provides today,
LocalOpenWeek provides onOpenWeek,
LocalOpenRange provides onOpenRange,
) {
if (scrolling) {
ContinuousMonthContent(
@@ -2346,6 +2356,23 @@ private fun MonthWeekRow(
isRtl = isRtl,
chipTimes = chipTimes,
),
)
.then(
monthRangePickModifier(
week = week,
controller = dragController,
pickable = { d -> !blankOutside || inMonth(d) },
chipAt = { col, cellY ->
week.chipAtCellY(
col = col,
cellY = cellY,
bandTopInCell = bandTopInCell(cellCoordinates, bandCoordinates),
rowHeightPx = rowHeightPx,
laneCap = laneCap,
)
},
isRtl = isRtl,
),
),
) {
// What a chip has to spend, against what [timeFit] says its start
@@ -2566,6 +2593,25 @@ private fun MonthWeekRow(
}
}
// The days a long press and drag is picking (#389).
val picked = dragController?.range?.days
if (picked != null && week.days.any { it in picked }) {
val pickedColor = MaterialTheme.colorScheme.primary.copy(alpha = RANGE_PICK_ALPHA)
Row(Modifier.matchParentSize()) {
week.days.forEach { d ->
Box(
Modifier
.weight(1f)
.fillMaxHeight()
.padding(horizontal = CELL_GAP, vertical = 1.dp)
.then(
if (d in picked) Modifier.background(pickedColor, CELL_SHAPE) else Modifier,
),
)
}
}
}
// Invisible stand-in for the compact grid's selection outline, so it
// has somewhere to travel to and from. Its own layer rather than a
// child of the cell pill: that pill is itself a tagged piece, and a
@@ -2753,12 +2799,113 @@ private fun monthChipDragModifier(
onCancel = { controller?.cancel() },
)
/** The picked days' tint: M3's dragged state layer. */
private const val RANGE_PICK_ALPHA = 0.16f
/**
* Long press on a day's empty space and drag to pick a run of days, which opens
* in the timeline (#389). Only a press that then moves picks anything: one held
* still is left untouched, and lifts into the day's tap as it always did. A
* press on a chip is the chip's to drag.
*/
@Composable
private fun monthRangePickModifier(
week: MonthWeek,
controller: MonthDragController?,
pickable: (LocalDate) -> Boolean,
chipAt: (col: Int, cellY: Float) -> EventInstance?,
isRtl: Boolean,
): Modifier {
val openRange = LocalOpenRange.current
if (controller == null || openRange == null) return Modifier
val haptics = LocalHapticFeedback.current
val holdMillis = LocalViewConfiguration.current.longPressTimeoutMillis
val tolerance = with(LocalDensity.current) { RANGE_HOLD_TOLERANCE.toPx() }
val currentOpen by rememberUpdatedState(openRange)
val currentPickable by rememberUpdatedState(pickable)
val currentChipAt by rememberUpdatedState(chipAt)
val coordinates = remember { arrayOfNulls<LayoutCoordinates>(1) }
return Modifier
.onGloballyPositioned { coordinates[0] = it }
.pointerInput(week.days.first(), controller, isRtl) {
val slop = viewConfiguration.touchSlop
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
val origin = down.position
// Null once held long enough; anything else let go of it first.
val abandoned = withTimeoutOrNull(holdMillis) {
var still = true
while (still) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull { it.id == down.id }
still = change != null && change.pressed && event.changes.count { it.pressed } == 1 &&
(change.position - origin).getDistance() <= tolerance &&
// An ancestor's claim only shows once the main pass has run.
awaitPointerEvent(PointerEventPass.Final).changes.none { it.isConsumed }
}
true
}
if (abandoned != null) return@awaitEachGesture
val columnPx = size.width / 7f
if (columnPx <= 0f) return@awaitEachGesture
val column = (origin.x / columnPx).toInt().coerceIn(0, week.days.lastIndex)
val dayIndex = if (isRtl) week.days.lastIndex - column else column
val day = week.days[dayIndex]
if (!currentPickable(day) || currentChipAt(dayIndex, origin.y) != null) return@awaitEachGesture
// Held still so far: only moving on past slop makes it a pick.
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture
if (!change.pressed || change.isConsumed || event.changes.count { it.pressed } > 1) {
return@awaitEachGesture
}
// Taken before the pager or the list can read it as their own.
if ((change.position - origin).getDistance() > slop) {
change.consume()
break
}
}
controller.beginRange(day) { currentPickable(it) }
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
var picked = controller.range
var finished = false
try {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
val change = event.changes.firstOrNull { it.id == down.id } ?: break
if (change.isConsumed) break
change.consume()
if (!change.pressed) {
finished = true
break
}
coordinates[0]?.takeIf { it.isAttached }?.let { controller.moveRange(it.localToRoot(change.position)) }
val now = controller.range
if (now != null && now != picked) {
haptics.performHapticFeedback(
if (now.clamped && picked?.clamped != true) HapticFeedbackType.Reject
else HapticFeedbackType.SegmentTick,
)
}
picked = now
}
} finally {
val range = if (finished) controller.finishRange() else null
if (range == null) controller.cancelRange() else currentOpen(range.days.start, range.count)
}
}
}
}
/** How far the finger may wander while the press is held — as a chip pickup allows. */
private val RANGE_HOLD_TOLERANCE = 6.dp
/**
* Left-gutter calendar-week cell (#25): a full-height tonal pill mirroring the
* day cells' geometry, set apart by the secondaryContainer tint (matching the
* Week view's badge), with the week number centred like a day number. It is
* numbered by the device region from the row's mid-week day, as in the Week
* view, so it is right for any first weekday (#493).
* numbered by the week-numbering setting from the row's mid-week day, as in the
* Week view, so it is right for any first weekday (#493).
*/
@Composable
private fun WeekNumberGutter(weekStart: LocalDate, modifier: Modifier = Modifier) {
@@ -48,7 +48,8 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.appname.LauncherName
import de.jeanlucmakiola.calendula.data.launcher.LauncherIcon
import de.jeanlucmakiola.calendula.data.launcher.LauncherName
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.ui.theme.BundledFont
@@ -67,7 +68,7 @@ import de.jeanlucmakiola.floret.components.positionOf
/**
* Appearance: how the app itself looks — theme and colour, the two typeface
* roles, and the launcher name. Anything that only changes how a *calendar view*
* roles, and the launcher name and icon. Anything that only changes how a *calendar view*
* reads (week start, time format, grid options) lives in [ViewsScreen] instead,
* and the widget-only settings in [WidgetsScreen] (#69).
*/
@@ -82,9 +83,10 @@ internal fun AppearanceScreen(
var showBrandFont by remember { mutableStateOf(false) }
var showPlainFont by remember { mutableStateOf(false) }
var showAppName by remember { mutableStateOf(false) }
var showAppIcon by remember { mutableStateOf(false) }
val fonts by viewModel.fontState.collectAsStateWithLifecycle()
val launcherName by viewModel.launcherName.collectAsStateWithLifecycle()
val launcher by viewModel.launcher.collectAsStateWithLifecycle()
val context = LocalContext.current
val importFailedMessage = stringResource(R.string.settings_font_import_failed)
LaunchedEffect(Unit) {
@@ -153,14 +155,20 @@ internal fun AppearanceScreen(
Spacer(Modifier.height(16.dp))
// App name — the launcher label (#44); its own group, being a
// The launcher label (#44) and icon (#451); their own group, being a
// launcher concern rather than app styling.
GroupedRow(
title = stringResource(R.string.settings_app_name),
summary = launcherNameLabel(launcherName),
position = Position.Alone,
summary = launcherNameLabel(launcher.name),
position = Position.Top,
onClick = { showAppName = true },
)
GroupedRow(
title = stringResource(R.string.settings_app_icon),
summary = launcherIconLabel(launcher.icon),
position = Position.Bottom,
onClick = { showAppIcon = true },
)
}
if (showAppName) {
@@ -188,9 +196,10 @@ internal fun AppearanceScreen(
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
LauncherName.entries.forEach { option ->
AppNameOptionCard(
name = option,
selected = launcherName == option,
LauncherOptionCard(
icon = launcher.icon,
label = launcherNameLabel(option),
selected = launcher.name == option,
onClick = { viewModel.setLauncherName(option) },
modifier = Modifier.weight(1f),
)
@@ -198,6 +207,40 @@ internal fun AppearanceScreen(
}
}
}
if (showAppIcon) {
FullScreenPicker(
title = stringResource(R.string.settings_app_icon),
onDismiss = { showAppIcon = false },
predictiveBack = true,
) {
Text(
text = stringResource(R.string.settings_app_icon_summary),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
)
Spacer(Modifier.height(24.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
LauncherIcon.entries.forEach { option ->
LauncherOptionCard(
icon = option,
label = launcherIconLabel(option),
selected = launcher.icon == option,
onClick = { viewModel.setLauncherIcon(option) },
modifier = Modifier.weight(1f),
)
}
}
}
}
if (showTheme) {
// No thumbnails: picking a theme repaints the app itself. Only which
// way "Follow the system" currently falls needs spelling out.
@@ -275,6 +318,15 @@ private fun launcherNameLabel(name: LauncherName): String = stringResource(
},
)
/** The display name for a launcher-icon choice (issue #451). */
@Composable
private fun launcherIconLabel(icon: LauncherIcon): String = stringResource(
when (icon) {
LauncherIcon.BLOOM -> R.string.settings_app_icon_bloom
LauncherIcon.PLAIN -> R.string.settings_app_icon_plain
},
)
/**
* MIME types offered to the document picker so it lists only font files. Covers
* the modern `font/` types plus the legacy `application/` font aliases some
@@ -419,12 +471,13 @@ private fun FontOptionRow(
}
/**
* One selectable launcher-name preview in the App name picker (#44): the app's
* launcher mark over the name, framed as a card.
* One selectable launcher preview in the App name (#44) and App icon (#451)
* pickers: the launcher mark over its label, framed as a card.
*/
@Composable
private fun AppNameOptionCard(
name: LauncherName,
private fun LauncherOptionCard(
icon: LauncherIcon,
label: String,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
@@ -459,13 +512,18 @@ private fun AppNameOptionCard(
.background(colorResource(R.color.ic_launcher_background)),
) {
Image(
painter = painterResource(R.drawable.ic_launcher_foreground),
painter = painterResource(
when (icon) {
LauncherIcon.BLOOM -> R.drawable.ic_launcher_foreground
LauncherIcon.PLAIN -> R.drawable.ic_launcher_foreground_plain
},
),
contentDescription = null,
modifier = Modifier.fillMaxSize(),
)
}
Text(
text = launcherNameLabel(name),
text = label,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center,
@@ -33,6 +33,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker
import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel
import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker
import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
@@ -52,6 +53,7 @@ import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings
import kotlinx.datetime.LocalTime
/**
* Per-calendar notifications and reminder overrides (#145, #272), reached from
@@ -73,6 +75,7 @@ internal fun CalendarRemindersScreen(
val canFullScreen = rememberCanUseFullScreenIntent()
val context = LocalContext.current
var fixedOverrideFor by remember { mutableStateOf<Long?>(null) }
var allDayTimeFor by remember { mutableStateOf<Long?>(null) }
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
val calendarIds = state.reminderCalendars.map { it.id }
val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds)
@@ -129,6 +132,7 @@ internal fun CalendarRemindersScreen(
onEditOverride = { overrideDialog = it },
onEditFixedOverride = { fixedOverrideFor = calendar.id },
onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) },
onEditAllDayTime = { allDayTimeFor = calendar.id },
)
}
}
@@ -189,6 +193,26 @@ internal fun CalendarRemindersScreen(
inherited = state.defaultFixedTimeReminder,
)
}
allDayTimeFor?.let { calendarId ->
val minutes = state.allDayReminderTimeFor(calendarId)
TimePickerAlert(
initial = LocalTime(minutes / 60, minutes % 60),
onConfirm = {
viewModel.setCalendarAllDayReminderTime(calendarId, it.hour * 60 + it.minute)
allDayTimeFor = null
},
onDismiss = { allDayTimeFor = null },
resetLabel = if (calendarId in state.perCalendarAllDayReminderTime) {
stringResource(R.string.settings_calendar_allday_time_use_default)
} else {
null
},
onReset = {
viewModel.setCalendarAllDayReminderTime(calendarId, null)
allDayTimeFor = null
},
)
}
overrideDialog?.let { target ->
val map = if (target.isAllDay) {
state.perCalendarAllDayReminderOverride
@@ -215,7 +239,7 @@ internal fun CalendarRemindersScreen(
},
onDismiss = { overrideDialog = null },
leadTimeSummary = if (target.isAllDay) {
allDayFiringTimeSummary(state.allDayReminderTimeMinutes)
allDayFiringTimeSummary(state.allDayReminderTimeFor(target.calendarId))
} else {
null
},
@@ -227,7 +251,7 @@ internal fun CalendarRemindersScreen(
* One calendar in its account group, with its options unfolding beneath it:
* the notification switch and channel deep-link for every calendar, then the
* default-reminder overrides where it takes them — or, for a special-dates
* calendar, a link to the section that owns them.
* calendar, a link to the section that owns them — and its all-day reminder time (#541).
*/
@Composable
private fun CalendarReminderEntry(
@@ -251,6 +275,7 @@ private fun CalendarReminderEntry(
onEditOverride: (OverrideTarget) -> Unit,
onEditFixedOverride: () -> Unit,
onSetInDigest: (Boolean) -> Unit,
onEditAllDayTime: () -> Unit,
) {
val opensGroup = position == Position.Top || position == Position.Alone
val closesGroup = position == Position.Bottom || position == Position.Alone
@@ -313,11 +338,10 @@ private fun CalendarReminderEntry(
trailing = { ExternalLinkIcon() },
onClick = onOpenSettings,
)
val lastAlertRow = !(managed || takesOverrides || digestOn)
GroupedRow(
title = stringResource(R.string.settings_alert_style),
summary = alertStyleLabel(alertStyle),
position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle,
position = Position.Middle,
container = nested,
onClick = onEditAlertStyle,
)
@@ -325,7 +349,7 @@ private fun CalendarReminderEntry(
GroupedRow(
title = stringResource(R.string.settings_alert_sound),
summary = alertSoundLabel(alertStyle),
position = if (lastAlertRow && !heldBack.any) Position.Bottom else Position.Middle,
position = Position.Middle,
container = nested,
onClick = onEditAlertSound,
)
@@ -334,7 +358,7 @@ private fun CalendarReminderEntry(
GroupedRow(
title = stringResource(R.string.reminder_ring_channel_name),
summary = stringResource(R.string.settings_ring_blocked_hint),
position = if (lastAlertRow && !heldBack.permission) Position.Bottom else Position.Middle,
position = Position.Middle,
container = nested,
trailing = { ExternalLinkIcon() },
onClick = onOpenRingSettings,
@@ -344,7 +368,7 @@ private fun CalendarReminderEntry(
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,
position = Position.Middle,
container = nested,
trailing = { ExternalLinkIcon() },
onClick = onAllowFullScreen,
@@ -356,7 +380,7 @@ private fun CalendarReminderEntry(
checked = calendar.id !in state.dailyDigest.excludedCalendarIds,
onCheckedChange = onSetInDigest,
summary = stringResource(R.string.settings_calendar_in_digest_hint),
position = if (managed || takesOverrides) Position.Middle else Position.Bottom,
position = Position.Middle,
container = nested,
)
}
@@ -364,7 +388,7 @@ private fun CalendarReminderEntry(
GroupedRow(
title = stringResource(R.string.settings_default_reminder_allday),
summary = stringResource(R.string.settings_calendar_reminders_managed_hint),
position = Position.Bottom,
position = Position.Middle,
container = nested,
trailing = { ChevronIcon() },
onClick = onOpenSpecialDates,
@@ -398,11 +422,22 @@ private fun CalendarReminderEntry(
isAllDay = true,
choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id),
globalDefault = state.defaultAllDayReminderMinutes,
position = Position.Bottom,
position = Position.Middle,
container = nested,
onEditOverride = onEditOverride,
)
}
GroupedRow(
title = stringResource(R.string.settings_allday_reminder_time),
summary = state.perCalendarAllDayReminderTime[calendar.id]?.let { settingsTimeOfDay(it) }
?: stringResource(
R.string.settings_calendar_reminder_inherits,
settingsTimeOfDay(state.allDayReminderTimeMinutes),
),
position = Position.Bottom,
container = nested,
onClick = onEditAllDayTime,
)
}
}
}
@@ -79,7 +79,8 @@ internal fun settingsTimeOfDay(minutesOfDay: Int): String =
/**
* Second line for an all-day lead-time row: the clock time it fires at. The
* offset only decides which day; the hour comes from the global all-day setting
* offset only decides which day; the hour comes from [allDayReminderTimeMinutes],
* the calendar's own or the global all-day time
* (see [de.jeanlucmakiola.calendula.domain.reminders.planReminders]).
*/
@Composable
@@ -5,10 +5,12 @@ import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
import android.net.Uri
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
import de.jeanlucmakiola.calendula.data.prefs.WeekNumberingPref
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventFormField
@@ -46,6 +48,8 @@ data class SettingsUiState(
val dimCompletedEvents: Boolean = false,
/** Whether the Month grid shows calendar-week numbers in a left gutter (#25). */
val showWeekNumbers: Boolean = false,
/** How week numbers are counted in every view (#493). */
val weekNumbering: WeekNumberingPref = WeekNumberingPref.AUTO,
/** Whether Month chips may show start times before their titles (#476). */
val monthShowStartTimes: Boolean = true,
/** Whether the jump-to-today control sits in the top bar instead of the FAB (#60). */
@@ -62,6 +66,8 @@ data class SettingsUiState(
val agendaShowRangeBar: Boolean = true,
/** The calendar view the app opens on, and the home of the view back stack (M1). */
val defaultView: CalendarView = CalendarView.Week,
/** What a date tap from another app opens (#524). */
val externalDateView: ExternalDateView = ExternalDateView.DAY,
/** Which views the top-bar quick-switch button cycles through, and their order (#24). */
val quickSwitchConfig: QuickSwitchConfig = QuickSwitchConfig.Default,
/** How the Month view lays itself out: pages, continuous scroll, or split (#38, #53). */
@@ -90,6 +96,8 @@ data class SettingsUiState(
val defaultAllDayReminderMinutes: List<Int> = emptyList(),
/** Wall-clock time (minutes from midnight) all-day reminders fire at; default 09:00. */
val allDayReminderTimeMinutes: Int = SettingsPrefs.DEFAULT_ALLDAY_REMINDER_TIME,
/** Calendars' own all-day reminder times (#541); absent = the global one. */
val perCalendarAllDayReminderTime: Map<Long, Int> = emptyMap(),
/** How long the notification "Snooze" action defers a reminder; default 10 min. */
val snoozeMinutes: Int = SettingsPrefs.DEFAULT_SNOOZE_MINUTES,
/**
@@ -133,7 +141,11 @@ data class SettingsUiState(
* out to it instead of offering an override here.
*/
val managedCalendarIds: Set<Long> = emptySet(),
)
) {
/** [calendarId]'s all-day reminder time: its own, or the global one. */
fun allDayReminderTimeFor(calendarId: Long): Int =
perCalendarAllDayReminderTime[calendarId] ?: allDayReminderTimeMinutes
}
/**
* State for the contact special-dates sub-page (issue #15). Exposed as its own
@@ -147,6 +159,8 @@ data class SpecialDatesUiState(
val titleTemplates: Map<SpecialDateType, String> = emptyMap(),
/** The reminder choice per type's managed calendar (applied to all its events). */
val reminderChoices: Map<SpecialDateType, ReminderOverride> = emptyMap(),
/** The time each type's managed calendar reminds at: its own, or the global one (#541). */
val allDayReminderTimes: Map<SpecialDateType, Int> = emptyMap(),
/** Whether {year} resolves in titles (the source year is static and always correct). */
val showYear: Boolean = true,
/** True when READ_CONTACTS was revoked after enabling — the mirror is paused. */
@@ -10,8 +10,10 @@ 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.appname.LauncherName
import de.jeanlucmakiola.calendula.data.appname.LauncherNameManager
import de.jeanlucmakiola.calendula.data.launcher.LauncherName
import de.jeanlucmakiola.calendula.data.launcher.LauncherEntry
import de.jeanlucmakiola.calendula.data.launcher.LauncherIcon
import de.jeanlucmakiola.calendula.data.launcher.LauncherManager
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
@@ -30,6 +32,7 @@ import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
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.ExternalDateView
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
@@ -42,6 +45,7 @@ import de.jeanlucmakiola.floret.prefs.get
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.WeekNumberingPref
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus
import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels
@@ -90,7 +94,7 @@ class SettingsViewModel @Inject constructor(
repository: CalendarRepository,
private val specialDatesEngine: SpecialDatesSyncEngine,
specialDatesSpec: SpecialDatesCalendarSpec,
private val launcherNameManager: LauncherNameManager,
private val launcherManager: LauncherManager,
private val reminderScanner: ReminderScanner,
private val reminderChannels: ReminderChannels,
private val reminderNotifier: ReminderNotifier,
@@ -142,6 +146,7 @@ class SettingsViewModel @Inject constructor(
pastEventDisplay = this[SettingsKeys.pastEventDisplay],
dimCompletedEvents = this[SettingsKeys.dimCompletedEvents],
showWeekNumbers = this[SettingsKeys.showWeekNumbers],
weekNumbering = this[SettingsKeys.weekNumbering],
monthShowStartTimes = this[SettingsKeys.monthShowStartTimes],
todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar],
dragToReschedule = this[SettingsKeys.dragToReschedule],
@@ -150,6 +155,7 @@ class SettingsViewModel @Inject constructor(
agendaShowToday = this[SettingsKeys.agendaShowToday],
agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar],
defaultView = this[SettingsKeys.defaultView],
externalDateView = this[SettingsKeys.externalDateView],
quickSwitchConfig = this[SettingsKeys.quickSwitchConfig],
monthViewStyle = this[SettingsKeys.monthViewStyle],
timelineScale = this[SettingsKeys.timelineScale],
@@ -163,6 +169,7 @@ class SettingsViewModel @Inject constructor(
defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes],
defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes],
allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes],
perCalendarAllDayReminderTime = this[SettingsKeys.perCalendarAllDayReminderTime],
snoozeMinutes = this[SettingsKeys.snoozeMinutes],
perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride],
perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride],
@@ -200,17 +207,17 @@ class SettingsViewModel @Inject constructor(
)
/**
* The launcher-label choice (#44), backed by the manifest aliases'
* The launcher name (#44) and icon (#451), backed by the manifest aliases'
* component-enabled state rather than a preference. Seeded with the manifest
* default and corrected off-thread — `getComponentEnabledSetting` is a
* binder round-trip and this ViewModel is built on the main thread.
*/
private val _launcherName = MutableStateFlow(LauncherName.CALENDULA)
val launcherName: StateFlow<LauncherName> = _launcherName.asStateFlow()
private val _launcher = MutableStateFlow(LauncherEntry())
val launcher: StateFlow<LauncherEntry> = _launcher.asStateFlow()
init {
viewModelScope.launch {
_launcherName.value = withContext(io) { launcherNameManager.current() }
_launcher.value = withContext(io) { launcherManager.current() }
}
}
@@ -223,6 +230,8 @@ class SettingsViewModel @Inject constructor(
val specialDatesState: StateFlow<SpecialDatesUiState> = prefs.data.map { stored ->
val templates = stored.specialDatesTitleTemplates
val allDayOverrides = stored[SettingsKeys.perCalendarAllDayReminderOverride]
val allDayTimes = stored[SettingsKeys.perCalendarAllDayReminderTime]
val allDayTime = stored[SettingsKeys.allDayReminderTimeMinutes]
val status = stored.specialDatesStatus
SpecialDatesUiState(
enabled = stored[SettingsKeys.specialDatesEnabled],
@@ -236,6 +245,9 @@ class SettingsViewModel @Inject constructor(
reminderChoices = stored.specialDatesCalendars.mapValues { (_, calendarId) ->
allDayOverrides.reminderOverrideFor(calendarId)
},
allDayReminderTimes = stored.specialDatesCalendars.mapValues { (_, calendarId) ->
allDayTimes[calendarId] ?: allDayTime
},
showYear = stored[SettingsKeys.specialDatesShowYear],
stalledPermission = status.stalled == SpecialDatesStalledReason.PermissionRevoked,
lastRun = status.lastRun,
@@ -345,6 +357,8 @@ class SettingsViewModel @Inject constructor(
fun setShowWeekNumbers(enabled: Boolean) = save { setShowWeekNumbers(enabled) }
fun setWeekNumbering(pref: WeekNumberingPref) = save { setWeekNumbering(pref) }
fun setMonthShowStartTimes(enabled: Boolean) = save { setMonthShowStartTimes(enabled) }
fun setTodayButtonInToolbar(enabled: Boolean) = save { setTodayButtonInToolbar(enabled) }
@@ -354,16 +368,20 @@ class SettingsViewModel @Inject constructor(
fun setTapOpensEditor(enabled: Boolean) = save { setTapOpensEditor(enabled) }
/**
* Switch the launcher label (#44). The card highlights at once, then settles
* on what the component state reports; the writes are binder round-trips and
* run off the main thread.
* Switch the launcher label (#44) or icon (#451). The card highlights at
* once, then settles on what the component state reports; the writes are
* binder round-trips and run off the main thread.
*/
fun setLauncherName(name: LauncherName) {
_launcherName.value = name
fun setLauncherName(name: LauncherName) = updateLauncher({ copy(name = name) }) { setName(name) }
fun setLauncherIcon(icon: LauncherIcon) = updateLauncher({ copy(icon = icon) }) { setIcon(icon) }
private fun updateLauncher(optimistic: LauncherEntry.() -> LauncherEntry, write: LauncherManager.() -> Unit) {
_launcher.value = _launcher.value.optimistic()
viewModelScope.launch {
_launcherName.value = withContext(io) {
launcherNameManager.set(name)
launcherNameManager.current()
_launcher.value = withContext(io) {
launcherManager.write()
launcherManager.current()
}
}
}
@@ -373,6 +391,7 @@ class SettingsViewModel @Inject constructor(
fun setDimCompletedEvents(enabled: Boolean) = save { setDimCompletedEvents(enabled) }
fun setDefaultView(view: CalendarView) = save { setDefaultView(view) }
fun setExternalDateView(view: ExternalDateView) = save { setExternalDateView(view) }
fun setFormFieldDefault(field: EventFormField, enabled: Boolean) = save { setFormFieldDefault(field, enabled) }
@@ -585,6 +604,10 @@ class SettingsViewModel @Inject constructor(
/** The armed alarm was planned for the old hour, so re-plan against the new one. */
fun setAllDayReminderTimeMinutes(minutesOfDay: Int) = saveAndScan { setAllDayReminderTimeMinutes(minutesOfDay) }
/** [minutesOfDay] null follows the global time again; re-plans like the global setting (#541). */
fun setCalendarAllDayReminderTime(calendarId: Long, minutesOfDay: Int?) =
saveAndScan { setCalendarAllDayReminderTime(calendarId, minutesOfDay) }
fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) }
fun setCalendarReminderOverride(calendarId: Long, override: ReminderOverride) = save { setCalendarReminderOverride(calendarId, override) }
@@ -202,7 +202,9 @@ internal fun SpecialDatesScreen(
allowInherit = false,
onSelect = { viewModel.setSpecialDatesReminders(type, it) },
onDismiss = { reminderPickerType = null },
leadTimeSummary = allDayFiringTimeSummary(settings.allDayReminderTimeMinutes),
leadTimeSummary = allDayFiringTimeSummary(
state.allDayReminderTimes[type] ?: settings.allDayReminderTimeMinutes,
),
)
}
}
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.calendula.ui.settings
import android.content.res.Resources
import android.text.format.DateFormat
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
@@ -25,10 +26,13 @@ import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref
import de.jeanlucmakiola.calendula.data.prefs.WeekNumberingPref
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
import de.jeanlucmakiola.calendula.data.time.currentDate
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
import de.jeanlucmakiola.calendula.ui.common.AgendaRangePicker
import de.jeanlucmakiola.calendula.ui.common.CalendarView
@@ -43,6 +47,8 @@ import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay
import de.jeanlucmakiola.calendula.ui.common.icon
import de.jeanlucmakiola.calendula.ui.common.label
import de.jeanlucmakiola.calendula.ui.common.labelRes
import de.jeanlucmakiola.calendula.ui.common.rowWeekNumber
import de.jeanlucmakiola.calendula.ui.common.startOfWeek
import de.jeanlucmakiola.calendula.ui.month.labelRes
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedHint
@@ -76,7 +82,9 @@ internal fun ViewsScreen(
) {
var showMonthStyle by remember { mutableStateOf(false) }
var showDefaultView by remember { mutableStateOf(false) }
var showExternalDateView by remember { mutableStateOf(false) }
var showWeekStart by remember { mutableStateOf(false) }
var showWeekNumbering by remember { mutableStateOf(false) }
var showTimeFormat by remember { mutableStateOf(false) }
var showTapOpens by remember { mutableStateOf(false) }
var showPastEvents by remember { mutableStateOf(false) }
@@ -103,12 +111,24 @@ internal fun ViewsScreen(
position = Position.Top,
onClick = { showDefaultView = true },
)
GroupedRow(
title = stringResource(R.string.settings_external_date_view),
summary = externalDateViewLabel(state.externalDateView),
position = Position.Middle,
onClick = { showExternalDateView = true },
)
GroupedRow(
title = stringResource(R.string.settings_week_start),
summary = weekStartLabel(state.weekStart).capitalizeStart(currentLocale()),
position = Position.Middle,
onClick = { showWeekStart = true },
)
GroupedRow(
title = stringResource(R.string.settings_week_numbering),
summary = weekNumberingLabel(state.weekNumbering),
position = Position.Middle,
onClick = { showWeekNumbering = true },
)
GroupedRow(
title = stringResource(R.string.settings_time_format),
summary = timeFormatLabel(state.timeFormat),
@@ -328,6 +348,17 @@ internal fun ViewsScreen(
onDismiss = { showDefaultView = false },
)
}
if (showExternalDateView) {
OptionPicker(
title = stringResource(R.string.settings_external_date_view),
predictiveBack = true,
options = ExternalDateView.entries,
selected = state.externalDateView,
label = { externalDateViewLabel(it) },
onSelect = viewModel::setExternalDateView,
onDismiss = { showExternalDateView = false },
)
}
if (showWeekStart) {
WeekStartPicker(
selected = state.weekStart,
@@ -339,6 +370,25 @@ internal fun ViewsScreen(
onDismiss = { showWeekStart = false },
)
}
if (showWeekNumbering) {
val firstDay = state.weekStart.resolveFirstDay(currentLocale())
val rowStart = currentDate().startOfWeek(firstDay)
val region = remember { Resources.getSystem().configuration.locales[0] }
OptionPicker(
title = stringResource(R.string.settings_week_numbering),
header = { GroupedHint(stringResource(R.string.settings_week_numbering_hint), verticalPadding = 8.dp) },
predictiveBack = true,
options = WeekNumberingPref.entries,
selected = state.weekNumbering,
label = { weekNumberingLabel(it) },
// Each option shows the number it gives this week, so the difference is visible.
summary = {
stringResource(R.string.settings_week_numbering_this_week, rowWeekNumber(rowStart, it, region))
},
onSelect = viewModel::setWeekNumbering,
onDismiss = { showWeekNumbering = false },
)
}
if (showTimeFormat) {
val locale = currentLocale()
val systemIs24Hour = DateFormat.is24HourFormat(LocalContext.current)
@@ -507,6 +557,15 @@ private fun ViewRow(
)
}
@Composable
private fun weekNumberingLabel(pref: WeekNumberingPref): String = stringResource(
when (pref) {
WeekNumberingPref.AUTO -> R.string.settings_week_numbering_auto
WeekNumberingPref.ISO -> R.string.settings_week_numbering_iso
WeekNumberingPref.US -> R.string.settings_week_numbering_us
},
)
/** Picker options: "Follow system" first, then Monday…Sunday in ISO order. */
private val WEEK_START_OPTIONS: List<WeekStartPref> =
listOf(WeekStartPref.Auto) + DayOfWeek.entries.map { WeekStartPref.Day(it) }
@@ -519,6 +578,14 @@ internal fun weekStartLabel(pref: WeekStartPref): String = when (pref) {
.getDisplayName(JavaTextStyle.FULL, currentLocale())
}
@Composable
private fun externalDateViewLabel(view: ExternalDateView): String = stringResource(
when (view) {
ExternalDateView.DAY -> R.string.settings_external_date_day
ExternalDateView.DEFAULT -> R.string.settings_external_date_default
},
)
@Composable
private fun tapOpensLabel(editor: Boolean): String = stringResource(
if (editor) R.string.settings_tap_opens_editor else R.string.settings_tap_opens_details,
@@ -0,0 +1,112 @@
package de.jeanlucmakiola.calendula.ui.week
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import kotlin.math.floor
import kotlin.math.ln
/** The fewest days a pinch shows. */
const val MIN_PINCH_DAYS = 1
/** The most days a pinch shows, unless it started from more. */
const val MAX_PINCH_DAYS = 7
/** The day counts a pinch can step through, starting from [origin] days. */
fun pinchDayRange(origin: Int): IntRange = MIN_PINCH_DAYS..maxOf(MAX_PINCH_DAYS, origin)
/**
* The day count a pinch that started on [origin] days and has spread the
* fingers by [zoom] shows, stepping from [current].
*
* Each day takes the same share of spread, on a log scale, so seven to one day
* fits in one pinch. A step is only taken [STEP_HYSTERESIS] past the midpoint
* between two counts, and only given back as far past it the other way, so
* fingers held near a threshold don't flicker between two counts.
*/
fun steppedDayCount(current: Int, origin: Int, zoom: Float, range: IntRange = pinchDayRange(origin)): Int {
if (zoom <= 0f) return current
val position = origin - ln(zoom) / ln(DAY_STEP_ZOOM)
var count = current.coerceIn(range)
while (count > range.first && position < count - 0.5f - STEP_HYSTERESIS) count--
while (count < range.last && position > count + 0.5f + STEP_HYSTERESIS) count++
return count
}
/**
* Where across the day columns [x] falls, from the first day's edge (0) to the
* last one's (1). The columns sit between the hour gutter on the start side and
* [endInsetPx] on the end side, mirrored right to left.
*/
fun columnFraction(x: Float, width: Float, gutterPx: Float, endInsetPx: Float, isRtl: Boolean): Float {
val columns = width - gutterPx - endInsetPx
if (columns <= 0f) return 0f
val fromStart = if (isRtl) width - gutterPx - x else x - gutterPx
return (fromStart / columns).coerceIn(0f, 1f)
}
/** The column [fraction] falls in, of [count]. */
private fun columnAt(fraction: Float, count: Int): Int =
floor(fraction * count).toInt().coerceIn(0, count - 1)
/** The day under [fraction] across [span]. */
fun DaySpan.dayAt(fraction: Float): LocalDate = start.plus(columnAt(fraction, count), DateTimeUnit.DAY)
/**
* The first day of a [count]-day run that keeps [anchor] in the column under
* [fraction], so the day under the fingers stays there as the columns change.
*/
fun anchoredStart(anchor: LocalDate, fraction: Float, count: Int): LocalDate =
anchor.minus(columnAt(fraction, count), DateTimeUnit.DAY)
/** What a pinch to [count] days shows: one day is the day view, more the multi-day view. */
fun pinchedView(count: Int): CalendarView = if (count == 1) CalendarView.Day else CalendarView.MultiDay
/** How much spread one day more or less takes: seven to one is about 3x. */
private const val DAY_STEP_ZOOM = 1.2f
/** How far past the midpoint between two counts a step is taken, in steps. */
private const val STEP_HYSTERESIS = 0.2f
/** Where a pinch's steps go: the view, the days it shows, and the multi-day count it holds. */
internal data class PinchTarget(val view: CalendarView, val span: DaySpan, val rangeCount: Int?)
/**
* One horizontal pinch (#389), from the page it started on. The day under the
* fingers when it started stays under them; coming back to the count it
* started from gives back the page and view it started on, so a pinch that
* changes its mind leaves the week a week.
*
* @param originRange the multi-day view's session count when the pinch started.
*/
internal class DayPinch(
private val originView: CalendarView,
private val origin: DaySpan,
private val originRange: Int?,
private val anchor: LocalDate,
) {
var count: Int = origin.count
private set
/** Where the pinch goes at [zoom] with the fingers at [fraction], or null while the count holds. */
fun step(zoom: Float, fraction: Float): PinchTarget? {
val next = steppedDayCount(count, origin.count, zoom)
if (next == count) return null
count = next
if (next == origin.count) return PinchTarget(originView, origin, originRange)
val view = pinchedView(next)
return PinchTarget(
view = view,
span = DaySpan(anchoredStart(anchor, fraction, next), next),
rangeCount = next.takeIf { view == CalendarView.MultiDay },
)
}
companion object {
/** A pinch starting on [span] of [view] with the fingers at [fraction]. */
fun start(view: CalendarView, span: DaySpan, rangeCount: Int?, fraction: Float): DayPinch =
DayPinch(view, span, rangeCount, span.dayAt(fraction))
}
}
@@ -0,0 +1,71 @@
package de.jeanlucmakiola.calendula.ui.week
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculateCentroid
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import de.jeanlucmakiola.calendula.ui.common.PINCH_SLOP
import de.jeanlucmakiola.calendula.ui.common.PinchAxis
import de.jeanlucmakiola.calendula.ui.common.PinchAxisLock
import de.jeanlucmakiola.calendula.ui.common.lockPinchAxis
import de.jeanlucmakiola.calendula.ui.common.spreadOf
import kotlin.math.abs
/** What a sideways pinch on the timeline drives (#389). */
internal interface DayCountPinchHandler {
/** A sideways pinch is taking over at [x] across [width]; false leaves it to the hour zoom. */
fun begin(x: Float, width: Float): Boolean
/** The fingers have spread by [zoom] since they came down, and sit at [x]. */
fun update(zoom: Float, x: Float, width: Float)
fun end()
}
/**
* Tells a sideways pinch from an up-and-down one as it starts, and drives
* [handler] with the sideways ones. It sits above the pager and the hour zoom
* and watches the initial pass, so it decides each gesture before they see it:
* the hour zoom waits for [lock] to say [PinchAxis.Vertical], and a sideways
* pinch consumes the fingers from then on, which stops the pager and the scroll.
* It outlives the pages and the column resize, so one pinch can step several times.
*/
internal fun Modifier.dayCountPinch(lock: PinchAxisLock, handler: DayCountPinchHandler): Modifier =
pointerInput(lock, handler) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
lock.axis = null
var zoom = 1f
var startSpread: Offset? = null
var claimed = false
try {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
val pressed = event.changes.filter { it.pressed }
if (pressed.isEmpty()) break
if (pressed.size >= 2) {
zoom *= event.calculateZoom()
val x = event.calculateCentroid(useCurrent = true).x
val width = size.width.toFloat()
if (lock.axis == null) {
val spread = spreadOf(pressed.map { it.position })
val first = startSpread ?: spread.also { startSpread = it }
if (abs(zoom - 1f) >= PINCH_SLOP) {
val axis = lockPinchAxis(spread.x - first.x, spread.y - first.y)
claimed = axis == PinchAxis.Horizontal && handler.begin(x, width)
lock.axis = if (claimed) PinchAxis.Horizontal else PinchAxis.Vertical
}
}
if (claimed) handler.update(zoom, x, width)
}
if (claimed) event.changes.forEach { if (it.pressed) it.consume() }
}
} finally {
if (claimed) handler.end()
}
}
}
@@ -6,6 +6,7 @@ import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.ui.common.PinchAxisLock
import de.jeanlucmakiola.calendula.ui.common.StripDrop
import de.jeanlucmakiola.calendula.ui.common.TimelineDragController
import de.jeanlucmakiola.calendula.ui.common.TimelineDrop
@@ -27,6 +28,8 @@ internal class TimelineActions(
val onDrop: (TimelineDrop) -> Unit,
val onResize: (TimelineResizeDrop) -> Unit,
val onStripDrop: (StripDrop) -> Unit,
/** The axis of the pinch under way, when a sideways pinch can change the days shown (#389). */
val pinchLock: PinchAxisLock? = null,
)
/** The callbacks are read through their latest values, so the holder outlives them. */
@@ -40,6 +43,7 @@ internal fun rememberTimelineActions(
onDrop: (TimelineDrop) -> Unit,
onResize: (TimelineResizeDrop) -> Unit,
onStripDrop: (StripDrop) -> Unit,
pinchLock: PinchAxisLock? = null,
): TimelineActions {
val eventClick = rememberUpdatedState(onEventClick)
val openDay = rememberUpdatedState(onOpenDay)
@@ -47,7 +51,7 @@ internal fun rememberTimelineActions(
val drop = rememberUpdatedState(onDrop)
val resize = rememberUpdatedState(onResize)
val stripDrop = rememberUpdatedState(onStripDrop)
return remember(scrollState, dragController) {
return remember(scrollState, dragController, pinchLock) {
TimelineActions(
scrollState = scrollState,
dragController = dragController,
@@ -57,6 +61,7 @@ internal fun rememberTimelineActions(
onDrop = { drop.value(it) },
onResize = { resize.value(it) },
onStripDrop = { stripDrop.value(it) },
pinchLock = pinchLock,
)
}
}
@@ -91,6 +91,8 @@ import androidx.compose.ui.Modifier
import de.jeanlucmakiola.calendula.ui.common.LocalViewMorph
import de.jeanlucmakiola.calendula.ui.common.StayPut
import kotlinx.coroutines.delay
import kotlinx.coroutines.channels.Channel
import de.jeanlucmakiola.calendula.ui.common.PinchAxisLock
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.first
import androidx.compose.runtime.withFrameNanos
@@ -184,6 +186,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberOutOfViewEdges
import de.jeanlucmakiola.calendula.ui.common.rememberCurrentMinute
import de.jeanlucmakiola.calendula.ui.common.EnterOnFocus
import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.TakeDateRequest
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarFadeSpec
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
import de.jeanlucmakiola.calendula.ui.common.ViewMorphPage
@@ -269,6 +272,7 @@ fun TimelineScreen(
onCreateEvent: (LocalDate, Int?) -> Unit,
onCreateDraft: (Instant, Instant) -> Unit,
modifier: Modifier = Modifier,
onPinchView: (CalendarView) -> Unit = {},
weekViewModel: WeekViewModel = hiltViewModel(),
multiDayViewModel: MultiDayViewModel = hiltViewModel(),
dayViewModel: DayViewModel = hiltViewModel(),
@@ -283,6 +287,7 @@ fun TimelineScreen(
onEventClick = onEventClick,
onCreateEvent = onCreateEvent,
onCreateDraft = onCreateDraft,
onPinchView = onPinchView,
modifier = modifier,
)
}
@@ -290,7 +295,7 @@ fun TimelineScreen(
/** Each timeline view's own pages and anchor, held side by side so a switch can show both. */
internal class TimelineViewModels(
private val week: WeekViewModel,
private val multiDay: MultiDayViewModel,
val multiDay: MultiDayViewModel,
private val day: DayViewModel,
) {
operator fun get(view: CalendarView): PagedTimelineViewModel = when (view) {
@@ -339,6 +344,7 @@ private fun PagedTimelineScreen(
onEventClick: (EventInstance) -> Unit,
onCreateEvent: (LocalDate, Int?) -> Unit,
onCreateDraft: (Instant, Instant) -> Unit,
onPinchView: (CalendarView) -> Unit,
modifier: Modifier,
) {
// The view on screen, which trails [view] while the columns resize into it.
@@ -354,6 +360,8 @@ private fun PagedTimelineScreen(
val navigationVersion = focus?.navigationVersion ?: 0
var handledNavigation by remember { mutableIntStateOf(navigationVersion) }
EnterOnFocus(viewModel) { viewModel.jumpTo(it) }
// The focus moves the timeline already; this only clears another app's date request (#524).
TakeDateRequest(Unit)
// Keyed on the view model: collected unkeyed, a switch would read the view
// before's anchor and grid for a frame and open its pager.
val loadedState by key(viewModel) { viewModel.state.collectAsStateWithLifecycle() }
@@ -416,6 +424,40 @@ private fun PagedTimelineScreen(
val currentPager by rememberUpdatedState(pagerState)
val currentGrid by rememberUpdatedState(grid)
val currentState by rememberUpdatedState(state)
val currentReduceMotion by rememberUpdatedState(reduceMotion)
val currentSwitchSpec by rememberUpdatedState(switchSpec)
val currentLongSwitchSpec by rememberUpdatedState(longSwitchSpec)
// The view a resize in flight lands on, beside its [TimelineMorph.to].
val landingView = remember { arrayOfNulls<CalendarView>(1) }
/**
* Resize the columns from [fromSpan] of [from] to [toSpan] of [to], then
* [land] there: whatever moves the target view's pages onto [toSpan] that
* hasn't already, in the same frame as it is shown.
*/
suspend fun resize(from: CalendarView, fromSpan: DaySpan, to: CalendarView, toSpan: DaySpan, land: () -> Unit) {
val fromLoaded = viewModels[from].span(fromSpan)
val toLoaded = viewModels[to].span(toSpan)
if (currentReduceMotion || currentState !is WeekUiState.Success) {
land()
shown = to
return
}
val switch = TimelineMorph(from.timelineKind, to.timelineKind, fromSpan, toSpan, fromLoaded, toLoaded)
try {
withTimeoutOrNull(MORPH_DATA_WAIT_MS) { toLoaded.first { it !is WeekUiState.Loading } }
landingView[0] = to
morph = switch
switch.progress.animateTo(1f, if (switch.isLong) currentLongSwitchSpec else currentSwitchSpec)
handoffStrip = (toLoaded.value as? WeekUiState.Success)?.allDayStripHeight()
land()
shown = to
} finally {
landingView[0] = null
morph = null
}
}
LaunchedEffect(view, navigationVersion) {
if (navigationVersion != handledNavigation) {
handledNavigation = navigationVersion
@@ -437,22 +479,75 @@ private fun PagedTimelineScreen(
val toModel = viewModels[view]
toModel.jumpTo(target)
val to = positionOf(target, toModel.rule.value)
val toSpan = DaySpan(to.grid.startForPage(to.page), to.grid.dayCount)
val fromLoaded = viewModels[from].span(fromSpan)
val toLoaded = toModel.span(toSpan)
if (reduceMotion || currentState !is WeekUiState.Success) {
shown = view
return@LaunchedEffect
resize(from, fromSpan, view, DaySpan(to.grid.startForPage(to.page), to.grid.dayCount)) {}
}
// A sideways pinch steps through day counts (#389). Each step resizes the
// columns like a view switch; steps queue behind the one resizing, the
// latest winning, and the host is told the view once a step lands.
val haptics = LocalHapticFeedback.current
val currentOnPinchView by rememberUpdatedState(onPinchView)
val pinchTargets = remember { Channel<PinchTarget>(Channel.CONFLATED) }
LaunchedEffect(pinchTargets) {
for (target in pinchTargets) {
snapshotFlow { morph }.first { it == null }
// Off the view model rather than the pager: a step that just landed
// has moved the one and not yet recomposed the other.
val from = shown
val fromModel = viewModels[from]
val at = positionOf(fromModel.anchor.value, fromModel.rule.value)
val fromSpan = DaySpan(at.grid.startForPage(at.page), at.grid.dayCount)
if (from == target.view && fromSpan == target.span) continue
resize(from, fromSpan, target.view, target.span) {
focus?.date = target.span.start
val multiDay = viewModels.multiDay
when {
target.view != CalendarView.MultiDay -> viewModels[target.view].jumpTo(target.span.start)
target.rangeCount != null -> multiDay.showRange(target.span.start, target.rangeCount)
else -> {
multiDay.clearRange()
multiDay.jumpTo(target.span.start)
}
}
currentOnPinchView(target.view)
}
}
val switch = TimelineMorph(from.timelineKind, view.timelineKind, fromSpan, toSpan, fromLoaded, toLoaded)
try {
withTimeoutOrNull(MORPH_DATA_WAIT_MS) { toLoaded.first { it !is WeekUiState.Loading } }
morph = switch
switch.progress.animateTo(1f, if (switch.isLong) longSwitchSpec else switchSpec)
handoffStrip = (toLoaded.value as? WeekUiState.Success)?.allDayStripHeight()
shown = view
} finally {
morph = null
}
val density = LocalDensity.current
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl
val gutterPx = with(density) { GUTTER_WIDTH.toPx() }
val endInsetPx = with(density) { TIMELINE_CONTENT_END_INSET.toPx() }
val pinchHandler = remember(gutterPx, endInsetPx, isRtl, haptics) {
object : DayCountPinchHandler {
var pinch: DayPinch? = null
fun fraction(x: Float, width: Float) = columnFraction(x, width, gutterPx, endInsetPx, isRtl)
override fun begin(x: Float, width: Float): Boolean {
if (currentState !is WeekUiState.Success) return false
val resizing = morph
val landing = landingView[0]
// Mid-resize, from where it lands: the steps queue behind it.
pinch = if (resizing != null && landing != null) {
DayPinch.start(landing, resizing.to, resizing.to.count, fraction(x, width))
} else if (resizing == null) {
val page = DaySpan(currentGrid.startForPage(currentPager.currentPage), currentGrid.dayCount)
DayPinch.start(currentShown, page, viewModels.multiDay.rangeCount.value, fraction(x, width))
} else {
null
}
return pinch != null
}
override fun update(zoom: Float, x: Float, width: Float) {
val target = pinch?.step(zoom, fraction(x, width)) ?: return
haptics.performHapticFeedback(HapticFeedbackType.SegmentTick)
pinchTargets.trySend(target)
}
override fun end() {
pinch = null
}
}
}
@@ -528,6 +623,7 @@ private fun PagedTimelineScreen(
onCreateAt = onCreateEvent,
onCreateDraft = onCreateDraft,
draftMinutes = draftMinutes,
pinchHandler = pinchHandler,
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
@@ -552,6 +648,7 @@ private fun WeekContent(
onCreateAt: (LocalDate, Int) -> Unit,
onCreateDraft: (Instant, Instant) -> Unit,
draftMinutes: Int,
pinchHandler: DayCountPinchHandler,
modifier: Modifier = Modifier,
) {
val fadeSpec = rememberCalendarFadeSpec()
@@ -683,6 +780,7 @@ private fun WeekContent(
}
}
val pinchLock = remember { PinchAxisLock() }
val actions = rememberTimelineActions(
scrollState = scrollState,
dragController = dragController,
@@ -692,9 +790,17 @@ private fun WeekContent(
onDrop = onDrop,
onResize = onResize,
onStripDrop = onStripDrop,
pinchLock = pinchLock,
)
// A held block or bar keeps its gesture; a second finger ends that drag anyway.
val dayPinch = remember(pinchHandler, dragController) {
object : DayCountPinchHandler by pinchHandler {
override fun begin(x: Float, width: Float): Boolean =
!dragController.isDragging && pinchHandler.begin(x, width)
}
}
Box(modifier = modifier) {
Box(modifier = modifier.dayCountPinch(pinchLock, dayPinch)) {
CompositionLocalProvider(LocalOpeningTimeline provides timelineScroll) {
// Loading and failure concern the provider as a whole, so they stand in
// for the pager; a page still loading its own week handles that itself.
@@ -972,7 +1078,7 @@ private fun WeekFrame(
scrollState = actions.scrollState,
hourHeight = hourHeight,
dragController = actions.dragController,
modifier = rememberTimelinePinchZoom(actions.scrollState, fitHeight, hourHeight, zoom),
modifier = rememberTimelinePinchZoom(actions.scrollState, fitHeight, hourHeight, zoom, actions.pinchLock),
)
}
}
@@ -1406,7 +1512,7 @@ private fun Timeline(
// The pinch sits above the scroll viewport: it has to outrank the
// vertical scroll, and it does that by watching the initial pass, which
// only reaches it if it is the viewport's ancestor.
val pinch = rememberTimelinePinchZoom(scrollState, fitHeight, hourHeight, zoom)
val pinch = rememberTimelinePinchZoom(scrollState, fitHeight, hourHeight, zoom, actions.pinchLock)
// What a block's text is fitted to: the column it will end up in once a
// view switch is past half way, so it reflows once rather than per frame.
val textColumns by remember(geometry) {
@@ -34,12 +34,14 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
@@ -126,12 +128,34 @@ abstract class PagedTimelineViewModel(
private val _anchor = MutableStateFlow(todayDate)
val anchor: StateFlow<LocalDate> = _anchor
private var settingsRule: (LocalDate) -> DaysGrid = initialRule
private var heldRule: ((LocalDate) -> DaysGrid)? = null
private val _rule = MutableStateFlow(initialRule)
/**
* The grid for a given anchor, held eagerly so a screen can place its pager
* on its very first frame rather than a frame after the anchor moved.
*/
val rule: StateFlow<(LocalDate) -> DaysGrid> =
gridRule.stateIn(viewModelScope, SharingStarted.Eagerly, initialRule)
val rule: StateFlow<(LocalDate) -> DaysGrid> = _rule
init {
viewModelScope.launch {
gridRule.collect {
settingsRule = it
if (heldRule == null) _rule.value = it
}
}
}
/**
* Cut the pages by [rule] instead of the one from Settings until it is
* released with null. Takes effect at once, so a caller can place a pager
* on it in the same frame.
*/
protected fun holdRule(rule: ((LocalDate) -> DaysGrid)?) {
heldRule = rule
_rule.value = rule ?: settingsRule
}
/** Today, kept current across midnight so a page left open doesn't mark yesterday (#373). */
private val today: StateFlow<LocalDate> =
@@ -252,7 +276,8 @@ class WeekViewModel @Inject constructor(
/**
* The multi-day view (#193): runs of the day count from Settings, with the
* anchor always a page's first day, so today — or a date jumped to — opens in
* the first column.
* the first column. A pinch or a range picked in the month (#389) overrides
* the count for the session, until a view is picked from the switcher.
*/
@HiltViewModel
class MultiDayViewModel @Inject constructor(
@@ -272,7 +297,33 @@ class MultiDayViewModel @Inject constructor(
},
initialRule = { DaysGrid.startingAt(it, SettingsPrefs.DEFAULT_MULTI_DAY_COUNT) },
view = CalendarView.MultiDay,
)
) {
private val _rangeCount = MutableStateFlow<Int?>(null)
/** The day count picked for this session, or null for the one from Settings. */
val rangeCount: StateFlow<Int?> = _rangeCount
init {
// A count picked in Settings is the user's say on it, over a session's.
viewModelScope.launch {
settingsPrefs.multiDayCount.distinctUntilChanged().drop(1).collect { clearRange() }
}
}
/** Show [count] days from [start], paging by [count] from there. */
fun showRange(start: LocalDate, count: Int) {
_rangeCount.value = count
holdRule { anchor -> DaysGrid.startingAt(anchor, count) }
jumpTo(start)
}
/** Back to the day count from Settings. */
fun clearRange() {
if (_rangeCount.value == null) return
_rangeCount.value = null
holdRule(null)
}
}
/** The day view: the timeline one day at a time. */
@HiltViewModel
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
The plain launcher icon foreground (issue #451): the Calendula mark's
calendar and "1" without the bloom badge, the bottom-right corner closed.
Offered in Settings > Appearance > App icon (LauncherManager) and reused
as the <monochrome> slot for themed-icon launchers.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="232"
android:viewportHeight="232">
<!-- Same centring and 0.50 scale as ic_launcher_foreground. -->
<group
android:pivotX="114"
android:pivotY="108"
android:scaleX="0.50"
android:scaleY="0.50"
android:translateX="2"
android:translateY="8">
<!-- Calendar body (rounded square with horizontal header divider) -->
<path
android:strokeColor="#FFFAF6F0"
android:strokeWidth="12"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:strokeMiterLimit="12"
android:pathData="M43,69H185M185,153V63C185,48.64 173.359,37 159,37H69C54.64,37 43,48.64 43,63V153C43,167.359 54.64,179 69,179H159C173.359,179 185,167.359 185,153Z" />
<!-- Numeral "1" inside the calendar body -->
<path
android:strokeColor="#FFFAF6F0"
android:strokeWidth="12"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:pathData="M103,110L113.999,99V142.428" />
</group>
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground_plain" />
<monochrome android:drawable="@drawable/ic_launcher_foreground_plain" />
</adaptive-icon>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground_plain" />
<monochrome android:drawable="@drawable/ic_launcher_foreground_plain" />
</adaptive-icon>
+65
View File
@@ -221,6 +221,24 @@
<string name="event_edit_recurrence_end_until">On a date</string>
<string name="event_edit_recurrence_end_count">After a number of times</string>
<string name="event_edit_recurrence_times">times</string>
<!-- Monthly custom rule: repeat on the start date's day of the month, e.g. "On day 14" (#520) -->
<string name="event_edit_recurrence_monthly_day">On day %1$d</string>
<!-- Monthly custom rule by weekday position; %1$s is a full weekday name, e.g. "On the second Tuesday" (#520) -->
<string name="event_edit_recurrence_monthly_weekday_first">On the first %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_second">On the second %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_third">On the third %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_fourth">On the fourth %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_fifth">On the fifth %1$s</string>
<string name="event_edit_recurrence_monthly_weekday_last">On the last %1$s</string>
<!-- Monthly weekday position: picker titles and its options (#520) -->
<string name="event_edit_recurrence_position">Position</string>
<string name="event_edit_recurrence_weekday">Weekday</string>
<string name="recurrence_position_first">First</string>
<string name="recurrence_position_second">Second</string>
<string name="recurrence_position_third">Third</string>
<string name="recurrence_position_fourth">Fourth</string>
<string name="recurrence_position_fifth">Fifth</string>
<string name="recurrence_position_last">Last</string>
<string name="event_edit_error_recurrence_ends_before_start">Repeats end before the event starts</string>
<string name="event_availability_busy">Busy</string>
<string name="event_access_default">Default</string>
@@ -247,6 +265,13 @@
<string name="recurrence_every_n_months">Every %1$d months</string>
<string name="recurrence_every_n_years">Every %1$d years</string>
<string name="recurrence_on_days">%1$s on %2$s</string>
<!-- %1$s is the frequency phrase ("Every month", "Every 2 months"), %2$s a full weekday name (#520) -->
<string name="recurrence_monthly_weekday_first">%1$s on the first %2$s</string>
<string name="recurrence_monthly_weekday_second">%1$s on the second %2$s</string>
<string name="recurrence_monthly_weekday_third">%1$s on the third %2$s</string>
<string name="recurrence_monthly_weekday_fourth">%1$s on the fourth %2$s</string>
<string name="recurrence_monthly_weekday_fifth">%1$s on the fifth %2$s</string>
<string name="recurrence_monthly_weekday_last">%1$s on the last %2$s</string>
<string name="recurrence_with_until">%1$s until %2$s</string>
<string name="recurrence_with_count">%1$s, %2$d times</string>
<string name="event_detail_not_found">This event no longer exists.</string>
@@ -575,6 +600,21 @@
<string name="filter_group_show_all">Show all calendars in this group</string>
<string name="filter_group_hide_all">Hide all calendars in this group</string>
<!-- Calendar groups (#166): user-named sets of calendars shown or hidden together from the drawer -->
<string name="calendar_groups_title">Groups</string>
<string name="calendar_groups_header">Calendar groups</string>
<string name="calendar_groups_manage">Manage groups</string>
<string name="calendar_groups_empty">No calendars</string>
<string name="calendar_groups_new">New group</string>
<string name="calendar_groups_edit">Edit group</string>
<string name="calendar_groups_name_hint">Group name</string>
<string name="calendar_groups_delete_title">Delete group?</string>
<string name="calendar_groups_delete_message">\"%1$s\" is removed. Its calendars stay as they are.</string>
<plurals name="calendar_groups_count">
<item quantity="one">%d calendar</item>
<item quantity="other">%d calendars</item>
</plurals>
<!-- Settings (M4) -->
<string name="settings_title">Settings</string>
<string name="settings_back">Back</string>
@@ -591,6 +631,9 @@
<!-- %1$s is the theme the system currently resolves to, e.g. "Dark". -->
<string name="settings_theme_system_summary">Currently %1$s</string>
<string name="settings_default_view">Default view</string>
<string name="settings_external_date_view">Dates opened from other apps</string>
<string name="settings_external_date_day">Day view</string>
<string name="settings_external_date_default">Default view</string>
<string name="settings_dynamic_color">Dynamic colour</string>
<string name="settings_dynamic_color_unavailable">Requires Android 12 or newer</string>
<string name="settings_soften_colors">Harmonise calendar colours</string>
@@ -614,12 +657,22 @@
<string name="settings_week_start_auto_summary">Currently %1$s</string>
<string name="settings_week_numbers">Week numbers</string>
<string name="settings_week_numbers_summary">Show calendar-week numbers in month view</string>
<string name="settings_week_numbering">Week numbering</string>
<string name="settings_week_numbering_auto">Automatic</string>
<string name="settings_week_numbering_iso">ISO 8601</string>
<string name="settings_week_numbering_us">US</string>
<!-- %1$d is the number this option gives the current week, e.g. "This week: 49". -->
<string name="settings_week_numbering_this_week">This week: %1$d</string>
<string name="settings_month_start_times">Start times</string>
<string name="settings_month_start_times_summary">Show the start time before an event\'s title when there is room</string>
<string name="settings_today_toolbar">Today button in toolbar</string>
<string name="settings_today_toolbar_summary">Show a jump-to-today button in the toolbar instead of a floating button</string>
<string name="settings_app_name">App name</string>
<string name="settings_app_name_summary">Show Calendula as “Calendar” in your launcher. Only the launcher name changes; the icon may move to a new spot after switching.</string>
<string name="settings_app_icon">App icon</string>
<string name="settings_app_icon_summary">The icon your launcher shows. After switching, the icon may move to a new spot.</string>
<string name="settings_app_icon_bloom">Bloom</string>
<string name="settings_app_icon_plain">Plain</string>
<string name="settings_time_format">Time format</string>
<string name="settings_time_format_auto">Automatic</string>
<string name="settings_time_format_12h">12-hour (2:00 PM)</string>
@@ -796,6 +849,7 @@
<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_calendar_allday_time_use_default">Use default</string>
<!-- Reminders at a set time (#459). %1$s is a lead in days ("1 day before"), %2$s a clock time. -->
<string name="reminder_fixed_time">%1$s at %2$s</string>
<string name="reminder_fixed_at_set_time">At a set time</string>
@@ -879,6 +933,7 @@
<!-- Picker descriptions (#69) -->
<string name="settings_default_view_hint">The view Calendula opens on when you start it.</string>
<string name="settings_week_start_hint">The day every week begins on, in all views and widgets.</string>
<string name="settings_week_numbering_hint">How week numbers are counted. Automatic follows your region.</string>
<string name="settings_time_format_hint">How times are written throughout the app. Automatic follows your system setting.</string>
<string name="settings_past_events_hint">What the agenda does with events that have already ended.</string>
<string name="settings_dynamic_color_summary">Take the app\'s colours from your wallpaper.</string>
@@ -994,6 +1049,16 @@
<string name="color_name_indigo">Indigo</string>
<string name="color_name_purple">Purple</string>
<string name="color_name_pink">Pink</string>
<string name="color_custom">Custom color</string>
<string name="color_custom_recent">Recent</string>
<string name="color_custom_hue">Hue</string>
<string name="color_custom_saturation">Saturation</string>
<string name="color_custom_brightness">Brightness</string>
<string name="color_custom_hex">Hex code</string>
<string name="color_custom_hex_error">Enter a 6-digit hex code</string>
<string name="color_custom_select">Select</string>
<string name="color_custom_preview">Preview</string>
<string name="color_custom_keyed_only">This calendar\'s account only allows its own colors.</string>
<string name="calendars_delete_confirm_title">Delete calendar?</string>
<string name="calendars_delete_confirm_message">\"%1$s\" and all of its events will be permanently removed from this device.</string>
<string name="calendars_write_error">Couldn\'t save the change.</string>
@@ -1,51 +0,0 @@
package de.jeanlucmakiola.calendula.data.appname
import android.content.pm.PackageManager
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
/**
* Pure decision logic behind the app-name toggle (issue #44). The framework seam
* ([LauncherNameManager.set]/[current], which call `PackageManager`) is covered
* on-device; these tests pin the read interpretation and the write ordering.
*/
class LauncherNameManagerTest {
@Test
fun `enabled calendar alias reads as CALENDAR`() {
assertThat(launcherNameFor(PackageManager.COMPONENT_ENABLED_STATE_ENABLED))
.isEqualTo(LauncherName.CALENDAR)
}
@Test
fun `default and disabled calendar alias read as CALENDULA`() {
assertThat(launcherNameFor(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT))
.isEqualTo(LauncherName.CALENDULA)
assertThat(launcherNameFor(PackageManager.COMPONENT_ENABLED_STATE_DISABLED))
.isEqualTo(LauncherName.CALENDULA)
}
@Test
fun `write plan enables the target alias before disabling the other`() {
val toCalendar = aliasWritePlan(LauncherName.CALENDAR)
assertThat(toCalendar).containsExactly(
AliasStateChange(LauncherAlias.CALENDAR, enabled = true),
AliasStateChange(LauncherAlias.DEFAULT, enabled = false),
).inOrder()
val toCalendula = aliasWritePlan(LauncherName.CALENDULA)
assertThat(toCalendula).containsExactly(
AliasStateChange(LauncherAlias.DEFAULT, enabled = true),
AliasStateChange(LauncherAlias.CALENDAR, enabled = false),
).inOrder()
}
@Test
fun `write plan never disables both aliases in the same step`() {
// The first step is always an enable, so the launcher can never observe a
// zero-entry transient regardless of switch direction.
for (target in LauncherName.entries) {
assertThat(aliasWritePlan(target).first().enabled).isTrue()
}
}
}
@@ -3,13 +3,17 @@ 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.launcher.LauncherEntry
import de.jeanlucmakiola.calendula.data.launcher.LauncherIcon
import de.jeanlucmakiola.calendula.data.launcher.LauncherName
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.withGroup
import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
@@ -55,7 +59,7 @@ class SettingsBackupTest {
calendars = calendars,
managed = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
language = LanguageChoice("de"),
launcherName = LauncherName.CALENDAR,
launcher = LauncherEntry(LauncherName.CALENDAR, LauncherIcon.PLAIN),
)
val decoded = decodeSettingsBackup(encodeSettingsBackup(backup, 1_700_000_000_000, "2.25.0"))
return (decoded as BackupResult.Success).value
@@ -126,6 +130,20 @@ class SettingsBackupTest {
assertThat(plan.calendars).hasSize(2)
}
@Test
fun `calendar groups travel and find their calendars by account and name`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.calendarGroups] = emptyList<CalendarGroup>().withGroup("g", "Both", listOf(work, home))
val moved = listOf(calendar(12, "Home"), calendar(11, "Work"))
val target = mutablePreferencesOf()
import(roundTrip(source), target, environment(calendars = moved, managed = emptyList()))
val group = target[CalendarPrefKeys.calendarGroups].single()
assertThat(group.name).isEqualTo("Both")
assertThat(group.resolve(moved).map { it.id }).containsExactly(11L, 12L).inOrder()
}
@Test
fun `a calendar missing here is reported, and its old id is not reused`() {
val source = mutablePreferencesOf()
@@ -159,6 +177,7 @@ class SettingsBackupTest {
source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30)
source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5))
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0))
source[SettingsKeys.perCalendarAllDayReminderTime] = mapOf(1L to 1_140)
source[SettingsKeys.perCalendarHiddenViews] = mapOf(1L to setOf(CalendarView.Month, CalendarView.Week))
source[SettingsKeys.mutedReminderCalendarIds] = setOf(1L)
source[SettingsKeys.reminderAlertStyles] = mapOf(1L to ReminderAlertStyle.FullScreenRing)
@@ -176,6 +195,7 @@ class SettingsBackupTest {
assertThat(target.asMap().keys.map { it.name }).contains(pref.name)
}
assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0))
assertThat(target[SettingsKeys.perCalendarAllDayReminderTime]).containsExactly(9L, 1_140)
assertThat(target[SettingsKeys.perCalendarHiddenViews]).containsExactly(9L, setOf(CalendarView.Month, CalendarView.Week))
assertThat(target[SettingsKeys.mutedReminderCalendarIds]).containsExactly(9L)
assertThat(target[SettingsKeys.reminderAlertStyles]).containsExactly(9L, ReminderAlertStyle.FullScreenRing)
@@ -226,6 +246,15 @@ class SettingsBackupTest {
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440)
}
@Test
fun `an out-of-range all-day reminder time is dropped`() {
val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[
{"account_name":"me@example.org","account_type":"com.google","display_name":"Work","all_day_reminder_time_minutes":1440}]}"""
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
assertThat(backup.calendars.single().allDayReminderTimeMinutes).isNull()
}
@Test
fun `unreadable calendars leave the per-calendar settings alone`() {
val source = mutablePreferencesOf()
@@ -358,6 +387,10 @@ class SettingsBackupTest {
assertThat(backup.language).isEqualTo(LanguageChoice("de"))
assertThat(backup.launcherName).isEqualTo(LauncherName.CALENDAR)
assertThat(backup.launcherIcon).isEqualTo(LauncherIcon.PLAIN)
val plan = planSettingsImport(backup, mutablePreferencesOf(), environment())
assertThat(plan.launcherName).isEqualTo(LauncherName.CALENDAR)
assertThat(plan.launcherIcon).isEqualTo(LauncherIcon.PLAIN)
}
@Test
@@ -366,7 +399,7 @@ class SettingsBackupTest {
{"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"}}
"app":{"launcher_name":"SOMETHING_NEW","launcher_icon":"SOMETHING_NEW"}}
""".trimIndent()
val backup = (decodeSettingsBackup(text) as BackupResult.Success).value
@@ -374,6 +407,7 @@ class SettingsBackupTest {
assertThat(backup.prefs.values).containsExactly(4)
assertThat(backup.calendars).hasSize(1)
assertThat(backup.launcherName).isNull()
assertThat(backup.launcherIcon).isNull()
assertThat(backup.language).isNull()
}
@@ -0,0 +1,108 @@
package de.jeanlucmakiola.calendula.data.calendar
import com.google.common.truth.Truth.assertWithMessage
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.color.eventTone
import de.jeanlucmakiola.calendula.domain.color.oklchOf
import org.junit.jupiter.api.Test
import kotlin.math.pow
class CalendarColorPaletteTest {
private val palette = CalendarColorPalette.all
@Test
fun `painted swatches stay apart in both themes`() {
assertMinDistance("light fill", MIN_FILL_DISTANCE) { eventTone(it, dark = false, harmonise = true).container }
assertMinDistance("dark fill", MIN_FILL_DISTANCE) { eventTone(it, dark = true, harmonise = true).container }
}
@Test
fun `raw swatches stay apart with softening off`() {
assertMinDistance("raw", MIN_FILL_DISTANCE) { it }
}
@Test
fun `accents (dots, stripes) stay apart in both themes`() {
assertMinDistance("light accent", MIN_ACCENT_DISTANCE) { eventTone(it, dark = false, harmonise = true).accent }
assertMinDistance("dark accent", MIN_ACCENT_DISTANCE) { eventTone(it, dark = true, harmonise = true).accent }
}
@Test
fun `no two painted swatches merge under a colour-vision deficiency`() {
for ((name, matrix) in CVD) {
for (dark in listOf(false, true)) {
assertMinDistance("$name dark=$dark", MIN_CVD_DISTANCE) {
simulate(eventTone(it, dark, harmonise = true).container, matrix)
}
}
}
}
@Test
fun `a stored preset matches regardless of alpha`() {
assertThat(CalendarColorPalette.presetOf(CalendarColorPalette.Green)).isEqualTo(CalendarColorPalette.Green)
val translucentBlue = CalendarColorPalette.Blue and 0x00FFFFFF
assertThat(CalendarColorPalette.presetOf(translucentBlue)).isEqualTo(CalendarColorPalette.Blue)
}
@Test
fun `a colour from the old palette or anywhere else is custom`() {
val oldGreen = 0xFF35A06A.toInt()
assertThat(CalendarColorPalette.presetOf(oldGreen)).isNull()
assertThat(CalendarColorPalette.presetOf(0xFF123456.toInt())).isNull()
assertThat(CalendarColorPalette.presetOf(null)).isNull()
}
private fun assertMinDistance(label: String, min: Float, paint: (Int) -> Int) {
val painted = palette.map(paint).map(::oklchOf)
for (i in painted.indices) for (j in i + 1 until painted.size) {
assertWithMessage("$label: ${hex(palette[i])} vs ${hex(palette[j])}")
.that(painted[i].distanceTo(painted[j]))
.isAtLeast(min)
}
}
private fun hex(argb: Int) = "#%06X".format(argb and 0xFFFFFF)
/** [argb] as seen with a dichromacy, via a Machado et al. (2009) severity-1 matrix on linear RGB. */
private fun simulate(argb: Int, m: Array<DoubleArray>): Int {
val rgb = listOf(16, 8, 0).map { toLinear(((argb shr it) and 0xFF) / 255.0) }
val out = m.map { row -> row.indices.sumOf { row[it] * rgb[it] } }
.map { (toSrgb(it.coerceIn(0.0, 1.0)) * 255.0).toInt().coerceIn(0, 255) }
return (0xFF shl 24) or (out[0] shl 16) or (out[1] shl 8) or out[2]
}
private fun toLinear(c: Double) = if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4)
private fun toSrgb(c: Double) = if (c <= 0.0031308) 12.92 * c else 1.055 * c.pow(1 / 2.4) - 0.055
private companion object {
/** Oklab distance; the palette before #198 had Olive/Green and Teal/Cyan at 0.056. */
const val MIN_FILL_DISTANCE = 0.075f
/** Accents share one lightness per theme, so only hue and chroma separate them. */
const val MIN_ACCENT_DISTANCE = 0.04f
/**
* Twelve hues at two lightness levels can't all stay far apart for a
* dichromat; this only rules out two swatches turning into one.
*/
const val MIN_CVD_DISTANCE = 0.01f
val CVD = mapOf(
"protanopia" to arrayOf(
doubleArrayOf(0.152286, 1.052583, -0.204868),
doubleArrayOf(0.114503, 0.786281, 0.099216),
doubleArrayOf(-0.003882, -0.048116, 1.051998),
),
"deuteranopia" to arrayOf(
doubleArrayOf(0.367322, 0.860646, -0.227968),
doubleArrayOf(0.280085, 0.672501, 0.047413),
doubleArrayOf(-0.011820, 0.042940, 0.968881),
),
"tritanopia" to arrayOf(
doubleArrayOf(1.255528, -0.076749, -0.178779),
doubleArrayOf(-0.078411, 0.930809, 0.147602),
doubleArrayOf(0.004733, 0.691367, 0.303900),
),
)
}
}
@@ -532,6 +532,27 @@ class CalendarRepositoryImplTest {
assertThat(fake.allDayReminderTimes).containsExactly(480)
}
@Test
fun `writes encode all-day reminders at the target calendar's own time`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource()
val settings = testSettings(tempDir)
settings.setAllDayReminderTimeMinutes(8 * 60)
settings.setCalendarAllDayReminderTime(2L, 18 * 60)
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined, settings = settings)
val day = LocalDateTime(LocalDate(2026, 6, 12), LocalTime(0, 0))
val form = EventForm(calendarId = 1L, isAllDay = true, start = FormTime(day), end = FormTime(day))
repo.createEvent(form)
repo.createEvent(form.copy(calendarId = 2L))
repo.moveEvent(5L, 2L, form, form.copy(calendarId = 2L))
settings.setCalendarAllDayReminderTime(2L, null)
repo.createEvent(form.copy(calendarId = 2L))
assertThat(fake.allDayReminderTimes).containsExactly(480, 1080, 1080, 480).inOrder()
}
@Test
fun `createEvent propagates write failures`(@TempDir tempDir: Path) = runTest {
val fake = FakeCalendarDataSource().apply {
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.calendar
import android.provider.CalendarContract
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.reminders.AllDayReminderTimes
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
@@ -91,11 +92,11 @@ internal class FakeCalendarDataSource : CalendarDataSource {
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> =
instancesResult(beginMillis, endMillis)
override fun searchEvents(query: String): List<SearchCandidate> = searchResult(query)
override fun eventDetail(eventId: Long, allDayReminderTimeMinutes: Int): EventDetail? =
override fun eventDetail(eventId: Long, allDayTimes: AllDayReminderTimes): EventDetail? =
eventDetailResult(eventId)
override fun publishedEventColors(calendarId: Long): List<EventColorOption> =
publishedEventColorsResult(calendarId)
override fun calendarRows(calendarIds: Set<Long>, allDayReminderTimeMinutes: Int): CalendarRows {
override fun calendarRows(calendarIds: Set<Long>, allDayTimes: AllDayReminderTimes): CalendarRows {
lastCalendarRowsIds = calendarIds
return calendarRowsResult
}
@@ -193,11 +194,11 @@ internal class FakeCalendarDataSource : CalendarDataSource {
targetCalendarId: Long,
original: EventForm,
updated: EventForm,
allDayReminderTimeMinutes: Int,
allDayTimes: AllDayReminderTimes,
): Long {
writeError?.let { throw it }
movedEvents += MovedEvent(eventId, targetCalendarId, original, updated)
allDayReminderTimes += allDayReminderTimeMinutes
allDayReminderTimes += allDayTimes.forCalendar(targetCalendarId)
return nextInsertId
}
@@ -0,0 +1,61 @@
package de.jeanlucmakiola.calendula.data.launcher
import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED
import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.floret.android.activeLauncherAlias
import org.junit.jupiter.api.Test
/** Which alias carries each name × icon combination (#44, #451). */
class LauncherAliasTest {
@Test
fun `each combination maps to its alias`() {
assertThat(LauncherAlias.of(LauncherEntry(LauncherName.CALENDULA, LauncherIcon.BLOOM)))
.isEqualTo(LauncherAlias.DEFAULT)
assertThat(LauncherAlias.of(LauncherEntry(LauncherName.CALENDAR, LauncherIcon.BLOOM)))
.isEqualTo(LauncherAlias.CALENDAR)
assertThat(LauncherAlias.of(LauncherEntry(LauncherName.CALENDULA, LauncherIcon.PLAIN)))
.isEqualTo(LauncherAlias.PLAIN)
assertThat(LauncherAlias.of(LauncherEntry(LauncherName.CALENDAR, LauncherIcon.PLAIN)))
.isEqualTo(LauncherAlias.CALENDAR_PLAIN)
}
@Test
fun `every combination has exactly one alias`() {
val combinations = LauncherName.entries.flatMap { name ->
LauncherIcon.entries.map { LauncherEntry(name, it) }
}
assertThat(LauncherAlias.entries.map { it.entry }).containsExactlyElementsIn(combinations)
}
@Test
fun `pre-451 component names are kept`() {
assertThat(LauncherAlias.DEFAULT.className).isEqualTo("DefaultNameAlias")
assertThat(LauncherAlias.CALENDAR.className).isEqualTo("CalendarNameAlias")
}
@Test
fun `the default combination is the manifest default`() {
assertThat(LauncherAlias.of(LauncherEntry())).isEqualTo(LauncherAlias.DEFAULT)
}
@Test
fun `a device switched to Calendar before 451 still reads as Calendar with the bloom`() {
val states = mapOf(
LauncherAlias.DEFAULT to COMPONENT_ENABLED_STATE_DISABLED,
LauncherAlias.CALENDAR to COMPONENT_ENABLED_STATE_ENABLED,
LauncherAlias.PLAIN to COMPONENT_ENABLED_STATE_DEFAULT,
LauncherAlias.CALENDAR_PLAIN to COMPONENT_ENABLED_STATE_DEFAULT,
)
assertThat(activeLauncherAlias(states, LauncherAlias.DEFAULT).entry)
.isEqualTo(LauncherEntry(LauncherName.CALENDAR, LauncherIcon.BLOOM))
}
@Test
fun `changing the icon keeps the name`() {
val entry = LauncherEntry(LauncherName.CALENDAR, LauncherIcon.BLOOM)
assertThat(LauncherAlias.of(entry.copy(icon = LauncherIcon.PLAIN))).isEqualTo(LauncherAlias.CALENDAR_PLAIN)
}
}
@@ -162,6 +162,14 @@ class SettingsPrefsTest {
assertThat(prefs.showWeekNumbers.first()).isTrue()
}
@Test
fun `week numbering defaults to automatic and round-trips`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.weekNumbering.first()).isEqualTo(WeekNumberingPref.AUTO)
prefs.setWeekNumbering(WeekNumberingPref.US)
assertThat(prefs.weekNumbering.first()).isEqualTo(WeekNumberingPref.US)
}
@Test
fun `month start times default on and round-trips`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
@@ -575,6 +583,26 @@ class SettingsPrefsTest {
assertThat(prefs.allDayReminderTimeMinutes.first()).isEqualTo(0)
}
@Test
fun `a calendar's own all-day reminder time overrides the global one until cleared`(
@TempDir tempDir: Path,
) = runTest {
val prefs = testSettings(tempDir)
prefs.setAllDayReminderTimeMinutes(8 * 60)
prefs.setCalendarAllDayReminderTime(3L, 19 * 60)
prefs.setCalendarAllDayReminderTime(4L, 5_000)
val times = prefs.allDayReminderTimes.first()
assertThat(times.forCalendar(3L)).isEqualTo(1_140)
assertThat(times.forCalendar(4L)).isEqualTo(1_439)
assertThat(times.forCalendar(5L)).isEqualTo(480)
prefs.setCalendarAllDayReminderTime(3L, null)
prefs.setAllDayReminderTimeMinutes(10 * 60)
assertThat(prefs.allDayReminderTimes.first().forCalendar(3L)).isEqualTo(600)
assertThat(prefs.perCalendarAllDayReminderTime.first()).containsExactly(4L, 1_439)
}
@Test
fun `snooze duration defaults to 10 minutes`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
@@ -1022,5 +1050,39 @@ class SettingsPrefsTest {
canModifyContents = true,
isLocal = local,
)
}
@Test
fun `a recent colour goes to the front, once, made opaque`() {
val recents = listOf(0xFF111111.toInt(), 0xFF222222.toInt())
assertThat(withRecentColor(recents, 0x00222222))
.containsExactly(0xFF222222.toInt(), 0xFF111111.toInt()).inOrder()
}
@Test
fun `recent colours are capped, dropping the oldest`() {
val full = (1..SettingsPrefs.MAX_RECENT_CUSTOM_COLORS).map { (0xFF shl 24) or it }
val next = withRecentColor(full, 0xFFABCDEF.toInt())
assertThat(next).hasSize(SettingsPrefs.MAX_RECENT_CUSTOM_COLORS)
assertThat(next.first()).isEqualTo(0xFFABCDEF.toInt())
assertThat(next).doesNotContain(full.last())
}
@Test
fun `recent custom colours round-trip most recent first`(@TempDir tempDir: Path) = runTest {
val prefs = testSettings(tempDir)
assertThat(prefs.recentCustomColors.first()).isEmpty()
prefs.addRecentCustomColor(0xFF112233.toInt())
prefs.addRecentCustomColor(0xFFAABBCC.toInt())
prefs.addRecentCustomColor(0xFF112233.toInt())
assertThat(prefs.recentCustomColors.first())
.containsExactly(0xFF112233.toInt(), 0xFFAABBCC.toInt()).inOrder()
}
@Test
fun `unreadable stored recent colours are dropped`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
store.updateData { it.toMutablePreferences().apply { this[stringPreferencesKey("recent_custom_colors")] = "112233,zz,ABC,445566" } }
assertThat(SettingsPrefs(store).recentCustomColors.first())
.containsExactly(0xFF112233.toInt(), 0xFFAABBCC.toInt(), 0xFF445566.toInt()).inOrder()
}
}
@@ -0,0 +1,78 @@
package de.jeanlucmakiola.calendula.domain
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class CalendarGroupsTest {
private fun calendar(id: Long, name: String, account: String = "me@example.org", type: String = "com.google") =
CalendarSource(id = id, displayName = name, accountName = account, accountType = type, color = 0, isVisibleInSystem = true)
private val work = calendar(1, "Work")
private val team = calendar(2, "Team", account = "dav", type = "bitfire.at.davdroid")
private val sports = calendar(3, "Sports")
@Test
fun `groups survive storage, members included`() {
val groups = emptyList<CalendarGroup>()
.withGroup("a", "Meet-ups", listOf(work, team))
.withGroup("b", "Fun \"quoted\", odd\u001Fname", listOf(sports))
val decoded = decodeCalendarGroups(encodeCalendarGroups(groups))
assertThat(decoded).isEqualTo(groups)
assertThat(decoded[0].members.map { it.accountName }).containsExactly("me@example.org", "dav").inOrder()
}
@Test
fun `no groups store nothing`() {
assertThat(encodeCalendarGroups(emptyList())).isNull()
assertThat(decodeCalendarGroups(null)).isEmpty()
}
@Test
fun `an unreadable value reads as no groups, a broken entry is skipped`() {
assertThat(decodeCalendarGroups("not json")).isEmpty()
assertThat(decodeCalendarGroups("""{"id":"a"}""")).isEmpty()
val stored = """[{"id":"a","name":"A","members":[{"calendar_id":"x"},""" +
"""{"calendar_id":1,"account_type":"t","account_name":"n","display_name":"Work"}]},{"name":"no id"}]"""
val decoded = decodeCalendarGroups(stored)
assertThat(decoded).hasSize(1)
assertThat(decoded.single().members).containsExactly(DefaultCalendarRef(1, "t", "n", "Work"))
}
@Test
fun `saving replaces the group of that id and keeps the order`() {
val groups = emptyList<CalendarGroup>()
.withGroup("a", "A", listOf(work))
.withGroup("b", "B", listOf(team))
.withGroup("a", "Renamed", listOf(work, sports, sports))
assertThat(groups.map { it.name }).containsExactly("Renamed", "B").inOrder()
assertThat(groups[0].resolve(listOf(work, team, sports))).containsExactly(work, sports).inOrder()
}
@Test
fun `a missing calendar drops out, an empty group stays`() {
val groups = emptyList<CalendarGroup>()
.withGroup("a", "A", listOf(work, team))
.withGroup("b", "B", listOf(sports))
val now = listOf(work)
assertThat(groups[0].resolve(now)).containsExactly(work)
assertThat(groups[1].resolve(now)).isEmpty()
// Saving it again prunes the stored member too.
val saved = groups.withGroup("a", "A", groups[0].resolve(now))
assertThat(saved[0].members.map { it.id }).containsExactly(1L)
}
@Test
fun `members are found by account and name when the ids changed`() {
val group = emptyList<CalendarGroup>().withGroup("a", "A", listOf(work, team)).single()
val otherDevice = listOf(calendar(40, "Team", account = "dav", type = "bitfire.at.davdroid"), calendar(41, "Work"))
assertThat(group.resolve(otherDevice).map { it.id }).containsExactly(41L, 40L).inOrder()
}
}
@@ -93,9 +93,15 @@ class EventFormTest {
@Test
fun `complex rrules are not validated against the start`() {
// The picker can't have produced this ("second Monday" ordinal BYDAY);
// it is preserved verbatim and never flagged.
assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO;UNTIL=20200101").problems(berlin)).isEmpty()
// The picker can't have produced this (two ordinal weekdays); it is
// preserved verbatim and never flagged.
assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO,4MO;UNTIL=20200101").problems(berlin)).isEmpty()
}
@Test
fun `a monthly weekday position rule is validated like any simple rule`() {
assertThat(form().copy(rrule = "FREQ=MONTHLY;BYDAY=2MO;UNTIL=20200101").problems(berlin))
.containsExactly(EventFormProblem.RecurrenceEndsBeforeStart)
}
@Test
@@ -0,0 +1,215 @@
package de.jeanlucmakiola.calendula.domain
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import org.junit.jupiter.api.Test
/** Monthly repeats by weekday position (#520). */
class MonthlyWeekdayTest {
private val utc = TimeZone.UTC
@Test
fun `ordinal BYDAY on a monthly rule parses into a weekday position`() {
(1..5).forEach { n ->
assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=${n}TU", utc))
.isEqualTo(
SimpleRecurrence(
RecurrenceFreq.Monthly,
monthlyWeekday = MonthlyWeekday(n, DayOfWeek.TUESDAY),
),
)
}
assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=-1SA", utc)?.monthlyWeekday)
.isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY))
assertThat(parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=+2tu", utc)?.monthlyWeekday)
.isEqualTo(MonthlyWeekday(2, DayOfWeek.TUESDAY))
}
@Test
fun `round-trips 1 to 5 and last with interval and end`() {
val positions = (1..5).map(Int::toString) + "-1"
val tails = listOf("", ";COUNT=6", ";UNTIL=20301231T235959Z")
positions.forEach { n ->
tails.forEach { tail ->
listOf("FREQ=MONTHLY;BYDAY=${n}SA$tail", "FREQ=MONTHLY;INTERVAL=3;BYDAY=${n}SA$tail")
.forEach { rule ->
assertThat(parseSimpleRecurrence(rule, utc)!!.toRRule(utc)).isEqualTo(rule)
}
}
}
}
@Test
fun `interval and end survive alongside the weekday position`() {
val parsed = parseSimpleRecurrence("FREQ=MONTHLY;INTERVAL=2;BYDAY=2TU;COUNT=12", utc)!!
assertThat(parsed.interval).isEqualTo(2)
assertThat(parsed.end).isEqualTo(RecurrenceEnd.Count(12))
val until = parseSimpleRecurrence("FREQ=MONTHLY;BYDAY=-1FR;UNTIL=20271231T235959Z", utc)!!
assertThat(until.end).isEqualTo(RecurrenceEnd.Until(LocalDate(2027, 12, 31)))
}
@Test
fun `rules the editor cannot represent stay unparsed`() {
listOf(
"FREQ=MONTHLY;BYDAY=2TU,4TU",
"FREQ=MONTHLY;BYDAY=MO",
"FREQ=MONTHLY;BYDAY=6TU",
"FREQ=MONTHLY;BYDAY=-2TU",
"FREQ=MONTHLY;BYDAY=0TU",
"FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1",
"FREQ=MONTHLY;BYDAY=2TU;BYMONTH=3",
"FREQ=YEARLY;BYDAY=2TU",
"FREQ=WEEKLY;BYDAY=2TU",
).forEach { assertThat(parseSimpleRecurrence(it, utc)).isNull() }
}
@Test
fun `the weekday position is only written on a monthly rule`() {
val rule = SimpleRecurrence(
RecurrenceFreq.Weekly,
monthlyWeekday = MonthlyWeekday(2, DayOfWeek.TUESDAY),
)
assertThat(rule.toRRule(utc)).isEqualTo("FREQ=WEEKLY")
}
@Test
fun `prefill is the start date's own position`() {
// 10 Nov 2026 is the second Tuesday; 31 Oct 2026 the fifth Saturday.
assertThat(MonthlyWeekday.of(LocalDate(2026, 11, 10))).isEqualTo(MonthlyWeekday(2, DayOfWeek.TUESDAY))
assertThat(MonthlyWeekday.of(LocalDate(2026, 10, 31))).isEqualTo(MonthlyWeekday(5, DayOfWeek.SATURDAY))
assertThat(MonthlyWeekday.of(LocalDate(2026, 11, 1))).isEqualTo(MonthlyWeekday(1, DayOfWeek.SUNDAY))
}
@Test
fun `first match on or after a date`() {
val secondTue = MonthlyWeekday(2, DayOfWeek.TUESDAY)
// Already a match: stays.
assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 10))).isEqualTo(LocalDate(2026, 11, 10))
// Before it in the month: later the same month.
assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 2))).isEqualTo(LocalDate(2026, 11, 10))
// Past it: next month.
assertThat(secondTue.firstOnOrAfter(LocalDate(2026, 11, 11))).isEqualTo(LocalDate(2026, 12, 8))
// Fifth Saturday: Nov and Dec 2026 have none, so across the year end to 30 Jan 2027.
assertThat(MonthlyWeekday(5, DayOfWeek.SATURDAY).firstOnOrAfter(LocalDate(2026, 11, 1)))
.isEqualTo(LocalDate(2027, 1, 30))
// Last Thursday: 31 Dec 2026, then across the year end to 28 Jan 2027.
val lastThu = MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.THURSDAY)
assertThat(lastThu.firstOnOrAfter(LocalDate(2026, 12, 20))).isEqualTo(LocalDate(2026, 12, 31))
assertThat(lastThu.firstOnOrAfter(LocalDate(2027, 1, 1))).isEqualTo(LocalDate(2027, 1, 28))
}
private fun form(start: LocalDateTime, end: LocalDateTime, rrule: String, isAllDay: Boolean = false) =
EventForm(calendarId = 1L, isAllDay = isAllDay, start = FormTime(start), end = FormTime(end), rrule = rrule)
private val berlin = TimeZone.of("Europe/Berlin")
@Test
fun `a timed start moves to the first matching day keeping time and length`() {
// Thu 3 Dec 2026 10:00–11:30, rule "fifth Saturday" → Sat 30 Jan 2027.
val moved = form(
LocalDateTime(2026, 12, 3, 10, 0),
LocalDateTime(2026, 12, 3, 11, 30),
"FREQ=MONTHLY;BYDAY=5SA",
).alignedToRecurrence(berlin)
assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 30, 10, 0))
assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 30, 11, 30))
}
@Test
fun `an all-day span moves by whole days`() {
// All-day Sat 26 Dec – Sun 27 Dec 2026 (end exclusive Mon 28), rule "last Thursday" → Thu 31 Dec.
val moved = form(
LocalDateTime(2026, 12, 26, 0, 0),
LocalDateTime(2026, 12, 28, 0, 0),
"FREQ=MONTHLY;BYDAY=-1TH",
isAllDay = true,
).alignedToRecurrence(berlin)
assertThat(moved.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 31, 0, 0))
assertThat(moved.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 2, 0, 0))
}
@Test
fun `a matching start or another rule leaves the form alone`() {
val matching = form(
LocalDateTime(2026, 11, 10, 9, 0),
LocalDateTime(2026, 11, 10, 10, 0),
"FREQ=MONTHLY;INTERVAL=2;BYDAY=2TU;COUNT=5",
)
assertThat(matching.alignedToRecurrence(berlin)).isEqualTo(matching)
val weekly = matching.copy(rrule = "FREQ=WEEKLY;BYDAY=FR")
assertThat(weekly.alignedToRecurrence(berlin)).isEqualTo(weekly)
val unsupported = matching.copy(rrule = "FREQ=MONTHLY;BYDAY=1MO,3MO")
assertThat(unsupported.alignedToRecurrence(berlin)).isEqualTo(unsupported)
}
@Test
fun `dateIn resolves positions and skips missing fifths`() {
val sat5 = MonthlyWeekday(5, DayOfWeek.SATURDAY)
assertThat(sat5.dateIn(2026, 10)).isEqualTo(LocalDate(2026, 10, 31))
assertThat(sat5.dateIn(2026, 11)).isNull()
assertThat(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY).dateIn(2026, 11))
.isEqualTo(LocalDate(2026, 11, 28))
assertThat(MonthlyWeekday(1, DayOfWeek.SUNDAY).dateIn(2026, 11))
.isEqualTo(LocalDate(2026, 11, 1))
assertThat(MonthlyWeekday(2, DayOfWeek.TUESDAY).dateIn(2026, 12))
.isEqualTo(LocalDate(2026, 12, 8))
}
@Test
fun `occurrences follow the weekday position across months`() {
val rule = SimpleRecurrence(
RecurrenceFreq.Monthly,
monthlyWeekday = MonthlyWeekday(5, DayOfWeek.SATURDAY),
)
// Fifth Saturdays after 31 Oct 2026: Jan 30 2027, May 29 2027.
assertThat(rule.upcomingOccurrences(LocalDate(2026, 10, 31), limit = 3))
.containsExactly(
LocalDate(2026, 10, 31),
LocalDate(2027, 1, 30),
LocalDate(2027, 5, 29),
).inOrder()
val lastEveryOther = SimpleRecurrence(
RecurrenceFreq.Monthly,
interval = 2,
monthlyWeekday = MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.FRIDAY),
end = RecurrenceEnd.Count(2),
)
assertThat(lastEveryOther.upcomingOccurrences(LocalDate(2026, 11, 27), limit = 5))
.containsExactly(LocalDate(2026, 11, 27), LocalDate(2027, 1, 29)).inOrder()
}
@Test
fun `a fifth weekday is suggested as the last one`() {
assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 10, 31)))
.isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.SATURDAY))
assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 12, 29)))
.isEqualTo(MonthlyWeekday(MonthlyWeekday.LAST, DayOfWeek.TUESDAY))
// The fourth Tuesday of December 2026 is not its last, but stays the fourth.
assertThat(MonthlyWeekday.suggestedFor(LocalDate(2026, 12, 22)))
.isEqualTo(MonthlyWeekday(4, DayOfWeek.TUESDAY))
}
@Test
fun `withRecurrence aligns only on a new weekday position`() {
// Mon 7 Dec 2026, off the second-Tuesday pattern.
val offPattern = form(
LocalDateTime(2026, 12, 7, 9, 0),
LocalDateTime(2026, 12, 7, 10, 0),
"FREQ=MONTHLY;BYDAY=2TU",
)
assertThat(offPattern.withRecurrence("FREQ=MONTHLY;BYDAY=2TU;COUNT=3", berlin).start)
.isEqualTo(offPattern.start)
assertThat(offPattern.withRecurrence("FREQ=MONTHLY;BYDAY=3TU", berlin).start.dateTime)
.isEqualTo(LocalDateTime(2026, 12, 15, 9, 0))
assertThat(offPattern.withRecurrence(null, berlin).start).isEqualTo(offPattern.start)
val plain = offPattern.copy(rrule = "FREQ=MONTHLY")
assertThat(plain.withRecurrence("FREQ=MONTHLY;BYDAY=2TU", berlin).start.dateTime)
.isEqualTo(LocalDateTime(2026, 12, 8, 9, 0))
}
}
@@ -41,7 +41,7 @@ class ReminderPlanTest {
minutesByEvent: Map<Long, List<Int>>,
zone: ZoneId = berlin,
allDayTimeMinutes: Int = nineAm,
) = planReminders(instances, minutesByEvent, zone, allDayTimeMinutes)
) = planReminders(instances, minutesByEvent, zone, AllDayReminderTimes(allDayTimeMinutes))
@Test
fun `a reminder fires its offset before the occurrence begins`() {
@@ -104,6 +104,64 @@ class ReminderPlanTest {
.isEqualTo(LocalDate.parse("2026-01-14").atTime(9, 0))
}
@Test
fun `a calendar's own all-day time replaces the global one for its events only`() {
val sevenPm = 19 * 60
val times = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(2L to sevenPm))
val begin = allDayBegin("2026-01-15")
val planned = planReminders(
instances = listOf(
instance(1L, beginMillis = begin, calendarId = 1L, isAllDay = true),
instance(2L, beginMillis = begin, calendarId = 2L, isAllDay = true),
),
minutesByEvent = mapOf(
1L to listOf(encodedAllDayMinutes("2026-01-15", days = 1)),
2L to listOf(encodedAllDayMinutes("2026-01-15", days = 1)),
),
zone = berlin,
allDayTimes = times,
).associate { it.instance.calendarId to firedAt(it.alarmMillis).toLocalDateTime() }
assertThat(planned).containsExactly(
1L, LocalDate.parse("2026-01-14").atTime(9, 0),
2L, LocalDate.parse("2026-01-14").atTime(19, 0),
)
}
@Test
fun `an on-the-day reminder fires at the calendar's own time`() {
val sixAm = 6 * 60
val alarm = planReminders(
instances = listOf(instance(1L, beginMillis = allDayBegin("2026-07-15"), calendarId = 3L, isAllDay = true)),
minutesByEvent = mapOf(1L to listOf(encodedAllDayMinutes("2026-07-15", days = 0, timeOfDayMinutes = sixAm))),
zone = berlin,
allDayTimes = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(3L to sixAm)),
).single().alarmMillis
assertThat(firedAt(alarm).toLocalDateTime()).isEqualTo(LocalDate.parse("2026-07-15").atTime(6, 0))
}
@Test
fun `a timed event ignores its calendar's all-day time`() {
val begin = now + 30 * minute
val planned = planReminders(
instances = listOf(instance(1L, beginMillis = begin, calendarId = 3L)),
minutesByEvent = mapOf(1L to listOf(10)),
zone = berlin,
allDayTimes = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(3L to 0)),
)
assertThat(planned.single().alarmMillis).isEqualTo(begin - 10 * minute)
}
@Test
fun `all-day times resolve to the calendar's own, else the global default`() {
val times = AllDayReminderTimes(default = nineAm, perCalendar = mapOf(4L to 0))
assertThat(times.forCalendar(4L)).isEqualTo(0)
assertThat(times.forCalendar(5L)).isEqualTo(nineAm)
}
@Test
fun `a summer occurrence of a row written in winter is not an hour early`() {
// The drift this replaces: the offset was sampled at UTC+1, the occurrence
@@ -0,0 +1,62 @@
package de.jeanlucmakiola.calendula.ui
import android.content.Intent
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.prefs.ExternalDateView
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import org.junit.jupiter.api.Test
class ExternalDateTapTest {
private val zone = TimeZone.of("Europe/Berlin")
private val lateEvening = LocalDateTime(2026, 11, 30, 23, 30).toInstant(zone).toEpochMilliseconds()
private fun request(
action: String? = Intent.ACTION_VIEW,
host: String? = CALENDAR_PROVIDER_HOST,
segments: List<String> = listOf("time", lateEvening.toString()),
ownDayTap: Boolean = false,
) = viewTimeRequest(action, host, segments, zone, ownDayTap)
@Test
fun `a launcher date tap opens its local date and follows the setting`() {
assertThat(request()).isEqualTo(WidgetNavRequest.OpenDate("2026-11-30", fromWidget = false, external = true))
}
@Test
fun `the daily summary's own tap stays on the day view`() {
assertThat(request(ownDayTap = true)?.external).isFalse()
}
@Test
fun `other intents are no date tap`() {
assertThat(request(action = Intent.ACTION_EDIT)).isNull()
assertThat(request(host = "com.example")).isNull()
assertThat(request(segments = listOf("events", "12"))).isNull()
assertThat(request(segments = listOf("time"))).isNull()
assertThat(request(segments = listOf("time", "noon"))).isNull()
}
@Test
fun `an external tap set to the default view lands on it`() {
val tap = request()!!
for (view in CalendarView.entries) {
assertThat(tap.stack(view, ExternalDateView.DEFAULT)).containsExactly(view)
}
assertThat(tap.stack(CalendarView.Month, ExternalDateView.DAY))
.containsExactly(CalendarView.Month, CalendarView.Day).inOrder()
}
@Test
fun `our own date opens always drill into the day`() {
val own = request(ownDayTap = true)!!
val widget = WidgetNavRequest.OpenDate("2026-11-30", fromWidget = true)
for (open in listOf(own, widget)) {
assertThat(open.stack(CalendarView.Agenda, ExternalDateView.DEFAULT))
.containsExactly(CalendarView.Agenda, CalendarView.Day).inOrder()
}
}
}
@@ -0,0 +1,33 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.ui.geometry.Offset
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
/** Telling a sideways pinch from an up-and-down one (#389). */
class PinchAxisTest {
@Test
fun `fingers spreading sideways lock to the day count`() {
assertThat(lockPinchAxis(spreadChangeX = 30f, spreadChangeY = 4f)).isEqualTo(PinchAxis.Horizontal)
assertThat(lockPinchAxis(spreadChangeX = -30f, spreadChangeY = 4f)).isEqualTo(PinchAxis.Horizontal)
}
@Test
fun `fingers spreading up and down keep the hour zoom`() {
assertThat(lockPinchAxis(spreadChangeX = 3f, spreadChangeY = -30f)).isEqualTo(PinchAxis.Vertical)
}
@Test
fun `a diagonal pinch stays the hour zoom it always was`() {
assertThat(lockPinchAxis(spreadChangeX = 20f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Vertical)
assertThat(lockPinchAxis(spreadChangeX = 24f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Vertical)
assertThat(lockPinchAxis(spreadChangeX = 30f, spreadChangeY = 20f)).isEqualTo(PinchAxis.Horizontal)
}
@Test
fun `spread is the mean distance from the centroid per axis`() {
assertThat(spreadOf(listOf(Offset(0f, 10f), Offset(100f, 30f)))).isEqualTo(Offset(50f, 10f))
assertThat(spreadOf(emptyList())).isEqualTo(Offset.Zero)
}
}
@@ -1,6 +1,8 @@
package de.jeanlucmakiola.calendula.ui.common
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.R
import java.util.Locale
import java.time.LocalDate
import java.time.ZoneId
import org.junit.jupiter.api.Test
@@ -67,3 +69,44 @@ class RecurrenceTextTest {
assertThat(untilLocalDate("20261340", berlin)).isNull()
}
}
/** Summary phrases for monthly weekday positions (#520). */
class MonthlyWeekdaySummaryTest {
private val english = mapOf(
R.string.recurrence_monthly to "Every month",
R.string.recurrence_every_n_months to "Every %1\$d months",
R.string.recurrence_with_count to "%1\$s, %2\$d times",
R.string.recurrence_monthly_weekday_first to "%1\$s on the first %2\$s",
R.string.recurrence_monthly_weekday_second to "%1\$s on the second %2\$s",
R.string.recurrence_monthly_weekday_third to "%1\$s on the third %2\$s",
R.string.recurrence_monthly_weekday_fourth to "%1\$s on the fourth %2\$s",
R.string.recurrence_monthly_weekday_fifth to "%1\$s on the fifth %2\$s",
R.string.recurrence_monthly_weekday_last to "%1\$s on the last %2\$s",
)
private fun describe(rule: String) = describeRecurrence(rule, Locale.ENGLISH) { id, args ->
english.getValue(id).format(Locale.ENGLISH, *args)
}.text
@Test
fun `each position reads as its ordinal`() {
assertThat(describe("FREQ=MONTHLY;BYDAY=1MO")).isEqualTo("Every month on the first Monday")
assertThat(describe("FREQ=MONTHLY;BYDAY=2TU")).isEqualTo("Every month on the second Tuesday")
assertThat(describe("FREQ=MONTHLY;BYDAY=3WE")).isEqualTo("Every month on the third Wednesday")
assertThat(describe("FREQ=MONTHLY;BYDAY=4TH")).isEqualTo("Every month on the fourth Thursday")
assertThat(describe("FREQ=MONTHLY;BYDAY=5SA")).isEqualTo("Every month on the fifth Saturday")
assertThat(describe("FREQ=MONTHLY;BYDAY=-1SU")).isEqualTo("Every month on the last Sunday")
}
@Test
fun `interval and count wrap the position phrase`() {
assertThat(describe("FREQ=MONTHLY;INTERVAL=2;BYDAY=-1FR;COUNT=4"))
.isEqualTo("Every 2 months on the last Friday, 4 times")
}
@Test
fun `multi-day ordinal BYDAY keeps the plain frequency`() {
assertThat(describe("FREQ=MONTHLY;BYDAY=2TU,4TU")).isEqualTo("Every month")
}
}
@@ -154,4 +154,32 @@ class ViewBackStackTest {
)
assertThat(config.cycle.size).isAtLeast(QuickSwitchConfig.MIN_CYCLE)
}
@Test
fun `a pinch over the home view goes on top of it`() {
assertThat(listOf(CalendarView.Week).swapView(CalendarView.MultiDay))
.containsExactly(CalendarView.Week, CalendarView.MultiDay).inOrder()
}
@Test
fun `a pinch swaps the view on top in place`() {
val stack = listOf(CalendarView.Month, CalendarView.Week)
assertThat(stack.swapView(CalendarView.MultiDay))
.containsExactly(CalendarView.Month, CalendarView.MultiDay).inOrder()
assertThat(stack.swapView(CalendarView.Week)).isEqualTo(stack)
}
@Test
fun `a pinch back to the home view returns to it`() {
assertThat(listOf(CalendarView.Week, CalendarView.Day).swapView(CalendarView.Week))
.containsExactly(CalendarView.Week)
}
@Test
fun `a range picked in the month drills the multi-day view on top, so back returns to the month`() {
val stack = listOf(CalendarView.Month).drillToMultiDay()
assertThat(stack).containsExactly(CalendarView.Month, CalendarView.MultiDay).inOrder()
assertThat(stack.drillToMultiDay()).isEqualTo(stack)
assertThat(stack.dropLast(1)).containsExactly(CalendarView.Month)
}
}
@@ -0,0 +1,89 @@
package de.jeanlucmakiola.calendula.ui.common
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.prefs.WeekNumberingPref
import de.jeanlucmakiola.calendula.data.prefs.weekFields
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import kotlinx.datetime.toJavaLocalDate
import org.junit.jupiter.api.Test
import java.util.Locale
class WeekNumberTest {
private val portugal = Locale.forLanguageTag("pt-PT")
private val germany = Locale.GERMANY
@Test
fun `1 January 2026 is week 1 under ISO for every row start`() {
val rows = (0..6).map { LocalDate(2026, 1, 1).minusDays(it) }
rows.forEach { start ->
assertThat(rowWeekNumber(start, WeekNumberingPref.ISO, portugal)).isEqualTo(1)
}
}
@Test
fun `automatic numbering in Portugal puts 1 January 2026 in week 53`() {
assertThat(rowWeekNumber(LocalDate(2025, 12, 28), WeekNumberingPref.AUTO, portugal)).isEqualTo(53)
assertThat(rowWeekNumber(LocalDate(2025, 12, 29), WeekNumberingPref.AUTO, portugal)).isEqualTo(53)
}
@Test
fun `automatic numbering in Germany matches ISO`() {
assertThat(WeekNumberingPref.AUTO.weekFields(germany)).isEqualTo(WeekNumberingPref.ISO.weekFields(germany))
}
@Test
fun `US numbering puts the week holding 1 January first`() {
assertThat(rowWeekNumber(LocalDate(2025, 12, 28), WeekNumberingPref.US, germany)).isEqualTo(1)
assertThat(rowWeekNumber(LocalDate(2026, 12, 27), WeekNumberingPref.US, germany)).isEqualTo(1)
assertThat(rowWeekNumber(LocalDate(2026, 12, 27), WeekNumberingPref.ISO, germany)).isEqualTo(53)
}
@Test
fun `US numbering with Monday rows`() {
// Mon 2025-12-29 .. Sun 2026-01-04: its Wednesday is in the US week holding 1 January.
assertThat(rowWeekNumber(LocalDate(2025, 12, 29), WeekNumberingPref.US, germany)).isEqualTo(1)
assertThat(rowWeekNumber(LocalDate(2026, 11, 30), WeekNumberingPref.US, germany)).isEqualTo(49)
}
@Test
fun `numbering ignores the region unless automatic`() {
val start = LocalDate(2025, 12, 28)
assertThat(rowWeekNumber(start, WeekNumberingPref.ISO, portugal))
.isEqualTo(rowWeekNumber(start, WeekNumberingPref.ISO, Locale.US))
assertThat(rowWeekNumber(start, WeekNumberingPref.US, portugal))
.isEqualTo(rowWeekNumber(start, WeekNumberingPref.US, Locale.US))
}
@Test
fun `ISO numbering with Sunday and Saturday rows takes the week holding most of the row`() {
// Sun 01-04 .. Sat 01-10: six days in ISO week 2.
assertThat(rowWeekNumber(LocalDate(2026, 1, 4), WeekNumberingPref.ISO, germany)).isEqualTo(2)
// Sat 01-03 .. Fri 01-09: Monday to Friday are ISO week 2.
assertThat(rowWeekNumber(LocalDate(2026, 1, 3), WeekNumberingPref.ISO, germany)).isEqualTo(2)
// Fri 01-02 .. Thu 01-08: Friday to Sunday are week 1, Monday to Thursday week 2.
assertThat(rowWeekNumber(LocalDate(2026, 1, 2), WeekNumberingPref.ISO, germany)).isEqualTo(2)
}
@Test
fun `every row gets the number of the week holding at least four of its days`() {
val regions = listOf(germany, Locale.US, portugal)
var start = LocalDate(2019, 12, 20)
while (start < LocalDate(2028, 1, 10)) {
for (numbering in WeekNumberingPref.entries) for (region in regions) {
val fields = numbering.weekFields(region)
val days = (0..6).map { start.plusDays(it).toJavaLocalDate() }
val majority = days.groupingBy { it.get(fields.weekOfWeekBasedYear()) }.eachCount()
.filterValues { it >= 4 }.keys.single()
assertThat(rowWeekNumber(start, numbering, region)).isEqualTo(majority)
}
start = start.plusDays(1)
}
}
private fun LocalDate.minusDays(days: Int) = minus(days, DateTimeUnit.DAY)
private fun LocalDate.plusDays(days: Int) = plus(days, DateTimeUnit.DAY)
}
@@ -1012,5 +1012,55 @@ class EventEditViewModelTest {
assertThat(vm.state.value?.form?.color).isEqualTo(9)
job.cancel()
}
}
@Test
fun `re-confirming a weekday-position rule keeps an off-pattern start`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
// Mon 7 Dec 2026 09:00 Berlin, a series on second Tuesdays (#520).
val begin = Instant.parse("2026-12-07T08:00:00Z")
val end = Instant.parse("2026-12-07T09:00:00Z")
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L))
eventDetailResult = { detail(calendarId = 1L, rrule = "FREQ=MONTHLY;BYDAY=2TU", start = begin, end = end) }
}
val vm = viewModel(tempDir, fake, zones = FakeZoneSource(berlin))
val job = activate(vm)
vm.openForEdit(eventId = 1L, beginMillis = begin.toEpochMilliseconds(), endMillis = end.toEpochMilliseconds())
advanceUntilIdle()
vm.setRecurrence("FREQ=MONTHLY;BYDAY=2TU")
vm.setRecurrence("FREQ=MONTHLY;BYDAY=2TU;COUNT=5")
assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 7, 9, 0))
vm.setRecurrence("FREQ=MONTHLY;BYDAY=-1TU;COUNT=5")
assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2026, 12, 29, 9, 0))
job.cancel()
}
@Test
fun `a new start date under a weekday-position rule moves on to the rule's next day`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
// Tue 8 Dec 2026 09:00–10:30 Berlin, second Tuesdays (#520).
val begin = Instant.parse("2026-12-08T08:00:00Z")
val end = Instant.parse("2026-12-08T09:30:00Z")
val fake = FakeCalendarDataSource().apply {
calendarsResult = listOf(cal(1L))
eventDetailResult = { detail(calendarId = 1L, rrule = "FREQ=MONTHLY;BYDAY=2TU", start = begin, end = end) }
}
val vm = viewModel(tempDir, fake, zones = FakeZoneSource(berlin))
val job = activate(vm)
vm.openForEdit(eventId = 1L, beginMillis = begin.toEpochMilliseconds(), endMillis = end.toEpochMilliseconds())
advanceUntilIdle()
vm.setStartDate(LocalDate(2026, 12, 16))
val form = vm.state.value!!.form!!
assertThat(form.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 9, 0))
assertThat(form.end.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 10, 30))
vm.setStartTime(LocalTime(11, 0))
assertThat(vm.state.value!!.form!!.start.dateTime).isEqualTo(LocalDateTime(2027, 1, 12, 11, 0))
job.cancel()
}
}
@@ -0,0 +1,60 @@
package de.jeanlucmakiola.calendula.ui.filter
import androidx.compose.ui.state.ToggleableState
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarGroup
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.withGroup
import org.junit.jupiter.api.Test
/** Calendar groups (#166) toggle like the drawer's account headers (#143). */
class CalendarGroupToggleTest {
private fun calendar(id: Long, name: String, visible: Boolean = true) =
CalendarSource(id = id, displayName = name, accountName = "acc$id", accountType = "t", color = 0, isVisibleInSystem = visible)
private val one = calendar(1, "One")
private val two = calendar(2, "Two")
private val three = calendar(3, "Three")
private val all = listOf(one, two, three)
private val groups: List<CalendarGroup> = emptyList<CalendarGroup>()
.withGroup("a", "A", listOf(one, two))
.withGroup("b", "B", listOf(two, three))
private fun drawer(calendars: List<CalendarSource> = all) =
drawerCalendarGroups(groups, calendars, calendars.filter { it.isVisibleInSystem }.map { it.id }.toSet())
@Test
fun `a fully shown group hides its calendars only`() {
val a = drawer()[0]
assertThat(groupVisibility(a.calendarIds, emptySet())).isEqualTo(ToggleableState.On)
assertThat(toggledGroup(emptySet(), a.calendarIds)).containsExactly(1L, 2L)
}
@Test
fun `a partly or fully hidden group shows all of them`() {
val a = drawer()[0]
assertThat(groupVisibility(a.calendarIds, setOf(1L, 3L))).isEqualTo(ToggleableState.Indeterminate)
assertThat(toggledGroup(setOf(1L, 3L), a.calendarIds)).containsExactly(3L)
assertThat(toggledGroup(setOf(1L, 2L), a.calendarIds)).isEmpty()
}
@Test
fun `overlapping groups share the calendar they both hold`() {
val (a, b) = drawer()
val afterA = toggledGroup(emptySet(), a.calendarIds)
assertThat(groupVisibility(b.calendarIds, afterA)).isEqualTo(ToggleableState.Indeterminate)
assertThat(toggledGroup(afterA, b.calendarIds)).containsExactly(1L)
}
@Test
fun `a switched-off or missing calendar is not toggled, a group left with none is empty`() {
val listed = drawer(listOf(one, calendar(2, "Two", visible = false)))
assertThat(listed[0].calendarIds).containsExactly(1L)
assertThat(listed[1].calendarIds).isEmpty()
}
}
@@ -0,0 +1,68 @@
package de.jeanlucmakiola.calendula.ui.month
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.LocalDate
import kotlinx.datetime.number
import org.junit.jupiter.api.Test
/** The run of days a long press and drag in the month picks (#389). */
class RangePickTest {
private val anchor = LocalDate(2026, 10, 16)
@Test
fun `a drag forward picks from the anchor to the finger`() {
val pick = pickRange(anchor, LocalDate(2026, 10, 18))
assertThat(pick.days).isEqualTo(anchor..LocalDate(2026, 10, 18))
assertThat(pick.count).isEqualTo(3)
assertThat(pick.clamped).isFalse()
}
@Test
fun `a drag backwards picks earliest first`() {
val pick = pickRange(anchor, LocalDate(2026, 10, 13))
assertThat(pick.days).isEqualTo(LocalDate(2026, 10, 13)..anchor)
assertThat(pick.count).isEqualTo(4)
}
@Test
fun `back on the anchor is the one day`() {
assertThat(pickRange(anchor, anchor)).isEqualTo(RangePick(anchor..anchor, clamped = false))
assertThat(pickRange(anchor, anchor).count).isEqualTo(1)
}
@Test
fun `exactly the most days is not clamped`() {
val pick = pickRange(anchor, LocalDate(2026, 10, 29))
assertThat(pick.count).isEqualTo(MAX_RANGE_DAYS)
assertThat(pick.clamped).isFalse()
}
@Test
fun `further than the most days stops that far from the anchor either way`() {
val forward = pickRange(anchor, LocalDate(2026, 11, 20))
assertThat(forward.days).isEqualTo(anchor..LocalDate(2026, 10, 29))
assertThat(forward.clamped).isTrue()
val back = pickRange(anchor, LocalDate(2026, 9, 1))
assertThat(back.days).isEqualTo(LocalDate(2026, 10, 3)..anchor)
assertThat(back.count).isEqualTo(MAX_RANGE_DAYS)
assertThat(back.clamped).isTrue()
}
@Test
fun `a pick crosses months`() {
val pick = pickRange(LocalDate(2026, 10, 30), LocalDate(2026, 11, 2))
assertThat(pick.days).isEqualTo(LocalDate(2026, 10, 30)..LocalDate(2026, 11, 2))
assertThat(pick.count).isEqualTo(4)
}
@Test
fun `a pick stops before days that are not shown`() {
val inOctober = { d: LocalDate -> d.month.number == 10 }
val forward = pickRange(LocalDate(2026, 10, 29), LocalDate(2026, 11, 3), pickable = inOctober)
assertThat(forward.days).isEqualTo(LocalDate(2026, 10, 29)..LocalDate(2026, 10, 31))
assertThat(forward.clamped).isFalse()
val back = pickRange(LocalDate(2026, 10, 2), LocalDate(2026, 9, 28), pickable = inOctober)
assertThat(back.days).isEqualTo(LocalDate(2026, 10, 1)..LocalDate(2026, 10, 2))
}
}
@@ -0,0 +1,122 @@
package de.jeanlucmakiola.calendula.ui.week
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import kotlinx.datetime.LocalDate
import org.junit.jupiter.api.Test
import kotlin.math.pow
/** A sideways pinch stepping through day counts (#389). */
class DayCountPinchTest {
private fun steps(n: Float) = 1.2f.pow(n)
@Test
fun `a small spread keeps the count`() {
assertThat(steppedDayCount(current = 7, origin = 7, zoom = 1.1f)).isEqualTo(7)
}
@Test
fun `a step's worth of spread shows a day less, closing shows a day more`() {
assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(1f))).isEqualTo(6)
assertThat(steppedDayCount(current = 3, origin = 3, zoom = steps(-1f))).isEqualTo(4)
}
@Test
fun `seven to one day fits in one pinch`() {
assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(6f))).isEqualTo(1)
}
@Test
fun `a step is taken past the midpoint and given back only past it the other way`() {
// Just past half a step: not yet.
assertThat(steppedDayCount(current = 7, origin = 7, zoom = steps(0.6f))).isEqualTo(7)
// At six, the same spread holds six rather than flicking back.
assertThat(steppedDayCount(current = 6, origin = 7, zoom = steps(0.6f))).isEqualTo(6)
assertThat(steppedDayCount(current = 6, origin = 7, zoom = steps(0.25f))).isEqualTo(7)
}
@Test
fun `the count stays between one day and a week`() {
assertThat(steppedDayCount(current = 3, origin = 3, zoom = 100f)).isEqualTo(1)
assertThat(steppedDayCount(current = 3, origin = 3, zoom = 0.01f)).isEqualTo(7)
}
@Test
fun `a pinch starting on more days than a week can close back to them`() {
assertThat(pinchDayRange(10)).isEqualTo(1..10)
assertThat(steppedDayCount(current = 10, origin = 10, zoom = 0.01f)).isEqualTo(10)
assertThat(steppedDayCount(current = 10, origin = 10, zoom = steps(1f))).isEqualTo(9)
}
@Test
fun `the fingers' place is read across the day columns only`() {
assertThat(columnFraction(x = 100f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false))
.isEqualTo(0f)
assertThat(columnFraction(x = 540f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false))
.isEqualTo(0.5f)
assertThat(columnFraction(x = 50f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false))
.isEqualTo(0f)
assertThat(columnFraction(x = 995f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = false))
.isEqualTo(1f)
}
@Test
fun `right to left the first day is on the right, past the gutter`() {
assertThat(columnFraction(x = 460f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = true))
.isEqualTo(0.5f)
assertThat(columnFraction(x = 900f, width = 1000f, gutterPx = 100f, endInsetPx = 20f, isRtl = true))
.isEqualTo(0f)
}
@Test
fun `the day under the fingers stays in their column`() {
val day = LocalDate(2026, 10, 16)
assertThat(anchoredStart(day, fraction = 0.5f, count = 3)).isEqualTo(LocalDate(2026, 10, 15))
// The run the issue could not reach: the 16th first, from a pinch on the left.
assertThat(anchoredStart(day, fraction = 0.1f, count = 3)).isEqualTo(day)
assertThat(anchoredStart(day, fraction = 1f, count = 3)).isEqualTo(LocalDate(2026, 10, 14))
assertThat(anchoredStart(day, fraction = 0.9f, count = 1)).isEqualTo(day)
}
@Test
fun `the day under a fraction of a span`() {
val span = DaySpan(LocalDate(2026, 10, 12), 7)
assertThat(span.dayAt(0f)).isEqualTo(LocalDate(2026, 10, 12))
assertThat(span.dayAt(0.6f)).isEqualTo(LocalDate(2026, 10, 16))
assertThat(span.dayAt(1f)).isEqualTo(LocalDate(2026, 10, 18))
}
@Test
fun `one day is the day view, more the multi-day view`() {
assertThat(pinchedView(1)).isEqualTo(CalendarView.Day)
assertThat(pinchedView(2)).isEqualTo(CalendarView.MultiDay)
assertThat(pinchedView(7)).isEqualTo(CalendarView.MultiDay)
}
@Test
fun `a pinch from the week anchors on the day under the fingers and gives the week back`() {
val week = DaySpan(LocalDate(2026, 10, 12), 7)
val pinch = DayPinch.start(CalendarView.Week, week, rangeCount = null, fraction = 0.6f)
assertThat(pinch.step(zoom = 1.05f, fraction = 0.6f)).isNull()
assertThat(pinch.step(zoom = steps(1f), fraction = 0.6f)).isEqualTo(
PinchTarget(CalendarView.MultiDay, DaySpan(LocalDate(2026, 10, 13), 6), rangeCount = 6),
)
assertThat(pinch.step(zoom = 1f, fraction = 0.6f))
.isEqualTo(PinchTarget(CalendarView.Week, week, rangeCount = null))
assertThat(pinch.step(zoom = steps(6f), fraction = 0.6f))
.isEqualTo(PinchTarget(CalendarView.Day, DaySpan(LocalDate(2026, 10, 16), 1), rangeCount = null))
assertThat(pinch.count).isEqualTo(1)
}
@Test
fun `a pinch back to the multi-day count it started on restores its session count`() {
val run = DaySpan(LocalDate(2026, 10, 15), 4)
val pinch = DayPinch.start(CalendarView.MultiDay, run, rangeCount = 4, fraction = 0f)
assertThat(pinch.step(zoom = steps(-1f), fraction = 0f))
.isEqualTo(PinchTarget(CalendarView.MultiDay, DaySpan(LocalDate(2026, 10, 15), 5), rangeCount = 5))
assertThat(pinch.step(zoom = 1f, fraction = 0f))
.isEqualTo(PinchTarget(CalendarView.MultiDay, run, rangeCount = 4))
}
}
+19 -2
View File
@@ -137,6 +137,16 @@ gesture finishes from its scaled preview.
out. Blocks sit in their column as shares of its width (`LaneColumn`), so
nothing recomposes per frame. The frame starts and ends exactly as the two
pages lay out, so the pagers either side hand over without a jump.
- **A sideways pinch steps the day count (#389).** `dayCountPinch` sits above
the pager and decides each two-finger gesture's axis once (`PinchAxisLock`):
up-and-down stays the hour zoom, sideways steps 7…1 days with hysteresis
(`steppedDayCount`), each step a column resize like a view switch, anchored
on the day under the fingers. One day is the day view, more the multi-day
view with a session day count (`MultiDayViewModel.showRange`) that the
switcher clears; the pinch swaps the view in place on the back stack. The
month's long press and drag on empty space (`monthRangePickModifier`) picks
up to 14 days the same way and drills the multi-day view over the month; a
long press held still stays the day's tap.
- **Across screens, what both show morphs.** Inside a `SharedTransitionLayout`,
an event shown in both views travels from its old bounds to its new ones,
keyed per occurrence *and* per day it is drawn from (`ViewMorphKey`); only a
@@ -393,8 +403,10 @@ not a plain lead time — `AllDayReminderEncoding` folds a wall-clock hour into
sampled against one date's UTC offset — so taking it at face value drifts by the
offset delta across a DST boundary, and rows from other apps carry no hour at
all. The offset is therefore read only for *which day* it means; the hour comes
from the global all-day reminder setting, recomposed against each occurrence's
own date. Which day that is comes from the local date the encoded instant falls
from the all-day reminder setting — the calendar's own (#541,
`SettingsPrefs.perCalendarAllDayReminderTime`, app-side only) or else the global
one, resolved through `AllDayReminderTimes` — recomposed against each
occurrence's own date. Writes encode against the same per-calendar hour. Which day that is comes from the local date the encoded instant falls
on — except for a plain multiple of 1440, read at face value because a foreign
row means literal days from UTC midnight. The two collide where the all-day hour
equals the zone's UTC offset (20:00 in New York), and there the instant landing
@@ -422,6 +434,11 @@ events through `instancesWithout(range, calendarsHiddenIn(view, …))`, which dr
the calendars hidden in that one view on top of the repository's filters; reminders, search and widgets read
the repository and never see it. The drawer's "Hide in “<view>” view" entry (#517, #143) edits the same
set for the view on show, and the drawer's per-row "Hidden in “<view>” view" notes read it.
Calendar groups (#166, `CalendarPrefs.calendarGroups`) are named member lists
over that same drawer filter: a group row toggles its members' entries in
`hiddenCalendarIds` exactly like an account header (#143). Members are stored
as `DefaultCalendarRef`s and resolved on read, so a missing calendar silently
drops out and a restore maps them by account and name.
**A channel per calendar (#145).** `ReminderChannels` keeps one notification
channel per calendar, grouped by account (one that syncs no events only gets
+8 -3
View File
@@ -48,7 +48,7 @@ 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
launcher name and icon and the app language. Theme and widgets follow the stored
values on their own. A summary lists what could not be imported.
## `settings`
@@ -57,7 +57,9 @@ 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 and its default calendar, reminders
views, the agenda screen, the event form and its default calendar, the drawer's
calendar groups (`calendar_groups`, members named by account and display name
like the default calendar, so they resolve on another device), reminders
and the daily summary, automatic backup (switch, interval and whether it runs, layout, retention,
backup on change) and contact special dates (switch, types, title
templates, year).
@@ -87,6 +89,7 @@ identity instead:
| `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. |
| `all_day_reminder_time_minutes` | Int? | Own all-day reminder time, minutes from midnight. Absent follows the global time. |
| `hidden_in_views` | String[]? | Views it is hidden in only (`Month`, `Week`, …); unknown names are dropped. |
| `notifications` | Boolean? | `false`: Calendula posts none of its reminders. |
| `alert_style` | String? | `full_screen` or `full_screen_ring`; absent or unknown is a plain notification. |
@@ -116,6 +119,7 @@ than writing a file without them.
|---|---|---|
| `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. |
| `launcher_icon` | String? | `BLOOM` or `PLAIN`. Unknown: left as is. |
## Not exported
@@ -125,7 +129,8 @@ 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`, `recent_fixed_time_reminders`: usage history.
- `recent_time_zones`, `recent_fixed_time_reminders`, `recent_custom_colors`: usage
history.
- `notification_category_hint_dismissed`, `reminder_channel_versions`:
this install's notification hint and channels.
- `sync_access_dismissed`: sync-request grants of this device's accounts.
Binary file not shown.
+2 -2
View File
@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6c
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
distributionSha256Sum=0b00b0ffe07c4d4789c12d4935a44a7057d55774b7540bd4a3f76f336deb177a
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
+4
View File
@@ -33,6 +33,10 @@
// One reviewable surface; the dashboard issue lists everything pending.
dependencyDashboard: true,
// settings.gradle includes floret-kit; without it `./gradlew wrapper` can't
// run and Gradle bumps arrive with a stale wrapper jar and checksum.
cloneSubmodules: true,
// The cooling-off periods below are advisory, not a gate. "flexible" still
// prefers a version that has cleared its window, but when every candidate is
// too young it opens the PR at the newest one anyway, so merging early stays