cranpose-services 0.9.39

Multiplatform service contracts and platform integrations for Cranpose apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Framework-owned application-host state and controls.

use std::{
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex, OnceLock,
        atomic::{AtomicU8, AtomicU64, Ordering},
    },
};

pub use crate::durable_save::{
    DurableSaveEffect, DurableSaveError, DurableSaveOutcome, DurableSaveRegistration,
    register_durable_save, register_preference_save, run_durable_saves,
};

/// Platform directory roots for application-owned files.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PlatformDirectories {
    pub data: PathBuf,
    pub config: PathBuf,
    pub cache: PathBuf,
    pub documents: Option<PathBuf>,
    pub temporary: PathBuf,
    pub shared: Option<PathBuf>,
}

impl PlatformDirectories {
    fn scoped(&self, application_id: &str) -> Self {
        Self {
            data: self.data.join(application_id),
            config: self.config.join(application_id),
            cache: self.cache.join(application_id),
            documents: self
                .documents
                .as_ref()
                .map(|path| path.join(application_id)),
            temporary: self.temporary.join(application_id),
            shared: self.shared.as_ref().map(|path| path.join(application_id)),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PlatformDirectoryError {
    #[error("application id must be one non-empty path component")]
    InvalidApplicationId,
    #[error("no application id has been registered")]
    NoApplicationId,
    #[error("platform directories are unavailable")]
    Unavailable,
}

/// Android-style lifecycle state exposed to composition observers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LifecycleState {
    Created,
    Started,
    Resumed,
    Paused,
    Stopped,
    Destroyed,
}

/// A lifecycle transition delivered by the platform host.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LifecycleEvent {
    pub from: LifecycleState,
    pub to: LifecycleState,
}

/// Host operations supplied by the framework platform backend.
pub trait HostController: Send + Sync {
    /// Keeps the host window awake while enabled.
    fn set_keep_screen_on(&self, enabled: bool);
    /// Returns platform directory roots inside the application's host sandbox.
    fn platform_directories(&self) -> Option<PlatformDirectories>;
    /// Finishes/backgrounds the host.
    fn exit(&self);
    /// Requests that the app move to the background.
    fn background(&self);
    /// Ordered BCP 47 language preferences supplied by an embedded or native host.
    /// An empty list lets the application use the operating system's default query.
    #[cfg(feature = "localization")]
    fn preferred_languages(&self) -> Vec<String> {
        Vec::new()
    }
    /// How long this host will wait for durable saves before it suspends the
    /// app. Android's `onPause` and iOS's background transition each allow a
    /// short, platform-defined budget; work that overruns it keeps running
    /// under a background-work lease.
    fn durable_save_deadline(&self) -> std::time::Duration {
        DEFAULT_DURABLE_SAVE_DEADLINE
    }
}

/// The budget used when a host does not state one of its own.
pub const DEFAULT_DURABLE_SAVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);

/// How long the installed host will wait for durable saves.
pub fn durable_save_deadline() -> std::time::Duration {
    host_controller().map_or(DEFAULT_DURABLE_SAVE_DEADLINE, |host| {
        host.durable_save_deadline()
    })
}

pub type HostControllerRef = Arc<dyn HostController>;

fn controller() -> &'static Mutex<Option<HostControllerRef>> {
    static SLOT: OnceLock<Mutex<Option<HostControllerRef>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

/// Installs the framework host controller.
pub fn set_host_controller(value: HostControllerRef) {
    if let Ok(mut slot) = controller().lock() {
        *slot = Some(value);
    }
    KEEP_SCREEN_ON.store(0, Ordering::Release);
}
/// Removes the installed host controller.
pub fn clear_host_controller() {
    if let Ok(mut slot) = controller().lock() {
        *slot = None;
    }
    KEEP_SCREEN_ON.store(0, Ordering::Release);
}
/// Returns the installed framework host controller.
pub fn host_controller() -> Option<HostControllerRef> {
    controller().lock().ok().and_then(|slot| slot.clone())
}
/// Enables or disables the host's keep-screen-on flag.
pub fn set_keep_screen_on(enabled: bool) {
    let value = if enabled { 2 } else { 1 };
    if KEEP_SCREEN_ON.swap(value, Ordering::AcqRel) == value {
        return;
    }
    if let Some(host) = host_controller() {
        host.set_keep_screen_on(enabled);
    }
}
fn valid_application_id(application_id: &str) -> bool {
    !application_id.is_empty()
        && Path::new(application_id).components().count() == 1
        && application_id != "."
        && application_id != ".."
}

fn desktop_platform_directories() -> Option<PlatformDirectories> {
    let base = directories::BaseDirs::new()?;
    let documents = directories::UserDirs::new()
        .and_then(|directories| directories.document_dir().map(Path::to_path_buf));
    Some(PlatformDirectories {
        data: base.data_dir().to_path_buf(),
        config: base.config_dir().to_path_buf(),
        cache: base.cache_dir().to_path_buf(),
        documents,
        temporary: std::env::temp_dir(),
        shared: None,
    })
}

