Skip to main content

cranpose_services/
host.rs

1//! Framework-owned application-host state and controls.
2
3use std::{
4    path::{Path, PathBuf},
5    sync::{
6        Arc, Mutex, OnceLock,
7        atomic::{AtomicU8, AtomicU64, Ordering},
8    },
9};
10
11/// Platform directory roots for application-owned files.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct PlatformDirectories {
14    pub data: PathBuf,
15    pub config: PathBuf,
16    pub cache: PathBuf,
17    pub documents: Option<PathBuf>,
18    pub temporary: PathBuf,
19    pub shared: Option<PathBuf>,
20}
21
22impl PlatformDirectories {
23    fn scoped(&self, application_id: &str) -> Self {
24        Self {
25            data: self.data.join(application_id),
26            config: self.config.join(application_id),
27            cache: self.cache.join(application_id),
28            documents: self
29                .documents
30                .as_ref()
31                .map(|path| path.join(application_id)),
32            temporary: self.temporary.join(application_id),
33            shared: self.shared.as_ref().map(|path| path.join(application_id)),
34        }
35    }
36}
37
38#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
39pub enum PlatformDirectoryError {
40    #[error("application id must be one non-empty path component")]
41    InvalidApplicationId,
42    #[error("no application id has been registered")]
43    NoApplicationId,
44    #[error("platform directories are unavailable")]
45    Unavailable,
46}
47
48/// Android-style lifecycle state exposed to composition observers.
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum LifecycleState {
51    Created,
52    Started,
53    Resumed,
54    Paused,
55    Stopped,
56    Destroyed,
57}
58
59/// A lifecycle transition delivered by the platform host.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct LifecycleEvent {
62    pub from: LifecycleState,
63    pub to: LifecycleState,
64}
65
66/// Host operations supplied by the framework platform backend.
67pub trait HostController: Send + Sync {
68    /// Keeps the host window awake while enabled.
69    fn set_keep_screen_on(&self, enabled: bool);
70    /// Returns platform directory roots inside the application's host sandbox.
71    fn platform_directories(&self) -> Option<PlatformDirectories>;
72    /// Finishes/backgrounds the host.
73    fn exit(&self);
74    /// Requests that the app move to the background.
75    fn background(&self);
76    /// How long this host will wait for durable saves before it suspends the
77    /// app. Android's `onPause` and iOS's background transition each allow a
78    /// short, platform-defined budget; work that overruns it keeps running
79    /// under a background-work lease.
80    fn durable_save_deadline(&self) -> std::time::Duration {
81        DEFAULT_DURABLE_SAVE_DEADLINE
82    }
83}
84
85/// The budget used when a host does not state one of its own.
86pub const DEFAULT_DURABLE_SAVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);
87
88/// How long the installed host will wait for durable saves.
89pub fn durable_save_deadline() -> std::time::Duration {
90    host_controller().map_or(DEFAULT_DURABLE_SAVE_DEADLINE, |host| {
91        host.durable_save_deadline()
92    })
93}
94
95pub type HostControllerRef = Arc<dyn HostController>;
96
97fn controller() -> &'static Mutex<Option<HostControllerRef>> {
98    static SLOT: OnceLock<Mutex<Option<HostControllerRef>>> = OnceLock::new();
99    SLOT.get_or_init(|| Mutex::new(None))
100}
101
102/// Installs the framework host controller.
103pub fn set_host_controller(value: HostControllerRef) {
104    if let Ok(mut slot) = controller().lock() {
105        *slot = Some(value);
106    }
107    KEEP_SCREEN_ON.store(0, Ordering::Release);
108}
109/// Removes the installed host controller.
110pub fn clear_host_controller() {
111    if let Ok(mut slot) = controller().lock() {
112        *slot = None;
113    }
114    KEEP_SCREEN_ON.store(0, Ordering::Release);
115}
116/// Returns the installed framework host controller.
117pub fn host_controller() -> Option<HostControllerRef> {
118    controller().lock().ok().and_then(|slot| slot.clone())
119}
120/// Enables or disables the host's keep-screen-on flag.
121pub fn set_keep_screen_on(enabled: bool) {
122    let value = if enabled { 2 } else { 1 };
123    if KEEP_SCREEN_ON.swap(value, Ordering::AcqRel) == value {
124        return;
125    }
126    if let Some(host) = host_controller() {
127        host.set_keep_screen_on(enabled);
128    }
129}
130fn valid_application_id(application_id: &str) -> bool {
131    !application_id.is_empty()
132        && Path::new(application_id).components().count() == 1
133        && application_id != "."
134        && application_id != ".."
135}
136
137fn desktop_platform_directories() -> Option<PlatformDirectories> {
138    let base = directories::BaseDirs::new()?;
139    let documents = directories::UserDirs::new()
140        .and_then(|directories| directories.document_dir().map(Path::to_path_buf));
141    Some(PlatformDirectories {
142        data: base.data_dir().to_path_buf(),
143        config: base.config_dir().to_path_buf(),
144        cache: base.cache_dir().to_path_buf(),
145        documents,
146        temporary: std::env::temp_dir(),
147        shared: None,
148    })
149}
150
151fn application_id_slot() -> &'static Mutex<Option<String>> {
152    static SLOT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
153    SLOT.get_or_init(|| Mutex::new(None))
154}
155
156/// Registers the id every framework-owned storage path is scoped by.
157///
158/// Platform backends call this at startup with what the platform packaged —
159/// the Android package name, the iOS bundle identifier, the desktop
160/// application name — so applications never assemble a storage path
161/// themselves.
162pub fn set_application_id(application_id: &str) -> Result<(), PlatformDirectoryError> {
163    if !valid_application_id(application_id) {
164        return Err(PlatformDirectoryError::InvalidApplicationId);
165    }
166    if let Ok(mut slot) = application_id_slot().lock() {
167        *slot = Some(application_id.to_string());
168    }
169    Ok(())
170}
171
172/// Removes the registered application id (tests and teardown).
173pub fn clear_application_id() {
174    if let Ok(mut slot) = application_id_slot().lock() {
175        *slot = None;
176    }
177}
178
179/// The registered application id, if a host has published one.
180pub fn application_id() -> Option<String> {
181    application_id_slot()
182        .lock()
183        .ok()
184        .and_then(|slot| slot.clone())
185}
186
187/// Returns typed directories for the registered application.
188pub fn application_directories() -> Result<PlatformDirectories, PlatformDirectoryError> {
189    let application_id = application_id().ok_or(PlatformDirectoryError::NoApplicationId)?;
190    let roots = host_controller()
191        .and_then(|host| host.platform_directories())
192        .or_else(desktop_platform_directories)
193        .ok_or(PlatformDirectoryError::Unavailable)?;
194    Ok(roots.scoped(&application_id))
195}
196/// Requests that the host finish the app.
197pub fn exit_app() {
198    if let Some(host) = host_controller() {
199        host.exit();
200    }
201}
202/// Requests that the host move the app to the background.
203pub fn background_app() {
204    if let Some(host) = host_controller() {
205        host.background();
206    }
207}
208
209#[cfg(not(target_arch = "wasm32"))]
210type Observer = Arc<dyn Fn(LifecycleEvent) + Send + Sync>;
211#[cfg(target_arch = "wasm32")]
212type Observer = std::rc::Rc<dyn Fn(LifecycleEvent)>;
213
214#[cfg(not(target_arch = "wasm32"))]
215fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
216    static SLOT: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
217    SLOT.get_or_init(|| Mutex::new(Vec::new()))
218}
219#[cfg(target_arch = "wasm32")]
220thread_local! {
221    static OBSERVERS: std::cell::RefCell<Vec<(u64, Observer)>> = const { std::cell::RefCell::new(Vec::new()) };
222}
223static NEXT_ID: AtomicU64 = AtomicU64::new(1);
224static LIFECYCLE_STATE: AtomicU8 = AtomicU8::new(LifecycleState::Created as u8);
225static KEEP_SCREEN_ON: AtomicU8 = AtomicU8::new(0);
226
227/// RAII lifecycle observer registration.
228pub struct LifecycleObserver {
229    id: u64,
230}
231impl Drop for LifecycleObserver {
232    fn drop(&mut self) {
233        #[cfg(not(target_arch = "wasm32"))]
234        if let Ok(mut list) = observers().lock() {
235            list.retain(|(id, _)| *id != self.id);
236        }
237        #[cfg(target_arch = "wasm32")]
238        OBSERVERS.with(|list| list.borrow_mut().retain(|(id, _)| *id != self.id));
239    }
240}
241/// Observes host lifecycle transitions until the returned handle is dropped.
242#[cfg(not(target_arch = "wasm32"))]
243pub fn observe_lifecycle(
244    observer: impl Fn(LifecycleEvent) + Send + Sync + 'static,
245) -> LifecycleObserver {
246    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
247    if let Ok(mut list) = observers().lock() {
248        list.push((id, Arc::new(observer)));
249    }
250    LifecycleObserver { id }
251}
252/// Observes host lifecycle transitions until the returned handle is dropped.
253#[cfg(target_arch = "wasm32")]
254pub fn observe_lifecycle(observer: impl Fn(LifecycleEvent) + 'static) -> LifecycleObserver {
255    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
256    OBSERVERS.with(|list| list.borrow_mut().push((id, std::rc::Rc::new(observer))));
257    LifecycleObserver { id }
258}
259/// Publishes a lifecycle transition from the platform host.
260pub fn dispatch_lifecycle(event: LifecycleEvent) {
261    LIFECYCLE_STATE.store(event.to as u8, Ordering::Release);
262    crate::media::on_lifecycle(event);
263    #[cfg(not(target_arch = "wasm32"))]
264    let callbacks = observers()
265        .lock()
266        .map(|list| {
267            list.iter()
268                .map(|(_, cb)| Arc::clone(cb))
269                .collect::<Vec<_>>()
270        })
271        .unwrap_or_default();
272    #[cfg(target_arch = "wasm32")]
273    let callbacks = OBSERVERS.with(|list| {
274        list.borrow()
275            .iter()
276            .map(|(_, callback)| std::rc::Rc::clone(callback))
277            .collect::<Vec<_>>()
278    });
279    for callback in callbacks {
280        callback(event);
281    }
282}
283
284/// Returns the latest lifecycle state published by the platform host.
285pub fn current_lifecycle_state() -> LifecycleState {
286    match LIFECYCLE_STATE.load(Ordering::Acquire) {
287        0 => LifecycleState::Created,
288        1 => LifecycleState::Started,
289        2 => LifecycleState::Resumed,
290        3 => LifecycleState::Paused,
291        4 => LifecycleState::Stopped,
292        _ => LifecycleState::Destroyed,
293    }
294}
295
296/// Publishes a platform lifecycle state and derives the transition source from
297/// the framework's previous state.
298///
299/// Leaving the foreground runs every registered durable save first, inside the
300/// budget the host allows, so an application never has to hook the transition
301/// itself to persist its data.
302pub fn dispatch_lifecycle_state(to: LifecycleState) {
303    let from = current_lifecycle_state();
304    if from == to {
305        return;
306    }
307    #[cfg(not(target_arch = "wasm32"))]
308    if matches!(to, LifecycleState::Paused) {
309        let outcome = run_durable_saves(durable_save_deadline());
310        if outcome == DurableSaveOutcome::TimedOut {
311            log::warn!("cranpose: durable saves overran the host deadline; they keep running");
312        }
313    }
314    dispatch_lifecycle(LifecycleEvent { from, to });
315}
316
317/// The lifecycle state of a window or browser page that is `visible` and
318/// has keyboard `focused`, mapped the way Compose Multiplatform maps desktop
319/// windows: resumed while focused, paused while only visible, and stopped
320/// while minimized, hidden or in a background tab.
321pub fn window_lifecycle_state(visible: bool, focused: bool) -> LifecycleState {
322    match (visible, focused) {
323        (false, _) => LifecycleState::Stopped,
324        (true, true) => LifecycleState::Resumed,
325        (true, false) => LifecycleState::Paused,
326    }
327}
328
329impl LifecycleState {
330    /// Whether this state is at least as active as `other`, counting paused
331    /// as started and stopped as created — Android's `isAtLeast`.
332    pub fn is_at_least(self, other: LifecycleState) -> bool {
333        lifecycle_level(self) >= lifecycle_level(other)
334    }
335}
336
337fn lifecycle_level(state: LifecycleState) -> u8 {
338    match state {
339        LifecycleState::Destroyed => 0,
340        LifecycleState::Created | LifecycleState::Stopped => 1,
341        LifecycleState::Started | LifecycleState::Paused => 2,
342        LifecycleState::Resumed => 3,
343    }
344}
345
346fn next_lifecycle_step(from: LifecycleState, to: LifecycleState) -> Option<LifecycleState> {
347    let rising = match lifecycle_level(from).cmp(&lifecycle_level(to)) {
348        std::cmp::Ordering::Equal => return None,
349        std::cmp::Ordering::Less => true,
350        std::cmp::Ordering::Greater => false,
351    };
352    match (from, rising) {
353        (LifecycleState::Destroyed, _) => None,
354        (LifecycleState::Created | LifecycleState::Stopped, true) => Some(LifecycleState::Started),
355        (LifecycleState::Started | LifecycleState::Paused, true) => Some(LifecycleState::Resumed),
356        (LifecycleState::Resumed, _) => Some(LifecycleState::Paused),
357        (LifecycleState::Started | LifecycleState::Paused, false) => Some(LifecycleState::Stopped),
358        (LifecycleState::Created | LifecycleState::Stopped, false) => {
359            Some(LifecycleState::Destroyed)
360        }
361    }
362}
363
364/// Moves the host lifecycle to `target` through every state in between, in
365/// Android's order: a stopped app starts before it resumes, and a resumed one
366/// pauses before it stops, so leaving the foreground always runs the durable
367/// saves. Paused and started count as the same place, as do created and
368/// stopped. Hosts whose platform reports only visibility and focus use this
369/// instead of dispatching each transition themselves.
370pub fn advance_lifecycle(target: LifecycleState) {
371    while let Some(next) = next_lifecycle_step(current_lifecycle_state(), target) {
372        dispatch_lifecycle_state(next);
373    }
374}
375
376/// The `CompositionLocal` carrying the host's current lifecycle state.
377///
378/// [`ProvideLifecycle`] installs it; descendants read it and recompose on every
379/// transition, so a screen can pause its own work without registering an
380/// observer of its own.
381pub fn local_lifecycle_state() -> cranpose_core::CompositionLocal<LifecycleState> {
382    thread_local! {
383        static LOCAL: std::cell::RefCell<Option<cranpose_core::CompositionLocal<LifecycleState>>> =
384            const { std::cell::RefCell::new(None) };
385    }
386    LOCAL.with(|cell| {
387        cell.borrow_mut()
388            .get_or_insert_with(|| cranpose_core::compositionLocalOf(current_lifecycle_state))
389            .clone()
390    })
391}
392
393/// The host's lifecycle state as observable state.
394#[expect(non_snake_case)]
395#[track_caller]
396pub fn rememberLifecycleState() -> cranpose_core::State<LifecycleState> {
397    let transitions = rememberLifecycleEvents();
398    let state = cranpose_core::collectAsState(
399        transitions,
400        (),
401        LifecycleEvent {
402            from: current_lifecycle_state(),
403            to: current_lifecycle_state(),
404        },
405    );
406    cranpose_core::derivedStateOf(move || state.get().to)
407}
408
409/// Host lifecycle transitions as a composition-scoped stream.
410#[expect(non_snake_case)]
411#[track_caller]
412pub fn rememberLifecycleEvents() -> cranpose_core::EventStream<LifecycleEvent> {
413    cranpose_core::rememberEventStream((), |sender| {
414        observe_lifecycle(move |event| sender.send(event))
415    })
416}
417
418/// Provides the host's lifecycle state to descendant composables.
419///
420/// The application shell wraps its content in this once; screens then read
421/// [`local_lifecycle_state`].
422#[cranpose_macros::composable]
423pub fn ProvideLifecycle(content: impl FnOnce()) {
424    let state = rememberLifecycleState();
425    let local = local_lifecycle_state();
426    cranpose_core::CompositionLocalProvider(vec![local.provides(state.get())], move || {
427        content();
428    });
429}
430
431/// What became of the durable saves the host asked for.
432#[derive(Clone, Copy, Debug, Eq, PartialEq)]
433pub enum DurableSaveOutcome {
434    /// Nothing was registered.
435    Nothing,
436    /// Every registered save finished inside the deadline.
437    Completed,
438    /// The deadline expired with saves still running. They keep running under
439    /// a background-work lease, but the host is free to suspend.
440    TimedOut,
441}
442
443type SaveWork = Arc<dyn Fn() + Send + Sync>;
444
445fn durable_saves() -> &'static Mutex<Vec<(u64, SaveWork)>> {
446    static SLOT: OnceLock<Mutex<Vec<(u64, SaveWork)>>> = OnceLock::new();
447    SLOT.get_or_init(|| Mutex::new(Vec::new()))
448}
449
450/// Keeps a durable save registered until it is dropped.
451pub struct DurableSaveRegistration {
452    id: u64,
453}
454
455impl Drop for DurableSaveRegistration {
456    fn drop(&mut self) {
457        if let Ok(mut saves) = durable_saves().lock() {
458            saves.retain(|(id, _)| *id != self.id);
459        }
460    }
461}
462
463/// Registers work that must reach durable storage before the host suspends.
464///
465/// Applications use [`DurableSaveEffect`] so the registration is scoped to the
466/// composition that owns the data.
467pub fn register_durable_save(save: impl Fn() + Send + Sync + 'static) -> DurableSaveRegistration {
468    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
469    if let Ok(mut saves) = durable_saves().lock() {
470        saves.push((id, Arc::new(save)));
471    }
472    DurableSaveRegistration { id }
473}
474
475/// Registers `save` for as long as this call stays in the composition.
476///
477/// The host runs it when the app is about to be suspended, off the UI thread
478/// and under a background-work lease, so a slow write does not stall the
479/// lifecycle callback the platform is waiting on.
480#[expect(non_snake_case)]
481#[track_caller]
482pub fn DurableSaveEffect<K: PartialEq + 'static>(keys: K, save: impl Fn() + Send + Sync + 'static) {
483    cranpose_core::__disposable_effect_impl(
484        cranpose_core::caller_location_key()
485            ^ cranpose_core::location_key(file!(), line!(), column!()),
486        keys,
487        move |scope| {
488            let registration = register_durable_save(save);
489            scope.on_dispose(move || drop(registration))
490        },
491    );
492}
493
494/// Runs every registered durable save, waiting up to `deadline`.
495///
496/// Platform hosts call this from the lifecycle callback the OS gives them —
497/// Android's `onPause`, iOS's `applicationDidEnterBackground` — passing the
498/// budget that platform allows. Saves run on worker threads under a
499/// background-work lease, so work that overruns the deadline still finishes
500/// while the OS keeps the process alive.
501#[cfg(not(target_arch = "wasm32"))]
502pub fn run_durable_saves(deadline: std::time::Duration) -> DurableSaveOutcome {
503    let saves: Vec<SaveWork> = durable_saves()
504        .lock()
505        .map(|saves| saves.iter().map(|(_, save)| Arc::clone(save)).collect())
506        .unwrap_or_default();
507    if saves.is_empty() {
508        return DurableSaveOutcome::Nothing;
509    }
510
511    let outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(saves.len()));
512    let finished = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
513    for save in saves {
514        let worker_outstanding = Arc::clone(&outstanding);
515        let worker_finished = Arc::clone(&finished);
516        let lease = crate::background::acquire_background_work();
517        let spawned = std::thread::Builder::new()
518            .name("cranpose-durable-save".to_string())
519            .spawn(move || {
520                save();
521                drop(lease);
522                if worker_outstanding.fetch_sub(1, Ordering::AcqRel) == 1 {
523                    let (done, wake) = &*worker_finished;
524                    if let Ok(mut done) = done.lock() {
525                        *done = true;
526                    }
527                    wake.notify_all();
528                }
529            });
530        if spawned.is_err() {
531            log::warn!("cranpose: a durable save could not be started");
532            if outstanding.fetch_sub(1, Ordering::AcqRel) == 1 {
533                let (done, wake) = &*finished;
534                if let Ok(mut done) = done.lock() {
535                    *done = true;
536                }
537                wake.notify_all();
538            }
539        }
540    }
541
542    let (done, wake) = &*finished;
543    let Ok(mut guard) = done.lock() else {
544        return DurableSaveOutcome::TimedOut;
545    };
546    let mut remaining = deadline;
547    let started = web_time::Instant::now();
548    while !*guard {
549        let Ok((next, timeout)) = wake.wait_timeout(guard, remaining) else {
550            return DurableSaveOutcome::TimedOut;
551        };
552        guard = next;
553        if timeout.timed_out() {
554            break;
555        }
556        remaining = deadline.saturating_sub(started.elapsed());
557        if remaining.is_zero() {
558            break;
559        }
560    }
561    if *guard {
562        DurableSaveOutcome::Completed
563    } else {
564        DurableSaveOutcome::TimedOut
565    }
566}
567
568#[cfg(test)]
569#[path = "tests/host_tests.rs"]
570mod tests;