cranpose_services/navigation.rs
1//! System "back" navigation requests.
2//!
3//! A platform back affordance — Android's back key / gesture, iOS's left-edge
4//! swipe — feeds [`push_back_request`]; the app drains it with
5//! [`take_back_requests`] and pops its own navigation. This gives one API
6//! across platforms for what is otherwise a per-OS gesture.
7//!
8//! Whether the platform *routes* its back control here is governed by
9//! [`set_back_interception`], the analogue of Compose's `BackHandler(enabled)`:
10//!
11//! - **Android**: while interception is enabled the back key/gesture is
12//! consumed and lands in [`push_back_request`]; while disabled it stays with
13//! the system, so the default behavior (leaving the activity) keeps working.
14//! Apps enable it exactly while they have somewhere to navigate back to.
15//! - **iOS**: the left-edge swipe is a framework-drawn gesture with no system
16//! fallback, so it always pushes a request regardless of interception. It
17//! goes back when let go past 30% of the width or on a flick.
18//!
19//! While a gesture moves, Android's predictive back (API 34+) and the iOS
20//! edge swipe also report its steps through [`push_back_gesture`], which a
21//! [`PredictiveBackHandler`] follows.
22//! - **Desktop/web**: no OS back control; apps may map keys themselves and
23//! call [`push_back_request`] directly.
24//!
25//! [`request_exit`] is the other direction: the app, rather than the platform,
26//! deciding that it is time to leave.
27
28use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
29#[cfg(not(target_arch = "wasm32"))]
30use std::sync::{Arc, Mutex, OnceLock};
31
32#[cfg(not(target_arch = "wasm32"))]
33type BackListener = Arc<dyn Fn(BackSignal) + Send + Sync + 'static>;
34#[cfg(target_arch = "wasm32")]
35type BackListener = std::rc::Rc<dyn Fn(BackSignal) + 'static>;
36
37/// The edge an interactive back gesture starts from.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum BackEdge {
40 Left,
41 Right,
42}
43
44/// Where an interactive back gesture is: Compose's `BackEventCompat`.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct BackEvent {
47 /// How far the gesture went, from 0 to 1.
48 pub progress: f32,
49 /// The edge it started from.
50 pub edge: BackEdge,
51}
52
53/// A step of an interactive back gesture: Android's predictive back, the
54/// iOS edge swipe. When the user lets go past the point of going back, the
55/// gesture ends with a back request instead of a step.
56#[derive(Clone, Copy, Debug, PartialEq)]
57pub enum BackGesture {
58 Started(BackEvent),
59 Progressed(BackEvent),
60 /// The user let go without going back.
61 Cancelled,
62}
63
64/// What reaches the innermost back observer.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub(crate) enum BackSignal {
67 Request,
68 Gesture(BackGesture),
69}
70
71static BACK_REQUESTS: AtomicUsize = AtomicUsize::new(0);
72static BACK_INTERCEPTION: AtomicBool = AtomicBool::new(false);
73static NEXT_LISTENER_ID: AtomicU64 = AtomicU64::new(1);
74static EXIT_REQUESTED: AtomicBool = AtomicBool::new(false);
75
76/// Record a system back request (called by the platform backend's gesture /
77/// button handler).
78pub fn push_back_request() {
79 BACK_REQUESTS.fetch_add(1, Ordering::SeqCst);
80 if let Some(listener) = latest_back_listener() {
81 listener(BackSignal::Request);
82 }
83}
84
85/// Record a step of an interactive back gesture (called by the platform
86/// backend). The innermost [`PredictiveBackHandler`] receives it; a
87/// [`BackHandler`] there ignores it.
88pub fn push_back_gesture(gesture: BackGesture) {
89 if let Some(listener) = latest_back_listener() {
90 listener(BackSignal::Gesture(gesture));
91 }
92}
93
94/// Registers a callback run whenever a back request arrives, so an app can be
95/// told rather than having to ask.
96///
97/// [`take_back_requests`] alone is a polling API, which quietly assumes the app
98/// is already running a frame loop to poll from. An app that has gone idle —
99/// the correct thing to do on a screen where nothing moves — has no such loop,
100/// and a back gesture would sit in the counter until something unrelated woke
101/// it. The listener closes that gap: it is the nudge, the counter is still the
102/// source of truth, and the app drains it as before.
103///
104/// Called from whatever thread the platform reports back on, which is not
105/// necessarily the UI thread, so the callback must be `Send + Sync`. It should
106/// do as little as possible — waking a parked task is the intended use.
107///
108/// Registrations form a stack. The most recently installed observer receives
109/// requests, matching nested Compose `BackHandler`s. Dropping it restores the
110/// observer beneath it.
111#[cfg(not(target_arch = "wasm32"))]
112pub fn observe_back_requests(listener: impl Fn() + Send + Sync + 'static) -> BackRequestObserver {
113 observe_back_signals(move |signal| {
114 if signal == BackSignal::Request {
115 listener();
116 }
117 })
118}
119
120#[cfg(target_arch = "wasm32")]
121pub fn observe_back_requests(listener: impl Fn() + 'static) -> BackRequestObserver {
122 observe_back_signals(move |signal| {
123 if signal == BackSignal::Request {
124 listener();
125 }
126 })
127}
128
129#[cfg(not(target_arch = "wasm32"))]
130fn observe_back_signals(
131 listener: impl Fn(BackSignal) + Send + Sync + 'static,
132) -> BackRequestObserver {
133 let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
134 if let Ok(mut listeners) = back_listeners().lock() {
135 listeners.push((id, Arc::new(listener)));
136 }
137 BackRequestObserver { id }
138}
139
140#[cfg(target_arch = "wasm32")]
141fn observe_back_signals(listener: impl Fn(BackSignal) + 'static) -> BackRequestObserver {
142 let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
143 crate::thread_state::with(|state| state.back_listeners.add(id, std::rc::Rc::new(listener)));
144 BackRequestObserver { id }
145}
146
147#[cfg(not(target_arch = "wasm32"))]
148fn back_listeners() -> &'static Mutex<Vec<(u64, BackListener)>> {
149 static LISTENERS: OnceLock<Mutex<Vec<(u64, BackListener)>>> = OnceLock::new();
150 LISTENERS.get_or_init(|| Mutex::new(Vec::new()))
151}
152
153#[cfg(not(target_arch = "wasm32"))]
154fn latest_back_listener() -> Option<BackListener> {
155 back_listeners()
156 .lock()
157 .ok()
158 .and_then(|listeners| listeners.last().map(|(_, listener)| Arc::clone(listener)))
159}
160
161#[cfg(target_arch = "wasm32")]
162fn latest_back_listener() -> Option<BackListener> {
163 crate::thread_state::with(|state| state.back_listeners.last())
164}
165
166/// A back observer installed by [`observe_back_requests`].
167pub struct BackRequestObserver {
168 id: u64,
169}
170
171impl Drop for BackRequestObserver {
172 fn drop(&mut self) {
173 #[cfg(not(target_arch = "wasm32"))]
174 if let Ok(mut listeners) = back_listeners().lock() {
175 listeners.retain(|(id, _)| *id != self.id);
176 }
177 #[cfg(target_arch = "wasm32")]
178 crate::thread_state::with(|state| state.back_listeners.remove(self.id));
179 }
180}
181
182/// Take (and clear) the number of pending back requests. Polled by the app; a
183/// burst collapses into a count the app can coalesce.
184pub fn take_back_requests() -> usize {
185 BACK_REQUESTS.swap(0, Ordering::SeqCst)
186}
187
188/// Declare whether the app currently wants the platform's back control routed
189/// to [`push_back_request`] instead of the platform default. Set it `true`
190/// while there is in-app navigation to pop and `false` when leaving the app is
191/// the right response (mirrors Compose's `BackHandler(enabled)`).
192pub fn set_back_interception(enabled: bool) {
193 BACK_INTERCEPTION.store(enabled, Ordering::SeqCst);
194}
195
196/// Whether the app asked to intercept the platform back control. Read by the
197/// platform input path.
198pub fn back_interception_enabled() -> bool {
199 BACK_INTERCEPTION.load(Ordering::SeqCst)
200}
201
202static ACTIVE_BACK_HANDLERS: AtomicUsize = AtomicUsize::new(0);
203
204/// Handles platform back requests on the UI thread while `enabled` is true.
205/// Nested handlers follow stack order: the innermost active handler receives
206/// the request and dropping it restores the handler beneath it.
207#[expect(non_snake_case)]
208#[track_caller]
209pub fn BackHandler(enabled: bool, on_back: impl FnMut() + 'static) {
210 PredictiveBackHandler(enabled, |_| {}, on_back);
211}
212
213/// [`BackHandler`] that also follows an interactive back gesture while it
214/// moves: Compose's `PredictiveBackHandler`. `on_gesture` receives each step;
215/// a gesture that goes back ends in `on_back`, one that does not ends in
216/// [`BackGesture::Cancelled`].
217#[expect(non_snake_case)]
218#[track_caller]
219pub fn PredictiveBackHandler(
220 enabled: bool,
221 mut on_gesture: impl FnMut(BackGesture) + 'static,
222 mut on_back: impl FnMut() + 'static,
223) {
224 let events = cranpose_core::rememberEventStream(enabled, move |sender| {
225 if !enabled {
226 return None;
227 }
228 if ACTIVE_BACK_HANDLERS.fetch_add(1, Ordering::AcqRel) == 0 {
229 set_back_interception(true);
230 }
231 let registration = observe_back_signals(move |signal| match signal {
232 BackSignal::Request => {
233 let count = take_back_requests();
234 if count > 0 {
235 sender.send(BackDelivery::Requests(count));
236 }
237 }
238 BackSignal::Gesture(gesture) => sender.send(BackDelivery::Gesture(gesture)),
239 });
240 Some(BackInterception {
241 _registration: registration,
242 })
243 });
244 if enabled {
245 cranpose_core::CollectEvents(
246 events,
247 enabled,
248 move |delivery: BackDelivery| match delivery {
249 BackDelivery::Requests(count) => {
250 for _ in 0..count {
251 on_back();
252 }
253 }
254 BackDelivery::Gesture(gesture) => on_gesture(gesture),
255 },
256 );
257 }
258}
259
260/// What a back handler's event stream carries to the UI thread.
261#[derive(Clone, Copy)]
262enum BackDelivery {
263 Requests(usize),
264 Gesture(BackGesture),
265}
266
267struct BackInterception {
268 _registration: BackRequestObserver,
269}
270
271impl Drop for BackInterception {
272 fn drop(&mut self) {
273 if ACTIVE_BACK_HANDLERS.fetch_sub(1, Ordering::AcqRel) == 1 {
274 set_back_interception(false);
275 }
276 }
277}
278
279/// Ask the platform to close the app.
280///
281/// The counterpart to [`set_back_interception`]`(false)`: interception says
282/// "let the platform's own back control take me out of here", and this says
283/// the same thing when the app is the one that decided. An app needs it
284/// whenever it owns the affordance that means "leave":
285///
286/// - a screen-level dismiss gesture the app draws itself. On Android a
287/// `NativeActivity` consumes every pointer event on the display, so the
288/// platform's window-level swipe never fires and the app's own gesture is
289/// the only one there is — completing it has to close the app, and there is
290/// no back key on a watch to fall back on.
291/// - a Quit item in the app's own menu.
292///
293/// It is a request, not a teardown: the platform decides when the frame loop
294/// stops, so it is safe to call from the middle of one — including from a
295/// gesture's settle animation, which is where the decision usually lands.
296///
297/// The backend drains it on its next turn of the loop, which is the following
298/// frame for the usual caller. An app that calls this from another thread while
299/// the loop is parked — nothing animating, no input — should wake it the same
300/// way it would for a back request; registering
301/// [`observe_back_requests`] is enough, because this nudges that listener
302/// too.
303///
304/// Platform behaviour, and where it does nothing:
305///
306/// - **Android**: finishes the activity, the same outcome as Compose's
307/// `backDispatcher.onBackPressed()` on a screen with no `BackHandler`.
308/// - **Desktop**: exits the event loop, closing the window.
309/// - **iOS**: nothing. Apple's guidelines forbid an app terminating itself and
310/// there is no supported API for it; the request is dropped rather than
311/// faked, so an app can call this unconditionally.
312/// - **Web**: nothing. A page cannot close a tab it did not open.
313pub fn request_exit() {
314 EXIT_REQUESTED.store(true, Ordering::SeqCst);
315 if let Some(listener) = latest_back_listener() {
316 listener(BackSignal::Request);
317 }
318}
319
320/// Whether an exit request is outstanding, without consuming it.
321///
322/// For a backend whose way of closing can fail. Consuming the flag and then
323/// discovering the platform call did not land loses the app's only record that
324/// it wanted to close: the app stays open, the gesture the user made did
325/// nothing, and nothing will ever ask again. Such a backend tests with this and
326/// calls [`take_exit_request`] once the request has actually been honoured.
327///
328/// This is also the cheap read for a loop that runs it every turn — see
329/// [`take_exit_request`].
330pub fn exit_requested() -> bool {
331 EXIT_REQUESTED.load(Ordering::SeqCst)
332}
333
334/// Take (and clear) a pending exit request. Drained by the platform backend.
335///
336/// Read before written: this runs on every turn of the platform's loop, and a
337/// bare `swap` would dirty the cache line each time even with nothing to take.
338/// The load is the common case by a very long way — an app asks to close once,
339/// ever.
340pub fn take_exit_request() -> bool {
341 exit_requested() && EXIT_REQUESTED.swap(false, Ordering::SeqCst)
342}
343
344#[cfg(test)]
345#[path = "tests/navigation_tests.rs"]
346mod tests;