fn application_id_slot() -> &'static Mutex<Option<String>> {
    static SLOT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

/// Registers the id every framework-owned storage path is scoped by.
///
/// Platform backends call this at startup with what the platform packaged —
/// the Android package name, the iOS bundle identifier, the desktop
/// application name — so applications never assemble a storage path
/// themselves.
pub fn set_application_id(application_id: &str) -> Result<(), PlatformDirectoryError> {
    if !valid_application_id(application_id) {
        return Err(PlatformDirectoryError::InvalidApplicationId);
    }
    if let Ok(mut slot) = application_id_slot().lock() {
        *slot = Some(application_id.to_string());
    }
    Ok(())
}

/// Removes the registered application id (tests and teardown).
pub fn clear_application_id() {
    if let Ok(mut slot) = application_id_slot().lock() {
        *slot = None;
    }
}

/// The registered application id, if a host has published one.
pub fn application_id() -> Option<String> {
    application_id_slot()
        .lock()
        .ok()
        .and_then(|slot| slot.clone())
}

/// Returns typed directories for the registered application.
pub fn application_directories() -> Result<PlatformDirectories, PlatformDirectoryError> {
    let application_id = application_id().ok_or(PlatformDirectoryError::NoApplicationId)?;
    let roots = host_controller()
        .and_then(|host| host.platform_directories())
        .or_else(desktop_platform_directories)
        .ok_or(PlatformDirectoryError::Unavailable)?;
    Ok(roots.scoped(&application_id))
}
/// Requests that the host finish the app.
pub fn exit_app() {
    if let Some(host) = host_controller() {
        host.exit();
    }
}
/// Requests that the host move the app to the background.
pub fn background_app() {
    if let Some(host) = host_controller() {
        host.background();
    }
}

#[cfg(not(target_arch = "wasm32"))]
type Observer = Arc<dyn Fn(LifecycleEvent) + Send + Sync>;

#[cfg(not(target_arch = "wasm32"))]
fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
static LIFECYCLE_STATE: AtomicU8 = AtomicU8::new(LifecycleState::Created as u8);
static KEEP_SCREEN_ON: AtomicU8 = AtomicU8::new(0);

