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