Skip to main content

day_process/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! What a Day process has before, and without, a user interface: its identity and directories,
5//! the services that start with it, native notification delivery, and the panic guard every
6//! foreign entry point runs through.
7//!
8//! Nothing here depends on the widget tree, a toolkit or the reactive runtime, so a background
9//! worker, a push handler, an app extension or a command-line tool links this crate alone.
10//! `day-spec` and `day-core` build on it.
11//!
12//! Exactly one copy of this crate may be linked into a process: the registries below are
13//! link-time slices, and a second copy would have its own, which the host never runs. The
14//! manifest's `links` key makes Cargo refuse a dependency graph that resolves two.
15
16pub use linkme;
17
18/// How fully a platform provides something a caller asks about.
19#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
20pub enum Support {
21    Native,
22    Emulated,
23    /// The default: what an unimplemented capability answers everywhere.
24    #[default]
25    Unsupported,
26}
27
28/// Containment for FFI entry points: native callbacks, JNI up-calls, posted-closure
29/// trampolines. A Rust panic unwinding out of an `extern "C"` frame is undefined
30/// behavior (an abort), so every backend trampoline runs its body through
31/// [`ffi_guard::contain`]: a caught panic is reported, the installed recovery hook
32/// restores runtime coherence (day-core installs the reactive runtime's
33/// `recover_from_panic` at boot), and the given default is returned.
34pub mod ffi_guard {
35    use std::sync::OnceLock;
36
37    static RECOVERY: OnceLock<fn()> = OnceLock::new();
38
39    /// Install the post-panic recovery hook (idempotent; first install wins). day-core
40    /// registers `day_reactive::recover_from_panic` here so a contained panic cannot
41    /// leave the reactive observer stack stranded.
42    pub fn set_recovery(f: fn()) {
43        let _ = RECOVERY.set(f);
44    }
45
46    /// Run `f`, containing any panic; on panic, report, run the recovery hook, and
47    /// return `default`.
48    pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
49        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
50            Ok(r) => r,
51            Err(payload) => {
52                let msg = payload
53                    .downcast_ref::<&str>()
54                    .map(std::string::ToString::to_string)
55                    .or_else(|| payload.downcast_ref::<String>().cloned())
56                    .unwrap_or_else(|| "<non-string panic>".into());
57                log::error!("panic contained at an FFI boundary: {msg}");
58                if let Some(recover) = RECOVERY.get() {
59                    recover();
60                }
61                default
62            }
63        }
64    }
65}
66
67/// Process services that must initialize before a window or reactive tree exists.
68///
69/// Optional parts register initializers at link time. Initializers run on the native startup
70/// thread once per process and must return promptly. They may register OS callbacks; they must
71/// not access UI signals or mount widgets. Android services can initialize this registry after
72/// attaching the JVM without starting an Activity.
73pub mod services {
74    use std::sync::Once;
75
76    /// A process initializer supplied by an optional part.
77    pub struct Service {
78        pub name: &'static str,
79        pub initialize: fn(),
80    }
81
82    #[cfg(not(target_arch = "wasm32"))]
83    #[linkme::distributed_slice]
84    pub static SERVICES: [Service];
85
86    /// Initialize linked process services. A native host calls this after its runtime is ready.
87    pub fn initialize() {
88        static ONCE: Once = Once::new();
89        ONCE.call_once(|| {
90            #[cfg(not(target_arch = "wasm32"))]
91            for service in SERVICES {
92                (service.initialize)();
93            }
94        });
95    }
96
97    /// Native notification delivery before or after a window exists. Handlers must return promptly
98    /// and use a main-thread setter to update UI state. Payloads are JSON from the platform.
99    #[derive(Clone)]
100    pub enum NotificationEvent {
101        Registered(Vec<u8>),
102        RegistrationFailed(String),
103        Received { payload: String, opened: bool },
104    }
105
106    impl std::fmt::Debug for NotificationEvent {
107        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108            match self {
109                Self::Registered(_) => f.debug_tuple("Registered").finish_non_exhaustive(),
110                Self::RegistrationFailed(error) => {
111                    f.debug_tuple("RegistrationFailed").field(error).finish()
112                }
113                Self::Received { opened, .. } => f
114                    .debug_struct("Received")
115                    .field("opened", opened)
116                    .finish_non_exhaustive(),
117            }
118        }
119    }
120
121    #[cfg(not(target_arch = "wasm32"))]
122    #[linkme::distributed_slice]
123    pub static NOTIFICATION_HANDLERS: [fn(&NotificationEvent)];
124
125    /// Forward a native delegate callback to linked optional parts.
126    #[expect(
127        clippy::needless_pass_by_value,
128        reason = "public signature; toolkits hand over the event they built"
129    )]
130    pub fn notification(event: NotificationEvent) {
131        #[cfg(not(target_arch = "wasm32"))]
132        for handler in NOTIFICATION_HANDLERS {
133            handler(&event);
134        }
135        #[cfg(target_arch = "wasm32")]
136        let _ = event;
137    }
138}
139
140/// A route requested from outside the user interface, at any lifecycle stage, from any thread:
141/// the rail a notification tap or a shortcut navigates through (docs/notify.md).
142///
143/// The request is buffered here, below the UI, so a part that receives a tap in a process with
144/// no window yet (Android delivers one on a JNI thread, Apple on a delegate callback, and both can
145/// arrive before the app has launched) records it without linking the navigation code. The UI
146/// runtime takes the buffer once routes exist and installs a notifier to hear about later
147/// requests. The newest request wins: a user who taps twice gets the second destination.
148pub mod routes {
149    use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
150
151    static REQUESTED: Mutex<Option<String>> = Mutex::new(None);
152    static NOTIFIER: OnceLock<fn()> = OnceLock::new();
153
154    fn slot() -> MutexGuard<'static, Option<String>> {
155        // A panic while holding this lock would otherwise wedge every later navigation; the
156        // buffer is one `Option<String>`, so recovering the value is always safe.
157        REQUESTED.lock().unwrap_or_else(PoisonError::into_inner)
158    }
159
160    /// Ask the app to navigate to `route`. An empty route is ignored.
161    pub fn request(route: &str) {
162        if route.is_empty() {
163            return;
164        }
165        *slot() = Some(route.to_owned());
166        if let Some(notify) = NOTIFIER.get() {
167            notify();
168        }
169    }
170
171    /// The buffered route, left in place.
172    #[must_use]
173    pub fn requested() -> Option<String> {
174        slot().clone()
175    }
176
177    /// Take the buffered route, if any.
178    #[must_use]
179    pub fn take() -> Option<String> {
180        slot().take()
181    }
182
183    /// Install the function called after each [`request`], on the requesting thread. The UI
184    /// runtime installs one that applies the route on its own thread. The first install wins.
185    pub fn set_notifier(notify: fn()) {
186        let _ = NOTIFIER.set(notify);
187    }
188}
189
190// ---------------------------------------------------------------------------
191// App directories (docs/fs.md "Where files live")
192// ---------------------------------------------------------------------------
193
194/// Where an app keeps its own files: its data, cache and configuration directories, each a
195/// folder named after the app id in the place its platform sets aside for that kind of file
196/// (docs/fs.md "Where files live"). Every Day crate that stores files resolves them here, so an
197/// app's database, documents, caches, settings file and remembered window frames sit together
198/// and apart from every other app's.
199///
200/// These only resolve paths; nothing is created until something is written. Each is `None` where
201/// the platform has no such directory: the web, or an Android or HarmonyOS process whose host
202/// passed none.
203pub mod storage {
204    use std::path::PathBuf;
205
206    /// The app's id, `[app] id` from Day.toml: `DAY_APP_ID` from `day launch`, else the value
207    /// `day build` baked in, else the executable's name (a test binary or a bare `cargo run`).
208    /// Made safe as a single folder name.
209    #[must_use]
210    pub fn app_id() -> String {
211        std::env::var("DAY_APP_ID")
212            .ok()
213            .filter(|id| !id.is_empty())
214            .or_else(|| {
215                option_env!("DAY_APP_ID")
216                    .filter(|id| !id.is_empty())
217                    .map(str::to_owned)
218            })
219            .or_else(|| {
220                let exe = std::env::current_exe().ok()?;
221                exe.file_stem()?.to_str().map(str::to_owned)
222            })
223            .map_or_else(|| "day-app".to_owned(), |id| folder_name(&id))
224    }
225
226    /// The app's data directory, for what it cannot recreate: databases, documents, downloads
227    /// the user kept. Application Support on Apple platforms (inside the container when
228    /// sandboxed), `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, the app's files
229    /// directory on Android and HarmonyOS. `DAY_DATA_DIR` replaces it.
230    #[must_use]
231    pub fn data_dir() -> Option<PathBuf> {
232        resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
233    }
234
235    /// [`data_dir`] for the app `app_id` rather than this process's own: a host that keeps a
236    /// folder per hosted app (a day-lite superapp, a crash reporter's store), or a tool finding
237    /// where an app it launched writes. On Android and HarmonyOS, where the host's directory is
238    /// already the one app's, the id changes nothing.
239    #[must_use]
240    pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
241        resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
242    }
243
244    /// The app's cache directory, for what it can fetch or compute again: the system may clear
245    /// it, and backups skip it. Caches on Apple platforms, `%LOCALAPPDATA%\<id>\cache` on
246    /// Windows, `$XDG_CACHE_HOME` on Linux, the app's cache directory on Android and HarmonyOS.
247    /// `DAY_CACHE_DIR` replaces it; with only `DAY_DATA_DIR` set it is that directory's `cache`.
248    #[must_use]
249    pub fn cache_dir() -> Option<PathBuf> {
250        resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
251    }
252
253    /// The app's configuration directory, for small settings files: Application Support on
254    /// Apple platforms (whose preferences proper are the user defaults), the roaming
255    /// `%APPDATA%` on Windows, `$XDG_CONFIG_HOME` on Linux. With `DAY_DATA_DIR` set (as the
256    /// Android and HarmonyOS hosts do) it is that directory's `config`.
257    #[must_use]
258    pub fn config_dir() -> Option<PathBuf> {
259        resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
260    }
261
262    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
263    enum Dir {
264        Data,
265        Cache,
266        Config,
267    }
268
269    /// The platform families whose conventions differ.
270    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
271    enum Os {
272        /// macOS and iOS: `~/Library`, which is the app's container when sandboxed.
273        Apple,
274        Windows,
275        /// Android and HarmonyOS: the host passes the app's private directories.
276        Hosted,
277        /// Linux and the BSDs: the XDG base directories.
278        Unix,
279        Web,
280    }
281
282    impl Os {
283        const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
284            Os::Apple
285        } else if cfg!(target_os = "windows") {
286            Os::Windows
287        } else if cfg!(any(target_os = "android", target_env = "ohos")) {
288            Os::Hosted
289        } else if cfg!(target_family = "wasm") {
290            Os::Web
291        } else {
292            Os::Unix
293        };
294    }
295
296    /// An environment variable naming a directory: set, non-empty and absolute, else ignored.
297    fn env_path(name: &str) -> Option<PathBuf> {
298        let path = PathBuf::from(std::env::var_os(name)?);
299        path.is_absolute().then_some(path)
300    }
301
302    /// One folder name: no separators, no `.`/`..`, nothing a filesystem rejects.
303    fn folder_name(id: &str) -> String {
304        let name: String = id
305            .chars()
306            .map(|c| match c {
307                '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
308                c if c.is_control() => '_',
309                c => c,
310            })
311            .collect();
312        match name.trim() {
313            "" | "." | ".." => "day-app".to_owned(),
314            name => name.to_owned(),
315        }
316    }
317
318    /// The pure resolution, over a platform and an environment, so every platform's rules are
319    /// testable on any host.
320    fn resolve(
321        dir: Dir,
322        os: Os,
323        id: &str,
324        var: &dyn Fn(&str) -> Option<PathBuf>,
325    ) -> Option<PathBuf> {
326        // The explicit overrides: a mobile host's own directories, or a test's scratch root.
327        if dir == Dir::Cache
328            && let Some(cache) = var("DAY_CACHE_DIR")
329        {
330            return Some(cache);
331        }
332        if let Some(data) = var("DAY_DATA_DIR") {
333            return Some(match dir {
334                Dir::Data => data,
335                Dir::Cache => data.join("cache"),
336                Dir::Config => data.join("config"),
337            });
338        }
339        let home = || var("HOME");
340        match os {
341            // One expression serves sandboxed and unsandboxed apps: inside the App Sandbox,
342            // and always on iOS, `HOME` is the container's Data folder, so the same Library
343            // path lands inside it. Apple asks for a bundle-id folder within Application
344            // Support and Caches either way. XDG variables are ignored here: a Finder launch
345            // never sees a shell's, so honoring them would split one app's data across two
346            // places depending on how it was started.
347            Os::Apple => {
348                let library = home()?.join("Library");
349                let base = match dir {
350                    Dir::Data | Dir::Config => library.join("Application Support"),
351                    Dir::Cache => library.join("Caches"),
352                };
353                Some(base.join(id))
354            }
355            // Local for data and caches: a database or cache roams badly, and a DPAPI-sealed
356            // file cannot be read on another machine. Roaming for the small settings files.
357            Os::Windows => {
358                let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
359                let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
360                match dir {
361                    Dir::Data => Some(local()?.join(id)),
362                    Dir::Cache => Some(local()?.join(id).join("cache")),
363                    Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
364                }
365            }
366            Os::Unix => {
367                let (xdg, fallback) = match dir {
368                    Dir::Data => ("XDG_DATA_HOME", ".local/share"),
369                    Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
370                    Dir::Config => ("XDG_CONFIG_HOME", ".config"),
371                };
372                Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
373            }
374            Os::Hosted | Os::Web => None,
375        }
376    }
377
378    #[cfg(test)]
379    mod tests {
380        use super::*;
381        use std::collections::HashMap;
382
383        /// The resolved path as text. `Path::join` uses the host's separator, so on a Windows host
384        /// another platform's path comes back with `\` between the joined parts; the expectations
385        /// are that platform's own, so its separators are compared as `/`.
386        fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
387            let vars: HashMap<&str, &str> = vars.iter().copied().collect();
388            let var = |name: &str| vars.get(name).map(PathBuf::from);
389            resolve(dir, os, "dev.example.notes", &var).map(|p| {
390                let text = p.display().to_string();
391                if os == Os::Windows {
392                    text
393                } else {
394                    text.replace('\\', "/")
395                }
396            })
397        }
398
399        #[test]
400        fn apple_uses_library_folders_named_for_the_app() {
401            let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
402            let support = "/Users/ada/Library/Application Support/dev.example.notes";
403            assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
404            assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
405            assert_eq!(
406                at(Os::Apple, Dir::Cache, &home).as_deref(),
407                Some("/Users/ada/Library/Caches/dev.example.notes")
408            );
409            // A sandboxed app's HOME is its container, so its folders land inside it.
410            let container = [(
411                "HOME",
412                "/Users/ada/Library/Containers/dev.example.notes/Data",
413            )];
414            assert_eq!(
415                at(Os::Apple, Dir::Data, &container).as_deref(),
416                Some(
417                    "/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
418                )
419            );
420        }
421
422        #[test]
423        fn windows_keeps_data_local_and_settings_roaming() {
424            let vars = [
425                ("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
426                ("APPDATA", r"C:\Users\ada\AppData\Roaming"),
427            ];
428            let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
429            assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
430            assert!(data.ends_with("dev.example.notes"), "{data}");
431            let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
432            assert!(cache.ends_with("cache"), "{cache}");
433            let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
434            assert!(
435                config.starts_with(r"C:\Users\ada\AppData\Roaming"),
436                "{config}"
437            );
438        }
439
440        #[test]
441        fn unix_follows_xdg_then_home() {
442            let xdg = [
443                ("HOME", "/home/ada"),
444                ("XDG_DATA_HOME", "/data"),
445                ("XDG_CACHE_HOME", "/cache"),
446                ("XDG_CONFIG_HOME", "/config"),
447            ];
448            assert_eq!(
449                at(Os::Unix, Dir::Data, &xdg).as_deref(),
450                Some("/data/dev.example.notes")
451            );
452            assert_eq!(
453                at(Os::Unix, Dir::Cache, &xdg).as_deref(),
454                Some("/cache/dev.example.notes")
455            );
456            assert_eq!(
457                at(Os::Unix, Dir::Config, &xdg).as_deref(),
458                Some("/config/dev.example.notes")
459            );
460            let home = [("HOME", "/home/ada")];
461            assert_eq!(
462                at(Os::Unix, Dir::Data, &home).as_deref(),
463                Some("/home/ada/.local/share/dev.example.notes")
464            );
465            assert_eq!(
466                at(Os::Unix, Dir::Cache, &home).as_deref(),
467                Some("/home/ada/.cache/dev.example.notes")
468            );
469            assert_eq!(
470                at(Os::Unix, Dir::Config, &home).as_deref(),
471                Some("/home/ada/.config/dev.example.notes")
472            );
473        }
474
475        #[test]
476        fn hosts_and_tests_override_every_platform() {
477            let host = [
478                ("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
479                ("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
480            ];
481            for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
482                assert_eq!(
483                    at(os, Dir::Data, &host).as_deref(),
484                    Some("/data/user/0/dev.example.notes/files")
485                );
486                assert_eq!(
487                    at(os, Dir::Cache, &host).as_deref(),
488                    Some("/data/user/0/dev.example.notes/cache")
489                );
490            }
491            let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
492            assert_eq!(
493                at(Os::Apple, Dir::Cache, &scratch).as_deref(),
494                Some("/tmp/run/cache")
495            );
496            assert_eq!(
497                at(Os::Apple, Dir::Config, &scratch).as_deref(),
498                Some("/tmp/run/config")
499            );
500            // Without a host directory there is nowhere to put anything.
501            assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
502            assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
503        }
504
505        #[test]
506        fn app_ids_become_one_folder_name() {
507            assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
508            assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
509            assert_eq!(folder_name(".."), "day-app");
510            assert_eq!(folder_name(""), "day-app");
511        }
512    }
513}