Skip to main content

eframe/native/
file_storage.rs

1use std::{
2    collections::HashMap,
3    io::Write as _,
4    path::{Path, PathBuf},
5};
6
7/// The folder where `eframe` will store its state.
8///
9/// The given `app_id` is either the
10/// [`egui::ViewportBuilder::app_id`] of [`crate::NativeOptions::viewport`]
11/// or the title argument to [`crate::run_native`].
12///
13/// On native, the path is:
14/// * Linux:   `/home/UserName/.local/share/APP_ID`
15/// * macOS:   `/Users/UserName/Library/Application Support/APP_ID`
16/// * Windows: `C:\Users\UserName\AppData\Roaming\APP_ID\data`
17pub fn storage_dir(app_id: &str) -> Option<PathBuf> {
18    use egui::os::OperatingSystem as OS;
19    use std::env::var_os;
20    match OS::from_target_os() {
21        OS::Nix => var_os("XDG_DATA_HOME")
22            .map(PathBuf::from)
23            .filter(|p| p.is_absolute())
24            .or_else(|| std::env::home_dir().map(|p| p.join(".local").join("share")))
25            .map(|p| {
26                p.join(
27                    app_id
28                        .to_lowercase()
29                        .replace(|c: char| c.is_ascii_whitespace(), ""),
30                )
31            }),
32        OS::Mac => std::env::home_dir().map(|p| {
33            p.join("Library")
34                .join("Application Support")
35                .join(app_id.replace(|c: char| c.is_ascii_whitespace(), "-"))
36        }),
37        OS::Windows => roaming_appdata().map(|p| p.join(app_id).join("data")),
38        OS::Unknown | OS::Android | OS::IOS => None,
39    }
40}
41
42// Adapted from
43// https://github.com/rust-lang/cargo/blob/6e11c77384989726bb4f412a0e23b59c27222c34/crates/home/src/windows.rs#L19-L37
44#[cfg(all(windows, not(target_vendor = "uwp")))]
45#[expect(unsafe_code)]
46fn roaming_appdata() -> Option<PathBuf> {
47    use core::ptr;
48    use core::slice;
49    use std::ffi::OsString;
50    use std::os::windows::ffi::OsStringExt as _;
51
52    use windows_sys::Win32::Foundation::S_OK;
53    use windows_sys::Win32::System::Com::CoTaskMemFree;
54    use windows_sys::Win32::UI::Shell::{
55        FOLDERID_RoamingAppData, KF_FLAG_DONT_VERIFY, SHGetKnownFolderPath,
56    };
57
58    unsafe extern "C" {
59        fn wcslen(buf: *const u16) -> usize;
60    }
61    let mut path_raw = ptr::null_mut();
62
63    // SAFETY: SHGetKnownFolderPath allocates for us, we don't pass any pointers to it.
64    // See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
65    let result = unsafe {
66        SHGetKnownFolderPath(
67            &FOLDERID_RoamingAppData,
68            KF_FLAG_DONT_VERIFY as u32,
69            core::ptr::null_mut(),
70            &raw mut path_raw,
71        )
72    };
73
74    let path = if result == S_OK {
75        // SAFETY: SHGetKnownFolderPath indicated success and is supposed to allocate a null-terminated string for us.
76        let path_slice = unsafe { slice::from_raw_parts(path_raw, wcslen(path_raw)) };
77        Some(PathBuf::from(OsString::from_wide(path_slice)))
78    } else {
79        None
80    };
81
82    // SAFETY:
83    // This memory got allocated by SHGetKnownFolderPath, we didn't touch anything in the process.
84    // A null ptr is a no-op for `CoTaskMemFree`, so in case this failed we're still good.
85    // https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemfree
86    unsafe { CoTaskMemFree(path_raw.cast()) };
87
88    path
89}
90
91#[cfg(any(not(windows), target_vendor = "uwp"))]
92fn roaming_appdata() -> Option<PathBuf> {
93    None
94}
95
96// ----------------------------------------------------------------------------
97
98/// A key-value store backed by a [RON](https://github.com/ron-rs/ron) file on disk.
99/// Used to restore egui state, glow window position/size and app state.
100pub struct FileStorage {
101    ron_filepath: PathBuf,
102    kv: HashMap<String, String>,
103    dirty: bool,
104    last_save_join_handle: Option<std::thread::JoinHandle<()>>,
105}
106
107impl Drop for FileStorage {
108    fn drop(&mut self) {
109        if let Some(join_handle) = self.last_save_join_handle.take() {
110            profiling::scope!("wait_for_save");
111            join_handle.join().ok();
112        }
113    }
114}
115
116impl FileStorage {
117    /// Store the state in this .ron file.
118    pub(crate) fn from_ron_filepath(ron_filepath: impl Into<PathBuf>) -> Self {
119        profiling::function_scope!();
120        let ron_filepath: PathBuf = ron_filepath.into();
121        log::debug!("Loading app state from {}…", ron_filepath.display());
122        Self {
123            kv: read_ron(&ron_filepath).unwrap_or_default(),
124            ron_filepath,
125            dirty: false,
126            last_save_join_handle: None,
127        }
128    }
129
130    /// Find a good place to put the files that the OS likes.
131    pub fn from_app_id(app_id: &str) -> Option<Self> {
132        profiling::function_scope!();
133        if let Some(data_dir) = storage_dir(app_id) {
134            if let Err(err) = std::fs::create_dir_all(&data_dir) {
135                log::warn!(
136                    "Saving disabled: Failed to create app path at {}: {err}",
137                    data_dir.display()
138                );
139                None
140            } else {
141                Some(Self::from_ron_filepath(data_dir.join("app.ron")))
142            }
143        } else {
144            log::warn!("Saving disabled: Failed to find path to data_dir.");
145            None
146        }
147    }
148}
149
150impl crate::Storage for FileStorage {
151    fn get_string(&self, key: &str) -> Option<String> {
152        self.kv.get(key).cloned()
153    }
154
155    fn set_string(&mut self, key: &str, value: String) {
156        if self.kv.get(key) != Some(&value) {
157            self.kv.insert(key.to_owned(), value);
158            self.dirty = true;
159        }
160    }
161
162    fn remove_string(&mut self, key: &str) {
163        self.kv.remove(key);
164        self.dirty = true;
165    }
166
167    fn flush(&mut self) {
168        if self.dirty {
169            profiling::scope!("FileStorage::flush");
170            self.dirty = false;
171
172            let file_path = self.ron_filepath.clone();
173            let kv = self.kv.clone();
174
175            if let Some(join_handle) = self.last_save_join_handle.take() {
176                // wait for previous save to complete.
177                join_handle.join().ok();
178            }
179
180            let result = std::thread::Builder::new()
181                .name("eframe_persist".to_owned())
182                .spawn(move || {
183                    save_to_disk(&file_path, &kv);
184                });
185            match result {
186                Ok(join_handle) => {
187                    self.last_save_join_handle = Some(join_handle);
188                }
189                Err(err) => {
190                    log::warn!("Failed to spawn thread to save app state: {err}");
191                }
192            }
193        }
194    }
195}
196
197fn save_to_disk(file_path: &PathBuf, kv: &HashMap<String, String>) {
198    profiling::function_scope!();
199
200    if let Some(parent_dir) = file_path.parent()
201        && !parent_dir.exists()
202        && let Err(err) = std::fs::create_dir_all(parent_dir)
203    {
204        log::warn!("Failed to create directory {}: {err}", parent_dir.display());
205    }
206
207    match std::fs::File::create(file_path) {
208        Ok(file) => {
209            let mut writer = std::io::BufWriter::new(file);
210            let config = Default::default();
211
212            profiling::scope!("ron::serialize");
213            if let Err(err) = ron::Options::default()
214                .to_io_writer_pretty(&mut writer, &kv, config)
215                .and_then(|()| writer.flush().map_err(|err| err.into()))
216            {
217                log::warn!("Failed to serialize app state: {err}");
218            } else {
219                log::trace!("Persisted to {}", file_path.display());
220            }
221        }
222        Err(err) => {
223            log::warn!("Failed to create file {}: {err}", file_path.display());
224        }
225    }
226}
227
228// ----------------------------------------------------------------------------
229
230fn read_ron<T>(ron_path: impl AsRef<Path>) -> Option<T>
231where
232    T: serde::de::DeserializeOwned,
233{
234    profiling::function_scope!();
235    match std::fs::File::open(ron_path) {
236        Ok(file) => {
237            let reader = std::io::BufReader::new(file);
238            match ron::de::from_reader(reader) {
239                Ok(value) => Some(value),
240                Err(err) => {
241                    log::warn!("Failed to parse RON: {err}");
242                    None
243                }
244            }
245        }
246        Err(_err) => {
247            // File probably doesn't exist. That's fine.
248            None
249        }
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    fn directories_storage_dir(app_id: &str) -> Option<PathBuf> {
258        directories::ProjectDirs::from("", "", app_id)
259            .map(|proj_dirs| proj_dirs.data_dir().to_path_buf())
260    }
261
262    #[test]
263    fn storage_path_matches_directories() {
264        use super::storage_dir;
265        for app_id in [
266            "MyApp", "My App", "my_app", "my-app", "My.App", "my/app", "my:app", r"my\app",
267        ] {
268            assert_eq!(directories_storage_dir(app_id), storage_dir(app_id));
269        }
270    }
271}