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
148static ACTIVE_BACK_HANDLERS: AtomicUsize = AtomicUsize::new(0);
149
150/// Handles platform back requests on the UI thread while `enabled` is true.
151/// Nested handlers follow stack order: the innermost active handler receives
152/// the request and dropping it restores the handler beneath it.
153#[expect(non_snake_case)]
154#[track_caller]
155pub fn BackHandler(enabled: bool, mut on_back: impl FnMut() + 'static) {
156 let requests = cranpose_core::rememberEventStream(enabled, move |sender| {
157 if !enabled {
158 return None;
159 }
160 if ACTIVE_BACK_HANDLERS.fetch_add(1, Ordering::AcqRel) == 0 {
161 set_back_interception(true);
162 }
163 let registration = observe_back_requests(move || {
164 let count = take_back_requests();
165 if count > 0 {
166 sender.send(count);
167 }
168 });
169 Some(BackInterception {
170 _registration: registration,
171 })
172 });
173 if enabled {
174 cranpose_core::CollectEvents(requests, enabled, move |count: usize| {
175 for _ in 0..count {
176 on_back();
177 }
178 });
179 }
180}
181
182struct BackInterception {
183 _registration: BackRequestObserver,
184}
185
186impl Drop for BackInterception {
187 fn drop(&mut self) {
188 if ACTIVE_BACK_HANDLERS.fetch_sub(1, Ordering::AcqRel) == 1 {
189 set_back_interception(false);
190 }
191 }
192}
193
194/// Ask the platform to close the app.
195///
196/// The counterpart to [`set_back_interception`]`(false)`: interception says
197/// "let the platform's own back control take me out of here", and this says
198/// the same thing when the app is the one that decided. An app needs it
199/// whenever it owns the affordance that means "leave":
200///
201/// - a screen-level dismiss gesture the app draws itself. On Android a
202/// `NativeActivity` consumes every pointer event on the display, so the
203/// platform's window-level swipe never fires and the app's own gesture is
204/// the only one there is — completing it has to close the app, and there is
205/// no back key on a watch to fall back on.
206/// - a Quit item in the app's own menu.
207///
208/// It is a request, not a teardown: the platform decides when the frame loop
209/// stops, so it is safe to call from the middle of one — including from a
210/// gesture's settle animation, which is where the decision usually lands.
211///
212/// The backend drains it on its next turn of the loop, which is the following
213/// frame for the usual caller. An app that calls this from another thread while
214/// the loop is parked — nothing animating, no input — should wake it the same
215/// way it would for a back request; registering
216/// [`observe_back_requests`] is enough, because this nudges that listener
217/// too.
218///
219/// Platform behaviour, and where it does nothing:
220///
221/// - **Android**: finishes the activity, the same outcome as Compose's
222/// `backDispatcher.onBackPressed()` on a screen with no `BackHandler`.
223/// - **Desktop**: exits the event loop, closing the window.
224/// - **iOS**: nothing. Apple's guidelines forbid an app terminating itself and
225/// there is no supported API for it; the request is dropped rather than
226/// faked, so an app can call this unconditionally.
227/// - **Web**: nothing. A page cannot close a tab it did not open.
228pub fn request_exit() {
229 EXIT_REQUESTED.store(true, Ordering::SeqCst);
230 if let Some(listener) = latest_back_listener() {
231 listener();
232 }
233}
234
235/// Whether an exit request is outstanding, without consuming it.
236///
237/// For a backend whose way of closing can fail. Consuming the flag and then
238/// discovering the platform call did not land loses the app's only record that
239/// it wanted to close: the app stays open, the gesture the user made did
240/// nothing, and nothing will ever ask again. Such a backend tests with this and
241/// calls [`take_exit_request`] once the request has actually been honoured.
242///
243/// This is also the cheap read for a loop that runs it every turn — see
244/// [`take_exit_request`].
245pub fn exit_requested() -> bool {
246 EXIT_REQUESTED.load(Ordering::SeqCst)
247}
248
249/// Take (and clear) a pending exit request. Drained by the platform backend.
250///
251/// Read before written: this runs on every turn of the platform's loop, and a
252/// bare `swap` would dirty the cache line each time even with nothing to take.
253/// The load is the common case by a very long way — an app asks to close once,
254/// ever.
255pub fn take_exit_request() -> bool {
256 exit_requested() && EXIT_REQUESTED.swap(false, Ordering::SeqCst)
257}
258
259#[cfg(test)]
260#[path = "tests/navigation_tests.rs"]
261mod tests;