Give every drop its own token and queue drops in order (#494)

This commit is contained in:
makiolaj committed 2026-11-13 12:00:37 +01:00
1 parent 5f8eb39206
commit 8e3202d1ad
10 files changed
+269 -217

No files matched your search

@@ -485,9 +485,8 @@ fun CalendarHost(
movableCalendarIds = movableCalendarIds,
dragEnabled = dragToReschedule,
move = { reschedule.move(it) },
inFlight = reschedule.inFlight,
drops = reschedule.drops,
undoStarted = reschedule.undoStarted,
abandoned = reschedule.abandoned,
edit = onEditEvent,
)
}
@@ -90,6 +90,7 @@ fun EventMoveHost(
MoveOutcome.Undone -> stringResource(R.string.event_move_undone)
MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied)
MoveOutcome.Gone -> stringResource(R.string.event_move_gone)
MoveOutcome.Stale -> stringResource(R.string.event_move_stale)
MoveOutcome.BlockedSeriesEnd -> stringResource(R.string.event_move_blocked_series_end)
MoveOutcome.BlockedCancelledSeries -> stringResource(R.string.event_move_blocked_cancelled_series)
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
@@ -6,7 +6,7 @@ import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
@@ -16,6 +16,7 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.util.concurrent.atomic.AtomicLong
/**
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
@@ -37,24 +38,18 @@ class EventMoveScope(
val dragEnabled: Boolean,
/**
* Hand a drop to the writer. Returns nothing on purpose: a drop is answered
* before its write resolves, so [abandoned] — not a return value — is what
* tells a held copy that nothing landed.
* before its write resolves, so [drops] — not a return value — is what tells
* a held copy whether anything landed.
*/
val move: (MoveRequest) -> Unit,
/**
* True while a dropped event is being written, including the time its scope
* dialog is up. A flow rather than a value so this scope stays the same
* object across a move — every visible block reads it as a composition local.
* Each drop's progress by its token — see `RescheduleViewModel.drops`. A flow
* rather than a value so this scope stays the same object across a move —
* every visible block reads it as a composition local.
*/
val inFlight: StateFlow<Boolean>,
/** Ticks when an undo write begins — see `RescheduleViewModel.undoStarted`. */
val undoStarted: StateFlow<Int>,
/**
* Ticks when a drop ends with nothing landing — see
* `RescheduleViewModel.abandoned`. [move] answers before the write is
* resolved, so this is what tells a held copy to stop waiting.
*/
val abandoned: StateFlow<Int>,
val drops: StateFlow<DropStates>,
/** The token of the undo write that just began — see `RescheduleViewModel.undoStarted`. */
val undoStarted: StateFlow<Long?>,
/** Open an event in the edit form — the pointer-free route to the same change. */
val edit: (EventInstance) -> Unit,
) {
@@ -63,46 +58,56 @@ class EventMoveScope(
val LocalEventMove = compositionLocalOf<EventMoveScope?> { null }
private val NEVER_IN_FLIGHT = MutableStateFlow(false)
private val moveTokens = AtomicLong()
private val NEVER_UNDONE = MutableStateFlow(0)
/** A fresh identity for one drop or undo, unique for the process. */
fun nextMoveToken(): Long = moveTokens.incrementAndGet()
private val NEVER_ABANDONED = MutableStateFlow(0)
/** How many ended drops [DropStates] remembers — far more than can be on screen at once. */
private const val ENDED_KEPT = 32
/** Per-drop progress, by token — see `RescheduleViewModel.drops`. */
@Immutable
data class DropStates(
val pending: Set<Long> = emptySet(),
val abandoned: Set<Long> = emptySet(),
) {
fun started(token: Long): DropStates = copy(pending = pending + token)
fun ended(token: Long, landed: Boolean): DropStates = copy(
pending = pending - token,
abandoned = if (landed) abandoned else (abandoned + token).toList().takeLast(ENDED_KEPT).toSet(),
)
}
private val NO_DROPS = MutableStateFlow(DropStates())
private val NEVER_UNDONE = MutableStateFlow<Long?>(null)
/**
* Whether a dropped event is still being written — false wherever moving is off.
* The drag overlays hold a landed block on its target for this window.
* Every drop's progress — empty wherever moving is off. A drag overlay keeps
* the token of its own drop and holds its copy while that token is pending.
*/
@Composable
fun moveInFlight(): Boolean {
val flow = LocalEventMove.current?.inFlight ?: NEVER_IN_FLIGHT
fun dropStates(): DropStates {
val flow = LocalEventMove.current?.drops ?: NO_DROPS
return flow.collectAsStateWithLifecycle().value
}
/**
* How many drops have ended with nothing landing. Read as a plain count so a
* drag overlay can capture it at the moment of the drop and tell, later, whether
* *its own* drop was one of them.
* Runs [onUndo] with the undo's token when an undo write begins, and never for
* one that began before this composable came on screen.
*/
@Composable
fun abandonedMoves(): Int {
val flow = LocalEventMove.current?.abandoned ?: NEVER_ABANDONED
return flow.collectAsStateWithLifecycle().value
}
/**
* Runs [onUndo] when an undo write begins, and never for one that began before
* this composable came on screen.
*/
@Composable
fun OnUndoStarted(onUndo: () -> Unit) {
fun OnUndoStarted(onUndo: (token: Long) -> Unit) {
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
val tick by flow.collectAsStateWithLifecycle()
var seen by remember { mutableIntStateOf(tick) }
LaunchedEffect(tick) {
if (tick == seen) return@LaunchedEffect
seen = tick
onUndo()
val token by flow.collectAsStateWithLifecycle()
var seen by remember { mutableStateOf(token) }
LaunchedEffect(token) {
val started = token
if (started == null || started == seen) return@LaunchedEffect
seen = started
onUndo(started)
}
}
@@ -32,6 +32,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
@@ -46,6 +47,9 @@ import javax.inject.Inject
private const val MILLIS_PER_MINUTE = 60_000
private const val MINUTES_PER_DAY = 24 * 60
/** How many drops may wait behind the one in flight before more are refused. */
private const val MAX_QUEUED = 8
/** Where a dragged event should land. */
sealed interface MoveTarget {
/** A new start instant — a timeline drag, which moves time and day at once. */
@@ -74,6 +78,8 @@ data class MoveRequest(
val beginMillis: Long,
val endMillis: Long,
val target: MoveTarget,
/** The drop's own identity, from [nextMoveToken], which the view holding its copy waits on. */
val token: Long = nextMoveToken(),
)
/**
@@ -115,6 +121,12 @@ sealed interface MoveOutcome {
/** The event vanished (sync, another device) between the read and the write. */
data object Gone : MoveOutcome
/**
* A drop that waited for an earlier one found its occurrence no longer where
* it was picked up — the earlier write moved it — so it is not written (#494).
*/
data object Stale : MoveOutcome
/** The drop would push the series past its own `UNTIL`, generating nothing. */
data object BlockedSeriesEnd : MoveOutcome
@@ -152,51 +164,37 @@ class RescheduleViewModel @Inject constructor(
private val _inFlight = MutableStateFlow(false)
/**
* True from the moment a drop is accepted until its write settles — the
* window the dropped block holds its landing position for.
*/
/** True while any write runs or waits, a queued drop included — what the confirmation chip holds for. */
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
private val _abandoned = MutableStateFlow(0)
private val _drops = MutableStateFlow(DropStates())
/**
* Ticks when a drop ends with nothing on the target day: refused outright,
* refused before the write, written and failed, or its scope dialog
* dismissed. [move] answers before any of that is known, so without this
* signal the view that drew the drop held its copy out for the full settle
* timeout waiting for a grid that was never going to draw it (#253).
* Each drop's own state, by its [MoveRequest.token]: pending from the moment
* it is accepted until its write settles, and abandoned once it ends with
* nothing on the target day — refused, failed, or its scope dialog dismissed.
* Per drop, so a queued drop's held copy waits on its own write and is never
* let go by another drop's failure (#253, #494).
*/
val abandoned: StateFlow<Int> = _abandoned.asStateFlow()
val drops: StateFlow<DropStates> = _drops.asStateFlow()
private val _undoStarted = MutableStateFlow(0)
private val _undoStarted = MutableStateFlow<Long?>(null)
/**
* Ticks the moment an undo write begins, before the provider has anything to
* re-read, so the view that drew the drop can carry its chip back rather than
* let it reappear on the old day.
* The token of an undo write the moment it begins, before the provider has
* anything to re-read, so the view that drew the drop can carry its chip back
* rather than let it reappear on the old day. Its fate then reads off [drops].
*/
val undoStarted: StateFlow<Int> = _undoStarted.asStateFlow()
val undoStarted: StateFlow<Long?> = _undoStarted.asStateFlow()
/**
* Set from the moment a drop is accepted until its write settles. Two drops
* of the same recurring event inside that window would compute their shift
* from the same pre-move occurrence, and the shifts would compound.
* Set while a drop is being prepared, waits on its scope dialog, or is
* written. Drops arriving in that window wait in [queue] and run in order.
*/
private var busy = false
set(value) {
field = value
_inFlight.value = value
}
/** The event whose drop owns the pipeline, while [busy]. */
private var busyEventId: Long? = null
/**
* A drop of another event that arrived while one was still being written,
* run once that write settles rather than snapping back unannounced (#494).
*/
private var queued: MoveRequest? = null
/** Drops that arrived while another was in flight, oldest first (#494). */
private val queue = ArrayDeque<MoveRequest>()
/**
* The calendars whose events may be dragged. Nothing below the UI guards
@@ -228,41 +226,44 @@ class RescheduleViewModel @Inject constructor(
}
/**
* Take a drop, or queue it behind the one being written (see [canQueue]). False means nothing will
* be written; [abandoned] ticks for that refusal too, so a held copy is let
* go by the one signal rather than by every caller remembering to.
* Take a drop: run it now, or queue it behind the ones in flight. False means
* nothing will be written — the queue is full — and the drop is marked
* abandoned in [drops], so its held copy is let go by the one signal rather
* than by every caller remembering to.
*
* The Boolean is diagnostic — the tests read it, [EventMoveScope] does not
* hand it on. A caller that gated on it would be back to releasing its copy
* from two places, and it answers before the write is resolved anyway.
* hand it on. It answers before the write is resolved anyway.
*/
fun move(request: MoveRequest): Boolean {
if (busy && canQueue(request)) {
queued = request
return true
}
if (busy || _scopePrompt.value != null) {
_abandoned.value += 1
if (queue.size >= MAX_QUEUED) {
_drops.update { it.ended(request.token, landed = false) }
return false
}
_drops.update { it.started(request.token) }
if (busy) {
queue.addLast(request)
} else {
run(request, waited = false)
}
syncInFlight()
return true
}
private fun run(request: MoveRequest, waited: Boolean) {
busy = true
busyEventId = request.eventId
viewModelScope.launch {
val prepared = prepare(request)
val prepared = prepare(request, waited)
if (prepared == null) {
_abandoned.value += 1
settle()
settle(request.token, landed = false)
return@launch
}
// A cancelled series only moves as a whole (#388).
val seriesOnly = !prepared.original.canSaveApartFromSeries()
if (!prepared.isRecurring || (seriesOnly && prepared.canRealign)) {
write(prepared, RecurringWriteScope.AllEvents)
settle()
settle(request.token, write(prepared, RecurringWriteScope.AllEvents))
} else if (seriesOnly) {
_outcome.value = MoveOutcome.BlockedCancelledSeries
_abandoned.value += 1
settle()
settle(request.token, landed = false)
} else {
// Still busy: the scope dialog is now the thing in flight.
pending = prepared
@@ -272,7 +273,6 @@ class RescheduleViewModel @Inject constructor(
)
}
}
return true
}
/** Answer the scope dialog. */
@@ -283,53 +283,45 @@ class RescheduleViewModel @Inject constructor(
pending = null
_scopePrompt.value = null
viewModelScope.launch {
write(prepared, scope)
settle()
settle(prepared.request.token, write(prepared, scope))
}
}
/** Dismiss the scope dialog without writing. */
fun cancelScope() {
val prepared = pending ?: return
pending = null
_scopePrompt.value = null
_abandoned.value += 1
settle()
settle(prepared.request.token, landed = false)
}
/**
* Only a drop of a different event, and only before a scope dialog is up:
* a second drop of the same event carries the occurrence times from before
* the first write, and would compound with it.
*/
private fun canQueue(request: MoveRequest): Boolean =
queued == null && _scopePrompt.value == null && request.eventId != busyEventId
/** Free the pipeline, then run the drop that waited for it, if any. */
private fun settle() {
/** End the drop [token], then run the next queued one, if any. */
private fun settle(token: Long, landed: Boolean) {
_drops.update { it.ended(token, landed) }
busy = false
busyEventId = null
val next = queued ?: return
queued = null
move(next)
queue.removeFirstOrNull()?.let { run(it, waited = true) }
syncInFlight()
}
private fun syncInFlight() {
_inFlight.value = busy || queue.isNotEmpty()
}
/**
* Put a completed move back where it came from. The outcome stands until the
* inverse write reports back, so the one chip changes what it says rather
* than closing and reopening. False when another write is already running —
* the chip hides its action for that window, so this is the backstop.
*
* [abandoned] ticks once an inverse that *started* fails to land: [undoStarted]
* has sent the chip back on its journey by then and nothing else will seat it.
* A refusal ticks nothing — it launched no journey of its own, and the counter
* is global, so a tick here would release some other drop's held copy before
* the grid has drawn it.
* the chip hides its action for that window, so this is the backstop. An
* undo is a journey of its own: [undoStarted] names its token, and [drops]
* reports whether it landed.
*/
fun undo(undo: MoveUndo): Boolean {
if (busy) return false
if (busy || queue.isNotEmpty()) return false
val token = nextMoveToken()
_drops.update { it.started(token) }
busy = true
busyEventId = undo.eventId
_undoStarted.value += 1
syncInFlight()
_undoStarted.value = token
viewModelScope.launch {
_outcome.value = try {
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
@@ -343,10 +335,7 @@ class RescheduleViewModel @Inject constructor(
} catch (e: Exception) {
MoveOutcome.Failed
}
// Read off the outcome, the way [write] does — no second copy of the
// same fact to drift from it.
if (_outcome.value !is MoveOutcome.Undone) _abandoned.value += 1
settle()
settle(token, landed = _outcome.value is MoveOutcome.Undone)
}
return true
}
@@ -356,8 +345,13 @@ class RescheduleViewModel @Inject constructor(
_outcome.value = null
}
private suspend fun prepare(request: MoveRequest): PreparedMove? {
private suspend fun prepare(request: MoveRequest, waited: Boolean): PreparedMove? {
val detail = try {
// A drop that waited carries times from before the writes ahead of it.
if (waited && !occurrenceStillAt(request)) {
_outcome.value = MoveOutcome.Stale
return null
}
repository.eventDetail(request.eventId)
} catch (e: CancellationException) {
throw e
@@ -427,12 +421,12 @@ class RescheduleViewModel @Inject constructor(
)
}
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope) {
/** Write [prepared] in [scope]; true when it landed. */
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope): Boolean {
val request = prepared.request
if (endsBeforeItStarts(prepared, scope)) {
_outcome.value = MoveOutcome.BlockedSeriesEnd
_abandoned.value += 1
return
return false
}
_outcome.value = try {
when {
@@ -469,9 +463,16 @@ class RescheduleViewModel @Inject constructor(
} catch (e: Exception) {
MoveOutcome.Failed
}
// Nothing landed, so the copy the view is holding has nothing to fade
// into — let it go now rather than at the end of the settle timeout.
if (_outcome.value !is MoveOutcome.Moved) _abandoned.value += 1
return _outcome.value is MoveOutcome.Moved
}
/** Whether [request]'s occurrence still begins where it was picked up. */
private suspend fun occurrenceStillAt(request: MoveRequest): Boolean {
val begin = Instant.fromEpochMilliseconds(request.beginMillis)
val end = Instant.fromEpochMilliseconds(maxOf(request.endMillis, request.beginMillis + 1))
return repository.eventOccurrences(request.eventId, begin..end).any {
it.eventId == request.eventId && it.start == begin
}
}
/**
@@ -60,7 +60,6 @@ import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.atStartOfDayIn
@@ -611,14 +610,8 @@ class TimelineDragController {
var settlingSelected: Boolean = false
private set
/**
* The abandoned-move counter, read at the drop so the mark can't be a
* composition behind the tick it is compared against.
*/
var abandonedTicks: StateFlow<Int>? = null
/** What [abandonedTicks] stood at when the settling drop was let go. */
var settledAbandonedMark: Int = 0
/** The token of the drop [settling] waits on; a drop's caller hands it to its `MoveRequest`. */
var settledToken: Long = 0L
private set
private var source: TimedBlock? = null
@@ -661,8 +654,8 @@ class TimelineDragController {
var stripSeated: Boolean by mutableStateOf(false)
private set
/** What [abandonedTicks] stood at when [stripSettling] was let go. */
var stripAbandonedMark: Int = 0
/** The token of the drop [stripSettling] waits on. */
var stripToken: Long = 0L
private set
/** The shown day the finger picked the strip bar up on. */
@@ -756,7 +749,7 @@ class TimelineDragController {
if (held.overGrid || held.dayShift == 0) return null
stripSettling = held
stripSeated = false
stripAbandonedMark = abandonedTicks?.value ?: 0
stripToken = nextMoveToken()
drops++
return StripDrop.Days(held.event, held.dayShift)
}
@@ -873,7 +866,7 @@ class TimelineDragController {
settling = if (landed.edgeOnly || leavesGrid) landed.copy(pieces = emptyList()) else landed
liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = nextMoveToken()
settledEnd = end
drops++
}
@@ -1199,7 +1192,6 @@ fun rememberTimelineDragController(): TimelineDragController {
controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() }
controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() }
controller.slopPx = LocalViewConfiguration.current.touchSlop
controller.abandonedTicks = LocalEventMove.current?.abandoned
return controller
}
@@ -1313,7 +1305,9 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
val use24Hour = LocalUse24HourFormat.current
val locale = currentLocale()
val reduceMotion = rememberReduceMotion()
val moveInFlight = moveInFlight()
val drops = dropStates()
val moveInFlight = controller.settledToken in drops.pending
val stripInFlight = controller.stripToken in drops.pending
// Both live here rather than beside the controller: they read [drag], which
// changes every frame, and this composable is the one that is meant to.
@@ -1327,12 +1321,11 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// recurring drop's scope dialog is up — and then until the grid draws the
// drop itself.
var handingOver by remember(controller.settling) { mutableStateOf(false) }
val abandoned = abandonedMoves()
val abandoned = controller.settledToken in drops.abandoned
LaunchedEffect(controller.settling, moveInFlight, controller.settledOnGrid, abandoned) {
if (controller.settling == null || moveInFlight) return@LaunchedEffect
// Past the mark this drop was let go on, it was abandoned: nothing will
// land and there is nothing to wait for.
if (abandoned == controller.settledAbandonedMark) {
// An abandoned drop: nothing will land and there is nothing to wait for.
if (!abandoned) {
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
}
handingOver = true
@@ -1342,9 +1335,10 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
}
// The same hold for a bar moved along the all-day strip.
LaunchedEffect(controller.stripSettling, moveInFlight, controller.stripSeated, abandoned) {
if (controller.stripSettling == null || moveInFlight) return@LaunchedEffect
if (abandoned == controller.stripAbandonedMark) {
val stripAbandoned = controller.stripToken in drops.abandoned
LaunchedEffect(controller.stripSettling, stripInFlight, controller.stripSeated, stripAbandoned) {
if (controller.stripSettling == null || stripInFlight) return@LaunchedEffect
if (!stripAbandoned) {
delay(if (controller.stripSeated) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
}
controller.releaseStrip()
@@ -14,8 +14,7 @@ import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.IntSize
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import kotlinx.coroutines.flow.StateFlow
import de.jeanlucmakiola.calendula.ui.common.nextMoveToken
import kotlinx.datetime.LocalDate
import kotlin.math.abs
@@ -112,6 +111,8 @@ data class MonthChipDrop(
val event: EventInstance,
val grabDate: LocalDate,
val targetDate: LocalDate,
/** The drop's identity, which its held copy waits on — see [MonthDragController.settledToken]. */
val token: Long,
)
/**
@@ -172,14 +173,8 @@ class MonthDragController {
*/
private var undoable: MonthChipDrag? = null
/**
* The abandoned-move counter, read at the drop so the mark can't be a
* composition behind the tick it is compared against.
*/
var abandonedTicks: StateFlow<Int>? = null
/** What [abandonedTicks] stood at when the settling chip was let go. */
var settledAbandonedMark: Int = 0
/** The token of the drop (or undo) [settling] is waiting on. */
var settledToken: Long = 0L
private set
private var event: EventInstance? = null
@@ -265,7 +260,7 @@ class MonthDragController {
* there is no drop of this controller's left to undo, or the grid doesn't
* seat the moved event where the chip would have to start from.
*/
fun beginUndo(): Boolean {
fun beginUndo(token: Long): Boolean {
val last = undoable ?: return false
undoable = null
val from = last.targetDate ?: return false
@@ -274,7 +269,7 @@ class MonthDragController {
liftedInstanceId = last.event.instanceId
settledGhost = true
settledInRoot = null
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = token
return true
}
@@ -295,9 +290,9 @@ class MonthDragController {
liftedInstanceId = landed.event.instanceId
settledGhost = true
undoable = settling
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = nextMoveToken()
drops++
return MonthChipDrop(landed.event, landed.grabDate, target)
return MonthChipDrop(landed.event, landed.grabDate, target, settledToken)
}
/**
@@ -355,9 +350,7 @@ class MonthDragController {
@Composable
fun rememberMonthDragController(): MonthDragController {
val controller = remember { MonthDragController() }
controller.abandonedTicks = LocalEventMove.current?.abandoned
return controller
return remember { MonthDragController() }
}
val LocalMonthDrag = compositionLocalOf<MonthDragController?> { null }
@@ -125,8 +125,7 @@ import de.jeanlucmakiola.calendula.ui.common.eventTitleOverflow
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import de.jeanlucmakiola.calendula.ui.common.moveInFlight
import de.jeanlucmakiola.calendula.ui.common.abandonedMoves
import de.jeanlucmakiola.calendula.ui.common.dropStates
import de.jeanlucmakiola.calendula.ui.common.OnUndoStarted
import de.jeanlucmakiola.calendula.ui.common.ghostAlpha
import de.jeanlucmakiola.calendula.ui.common.DragSnapHaptics
@@ -515,7 +514,7 @@ fun MonthScreen(
val chipDrag = rememberMonthDragController()
// Undo moves the event back, so the chip travels back too. The
// signal comes from the write, not from the chip that offers it.
OnUndoStarted { chipDrag.beginUndo() }
OnUndoStarted { token -> chipDrag.beginUndo(token) }
Box(
modifier = Modifier
.padding(innerPadding)
@@ -595,7 +594,9 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
val density = LocalDensity.current
val timeFit = rememberMonthChipTimeFit(showStartTimes)
val reduceMotion = rememberReduceMotion()
val moveInFlight = moveInFlight()
val drops = dropStates()
val moveInFlight = controller.settledToken in drops.pending
val abandoned = controller.settledToken in drops.abandoned
// Here rather than beside the controller: this reads [drag], which changes
// every frame, and this composable is the one that is meant to.
DragSnapHaptics(controller.drag?.targetDate, controller.drops)
@@ -608,14 +609,12 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
val glide = remember { Animatable(Offset.Zero, Offset.VectorConverter) }
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
val seat = controller.settledInRoot
val abandoned = abandonedMoves()
LaunchedEffect(controller.settling, moveInFlight, seat, abandoned) {
val landed = controller.settling
if (landed == null || moveInFlight) return@LaunchedEffect
if (seat == null) {
// Past the mark this drop was let go on, it was abandoned and no
// seat is ever coming.
if (abandoned == controller.settledAbandonedMark) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
// An abandoned drop has no seat coming.
if (!abandoned) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
} else {
if (!gliding) glide.snapTo(landed.topLeftInRoot)
gliding = true
@@ -2691,6 +2690,7 @@ private fun monthChipDragModifier(
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
target = MoveTarget.ByDays(delta),
token = drop.token,
),
)
}
@@ -592,6 +592,7 @@ private fun WeekContent(
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
target = MoveTarget.Start(start),
token = dragController.settledToken,
),
)
}
@@ -611,6 +612,7 @@ private fun WeekContent(
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
target = MoveTarget.Span(drop.start, drop.end),
token = dragController.settledToken,
),
)
}
@@ -626,6 +628,11 @@ private fun WeekContent(
is StripDrop.Days -> MoveTarget.ByDays(drop.days)
is StripDrop.Timed -> MoveTarget.Span(drop.start, drop.end)
},
// A bar dropped into the grid settles as a timed copy, not on the strip.
token = when (drop) {
is StripDrop.Days -> dragController.stripToken
is StripDrop.Timed -> dragController.settledToken
},
),
)
}
+1
View File
@@ -110,6 +110,7 @@
<string name="event_move_failed">Couldn\'t move the event</string>
<string name="event_move_write_denied">Calendula needs write access to move events</string>
<string name="event_move_gone">That event no longer exists</string>
<string name="event_move_stale">That event moved before your drop could be saved</string>
<string name="event_move_blocked_series_end">Can\'t move an event past the end of its series</string>
<string name="event_move_blocked_cancelled_series">A cancelled series can only move as a whole, and this would change which days it falls on</string>
@@ -100,6 +100,8 @@ class RescheduleViewModelTest {
return RescheduleViewModel(repo, io, FakeZoneSource())
}
private val RescheduleViewModel.abandonedCount: Int get() = drops.value.abandoned.size
private fun CoroutineScope.activate(vm: RescheduleViewModel): Job =
launch { vm.movableCalendarIds.collect {} }
@@ -270,54 +272,103 @@ class RescheduleViewModelTest {
assertThat(vm.scopePrompt.value).isEqualTo(MoveScopePrompt(occurrenceOnly = true))
}
@Test
fun `a second drop is refused while the first is still in flight`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { detail(rrule = "FREQ=WEEKLY;BYDAY=MO") }
/** The occurrences [ids] still at the dragged start, as a waiting drop re-checks them. */
private fun FakeCalendarDataSource.occurrencesAt(vararg ids: Long) {
instancesResult = { _, _ ->
ids.map { id ->
testEvent(
id = id,
start = Instant.fromEpochMilliseconds(beginMillis),
end = Instant.fromEpochMilliseconds(endMillis),
)
}
}
val vm = viewModel(tempDir, fake)
assertThat(vm.move(toWednesday())).isTrue()
advanceUntilIdle()
// Parked on the scope dialog, so the first drop still owns the pipeline.
assertThat(vm.move(oneHourLater())).isFalse()
advanceUntilIdle()
assertThat(fake.updatedEvents).isEmpty()
}
@Test
fun `a drop of another event waits for the one in flight, then lands`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { detail() }
occurrencesAt(7L)
}
val vm = slowViewModel(tempDir, fake)
assertThat(vm.move(oneHourLater())).isTrue()
assertThat(vm.inFlight.value).isTrue()
val abandoned = vm.abandoned.value
assertThat(vm.move(toWednesday().copy(eventId = 7L))).isTrue()
val first = oneHourLater()
val second = toWednesday().copy(eventId = 7L)
assertThat(vm.move(first)).isTrue()
assertThat(vm.move(second)).isTrue()
assertThat(vm.drops.value.pending).containsExactly(first.token, second.token)
advanceUntilIdle()
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L, 7L).inOrder()
assertThat(vm.abandoned.value).isEqualTo(abandoned)
assertThat(vm.drops.value).isEqualTo(DropStates())
assertThat(vm.inFlight.value).isFalse()
}
@Test
fun `a second drop of the event in flight is still refused`(
fun `a failed drop lets go of its own copy only, not the one queued behind it`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { detail() }
occurrencesAt(7L)
}
val vm = slowViewModel(tempDir, fake)
// Zero distance: refused in prepare.
val nowhere = oneHourLater().copy(target = MoveTarget.Start(Instant.fromEpochMilliseconds(beginMillis)))
val queued = toWednesday().copy(eventId = 7L)
vm.move(nowhere)
vm.move(queued)
advanceUntilIdle()
assertThat(vm.drops.value.abandoned).containsExactly(nowhere.token)
assertThat(fake.updatedEvents.map { it.first }).containsExactly(7L)
}
@Test
fun `a waiting drop whose occurrence an earlier write moved is not written`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
// The first drop moved event 42, so nothing of it begins at the old start any more.
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
assertThat(vm.move(oneHourLater())).isTrue()
assertThat(vm.move(toWednesday())).isFalse()
val again = toWednesday()
vm.move(oneHourLater())
vm.move(again)
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(1)
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Stale)
assertThat(vm.drops.value.abandoned).containsExactly(again.token)
}
@Test
fun `a drop made while a scope dialog is up runs once it is answered`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { id -> if (id == 42L) detail(rrule = "FREQ=WEEKLY") else detail() }
occurrencesAt(7L)
}
val vm = viewModel(tempDir, fake)
vm.move(oneHourLater())
advanceUntilIdle()
val queued = toWednesday().copy(eventId = 7L)
assertThat(vm.move(queued)).isTrue()
advanceUntilIdle()
assertThat(fake.updatedEvents).isEmpty()
assertThat(vm.drops.value.pending).contains(queued.token)
vm.moveWithScope(RecurringWriteScope.AllEvents)
advanceUntilIdle()
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L, 7L).inOrder()
assertThat(vm.drops.value.pending).isEmpty()
}
@Test
@@ -333,14 +384,14 @@ class RescheduleViewModelTest {
vm.move(toWednesday())
advanceUntilIdle()
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
assertThat(vm.undo(undo)).isFalse()
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(1)
// Nothing ticks: the refusal started no journey of its own, and the
// counter is global — a tick here would release the copy the drop that
// *is* in flight is holding, before the grid has drawn it.
assertThat(vm.abandoned.value).isEqualTo(abandoned)
assertThat(vm.abandonedCount).isEqualTo(abandoned)
}
@Test
@@ -355,13 +406,13 @@ class RescheduleViewModelTest {
advanceUntilIdle()
val undo = (vm.outcome.value as MoveOutcome.Moved).undo!!
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
fake.writeError = SecurityException("permission revoked")
assertThat(vm.undo(undo)).isTrue()
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.WriteDenied)
assertThat(vm.abandoned.value).isEqualTo(abandoned + 1)
assertThat(vm.abandonedCount).isEqualTo(abandoned + 1)
}
@Test
@@ -374,12 +425,12 @@ class RescheduleViewModelTest {
advanceUntilIdle()
val undo = (vm.outcome.value as MoveOutcome.Moved).undo!!
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
vm.undo(undo)
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Undone)
assertThat(vm.abandoned.value).isEqualTo(abandoned)
assertThat(vm.abandonedCount).isEqualTo(abandoned)
}
@Test
@@ -603,14 +654,14 @@ class RescheduleViewModelTest {
),
)).isTrue()
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
// Refused by the provider, after the write was attempted.
fake.writeError = SecurityException("revoked")
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.WriteDenied)
assertThat(vm.abandoned.value).isEqualTo(2)
assertThat(vm.abandonedCount).isEqualTo(2)
}
@Test
@@ -624,11 +675,11 @@ class RescheduleViewModelTest {
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(0)
assertThat(vm.abandonedCount).isEqualTo(0)
vm.cancelScope()
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
}
@Test
@@ -640,7 +691,7 @@ class RescheduleViewModelTest {
advanceUntilIdle()
assertThat(vm.outcome.value).isInstanceOf(MoveOutcome.Moved::class.java)
assertThat(vm.abandoned.value).isEqualTo(0)
assertThat(vm.abandonedCount).isEqualTo(0)
}
@Test
@@ -753,7 +804,7 @@ class RescheduleViewModelTest {
assertThat(vm.scopePrompt.value).isNull()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.BlockedCancelledSeries)
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
assertThat(fake.updatedEvents).isEmpty()
assertThat(fake.updatedOccurrences).isEmpty()
}