fix(#530): review round 3 - widget day backs to home warm, pending nav restored as sent

This commit is contained in:
makiolaj committed 2026-11-25 15:18:48 +01:00
1 parent 2970ca08d0
commit cd7474f314
12 files changed
+162 -52

No files matched your search

@@ -48,6 +48,8 @@ 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.WidgetNavRequest
import de.jeanlucmakiola.calendula.ui.decodeWidgetNavRequest
import de.jeanlucmakiola.calendula.ui.encode
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
@@ -92,6 +94,7 @@ class MainActivity : AppCompatActivity() {
insertFormOpen = false
if (launchedForInsert) finish()
},
onLeave = { moveTaskToBack(true) },
)
// Whether such a form is still open. Only then does a recreation re-read the
@@ -150,9 +153,10 @@ class MainActivity : AppCompatActivity() {
// specific event is what made a single reminder or widget tap re-open
// that event on every later launch, an error screen once the event had
// been deleted (#309); the user left it long ago, and the activity
// restores where they actually were along with its saved state. A date
// open is held back the same way once handled, so a finished widget day
// (#530) comes back from Recents on the home view.
// restores where they actually were along with its saved state. Every
// widget/shortcut navigation is held back the same way; one still pending
// at the recreation is restored from the saved state instead, so it's the
// request that actually arrived last, not the launch intent's (#530).
//
// Only those channels are held back. An .ics import or a prefilled
// create form keeps no saved state of its own, so re-reading the intent
@@ -164,10 +168,12 @@ class MainActivity : AppCompatActivity() {
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requests.editKey = intent.editEventKeyOrNull()
}
val navPendingBefore = savedInstanceState?.getBoolean(KEY_NAV_PENDING) == true
requests.nav = intent.navRequestOrNull()?.takeUnless {
replaying && (it is WidgetNavRequest.OpenEvent || (it is WidgetNavRequest.OpenDate && !navPendingBefore))
requests.nav = if (replaying) {
savedInstanceState?.getString(KEY_PENDING_NAV)?.let(::decodeWidgetNavRequest)
} else {
intent.navRequestOrNull()
}
requests.leaveOnBack = savedInstanceState?.getBoolean(KEY_LEAVE_ON_BACK) == true
requests.importUri = intent.importUriOrNull()
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
@@ -282,6 +288,12 @@ class MainActivity : AppCompatActivity() {
calendarRepository.refresh()
}
override fun onStop() {
super.onStop()
// Once the user has left, a later return is no longer the widget's day.
if (!isChangingConfigurations) requests.leaveOnBack = false
}
override fun onResume() {
super.onResume()
// Reaching a running UI means startup succeeded; reset the loop trail.
@@ -293,7 +305,8 @@ class MainActivity : AppCompatActivity() {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen)
outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert)
outState.putBoolean(KEY_NAV_PENDING, requests.nav != null)
outState.putString(KEY_PENDING_NAV, requests.nav?.encode())
outState.putBoolean(KEY_LEAVE_ON_BACK, requests.leaveOnBack)
}
override fun onNewIntent(intent: Intent) {
@@ -486,7 +499,7 @@ class MainActivity : AppCompatActivity() {
endMillis = getLongExtra(EXTRA_END_MILLIS, 0L),
source = source,
)
source != null && getStringExtra(EXTRA_DATE_ISO) != null ->
getStringExtra(EXTRA_DATE_ISO) != null ->
WidgetNavRequest.OpenDate(getStringExtra(EXTRA_DATE_ISO)!!, fromWidget = true)
else -> null
}
@@ -569,7 +582,13 @@ class MainActivity : AppCompatActivity() {
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
private const val KEY_NAV_PENDING = "nav_pending"
private const val KEY_PENDING_NAV = "pending_nav"
// Delivered to the running activity even when the task was started by
// this very intent, which NEW_TASK alone would only bring to the front.
private const val WIDGET_LAUNCH_FLAGS = Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
private const val KEY_LEAVE_ON_BACK = "leave_on_back"
private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
@@ -609,18 +628,13 @@ class MainActivity : AppCompatActivity() {
/**
* Open the day view anchored on [date] from a home-screen widget; backing
* out of the day returns to the home screen (#530). [source] marks the
* launch as a widget's and keeps different widget kinds' PendingIntents
* apart; its value doesn't change where back goes.
* out of the day returns to the home screen (#530).
*/
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
fun openDateIntent(context: Context, date: LocalDate): Intent =
Intent(context, MainActivity::class.java).apply {
// The source is part of the URI so widgets of different kinds
// tapping the same date don't share one PendingIntent.
data = "calendula://date/$date/${source.name}".toUri()
data = "calendula://date/$date".toUri()
putExtra(EXTRA_DATE_ISO, date.toString())
putExtra(EXTRA_SOURCE_VIEW, source.name)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(WIDGET_LAUNCH_FLAGS)
}
/**
@@ -638,6 +652,7 @@ class MainActivity : AppCompatActivity() {
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
data = "calendula://event/$eventId/$beginMillis/${source.name}".toUri()
putExtra(EXTRA_SOURCE_VIEW, source.name)
addFlags(WIDGET_LAUNCH_FLAGS)
}
/**
@@ -660,7 +675,7 @@ class MainActivity : AppCompatActivity() {
data = "calendula://create/$date".toUri()
putExtra(EXTRA_CREATE, true)
putExtra(EXTRA_DATE_ISO, date.toString())
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(WIDGET_LAUNCH_FLAGS)
}
/**
@@ -674,7 +689,7 @@ class MainActivity : AppCompatActivity() {
Intent(context, MainActivity::class.java).apply {
data = "calendula://view/${view?.name ?: "default"}".toUri()
putExtra(EXTRA_OPEN_VIEW, view?.name ?: "")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(WIDGET_LAUNCH_FLAGS)
}
}
}
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivity
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
@@ -167,8 +166,6 @@ fun CalendarHost(
// True after backing out of a day opened from the view now shown, so the
// agenda returns to where it was instead of today (#367).
var returnedFromDay by remember { mutableStateOf(false) }
// A day opened from a widget leaves the app on back (#530), until the user moves on in it.
var exitOnBack by rememberSaveable { mutableStateOf(false) }
val view = viewStack.last()
// The date every view opens on and carries along (#184); tapping a day
// anywhere focuses it and opens the day view there.
@@ -188,7 +185,7 @@ fun CalendarHost(
navigationVersion++
returnedFromDay = false
val moved = move(viewStack)
if (moved != viewStack) exitOnBack = false
requests.leaveOnBack = keepsLeaveOnBack(requests.leaveOnBack, viewStack, moved)
viewStack = moved
}
val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } }
@@ -425,7 +422,7 @@ fun CalendarHost(
dismissCoveringOverlays()
focus.navigateTo(LocalDate.parse(req.dateIso))
viewStack = listOf(defaultView).drillToDay()
exitOnBack = req.fromWidget
requests.leaveOnBack = req.leavesOnBack
requests.nav = null
}
is WidgetNavRequest.OpenEvent -> {
@@ -433,7 +430,7 @@ fun CalendarHost(
// detail over it (same key shape as a tapped event / reminder).
dismissCoveringOverlays()
viewStack = viewBaseStack(defaultView, req.source)
exitOnBack = false
requests.leaveOnBack = false
detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
requests.nav = null
}
@@ -445,7 +442,7 @@ fun CalendarHost(
dismissCoveringOverlays()
focus.navigateTo(currentDate())
viewStack = viewBaseStack(defaultView, req.view ?: defaultView)
exitOnBack = false
requests.leaveOnBack = false
requests.nav = null
}
is WidgetNavRequest.Create -> {
@@ -542,11 +539,17 @@ fun CalendarHost(
val viewTransition = remember { SeekableTransitionState(view) }
LaunchedEffect(view) { viewTransition.animateTo(view) }
val reduceMotion = rememberReduceMotion()
val activity = LocalActivity.current
val leaveOnBack = !anyOverlayVisible && exitOnBack && activity != null
val leaveOnBack = !anyOverlayVisible && requests.leaveOnBack
val viewBackEnabled = !anyOverlayVisible && viewStack.size > 1 && !leaveOnBack
// Finished rather than sent to the background, so the next launch opens on the home view.
BackHandler(enabled = leaveOnBack) { activity?.finish() }
// The app goes to the background on the home view, so coming back shows home.
BackHandler(enabled = leaveOnBack) {
requests.onLeave()
requests.leaveOnBack = false
navigationVersion++
returnedFromDay = false
focus.navigateTo(currentDate())
viewStack = listOf(defaultView)
}
if (reduceMotion) {
BackHandler(enabled = viewBackEnabled) {
navigationVersion++
@@ -15,10 +15,14 @@ import de.jeanlucmakiola.calendula.ui.edit.ImportSource
* it, so a later recomposition can't act on it twice.
*
* [onExternalFormClosed] runs when a form opened for [insert] closes, so the
* activity can hand control back to the app that asked.
* activity can hand control back to the app that asked. [onLeave] sends the app
* to the background when back leaves a widget's day ([leaveOnBack]).
*/
@Stable
class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) {
class ExternalRequests(
val onExternalFormClosed: () -> Unit = {},
val onLeave: () -> Unit = {},
) {
/** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */
var detailKey by mutableStateOf<LongArray?>(null)
@@ -37,6 +41,9 @@ class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) {
/** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */
var editKey by mutableStateOf<LongArray?>(null)
/** Back leaves the app at once: a widget's day is showing (#530). Cleared when the app goes to the background. */
var leaveOnBack by mutableStateOf(false)
/** Whether these came from re-reading the launch intent on a recreation. */
var replayed = false
}
@@ -39,3 +39,49 @@ sealed interface WidgetNavRequest {
*/
data class OpenView(val view: CalendarView?) : WidgetNavRequest
}
/** Whether back leaves the app straight from what this request opens (a widget's day, #530). */
val WidgetNavRequest.leavesOnBack: Boolean
get() = this is WidgetNavRequest.OpenDate && fromWidget
/**
* Whether a widget day's leave-on-back stays armed across a move from [before] to
* [after]: only while the user hasn't navigated to another view.
*/
fun keepsLeaveOnBack(armed: Boolean, before: List<CalendarView>, after: List<CalendarView>): Boolean =
armed && before == after
/** A request as one string, so a still-pending one survives a recreation. */
fun WidgetNavRequest.encode(): String = when (this) {
is WidgetNavRequest.OpenDate -> listOf("date", dateIso, fromWidget.toString())
is WidgetNavRequest.OpenEvent -> listOf("event", eventId, beginMillis, endMillis, source.name)
is WidgetNavRequest.Create -> listOf("create", dateIso.orEmpty())
is WidgetNavRequest.OpenView -> listOf("view", view?.name.orEmpty())
}.joinToString(SEPARATOR)
/** The request [encode] wrote, or null for anything it didn't. */
fun decodeWidgetNavRequest(encoded: String): WidgetNavRequest? {
val parts = encoded.split(SEPARATOR)
fun view(name: String) = CalendarView.entries.firstOrNull { it.name == name }
return when (parts.firstOrNull()) {
"date" -> if (parts.size == 3) WidgetNavRequest.OpenDate(parts[1], parts[2].toBoolean()) else null
"event" -> if (parts.size == 5) {
val id = parts[1].toLongOrNull()
val begin = parts[2].toLongOrNull()
val end = parts[3].toLongOrNull()
val source = view(parts[4])
if (id != null && begin != null && end != null && source != null) {
WidgetNavRequest.OpenEvent(id, begin, end, source)
} else {
null
}
} else {
null
}
"create" -> if (parts.size == 2) WidgetNavRequest.Create(parts[1].ifEmpty { null }) else null
"view" -> if (parts.size == 2) WidgetNavRequest.OpenView(view(parts[1])) else null
else -> null
}
}
private const val SEPARATOR = "|"
@@ -39,9 +39,9 @@ internal fun EventInstance.openIntent(context: Context, source: CalendarView) =
source = source,
)
/** Opens [date] in the app's agenda. */
/** Opens [date]'s day view. */
internal fun openDayAction(context: Context, date: LocalDate) =
actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda))
actionStartActivity(MainActivity.openDateIntent(context, date))
/** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */
internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String =
@@ -33,7 +33,6 @@ import androidx.glance.text.Text
import androidx.glance.text.TextAlign
import androidx.glance.text.TextStyle
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
import de.jeanlucmakiola.calendula.widget.WidgetAppearance
@@ -99,7 +98,7 @@ internal fun DateWidgetContent(today: LocalDate, appearance: WidgetAppearance, a
Column(
modifier = GlanceModifier
.fillMaxSize()
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day)))
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today)))
.semantics { contentDescription = label },
horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically,
@@ -14,7 +14,6 @@ import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.isCrossedOut
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.ui.common.eventInk
import de.jeanlucmakiola.floret.glance.RemoteColor
@@ -161,7 +160,7 @@ private fun span(text: String, span: Any): CharSequence =
private fun openDayIntent(context: Context, date: LocalDate): PendingIntent = PendingIntent.getActivity(
context,
date.toEpochDays().toInt(),
MainActivity.openDateIntent(context, date, CalendarView.Month),
MainActivity.openDateIntent(context, date),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
@@ -415,7 +415,7 @@ private fun DayList(day: LocalDate, data: MonthDayData.Ready, preview: Boolean)
val events = groupAgendaDays(day, day, source.instances, zone).firstOrNull()?.events.orEmpty()
.let { all -> if (data.options.pastDisplay == PastEventDisplay.HIDE) all.filterNot { it.hasEnded(data.now) } else all }
val metrics = compactRowMetrics(data.options.textSize, context.resources.configuration.fontScale)
val openDay = actionStartActivity(MainActivity.openDateIntent(context, day, CalendarView.Month))
val openDay = actionStartActivity(MainActivity.openDateIntent(context, day))
Column(modifier = GlanceModifier.fillMaxSize()) {
val date = localizedDateFormatter(widgetLocale(), "EEEdMMM").format(day.toJavaLocalDate())
val label = when (day) {
@@ -245,7 +245,7 @@ private fun TodayPill(today: LocalDate) {
.fillMaxHeight()
.cornerRadius(PillWidth / 2)
.background(GlanceTheme.colors.primary)
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day)))
.clickable(actionStartActivity(MainActivity.openDateIntent(context, today)))
.semantics { contentDescription = localizedDateFormatter(locale, "EEEEdMMMM").format(today.toJavaLocalDate()) },
horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically,
@@ -46,7 +46,6 @@ import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
@@ -155,7 +154,7 @@ private fun DayTile(date: LocalDate, data: DaysWidgetData.Ready) {
.fillMaxSize()
.cornerRadius(14.dp)
.background(container)
.clickable(actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Week)))
.clickable(actionStartActivity(MainActivity.openDateIntent(context, date)))
.semantics {
contentDescription = if (colors.isEmpty()) label else context.resources.getQuantityString(
R.plurals.widget_day_with_events, events.size, label, events.size,
@@ -0,0 +1,49 @@
package de.jeanlucmakiola.calendula.ui
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import org.junit.jupiter.api.Test
class WidgetNavRequestTest {
@Test
fun `only a widget's day leaves on back`() {
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = true).leavesOnBack).isTrue()
assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = false).leavesOnBack).isFalse()
assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Agenda).leavesOnBack).isFalse()
assertThat(WidgetNavRequest.OpenView(CalendarView.Month).leavesOnBack).isFalse()
assertThat(WidgetNavRequest.Create(null).leavesOnBack).isFalse()
}
@Test
fun `leave on back stays armed only while the view stays put`() {
val day = listOf(CalendarView.Week, CalendarView.Day)
assertThat(keepsLeaveOnBack(true, day, day.toList())).isTrue()
assertThat(keepsLeaveOnBack(true, day, listOf(CalendarView.Week))).isFalse()
assertThat(keepsLeaveOnBack(true, day, day + CalendarView.Month)).isFalse()
assertThat(keepsLeaveOnBack(false, day, day)).isFalse()
}
@Test
fun `every request survives the encode round trip`() {
val requests = listOf(
WidgetNavRequest.OpenDate("2026-11-25", fromWidget = true),
WidgetNavRequest.OpenDate("2026-11-25", fromWidget = false),
WidgetNavRequest.OpenEvent(42, 1_000, 2_000, CalendarView.Agenda),
WidgetNavRequest.Create("2026-11-25"),
WidgetNavRequest.Create(null),
WidgetNavRequest.OpenView(CalendarView.Month),
WidgetNavRequest.OpenView(null),
)
requests.forEach { assertThat(decodeWidgetNavRequest(it.encode())).isEqualTo(it) }
}
@Test
fun `malformed input decodes to nothing`() {
assertThat(decodeWidgetNavRequest("")).isNull()
assertThat(decodeWidgetNavRequest("date|2026-11-25")).isNull()
assertThat(decodeWidgetNavRequest("event|x|1|2|Agenda")).isNull()
assertThat(decodeWidgetNavRequest("event|1|1|2|Nope")).isNull()
assertThat(decodeWidgetNavRequest("other|1")).isNull()
}
}
@@ -74,7 +74,8 @@ class ViewBackStackTest {
}
@Test
fun `a day drilled over a widget's view backs out to it, then home`() {
fun `a day tapped in a widget event's view backs out to it, then home`() {
// Agenda widget event tap roots [Week, Agenda]; a day tapped there drills on top.
val stack = viewBaseStack(CalendarView.Week, CalendarView.Agenda).drillToDay()
assertThat(stack)
.containsExactly(CalendarView.Week, CalendarView.Agenda, CalendarView.Day)
@@ -84,14 +85,6 @@ class ViewBackStackTest {
assertThat(stack.dropLast(2)).containsExactly(CalendarView.Week)
}
@Test
fun `a day drilled over the month backs out to it, then home`() {
val stack = viewBaseStack(CalendarView.Week, CalendarView.Month).drillToDay()
assertThat(stack.last()).isEqualTo(CalendarView.Day)
assertThat(stack.dropLast(1).last()).isEqualTo(CalendarView.Month)
assertThat(stack.first()).isEqualTo(CalendarView.Week)
}
@Test
fun `a date launch drills the day over the home view only`() {
assertThat(listOf(CalendarView.Week).drillToDay())