Skip to main content

egui_pop_platform/
dirs.rs

1//! Where an application keeps what it writes for itself: its state, its
2//! logs, its crash reports. Read from the environment, as each platform
3//! names these places:
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! | | State | Logs |
9//! |---|---|---|
10//! | Linux and BSD | `$XDG_STATE_HOME/<app>` (`~/.local/state/<app>`) | `<state>/logs` |
11//! | macOS | `~/Library/Application Support/<app>` | `~/Library/Logs/<app>` |
12//! | Windows | `%LOCALAPPDATA%\<app>` | `<state>\logs` |
13//!
14//! Settings go to the configuration folder ([`config_dir`]). Crash reports go to `<state>/crashes`. Compiled files go to the
15//! platform's cache directory ([`cache_dir`], `egui_pop_tokens::cache`). Inside a Flatpak sandbox,
16//! `XDG_STATE_HOME` points into the application's own directory, so the
17//! same code finds the sandbox's place.
18//!
19//! Owned rather than `dirs` or `directories` (MIT OR Apache-2.0): three
20//! environment variables, and those crates have no state directory on
21//! macOS and Windows anyway.
22//!
23//! ```
24//! let dir = egui_pop_platform::dirs::state_dir_with("demo", |name| match name {
25//!     "XDG_STATE_HOME" => Some("/state".into()),
26//!     _ => None,
27//! });
28//! if cfg!(all(unix, not(target_os = "macos"))) {
29//!     assert_eq!(dir, Some("/state/demo".into()));
30//! }
31//! ```
32
33use std::path::{Path, PathBuf};
34
35/// The application's configuration folder, where its settings are kept
36/// (`AppBuilder::persist_in_config`): `~/.config/<app>`,
37/// `~/Library/Application Support/<app>`, `%APPDATA%\<app>`.
38pub use egui_pop_api::dirs::{config_dir, config_dir_with};
39
40/// The application's state directory, from the environment `env` gives
41/// (none: the variables it needs are missing).
42pub fn state_dir_with(app: &str, env: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
43    let absolute = |v: Option<String>| v.map(PathBuf::from).filter(|p| p.is_absolute());
44    let base = if cfg!(windows) {
45        absolute(env("LOCALAPPDATA"))?
46    } else if cfg!(target_os = "macos") {
47        absolute(env("HOME"))?.join("Library/Application Support")
48    } else {
49        match absolute(env("XDG_STATE_HOME")) {
50            Some(p) => p,
51            None => absolute(env("HOME"))?.join(".local/state"),
52        }
53    };
54    Some(base.join(app))
55}
56
57/// The application's state directory (see the module).
58pub fn state_dir(app: &str) -> Option<PathBuf> {
59    state_dir_with(app, |name| std::env::var(name).ok())
60}
61
62/// The application's log directory (see the module).
63pub fn log_dir(app: &str) -> Option<PathBuf> {
64    if cfg!(target_os = "macos") {
65        let home = std::env::var("HOME").ok().map(PathBuf::from)?;
66        return Some(home.join("Library/Logs").join(app));
67    }
68    state_dir(app).map(|d| d.join("logs"))
69}
70
71/// The system's temporary directory, the last resort when the
72/// environment names no place. The web has neither a file system nor a
73/// temporary directory (`std::env::temp_dir` panics there): a relative,
74/// empty path, where writes fail and are given up.
75pub fn temp_dir() -> PathBuf {
76    #[cfg(not(target_arch = "wasm32"))]
77    {
78        std::env::temp_dir()
79    }
80    #[cfg(target_arch = "wasm32")]
81    {
82        PathBuf::new()
83    }
84}
85
86/// This process's id; 0 on the web, which has no processes
87/// (`std::process::id` panics there).
88pub fn pid() -> u32 {
89    #[cfg(not(target_arch = "wasm32"))]
90    {
91        std::process::id()
92    }
93    #[cfg(target_arch = "wasm32")]
94    {
95        0
96    }
97}
98
99/// The application's crash report directory: `<state>/crashes`.
100pub fn crash_dir(app: &str) -> Option<PathBuf> {
101    state_dir(app).map(|d| d.join("crashes"))
102}
103
104/// Where egui-pop keeps the files it compiles for the application
105/// (`<platform cache>/<app>/egui-pop`): the directory of
106/// `egui_pop_tokens::cache::Cache::for_app`.
107pub fn cache_dir(app: &str) -> Option<PathBuf> {
108    egui_pop_core::tokens::cache::platform_dir(app)
109}
110
111/// Opens a file or a folder with what the system opens it with
112/// (`xdg-open`, `open`, `explorer`); returns at once.
113pub fn reveal(path: &Path) -> Result<(), String> {
114    let program = if cfg!(windows) {
115        "explorer"
116    } else if cfg!(target_os = "macos") {
117        "open"
118    } else {
119        "xdg-open"
120    };
121    #[cfg(not(target_arch = "wasm32"))]
122    {
123        std::process::Command::new(program)
124            .arg(path)
125            .stdout(std::process::Stdio::null())
126            .stderr(std::process::Stdio::null())
127            .spawn()
128            .map(|_| ())
129            .map_err(|e| format!("{program}: {e}"))
130    }
131    #[cfg(target_arch = "wasm32")]
132    {
133        let _ = (program, path);
134        Err("nothing opens files on the web".into())
135    }
136}