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, Ordering},
8    },
9};
10
11use portable_atomic::AtomicU64;
12
13pub use crate::durable_save::{
14    DurableSaveEffect, DurableSaveError, DurableSaveOutcome, DurableSaveRegistration,
15    register_durable_save, register_preference_save, run_durable_saves,
16};
17
18/// Platform directory roots for application-owned files.
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct PlatformDirectories {
21    /// Folder for the persistent data of the app.
22    pub data: PathBuf,
23    /// Folder for settings files.
24    pub config: PathBuf,
25    /// Folder for files that the app can recreate. The system may delete them.
26    pub cache: PathBuf,
27    /// Folder for documents that the person can see. `None` where the platform has no such folder.
28    pub documents: Option<PathBuf>,
29    /// Folder for short-lived files.
30    pub temporary: PathBuf,
31    /// Folder that the person and other apps can reach, such as the external files folder on
32    /// Android. `None` where the platform has no such folder.
33    pub shared: Option<PathBuf>,
34}
35
36impl PlatformDirectories {
37    fn scoped(&self, application_id: &str) -> Self {
38        Self {
39            data: self.data.join(application_id),
40            config: self.config.join(application_id),
41            cache: self.cache.join(application_id),
42            documents: self
43                .documents
44                .as_ref()
45                .map(|path| path.join(application_id)),
46            temporary: self.temporary.join(application_id),
47            shared: self.shared.as_ref().map(|path| path.join(application_id)),
48        }
49    }
50}
51
52/// Why the application directories could not be resolved.
53#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
54pub enum PlatformDirectoryError {
55    /// The application id is empty or has more than one path component.
56    #[error("application id must be one non-empty path component")]
57    InvalidApplicationId,
58    /// No host has registered an application id.
59    #[error("no application id has been registered")]
60    NoApplicationId,
61    /// The platform reports no directories.
62    #[error("platform directories are unavailable")]
63    Unavailable,
64}
65
66/// Android-style lifecycle state exposed to composition observers.
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum LifecycleState {
69    /// The host exists and has not become visible yet.
70    Created,
71    /// The host is visible.
72    Started,
73    /// The host is in the foreground and receives input.
74    Resumed,
75    /// The host lost the foreground and may still be visible.
76    Paused,
77    /// The host is not visible.
78    Stopped,
79    /// The host is being torn down.
80    Destroyed,
81}
82
83/// A lifecycle transition delivered by the platform host.
84#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub struct LifecycleEvent {
86    /// The state before the transition.
87    pub from: LifecycleState,
88    /// The state after the transition.
89    pub to: LifecycleState,
90}
91
92/// Host operations supplied by the framework platform backend.
93pub trait HostController: Send + Sync {
94    /// Keeps the host window awake while enabled.
95    fn set_keep_screen_on(&self, enabled: bool);
96    /// Returns platform directory roots inside the application's host sandbox.
97    fn platform_directories(&self) -> Option<PlatformDirectories>;
98    /// Finishes/backgrounds the host.
99    fn exit(&self);
100    /// Requests that the app move to the background.
101    fn background(&self);
102    /// Ordered BCP 47 language preferences supplied by an embedded or native host.
103    /// An empty list lets the application use the operating system's default query.
104    #[cfg(feature = "localization")]
105    fn preferred_languages(&self) -> Vec<String> {
106        Vec::new()
107    }
108    /// How long this host will wait for durable saves before it suspends the
109    /// app. Android's `onPause` and iOS's background transition each allow a
110    /// short, platform-defined budget; work that overruns it keeps running
111    /// under a background-work lease.
112    fn durable_save_deadline(&self) -> std::time::Duration {
113        DEFAULT_DURABLE_SAVE_DEADLINE
114    }
115}
116
117/// The budget used when a host does not state one of its own.
118pub const DEFAULT_DURABLE_SAVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);
119
120/// How long the installed host will wait for durable saves.
121pub fn durable_save_deadline() -> std::time::Duration {
122    host_controller().map_or(DEFAULT_DURABLE_SAVE_DEADLINE, |host| {
123        host.durable_save_deadline()
124    })
125}
126
127/// Shared handle to a [`HostController`].
128pub type HostControllerRef = Arc<dyn HostController>;
129
130fn controller() -> &'static Mutex<Option<HostControllerRef>> {
131    static SLOT: OnceLock<Mutex<Option<HostControllerRef>>> = OnceLock::new();
132    SLOT.get_or_init(|| Mutex::new(None))
133}
134
135/// Installs the framework host controller.
136pub fn set_host_controller(value: HostControllerRef) {
137    if let Ok(mut slot) = controller().lock() {
138        *slot = Some(value);
139    }
140    KEEP_SCREEN_ON.store(0, Ordering::Release);
141}
142/// Removes the installed host controller.
143pub fn clear_host_controller() {
144    if let Ok(mut slot) = controller().lock() {
145        *slot = None;
146    }
147    KEEP_SCREEN_ON.store(0, Ordering::Release);
148}
149/// Returns the installed framework host controller.
150pub fn host_controller() -> Option<HostControllerRef> {
151    controller().lock().ok().and_then(|slot| slot.clone())
152}
153/// Enables or disables the host's keep-screen-on flag.
154pub fn set_keep_screen_on(enabled: bool) {
155    let value = if enabled { 2 } else { 1 };
156    if KEEP_SCREEN_ON.swap(value, Ordering::AcqRel) == value {
157        return;
158    }
159    if let Some(host) = host_controller() {
160        host.set_keep_screen_on(enabled);
161    }
162}
163fn valid_application_id(application_id: &str) -> bool {
164    !application_id.is_empty()
165        && Path::new(application_id).components().count() == 1
166        && application_id != "."
167        && application_id != ".."
168}
169
170fn desktop_platform_directories() -> Option<PlatformDirectories> {
171    let base = directories::BaseDirs::new()?;
172    let documents = directories::UserDirs::new()
173        .and_then(|directories| directories.document_dir().map(Path::to_path_buf));
174    Some(PlatformDirectories {
175        data: base.data_dir().to_path_buf(),
176        config: base.config_dir().to_path_buf(),
177        cache: base.cache_dir().to_path_buf(),
178        documents,
179        temporary: std::env::temp_dir(),
180        shared: None,
181    })
182}
183
184fn application_id_slot() -> &'static Mutex<Option<String>> {
185    static SLOT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
186    SLOT.get_or_init(|| Mutex::new(None))
187}
188
189/// Registers the id every framework-owned storage path is scoped by.
190///
191/// Platform backends call this at startup with what the platform packaged —
192/// the Android package name, the iOS bundle identifier, the desktop
193/// application name — so applications never assemble a storage path
194/// themselves.
195pub fn set_application_id(application_id: &str) -> Result<(), PlatformDirectoryError> {
196    if !valid_application_id(application_id) {
197        return Err(PlatformDirectoryError::InvalidApplicationId);
198    }
199    if let Ok(mut slot) = application_id_slot().lock() {
200        *slot = Some(application_id.to_string());
201    }
202    Ok(())
203}
204
205/// Removes the registered application id (tests and teardown).
206pub fn clear_application_id() {
207    if let Ok(mut slot) = application_id_slot().lock() {
208        *slot = None;
209    }
210}
211
212/// The registered application id, if a host has published one.
213pub fn application_id() -> Option<String> {
214    application_id_slot()
215        .lock()
216        .ok()
217        .and_then(|slot| slot.clone())
218}
219
220/// Returns typed directories for the registered application.
221pub fn application_directories() -> Result<PlatformDirectories, PlatformDirectoryError> {
222    let application_id = application_id().ok_or(PlatformDirectoryError::NoApplicationId)?;
223    let roots = host_controller()
224        .and_then(|host| host.platform_directories())
225        .or_else(desktop_platform_directories)
226        .ok_or(PlatformDirectoryError::Unavailable)?;
227    Ok(roots.scoped(&application_id))
228}
229/// Requests that the host finish the app.
230pub fn exit_app() {
231    if let Some(host) = host_controller() {
232        host.exit();
233    }
234}
235/// Requests that the host move the app to the background.
236pub fn background_app() {
237    if let Some(host) = host_controller() {
238        host.background();
239    }
240}
241
242#[cfg(not(target_arch = "wasm32"))]
243type Observer = Arc<dyn Fn(LifecycleEvent) + Send + Sync>;
244
245#[cfg(not(target_arch = "wasm32"))]
246fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
247    static SLOT: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
248    SLOT.get_or_init(|| Mutex::new(Vec::new()))
249}
250static NEXT_ID: AtomicU64 = AtomicU64::new(1);
251static LIFECYCLE_STATE: AtomicU8 = AtomicU8::new(LifecycleState::Created as u8);
252static KEEP_SCREEN_ON: AtomicU8 = AtomicU8::new(0);
253
254/// RAII lifecycle observer registration.
255pub struct LifecycleObserver {
256    id: u64,
257}
258impl Drop for LifecycleObserver {
259    fn drop(&mut self) {
260        #[cfg(not(target_arch = "wasm32"))]
261        if let Ok(mut list) = observers().lock() {
262            list.retain(|(id, _)| *id != self.id);
263        }
264        #[cfg(target_arch = "wasm32")]
265        crate::thread_state::with(|state| state.lifecycle_observers.remove(self.id));
266    }
267}
268/// Observes host lifecycle transitions until the returned handle is dropped.
269#[cfg(not(target_arch = "wasm32"))]
270pub fn observe_lifecycle(
271    observer: impl Fn(LifecycleEvent) + Send + Sync + 'static,
272) -> LifecycleObserver {
273    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
274    if let Ok(mut list) = observers().lock() {
275        list.push((id, Arc::new(observer)));
276    }
277    LifecycleObserver { id }
278}
279/// Observes host lifecycle transitions until the returned handle is dropped.
280#[cfg(target_arch = "wasm32")]
281pub fn observe_lifecycle(observer: impl Fn(LifecycleEvent) + 'static) -> LifecycleObserver {
282    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
283    crate::thread_state::with(|state| {
284        state
285            .lifecycle_observers
286            .add(id, std::rc::Rc::new(observer));
287    });
288    LifecycleObserver { id }
289}
290/// Publishes a lifecycle transition from the platform host.
291pub fn dispatch_lifecycle(event: LifecycleEvent) {
292    LIFECYCLE_STATE.store(event.to as u8, Ordering::Release);
293    crate::media::on_lifecycle(event);
294    #[cfg(not(target_arch = "wasm32"))]
295    let callbacks = observers()
296        .lock()
297        .map(|list| {
298            list.iter()
299                .map(|(_, cb)| Arc::clone(cb))
300                .collect::<Vec<_>>()
301        })
302        .unwrap_or_default();
303    #[cfg(target_arch = "wasm32")]
304    let callbacks = crate::thread_state::with(|state| state.lifecycle_observers.all());
305    for callback in callbacks {
306        callback(event);
307    }
308}
309
310/// Returns the latest lifecycle state published by the platform host.
311pub fn current_lifecycle_state() -> LifecycleState {
312    match LIFECYCLE_STATE.load(Ordering::Acquire) {
313        0 => LifecycleState::Created,
314        1 => LifecycleState::Started,
315        2 => LifecycleState::Resumed,
316        3 => LifecycleState::Paused,
317        4 => LifecycleState::Stopped,
318        _ => LifecycleState::Destroyed,
319    }
320}
321
322/// Publishes a platform lifecycle state and derives the transition source from
323/// the framework's previous state.
324///
325/// Leaving the foreground runs every registered durable save first, inside the
326/// budget the host allows, so an application never has to hook the transition
327/// itself to persist its data.
328pub fn dispatch_lifecycle_state(to: LifecycleState) {
329    let from = current_lifecycle_state();
330    if from == to {
331        return;
332    }
333    if matches!(to, LifecycleState::Paused) {
334        let outcome = run_durable_saves(durable_save_deadline());
335        if matches!(
336            outcome,
337            DurableSaveOutcome::TimedOut | DurableSaveOutcome::Failed
338        ) {
339            log::warn!("cranpose: durable saves did not complete successfully: {outcome:?}");
340        }
341    }
342    dispatch_lifecycle(LifecycleEvent { from, to });
343}
344
345/// The lifecycle state of a window or browser page that is `visible` and
346/// has keyboard `focused`, mapped the way Compose Multiplatform maps desktop
347/// windows: resumed while focused, paused while only visible, and stopped
348/// while minimized, hidden or in a background tab.
349pub fn window_lifecycle_state(visible: bool, focused: bool) -> LifecycleState {
350    match (visible, focused) {
351        (false, _) => LifecycleState::Stopped,
352        (true, true) => LifecycleState::Resumed,
353        (true, false) => LifecycleState::Paused,
354    }
355}
356
357impl LifecycleState {
358    /// Whether this state is at least as active as `other`, counting paused
359    /// as started and stopped as created — Android's `isAtLeast`.
360    pub fn is_at_least(self, other: LifecycleState) -> bool {
361        lifecycle_level(self) >= lifecycle_level(other)
362    }
363}
364
365fn lifecycle_level(state: LifecycleState) -> u8 {
366    match state {
367        LifecycleState::Destroyed => 0,
368        LifecycleState::Created | LifecycleState::Stopped => 1,
369        LifecycleState::Started | LifecycleState::Paused => 2,
370        LifecycleState::Resumed => 3,
371    }
372}
373
374fn next_lifecycle_step(from: LifecycleState, to: LifecycleState) -> Option<LifecycleState> {
375    let rising = match lifecycle_level(from).cmp(&lifecycle_level(to)) {
376        std::cmp::Ordering::Equal => return None,
377        std::cmp::Ordering::Less => true,
378        std::cmp::Ordering::Greater => false,
379    };
380    match (from, rising) {
381        (LifecycleState::Destroyed, _) => None,
382        (LifecycleState::Created | LifecycleState::Stopped, true) => Some(LifecycleState::Started),
383        (LifecycleState::Started | LifecycleState::Paused, true) => Some(LifecycleState::Resumed),
384        (LifecycleState::Resumed, _) => Some(LifecycleState::Paused),
385        (LifecycleState::Started | LifecycleState::Paused, false) => Some(LifecycleState::Stopped),
386        (LifecycleState::Created | LifecycleState::Stopped, false) => {
387            Some(LifecycleState::Destroyed)
388        }
389    }
390}
391
392/// Moves the host lifecycle to `target` through every state in between, in
393/// Android's order: a stopped app starts before it resumes, and a resumed one
394/// pauses before it stops, so leaving the foreground always runs the durable
395/// saves. Paused and started count as the same place, as do created and
396/// stopped. Hosts whose platform reports only visibility and focus use this
397/// instead of dispatching each transition themselves.
398pub fn advance_lifecycle(target: LifecycleState) {
399    while let Some(next) = next_lifecycle_step(current_lifecycle_state(), target) {
400        dispatch_lifecycle_state(next);
401    }
402}
403
404/// The `CompositionLocal` carrying the host's current lifecycle state.
405///
406/// [`ProvideLifecycle`] installs it; descendants read it and recompose on every
407/// transition, so a screen can pause its own work without registering an
408/// observer of its own.
409pub fn local_lifecycle_state() -> cranpose_core::CompositionLocal<LifecycleState> {
410    crate::composition_locals::cached_local(
411        |locals| &locals.lifecycle,
412        || cranpose_core::compositionLocalOf(current_lifecycle_state),
413    )
414}
415
416/// The host's lifecycle state as observable state.
417#[expect(non_snake_case)]
418#[track_caller]
419pub fn rememberLifecycleState() -> cranpose_core::State<LifecycleState> {
420    let transitions = rememberLifecycleEvents();
421    let state = cranpose_core::collectAsState(
422        transitions,
423        (),
424        LifecycleEvent {
425            from: current_lifecycle_state(),
426            to: current_lifecycle_state(),
427        },
428    );
429    cranpose_core::derivedStateOf(move || state.get().to)
430}
431
432/// Host lifecycle transitions as a composition-scoped stream.
433#[expect(non_snake_case)]
434#[track_caller]
435pub fn rememberLifecycleEvents() -> cranpose_core::EventStream<LifecycleEvent> {
436    cranpose_core::rememberEventStream((), |sender| {
437        observe_lifecycle(move |event| sender.send(event))
438    })
439}
440
441/// Provides the host's lifecycle state to descendant composables.
442///
443/// The application shell wraps its content in this once; screens then read
444/// [`local_lifecycle_state`].
445#[cranpose_macros::composable]
446pub fn ProvideLifecycle(content: impl FnOnce()) {
447    let state = rememberLifecycleState();
448    let local = local_lifecycle_state();
449    cranpose_core::CompositionLocalProvider([local.provides(state.get())], move || {
450        content();
451    });
452}
453
454#[cfg(test)]
455#[path = "tests/host_tests.rs"]
456mod tests;