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