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);
35/// A flag rather than a count: closing twice is closing once.
36static EXIT_REQUESTED: AtomicBool = AtomicBool::new(false);
37
38/// Record a system back request (called by the platform backend's gesture /
39/// button handler).
40pub fn push_back_request() {
41 BACK_REQUESTS.fetch_add(1, Ordering::SeqCst);
42 if let Some(listener) = latest_back_listener() {
43 listener();
44 }
45}
46
47/// Registers a callback run whenever a back request arrives, so an app can be
48/// told rather than having to ask.
49///
50/// [`take_back_requests`] alone is a polling API, which quietly assumes the app
51/// is already running a frame loop to poll from. An app that has gone idle —
52/// the correct thing to do on a screen where nothing moves — has no such loop,
53/// and a back gesture would sit in the counter until something unrelated woke
54/// it. The listener closes that gap: it is the nudge, the counter is still the
55/// source of truth, and the app drains it as before.
56///
57/// Called from whatever thread the platform reports back on, which is not
58/// necessarily the UI thread, so the callback must be `Send + Sync`. It should
59/// do as little as possible — waking a parked task is the intended use.
60///
61/// Registrations form a stack. The most recently installed observer receives
62/// requests, matching nested Compose `BackHandler`s. Dropping it restores the
63/// observer beneath it.
64#[cfg(not(target_arch = "wasm32"))]
65pub fn observe_back_requests(listener: impl Fn() + Send + Sync + 'static) -> BackRequestObserver {
66 let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
67 if let Ok(mut listeners) = back_listeners().lock() {
68 listeners.push((id, Arc::new(listener)));
69 }
70 BackRequestObserver { id }
71}
72
73#[cfg(target_arch = "wasm32")]
74pub fn observe_back_requests(listener: impl Fn() + 'static) -> BackRequestObserver {
75 let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::Relaxed);
76 BACK_LISTENERS.with(|listeners| {
77 listeners
78 .borrow_mut()
79 .push((id, std::rc::Rc::new(listener)))
80 });
81 BackRequestObserver { id }
82}
83
84#[cfg(not(target_arch = "wasm32"))]
85fn back_listeners() -> &'static Mutex<Vec<(u64, BackListener)>> {
86 static LISTENERS: OnceLock<Mutex<Vec<(u64, BackListener)>>> = OnceLock::new();
87 LISTENERS.get_or_init(|| Mutex::new(Vec::new()))
88}
89
90#[cfg(target_arch = "wasm32")]
91thread_local! {
92 static BACK_LISTENERS: std::cell::RefCell<Vec<(u64, BackListener)>> = const { std::cell::RefCell::new(Vec::new()) };
93}
94
95#[cfg(not(target_arch = "wasm32"))]
96fn latest_back_listener() -> Option<BackListener> {
97 back_listeners()
98 .lock()
99 .ok()
100 .and_then(|listeners| listeners.last().map(|(_, listener)| Arc::clone(listener)))
101}
102
103#[cfg(target_arch = "wasm32")]
104fn latest_back_listener() -> Option<BackListener> {
105 BACK_LISTENERS.with(|listeners| {
106 listeners
107 .borrow()
108 .last()
109 .map(|(_, listener)| std::rc::Rc::clone(listener))
110 })
111}
112
113/// A back observer installed by [`observe_back_requests`].
114pub struct BackRequestObserver {
115 id: u64,
116}
117
118impl Drop for BackRequestObserver {
119 fn drop(&mut self) {
120 #[cfg(not(target_arch = "wasm32"))]
121 if let Ok(mut listeners) = back_listeners().lock() {
122 listeners.retain(|(id, _)| *id != self.id);
123 }
124 #[cfg(target_arch = "wasm32")]
125 BACK_LISTENERS.with(|listeners| listeners.borrow_mut().retain(|(id, _)| *id != self.id));
126 }
127}
128
129/// Take (and clear) the number of pending back requests. Polled by the app; a
130/// burst collapses into a count the app can coalesce.
131pub fn take_back_requests() -> usize {
132 BACK_REQUESTS.swap(0, Ordering::SeqCst)
133}
134
135/// Declare whether the app currently wants the platform's back control routed
136/// to [`push_back_request`] instead of the platform default. Set it `true`
137/// while there is in-app navigation to pop and `false` when leaving the app is
138/// the right response (mirrors Compose's `BackHandler(enabled)`).
139pub fn set_back_interception(enabled: bool) {
140 BACK_INTERCEPTION.store(enabled, Ordering::SeqCst);
141}
142
143/// Whether the app asked to intercept the platform back control. Read by the
144/// platform input path.
145pub fn back_interception_enabled() -> bool {
146 BACK_INTERCEPTION.load(Ordering::SeqCst)
147}
148
149/// Ask the platform to close the app.
150///
151/// The counterpart to [`set_back_interception`]`(false)`: interception says
152/// "let the platform's own back control take me out of here", and this says
153/// the same thing when the app is the one that decided. An app needs it
154/// whenever it owns the affordance that means "leave":
155///
156/// - a screen-level dismiss gesture the app draws itself. On Android a
157/// `NativeActivity` consumes every pointer event on the display, so the
158/// platform's window-level swipe never fires and the app's own gesture is
159/// the only one there is — completing it has to close the app, and there is
160/// no back key on a watch to fall back on.
161/// - a Quit item in the app's own menu.
162///
163/// It is a request, not a teardown: the platform decides when the frame loop
164/// stops, so it is safe to call from the middle of one — including from a
165/// gesture's settle animation, which is where the decision usually lands.
166///
167/// The backend drains it on its next turn of the loop, which is the following
168/// frame for the usual caller. An app that calls this from another thread while
169/// the loop is parked — nothing animating, no input — should wake it the same
170/// way it would for a back request; registering
171/// [`observe_back_requests`] is enough, because this nudges that listener
172/// too.
173///
174/// Platform behaviour, and where it does nothing:
175///
176/// - **Android**: finishes the activity, the same outcome as Compose's
177/// `backDispatcher.onBackPressed()` on a screen with no `BackHandler`.
178/// - **Desktop**: exits the event loop, closing the window.
179/// - **iOS**: nothing. Apple's guidelines forbid an app terminating itself and
180/// there is no supported API for it; the request is dropped rather than
181/// faked, so an app can call this unconditionally.
182/// - **Web**: nothing. A page cannot close a tab it did not open.
183pub fn request_exit() {
184 EXIT_REQUESTED.store(true, Ordering::SeqCst);
185 if let Some(listener) = latest_back_listener() {
186 // The same nudge a back request gets, and for the same reason: an app
187 // that has gone idle has no frame loop to notice the flag, and the
188 // platform drains it from that loop.
189 listener();
190 }
191}
192
193/// Whether an exit request is outstanding, without consuming it.
194///
195/// For a backend whose way of closing can fail. Consuming the flag and then
196/// discovering the platform call did not land loses the app's only record that
197/// it wanted to close: the app stays open, the gesture the user made did
198/// nothing, and nothing will ever ask again. Such a backend tests with this and
199/// calls [`take_exit_request`] once the request has actually been honoured.
200///
201/// This is also the cheap read for a loop that runs it every turn — see
202/// [`take_exit_request`].
203pub fn exit_requested() -> bool {
204 EXIT_REQUESTED.load(Ordering::SeqCst)
205}
206
207/// Take (and clear) a pending exit request. Drained by the platform backend.
208///
209/// Read before written: this runs on every turn of the platform's loop, and a
210/// bare `swap` would dirty the cache line each time even with nothing to take.
211/// The load is the common case by a very long way — an app asks to close once,
212/// ever.
213pub fn take_exit_request() -> bool {
214 exit_requested() && EXIT_REQUESTED.swap(false, Ordering::SeqCst)
215}
216
217#[cfg(test)]
218mod tests {
219 use std::sync::Arc;
220
221 use super::*;
222
223 /// Every global in this module is process-wide and the runner is threaded,
224 /// so the tests take turns. They share one lock rather than one each: the
225 /// back-request counter, the exit flag and the listener are entangled --
226 /// `request_exit` nudges the listener, so a test asserting on the listener
227 /// count is moved by a test that only meant to touch the exit flag. One
228 /// failure in twenty, which is the worst rate for anyone to debug.
229 fn navigation_lock() -> std::sync::MutexGuard<'static, ()> {
230 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
231 LOCK.lock().unwrap_or_else(|e| e.into_inner())
232 }
233
234 #[test]
235 fn requests_accumulate_and_drain() {
236 let _guard = navigation_lock();
237 let _ = take_back_requests(); // clear any residue
238 push_back_request();
239 push_back_request();
240 assert_eq!(take_back_requests(), 2);
241 assert_eq!(take_back_requests(), 0);
242 }
243
244 /// The listener is a `OnceLock`, so exactly one test in this process can
245 /// own it -- a second registration is silently ignored, and a test that
246 /// registered its own would sit there hearing nothing. Everything that has
247 /// to observe the nudge is therefore checked here.
248 #[test]
249 fn a_registered_listener_hears_every_request() {
250 let _guard = navigation_lock();
251 let heard = Arc::new(AtomicUsize::new(0));
252 let counter = Arc::clone(&heard);
253 let _observer = observe_back_requests(move || {
254 counter.fetch_add(1, Ordering::SeqCst);
255 });
256 let before = heard.load(Ordering::SeqCst);
257 push_back_request();
258 push_back_request();
259 assert_eq!(heard.load(Ordering::SeqCst), before + 2);
260 let _ = take_back_requests();
261
262 // An exit request nudges it too. The flag is drained from the frame
263 // loop, and an app with nothing moving has parked that loop; without
264 // the nudge the request would sit there until something unrelated
265 // woke the app.
266 let before = heard.load(Ordering::SeqCst);
267 request_exit();
268 assert_eq!(
269 heard.load(Ordering::SeqCst),
270 before + 1,
271 "an exit request has to wake an idle app the way a back request does"
272 );
273 let _ = take_exit_request();
274 }
275
276 #[test]
277 fn the_latest_back_observer_wins_until_it_is_dropped() {
278 let _guard = navigation_lock();
279 let first = Arc::new(AtomicUsize::new(0));
280 let second = Arc::new(AtomicUsize::new(0));
281 let first_seen = Arc::clone(&first);
282 let first_observer = observe_back_requests(move || {
283 first_seen.fetch_add(1, Ordering::SeqCst);
284 });
285 let second_seen = Arc::clone(&second);
286 let second_observer = observe_back_requests(move || {
287 second_seen.fetch_add(1, Ordering::SeqCst);
288 });
289 push_back_request();
290 assert_eq!(first.load(Ordering::SeqCst), 0);
291 assert_eq!(second.load(Ordering::SeqCst), 1);
292 drop(second_observer);
293 push_back_request();
294 assert_eq!(first.load(Ordering::SeqCst), 1);
295 drop(first_observer);
296 let _ = take_back_requests();
297 }
298
299 #[test]
300 fn an_exit_request_is_taken_once() {
301 let _guard = navigation_lock();
302 let _ = take_exit_request(); // clear any residue
303 assert!(!take_exit_request());
304 request_exit();
305 // Twice, because closing twice is closing once and a settle animation
306 // can easily ask on two consecutive frames.
307 request_exit();
308 assert!(take_exit_request());
309 assert!(
310 !take_exit_request(),
311 "a drained request came back; the platform would close twice"
312 );
313 }
314
315 #[test]
316 fn a_backend_can_look_at_the_request_without_consuming_it() {
317 let _guard = navigation_lock();
318 // The Android backend's way of closing is a JNI call that can fail.
319 // Consuming the flag first and then discovering the call did not land
320 // loses the app's only record that it asked to close: it stays open,
321 // the gesture the user made did nothing, and nothing asks again.
322 let _ = take_exit_request();
323 assert!(!exit_requested());
324
325 request_exit();
326 assert!(exit_requested());
327 assert!(
328 exit_requested(),
329 "looking at the request consumed it, which is the bug"
330 );
331
332 assert!(take_exit_request());
333 assert!(!exit_requested());
334 }
335
336 #[test]
337 fn interception_defaults_off_and_toggles() {
338 let _guard = navigation_lock();
339 set_back_interception(false);
340 assert!(!back_interception_enabled());
341 set_back_interception(true);
342 assert!(back_interception_enabled());
343 set_back_interception(false);
344 }
345}