1use std::path::Path;
23use std::sync::atomic::{AtomicU32, Ordering};
24use std::sync::{Arc, Mutex};
25
26use super::{
27 BUS_INTERFACE, BUS_NAME, Connection, Error, Message, MethodCall, MethodError,
28 NAME_FLAG_DO_NOT_QUEUE, NAME_REPLY_ALREADY_OWNER, NAME_REPLY_PRIMARY_OWNER,
29 PROPERTIES_INTERFACE, SignalFilter, SubscriptionId, Value, introspection_xml, lock,
30};
31
32pub const ITEM_PATH: &str = "/StatusNotifierItem";
34pub const MENU_PATH: &str = "/MenuBar";
36pub const ITEM_INTERFACE: &str = "org.kde.StatusNotifierItem";
38pub const MENU_INTERFACE: &str = "com.canonical.dbusmenu";
40pub const WATCHER_NAME: &str = "org.kde.StatusNotifierWatcher";
42pub const WATCHER_PATH: &str = "/StatusNotifierWatcher";
44
45#[must_use]
47pub fn watcher_available(conn: &Connection) -> bool {
48 conn.name_has_owner(WATCHER_NAME)
49}
50
51#[derive(Clone, Debug, Default, PartialEq, Eq)]
55pub struct Pixmap {
56 pub width: i32,
58 pub height: i32,
60 pub argb: Vec<u32>,
62}
63
64impl Pixmap {
65 #[must_use]
68 pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Option<Pixmap> {
69 let pixels = usize::try_from(u64::from(width) * u64::from(height)).ok()?;
70 if rgba.len() != pixels.checked_mul(4)? {
71 return None;
72 }
73 Some(Pixmap {
74 width: i32::try_from(width).ok()?,
75 height: i32::try_from(height).ok()?,
76 argb: rgba
77 .as_chunks::<4>()
78 .0
79 .iter()
80 .map(|[r, g, b, a]| u32::from_be_bytes([*a, *r, *g, *b]))
81 .collect(),
82 })
83 }
84
85 fn to_value(&self) -> Option<Value> {
87 let expected = usize::try_from(self.width).ok()? * usize::try_from(self.height).ok()?;
88 if expected != self.argb.len() {
89 return None;
90 }
91 let mut bytes = Vec::with_capacity(expected * 4);
92 for px in &self.argb {
93 bytes.extend_from_slice(&px.to_be_bytes());
94 }
95 Some(Value::Struct(vec![
96 Value::I32(self.width),
97 Value::I32(self.height),
98 Value::bytes(&bytes),
99 ]))
100 }
101}
102
103fn pixmaps_value(pixmaps: &[Pixmap]) -> Value {
104 Value::array(
105 "(iiay)",
106 pixmaps.iter().filter_map(Pixmap::to_value).collect(),
107 )
108}
109
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
112pub enum Status {
113 #[default]
115 Active,
116 Passive,
118 NeedsAttention,
120}
121
122impl Status {
123 fn as_str(self) -> &'static str {
124 match self {
125 Status::Active => "Active",
126 Status::Passive => "Passive",
127 Status::NeedsAttention => "NeedsAttention",
128 }
129 }
130}
131
132#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
134pub enum Category {
135 #[default]
137 ApplicationStatus,
138 Communications,
140 SystemServices,
142 Hardware,
144}
145
146impl Category {
147 fn as_str(self) -> &'static str {
148 match self {
149 Category::ApplicationStatus => "ApplicationStatus",
150 Category::Communications => "Communications",
151 Category::SystemServices => "SystemServices",
152 Category::Hardware => "Hardware",
153 }
154 }
155}
156
157#[derive(Clone, Debug, Default, PartialEq)]
159pub struct Item {
160 pub id: String,
162 pub title: String,
164 pub tooltip: String,
166 pub icon_name: String,
168 pub icon_theme_path: String,
170 pub icon_pixmaps: Vec<Pixmap>,
172 pub status: Status,
174 pub category: Category,
176 pub item_is_menu: bool,
178}
179
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
182pub enum Check {
183 #[default]
185 None,
186 On,
188 Off,
190}
191
192#[derive(Clone, Debug, PartialEq, Eq)]
195#[must_use]
196pub struct MenuEntry {
197 pub id: i32,
199 pub label: String,
201 pub enabled: bool,
203 pub visible: bool,
205 pub check: Check,
207 pub separator: bool,
209 pub children: Vec<MenuEntry>,
211}
212
213impl MenuEntry {
214 pub fn item(id: i32, label: impl Into<String>) -> Self {
216 MenuEntry {
217 id,
218 label: label.into(),
219 enabled: true,
220 visible: true,
221 check: Check::None,
222 separator: false,
223 children: Vec::new(),
224 }
225 }
226
227 pub fn separator(id: i32) -> Self {
229 MenuEntry {
230 separator: true,
231 ..MenuEntry::item(id, "")
232 }
233 }
234
235 pub fn submenu(id: i32, label: impl Into<String>, children: Vec<MenuEntry>) -> Self {
237 MenuEntry {
238 children,
239 ..MenuEntry::item(id, label)
240 }
241 }
242
243 pub fn with_check(mut self, check: Check) -> Self {
245 self.check = check;
246 self
247 }
248
249 pub fn with_enabled(mut self, enabled: bool) -> Self {
251 self.enabled = enabled;
252 self
253 }
254}
255
256#[derive(Clone, Debug, PartialEq, Eq)]
258pub enum Event {
259 Activate {
261 x: i32,
263 y: i32,
265 },
266 SecondaryActivate {
268 x: i32,
270 y: i32,
272 },
273 ContextMenu {
276 x: i32,
278 y: i32,
280 },
281 Scroll {
283 delta: i32,
285 horizontal: bool,
287 },
288 MenuItem {
290 id: i32,
292 },
293}
294
295struct State {
296 item: Item,
297 menu: Vec<MenuEntry>,
298 revision: u32,
299}
300
301type EventFn = dyn FnMut(Event) + Send;
302
303struct Core {
304 state: Mutex<State>,
305 on_event: Mutex<Box<EventFn>>,
306}
307
308impl Core {
309 fn deliver(&self, event: Event) {
310 let mut callback = lock(&self.on_event);
311 (callback)(event);
312 }
313}
314
315pub struct StatusItem {
317 conn: Connection,
318 core: Arc<Core>,
319 service: String,
320 owns_name: bool,
321 subscription: Option<SubscriptionId>,
322 match_rule: String,
323}
324
325static NEXT_ITEM: AtomicU32 = AtomicU32::new(1);
326
327fn sandboxed() -> bool {
328 Path::new("/.flatpak-info").exists() || std::env::var_os("SNAP").is_some()
329}
330
331impl StatusItem {
332 pub fn new<F>(
341 conn: &Connection,
342 item: Item,
343 menu: Vec<MenuEntry>,
344 on_event: F,
345 ) -> Result<StatusItem, Error>
346 where
347 F: FnMut(Event) + Send + 'static,
348 {
349 let core = Arc::new(Core {
350 state: Mutex::new(State {
351 item,
352 menu,
353 revision: 1,
354 }),
355 on_event: Mutex::new(Box::new(on_event)),
356 });
357 let item_core = core.clone();
358 conn.export(ITEM_PATH, move |call| item_call(&item_core, call))?;
359 let menu_core = core.clone();
360 if let Err(e) = conn.export(MENU_PATH, move |call| menu_call(&menu_core, call)) {
361 conn.unexport(ITEM_PATH);
363 return Err(e);
364 }
365 let mut this = StatusItem {
367 conn: conn.clone(),
368 core,
369 service: conn.unique_name().to_owned(),
370 owns_name: false,
371 subscription: None,
372 match_rule: String::new(),
373 };
374
375 if !sandboxed() {
376 let n = NEXT_ITEM.fetch_add(1, Ordering::Relaxed);
377 let name = format!("org.kde.StatusNotifierItem-{}-{n}", std::process::id());
378 match conn.request_name(&name, NAME_FLAG_DO_NOT_QUEUE)? {
379 NAME_REPLY_PRIMARY_OWNER | NAME_REPLY_ALREADY_OWNER => {
380 this.service = name;
381 this.owns_name = true;
382 }
383 code => {
384 return Err(Error::Protocol(format!(
385 "could not own {name} (RequestName answered {code})"
386 )));
387 }
388 }
389 }
390
391 let rule = format!(
394 "type='signal',sender='{BUS_NAME}',interface='{BUS_INTERFACE}',\
395 member='NameOwnerChanged',arg0='{WATCHER_NAME}'"
396 );
397 conn.add_match(&rule)?;
398 this.match_rule = rule;
399 let service = this.service.clone();
400 this.subscription = Some(
401 conn.on_signal(
402 SignalFilter::new()
403 .sender(BUS_NAME)
404 .interface(BUS_INTERFACE)
405 .member("NameOwnerChanged"),
406 move |conn, msg| watcher_changed(conn, msg, &service),
407 ),
408 );
409 if watcher_available(conn) {
410 conn.call(
411 WATCHER_NAME,
412 WATCHER_PATH,
413 WATCHER_NAME,
414 "RegisterStatusNotifierItem",
415 &[Value::str(&this.service)],
416 )?;
417 }
418 Ok(this)
419 }
420
421 #[must_use]
424 pub fn service(&self) -> &str {
425 &self.service
426 }
427
428 fn emit(&self, member: &str, args: &[Value]) -> Result<(), Error> {
429 self.conn
430 .emit_signal(ITEM_PATH, ITEM_INTERFACE, member, args)
431 }
432
433 pub fn set_menu(&self, menu: Vec<MenuEntry>) -> Result<(), Error> {
439 let revision = {
440 let mut state = lock(&self.core.state);
441 state.menu = menu;
442 state.revision = state.revision.wrapping_add(1);
443 state.revision
444 };
445 self.conn.emit_signal(
446 MENU_PATH,
447 MENU_INTERFACE,
448 "LayoutUpdated",
449 &[Value::U32(revision), Value::I32(0)],
450 )
451 }
452
453 pub fn set_icon(&self, icon_name: &str, pixmaps: Vec<Pixmap>) -> Result<(), Error> {
459 {
460 let mut state = lock(&self.core.state);
461 icon_name.clone_into(&mut state.item.icon_name);
462 state.item.icon_pixmaps = pixmaps;
463 }
464 self.emit("NewIcon", &[])
465 }
466
467 pub fn set_title(&self, title: &str) -> Result<(), Error> {
473 title.clone_into(&mut lock(&self.core.state).item.title);
474 self.emit("NewTitle", &[])
475 }
476
477 pub fn set_tooltip(&self, tooltip: &str) -> Result<(), Error> {
483 tooltip.clone_into(&mut lock(&self.core.state).item.tooltip);
484 self.emit("NewToolTip", &[])
485 }
486
487 pub fn set_status(&self, status: Status) -> Result<(), Error> {
493 lock(&self.core.state).item.status = status;
494 self.emit("NewStatus", &[Value::str(status.as_str())])
495 }
496}
497
498impl Drop for StatusItem {
499 fn drop(&mut self) {
500 self.conn.unexport(ITEM_PATH);
502 self.conn.unexport(MENU_PATH);
503 if let Some(id) = self.subscription.take() {
504 self.conn.remove_signal_handler(id);
505 }
506 if !self.match_rule.is_empty() {
507 let _ = self.conn.remove_match(&self.match_rule);
508 }
509 if self.owns_name {
510 let _ = self.conn.release_name(&self.service);
511 }
512 }
513}
514
515fn watcher_changed(conn: &Connection, msg: &Message, service: &str) {
516 if let [Value::Str(name), _, Value::Str(new_owner)] = msg.body.as_slice()
517 && name == WATCHER_NAME
518 && !new_owner.is_empty()
519 {
520 let _ = conn.call_no_reply(
522 WATCHER_NAME,
523 WATCHER_PATH,
524 WATCHER_NAME,
525 "RegisterStatusNotifierItem",
526 &[Value::str(service)],
527 );
528 }
529}
530
531fn item_property(item: &Item, name: &str) -> Option<Value> {
536 let empty_pixmaps = || pixmaps_value(&[]);
537 Some(match name {
538 "Category" => Value::str(item.category.as_str()),
539 "Id" => Value::str(&item.id),
540 "Title" => Value::str(&item.title),
541 "Status" => Value::str(item.status.as_str()),
542 "WindowId" => Value::I32(0),
543 "IconName" => Value::str(&item.icon_name),
544 "IconThemePath" => Value::str(&item.icon_theme_path),
545 "IconPixmap" => pixmaps_value(&item.icon_pixmaps),
546 "OverlayIconName" | "AttentionIconName" | "AttentionMovieName" => Value::str(""),
547 "OverlayIconPixmap" | "AttentionIconPixmap" => empty_pixmaps(),
548 "ToolTip" => Value::Struct(vec![
549 Value::str(""),
550 empty_pixmaps(),
551 Value::str(if item.tooltip.is_empty() {
552 &item.title
553 } else {
554 &item.tooltip
555 }),
556 Value::str(""),
557 ]),
558 "ItemIsMenu" => Value::Bool(item.item_is_menu),
559 "Menu" => Value::path(MENU_PATH),
560 _ => return None,
561 })
562}
563
564const ITEM_PROPERTIES: &[&str] = &[
565 "Category",
566 "Id",
567 "Title",
568 "Status",
569 "WindowId",
570 "IconName",
571 "IconThemePath",
572 "IconPixmap",
573 "OverlayIconName",
574 "OverlayIconPixmap",
575 "AttentionIconName",
576 "AttentionIconPixmap",
577 "AttentionMovieName",
578 "ToolTip",
579 "ItemIsMenu",
580 "Menu",
581];
582
583const ITEM_XML: &str = r#" <interface name="org.kde.StatusNotifierItem">
584 <property name="Category" type="s" access="read"/>
585 <property name="Id" type="s" access="read"/>
586 <property name="Title" type="s" access="read"/>
587 <property name="Status" type="s" access="read"/>
588 <property name="WindowId" type="i" access="read"/>
589 <property name="IconName" type="s" access="read"/>
590 <property name="IconThemePath" type="s" access="read"/>
591 <property name="IconPixmap" type="a(iiay)" access="read"/>
592 <property name="OverlayIconName" type="s" access="read"/>
593 <property name="OverlayIconPixmap" type="a(iiay)" access="read"/>
594 <property name="AttentionIconName" type="s" access="read"/>
595 <property name="AttentionIconPixmap" type="a(iiay)" access="read"/>
596 <property name="AttentionMovieName" type="s" access="read"/>
597 <property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
598 <property name="ItemIsMenu" type="b" access="read"/>
599 <property name="Menu" type="o" access="read"/>
600 <method name="ContextMenu"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
601 <method name="Activate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
602 <method name="SecondaryActivate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
603 <method name="Scroll"><arg name="delta" type="i" direction="in"/><arg name="orientation" type="s" direction="in"/></method>
604 <signal name="NewTitle"/>
605 <signal name="NewIcon"/>
606 <signal name="NewAttentionIcon"/>
607 <signal name="NewOverlayIcon"/>
608 <signal name="NewToolTip"/>
609 <signal name="NewStatus"><arg name="status" type="s"/></signal>
610 </interface>
611 <interface name="org.freedesktop.DBus.Properties">
612 <method name="Get"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
613 <method name="GetAll"><arg type="s" direction="in"/><arg type="a{sv}" direction="out"/></method>
614 </interface>
615"#;
616
617fn point(args: &[Value]) -> Result<(i32, i32), MethodError> {
619 match args {
620 [Value::I32(x), Value::I32(y)] => Ok((*x, *y)),
621 _ => Err(MethodError::invalid_args("expected (ii)")),
622 }
623}
624
625fn string_arg(args: &[Value], at: usize) -> Result<&str, MethodError> {
626 match args.get(at) {
627 Some(Value::Str(s)) => Ok(s),
628 _ => Err(MethodError::invalid_args(format!(
629 "argument {at} must be a string"
630 ))),
631 }
632}
633
634fn properties(
636 call: &MethodCall,
637 interface: &str,
638 names: &[&str],
639 get: impl Fn(&str) -> Option<Value>,
640) -> Result<Vec<Value>, MethodError> {
641 match call.member.as_str() {
642 "Get" => {
643 let (iface, name) = (string_arg(&call.args, 0)?, string_arg(&call.args, 1)?);
644 match get(name) {
645 Some(v) if iface == interface || iface.is_empty() => Ok(vec![Value::variant(v)]),
646 _ => Err(MethodError::unknown_property(name)),
647 }
648 }
649 "GetAll" => {
650 let iface = string_arg(&call.args, 0)?;
651 let all = if iface == interface || iface.is_empty() {
652 names
653 .iter()
654 .filter_map(|n| get(n).map(|v| (*n, v)))
655 .collect()
656 } else {
657 Vec::new()
658 };
659 Ok(vec![Value::props(all)])
660 }
661 "Set" => Err(MethodError::new(
662 "org.freedesktop.DBus.Error.PropertyReadOnly",
663 "properties are read-only",
664 )),
665 _ => Err(MethodError::unknown_method(call)),
666 }
667}
668
669fn item_call(core: &Core, call: &MethodCall) -> Result<Vec<Value>, MethodError> {
670 match call.interface.as_deref() {
671 Some(PROPERTIES_INTERFACE) => {
672 let item = lock(&core.state).item.clone();
673 return properties(call, ITEM_INTERFACE, ITEM_PROPERTIES, |n| {
674 item_property(&item, n)
675 });
676 }
677 Some(super::INTROSPECTABLE_INTERFACE) | None if call.member == "Introspect" => {
678 return Ok(vec![Value::Str(introspection_xml(ITEM_XML, &[]))]);
679 }
680 Some(ITEM_INTERFACE) | None => {}
681 Some(_) => return Err(MethodError::unknown_method(call)),
682 }
683 let event = match call.member.as_str() {
684 "Activate" => {
685 let (x, y) = point(&call.args)?;
686 Event::Activate { x, y }
687 }
688 "SecondaryActivate" => {
689 let (x, y) = point(&call.args)?;
690 Event::SecondaryActivate { x, y }
691 }
692 "ContextMenu" => {
693 let (x, y) = point(&call.args)?;
694 Event::ContextMenu { x, y }
695 }
696 "Scroll" => match call.args.as_slice() {
697 [Value::I32(delta), Value::Str(orientation)] => Event::Scroll {
698 delta: *delta,
699 horizontal: orientation.eq_ignore_ascii_case("horizontal"),
700 },
701 _ => return Err(MethodError::invalid_args("expected (is)")),
702 },
703 "ProvideXdgActivationToken" => return Ok(Vec::new()),
705 _ => return Err(MethodError::unknown_method(call)),
706 };
707 core.deliver(event);
708 Ok(Vec::new())
709}
710
711const MENU_XML: &str = r#" <interface name="com.canonical.dbusmenu">
716 <property name="Version" type="u" access="read"/>
717 <property name="TextDirection" type="s" access="read"/>
718 <property name="Status" type="s" access="read"/>
719 <property name="IconThemePath" type="as" access="read"/>
720 <method name="GetLayout"><arg type="i" name="parentId" direction="in"/><arg type="i" name="recursionDepth" direction="in"/><arg type="as" name="propertyNames" direction="in"/><arg type="u" name="revision" direction="out"/><arg type="(ia{sv}av)" name="layout" direction="out"/></method>
721 <method name="GetGroupProperties"><arg type="ai" name="ids" direction="in"/><arg type="as" name="propertyNames" direction="in"/><arg type="a(ia{sv})" name="properties" direction="out"/></method>
722 <method name="GetProperty"><arg type="i" name="id" direction="in"/><arg type="s" name="name" direction="in"/><arg type="v" name="value" direction="out"/></method>
723 <method name="Event"><arg type="i" name="id" direction="in"/><arg type="s" name="eventId" direction="in"/><arg type="v" name="data" direction="in"/><arg type="u" name="timestamp" direction="in"/></method>
724 <method name="EventGroup"><arg type="a(isvu)" name="events" direction="in"/><arg type="ai" name="idErrors" direction="out"/></method>
725 <method name="AboutToShow"><arg type="i" name="id" direction="in"/><arg type="b" name="needUpdate" direction="out"/></method>
726 <method name="AboutToShowGroup"><arg type="ai" name="ids" direction="in"/><arg type="ai" name="updatesNeeded" direction="out"/><arg type="ai" name="idErrors" direction="out"/></method>
727 <signal name="ItemsPropertiesUpdated"><arg type="a(ia{sv})" name="updatedProps"/><arg type="a(ias)" name="removedProps"/></signal>
728 <signal name="LayoutUpdated"><arg type="u" name="revision"/><arg type="i" name="parent"/></signal>
729 <signal name="ItemActivationRequested"><arg type="i" name="id"/><arg type="u" name="timestamp"/></signal>
730 </interface>
731 <interface name="org.freedesktop.DBus.Properties">
732 <method name="Get"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
733 <method name="GetAll"><arg type="s" direction="in"/><arg type="a{sv}" direction="out"/></method>
734 </interface>
735"#;
736
737const MENU_PROPERTIES: &[&str] = &["Version", "TextDirection", "Status", "IconThemePath"];
738
739fn menu_property(name: &str) -> Option<Value> {
740 Some(match name {
741 "Version" => Value::U32(3),
742 "TextDirection" => Value::str("ltr"),
743 "Status" => Value::str("normal"),
744 "IconThemePath" => Value::strings::<&str>(&[]),
745 _ => return None,
746 })
747}
748
749fn find(entries: &[MenuEntry], id: i32) -> Option<&MenuEntry> {
750 entries.iter().find_map(|e| {
751 if e.id == id {
752 Some(e)
753 } else {
754 find(&e.children, id)
755 }
756 })
757}
758
759fn all_entries(entries: &[MenuEntry], out: &mut Vec<(i32, Vec<(&'static str, Value)>)>) {
760 for e in entries {
761 out.push((e.id, entry_props(e)));
762 all_entries(&e.children, out);
763 }
764}
765
766fn escape_label(label: &str) -> String {
768 label.replace('_', "__")
769}
770
771fn entry_props(e: &MenuEntry) -> Vec<(&'static str, Value)> {
773 let mut props = Vec::new();
774 if e.separator {
775 props.push(("type", Value::str("separator")));
776 } else {
777 props.push(("label", Value::str(escape_label(&e.label))));
778 props.push(("enabled", Value::Bool(e.enabled)));
779 }
780 props.push(("visible", Value::Bool(e.visible)));
781 if e.check != Check::None && !e.separator {
782 props.push(("toggle-type", Value::str("checkmark")));
783 props.push(("toggle-state", Value::I32(i32::from(e.check == Check::On))));
784 }
785 if !e.children.is_empty() {
786 props.push(("children-display", Value::str("submenu")));
787 }
788 props
789}
790
791fn root_props() -> Vec<(&'static str, Value)> {
792 vec![("children-display", Value::str("submenu"))]
793}
794
795fn filtered(props: Vec<(&'static str, Value)>, names: &[String]) -> Value {
796 Value::props(
797 props
798 .into_iter()
799 .filter(|(k, _)| names.is_empty() || names.iter().any(|n| n == k)),
800 )
801}
802
803fn layout(
804 id: i32,
805 props: Vec<(&'static str, Value)>,
806 children: &[MenuEntry],
807 depth: i32,
808 names: &[String],
809) -> Value {
810 let kids = if depth == 0 {
811 Vec::new()
812 } else {
813 let next = if depth < 0 { -1 } else { depth - 1 };
814 children
815 .iter()
816 .map(|c| Value::variant(layout(c.id, entry_props(c), &c.children, next, names)))
817 .collect()
818 };
819 Value::Struct(vec![
820 Value::I32(id),
821 filtered(props, names),
822 Value::array("v", kids),
823 ])
824}
825
826fn string_list(v: Option<&Value>) -> Vec<String> {
827 v.and_then(Value::as_array)
828 .unwrap_or_default()
829 .iter()
830 .filter_map(|s| s.as_str().map(str::to_owned))
831 .collect()
832}
833
834fn int_list(v: Option<&Value>) -> Vec<i32> {
835 v.and_then(Value::as_array)
836 .unwrap_or_default()
837 .iter()
838 .filter_map(|n| match n {
839 Value::I32(n) => Some(*n),
840 _ => None,
841 })
842 .collect()
843}
844
845fn menu_event(core: &Core, id: i32, event_id: &str) -> bool {
847 let clickable = {
848 let state = lock(&core.state);
849 if id == 0 {
850 Some(false)
851 } else {
852 find(&state.menu, id).map(|e| e.enabled && !e.separator)
853 }
854 };
855 match clickable {
856 None => false,
857 Some(clickable) => {
858 if clickable && event_id == "clicked" {
859 core.deliver(Event::MenuItem { id });
860 }
861 true
862 }
863 }
864}
865
866fn menu_call(core: &Core, call: &MethodCall) -> Result<Vec<Value>, MethodError> {
867 match call.interface.as_deref() {
868 Some(PROPERTIES_INTERFACE) => {
869 return properties(call, MENU_INTERFACE, MENU_PROPERTIES, menu_property);
870 }
871 Some(super::INTROSPECTABLE_INTERFACE) | None if call.member == "Introspect" => {
872 return Ok(vec![Value::Str(introspection_xml(MENU_XML, &[]))]);
873 }
874 Some(MENU_INTERFACE) | None => {}
875 Some(_) => return Err(MethodError::unknown_method(call)),
876 }
877 let args = call.args.as_slice();
878 match call.member.as_str() {
879 "GetLayout" => {
880 let [Value::I32(parent), Value::I32(depth), names] = args else {
881 return Err(MethodError::invalid_args("expected (iias)"));
882 };
883 let names = string_list(Some(names));
884 let state = lock(&core.state);
885 let node = if *parent == 0 {
886 layout(0, root_props(), &state.menu, *depth, &names)
887 } else {
888 let entry = find(&state.menu, *parent)
889 .ok_or_else(|| MethodError::invalid_args(format!("no menu entry {parent}")))?;
890 layout(
891 entry.id,
892 entry_props(entry),
893 &entry.children,
894 *depth,
895 &names,
896 )
897 };
898 Ok(vec![Value::U32(state.revision), node])
899 }
900 "GetGroupProperties" => {
901 let ids = int_list(args.first());
902 let names = string_list(args.get(1));
903 let state = lock(&core.state);
904 let mut rows = Vec::new();
905 if ids.is_empty() {
906 all_entries(&state.menu, &mut rows);
907 } else {
908 for id in ids {
909 if id == 0 {
910 rows.push((0, root_props()));
911 } else if let Some(e) = find(&state.menu, id) {
912 rows.push((id, entry_props(e)));
913 }
914 }
915 }
916 let rows = rows
917 .into_iter()
918 .map(|(id, props)| Value::Struct(vec![Value::I32(id), filtered(props, &names)]))
919 .collect();
920 Ok(vec![Value::array("(ia{sv})", rows)])
921 }
922 "GetProperty" => {
923 let [Value::I32(id), Value::Str(name)] = args else {
924 return Err(MethodError::invalid_args("expected (is)"));
925 };
926 let state = lock(&core.state);
927 let props = if *id == 0 {
928 root_props()
929 } else {
930 find(&state.menu, *id)
931 .map(entry_props)
932 .ok_or_else(|| MethodError::invalid_args(format!("no menu entry {id}")))?
933 };
934 props
935 .into_iter()
936 .find(|(k, _)| k == name)
937 .map(|(_, v)| vec![Value::variant(v)])
938 .ok_or_else(|| MethodError::unknown_property(name))
939 }
940 "Event" => {
941 let [Value::I32(id), Value::Str(event_id), ..] = args else {
942 return Err(MethodError::invalid_args("expected (isvu)"));
943 };
944 if menu_event(core, *id, event_id) {
945 Ok(Vec::new())
946 } else {
947 Err(MethodError::invalid_args(format!("no menu entry {id}")))
948 }
949 }
950 "EventGroup" => {
951 let events = args.first().and_then(Value::as_array).unwrap_or_default();
952 let mut errors = Vec::new();
953 for event in events {
954 if let Some([Value::I32(id), Value::Str(event_id), ..]) = event.as_struct()
955 && !menu_event(core, *id, event_id)
956 {
957 errors.push(Value::I32(*id));
958 }
959 }
960 Ok(vec![Value::array("i", errors)])
961 }
962 "AboutToShow" => Ok(vec![Value::Bool(false)]),
963 "AboutToShowGroup" => {
964 let state = lock(&core.state);
965 let errors = int_list(args.first())
966 .into_iter()
967 .filter(|id| *id != 0 && find(&state.menu, *id).is_none())
968 .map(Value::I32)
969 .collect();
970 Ok(vec![
971 Value::array("i", Vec::new()),
972 Value::array("i", errors),
973 ])
974 }
975 _ => Err(MethodError::unknown_method(call)),
976 }
977}
978
979#[cfg(test)]
980mod tests {
981 use super::*;
982
983 #[test]
984 fn pixmaps_go_out_big_endian_argb() {
985 let px = Pixmap::from_rgba(1, 1, &[0x10, 0x20, 0x30, 0xff]).expect("pixmap");
986 assert_eq!(px.argb, vec![0xff10_2030]);
987 let v = px.to_value().expect("value");
988 assert_eq!(
989 v,
990 Value::Struct(vec![
991 Value::I32(1),
992 Value::I32(1),
993 Value::bytes(&[0xff, 0x10, 0x20, 0x30])
994 ])
995 );
996 assert_eq!(pixmaps_value(&[px]).signature(), "a(iiay)");
997 assert!(Pixmap::from_rgba(2, 2, &[0; 4]).is_none());
998 let bad = Pixmap {
999 width: 2,
1000 height: 2,
1001 argb: vec![0],
1002 };
1003 assert!(bad.to_value().is_none());
1004 }
1005
1006 #[test]
1007 fn tooltip_and_properties_have_spec_signatures() {
1008 let item = Item {
1009 title: "T".into(),
1010 ..Item::default()
1011 };
1012 for name in ITEM_PROPERTIES {
1013 assert!(item_property(&item, name).is_some(), "{name}");
1014 }
1015 let tip = item_property(&item, "ToolTip").expect("tooltip");
1016 assert_eq!(tip.signature(), "(sa(iiay)ss)");
1017 assert_eq!(tip.as_struct().map(|f| f[2].clone()), Some(Value::str("T")));
1018 assert_eq!(item_property(&item, "Menu"), Some(Value::path(MENU_PATH)));
1019 let all: Vec<Value> = ITEM_PROPERTIES
1021 .iter()
1022 .filter_map(|n| item_property(&item, n))
1023 .collect();
1024 assert!(super::super::marshal(&all).is_ok());
1025 }
1026
1027 #[test]
1028 fn layout_respects_depth_and_names() {
1029 let menu = vec![
1030 MenuEntry::item(1, "Open_File").with_check(Check::On),
1031 MenuEntry::separator(2),
1032 MenuEntry::submenu(3, "More", vec![MenuEntry::item(4, "Deep")]),
1033 ];
1034 let full = layout(0, root_props(), &menu, -1, &[]);
1035 assert_eq!(full.signature(), "(ia{sv}av)");
1036 let kids = full.as_struct().expect("struct")[2].as_array().expect("av");
1037 assert_eq!(kids.len(), 3);
1038 let first = kids[0].as_struct().expect("child");
1039 assert_eq!(first[1].dict_get("label"), Some(&Value::str("Open__File")));
1040 assert_eq!(first[1].dict_get("toggle-state"), Some(&Value::I32(1)));
1041 let sub = kids[2].as_struct().expect("submenu");
1042 assert_eq!(sub[2].as_array().map(<[Value]>::len), Some(1));
1043
1044 let shallow = layout(0, root_props(), &menu, 1, &["label".into()]);
1045 let kids = shallow.as_struct().expect("struct")[2]
1046 .as_array()
1047 .expect("av");
1048 let sub = kids[2].as_struct().expect("submenu");
1049 assert_eq!(sub[2].as_array().map(<[Value]>::len), Some(0));
1050 assert_eq!(sub[1].as_array().map(<[Value]>::len), Some(1));
1051 assert!(super::super::marshal(&[full, shallow]).is_ok());
1052 }
1053}