Skip to main content

hyprforge_tray/
menu.rs

1//! What a tray menu *is*, with no D-Bus in sight.
2//!
3//! Same split as [`crate::item`]: the question worth testing is which
4//! entries a given radio state deserves, and that is a pure function over
5//! plain data.
6//!
7//! Every type here derives `Serialize`/`Deserialize` for one reason: this
8//! is the wire format `hyprforge-trayd` hands `hyprforge-traymenu` on its
9//! stdin, as JSON — see `crate::launch`. That is a private pipe between a
10//! daemon and the one popup it just spawned, which is what makes it safe
11//! to serialise [`MenuItem::action`] directly. The other path,
12//! `crate::dbusmenu`, exposes the same menu to an arbitrary host and keeps
13//! the id-indirection that protocol needs: a host sees ids and labels,
14//! never an action string.
15
16use serde::{Deserialize, Serialize};
17
18/// What a row does.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub enum ItemKind {
21    /// An ordinary clickable row.
22    Standard,
23    /// A horizontal rule. Carries no label and cannot be clicked.
24    Separator,
25    /// A checkbox-style row. `toggle` carries its state.
26    Checkmark,
27}
28
29/// One row of a menu.
30///
31/// `id` must be **stable for as long as the row means the same thing**. A
32/// host asks for properties by id after the layout is sent, and reuses an
33/// id it already knows: renumbering rows between revisions makes a click
34/// land on whatever row inherited the number. Ids are assigned from the
35/// content, not from position — see `assign_ids`.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct MenuItem {
38    pub id: i32,
39    pub label: String,
40    pub enabled: bool,
41    pub visible: bool,
42    pub kind: ItemKind,
43    /// `Some` only for [`ItemKind::Checkmark`].
44    pub toggle: Option<bool>,
45    /// What clicking this row should do. Serialised for this crate's own
46    /// popup, the only thing that ever reads it (see `crate::launch`): it
47    /// hands the string straight back on its own stdout rather than an id
48    /// needing a second lookup. A dbusmenu host never sees it — it sends
49    /// back an id, which [`Menu::action_for`] resolves.
50    pub action: Option<String>,
51    pub children: Vec<MenuItem>,
52}
53
54impl MenuItem {
55    pub fn standard(label: impl Into<String>, action: impl Into<String>) -> Self {
56        MenuItem {
57            id: 0,
58            label: label.into(),
59            enabled: true,
60            visible: true,
61            kind: ItemKind::Standard,
62            toggle: None,
63            action: Some(action.into()),
64            children: Vec::new(),
65        }
66    }
67
68    pub fn checkmark(label: impl Into<String>, on: bool, action: impl Into<String>) -> Self {
69        MenuItem {
70            toggle: Some(on),
71            kind: ItemKind::Checkmark,
72            ..MenuItem::standard(label, action)
73        }
74    }
75
76    pub fn separator() -> Self {
77        MenuItem {
78            id: 0,
79            label: String::new(),
80            enabled: false,
81            visible: true,
82            kind: ItemKind::Separator,
83            toggle: None,
84            action: None,
85            children: Vec::new(),
86        }
87    }
88
89    /// A row that is shown but cannot be clicked — "Wi-Fi is off", or a
90    /// network this app cannot join yet.
91    pub fn disabled(label: impl Into<String>) -> Self {
92        MenuItem {
93            enabled: false,
94            action: None,
95            ..MenuItem::standard(label, "")
96        }
97    }
98
99    /// A checkmark that cannot be clicked — a radio blocked by a
100    /// hardware kill switch, say, where `on`/`off` is still true but no
101    /// D-Bus call flips it back. Shown rather than hidden, and shown as
102    /// a checkmark rather than an ordinary disabled row, so the state it
103    /// reports is not lost along with the ability to change it.
104    pub fn disabled_checkmark(label: impl Into<String>, on: bool) -> Self {
105        MenuItem {
106            kind: ItemKind::Checkmark,
107            toggle: Some(on),
108            ..MenuItem::disabled(label)
109        }
110    }
111}
112
113/// Builds a menu in the one shape every menu in this crate follows: a
114/// toggle row up top (or, in place of one, a single disabled row saying
115/// why there is nothing to toggle), then whatever content that toggle
116/// governs, then a settings row at the bottom.
117///
118/// The settings row is unconditional — offered in *every* state,
119/// unavailable included — because a menu with no way out of it is
120/// exactly the dead end CLAUDE.md's rules warn against; see
121/// `trayd.rs`'s module doc for where each of the four settings rows
122/// actually goes.
123///
124/// `content` may be empty (a keep-awake menu with nothing else holding
125/// an inhibit, a radio that is off or blocked). When it is, no separator
126/// is added for it — an empty section would otherwise put two
127/// separators in a row between the toggle and the settings row for
128/// nothing. `top` is a `Vec` rather than a single `MenuItem` only
129/// because the "nothing to toggle" case still has to supply *a* row —
130/// callers pass a one-element vec in the ordinary case.
131///
132/// This is what keeps a fifth icon from drifting from the other four:
133/// the shape lives here, once, rather than being re-derived per menu.
134pub fn radio_menu(top: Vec<MenuItem>, content: Vec<MenuItem>, settings: MenuItem) -> Menu {
135    let mut items = top;
136    if !content.is_empty() {
137        items.push(MenuItem::separator());
138        items.extend(content);
139    }
140    items.push(MenuItem::separator());
141    items.push(settings);
142    Menu::new(items)
143}
144
145/// A whole menu, with ids assigned.
146#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
147pub struct Menu {
148    pub items: Vec<MenuItem>,
149}
150
151impl Menu {
152    /// Builds a menu, numbering every row.
153    ///
154    /// Root is id 0 by the spec's own convention, so rows start at 1.
155    pub fn new(items: Vec<MenuItem>) -> Self {
156        let mut menu = Menu { items };
157        let mut next = 1;
158        assign_ids(&mut menu.items, &mut next);
159        menu
160    }
161
162    /// The action behind a row, by the id a host sends back.
163    pub fn action_for(&self, id: i32) -> Option<&str> {
164        find(&self.items, id).and_then(|item| item.action.as_deref())
165    }
166
167    pub fn find(&self, id: i32) -> Option<&MenuItem> {
168        find(&self.items, id)
169    }
170
171    /// Every row, depth-first — what `GetGroupProperties` answers from.
172    pub fn flatten(&self) -> Vec<&MenuItem> {
173        let mut out = Vec::new();
174        collect(&self.items, &mut out);
175        out
176    }
177}
178
179fn assign_ids(items: &mut [MenuItem], next: &mut i32) {
180    for item in items {
181        item.id = *next;
182        *next += 1;
183        assign_ids(&mut item.children, next);
184    }
185}
186
187fn find(items: &[MenuItem], id: i32) -> Option<&MenuItem> {
188    for item in items {
189        if item.id == id {
190            return Some(item);
191        }
192        if let Some(found) = find(&item.children, id) {
193            return Some(found);
194        }
195    }
196    None
197}
198
199fn collect<'a>(items: &'a [MenuItem], out: &mut Vec<&'a MenuItem>) {
200    for item in items {
201        out.push(item);
202        collect(&item.children, out);
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    fn sample() -> Menu {
211        Menu::new(vec![
212            MenuItem::checkmark("Wi-Fi", true, "radio:toggle"),
213            MenuItem::separator(),
214            MenuItem::standard("home", "connect:home"),
215            MenuItem::disabled("guest (enterprise)"),
216            MenuItem::separator(),
217            MenuItem::standard("Network settings…", "settings"),
218        ])
219    }
220
221    /// Root is 0 by the spec, so a row numbered 0 would be the menu
222    /// itself and every click on it would be ignored.
223    #[test]
224    fn rows_are_numbered_from_one_because_zero_is_the_root() {
225        let menu = sample();
226        assert!(menu.items.iter().all(|i| i.id > 0));
227        assert_eq!(menu.items[0].id, 1);
228    }
229
230    #[test]
231    fn every_row_has_its_own_id_including_nested_ones() {
232        let menu = Menu::new(vec![
233            MenuItem::standard("a", "a"),
234            MenuItem {
235                children: vec![MenuItem::standard("c", "c"), MenuItem::standard("d", "d")],
236                ..MenuItem::standard("b", "b")
237            },
238        ]);
239        let ids: Vec<i32> = menu.flatten().iter().map(|i| i.id).collect();
240        let mut unique = ids.clone();
241        unique.sort_unstable();
242        unique.dedup();
243        assert_eq!(ids.len(), unique.len(), "ids collide: {ids:?}");
244        assert_eq!(ids.len(), 4);
245    }
246
247    /// The whole point of the id: a host sends back a number and the
248    /// daemon has to know which row that was.
249    #[test]
250    fn a_click_id_resolves_to_the_action_that_row_stood_for() {
251        let menu = sample();
252        let home = menu.flatten().iter().find(|i| i.label == "home").unwrap().id;
253        assert_eq!(menu.action_for(home), Some("connect:home"));
254    }
255
256    /// A separator and a disabled row both carry no action. A host will
257    /// still send a click for a row it thinks is clickable, and answering
258    /// one with someone else's action is worse than answering nothing.
259    #[test]
260    fn a_row_that_does_nothing_resolves_to_no_action_rather_than_the_next_one() {
261        let menu = sample();
262        let sep = menu.flatten().iter().find(|i| i.kind == ItemKind::Separator).unwrap().id;
263        assert_eq!(menu.action_for(sep), None);
264
265        let disabled = menu
266            .flatten()
267            .iter()
268            .find(|i| i.label.contains("enterprise"))
269            .unwrap()
270            .id;
271        assert_eq!(menu.action_for(disabled), None);
272    }
273
274    #[test]
275    fn an_unknown_id_resolves_to_nothing_rather_than_panicking() {
276        assert_eq!(sample().action_for(9999), None);
277        assert!(sample().find(9999).is_none());
278    }
279
280    /// Only a checkmark carries a toggle state. A standard row reporting
281    /// one would draw a checkbox a host cannot change.
282    #[test]
283    fn only_a_checkmark_carries_a_toggle_state() {
284        let menu = sample();
285        for item in menu.flatten() {
286            match item.kind {
287                ItemKind::Checkmark => assert!(item.toggle.is_some()),
288                _ => assert!(item.toggle.is_none(), "{} carries a toggle", item.label),
289            }
290        }
291    }
292
293    // --- radio_menu: the one shape every menu in the daemon follows ------
294
295    #[test]
296    fn a_disabled_checkmark_still_reports_its_state_but_cannot_be_clicked() {
297        let row = MenuItem::disabled_checkmark("Wi-Fi (blocked by hardware switch)", false);
298        assert_eq!(row.kind, ItemKind::Checkmark);
299        assert_eq!(row.toggle, Some(false));
300        assert!(!row.enabled);
301        assert!(row.action.is_none());
302    }
303
304    /// The ordinary shape: toggle, separator, content, separator,
305    /// settings — every icon that has something to show ends up here.
306    #[test]
307    fn radio_menu_with_content_is_toggle_then_content_then_settings_with_separators_between() {
308        let menu = radio_menu(
309            vec![MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off")],
310            vec![MenuItem::standard("home", "wifi:connect:home")],
311            MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
312        );
313        let kinds: Vec<ItemKind> = menu.items.iter().map(|i| i.kind).collect();
314        assert_eq!(
315            kinds,
316            vec![
317                ItemKind::Checkmark,
318                ItemKind::Separator,
319                ItemKind::Standard,
320                ItemKind::Separator,
321                ItemKind::Standard,
322            ]
323        );
324        assert_eq!(menu.items[0].label, "Wi-Fi");
325        assert_eq!(menu.items[2].label, "home");
326        assert_eq!(menu.items[4].label, "Wi-Fi settings…");
327    }
328
329    /// Empty content collapses to one separator, not two — a keep-awake
330    /// menu with no other inhibitor must not show a blank gap between
331    /// the toggle and the settings row.
332    #[test]
333    fn radio_menu_with_no_content_has_exactly_one_separator() {
334        let menu = radio_menu(
335            vec![MenuItem::checkmark("Keep awake", false, "keepawake:on")],
336            Vec::new(),
337            MenuItem::standard("Keep awake settings…", "keepawake:settings"),
338        );
339        let kinds: Vec<ItemKind> = menu.items.iter().map(|i| i.kind).collect();
340        assert_eq!(kinds, vec![ItemKind::Checkmark, ItemKind::Separator, ItemKind::Standard]);
341    }
342
343    /// The unavailable shape: one disabled row explaining why, then the
344    /// settings row — never an empty popup, and never a dead end either.
345    #[test]
346    fn radio_menu_unavailable_still_offers_the_settings_row() {
347        let menu = radio_menu(
348            vec![MenuItem::disabled("Wi-Fi unavailable")],
349            Vec::new(),
350            MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
351        );
352        assert!(!menu.items[0].enabled);
353        assert_eq!(menu.items.last().unwrap().label, "Wi-Fi settings…");
354        assert!(menu.items.last().unwrap().enabled);
355    }
356
357    /// Ids only ever move when a row's own meaning changes — never
358    /// merely because content between two states differs in length. A
359    /// settings row built at the end of a longer menu and a shorter one
360    /// still gets whatever id `Menu::new` assigns it in each case; what
361    /// this test actually pins is that adding a settings row through
362    /// `radio_menu` does not disturb the ids of the rows *before* it.
363    #[test]
364    fn rows_before_the_settings_row_keep_their_ids_whether_or_not_content_is_present() {
365        let toggle = || MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off");
366        let settings = || MenuItem::standard("Wi-Fi settings…", "wifi:settings");
367
368        let short = radio_menu(vec![toggle()], Vec::new(), settings());
369        let long = radio_menu(
370            vec![toggle()],
371            vec![MenuItem::standard("home", "wifi:connect:home")],
372            settings(),
373        );
374        assert_eq!(short.items[0].id, long.items[0].id, "the toggle is row 1 in both");
375    }
376
377    /// Every menu `hyprforge-trayd` builds goes through `radio_menu`, and
378    /// the settings row it always ends with is what lets the dbusmenu
379    /// path declare a `Menu` for every icon: a menu with no rows is never
380    /// declared (`sni::declares_menu`), so an empty one here would quietly
381    /// put that icon back on the popup path, on a machine that cannot run
382    /// the popup.
383    #[test]
384    fn a_menu_built_for_an_icon_is_never_empty_even_with_nothing_to_toggle() {
385        let menu = radio_menu(vec![MenuItem::disabled("Unavailable")], Vec::new(), MenuItem::standard("Settings…", "settings"));
386        assert!(!menu.items.is_empty());
387        assert_eq!(menu.items.last().map(|i| i.label.as_str()), Some("Settings…"));
388    }
389
390    // --- JSON round trip: the wire format `hyprforge-trayd` hands
391    // `hyprforge-traymenu` on stdin. Getting this wrong is silent in
392    // exactly the way `dbusmenu.rs`'s own module doc warns about for
393    // that protocol — a menu that deserialises with the wrong shape opens
394    // an empty or broken popup, with nothing logged at either end.
395
396    #[test]
397    fn a_menu_round_trips_through_json_including_a_nested_child() {
398        let menu = radio_menu(
399            vec![MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off")],
400            vec![MenuItem {
401                children: vec![MenuItem::standard("child", "wifi:connect:686f6d65")],
402                ..MenuItem::standard("home", "wifi:connect:686f6d65")
403            }],
404            MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
405        );
406        let json = serde_json::to_string(&menu).expect("a menu always serialises");
407        let restored: Menu = serde_json::from_str(&json).expect("what was serialised must deserialise");
408        assert_eq!(menu, restored);
409    }
410
411    /// The action string is the whole point of serialising this at all —
412    /// `hyprforge-traymenu` prints it straight back on its own stdout, so
413    /// it must survive the round trip unchanged, `None` included (a
414    /// separator or a disabled row carries none).
415    #[test]
416    fn the_action_string_survives_the_round_trip() {
417        let menu = sample();
418        let json = serde_json::to_string(&menu).unwrap();
419        let restored: Menu = serde_json::from_str(&json).unwrap();
420        let home = restored.flatten().into_iter().find(|i| i.label == "home").unwrap();
421        assert_eq!(home.action.as_deref(), Some("connect:home"));
422        let sep = restored.flatten().into_iter().find(|i| i.kind == ItemKind::Separator).unwrap();
423        assert_eq!(sep.action, None);
424    }
425}