Compare commits

..
Author SHA1 Message Date
makiolaj 5d45bb64f0 Setting for what other apps' date taps open (#524) 2026-11-30 19:38:16 +01:00
31 changed files with 254 additions and 677 deletions

No files matched your search

+2 -2
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" />
@@ -49,7 +49,9 @@ 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.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 +75,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
@@ -473,26 +473,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 +586,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 +601,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 +673,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)
}
@@ -42,14 +42,13 @@ 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,
@@ -9,9 +9,6 @@ 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
@@ -82,13 +79,6 @@ 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.
@@ -106,8 +96,6 @@ 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}" } },
@@ -97,6 +97,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?,
@@ -183,6 +186,7 @@ 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)
@@ -290,6 +294,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
@@ -792,6 +797,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
@@ -1,92 +0,0 @@
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"
@@ -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
@@ -431,11 +432,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,10 +677,6 @@ fun CalendarHost(
showViewCalendars = true
switchScope.launch { drawerState.close() }
},
onManageGroups = {
showCalendars = true
switchScope.launch { drawerState.close() }
},
)
},
) {
@@ -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 ||
@@ -1,180 +0,0 @@
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,7 +66,6 @@ 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
@@ -126,9 +125,6 @@ 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
@@ -151,9 +147,6 @@ fun CalendarsScreen(
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
@@ -207,36 +200,7 @@ 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) {
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.
@@ -273,9 +237,6 @@ 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() }
@@ -299,14 +260,6 @@ 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)
@@ -739,7 +692,7 @@ private fun ManagedNote() {
}
@Composable
internal fun DeleteCalendarRow(onClick: () -> Unit) {
private fun DeleteCalendarRow(onClick: () -> Unit) {
GroupedSurface(
position = Position.Alone,
modifier = Modifier.padding(horizontal = 16.dp),
@@ -13,11 +13,7 @@ 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
@@ -56,7 +52,6 @@ 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() {
@@ -155,21 +150,6 @@ class CalendarsViewModel @Inject constructor(
settingsPrefs.setCalendarHiddenIn(id, view, hidden)
}
/** 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,7 +79,6 @@ fun CalendarDrawer(
onJumpToDate: (LocalDate) -> Unit,
onSettings: () -> Unit,
onHideInView: () -> Unit,
onManageGroups: () -> Unit,
viewOrder: List<CalendarView> = IMPLEMENTED_VIEWS,
sync: DrawerSync? = null,
) {
@@ -124,7 +123,7 @@ fun CalendarDrawer(
Spacer(Modifier.height(16.dp))
DrawerSectionHeader(stringResource(R.string.filter_title))
CalendarFilterList(currentView = currentView, onHideInView = onHideInView, onManageGroups = onManageGroups)
CalendarFilterList(currentView = currentView, onHideInView = onHideInView)
Spacer(Modifier.height(16.dp))
GroupedRow(
@@ -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
}
@@ -7,20 +7,15 @@ 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
@@ -32,9 +27,6 @@ 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
@@ -65,7 +57,6 @@ import de.jeanlucmakiola.floret.components.positionOf
fun CalendarFilterList(
currentView: CalendarView,
onHideInView: () -> Unit,
onManageGroups: () -> Unit,
modifier: Modifier = Modifier,
viewModel: FilterViewModel = hiltViewModel(),
) {
@@ -77,7 +68,6 @@ 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,
@@ -85,7 +75,6 @@ fun CalendarFilterList(
onHideInView = onHideInView,
onToggleCalendar = viewModel::toggleCalendar,
onToggleGroup = viewModel::toggleGroup,
onManageGroups = onManageGroups,
modifier = modifier,
)
}
@@ -100,7 +89,6 @@ fun CalendarFilterList(
@Composable
private fun FilterList(
groups: List<CalendarAccountGroup>,
calendarGroups: List<DrawerCalendarGroup>,
hidden: Set<Long>,
hiddenInView: Set<Long>,
hiddenOnlyHere: Int,
@@ -108,14 +96,10 @@ 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(
@@ -165,63 +149,6 @@ 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,7 +21,6 @@ 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
@@ -33,6 +32,3 @@ 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,8 +37,7 @@ 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(),
prefs.calendarGroups,
) { calendars, hidden, hiddenViews, groups ->
) { calendars, hidden, hiddenViews ->
// 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 }
@@ -46,13 +45,7 @@ class FilterViewModel @Inject constructor(
if (failure != null) {
FilterUiState.Failure(failure)
} else {
val listed = enabled.mapTo(mutableSetOf()) { it.id }
FilterUiState.Success(
groups = enabled.groupByAccount(),
hidden = hidden,
hiddenViews = hiddenViews,
calendarGroups = drawerCalendarGroups(groups, calendars, listed),
)
FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews)
}
}
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
@@ -76,8 +69,7 @@ class FilterViewModel @Inject constructor(
}
/**
* Flip one calendar, or a whole account from its header (#143) or a
* calendar group (#166). All decide
* Flip one calendar, or a whole group from its header (#143). Both decide
* against the stored set rather than the last drawn state, so quick repeated
* taps still alternate.
*/
@@ -1,8 +1,6 @@
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 {
@@ -20,15 +18,3 @@ 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 })
}
@@ -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
@@ -480,6 +481,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(
@@ -5,6 +5,7 @@ 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
@@ -62,6 +63,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). */
@@ -30,6 +30,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
@@ -150,6 +151,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],
@@ -373,6 +375,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) }
@@ -25,6 +25,7 @@ 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
@@ -76,6 +77,7 @@ 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 showTimeFormat by remember { mutableStateOf(false) }
var showTapOpens by remember { mutableStateOf(false) }
@@ -103,6 +105,12 @@ 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()),
@@ -328,6 +336,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,
@@ -519,6 +538,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,
@@ -184,6 +184,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
@@ -354,6 +355,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() }
+3 -15
View File
@@ -575,21 +575,6 @@
<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>
@@ -606,6 +591,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>
@@ -9,9 +9,7 @@ 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
@@ -128,20 +126,6 @@ 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()
@@ -1,78 +0,0 @@
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()
}
}
@@ -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()
}
}
}
@@ -1,60 +0,0 @@
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()
}
}
-5
View File
@@ -422,11 +422,6 @@ 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
+1 -3
View File
@@ -57,9 +57,7 @@ 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, 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
views, the agenda screen, the event form and its default calendar, 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).