Skip to main content

hyprforge_tray/
dbusmenu.rs

1//! Serving `com.canonical.dbusmenu` — the right-click menu a bar draws
2//! itself.
3//!
4//! The fallback, not the default: where `hyprforge-traymenu` can run, the
5//! suite's own popup draws the menu instead (see
6//! [`crate::prefs::MenuMode`]). This is served only for an item
7//! registered with [`crate::prefs::MenuServing::Dbusmenu`] — another
8//! compositor, a bar that never calls `ContextMenu`, or a user who chose
9//! it. It is the module this crate deleted when the popup arrived
10//! (`461fc9c`), brought back over the same unchanged [`Menu`] model: the
11//! same row ids, the same [`Menu::action_for`], and the same action
12//! strings arriving on the same channel the popup answers on, so
13//! `hyprforge-trayd` cannot tell which of the two served a click.
14//!
15//! The protocol is older and stranger than StatusNotifierItem, and one
16//! detail carries most of the risk: `GetLayout` returns a **recursive**
17//! structure, `(ia{sv}av)`, whose children are variants each wrapping
18//! another one of the same. Getting that signature wrong does not fail —
19//! the host reads a menu with no rows in it and shows an empty popup,
20//! with nothing logged at either end.
21
22// The open announcement is shared with the popup path, so the daemon
23// reads one prefix whichever way the menu was served.
24use crate::launch::OPENED_PREFIX;
25use crate::menu::{ItemKind, Menu, MenuItem};
26use std::collections::HashMap;
27use std::sync::Arc;
28use tokio::sync::Mutex;
29use zbus::object_server::SignalEmitter;
30use zbus::zvariant::{OwnedValue, StructureBuilder, Type, Value};
31
32/// One node of `GetLayout`'s tree: `(ia{sv}av)`.
33///
34/// A concrete type rather than a `Structure`, because `Structure`'s
35/// signature is only known at runtime and `zbus::interface` needs a
36/// static one to advertise. Children are variants each wrapping another
37/// `LayoutNode`, which is what makes the type recursive without being
38/// recursive in Rust.
39#[derive(Debug, Clone, serde::Serialize, Type)]
40pub struct LayoutNode(i32, HashMap<String, OwnedValue>, Vec<OwnedValue>);
41
42/// The properties a host asks for, per row.
43fn properties(item: &MenuItem) -> HashMap<String, OwnedValue> {
44    let mut props: HashMap<String, OwnedValue> = HashMap::new();
45
46    // "standard" is the default and may be omitted; "separator" may not.
47    if item.kind == ItemKind::Separator {
48        props.insert(
49            "type".to_string(),
50            OwnedValue::try_from(Value::from("separator")).expect("a string is a value"),
51        );
52        return props;
53    }
54
55    props.insert(
56        "label".to_string(),
57        OwnedValue::try_from(Value::from(item.label.as_str())).expect("a string is a value"),
58    );
59    props.insert(
60        "enabled".to_string(),
61        OwnedValue::try_from(Value::from(item.enabled)).expect("a bool is a value"),
62    );
63    props.insert(
64        "visible".to_string(),
65        OwnedValue::try_from(Value::from(item.visible)).expect("a bool is a value"),
66    );
67
68    if let Some(on) = item.toggle {
69        props.insert(
70            "toggle-type".to_string(),
71            OwnedValue::try_from(Value::from("checkmark")).expect("a string is a value"),
72        );
73        // 1 on, 0 off. The spec also has -1 for "indeterminate", which
74        // nothing here produces.
75        props.insert(
76            "toggle-state".to_string(),
77            OwnedValue::try_from(Value::from(if on { 1i32 } else { 0i32 })).expect("an int is a value"),
78        );
79    }
80
81    if !item.children.is_empty() {
82        // Without this a host does not know the row opens a submenu and
83        // draws it as an ordinary entry that does nothing.
84        props.insert(
85            "children-display".to_string(),
86            OwnedValue::try_from(Value::from("submenu")).expect("a string is a value"),
87        );
88    }
89
90    props
91}
92
93/// One node of the layout tree.
94///
95/// `depth` counts down; `-1` means "everything", which is what every host
96/// actually asks for.
97fn node(
98    id: i32,
99    props: HashMap<String, OwnedValue>,
100    children: &[MenuItem],
101    depth: i32,
102) -> LayoutNode {
103    let kids: Vec<OwnedValue> = if depth == 0 {
104        Vec::new()
105    } else {
106        children
107            .iter()
108            .map(|child| {
109                let child_node = node(
110                    child.id,
111                    properties(child),
112                    &child.children,
113                    depth.saturating_sub(1),
114                );
115                into_value(child_node)
116            })
117            .collect()
118    };
119
120    LayoutNode(id, props, kids)
121}
122
123/// Wraps a node in the variant its parent's `av` needs.
124///
125/// Built by hand because a derived `Serialize` gives no way *into* a
126/// `Value`, and the child level of this protocol is variants all the way
127/// down.
128fn into_value(node: LayoutNode) -> OwnedValue {
129    let structure = StructureBuilder::new()
130        .add_field(node.0)
131        .add_field(node.1)
132        .add_field(node.2)
133        .build()
134        .expect("a node is always exactly three fields");
135    OwnedValue::try_from(Value::from(structure)).expect("a structure is a value")
136}
137
138/// The menu object a host reads and clicks.
139pub struct MenuInterface {
140    /// The owning item's id, so an open event says which menu it was.
141    id: String,
142    menu: Arc<Mutex<Menu>>,
143    revision: Arc<Mutex<u32>>,
144    /// Clicked actions, as the strings the [`Menu`] carries. Unbounded
145    /// and never awaited on, for the same reason the item's clicks are:
146    /// the host is blocked on the D-Bus method returning.
147    ///
148    /// Carries menu *events*, not only clicks — [`OPENED_PREFIX`] arrives
149    /// here too, so a daemon can refresh what the menu is about to show.
150    events: tokio::sync::mpsc::UnboundedSender<String>,
151}
152
153impl MenuInterface {
154    pub fn new(
155        id: String,
156        menu: Arc<Mutex<Menu>>,
157        revision: Arc<Mutex<u32>>,
158        events: tokio::sync::mpsc::UnboundedSender<String>,
159    ) -> Self {
160        MenuInterface {
161            id,
162            menu,
163            revision,
164            events,
165        }
166    }
167}
168
169#[zbus::interface(name = "com.canonical.dbusmenu")]
170impl MenuInterface {
171    /// `(revision, (id, props, children))`.
172    ///
173    /// `parent_id` 0 is the root, which is not a row of its own: it
174    /// carries no label and exists only to hold the top-level items.
175    async fn get_layout(
176        &self,
177        parent_id: i32,
178        recursion_depth: i32,
179        _property_names: Vec<String>,
180    ) -> (u32, LayoutNode) {
181        let menu = self.menu.lock().await;
182        let revision = *self.revision.lock().await;
183
184        if parent_id == 0 {
185            let mut root: HashMap<String, OwnedValue> = HashMap::new();
186            root.insert(
187                "children-display".to_string(),
188                OwnedValue::try_from(Value::from("submenu")).expect("a string is a value"),
189            );
190            return (revision, node(0, root, &menu.items, recursion_depth));
191        }
192
193        match menu.find(parent_id) {
194            Some(item) => (
195                revision,
196                node(item.id, properties(item), &item.children, recursion_depth),
197            ),
198            // An id we do not know is answered with an empty node rather
199            // than an error: hosts ask about stale ids after a layout
200            // change, and an error there shows the user a broken menu for
201            // something that has merely moved.
202            None => (revision, node(parent_id, HashMap::new(), &[], 0)),
203        }
204    }
205
206    async fn get_group_properties(
207        &self,
208        ids: Vec<i32>,
209        _property_names: Vec<String>,
210    ) -> Vec<(i32, HashMap<String, OwnedValue>)> {
211        let menu = self.menu.lock().await;
212        menu.flatten()
213            .into_iter()
214            .filter(|item| ids.is_empty() || ids.contains(&item.id))
215            .map(|item| (item.id, properties(item)))
216            .collect()
217    }
218
219    async fn get_property(&self, id: i32, name: String) -> OwnedValue {
220        let menu = self.menu.lock().await;
221        menu.find(id)
222            .and_then(|item| properties(item).remove(&name))
223            .unwrap_or_else(|| {
224                OwnedValue::try_from(Value::from("")).expect("a string is a value")
225            })
226    }
227
228    /// A click, a hover, or an open. Only `clicked` does anything.
229    async fn event(&self, id: i32, event_id: String, _data: Value<'_>, _timestamp: u32) {
230        if event_id != "clicked" {
231            return;
232        }
233        let action = self.menu.lock().await.action_for(id).map(str::to_string);
234        if let Some(action) = action {
235            let _ = self.events.send(action);
236        }
237    }
238
239    /// Hosts batch events. Answering only `Event` leaves menus that use
240    /// this one entirely unclickable.
241    async fn event_group(
242        &self,
243        events: Vec<(i32, String, Value<'_>, u32)>,
244    ) -> Vec<i32> {
245        for (id, event_id, data, timestamp) in events {
246            self.event(id, event_id, data, timestamp).await;
247        }
248        Vec::new()
249    }
250
251    /// Announces the open and answers `false`.
252    ///
253    /// `false` because the layout already served is the current one —
254    /// the daemon rebuilds it on its own schedule and bumps the revision,
255    /// so `true` would make a host re-fetch the whole tree every time for
256    /// nothing.
257    ///
258    /// The useful half is the announcement: it is this protocol's form of
259    /// the event the popup path sends before spawning
260    /// `hyprforge-traymenu`, and it is where the Wi-Fi menu's scan on
261    /// open comes from. Anything this menu is built from that goes stale
262    /// while nobody looks at it can be refreshed now, and the *next* open
263    /// shows it — which is what `nm-applet` does with a scan, and the
264    /// reason its network list is never as empty as one built only on a
265    /// timer.
266    async fn about_to_show(&self, _id: i32) -> bool {
267        let _ = self.events.send(format!("{OPENED_PREFIX}{}", self.id));
268        false
269    }
270
271    /// The batched form. Hosts use one or the other, so both have to
272    /// announce or the refresh silently never happens on half of them.
273    async fn about_to_show_group(&self, _ids: Vec<i32>) -> (Vec<i32>, Vec<i32>) {
274        let _ = self.events.send(format!("{OPENED_PREFIX}{}", self.id));
275        (Vec::new(), Vec::new())
276    }
277
278    #[zbus(property)]
279    async fn version(&self) -> u32 {
280        3
281    }
282
283    #[zbus(property)]
284    async fn status(&self) -> String {
285        "normal".to_string()
286    }
287
288    #[zbus(property)]
289    async fn text_direction(&self) -> String {
290        "ltr".to_string()
291    }
292
293    /// Empty: icons are named and resolved from the user's own theme, the
294    /// same rule the tray item follows.
295    #[zbus(property)]
296    async fn icon_theme_path(&self) -> Vec<String> {
297        Vec::new()
298    }
299
300    #[zbus(signal)]
301    pub async fn layout_updated(
302        emitter: &SignalEmitter<'_>,
303        revision: u32,
304        parent: i32,
305    ) -> zbus::Result<()>;
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::menu::MenuItem;
312
313    fn menu() -> Menu {
314        Menu::new(vec![
315            MenuItem::checkmark("Wi-Fi", true, "radio:toggle"),
316            MenuItem::separator(),
317            MenuItem::standard("home", "connect:home"),
318        ])
319    }
320
321    /// Both forms of "about to show" must announce. Hosts use one or
322    /// the other, so implementing only the singular means the refresh
323    /// silently never happens on half of them — and silence is exactly
324    /// what that failure looks like.
325    #[tokio::test]
326    async fn both_forms_of_about_to_show_announce_which_menu_opened() {
327        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
328        let iface = MenuInterface::new(
329            "hyprforge-network".to_string(),
330            Arc::new(Mutex::new(menu())),
331            Arc::new(Mutex::new(1)),
332            tx,
333        );
334
335        assert!(!iface.about_to_show(0).await, "the served layout is current");
336        assert_eq!(
337            rx.recv().await.unwrap(),
338            "menu:opened:hyprforge-network",
339            "the event carries the id, so a daemon knows which menu it was"
340        );
341
342        let _ = iface.about_to_show_group(vec![0]).await;
343        assert_eq!(rx.recv().await.unwrap(), "menu:opened:hyprforge-network");
344    }
345
346    /// A separator must say so. Without `type = separator` a host draws a
347    /// clickable blank row where the rule should be.
348    #[test]
349    fn a_separator_is_marked_as_one_and_carries_nothing_else() {
350        let menu = menu();
351        let sep = menu.flatten().into_iter().find(|i| i.kind == ItemKind::Separator).unwrap();
352        let props = properties(sep);
353        assert_eq!(
354            String::try_from(props["type"].clone()).unwrap(),
355            "separator"
356        );
357        assert!(!props.contains_key("label"), "a separator has no label to draw");
358    }
359
360    /// A checkmark needs both keys. `toggle-state` alone draws nothing,
361    /// because the host does not know it is a checkbox.
362    #[test]
363    fn a_checkmark_sends_both_the_type_and_the_state() {
364        let menu = menu();
365        let wifi = menu.flatten().into_iter().find(|i| i.label == "Wi-Fi").unwrap();
366        let props = properties(wifi);
367        assert_eq!(
368            String::try_from(props["toggle-type"].clone()).unwrap(),
369            "checkmark"
370        );
371        assert_eq!(i32::try_from(props["toggle-state"].clone()).unwrap(), 1);
372    }
373
374    #[test]
375    fn an_ordinary_row_is_not_given_a_toggle_a_host_would_draw() {
376        let menu = menu();
377        let home = menu.flatten().into_iter().find(|i| i.label == "home").unwrap();
378        let props = properties(home);
379        assert!(!props.contains_key("toggle-type"));
380        assert!(!props.contains_key("toggle-state"));
381    }
382
383    /// The shape the whole protocol turns on. A node is
384    /// `(id, a{sv}, av)`, and the children are variants each wrapping
385    /// another node — get this wrong and the host shows an empty popup
386    /// with nothing logged at either end.
387    #[test]
388    fn a_layout_node_has_three_fields_and_its_children_are_nested_nodes() {
389        let menu = menu();
390        let root = node(0, HashMap::new(), &menu.items, -1);
391        assert_eq!(root.0, 0, "the root is id 0");
392        assert_eq!(root.2.len(), 3, "three top-level rows");
393
394        // Each child must be a variant wrapping another node of the same
395        // shape — that recursion is the whole protocol.
396        let first = root.2.first().expect("a child");
397        let Value::Structure(child) = Value::from(first.clone()) else {
398            panic!("each child is a variant wrapping a structure");
399        };
400        assert_eq!(
401            child.fields().len(),
402            3,
403            "a child is a node of the same (id, properties, children) shape"
404        );
405    }
406
407    /// `recursion_depth = 0` means one level only. A host asking for one
408    /// level and receiving the whole tree is merely wasteful; a host
409    /// asking for everything and receiving one level shows empty
410    /// submenus.
411    #[test]
412    fn depth_zero_returns_the_node_without_its_children() {
413        let menu = Menu::new(vec![MenuItem {
414            children: vec![MenuItem::standard("child", "c")],
415            ..MenuItem::standard("parent", "p")
416        }]);
417        let shallow = node(0, HashMap::new(), &menu.items, 0);
418        assert!(shallow.2.is_empty(), "depth 0 stops at this node");
419    }
420
421    /// The signature hosts parse against. A wrong one here is the failure
422    /// this whole module's comment warns about: an empty popup, logged
423    /// nowhere.
424    #[test]
425    fn the_layout_node_signature_is_the_one_the_protocol_specifies() {
426        assert_eq!(LayoutNode::SIGNATURE.to_string(), "(ia{sv}av)");
427    }
428}