Skip to main content

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.
17//! - **Desktop/web**: no OS back control; apps may map keys themselves and
18//!   call [`push_back_request`] directly.
19//!
20//! [`request_exit`] is the other direction: the app, rather than the platform,
21//! deciding that it is time to leave.
22
23use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
24#[cfg(not(target_arch = "wasm32"))]
25use std::sync::{Arc, Mutex, OnceLock};
26
27#[cfg(not(target_arch = "wasm32"))]
28type BackListener = Arc<dyn Fn() + Send + Sync + 'static>;
29#[cfg(target_arch = "wasm32")]
30type BackListener = std::rc::Rc<dyn Fn() + 'static>;
31
32static BACK_REQUESTS: AtomicUsize = AtomicUsize::new(0);
33static BACK_INTERCEPTION: AtomicBool = AtomicBool::new(false);
34static NEXT_LISTENER_ID: AtomicU64 = AtomicU64::new(1);
35static EXIT_REQUESTED: AtomicBool = AtomicBool::new(false);
36
37/// Record a system back request (called by the platform backend's gesture /
38/// button handler).
39pub fn push_back_request() {
40    BACK_REQUESTS.fetch_add(1, Ordering::SeqCst);
41    if let Some(listener) = latest_back_listener() {
42        listener();
43    }
44}
45
46/// Registers a callback run whenever a back request arrives, so an app can be
47/// told rather than having to ask.
48///
49/// [`take_back_requests`] alone is a polling API, which quietly assumes the app
50/// is already running a frame loop to poll from. An app that has gone idle —
51/// the correct thing to do on a screen where nothing moves — has no such loop,
52/// and a back gesture would sit in the counter until something unrelated woke
53/// it. The listener closes that gap: it is the nudge, the counter is still the
54/// source of truth, and the app drains it as before.
55///
56/// Called from whatever thread the platform reports back on, which is not
57/// necessarily the UI thread, so the callback must be `Send + Sync`. It should
58/// do as little as possible — waking a parked task is the intended use.
59///
60/// Registrations form a stack. The most recently installed observer receives
61/// requests, matching nested Compose `BackHandler`s. Dropping it restores the
62/// observer beneath it.
63#[cfg(not(target_arch = "wasm32"))]
64pub fn observe_back_requests(listener: impl Fn() + Send + Sync + 'static) -> BackRequestObserver {
65    let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
66    if let Ok(mut listeners) = back_listeners().lock() {
67        listeners.push((id, Arc::new(listener)));
68    }
69    BackRequestObserver { id }
70}
71
72#[cfg(target_arch = "wasm32")]
73pub fn observe_back_requests(listener: impl Fn() + 'static) -> BackRequestObserver {
74    let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
75    BACK_LISTENERS.with(|listeners| {
76        listeners
77            .borrow_mut()
78            .push((id, std::rc::Rc::new(listener)));
79    });
80    BackRequestObserver { id }
81}
82
83#[cfg(not(target_arch = "wasm32"))]
84fn back_listeners() -> &'static Mutex<Vec<(u64, BackListener)>> {
85    static LISTENERS: OnceLock<Mutex<Vec<(u64, BackListener)>>> = OnceLock::new();
86    LISTENERS.get_or_init(|| Mutex::new(Vec::new()))
87}
88
89#[cfg(target_arch = "wasm32")]
90thread_local! {
91    static BACK_LISTENERS: std::cell::RefCell<Vec<(u64, BackListener)>> = const { std::cell::RefCell::new(Vec::new()) };
92}
93
94#[cfg(not(target_arch = "wasm32"))]
95fn latest_back_listener() -> Option<BackListener> {
96    back_listeners()
97        .lock()
98        .ok()
99        .and_then(|listeners| listeners.last().map(|(_, listener)| Arc::clone(listener)))
100}
101
102#[cfg(target_arch = "wasm32")]
103fn latest_back_listener() -> Option<BackListener> {
104    BACK_LISTENERS.with(|listeners| {
105        listeners
106            .borrow()
107            .last()
108            .map(|(_, listener)| std::rc::Rc::clone(listener))
109    })
110}
111
112/// A back observer installed by [`observe_back_requests`].
113pub struct BackRequestObserver {
114    id: u64,
115}
116
117impl Drop for BackRequestObserver {
118    fn drop(&mut self) {
119        #[cfg(not(target_arch = "wasm32"))]
120        if let Ok(mut listeners) = back_listeners().lock() {
121            listeners.retain(|(id, _)| *id != self.id);
122        }
123        #[cfg(target_arch = "wasm32")]
124        BACK_LISTENERS.with(|listeners| listeners.borrow_mut().retain(|(id, _)| *id != self.id));
125    }
126}
127
128/// Take (and clear) the number of pending back requests. Polled by the app; a
129/// burst collapses into a count the app can coalesce.
130pub fn take_back_requests() -> usize {
131    BACK_REQUESTS.swap(0, Ordering::SeqCst)
132}
133
134/// Declare whether the app currently wants the platform's back control routed
135/// to [`push_back_request`] instead of the platform default. Set it `true`
136/// while there is in-app navigation to pop and `false` when leaving the app is
137/// the right response (mirrors Compose's `BackHandler(enabled)`).
138pub fn set_back_interception(enabled: bool) {
139    BACK_INTERCEPTION.store(enabled, Ordering::SeqCst);
140}
141
142/// Whether the app asked to intercept the platform back control. Read by the
143/// platform input path.
144pub fn back_interception_enabled() -> bool {
145    BACK_INTERCEPTION.load(Ordering::SeqCst)
146}
147
148/// Ask the platform to close the app.
149///
150/// The counterpart to [`set_back_interception`]`(false)`: interception says
151/// "let the platform's own back control take me out of here", and this says
152/// the same thing when the app is the one that decided. An app needs it
153/// whenever it owns the affordance that means "leave":
154///
155/// - a screen-level dismiss gesture the app draws itself. On Android a
156///   `NativeActivity` consumes every pointer event on the display, so the
157///   platform's window-level swipe never fires and the app's own gesture is
158///   the only one there is — completing it has to close the app, and there is
159///   no back key on a watch to fall back on.
160/// - a Quit item in the app's own menu.
161///
162/// It is a request, not a teardown: the platform decides when the frame loop
163/// stops, so it is safe to call from the middle of one — including from a
164/// gesture's settle animation, which is where the decision usually lands.
165///
166/// The backend drains it on its next turn of the loop, which is the following
167/// frame for the usual caller. An app that calls this from another thread while
168/// the loop is parked — nothing animating, no input — should wake it the same
169/// way it would for a back request; registering
170/// [`observe_back_requests`] is enough, because this nudges that listener
171/// too.
172///
173/// Platform behaviour, and where it does nothing:
174///
175/// - **Android**: finishes the activity, the same outcome as Compose's
176///   `backDispatcher.onBackPressed()` on a screen with no `BackHandler`.
177/// - **Desktop**: exits the event loop, closing the window.
178/// - **iOS**: nothing. Apple's guidelines forbid an app terminating itself and
179///   there is no supported API for it; the request is dropped rather than
180///   faked, so an app can call this unconditionally.
181/// - **Web**: nothing. A page cannot close a tab it did not open.
182pub fn request_exit() {
183    EXIT_REQUESTED.store(true, Ordering::SeqCst);
184    if let Some(listener) = latest_back_listener() {
185        listener();
186    }
187}
188
189/// Whether an exit request is outstanding, without consuming it.
190///
191/// For a backend whose way of closing can fail. Consuming the flag and then
192/// discovering the platform call did not land loses the app's only record that
193/// it wanted to close: the app stays open, the gesture the user made did
194/// nothing, and nothing will ever ask again. Such a backend tests with this and
195/// calls [`take_exit_request`] once the request has actually been honoured.
196///
197/// This is also the cheap read for a loop that runs it every turn — see
198/// [`take_exit_request`].
199pub fn exit_requested() -> bool {
200    EXIT_REQUESTED.load(Ordering::SeqCst)
201}
202
203/// Take (and clear) a pending exit request. Drained by the platform backend.
204///
205/// Read before written: this runs on every turn of the platform's loop, and a
206/// bare `swap` would dirty the cache line each time even with nothing to take.
207/// The load is the common case by a very long way — an app asks to close once,
208/// ever.
209pub fn take_exit_request() -> bool {
210    exit_requested() && EXIT_REQUESTED.swap(false, Ordering::SeqCst)
211}
212
213#[cfg(test)]
214#[path = "tests/navigation_tests.rs"]
215mod tests;