hyprforge_tray/prefs.rs
1//! Which tray icons the user wants.
2//!
3//! Its own file rather than a section of something larger, because two
4//! processes read it: the Settings app writes it, and `hyprforge-trayd`
5//! re-reads it on every poll so a toggle takes effect without restarting
6//! anything.
7//!
8//! Defaults are "show both" for the original two icons — a tray icon the
9//! user never asked to hide is the reason they installed a tray daemon.
10//!
11//! `keep_awake` and `night_light` default to **off**, unlike `network`
12//! and `bluetooth`. Those two were the whole reason this daemon exists;
13//! a third and fourth icon appearing in someone's bar with no action of
14//! theirs is a surprise these were not, and `#[serde(default)]` per
15//! field is exactly what lets an old `tray.toml` that only ever named
16//! `network`/`bluetooth` keep meaning the same thing after this file
17//! grows two more fields.
18//!
19//! `menu_y_offset` is unrelated to which icons show: it is how far below
20//! the bar's own reserved area `hyprforge-traymenu` opens the popup (see
21//! `hyprforge_popup::place_below_bar`) — `hyprctl monitors -j`'s own
22//! `reserved` array says how tall the *exclusive zone* is, but a bar can
23//! reserve less than it visually occupies (padding, a border), so this
24//! is the user's own answer to the rest of that gap. Read by
25//! `hyprforge-traymenu` itself, fresh on every right click, the same way
26//! every other field here is re-read on every poll tick — not by
27//! `hyprforge-trayd`, even though this file lives in that daemon's own
28//! crate: `ItemInterface::context_menu` (`sni.rs`) used to add this to
29//! the click's own Y before spawning the popup, which made the popup's
30//! position depend on where on the icon the click landed. Anchoring to
31//! the bar instead of the pointer meant moving the read to whichever
32//! process actually places the popup.
33//!
34//! `menu` is which of two ways a right click is served — see
35//! [`MenuMode`]. The answer depends on the machine as well as the file,
36//! so the file holds the user's *choice* and [`MenuMode::serving_here`]
37//! turns it into what actually happens.
38
39use serde::{Deserialize, Serialize};
40use std::path::{Path, PathBuf};
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(default)]
44pub struct Prefs {
45 pub network: bool,
46 pub bluetooth: bool,
47 pub keep_awake: bool,
48 pub night_light: bool,
49 /// Battery level and power profile, one icon — off by default for
50 /// the reason `keep_awake` and `night_light` are.
51 pub power: bool,
52 /// Saved display layouts, and the keep-or-revert prompt after
53 /// switching one. Off by default like the others added after the
54 /// first two.
55 pub displays: bool,
56 /// Logical pixels below the bar's own reserved area at which the tray
57 /// menu opens — see this module's own doc. (It was once added to the
58 /// click's Y instead; that made the menu's position depend on where
59 /// on the icon the click landed.) A bar that reserves less than it
60 /// visually occupies is what this field is for.
61 pub menu_y_offset: i32,
62 /// Whether clicking outside an open tray menu dismisses it.
63 ///
64 /// Not a cosmetic preference: it decides how the popup asks the
65 /// compositor for the keyboard, because those are the same question
66 /// (see `hyprforge_popup::Dismissal`). `true` — the default, and how
67 /// every other menu on the desktop behaves — means the menu takes
68 /// the keyboard only while it is being used, so a click elsewhere
69 /// both closes it *and* reaches whatever it landed on. `false` means
70 /// the menu holds the keyboard until it is dismissed deliberately,
71 /// which is what somebody driving it entirely from the keyboard
72 /// would want, at the cost of a stray click doing nothing.
73 pub menu_closes_on_click_outside: bool,
74 /// How a right click is served: Hyprforge's own popup, or a
75 /// `com.canonical.dbusmenu` menu the bar draws itself. See
76 /// [`MenuMode`].
77 pub menu: MenuMode,
78}
79
80/// Which way the right-click menus are served — the user's choice, as
81/// `tray.toml` holds it.
82///
83/// The popup (`hyprforge-traymenu`) is the suite's own menu: themed like
84/// the clipboard and emoji popups, anchored below the bar at the icon
85/// that was clicked. It needs two things this daemon cannot assume. It
86/// reads the monitors through `hyprctl`, so it only works on Hyprland.
87/// And the bar has to call `ContextMenu` on an item that declares no
88/// `Menu` property, which a bar that only draws dbusmenu never does —
89/// on such a bar the popup is never even asked for.
90///
91/// `com.canonical.dbusmenu` is the fallback that works on any
92/// spec-compliant bar and any compositor, drawn and placed however that
93/// bar's tray module chooses. It is the menu this crate served before the
94/// popup existed, and it comes back as a choice rather than the default
95/// because the popup is the better menu wherever it can run.
96///
97/// `Auto`, the default, picks the popup where it can run and dbusmenu
98/// everywhere else, so installing the tray on sway gives right-click
99/// menus with nothing configured. `Popup` and `Dbusmenu` force one —
100/// `Dbusmenu` is for a bar on Hyprland that never calls `ContextMenu`,
101/// which nothing here can detect from the outside.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
103#[serde(rename_all = "lowercase")]
104pub enum MenuMode {
105 #[default]
106 Auto,
107 Popup,
108 Dbusmenu,
109}
110
111/// What a right click is actually served by, once [`MenuMode::Auto`] has
112/// been decided.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum MenuServing {
115 /// No `Menu` property; `ContextMenu` spawns `hyprforge-traymenu`.
116 Popup,
117 /// A `Menu` property naming a `com.canonical.dbusmenu` object.
118 Dbusmenu,
119}
120
121impl MenuMode {
122 /// The decision, as a pure function of what the machine offers.
123 ///
124 /// `on_hyprland` and `traymenu_installed` are passed in rather than
125 /// looked up so every combination is testable without a compositor
126 /// or a `$PATH` — [`Self::serving_here`] is the one place that asks.
127 pub fn serving(self, on_hyprland: bool, traymenu_installed: bool) -> MenuServing {
128 match self {
129 MenuMode::Popup => MenuServing::Popup,
130 MenuMode::Dbusmenu => MenuServing::Dbusmenu,
131 MenuMode::Auto if on_hyprland && traymenu_installed => MenuServing::Popup,
132 MenuMode::Auto => MenuServing::Dbusmenu,
133 }
134 }
135
136 /// [`Self::serving`], asked of this machine.
137 ///
138 /// Hyprland sets `HYPRLAND_INSTANCE_SIGNATURE` for everything it
139 /// starts, and `hyprctl` — which the popup needs — reads the same
140 /// variable to find its socket, so its absence is exactly "the popup
141 /// cannot place itself". Cheap enough for every poll tick: one
142 /// environment read and a `stat` per `$PATH` entry.
143 pub fn serving_here(self) -> MenuServing {
144 let on_hyprland = std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some_and(|v| !v.is_empty());
145 self.serving(on_hyprland, on_path(crate::launch::TRAYMENU_BINARY))
146 }
147}
148
149/// Whether `name` is an executable file in some `$PATH` directory — the
150/// lookup `Command::new` will do when it is spawned.
151fn on_path(name: &str) -> bool {
152 use std::os::unix::fs::PermissionsExt;
153 let Some(path) = std::env::var_os("PATH") else {
154 return false;
155 };
156 std::env::split_paths(&path).any(|dir| {
157 std::fs::metadata(dir.join(name))
158 .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
159 })
160}
161
162impl Default for Prefs {
163 fn default() -> Self {
164 Prefs {
165 network: true,
166 bluetooth: true,
167 keep_awake: false,
168 night_light: false,
169 power: false,
170 displays: false,
171 menu_y_offset: 32,
172 menu_closes_on_click_outside: true,
173 menu: MenuMode::Auto,
174 }
175 }
176}
177
178#[derive(Debug, thiserror::Error)]
179pub enum PrefsError {
180 /// The file exists and will not parse. **Not** the same as absent —
181 /// see [`load_from`].
182 #[error("{path} could not be read as tray settings: {source}")]
183 Unreadable {
184 path: PathBuf,
185 #[source]
186 source: toml::de::Error,
187 },
188 #[error("{path} could not be opened: {source}")]
189 Io {
190 path: PathBuf,
191 #[source]
192 source: std::io::Error,
193 },
194 #[error("{path} could not be written: {source}")]
195 Write {
196 path: PathBuf,
197 #[source]
198 source: std::io::Error,
199 },
200}
201
202/// Where it lives. `hyprforge-paths` owns this, the way it owns
203/// `lock.toml` and `appearance.toml` — one crate knows the layout of the
204/// config directory, and no other crate joins path segments to guess it.
205pub fn path() -> PathBuf {
206 hyprforge_paths::tray_toml_path()
207}
208
209pub fn load() -> Result<Prefs, PrefsError> {
210 load_from(&path())
211}
212
213/// Reads the preferences, or says why it could not.
214///
215/// A **missing** file is first run and yields the defaults. A file that
216/// **exists and will not parse** is an error the user has to hear about,
217/// and must never be silently replaced with defaults — doing that would
218/// turn a typo into "you have configured nothing" and then overwrite what
219/// they wrote on the next save. This suite has paid for that mistake
220/// once already, in `hlconfig::storage`, and the rule is in CLAUDE.md.
221pub fn load_from(path: &Path) -> Result<Prefs, PrefsError> {
222 let text = match std::fs::read_to_string(path) {
223 Ok(text) => text,
224 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Prefs::default()),
225 Err(source) => {
226 return Err(PrefsError::Io {
227 path: path.to_path_buf(),
228 source,
229 })
230 }
231 };
232 toml::from_str(&text).map_err(|source| PrefsError::Unreadable {
233 path: path.to_path_buf(),
234 source,
235 })
236}
237
238pub fn save(prefs: &Prefs) -> Result<(), PrefsError> {
239 save_to(&path(), prefs)
240}
241
242pub fn save_to(path: &Path, prefs: &Prefs) -> Result<(), PrefsError> {
243 let text = toml::to_string_pretty(prefs).expect("Prefs is plain fields and always serialises");
244 hyprforge_paths::write_atomic(path, &text).map_err(|source| PrefsError::Write {
245 path: path.to_path_buf(),
246 source,
247 })
248}
249
250/// Read-modify-write, and the one thing every writer of this file should
251/// call instead of saving a copy it loaded earlier.
252///
253/// This file has more than one writer inside a single `hyprforge-settings`
254/// process — the Network and Bluetooth screens each flip their own icon's
255/// bit, and the Tray screen this function was written for flips all four
256/// plus [`Prefs::menu_y_offset`] — and each of them loads `Prefs` once, at
257/// its own construction. Two screens open at once (or one screen left
258/// open while another is visited) hold two independently stale copies of
259/// the same struct, and a save that writes back "the whole struct as I
260/// last saw it" from either one **silently undoes** whatever the other
261/// screen wrote in between. Reloading right before every write is the
262/// only form of the save that is correct regardless of who else touched
263/// the file since — another screen in this process, `hyprforge-trayd`
264/// re-reading it (this crate never writes it), or the user's own editor.
265///
266/// It also composes with the rule in [`load_from`] for free: a `tray.toml`
267/// that exists and will not parse makes the reload fail, which returns
268/// here before `f` ever runs and before anything is written — the same
269/// "refuse and report, never silently overwrite" this module already
270/// promises for a plain load, now also true of every write.
271pub fn update(f: impl FnOnce(&mut Prefs)) -> Result<Prefs, PrefsError> {
272 update_at(&path(), f)
273}
274
275/// [`update`], against an arbitrary path — the seam a test uses to point
276/// this at a throwaway `tray.toml` instead of the real one.
277pub fn update_at(path: &Path, f: impl FnOnce(&mut Prefs)) -> Result<Prefs, PrefsError> {
278 let mut prefs = load_from(path)?;
279 f(&mut prefs);
280 save_to(path, &prefs)?;
281 Ok(prefs)
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn both_icons_are_shown_until_someone_says_otherwise() {
290 let prefs = Prefs::default();
291 assert!(prefs.network);
292 assert!(prefs.bluetooth);
293 }
294
295 #[test]
296 fn a_missing_file_is_first_run_not_a_failure() {
297 let dir = tempfile::tempdir().unwrap();
298 let missing = dir.path().join("tray.toml");
299 assert_eq!(load_from(&missing).unwrap(), Prefs::default());
300 }
301
302 /// The rule this file is most likely to break. A tray.toml with a
303 /// typo in it must be reported, not silently treated as "nothing
304 /// configured" — because the next save would then overwrite what the
305 /// user actually wrote.
306 #[test]
307 fn a_file_that_exists_and_will_not_parse_is_reported_rather_than_defaulted() {
308 let dir = tempfile::tempdir().unwrap();
309 let path = dir.path().join("tray.toml");
310 std::fs::write(&path, "network = yes please\n").unwrap();
311
312 let err = load_from(&path).expect_err("a malformed file is an error, not defaults");
313 assert!(matches!(err, PrefsError::Unreadable { .. }));
314 assert!(err.to_string().contains("tray.toml"));
315 }
316
317 /// A file naming only one icon leaves the other at its default,
318 /// rather than switching it off — `#[serde(default)]` per field is
319 /// what makes adding a third icon later not break existing files.
320 #[test]
321 fn a_partial_file_leaves_the_icons_it_does_not_mention_alone() {
322 let dir = tempfile::tempdir().unwrap();
323 let path = dir.path().join("tray.toml");
324 std::fs::write(&path, "network = false\n").unwrap();
325
326 let prefs = load_from(&path).unwrap();
327 assert!(!prefs.network);
328 assert!(prefs.bluetooth, "an unmentioned icon keeps its default");
329 }
330
331 #[test]
332 fn what_is_saved_is_what_comes_back() {
333 let dir = tempfile::tempdir().unwrap();
334 let path = dir.path().join("tray.toml");
335 // `keep_awake`/`night_light` given explicitly (not `..Default::default()`)
336 // so this test still proves a round trip of a value that differs
337 // from the default in every field, not just the original two.
338 let prefs = Prefs {
339 network: false,
340 bluetooth: true,
341 keep_awake: true,
342 night_light: true,
343 power: true,
344 displays: true,
345 menu_y_offset: 50,
346 menu_closes_on_click_outside: false,
347 menu: MenuMode::Dbusmenu,
348 };
349 save_to(&path, &prefs).unwrap();
350 assert_eq!(load_from(&path).unwrap(), prefs);
351 }
352
353 /// The two new icons are opt-in: unlike `network`/`bluetooth`, which
354 /// default to shown, `keep_awake` and `night_light` default to
355 /// hidden, so installing this daemon does not put an icon in the bar
356 /// nobody asked for.
357 #[test]
358 fn the_two_new_icons_default_to_off_unlike_the_original_two() {
359 let prefs = Prefs::default();
360 assert!(prefs.network);
361 assert!(prefs.bluetooth);
362 assert!(!prefs.keep_awake);
363 assert!(!prefs.night_light);
364 }
365
366 /// The property `#[serde(default)]` per field exists to guarantee:
367 /// a `tray.toml` written before `keep_awake`/`night_light` existed —
368 /// naming only the original two — must not be read as "hide
369 /// everything else" or fail to parse. It leaves the new icons at
370 /// their own default, off.
371 #[test]
372 fn a_tray_toml_naming_only_the_original_two_icons_leaves_the_new_ones_off() {
373 let dir = tempfile::tempdir().unwrap();
374 let path = dir.path().join("tray.toml");
375 std::fs::write(&path, "network = true\nbluetooth = false\n").unwrap();
376
377 let prefs = load_from(&path).unwrap();
378 assert!(prefs.network);
379 assert!(!prefs.bluetooth);
380 assert!(!prefs.keep_awake, "an icon added later than this file defaults off");
381 assert!(!prefs.night_light, "an icon added later than this file defaults off");
382 assert!(!prefs.power, "an icon added later than this file defaults off");
383 assert!(!prefs.displays, "an icon added later than this file defaults off");
384 }
385
386 /// A `tray.toml` written before `menu_y_offset` existed must still
387 /// parse and get the default — the same backward-compatibility
388 /// property the two icon fields above already have to hold, now
389 /// extended to a field that is not a bool.
390 #[test]
391 fn a_tray_toml_naming_no_offset_gets_the_default_that_clears_a_typical_bar() {
392 let dir = tempfile::tempdir().unwrap();
393 let path = dir.path().join("tray.toml");
394 std::fs::write(&path, "network = true\nbluetooth = true\n").unwrap();
395
396 let prefs = load_from(&path).unwrap();
397 assert_eq!(prefs.menu_y_offset, 32);
398 }
399
400 /// The same backward-compatibility property every field here has to
401 /// hold, for the field most likely to be missing: a `tray.toml`
402 /// written before clicking away meant anything must read as the
403 /// behaviour every other menu on the desktop already has, rather
404 /// than as "off".
405 #[test]
406 fn a_tray_toml_written_before_this_setting_existed_closes_on_a_click_outside() {
407 let dir = tempfile::tempdir().unwrap();
408 let path = dir.path().join("tray.toml");
409 std::fs::write(&path, "network = true\nmenu_y_offset = 40\n").unwrap();
410
411 let prefs = load_from(&path).unwrap();
412 assert_eq!(prefs.menu_y_offset, 40);
413 assert!(prefs.menu_closes_on_click_outside, "a file that predates the field gets the default, not false");
414 }
415
416 #[test]
417 fn a_configured_offset_round_trips() {
418 let dir = tempfile::tempdir().unwrap();
419 let path = dir.path().join("tray.toml");
420 let prefs = Prefs { menu_y_offset: 48, ..Prefs::default() };
421 save_to(&path, &prefs).unwrap();
422 assert_eq!(load_from(&path).unwrap().menu_y_offset, 48);
423 }
424
425 // --- `update`: the read-modify-write every writer shares -------------
426
427 /// The property this function exists to guarantee, pinned directly:
428 /// two independent "screens" (here, just two closures) each holding
429 /// nothing but the path, one flips `network` and the other flips
430 /// `menu_y_offset`, in either order — both must survive. A plain
431 /// load-mutate-save built on a copy loaded once, before either write,
432 /// would let the second write silently erase the first.
433 #[test]
434 fn two_writers_changing_different_fields_both_survive() {
435 let dir = tempfile::tempdir().unwrap();
436 let path = dir.path().join("tray.toml");
437 // Both "screens" load their own starting copy up front, the way
438 // `NetworkModule::new`/`BluetoothModule::new`/`TrayModule::new`
439 // each do in `hyprforge-settings` — before either has written
440 // anything.
441 let screen_a_initial = load_from(&path).unwrap();
442 let screen_b_initial = load_from(&path).unwrap();
443 assert_eq!(screen_a_initial, screen_b_initial, "both start from the same defaults");
444
445 // Screen A flips its own icon off.
446 update_at(&path, |p| p.network = false).unwrap();
447 // Screen B, still only holding what it loaded before A's write,
448 // flips a completely different field.
449 update_at(&path, |p| p.menu_y_offset = 60).unwrap();
450
451 let on_disk = load_from(&path).unwrap();
452 assert!(!on_disk.network, "screen A's write must not be undone by screen B's");
453 assert_eq!(on_disk.menu_y_offset, 60, "screen B's own write must have landed");
454 }
455
456 /// The composed half of the guarantee: a file that has gone bad
457 /// between load and write must refuse the write entirely, the same
458 /// as a plain load would refuse to hand back defaults for it.
459 #[test]
460 fn update_refuses_to_write_over_a_file_it_cannot_reload() {
461 let dir = tempfile::tempdir().unwrap();
462 let path = dir.path().join("tray.toml");
463 std::fs::write(&path, "network = yes please\n").unwrap();
464
465 let before = std::fs::read_to_string(&path).unwrap();
466 let err = update_at(&path, |p| p.network = false)
467 .expect_err("a file that won't parse must refuse the write, not overwrite it");
468 assert!(matches!(err, PrefsError::Unreadable { .. }));
469 let after = std::fs::read_to_string(&path).unwrap();
470 assert_eq!(before, after, "the mutation must never have been applied or saved");
471 }
472
473 // --- `menu`: which way a right click is served ----------------------
474
475 /// A `tray.toml` written before this field existed must keep the menu
476 /// people already had where it can still run — `auto`, never a forced
477 /// mode they did not choose.
478 #[test]
479 fn a_tray_toml_written_before_the_menu_mode_existed_reads_as_auto() {
480 let dir = tempfile::tempdir().unwrap();
481 let path = dir.path().join("tray.toml");
482 std::fs::write(&path, "network = true\nmenu_y_offset = 40\n").unwrap();
483 assert_eq!(load_from(&path).unwrap().menu, MenuMode::Auto);
484 }
485
486 /// The spelling a person writes by hand, and the spelling this file
487 /// writes, are the same lowercase words.
488 #[test]
489 fn the_menu_mode_is_written_and_read_as_a_lowercase_word() {
490 let dir = tempfile::tempdir().unwrap();
491 let path = dir.path().join("tray.toml");
492 std::fs::write(&path, "menu = \"dbusmenu\"\n").unwrap();
493 assert_eq!(load_from(&path).unwrap().menu, MenuMode::Dbusmenu);
494
495 save_to(&path, &Prefs { menu: MenuMode::Popup, ..Prefs::default() }).unwrap();
496 assert!(std::fs::read_to_string(&path).unwrap().contains("menu = \"popup\""));
497 }
498
499 /// A misspelt mode is a file that will not parse, reported like any
500 /// other — not quietly read as `auto`.
501 #[test]
502 fn an_unknown_menu_mode_is_reported_rather_than_defaulted() {
503 let dir = tempfile::tempdir().unwrap();
504 let path = dir.path().join("tray.toml");
505 std::fs::write(&path, "menu = \"gtk\"\n").unwrap();
506 assert!(matches!(load_from(&path), Err(PrefsError::Unreadable { .. })));
507 }
508
509 /// `auto` picks the popup only where it can run: on Hyprland, with
510 /// the binary installed. Anywhere else it is dbusmenu, so a tray on
511 /// another compositor has right-click menus with nothing configured.
512 #[test]
513 fn auto_serves_the_popup_only_on_hyprland_with_traymenu_installed() {
514 assert_eq!(MenuMode::Auto.serving(true, true), MenuServing::Popup);
515 assert_eq!(MenuMode::Auto.serving(true, false), MenuServing::Dbusmenu);
516 assert_eq!(MenuMode::Auto.serving(false, true), MenuServing::Dbusmenu);
517 assert_eq!(MenuMode::Auto.serving(false, false), MenuServing::Dbusmenu);
518 }
519
520 /// A forced mode is what the user asked for, whatever the machine
521 /// offers — `dbusmenu` exists for a bar on Hyprland that never calls
522 /// `ContextMenu`, which looks identical from here to one that does.
523 #[test]
524 fn a_forced_mode_wins_over_what_the_machine_offers() {
525 for (hyprland, installed) in [(true, true), (true, false), (false, true), (false, false)] {
526 assert_eq!(MenuMode::Popup.serving(hyprland, installed), MenuServing::Popup);
527 assert_eq!(MenuMode::Dbusmenu.serving(hyprland, installed), MenuServing::Dbusmenu);
528 }
529 }
530
531 #[test]
532 fn a_binary_counts_as_installed_only_when_it_is_an_executable_file_on_path() {
533 assert!(on_path("sh"), "every machine this runs on has a shell on $PATH");
534 assert!(!on_path("hyprforge-no-such-binary-anywhere"));
535 }
536
537 /// `update` on a first run (no file yet) still works, starting from
538 /// the same defaults `load_from` would hand back.
539 #[test]
540 fn update_on_a_missing_file_starts_from_the_defaults() {
541 let dir = tempfile::tempdir().unwrap();
542 let path = dir.path().join("tray.toml");
543 let updated = update_at(&path, |p| p.keep_awake = true).unwrap();
544 assert!(updated.keep_awake);
545 assert!(updated.network, "everything else stays at its default");
546 assert_eq!(load_from(&path).unwrap(), updated);
547 }
548}