Skip to main content

hyprforge_paths/
lib.rs

1//! Where Hyprforge keeps things, and how it writes them.
2//!
3//! Every app in the suite needs these two answers and nothing else from
4//! them: which directory is mine, and how do I replace a file without
5//! ever leaving a half-written one on disk. Neither question has
6//! anything to do with Hyprland, a GUI toolkit, or Lua, so neither does
7//! this crate — it has no dependencies at all.
8//!
9//! Paths that *are* Hyprland-specific (`hypr/hyprforge/*.lua`, the
10//! generated config artifacts) live in `hyprforge-core` instead.
11//!
12//! [`user_dirs`] is the one module with a third answer — where *your*
13//! Pictures and Downloads are — and it belongs here for the same reason:
14//! two apps ask it, and it needs nothing but `std`.
15
16pub mod user_dirs;
17
18use std::path::PathBuf;
19
20/// `$XDG_CONFIG_HOME`, falling back to `~/.config`.
21pub fn config_home() -> PathBuf {
22    if let Some(dir) = std::env::var_os("XDG_CONFIG_HOME") {
23        let dir = PathBuf::from(dir);
24        if dir.is_absolute() {
25            return dir;
26        }
27    }
28    let home = std::env::var_os("HOME").expect("HOME must be set");
29    PathBuf::from(home).join(".config")
30}
31
32
33/// `$XDG_CONFIG_HOME/hyprforge` — canonical storage for all Hyprforge-owned
34/// config (display profiles, window-rules TOML).
35pub fn hyprforge_config_dir() -> PathBuf {
36    config_home().join("hyprforge")
37}
38
39/// `$XDG_DATA_HOME`, falling back to `~/.local/share` — the XDG base
40/// directory for user-specific data, as opposed to config. Added for
41/// `hyprforge-fileops`, which needs it for the trash spec's home trash
42/// (`$XDG_DATA_HOME/Trash`); mirrors [`config_home`] exactly; per the XDG
43/// spec a relative value is invalid and must be treated as unset.
44pub fn data_home() -> PathBuf {
45    if let Some(dir) = std::env::var_os("XDG_DATA_HOME") {
46        let dir = PathBuf::from(dir);
47        if dir.is_absolute() {
48            return dir;
49        }
50    }
51    let home = std::env::var_os("HOME").expect("HOME must be set");
52    PathBuf::from(home).join(".local").join("share")
53}
54
55/// The lock screen's theme, written by Settings and read by
56/// `hyprforge-lock`. The greeter cannot use this one — it runs as its own
57/// user and a home directory is `drwx------` — so it reads an exported
58/// copy instead.
59pub fn lock_toml_path() -> PathBuf {
60    hyprforge_config_dir().join("lock.toml")
61}
62
63/// The Appearance module's stored settings, read when resolving the
64/// shared theme.
65pub fn appearance_toml_path() -> PathBuf {
66    hyprforge_config_dir().join("appearance.toml")
67}
68
69/// Which tray icons the user wants, written by Settings and re-read by
70/// `hyprforge-trayd` on every poll so a toggle takes effect without
71/// restarting anything.
72pub fn tray_toml_path() -> PathBuf {
73    hyprforge_config_dir().join("tray.toml")
74}
75
76/// The emoji picker's own preferences — currently just the default skin
77/// tone a long-press (or its keyboard equivalent) sets. Lives beside
78/// `tray.toml`/`appearance.toml` rather than the picker inventing its own
79/// directory, for the same reason every other single-file Hyprforge
80/// setting does: one place a person restoring their dotfiles from a
81/// backup already knows to look. A missing file here is first-run, never
82/// an error — see `hyprforge-emojimenu::config`'s own doc for how it
83/// tells that apart from a file that exists but will not parse.
84pub fn emojimenu_toml_path() -> PathBuf {
85    hyprforge_config_dir().join("emojimenu.toml")
86}
87
88/// The file browser's remembered state — sort order, view mode, whether
89/// the preview pane is on, window size. Same one-file-beside-the-others
90/// convention as `tray.toml`/`emojimenu.toml`.
91pub fn files_toml_path() -> PathBuf {
92    hyprforge_config_dir().join("files.toml")
93}
94
95/// The file browser's *hand-written* configuration — key bindings, and
96/// later menus and behaviour switches.
97///
98/// A separate file from [`files_toml_path`] because the two have
99/// different writers. `files.toml` is state the app rewrites whole on
100/// every save, including every time a window resize settles, and a
101/// whole-struct rewrite drops comments and reorders tables. Anything a
102/// person writes by hand, comments and all, has to live where the app
103/// never writes.
104pub fn files_config_toml_path() -> PathBuf {
105    hyprforge_config_dir().join("files-config.toml")
106}
107
108/// The image viewer's remembered state — window size, and whether the
109/// filmstrip and info panel are showing.
110///
111/// The same two-file split the file browser has, and for the same
112/// reason; see [`media_config_toml_path`].
113///
114/// Note what is *not* here: the order pictures are shown in. That is the
115/// file manager's setting, read out of [`files_toml_path`], so the two
116/// windows cannot come to disagree about which picture is next.
117pub fn media_toml_path() -> PathBuf {
118    hyprforge_config_dir().join("media.toml")
119}
120
121/// The image viewer's *hand-written* configuration — its key bindings.
122///
123/// Separate from [`media_toml_path`] because the two have different
124/// writers, exactly as `files-config.toml` is separate from
125/// `files.toml`: one is rewritten whole every time a window resize
126/// settles, and a whole-struct rewrite drops comments and reorders
127/// tables.
128pub fn media_config_toml_path() -> PathBuf {
129    hyprforge_config_dir().join("media-config.toml")
130}
131
132/// Where the clipboard manager keeps its history. Its own subdirectory,
133/// not a file directly under `hyprforge_config_dir()`, because the index
134/// is one file but image content is one file *per entry* — see
135/// [`clipboard_images_dir`] — and both need a directory to live in.
136pub fn clipboard_dir() -> PathBuf {
137    hyprforge_config_dir().join("clipboard")
138}
139
140/// The clipboard history's index: ids, timestamps, pins, text content and
141/// image *references*. Never image bytes themselves — see
142/// [`clipboard_images_dir`] for why those live elsewhere.
143pub fn clipboard_index_path() -> PathBuf {
144    clipboard_dir().join("history.toml")
145}
146
147/// Where clipboard image bytes are kept, one file per entry, named by its
148/// content hash. Inlining a screenshot's bytes into the index as base64
149/// would make that file unreadable by eye, unparseable at any real size,
150/// and would mean rewriting the whole index — text entries included —
151/// every time a single image is added or evicted.
152pub fn clipboard_images_dir() -> PathBuf {
153    clipboard_dir().join("images")
154}
155
156/// The path for one clipboard entry's image bytes, keyed by its
157/// `EntryId` (as returned by `EntryId::as_str`) so the index and the
158/// file agree on which entry a file belongs to without either side
159/// having to store the other's full path.
160pub fn clipboard_image_path(id: &str) -> PathBuf {
161    clipboard_images_dir().join(format!("{id}.bin"))
162}
163
164/// Write `contents` to `path` atomically and durably: write a sibling temp
165/// file, flush it to disk, rename over the target, then flush the
166/// directory.
167///
168/// The rename alone makes the change atomic *for a concurrent reader* —
169/// nobody ever sees half a file. It does not make it survive a power
170/// loss, and those are two different guarantees that are easy to
171/// conflate. Without the first fsync the rename can land while the new
172/// file's contents are still only in page cache, so the file comes back
173/// empty; without the second the rename itself can be lost, so the file
174/// comes back missing or with its previous contents.
175///
176/// The cost is one flush per config write. These files are written when
177/// a user changes a setting or a layout settles, not in a loop, and what
178/// is being protected is the only record of something the user cannot
179/// reconstruct — their profiles, their keybinds.
180pub fn write_atomic(path: &std::path::Path, contents: &str) -> std::io::Result<()> {
181    write_atomic_bytes(path, contents.as_bytes())
182}
183
184/// The same guarantee as [`write_atomic`], for content that is not text —
185/// clipboard image bytes, specifically. Kept as a second entry point
186/// rather than making [`write_atomic`] generic over `AsRef<[u8]>`. so
187/// every existing caller (all of which pass `&str`) keeps its exact
188/// signature.
189pub fn write_atomic_bytes(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> {
190    if let Some(parent) = path.parent() {
191        std::fs::create_dir_all(parent)?;
192    }
193
194    // Unique per call, not a fixed `<name>.tmp`. Two processes write some
195    // of these files — `monitors.lua` has both the display daemon and the
196    // Settings app as writers — and with one shared temp name the second
197    // `create` truncates the first writer's half-written file, so the
198    // bytes that get renamed into place can be an interleaving of both.
199    // The fsync below then commits that corruption to disk.
200    //
201    // Process id and a counter rather than randomness: no dependency, and
202    // the only collision that matters is between concurrent writers,
203    // which these distinguish. A leftover from a previous boot with a
204    // recycled pid is cleaned up below rather than reused.
205    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
206    let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
207    let stem = path.file_name().and_then(|n| n.to_str()).unwrap_or("hyprforge");
208    let tmp = path.with_file_name(format!(".{stem}.{}.{unique}.tmp", std::process::id()));
209
210    // Removes the temp file unless the rename claimed it. Without this a
211    // full disk leaves one behind on every failed save, accumulating in
212    // the user's config directory — and a leftover is not inert, because
213    // it is exactly what the next writer would have reused.
214    struct Cleanup<'a>(Option<&'a std::path::Path>);
215    impl Drop for Cleanup<'_> {
216        fn drop(&mut self) {
217            if let Some(path) = self.0 {
218                let _ = std::fs::remove_file(path);
219            }
220        }
221    }
222    let mut cleanup = Cleanup(Some(&tmp));
223
224    {
225        let file = std::fs::File::create(&tmp)?;
226        {
227            use std::io::Write as _;
228            let mut writer = std::io::BufWriter::new(&file);
229            writer.write_all(contents)?;
230            writer.flush()?;
231        }
232        file.sync_all()?;
233    }
234
235    std::fs::rename(&tmp, path)?;
236    // The rename consumed it; there is nothing left to remove, and the
237    // name now belongs to whatever a later writer creates.
238    cleanup.0 = None;
239
240    // Flushing the directory is what makes the rename itself durable.
241    // Best-effort: some filesystems refuse to open a directory for this,
242    // and failing the whole write because the *extra* guarantee could not
243    // be had would be worse than the guarantee being missing — the data
244    // is already on disk and already renamed into place.
245    if let Some(parent) = path.parent() {
246        if let Ok(dir) = std::fs::File::open(parent) {
247            let _ = dir.sync_all();
248        }
249    }
250    Ok(())
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use std::sync::{Mutex, MutexGuard};
257
258    /// `set_var`/`remove_var` are process-global and Rust runs tests on
259    /// threads, so every test that touches the environment has to take this
260    /// first or they corrupt each other's reads.
261    static ENV_LOCK: Mutex<()> = Mutex::new(());
262
263    /// Sets the two variables `config_home` reads, restoring whatever was
264    /// there when the guard drops — otherwise a test would leak its fake
265    /// `$HOME` into every test that runs after it.
266    struct EnvGuard {
267        _lock: MutexGuard<'static, ()>,
268        xdg: Option<std::ffi::OsString>,
269        home: Option<std::ffi::OsString>,
270    }
271
272    impl EnvGuard {
273        fn set(xdg: Option<&str>, home: Option<&str>) -> Self {
274            let guard = EnvGuard {
275                _lock: ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()),
276                xdg: std::env::var_os("XDG_CONFIG_HOME"),
277                home: std::env::var_os("HOME"),
278            };
279            // SAFETY: ENV_LOCK serializes every env mutation in this module.
280            unsafe {
281                match xdg {
282                    Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
283                    None => std::env::remove_var("XDG_CONFIG_HOME"),
284                }
285                match home {
286                    Some(v) => std::env::set_var("HOME", v),
287                    None => std::env::remove_var("HOME"),
288                }
289            }
290            guard
291        }
292    }
293
294    impl Drop for EnvGuard {
295        fn drop(&mut self) {
296            // SAFETY: `_lock` is still held — it is a field of `self`, and
297            // fields drop after this body runs — so this restore is
298            // serialised against every other env mutation in this module
299            // exactly as `set` was. No other thread reads the environment
300            // unlocked: `config_home` is only called from tests that hold
301            // the guard.
302            unsafe {
303                match &self.xdg {
304                    Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
305                    None => std::env::remove_var("XDG_CONFIG_HOME"),
306                }
307                match &self.home {
308                    Some(v) => std::env::set_var("HOME", v),
309                    None => std::env::remove_var("HOME"),
310                }
311            }
312        }
313    }
314
315    #[test]
316    fn absolute_xdg_config_home_is_used_as_is() {
317        let _g = EnvGuard::set(Some("/custom/config"), Some("/home/someone"));
318        assert_eq!(config_home(), PathBuf::from("/custom/config"));
319    }
320
321    #[test]
322    fn unset_xdg_config_home_falls_back_to_home_dot_config() {
323        let _g = EnvGuard::set(None, Some("/home/someone"));
324        assert_eq!(config_home(), PathBuf::from("/home/someone/.config"));
325    }
326
327    #[test]
328    fn relative_xdg_config_home_is_ignored_per_the_xdg_spec() {
329        // The spec says a relative value is invalid and must be treated as
330        // unset — not resolved against the cwd, which would scatter config
331        // wherever the app happened to be launched from.
332        let _g = EnvGuard::set(Some("relative/path"), Some("/home/someone"));
333        assert_eq!(config_home(), PathBuf::from("/home/someone/.config"));
334    }
335
336    #[test]
337    fn empty_xdg_config_home_falls_back_too() {
338        let _g = EnvGuard::set(Some(""), Some("/home/someone"));
339        assert_eq!(config_home(), PathBuf::from("/home/someone/.config"));
340    }
341
342    #[test]
343    fn write_atomic_creates_parent_directories() {
344        let dir = tempfile::tempdir().unwrap();
345        let path = dir.path().join("a").join("b").join("file.toml");
346        write_atomic(&path, "hello").unwrap();
347        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello");
348    }
349
350    /// The failure path, which the success-only test above never
351    /// reaches. A full disk or a quota'd home leaves the error to the
352    /// caller — and must not also leave debris in the user's config
353    /// directory, one file per failed save.
354    #[test]
355    fn a_failed_write_leaves_no_temp_file_behind() {
356        let dir = tempfile::tempdir().unwrap();
357        // A directory where the file should go: `File::create` fails, so
358        // the error arrives after the temp path has been chosen.
359        let target = dir.path().join("occupied.toml");
360        std::fs::create_dir(&target).unwrap();
361
362        assert!(write_atomic(&target, "anything").is_err());
363
364        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
365            .unwrap()
366            .filter_map(|e| e.ok())
367            .map(|e| e.file_name().to_string_lossy().into_owned())
368            .filter(|name| name.ends_with(".tmp"))
369            .collect();
370        assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
371    }
372
373    /// Two writers to one path must not share a temp file. `monitors.lua`
374    /// really does have two: the display daemon and the Settings app.
375    /// With one fixed `<name>.tmp` the second `create` truncates the
376    /// first's in-progress file, and what gets renamed into place can be
377    /// an interleaving of both.
378    #[test]
379    fn concurrent_writers_to_one_path_never_share_a_temp_file() {
380        let dir = tempfile::tempdir().unwrap();
381        let target = dir.path().join("monitors.lua");
382
383        let a = std::thread::spawn({
384            let target = target.clone();
385            move || {
386                for _ in 0..50 {
387                    write_atomic(&target, &"a".repeat(4096)).unwrap();
388                }
389            }
390        });
391        let b = std::thread::spawn({
392            let target = target.clone();
393            move || {
394                for _ in 0..50 {
395                    write_atomic(&target, &"b".repeat(4096)).unwrap();
396                }
397            }
398        });
399        a.join().unwrap();
400        b.join().unwrap();
401
402        // Whichever writer landed last, the file must be entirely one of
403        // them — never a mixture, and never short.
404        let got = std::fs::read_to_string(&target).unwrap();
405        assert!(
406            got == "a".repeat(4096) || got == "b".repeat(4096),
407            "torn write: {} bytes, starts {:?}",
408            got.len(),
409            &got[..got.len().min(8)]
410        );
411    }
412
413    #[test]
414    fn write_atomic_overwrites_and_leaves_no_temp_file() {
415        let dir = tempfile::tempdir().unwrap();
416        let path = dir.path().join("file.toml");
417        write_atomic(&path, "first").unwrap();
418        write_atomic(&path, "second").unwrap();
419
420        assert_eq!(std::fs::read_to_string(&path).unwrap(), "second");
421        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
422            .unwrap()
423            .map(|e| e.unwrap().file_name())
424            .filter(|n| n.to_string_lossy().contains(".tmp"))
425            .collect();
426        assert!(leftovers.is_empty(), "temp file left behind: {leftovers:?}");
427    }
428
429    #[test]
430    fn write_atomic_handles_an_extensionless_path() {
431        // `with_extension` on a name with no extension is the easy way to
432        // accidentally produce a temp path that collides with the target.
433        let dir = tempfile::tempdir().unwrap();
434        let path = dir.path().join("noext");
435        write_atomic(&path, "body").unwrap();
436        assert_eq!(std::fs::read_to_string(&path).unwrap(), "body");
437    }
438    #[test]
439    fn the_app_config_files_hang_off_the_hyprforge_dir() {
440        let _g = EnvGuard::set(Some("/custom/config"), Some("/home/someone"));
441        assert_eq!(
442            lock_toml_path(),
443            PathBuf::from("/custom/config/hyprforge/lock.toml")
444        );
445        assert_eq!(
446            appearance_toml_path(),
447            PathBuf::from("/custom/config/hyprforge/appearance.toml")
448        );
449    }
450
451    #[test]
452    fn the_emojimenu_config_hangs_off_the_hyprforge_dir_too() {
453        let _g = EnvGuard::set(Some("/custom/config"), Some("/home/someone"));
454        assert_eq!(
455            emojimenu_toml_path(),
456            PathBuf::from("/custom/config/hyprforge/emojimenu.toml")
457        );
458    }
459
460    #[test]
461    fn clipboard_paths_hang_off_their_own_subdirectory() {
462        let _g = EnvGuard::set(Some("/custom/config"), Some("/home/someone"));
463        assert_eq!(
464            clipboard_dir(),
465            PathBuf::from("/custom/config/hyprforge/clipboard")
466        );
467        assert_eq!(
468            clipboard_index_path(),
469            PathBuf::from("/custom/config/hyprforge/clipboard/history.toml")
470        );
471        assert_eq!(
472            clipboard_images_dir(),
473            PathBuf::from("/custom/config/hyprforge/clipboard/images")
474        );
475        assert_eq!(
476            clipboard_image_path("abc123"),
477            PathBuf::from("/custom/config/hyprforge/clipboard/images/abc123.bin")
478        );
479    }
480
481    #[test]
482    fn write_atomic_bytes_round_trips_binary_content() {
483        let dir = tempfile::tempdir().unwrap();
484        let path = dir.path().join("image.bin");
485        let bytes: Vec<u8> = (0..=255).collect();
486        write_atomic_bytes(&path, &bytes).unwrap();
487        assert_eq!(std::fs::read(&path).unwrap(), bytes);
488    }
489}