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    crate::thread_state::with(|state| state.back_listeners.add(id, std::rc::Rc::new(listener)));
76    BackRequestObserver { id }
77}
78
79#[cfg(not(target_arch = "wasm32"))]
80fn back_listeners() -> &'static Mutex<Vec<(u64, BackListener)>> {
81    static LISTENERS: OnceLock<Mutex<Vec<(u64, BackListener)>>> = OnceLock::new();
82    LISTENERS.get_or_init(|| Mutex::new(Vec::new()))
83}
84
85#[cfg(not(target_arch = "wasm32"))]
86fn latest_back_listener() -> Option<BackListener> {
87    back_listeners()
88        .lock()
89        .ok()
90        .and_then(|listeners| listeners.last().map(|(_, listener)| Arc::clone(listener)))
91}
92
93#[cfg(target_arch = "wasm32")]
94fn latest_back_listener() -> Option<BackListener> {
95    crate::thread_state::with(|state| state.back_listeners.last())
96}
97
98/// A back observer installed by [`observe_back_requests`].
99pub struct BackRequestObserver {
100    id: u64,
101}
102
103impl Drop for BackRequestObserver {
104    fn drop(&mut self) {
105        #[cfg(not(target_arch = "wasm32"))]
106        if let Ok(mut listeners) = back_listeners().lock() {
107            listeners.retain(|(id, _)| *id != self.id);
108        }
109        #[cfg(target_arch = "wasm32")]
110        crate::thread_state::with(|state| state.back_listeners.remove(self.id));
111    }
112}
113
114/// Take (and clear) the number of pending back requests. Polled by the app; a
115/// burst collapses into a count the app can coalesce.
116pub fn take_back_requests() -> usize {
117    BACK_REQUESTS.swap(0, Ordering::SeqCst)
118}
119
120/// Declare whether the app currently wants the platform's back control routed
121/// to [`push_back_request`] instead of the platform default. Set it `true`
122/// while there is in-app navigation to pop and `false` when leaving the app is
123/// the right response (mirrors Compose's `BackHandler(enabled)`).
124pub fn set_back_interception(enabled: bool) {
125    BACK_INTERCEPTION.store(enabled, Ordering::SeqCst);
126}
127
128/// Whether the app asked to intercept the platform back control. Read by the
129/// platform input path.
130pub fn back_interception_enabled() -> bool {
131    BACK_INTERCEPTION.load(Ordering::SeqCst)
132}
133
134static ACTIVE_BACK_HANDLERS: AtomicUsize = AtomicUsize::new(0);
135
136/// Handles platform back requests on the UI thread while `enabled` is true.
137/// Nested handlers follow stack order: the innermost active handler receives
138/// the request and dropping it restores the handler beneath it.
139#[expect(non_snake_case)]
140#[track_caller]
141pub fn BackHandler(enabled: bool, mut on_back: impl FnMut() + 'static) {
142    let requests = cranpose_core::rememberEventStream(enabled, move |sender| {
143        if !enabled {
144            return None;
145        }
146        if ACTIVE_BACK_HANDLERS.fetch_add(1, Ordering::AcqRel) == 0 {
147            set_back_interception(true);
148        }
149        let registration = observe_back_requests(move || {
150            let count = take_back_requests();
151            if count > 0 {
152                sender.send(count);
153            }
154        });
155        Some(BackInterception {
156            _registration: registration,
157        })
158    });
159    if enabled {
160        cranpose_core::CollectEvents(requests, enabled, move |count: usize| {
161            for _ in 0..count {
162                on_back();
163            }
164        });
165    }
166}
167
168struct BackInterception {
169    _registration: BackRequestObserver,
170}
171
172impl Drop for BackInterception {
173    fn drop(&mut self) {
174        if ACTIVE_BACK_HANDLERS.fetch_sub(1, Ordering::AcqRel) == 1 {
175            set_back_interception(false);
176        }
177    }
178}
179
180/// Ask the platform to close the app.
181///
182/// The counterpart to [`set_back_interception`]`(false)`: interception says
183/// "let the platform's own back control take me out of here", and this says
184/// the same thing when the app is the one that decided. An app needs it
185/// whenever it owns the affordance that means "leave":
186///
187/// - a screen-level dismiss gesture the app draws itself. On Android a
188///   `NativeActivity` consumes every pointer event on the display, so the
189///   platform's window-level swipe never fires and the app's own gesture is
190///   the only one there is — completing it has to close the app, and there is
191///   no back key on a watch to fall back on.
192/// - a Quit item in the app's own menu.
193///
194/// It is a request, not a teardown: the platform decides when the frame loop
195/// stops, so it is safe to call from the middle of one — including from a
196/// gesture's settle animation, which is where the decision usually lands.
197///
198/// The backend drains it on its next turn of the loop, which is the following
199/// frame for the usual caller. An app that calls this from another thread while
200/// the loop is parked — nothing animating, no input — should wake it the same
201/// way it would for a back request; registering
202/// [`observe_back_requests`] is enough, because this nudges that listener
203/// too.
204///
205/// Platform behaviour, and where it does nothing:
206///
207/// - **Android**: finishes the activity, the same outcome as Compose's
208///   `backDispatcher.onBackPressed()` on a screen with no `BackHandler`.
209/// - **Desktop**: exits the event loop, closing the window.
210/// - **iOS**: nothing. Apple's guidelines forbid an app terminating itself and
211///   there is no supported API for it; the request is dropped rather than
212///   faked, so an app can call this unconditionally.
213/// - **Web**: nothing. A page cannot close a tab it did not open.
214pub fn request_exit() {
215    EXIT_REQUESTED.store(true, Ordering::SeqCst);
216    if let Some(listener) = latest_back_listener() {
217        listener();
218    }
219}
220
221/// Whether an exit request is outstanding, without consuming it.
222///
223/// For a backend whose way of closing can fail. Consuming the flag and then
224/// discovering the platform call did not land loses the app's only record that
225/// it wanted to close: the app stays open, the gesture the user made did
226/// nothing, and nothing will ever ask again. Such a backend tests with this and
227/// calls [`take_exit_request`] once the request has actually been honoured.
228///
229/// This is also the cheap read for a loop that runs it every turn — see
230/// [`take_exit_request`].
231pub fn exit_requested() -> bool {
232    EXIT_REQUESTED.load(Ordering::SeqCst)
233}
234
235/// Take (and clear) a pending exit request. Drained by the platform backend.
236///
237/// Read before written: this runs on every turn of the platform's loop, and a
238/// bare `swap` would dirty the cache line each time even with nothing to take.
239/// The load is the common case by a very long way — an app asks to close once,
240/// ever.
241pub fn take_exit_request() -> bool {
242    exit_requested() && EXIT_REQUESTED.swap(false, Ordering::SeqCst)
243}
244
245#[cfg(test)]
246#[path = "tests/navigation_tests.rs"]
247mod tests;