1use 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#[derive(Debug, Clone, serde::Serialize, Type)]
40pub struct LayoutNode(i32, HashMap<String, OwnedValue>, Vec<OwnedValue>);
41
42fn properties(item: &MenuItem) -> HashMap<String, OwnedValue> {
44 let mut props: HashMap<String, OwnedValue> = HashMap::new();
45
46 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 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 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
93fn 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
123fn 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
138pub struct MenuInterface {
140 id: String,
142 menu: Arc<Mutex<Menu>>,
143 revision: Arc<Mutex<u32>>,
144 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 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 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 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 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 async fn about_to_show(&self, _id: i32) -> bool {
267 let _ = self.events.send(format!("{OPENED_PREFIX}{}", self.id));
268 false
269 }
270
271 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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}