repose_core/back.rs
1//! Predictive-back gesture state.
2//!
3//! Android 14 and later report the back gesture before it commits. The Android
4//! runner stores that progress here so a view can move with the finger:
5//!
6//! ```ignore
7//! let offset = repose_core::back::progress() * 120.0;
8//! ```
9//!
10//! [`progress`] is `0.0` unless a gesture is in progress, so it is safe to
11//! multiply on every platform. A cancelled gesture settles back to `0.0` over a
12//! short animation, the way the platform does. A committed one keeps easing to
13//! `1.0` for a moment, so the screen finishes leaving before the back dispatch
14//! pops it: Android commits around a tenth of the drag, and cutting the screen
15//! out at that point is what makes a predictive transition look like two
16//! animations.
17
18use std::sync::Mutex;
19use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
20
21/// The current predictive-back gesture.
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct BackGesture {
24 /// Whether the user is currently dragging the back gesture.
25 pub active: bool,
26 /// How far the gesture has travelled, `0.0` at the edge. Android commits a
27 /// back gesture after a fraction of that travel, so a view should finish its
28 /// transition at `1.0` rather than at the release point.
29 pub progress: f32,
30 /// The screen edge the gesture started from.
31 pub edge: SwipeEdge,
32}
33
34/// The edge a back gesture started from.
35///
36/// The platform reports it so a view can move with the finger instead of
37/// guessing a direction: a left-edge gesture travels right, a right-edge one
38/// travels left.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum SwipeEdge {
41 #[default]
42 Left,
43 Right,
44}
45
46static ACTIVE: AtomicBool = AtomicBool::new(false);
47static EDGE_RIGHT: AtomicBool = AtomicBool::new(false);
48static PROGRESS_BITS: AtomicU32 = AtomicU32::new(0);
49static SETTLE_BITS: AtomicU32 = AtomicU32::new(0);
50static SETTLE_START: Mutex<Option<web_time::Instant>> = Mutex::new(None);
51static COMMIT_BITS: AtomicU32 = AtomicU32::new(0);
52static COMMIT_START: Mutex<Option<web_time::Instant>> = Mutex::new(None);
53static COMMITTED: AtomicBool = AtomicBool::new(false);
54
55/// How long one full predictive transition takes. Compose derives this from the
56/// transition's spring; both the cancel and the commit scale it by the fraction
57/// they have to cover.
58const TRANSITION_MS: f32 = 200.0;
59
60/// The current gesture, with `progress` already settled when it is inactive.
61pub fn gesture() -> BackGesture {
62 BackGesture {
63 active: active(),
64 progress: progress(),
65 edge: edge(),
66 }
67}
68
69/// Whether a predictive-back gesture is in progress.
70pub fn active() -> bool {
71 ACTIVE.load(Ordering::Relaxed)
72}
73
74/// The edge the last back gesture started from.
75///
76/// Kept after the finger lifts so a settling view keeps moving the way the
77/// gesture did. Platforms without an edge keep the default.
78pub fn edge() -> SwipeEdge {
79 if EDGE_RIGHT.load(Ordering::Relaxed) {
80 SwipeEdge::Right
81 } else {
82 SwipeEdge::Left
83 }
84}
85
86/// Record the edge a gesture started from.
87pub fn set_edge(edge: SwipeEdge) {
88 let right = edge == SwipeEdge::Right;
89 if EDGE_RIGHT.swap(right, Ordering::Relaxed) != right {
90 crate::request_frame();
91 }
92}
93
94/// The gesture's progress, `0.0` at the start and `1.0` fully committed.
95///
96/// Returns the settling value for a moment after a cancelled gesture, so a view
97/// that follows it never jumps back to rest, and keeps easing to `1.0` for a
98/// moment after a commit, so the screen finishes leaving before the pop lands.
99pub fn progress() -> f32 {
100 if active() {
101 return f32::from_bits(PROGRESS_BITS.load(Ordering::Relaxed));
102 }
103 if let Some(progress) = commit_progress() {
104 return progress;
105 }
106 settling_progress()
107}
108
109fn commit_progress() -> Option<f32> {
110 let phase = commit_phase()?;
111 let from = f32::from_bits(COMMIT_BITS.load(Ordering::Relaxed));
112 Some(from + (1.0 - from) * phase)
113}
114
115/// How far the remaining exit of a committed gesture has run, `0.0` at the
116/// commit and `1.0` when the screen has finished leaving.
117///
118/// The commit covers only the part of the transition the drag did not, so a deep
119/// drag lands almost at once, the way a Compose seek finishes.
120pub fn commit_phase() -> Option<f32> {
121 let start = (*COMMIT_START.lock().unwrap_or_else(|e| e.into_inner()))?;
122 let from = f32::from_bits(COMMIT_BITS.load(Ordering::Relaxed));
123 let span = TRANSITION_MS * (1.0 - from);
124 if span <= 0.0 {
125 return Some(1.0);
126 }
127 let t = ((crate::animation::now() - start).as_secs_f32() * 1000.0 / span).clamp(0.0, 1.0);
128 if t < 1.0 {
129 crate::request_frame();
130 }
131 Some(t)
132}
133
134fn settling_progress() -> f32 {
135 let mut start = SETTLE_START.lock().unwrap_or_else(|e| e.into_inner());
136 let Some(at) = *start else {
137 return 0.0;
138 };
139 let from = f32::from_bits(SETTLE_BITS.load(Ordering::Relaxed));
140 // Reversing a gesture takes as long as the part of the transition it already
141 // played, which is how a Compose cancel is timed.
142 let span = TRANSITION_MS * from;
143 if span <= 0.0 {
144 *start = None;
145 SETTLE_BITS.store(0, Ordering::Relaxed);
146 return 0.0;
147 }
148 let t = (crate::animation::now() - at).as_secs_f32() * 1000.0 / span;
149 if t >= 1.0 {
150 *start = None;
151 SETTLE_BITS.store(0, Ordering::Relaxed);
152 return 0.0;
153 }
154 crate::request_frame();
155 from * (1.0 - t)
156}
157
158/// Update the gesture state and request a frame.
159///
160/// Platform runners call this on the UI thread as gesture events arrive. Passing
161/// `false` resets at once; use [`cancel`] to let a released gesture settle, or
162/// [`commit`] to let it finish leaving.
163pub fn set_gesture(active: bool, progress: f32) {
164 let progress = if active && progress.is_finite() {
165 progress.clamp(0.0, 1.0)
166 } else {
167 0.0
168 };
169 let was_active = ACTIVE.swap(active, Ordering::Relaxed);
170 let old_progress = PROGRESS_BITS.swap(progress.to_bits(), Ordering::Relaxed);
171 SETTLE_START
172 .lock()
173 .unwrap_or_else(|e| e.into_inner())
174 .take();
175 SETTLE_BITS.store(0, Ordering::Relaxed);
176 COMMIT_START
177 .lock()
178 .unwrap_or_else(|e| e.into_inner())
179 .take();
180 if was_active != active || old_progress != progress.to_bits() {
181 crate::request_frame();
182 }
183}
184
185/// Abandon the gesture, easing back to rest from where the finger left it.
186///
187/// The committed case goes through [`commit`] instead: the screen finishes
188/// leaving before the back dispatch pops it. A cancel that arrives after the
189/// commit is authoritative cannot pull the finished exit back to rest.
190pub fn cancel() {
191 if committing() {
192 return;
193 }
194 let from = progress();
195 ACTIVE.store(false, Ordering::Relaxed);
196 PROGRESS_BITS.store(0, Ordering::Relaxed);
197 SETTLE_BITS.store(from.to_bits(), Ordering::Relaxed);
198 *SETTLE_START.lock().unwrap_or_else(|e| e.into_inner()) = Some(crate::animation::now());
199 COMMIT_START
200 .lock()
201 .unwrap_or_else(|e| e.into_inner())
202 .take();
203 crate::request_frame();
204}
205
206/// Finish a gesture that committed.
207///
208/// The progress runs to `1.0` over the remaining fraction of the transition
209/// while the runner holds the back dispatch: Android commits at roughly a third
210/// of the drag, so dispatching at once would cut the screen out mid-transition.
211/// [`commit_settled`] reports when the screen has finished leaving.
212pub fn commit() {
213 let from = progress();
214 ACTIVE.store(false, Ordering::Relaxed);
215 PROGRESS_BITS.store(0, Ordering::Relaxed);
216 SETTLE_START
217 .lock()
218 .unwrap_or_else(|e| e.into_inner())
219 .take();
220 SETTLE_BITS.store(0, Ordering::Relaxed);
221 COMMIT_BITS.store(from.to_bits(), Ordering::Relaxed);
222 *COMMIT_START.lock().unwrap_or_else(|e| e.into_inner()) = Some(crate::animation::now());
223 crate::request_frame();
224}
225
226/// Whether a committed gesture has finished leaving.
227pub fn commit_settled() -> bool {
228 commit_phase().is_some_and(|phase| phase >= 1.0)
229}
230
231/// Whether a committed gesture is still finishing its exit.
232///
233/// A view uses this to tell a commit from a cancel while both are inactive:
234/// the commit is the one that plays the arriving screen in.
235pub fn committing() -> bool {
236 commit_phase().is_some_and(|phase| phase < 1.0)
237}
238
239/// Note that the gesture that just ended committed.
240///
241/// A navigation display consumes this with [`take_committed`] while popping the
242/// entry the gesture dragged away: the gesture already played the whole
243/// transition, so the pop must not animate the destination in a second time.
244pub fn mark_committed() {
245 COMMITTED.store(true, Ordering::Relaxed);
246}
247
248/// Take the [`mark_committed`] flag, leaving it clear.
249pub fn take_committed() -> bool {
250 COMMITTED.swap(false, Ordering::Relaxed)
251}