/// RAII lifecycle observer registration.
pub struct LifecycleObserver {
    id: u64,
}
impl Drop for LifecycleObserver {
    fn drop(&mut self) {
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut list) = observers().lock() {
            list.retain(|(id, _)| *id != self.id);
        }
        #[cfg(target_arch = "wasm32")]
        crate::thread_state::with(|state| state.lifecycle_observers.remove(self.id));
    }
}
/// Observes host lifecycle transitions until the returned handle is dropped.
#[cfg(not(target_arch = "wasm32"))]
pub fn observe_lifecycle(
    observer: impl Fn(LifecycleEvent) + Send + Sync + 'static,
) -> LifecycleObserver {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut list) = observers().lock() {
        list.push((id, Arc::new(observer)));
    }
    LifecycleObserver { id }
}
/// Observes host lifecycle transitions until the returned handle is dropped.
#[cfg(target_arch = "wasm32")]
pub fn observe_lifecycle(observer: impl Fn(LifecycleEvent) + 'static) -> LifecycleObserver {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    crate::thread_state::with(|state| {
        state
            .lifecycle_observers
            .add(id, std::rc::Rc::new(observer));
    });
    LifecycleObserver { id }
}
/// Publishes a lifecycle transition from the platform host.
pub fn dispatch_lifecycle(event: LifecycleEvent) {
    LIFECYCLE_STATE.store(event.to as u8, Ordering::Release);
    crate::media::on_lifecycle(event);
    #[cfg(not(target_arch = "wasm32"))]
    let callbacks = observers()
        .lock()
        .map(|list| {
            list.iter()
                .map(|(_, cb)| Arc::clone(cb))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    #[cfg(target_arch = "wasm32")]
    let callbacks = crate::thread_state::with(|state| state.lifecycle_observers.all());
    for callback in callbacks {
        callback(event);
    }
}

/// Returns the latest lifecycle state published by the platform host.
pub fn current_lifecycle_state() -> LifecycleState {
    match LIFECYCLE_STATE.load(Ordering::Acquire) {
        0 => LifecycleState::Created,
        1 => LifecycleState::Started,
        2 => LifecycleState::Resumed,
        3 => LifecycleState::Paused,
        4 => LifecycleState::Stopped,
        _ => LifecycleState::Destroyed,
    }
}

/// Publishes a platform lifecycle state and derives the transition source from
/// the framework's previous state.
///
/// Leaving the foreground runs every registered durable save first, inside the
/// budget the host allows, so an application never has to hook the transition
/// itself to persist its data.
pub fn dispatch_lifecycle_state(to: LifecycleState) {
    let from = current_lifecycle_state();
    if from == to {
        return;
    }
    if matches!(to, LifecycleState::Paused) {
        let outcome = run_durable_saves(durable_save_deadline());
        if matches!(
            outcome,
            DurableSaveOutcome::TimedOut | DurableSaveOutcome::Failed
        ) {
            log::warn!("cranpose: durable saves did not complete successfully: {outcome:?}");
        }
    }
    dispatch_lifecycle(LifecycleEvent { from, to });
}

/// The lifecycle state of a window or browser page that is `visible` and
/// has keyboard `focused`, mapped the way Compose Multiplatform maps desktop
/// windows: resumed while focused, paused while only visible, and stopped
/// while minimized, hidden or in a background tab.
pub fn window_lifecycle_state(visible: bool, focused: bool) -> LifecycleState {
    match (visible, focused) {
        (false, _) => LifecycleState::Stopped,
        (true, true) => LifecycleState::Resumed,
        (true, false) => LifecycleState::Paused,
    }
}

impl LifecycleState {
    /// Whether this state is at least as active as `other`, counting paused
    /// as started and stopped as created — Android's `isAtLeast`.
    pub fn is_at_least(self, other: LifecycleState) -> bool {
        lifecycle_level(self) >= lifecycle_level(other)
    }
}

fn lifecycle_level(state: LifecycleState) -> u8 {
    match state {
        LifecycleState::Destroyed => 0,
        LifecycleState::Created | LifecycleState::Stopped => 1,
        LifecycleState::Started | LifecycleState::Paused => 2,
        LifecycleState::Resumed => 3,
    }
}

fn next_lifecycle_step(from: LifecycleState, to: LifecycleState) -> Option<LifecycleState> {
    let rising = match lifecycle_level(from).cmp(&lifecycle_level(to)) {
        std::cmp::Ordering::Equal => return None,
        std::cmp::Ordering::Less => true,
        std::cmp::Ordering::Greater => false,
    };
    match (from, rising) {
        (LifecycleState::Destroyed, _) => None,
        (LifecycleState::Created | LifecycleState::Stopped, true) => Some(LifecycleState::Started),
        (LifecycleState::Started | LifecycleState::Paused, true) => Some(LifecycleState::Resumed),
        (LifecycleState::Resumed, _) => Some(LifecycleState::Paused),
        (LifecycleState::Started | LifecycleState::Paused, false) => Some(LifecycleState::Stopped),
        (LifecycleState::Created | LifecycleState::Stopped, false) => {
            Some(LifecycleState::Destroyed)
        }
    }
}

/// Moves the host lifecycle to `target` through every state in between, in
/// Android's order: a stopped app starts before it resumes, and a resumed one
/// pauses before it stops, so leaving the foreground always runs the durable
/// saves. Paused and started count as the same place, as do created and
/// stopped. Hosts whose platform reports only visibility and focus use this
/// instead of dispatching each transition themselves.
pub fn advance_lifecycle(target: LifecycleState) {
    while let Some(next) = next_lifecycle_step(current_lifecycle_state(), target) {
        dispatch_lifecycle_state(next);
    }
}

/// The `CompositionLocal` carrying the host's current lifecycle state.
///
/// [`ProvideLifecycle`] installs it; descendants read it and recompose on every
/// transition, so a screen can pause its own work without registering an
/// observer of its own.
pub fn local_lifecycle_state() -> cranpose_core::CompositionLocal<LifecycleState> {
    crate::composition_locals::cached_local(
        |locals| &locals.lifecycle,
        || cranpose_core::compositionLocalOf(current_lifecycle_state),
    )
}

/// The host's lifecycle state as observable state.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberLifecycleState() -> cranpose_core::State<LifecycleState> {
    let transitions = rememberLifecycleEvents();
    let state = cranpose_core::collectAsState(
        transitions,
        (),
        LifecycleEvent {
            from: current_lifecycle_state(),
            to: current_lifecycle_state(),
        },
    );
    cranpose_core::derivedStateOf(move || state.get().to)
}

/// Host lifecycle transitions as a composition-scoped stream.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberLifecycleEvents() -> cranpose_core::EventStream<LifecycleEvent> {
    cranpose_core::rememberEventStream((), |sender| {
        observe_lifecycle(move |event| sender.send(event))
    })
}

/// Provides the host's lifecycle state to descendant composables.
///
/// The application shell wraps its content in this once; screens then read
/// [`local_lifecycle_state`].
#[cranpose_macros::composable]
pub fn ProvideLifecycle(content: impl FnOnce()) {
    let state = rememberLifecycleState();
    let local = local_lifecycle_state();
    cranpose_core::CompositionLocalProvider([local.provides(state.get())], move || {
        content();
    });
}

#[cfg(test)]
#[path = "tests/host_tests.rs"]
mod tests;