1use 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#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct PlatformDirectories {
21 pub data: PathBuf,
23 pub config: PathBuf,
25 pub cache: PathBuf,
27 pub documents: Option<PathBuf>,
29 pub temporary: PathBuf,
31 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#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
54pub enum PlatformDirectoryError {
55 #[error("application id must be one non-empty path component")]
57 InvalidApplicationId,
58 #[error("no application id has been registered")]
60 NoApplicationId,
61 #[error("platform directories are unavailable")]
63 Unavailable,
64}
65
66#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum LifecycleState {
69 Created,
71 Started,
73 Resumed,
75 Paused,
77 Stopped,
79 Destroyed,
81}
82
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
85pub struct LifecycleEvent {
86 pub from: LifecycleState,
88 pub to: LifecycleState,
90}
91
92pub trait HostController: Send + Sync {
94 fn set_keep_screen_on(&self, enabled: bool);
96 fn platform_directories(&self) -> Option<PlatformDirectories>;
98 fn exit(&self);
100 fn background(&self);
102 #[cfg(feature = "localization")]
105 fn preferred_languages(&self) -> Vec<String> {
106 Vec::new()
107 }
108 fn durable_save_deadline(&self) -> std::time::Duration {
113 DEFAULT_DURABLE_SAVE_DEADLINE
114 }
115}
116
117pub const DEFAULT_DURABLE_SAVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);
119
120pub 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
127pub 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
135pub 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}
142pub 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}
149pub fn host_controller() -> Option<HostControllerRef> {
151 controller().lock().ok().and_then(|slot| slot.clone())
152}
153pub 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
189pub 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
205pub fn clear_application_id() {
207 if let Ok(mut slot) = application_id_slot().lock() {
208 *slot = None;
209 }
210}
211
212pub fn application_id() -> Option<String> {
214 application_id_slot()
215 .lock()
216 .ok()
217 .and_then(|slot| slot.clone())
218}
219
220pub 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}
229pub fn exit_app() {
231 if let Some(host) = host_controller() {
232 host.exit();
233 }
234}
235pub 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
254pub 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#[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#[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}
290pub 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
310pub 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
322pub 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
345pub 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 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
392pub 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
404pub 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#[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#[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#[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;