Skip to main content

status_notifier/
lib.rs

1//! A [StatusNotifierHost](https://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/)
2//! for building system trays and similar applications.
3//!
4//! [`Host`] connects to the session bus, registers a `StatusNotifierHost` (and a built-in
5//! `StatusNotifierWatcher` if not already present), and keeps track of every registered item along
6//! with its menu. Changes are delivered as [`Event`]s through [`Host::process_events`], and items
7//! are interacted with through the `item_*` and `menu_*` methods.
8//!
9//! See the `blocking` and `polling` examples for usage.
10
11use std::collections::{HashMap, HashSet};
12use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
13use std::process;
14use std::time::{Duration, Instant};
15
16use dbus::MessageType;
17use dbus::arg::{AppendAll, RefArg, Variant};
18use dbus::channel::{BusType, Channel};
19use dbus::message::Message;
20
21const DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: u32 = 1;
22const DBUS_NAME_FLAG_DO_NOT_QUEUE: u32 = 4;
23
24/// The tooltip of an [`Item`].
25#[derive(Default, Debug, Clone, PartialEq)]
26pub struct ToolTip {
27    /// The freedesktop-compliant name of the tooltip's icon.
28    pub icon_name: String,
29    /// The tooltip's icon as raw image data, possibly in multiple sizes.
30    pub icon_pixmap: Vec<Pixmap>,
31    /// The title of the tooltip.
32    pub title: String,
33    /// Descriptive text for the tooltip. May contain a subset of HTML markup.
34    pub description: String,
35}
36
37/// An icon image provided by an item.
38#[derive(Default, Clone, PartialEq)]
39pub struct Pixmap {
40    /// The width and height of the image in pixels.
41    pub dimensions: [i32; 2],
42    /// The raw image data in ARGB32 format, in network (big-endian) byte order.
43    pub image_data: Vec<u8>,
44}
45
46impl std::fmt::Debug for Pixmap {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("Pixmap")
49            .field("dimensions", &self.dimensions)
50            .finish_non_exhaustive()
51    }
52}
53
54/// A `StatusNotifierItem` and its menu.
55///
56/// Most fields correspond directly to the properties of the `org.kde.StatusNotifierItem`
57/// interface. Fields an item doesn't provide are left with their default (empty) values.
58#[derive(Debug, Default, Clone, PartialEq)]
59pub struct Item {
60    /// The bus name the item is reachable at, used to identify it in the [`Host`] methods.
61    pub bus_name: String,
62    /// The category of the item, e.g. `ApplicationStatus`, `Communications`, `SystemServices`
63    /// or `Hardware`.
64    pub category: String,
65    /// A name unique to the application, e.g. its name.
66    pub id: String,
67    /// A human readable name of the item.
68    pub title: String,
69    /// The status of the item: `Passive`, `Active` or `NeedsAttention`.
70    pub status: String,
71    /// The windowing-system dependent id of the application's window, or `0` if there is none.
72    pub window_id: u64,
73    /// An additional path to search for the item's icons.
74    pub icon_theme_path: String,
75    /// The freedesktop-compliant name of the main icon.
76    pub icon_name: String,
77    /// The main icon as raw image data, possibly in multiple sizes.
78    pub icon_pixmap: Vec<Pixmap>,
79    /// The name of an icon overlayed on top of the main icon.
80    pub overlay_icon_name: String,
81    /// The overlay icon as raw image data, possibly in multiple sizes.
82    pub overlay_icon_pixmap: Vec<Pixmap>,
83    /// The name of the icon used when the status is `NeedsAttention`.
84    pub attention_icon_name: String,
85    /// The attention icon as raw image data, possibly in multiple sizes.
86    pub attention_icon_pixmap: Vec<Pixmap>,
87    /// The name of an animation used when the status is `NeedsAttention`.
88    pub attention_movie_name: String,
89    /// The tooltip of the item.
90    pub tool_tip: ToolTip,
91    /// Whether the item only supports a context menu; activation should open the menu instead.
92    pub item_is_menu: bool,
93    /// The root of the item's menu tree, [`MenuNode::Empty`] if the item has no menu.
94    pub menu: MenuNode,
95}
96
97/// PNG image data for the icon of a [`MenuNode::Item`].
98#[derive(Clone, PartialEq)]
99pub struct IconData(pub Vec<u8>);
100
101impl std::fmt::Debug for IconData {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        if self.0.is_empty() {
104            write!(f, "IconData(empty)")
105        } else {
106            write!(f, "IconData({} bytes)", self.0.len())
107        }
108    }
109}
110
111/// A node in the menu tree of an [`Item`].
112///
113/// Nodes are identified by their `id`, which is used with the `menu_*` methods of [`Host`].
114#[derive(Debug, Clone, Default, PartialEq)]
115pub enum MenuNode {
116    /// The item doesn't have a menu, or the menu hasn't been retrieved yet.
117    #[default]
118    Empty,
119    /// A (sub)menu containing other nodes.
120    Menu {
121        /// The id of the node.
122        id: i32,
123        /// The displayed text of the menu.
124        label: String,
125        /// Whether the menu can be opened.
126        enabled: bool,
127        /// Whether the menu should be shown.
128        visible: bool,
129        /// The nodes contained in the menu.
130        children: Vec<Self>,
131    },
132    /// An entry of a menu.
133    Item {
134        /// The id of the node.
135        id: i32,
136        /// The displayed text of the entry.
137        label: String,
138        /// Whether the entry can be clicked.
139        enabled: bool,
140        /// Whether the entry should be shown.
141        visible: bool,
142        /// The freedesktop-compliant name of the entry's icon.
143        icon_name: String,
144        /// PNG data of the entry's icon.
145        icon_data: IconData,
146        /// How the entry can be toggled.
147        toggle_type: ToggleType,
148        /// The current toggle state of the entry.
149        toggle_state: ToggleState,
150    },
151    /// A separator between entries.
152    Separator {
153        /// The id of the node.
154        id: i32,
155        /// Whether the separator should be shown.
156        visible: bool,
157    },
158}
159
160/// How a [`MenuNode::Item`] can be toggled.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum ToggleType {
163    /// The entry can't be toggled.
164    None,
165    /// The entry can be toggled independently, like a checkbox.
166    Checkmark,
167    /// The entry is part of a group where only one entry is toggled at a time, like a radio
168    /// button.
169    Radio,
170}
171
172/// The toggle state of a [`MenuNode::Item`].
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum ToggleState {
175    /// The entry is toggled on.
176    On,
177    /// The entry is toggled off.
178    Off,
179    /// The state is indeterminate, or the entry can't be toggled.
180    Unknown,
181}
182
183struct IntlItem {
184    menu_path: String,
185    menu_revision: u32,
186    item_op: Option<Item>,
187}
188
189/// A change of an [`Item`], delivered through the `event_fn` of [`Host::process_events`].
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum Event {
192    /// The item was registered and its properties retrieved.
193    ///
194    /// **Note**: The item's menu will not be fetched at the time of this event, but all other
195    /// item properties *should be* present.
196    Added,
197    /// The item was removed.
198    Removed,
199    /// [`Item::title`] was updated.
200    UpdatedTitle,
201    /// [`Item::status`] was updated.
202    UpdatedStatus,
203    /// [`Item::icon_theme_path`] was updated.
204    UpdatedIconThemePath,
205    /// [`Item::icon_name`] was updated.
206    UpdatedIconName,
207    /// [`Item::icon_pixmap`] was updated.
208    UpdatedIconPixmap,
209    /// [`Item::attention_icon_name`] was updated.
210    UpdatedAttentionIconName,
211    /// [`Item::attention_icon_pixmap`] was updated.
212    UpdatedAttentionIconPixmap,
213    /// [`Item::overlay_icon_name`] was updated.
214    UpdatedOverlayIconName,
215    /// [`Item::overlay_icon_pixmap`] was updated.
216    UpdatedOverlayIconPixmap,
217    /// [`Item::tool_tip`] was updated.
218    UpdatedToolTip,
219    /// [`Item::menu`] was updated.
220    UpdatedMenu,
221}
222
223struct Watcher {
224    hosts: HashSet<String>,
225    items: HashSet<String>,
226}
227
228enum ReplyTo {
229    RegisterHost,
230    NotifierItems,
231    ItemGetAll {
232        item_name: String,
233    },
234    ItemGet {
235        item_name: String,
236        property: &'static str,
237    },
238    MenuGetLayout {
239        item_name: String,
240        parent_id: i32,
241    },
242    ItemMethod {
243        item_name: String,
244    },
245    MenuEvent {
246        item_name: String,
247    },
248}
249
250/// The main object representing a `StatusNotifierHost`.
251///
252/// A `Host` connects to the session bus and keeps track of every registered `StatusNotifierItem`
253/// along with its menu. Item state is kept up to date, and changes are delivered as [`Event`]s,
254/// by calling [`Host::process_events`].
255///
256/// `Host` implements [`AsFd`], so instead of polling, the underlying connection can be registered
257/// with `poll`/`epoll`-style event loops to wait for activity (see the `polling` example).
258///
259/// **Note**: The built-in `StatusNotifierWatcher` will only be used if there isn't a
260/// `StatusNotifierWatcher` already registered.
261pub struct Host {
262    channel: Channel,
263    bus_name: String,
264    items: HashMap<String, IntlItem>,
265    intl_watcher_op: Option<Watcher>,
266    pending_replies: HashMap<u32, (Instant, ReplyTo)>,
267}
268
269/// The error type used throughout the library.
270///
271/// [`operation`](Error::operation) tracks where the error originated and [`kind`](Error::kind)
272/// what went wrong.
273#[derive(Debug)]
274pub struct Error {
275    /// The operation the error originated from.
276    pub operation: Operation,
277    /// What went wrong.
278    pub kind: ErrorKind,
279    /// The bus name of the remote peer involved, when known.
280    pub peer: Option<String>,
281}
282
283impl Error {
284    fn new(operation: Operation, kind: ErrorKind) -> Self {
285        Self {
286            operation,
287            kind,
288            peer: None,
289        }
290    }
291
292    fn with_peer<P>(operation: Operation, kind: ErrorKind, peer: P) -> Self
293    where
294        P: Into<String>,
295    {
296        Self {
297            operation,
298            kind,
299            peer: Some(peer.into()),
300        }
301    }
302}
303
304impl std::fmt::Display for Error {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        write!(f, "error while {}", self.operation)?;
307
308        if let Some(peer) = self.peer.as_deref() {
309            write!(f, " ({peer})")?;
310        }
311
312        write!(f, ": {}", self.kind)
313    }
314}
315
316impl std::error::Error for Error {
317    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
318        match &self.kind {
319            ErrorKind::Dbus(e) => Some(e),
320            _ => None,
321        }
322    }
323}
324
325/// The operation an [`Error`] originated from.
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub enum Operation {
328    /// Connecting to or communicating with the session bus.
329    Connect,
330    /// Requesting a bus name.
331    RequestName,
332    /// Adding a signal match rule.
333    AddMatch,
334    /// Registering this host with the `StatusNotifierWatcher`.
335    RegisterHost,
336    /// Retrieving the registered items from the `StatusNotifierWatcher`.
337    GetItems,
338    /// Retrieving the properties of an item.
339    ItemGet,
340    /// Calling a method of an item.
341    ItemMethod,
342    /// Processing a signal sent by an item.
343    ItemSignal,
344    /// Sending a menu event to an item.
345    MenuEvent,
346    /// Retrieving the menu layout of an item.
347    MenuGetLayout,
348    /// Handling a registration request sent to the internal watcher.
349    WatcherRegister,
350    /// Handling a property request sent to the internal watcher.
351    WatcherGet,
352    /// Handling or emitting a signal of the internal watcher.
353    WatcherSignal,
354    /// Processing a reply to a previously sent message.
355    Reply,
356}
357
358impl std::fmt::Display for Operation {
359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        f.write_str(match self {
361            Self::Connect => "communicating with the session bus",
362            Self::RequestName => "requesting a bus name",
363            Self::AddMatch => "adding a signal match rule",
364            Self::RegisterHost => "registering the host",
365            Self::GetItems => "retrieving the registered items",
366            Self::ItemGet => "retrieving item properties",
367            Self::ItemMethod => "calling an item method",
368            Self::ItemSignal => "processing an item signal",
369            Self::MenuEvent => "sending a menu event",
370            Self::MenuGetLayout => "retrieving a menu layout",
371            Self::WatcherRegister => "handling a watcher registration",
372            Self::WatcherGet => "handling a watcher property request",
373            Self::WatcherSignal => "handling a watcher signal",
374            Self::Reply => "processing a reply",
375        })
376    }
377}
378
379/// What went wrong for an [`Error`].
380#[derive(Debug)]
381pub enum ErrorKind {
382    /// A message could not be sent.
383    SendFailed,
384    /// A message contained invalid or unexpected data.
385    InvalidData,
386    /// A reply wasn't received in time.
387    Timeout,
388    /// The remote peer replied with an error.
389    Dbus(dbus::Error),
390    /// The connection to the session bus was lost.
391    Disconnected,
392    /// A `StatusNotifierHost` is already registered on the session bus.
393    HostAlreadyExists,
394    /// The external `StatusNotifierWatcher` is no longer available.
395    WatcherLost,
396    /// The given item bus name isn't known.
397    UnknownItem,
398    /// The given menu node doesn't exist in the item's menu.
399    UnknownMenuNode,
400    /// The given menu node is disabled.
401    MenuNodeDisabled,
402}
403
404impl std::fmt::Display for ErrorKind {
405    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406        match self {
407            Self::SendFailed => f.write_str("the message could not be sent"),
408            Self::InvalidData => f.write_str("invalid or unexpected data was received"),
409            Self::Timeout => f.write_str("the reply wasn't received in time"),
410            Self::Dbus(e) => write!(f, "{e}"),
411            Self::Disconnected => f.write_str("the connection was lost"),
412            Self::HostAlreadyExists => f.write_str("a StatusNotifierHost is already registered"),
413            Self::WatcherLost => f.write_str("the StatusNotifierWatcher is no longer available"),
414            Self::UnknownItem => f.write_str("the item doesn't exist"),
415            Self::UnknownMenuNode => f.write_str("the menu node doesn't exist"),
416            Self::MenuNodeDisabled => f.write_str("the menu node is disabled"),
417        }
418    }
419}
420
421/// The direction of a [`Host::item_scroll`] request.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423pub enum ScrollOrientation {
424    /// Scroll horizontally.
425    Horizontal,
426    /// Scroll vertically.
427    Vertical,
428}
429
430impl Host {
431    /// Connect to the session bus and register a `StatusNotifierHost`.
432    ///
433    /// If no `StatusNotifierWatcher` is present on the bus, the built-in one is registered and
434    /// used (see [`Host::using_intl_watcher`]).
435    ///
436    /// # Errors
437    ///
438    /// Returns an error if connecting to the session bus fails, if another `StatusNotifierHost`
439    /// is already registered ([`ErrorKind::HostAlreadyExists`]), or if any of the setup messages
440    /// can't be sent.
441    pub fn new() -> Result<Self, Error> {
442        let mut channel = Channel::get_private(BusType::Session)
443            .map_err(|e| Error::new(Operation::Connect, ErrorKind::Dbus(e)))?;
444
445        let bus_msg = channel
446            .pop_message()
447            .ok_or_else(|| Error::new(Operation::Connect, ErrorKind::InvalidData))?;
448
449        let bus_name: String = bus_msg
450            .read1()
451            .map_err(|_| Error::new(Operation::Connect, ErrorKind::InvalidData))?;
452        let host_name = format!("org.kde.StatusNotifierHost-{}", process::id());
453
454        let req_host_msg = channel
455            .send_with_reply_and_block(
456                Message::call_with_args(
457                    "org.freedesktop.DBus",
458                    "/org/freedesktop/DBus",
459                    "org.freedesktop.DBus",
460                    "RequestName",
461                    (&host_name, DBUS_NAME_FLAG_DO_NOT_QUEUE),
462                ),
463                Duration::from_secs(3),
464            )
465            .map_err(|e| Error::new(Operation::RequestName, ErrorKind::Dbus(e)))?;
466
467        let req_host_reply: u32 = req_host_msg
468            .read1()
469            .map_err(|_| Error::new(Operation::RequestName, ErrorKind::InvalidData))?;
470
471        if req_host_reply != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER {
472            return Err(Error::new(
473                Operation::RequestName,
474                ErrorKind::HostAlreadyExists,
475            ));
476        }
477
478        let req_watcher_msg = channel
479            .send_with_reply_and_block(
480                Message::call_with_args(
481                    "org.freedesktop.DBus",
482                    "/org/freedesktop/DBus",
483                    "org.freedesktop.DBus",
484                    "RequestName",
485                    ("org.kde.StatusNotifierWatcher", DBUS_NAME_FLAG_DO_NOT_QUEUE),
486                ),
487                Duration::from_secs(3),
488            )
489            .map_err(|e| Error::new(Operation::RequestName, ErrorKind::Dbus(e)))?;
490
491        let req_watcher_reply: u32 = req_watcher_msg
492            .read1()
493            .map_err(|_| Error::new(Operation::RequestName, ErrorKind::InvalidData))?;
494
495        let use_intl_watcher = req_watcher_reply == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
496
497        for match_rule in [
498            "type='signal',interface='org.kde.StatusNotifierWatcher'",
499            "type='signal',interface='org.kde.StatusNotifierItem'",
500            "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged'",
501            "type='signal',interface='com.canonical.dbusmenu'",
502        ] {
503            channel
504                .send_with_reply_and_block(
505                    Message::call_with_args(
506                        "org.freedesktop.DBus",
507                        "/org/freedesktop/DBus",
508                        "org.freedesktop.DBus",
509                        "AddMatch",
510                        (match_rule,),
511                    ),
512                    Duration::from_secs(3),
513                )
514                .map_err(|e| Error::new(Operation::AddMatch, ErrorKind::Dbus(e)))?;
515        }
516
517        channel.set_watch_enabled(true);
518
519        let mut host = Self {
520            channel,
521            bus_name,
522            items: HashMap::new(),
523            intl_watcher_op: None,
524            pending_replies: HashMap::new(),
525        };
526
527        if use_intl_watcher {
528            host.intl_watcher_op = Some(Watcher {
529                hosts: HashSet::new(),
530                items: HashSet::new(),
531            });
532        }
533
534        let serial = host
535            .channel
536            .send(Message::call_with_args(
537                "org.kde.StatusNotifierWatcher",
538                "/StatusNotifierWatcher",
539                "org.kde.StatusNotifierWatcher",
540                "RegisterStatusNotifierHost",
541                ((&host.bus_name),),
542            ))
543            .map_err(|()| Error::new(Operation::RegisterHost, ErrorKind::SendFailed))?;
544
545        host.pending_replies
546            .insert(serial, (Instant::now(), ReplyTo::RegisterHost));
547
548        Ok(host)
549    }
550
551    /// Get an [`Item`] from the item's bus name.
552    ///
553    /// Returns `None` if the item doesn't exist or its properties haven't been retrieved yet.
554    pub fn get_item<N>(&self, item_name: N) -> Option<&Item>
555    where
556        N: AsRef<str>,
557    {
558        self.items
559            .get(item_name.as_ref())
560            .and_then(|intl_item| intl_item.item_op.as_ref())
561    }
562
563    /// Get all existing [`Item`]'s.
564    pub fn get_all_items(&self) -> impl Iterator<Item = (&String, &Item)> {
565        self.items.iter().filter_map(|(item_name, intl_item)| {
566            intl_item.item_op.as_ref().map(|item| (item_name, item))
567        })
568    }
569
570    /// Call the `Activate` method of the `StatusNotifierItem` interface.
571    ///
572    /// This is the primary action of an item, typically triggered by a left click. `x` and `y`
573    /// are the screen coordinates of the triggering input event.
574    ///
575    /// # Errors
576    ///
577    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
578    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
579    ///
580    /// **Note**: An error reply from the item itself is delivered later through the `error_fn`
581    // of [`Host::process_events`].
582    pub fn item_activate<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
583    where
584        N: AsRef<str>,
585    {
586        self.item_method(item_name.as_ref(), "Activate", (x, y))
587    }
588
589    /// Call the `ContextMenu` method of the `StatusNotifierItem` interface.
590    ///
591    /// This asks the item to show its own context menu at the screen coordinates `x` and `y`,
592    /// typically triggered by a right click.
593    ///
594    /// # Errors
595    ///
596    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
597    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
598    ///
599    /// **Note**: An error reply from the item itself is delivered later through the `error_fn`
600    // of [`Host::process_events`].
601    pub fn item_context_menu<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
602    where
603        N: AsRef<str>,
604    {
605        self.item_method(item_name.as_ref(), "ContextMenu", (x, y))
606    }
607
608    /// Call the `SecondaryActivate` method of the `StatusNotifierItem` interface.
609    ///
610    /// This is the secondary action of an item, typically triggered by a middle click. `x` and
611    /// `y` are the screen coordinates of the triggering input event.
612    ///
613    /// # Errors
614    ///
615    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
616    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
617    ///
618    /// **Note**: An error reply from the item itself is delivered later through the `error_fn`
619    // of [`Host::process_events`].
620    pub fn item_secondary_activate<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
621    where
622        N: AsRef<str>,
623    {
624        self.item_method(item_name.as_ref(), "SecondaryActivate", (x, y))
625    }
626
627    /// Call the `Scroll` method of the `StatusNotifierItem` interface.
628    ///
629    /// This reports scroll wheel input over the item, `delta` being the amount scrolled in the
630    /// given [`ScrollOrientation`].
631    ///
632    /// # Errors
633    ///
634    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
635    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
636    ///
637    /// **Note**: An error reply from the item itself is delivered later through the `error_fn`
638    // of [`Host::process_events`].
639    pub fn item_scroll<N>(
640        &mut self,
641        item_name: N,
642        delta: i32,
643        orientation: ScrollOrientation,
644    ) -> Result<(), Error>
645    where
646        N: AsRef<str>,
647    {
648        self.item_method(
649            item_name.as_ref(),
650            "Scroll",
651            (
652                delta,
653                match orientation {
654                    ScrollOrientation::Horizontal => "horizontal",
655                    ScrollOrientation::Vertical => "vertical",
656                },
657            ),
658        )
659    }
660
661    fn item_method<A>(&mut self, item_name: &str, method: &str, args: A) -> Result<(), Error>
662    where
663        A: AppendAll,
664    {
665        if self.get_item(item_name).is_none() {
666            return Err(Error::with_peer(
667                Operation::ItemMethod,
668                ErrorKind::UnknownItem,
669                item_name,
670            ));
671        }
672
673        let serial = self
674            .channel
675            .send(Message::call_with_args(
676                item_name,
677                "/StatusNotifierItem",
678                "org.kde.StatusNotifierItem",
679                method,
680                args,
681            ))
682            .map_err(|()| {
683                Error::with_peer(Operation::ItemMethod, ErrorKind::Disconnected, item_name)
684            })?;
685
686        self.pending_replies.insert(
687            serial,
688            (
689                Instant::now(),
690                ReplyTo::ItemMethod {
691                    item_name: item_name.to_string(),
692                },
693            ),
694        );
695
696        Ok(())
697    }
698
699    /// Send the `clicked` event of the `dbusmenu` interface to a menu node.
700    ///
701    /// This activates the [`MenuNode`] with `node_id`, e.g. after the user clicked the entry.
702    ///
703    /// # Errors
704    ///
705    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
706    /// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
707    /// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
708    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
709    ///
710    /// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
711    /// [`Host::process_events`].
712    pub fn menu_clicked<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
713    where
714        N: AsRef<str>,
715    {
716        self.menu_event(item_name.as_ref(), node_id, "clicked")
717    }
718
719    /// Send the `hovered` event of the `dbusmenu` interface to a menu node.
720    ///
721    /// This tells the item that the pointer moved onto the [`MenuNode`] with `node_id`.
722    ///
723    /// # Errors
724    ///
725    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
726    /// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
727    /// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
728    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
729    ///
730    /// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
731    /// [`Host::process_events`].
732    pub fn menu_hovered<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
733    where
734        N: AsRef<str>,
735    {
736        self.menu_event(item_name.as_ref(), node_id, "hovered")
737    }
738
739    /// Send the `opened` event of the `dbusmenu` interface to a menu node.
740    ///
741    /// This tells the item that the (sub)menu with `node_id` was shown to the user.
742    ///
743    /// # Errors
744    ///
745    /// # Errors
746    ///
747    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
748    /// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
749    /// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
750    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
751    ///
752    /// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
753    /// [`Host::process_events`].
754    pub fn menu_opened<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
755    where
756        N: AsRef<str>,
757    {
758        self.menu_event(item_name.as_ref(), node_id, "opened")
759    }
760
761    /// Send the `closed` event of the `dbusmenu` interface to a menu node.
762    ///
763    /// This tells the item that the (sub)menu with `node_id` was closed.
764    ///
765    /// # Errors
766    ///
767    /// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
768    /// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
769    /// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
770    /// - [`ErrorKind::Disconnected`] if the message couldn't be sent
771    ///
772    /// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
773    /// [`Host::process_events`].
774    pub fn menu_closed<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
775    where
776        N: AsRef<str>,
777    {
778        self.menu_event(item_name.as_ref(), node_id, "closed")
779    }
780
781    fn menu_event(&mut self, item_name: &str, node_id: i32, event: &str) -> Result<(), Error> {
782        let Some(intl_item) = self.items.get(item_name) else {
783            return Err(Error::with_peer(
784                Operation::MenuEvent,
785                ErrorKind::UnknownItem,
786                item_name,
787            ));
788        };
789
790        let Some(item) = intl_item.item_op.as_ref() else {
791            return Err(Error::with_peer(
792                Operation::MenuEvent,
793                ErrorKind::UnknownItem,
794                item_name,
795            ));
796        };
797
798        if intl_item.menu_path.is_empty() {
799            return Err(Error::with_peer(
800                Operation::MenuEvent,
801                ErrorKind::UnknownMenuNode,
802                item_name,
803            ));
804        }
805
806        let mut check_nodes = vec![&item.menu];
807        let mut node_exists = false;
808        let mut node_enabled = false;
809
810        while let Some(node) = check_nodes.pop() {
811            match node {
812                MenuNode::Empty
813                | MenuNode::Separator {
814                    ..
815                } => continue,
816                MenuNode::Menu {
817                    id,
818                    children,
819                    enabled,
820                    ..
821                } => {
822                    if *id == node_id {
823                        node_exists = true;
824                        node_enabled = *enabled;
825                        break;
826                    }
827
828                    check_nodes.extend(children.iter())
829                },
830                MenuNode::Item {
831                    id,
832                    enabled,
833                    ..
834                } => {
835                    if *id == node_id {
836                        node_exists = true;
837                        node_enabled = *enabled;
838                        break;
839                    }
840                },
841            }
842        }
843
844        if !node_exists {
845            return Err(Error::with_peer(
846                Operation::MenuEvent,
847                ErrorKind::UnknownMenuNode,
848                item_name,
849            ));
850        }
851
852        if event == "clicked" && !node_enabled {
853            return Err(Error::with_peer(
854                Operation::MenuEvent,
855                ErrorKind::MenuNodeDisabled,
856                item_name,
857            ));
858        }
859
860        let serial = self
861            .channel
862            .send(Message::call_with_args(
863                item_name,
864                &intl_item.menu_path,
865                "com.canonical.dbusmenu",
866                "Event",
867                (node_id, event, Variant(""), 0_u32),
868            ))
869            .map_err(|()| {
870                Error::with_peer(Operation::MenuEvent, ErrorKind::Disconnected, item_name)
871            })?;
872
873        self.pending_replies.insert(
874            serial,
875            (
876                Instant::now(),
877                ReplyTo::MenuEvent {
878                    item_name: item_name.to_string(),
879                },
880            ),
881        );
882
883        Ok(())
884    }
885
886    /// Check if the internal `StatusNotifierWatcher` is being used.
887    pub fn using_intl_watcher(&self) -> bool {
888        self.intl_watcher_op.is_some()
889    }
890
891    /// Process pending [`Event`]s and [`Error`]s.
892    ///
893    /// - `event_fn` callback is used for events of an [`Item`].
894    /// - `error_fn` callback is used for [`Error`]s that occur that are non-fatal.
895    ///    - The method itself will return an `Err(..)` if the error is fatal.
896    /// - `timeout` field is used to configure the blocking behavior.
897    ///     - `None` will block until there is an event or an error to be processed.
898    ///     - `Some(Duration::ZERO)` will not block (primarily used for polling).
899    ///
900    /// **Note**: This method will return `Ok(true)` when there are pending writes to the `Fd`.
901    /// This *should* be relatively rare, so it can be ignored for initial implementations, but
902    /// should be considered when writing more robust implementations.
903    pub fn process_events<EventFn, ErrorFn>(
904        &mut self,
905        mut event_fn: EventFn,
906        mut error_fn: ErrorFn,
907        timeout: Option<Duration>,
908    ) -> Result<bool, Error>
909    where
910        EventFn: FnMut(String, &Item, Event),
911        ErrorFn: FnMut(Error),
912    {
913        if self.channel.read_write(timeout).is_err() {
914            return Err(Error::new(Operation::Connect, ErrorKind::Disconnected));
915        }
916
917        struct MsgMatch<'a> {
918            ty: MessageType,
919            sender: Option<&'a str>,
920            destination: Option<&'a str>,
921            interface: Option<&'a str>,
922            member: Option<&'a str>,
923        }
924
925        while let Some(mut message) = self.channel.pop_message() {
926            match (MsgMatch {
927                ty: message.msg_type(),
928                sender: message.sender().as_deref(),
929                destination: message.destination().as_deref(),
930                interface: message.interface().as_deref(),
931                member: message.member().as_deref(),
932            }) {
933                MsgMatch {
934                    ty: MessageType::MethodCall,
935                    sender: Some(sender),
936                    destination: Some("org.kde.StatusNotifierWatcher"),
937                    interface: Some("org.kde.StatusNotifierWatcher"),
938                    member: Some("RegisterStatusNotifierHost"),
939                } => {
940                    let Some(watcher) = self.intl_watcher_op.as_mut() else {
941                        let _ = self.channel.send(reply_error(
942                            &message,
943                            "org.freedesktop.DBus.Error.UnknownObject",
944                        ));
945
946                        continue;
947                    };
948
949                    let Ok(host_name) = message.read1::<String>() else {
950                        error_fn(Error::with_peer(
951                            Operation::WatcherRegister,
952                            ErrorKind::InvalidData,
953                            sender,
954                        ));
955
956                        let _ = self.channel.send(reply_error(
957                            &message,
958                            "org.freedesktop.DBus.Error.InvalidArgs",
959                        ));
960
961                        continue;
962                    };
963
964                    let is_host_new = watcher.hosts.insert(host_name.clone());
965
966                    if self.channel.send(message.method_return()).is_err() {
967                        error_fn(Error::with_peer(
968                            Operation::WatcherRegister,
969                            ErrorKind::SendFailed,
970                            sender,
971                        ));
972                    }
973
974                    if is_host_new && watcher.hosts.len() == 1 {
975                        send_signal(
976                            &self.channel,
977                            Message::new_signal(
978                                "/StatusNotifierWatcher",
979                                "org.kde.StatusNotifierWatcher",
980                                "StatusNotifierHostRegistered",
981                            )
982                            .unwrap(),
983                            &mut error_fn,
984                            Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
985                        );
986                    }
987                },
988                MsgMatch {
989                    ty: MessageType::MethodCall,
990                    sender: Some(sender),
991                    destination: Some("org.kde.StatusNotifierWatcher"),
992                    interface: Some("org.kde.StatusNotifierWatcher"),
993                    member: Some("RegisterStatusNotifierItem"),
994                } => {
995                    let Some(watcher) = self.intl_watcher_op.as_mut() else {
996                        let _ = self.channel.send(reply_error(
997                            &message,
998                            "org.freedesktop.DBus.Error.UnknownObject",
999                        ));
1000
1001                        continue;
1002                    };
1003
1004                    let Ok(item_name) = message.read1::<String>() else {
1005                        error_fn(Error::with_peer(
1006                            Operation::WatcherRegister,
1007                            ErrorKind::InvalidData,
1008                            sender,
1009                        ));
1010
1011                        let _ = self.channel.send(reply_error(
1012                            &message,
1013                            "org.freedesktop.DBus.Error.InvalidArgs",
1014                        ));
1015
1016                        continue;
1017                    };
1018
1019                    let is_item_new = watcher.items.insert(item_name.clone());
1020
1021                    if self.channel.send(message.method_return()).is_err() {
1022                        error_fn(Error::with_peer(
1023                            Operation::WatcherRegister,
1024                            ErrorKind::SendFailed,
1025                            sender,
1026                        ));
1027                    }
1028
1029                    if is_item_new {
1030                        send_signal(
1031                            &self.channel,
1032                            Message::new_signal(
1033                                "/StatusNotifierWatcher",
1034                                "org.kde.StatusNotifierWatcher",
1035                                "StatusNotifierItemRegistered",
1036                            )
1037                            .unwrap()
1038                            .append1(item_name),
1039                            &mut error_fn,
1040                            Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
1041                        );
1042                    }
1043                },
1044                MsgMatch {
1045                    ty: MessageType::MethodCall,
1046                    sender: Some(sender),
1047                    interface: Some("org.freedesktop.DBus.Properties"),
1048                    member: Some("GetAll"),
1049                    ..
1050                } => {
1051                    let Ok(interface) = message.read1::<String>() else {
1052                        error_fn(Error::with_peer(
1053                            Operation::WatcherGet,
1054                            ErrorKind::InvalidData,
1055                            sender,
1056                        ));
1057
1058                        let _ = self.channel.send(reply_error(
1059                            &message,
1060                            "org.freedesktop.DBus.Error.InvalidArgs",
1061                        ));
1062
1063                        continue;
1064                    };
1065
1066                    match interface.as_str() {
1067                        "org.kde.StatusNotifierWatcher" => {
1068                            let Some(watcher) = self.intl_watcher_op.as_mut() else {
1069                                let _ = self.channel.send(reply_error(
1070                                    &message,
1071                                    "org.freedesktop.DBus.Error.UnknownObject",
1072                                ));
1073
1074                                continue;
1075                            };
1076
1077                            let host_registered = !watcher.hosts.is_empty();
1078                            let items: Vec<String> = watcher.items.iter().cloned().collect();
1079                            let mut dict: HashMap<&str, Variant<Box<dyn RefArg>>> = HashMap::new();
1080                            dict.insert("RegisteredStatusNotifierItems", Variant(Box::new(items)));
1081
1082                            dict.insert(
1083                                "IsStatusNotifierHostRegistered",
1084                                Variant(Box::new(host_registered)),
1085                            );
1086
1087                            dict.insert("ProtocolVersion", Variant(Box::new(0_i32)));
1088
1089                            if self
1090                                .channel
1091                                .send(message.method_return().append1(dict))
1092                                .is_err()
1093                            {
1094                                error_fn(Error::with_peer(
1095                                    Operation::WatcherGet,
1096                                    ErrorKind::SendFailed,
1097                                    sender,
1098                                ));
1099                            }
1100                        },
1101                        _ => {
1102                            let _ = self.channel.send(reply_error(
1103                                &message,
1104                                "org.freedesktop.DBus.Error.UnknownInterface",
1105                            ));
1106                        },
1107                    }
1108                },
1109                MsgMatch {
1110                    ty: MessageType::MethodCall,
1111                    sender: Some(sender),
1112                    interface: Some("org.freedesktop.DBus.Properties"),
1113                    member: Some("Get"),
1114                    ..
1115                } => {
1116                    let Ok((interface, property)) = message.read2::<String, String>() else {
1117                        error_fn(Error::with_peer(
1118                            Operation::WatcherGet,
1119                            ErrorKind::InvalidData,
1120                            sender,
1121                        ));
1122
1123                        let _ = self.channel.send(reply_error(
1124                            &message,
1125                            "org.freedesktop.DBus.Error.InvalidArgs",
1126                        ));
1127
1128                        continue;
1129                    };
1130
1131                    match interface.as_str() {
1132                        "org.kde.StatusNotifierWatcher" => {
1133                            let Some(watcher) = self.intl_watcher_op.as_mut() else {
1134                                let _ = self.channel.send(reply_error(
1135                                    &message,
1136                                    "org.freedesktop.DBus.Error.UnknownObject",
1137                                ));
1138
1139                                continue;
1140                            };
1141
1142                            let reply = match property.as_str() {
1143                                "RegisteredStatusNotifierItems" => {
1144                                    let items = watcher.items.iter().collect::<Vec<_>>();
1145                                    message.method_return().append1(Variant(items))
1146                                },
1147                                "IsStatusNotifierHostRegistered" => {
1148                                    message
1149                                        .method_return()
1150                                        .append1(Variant(!watcher.hosts.is_empty()))
1151                                },
1152                                "ProtocolVersion" => {
1153                                    message.method_return().append1(Variant(0_i32))
1154                                },
1155                                _ => {
1156                                    reply_error(
1157                                        &message,
1158                                        "org.freedesktop.DBus.Error.UnknownProperty",
1159                                    )
1160                                },
1161                            };
1162
1163                            if self.channel.send(reply).is_err() {
1164                                error_fn(Error::with_peer(
1165                                    Operation::WatcherGet,
1166                                    ErrorKind::SendFailed,
1167                                    sender,
1168                                ));
1169                            }
1170                        },
1171                        _ => {
1172                            let _ = self.channel.send(reply_error(
1173                                &message,
1174                                "org.freedesktop.DBus.Error.UnknownInterface",
1175                            ));
1176                        },
1177                    }
1178                },
1179                MsgMatch {
1180                    ty: MessageType::Signal,
1181                    sender: Some(sender),
1182                    interface: Some("org.kde.StatusNotifierWatcher"),
1183                    member: Some("StatusNotifierItemRegistered"),
1184                    ..
1185                } => {
1186                    let Ok(item_name) = message.read1::<String>() else {
1187                        error_fn(Error::with_peer(
1188                            Operation::WatcherSignal,
1189                            ErrorKind::InvalidData,
1190                            sender,
1191                        ));
1192                        continue;
1193                    };
1194
1195                    if self.items.contains_key(&item_name) {
1196                        error_fn(Error::with_peer(
1197                            Operation::WatcherSignal,
1198                            ErrorKind::InvalidData,
1199                            sender,
1200                        ));
1201                        continue;
1202                    }
1203
1204                    self.items.insert(
1205                        item_name.clone(),
1206                        IntlItem {
1207                            menu_path: String::new(),
1208                            menu_revision: 0,
1209                            item_op: None,
1210                        },
1211                    );
1212
1213                    match self.channel.send(msg_item_get_all(&item_name)) {
1214                        Ok(serial) => {
1215                            self.pending_replies.insert(
1216                                serial,
1217                                (
1218                                    Instant::now(),
1219                                    ReplyTo::ItemGetAll {
1220                                        item_name: item_name.clone(),
1221                                    },
1222                                ),
1223                            );
1224                        },
1225                        Err(()) => {
1226                            error_fn(Error::with_peer(
1227                                Operation::ItemGet,
1228                                ErrorKind::SendFailed,
1229                                item_name.clone(),
1230                            ));
1231                        },
1232                    }
1233                },
1234                MsgMatch {
1235                    ty: MessageType::Signal,
1236                    sender: Some(sender),
1237                    interface: Some("org.kde.StatusNotifierWatcher"),
1238                    member: Some("StatusNotifierItemUnregistered"),
1239                    ..
1240                } => {
1241                    let Ok(item_name) = message.read1::<String>() else {
1242                        error_fn(Error::with_peer(
1243                            Operation::WatcherSignal,
1244                            ErrorKind::InvalidData,
1245                            sender,
1246                        ));
1247                        continue;
1248                    };
1249
1250                    let Some(item) = self.items.remove(&item_name) else {
1251                        error_fn(Error::with_peer(
1252                            Operation::WatcherSignal,
1253                            ErrorKind::InvalidData,
1254                            sender,
1255                        ));
1256                        continue;
1257                    };
1258
1259                    if let Some(item) = item.item_op {
1260                        event_fn(item_name, &item, Event::Removed);
1261                    }
1262                },
1263                MsgMatch {
1264                    ty: MessageType::Signal,
1265                    sender: Some(sender),
1266                    interface: Some("org.kde.StatusNotifierItem"),
1267                    member: Some(member),
1268                    ..
1269                } => {
1270                    if !self.items.contains_key(sender) {
1271                        // Note: signals may be received before the item is registered with the
1272                        //       watcher. All properies will be fetched when it is registered.
1273                        continue;
1274                    }
1275
1276                    let get_properties = match member {
1277                        "NewTitle" => vec!["Title"],
1278                        "NewIcon" => vec!["IconName", "IconPixmap"],
1279                        "NewAttentionIcon" => vec!["AttentionIconName", "AttentionIconPixmap"],
1280                        "NewOverlayIcon" => vec!["OverlayIconName", "OverlayIconPixmap"],
1281                        "NewToolTip" => vec!["ToolTip"],
1282                        "NewStatus" => {
1283                            let Ok(status) = message.read1::<String>() else {
1284                                error_fn(Error::with_peer(
1285                                    Operation::ItemSignal,
1286                                    ErrorKind::InvalidData,
1287                                    sender,
1288                                ));
1289                                continue;
1290                            };
1291
1292                            let intl_item = self.items.get_mut(sender).expect("unreachable");
1293
1294                            let Some(item) = intl_item.item_op.as_mut() else {
1295                                error_fn(Error::with_peer(
1296                                    Operation::ItemSignal,
1297                                    ErrorKind::InvalidData,
1298                                    sender,
1299                                ));
1300                                continue;
1301                            };
1302
1303                            item.status = status;
1304                            event_fn(sender.to_string(), item, Event::UpdatedStatus);
1305                            continue;
1306                        },
1307                        "NewIconThemePath" => vec!["IconThemePath"],
1308                        _ => {
1309                            error_fn(Error::with_peer(
1310                                Operation::ItemSignal,
1311                                ErrorKind::InvalidData,
1312                                sender,
1313                            ));
1314                            continue;
1315                        },
1316                    };
1317
1318                    for property in get_properties {
1319                        match self.channel.send(msg_item_get_prop(sender, property)) {
1320                            Ok(serial) => {
1321                                self.pending_replies.insert(
1322                                    serial,
1323                                    (
1324                                        Instant::now(),
1325                                        ReplyTo::ItemGet {
1326                                            item_name: sender.to_string(),
1327                                            property,
1328                                        },
1329                                    ),
1330                                );
1331                            },
1332                            Err(()) => {
1333                                error_fn(Error::with_peer(
1334                                    Operation::ItemGet,
1335                                    ErrorKind::SendFailed,
1336                                    sender,
1337                                ));
1338                            },
1339                        }
1340                    }
1341                },
1342                MsgMatch {
1343                    ty: MessageType::Signal,
1344                    sender: Some(sender),
1345                    interface: Some("com.canonical.dbusmenu"),
1346                    member: Some("ItemsPropertiesUpdated"),
1347                    ..
1348                } => {
1349                    type UpdatedProps = Vec<(i32, HashMap<String, Variant<Box<dyn RefArg>>>)>;
1350                    type RemovedProps = Vec<(i32, Vec<String>)>;
1351
1352                    let Ok((updated_props, removed_props)) =
1353                        message.read2::<UpdatedProps, RemovedProps>()
1354                    else {
1355                        error_fn(Error::with_peer(
1356                            Operation::ItemSignal,
1357                            ErrorKind::InvalidData,
1358                            sender,
1359                        ));
1360                        continue;
1361                    };
1362
1363                    let Some(intl_item) = self.items.get_mut(sender) else {
1364                        continue;
1365                    };
1366
1367                    if intl_item.menu_path.is_empty() {
1368                        continue;
1369                    }
1370
1371                    let Some(item) = intl_item.item_op.as_mut() else {
1372                        continue;
1373                    };
1374
1375                    let mut menu_updated = false;
1376
1377                    for (node_id, node_properties) in updated_props {
1378                        let Some((node, _depth)) = find_menu_node(&mut item.menu, node_id, 0)
1379                        else {
1380                            continue;
1381                        };
1382
1383                        for (p_name, p_value_arg) in node_properties {
1384                            match p_name.as_str() {
1385                                "visible" => {
1386                                    let Some(p_value) = p_value_arg.as_i64() else {
1387                                        continue;
1388                                    };
1389
1390                                    match node {
1391                                        MenuNode::Empty => continue,
1392                                        MenuNode::Menu {
1393                                            visible, ..
1394                                        }
1395                                        | MenuNode::Item {
1396                                            visible, ..
1397                                        }
1398                                        | MenuNode::Separator {
1399                                            visible, ..
1400                                        } => {
1401                                            *visible = p_value == 1;
1402                                        },
1403                                    }
1404                                },
1405                                "enabled" => {
1406                                    let Some(p_value) = p_value_arg.as_i64() else {
1407                                        continue;
1408                                    };
1409
1410                                    match node {
1411                                        MenuNode::Menu {
1412                                            enabled, ..
1413                                        }
1414                                        | MenuNode::Item {
1415                                            enabled, ..
1416                                        } => {
1417                                            *enabled = p_value == 1;
1418                                        },
1419                                        _ => continue,
1420                                    }
1421                                },
1422                                "label" => {
1423                                    let Some(p_value) = p_value_arg.as_str() else {
1424                                        continue;
1425                                    };
1426
1427                                    match node {
1428                                        MenuNode::Menu {
1429                                            label, ..
1430                                        }
1431                                        | MenuNode::Item {
1432                                            label, ..
1433                                        } => {
1434                                            *label = p_value.to_string();
1435                                        },
1436                                        _ => continue,
1437                                    }
1438                                },
1439                                "icon-name" => {
1440                                    let Some(p_value) = p_value_arg.as_str() else {
1441                                        continue;
1442                                    };
1443
1444                                    let MenuNode::Item {
1445                                        icon_name, ..
1446                                    } = node
1447                                    else {
1448                                        continue;
1449                                    };
1450
1451                                    *icon_name = p_value.to_string();
1452                                },
1453                                "icon-data" => {
1454                                    let Some(new_icon_data) = parse_icon_data_arg(&p_value_arg)
1455                                    else {
1456                                        continue;
1457                                    };
1458
1459                                    let MenuNode::Item {
1460                                        icon_data, ..
1461                                    } = node
1462                                    else {
1463                                        continue;
1464                                    };
1465
1466                                    *icon_data = new_icon_data;
1467                                },
1468                                "toggle-state" => {
1469                                    let Some(new_toggle_state) =
1470                                        parse_toggle_state_arg(&p_value_arg)
1471                                    else {
1472                                        continue;
1473                                    };
1474
1475                                    let MenuNode::Item {
1476                                        toggle_state, ..
1477                                    } = node
1478                                    else {
1479                                        continue;
1480                                    };
1481
1482                                    *toggle_state = new_toggle_state;
1483                                },
1484                                "toggle-type" => {
1485                                    let Some(new_toggle_type) = parse_toggle_type_arg(&p_value_arg)
1486                                    else {
1487                                        continue;
1488                                    };
1489
1490                                    let MenuNode::Item {
1491                                        toggle_type, ..
1492                                    } = node
1493                                    else {
1494                                        continue;
1495                                    };
1496
1497                                    *toggle_type = new_toggle_type;
1498                                },
1499                                _ => continue,
1500                            }
1501
1502                            menu_updated = true;
1503                        }
1504                    }
1505
1506                    for (node_id, removed_props) in removed_props {
1507                        let Some((node, _depth)) = find_menu_node(&mut item.menu, node_id, 0)
1508                        else {
1509                            continue;
1510                        };
1511
1512                        for p_name in removed_props {
1513                            match p_name.as_str() {
1514                                "label" => {
1515                                    match node {
1516                                        MenuNode::Menu {
1517                                            label, ..
1518                                        }
1519                                        | MenuNode::Item {
1520                                            label, ..
1521                                        } => {
1522                                            *label = String::new();
1523                                        },
1524                                        _ => continue,
1525                                    }
1526                                },
1527                                "enabled" => {
1528                                    match node {
1529                                        MenuNode::Menu {
1530                                            enabled, ..
1531                                        }
1532                                        | MenuNode::Item {
1533                                            enabled, ..
1534                                        } => {
1535                                            *enabled = true;
1536                                        },
1537                                        _ => continue,
1538                                    }
1539                                },
1540                                "visible" => {
1541                                    match node {
1542                                        MenuNode::Empty => continue,
1543                                        MenuNode::Menu {
1544                                            visible, ..
1545                                        }
1546                                        | MenuNode::Item {
1547                                            visible, ..
1548                                        }
1549                                        | MenuNode::Separator {
1550                                            visible, ..
1551                                        } => {
1552                                            *visible = true;
1553                                        },
1554                                    }
1555                                },
1556                                "icon-name" => {
1557                                    let MenuNode::Item {
1558                                        icon_name, ..
1559                                    } = node
1560                                    else {
1561                                        continue;
1562                                    };
1563
1564                                    icon_name.clear();
1565                                },
1566                                "icon-data" => {
1567                                    let MenuNode::Item {
1568                                        icon_data, ..
1569                                    } = node
1570                                    else {
1571                                        continue;
1572                                    };
1573
1574                                    icon_data.0.clear();
1575                                },
1576                                "toggle-type" => {
1577                                    let MenuNode::Item {
1578                                        toggle_type, ..
1579                                    } = node
1580                                    else {
1581                                        continue;
1582                                    };
1583
1584                                    *toggle_type = ToggleType::None;
1585                                },
1586                                "toggle-state" => {
1587                                    let MenuNode::Item {
1588                                        toggle_state, ..
1589                                    } = node
1590                                    else {
1591                                        continue;
1592                                    };
1593
1594                                    *toggle_state = ToggleState::Unknown;
1595                                },
1596                                _ => continue,
1597                            }
1598
1599                            menu_updated = true;
1600                        }
1601                    }
1602
1603                    if menu_updated {
1604                        event_fn(sender.to_string(), item, Event::UpdatedMenu);
1605                    }
1606                },
1607                MsgMatch {
1608                    ty: MessageType::Signal,
1609                    sender: Some(sender),
1610                    interface: Some("com.canonical.dbusmenu"),
1611                    member: Some("LayoutUpdated"),
1612                    ..
1613                } => {
1614                    let Ok((_revision, parent_id)) = message.read2::<u32, i32>() else {
1615                        error_fn(Error::with_peer(
1616                            Operation::ItemSignal,
1617                            ErrorKind::InvalidData,
1618                            sender,
1619                        ));
1620                        continue;
1621                    };
1622
1623                    let Some(intl_item) = self.items.get_mut(sender) else {
1624                        continue;
1625                    };
1626
1627                    if intl_item.menu_path.is_empty() {
1628                        continue;
1629                    }
1630
1631                    let args: (i32, i32, &[&str]) = (parent_id, -1, &[]);
1632
1633                    match self.channel.send(Message::call_with_args(
1634                        sender,
1635                        &intl_item.menu_path,
1636                        "com.canonical.dbusmenu",
1637                        "GetLayout",
1638                        args,
1639                    )) {
1640                        Ok(serial) => {
1641                            self.pending_replies.insert(
1642                                serial,
1643                                (
1644                                    Instant::now(),
1645                                    ReplyTo::MenuGetLayout {
1646                                        item_name: sender.to_string(),
1647                                        parent_id,
1648                                    },
1649                                ),
1650                            );
1651                        },
1652                        Err(()) => {
1653                            error_fn(Error::with_peer(
1654                                Operation::MenuGetLayout,
1655                                ErrorKind::SendFailed,
1656                                sender,
1657                            ))
1658                        },
1659                    }
1660                },
1661                MsgMatch {
1662                    ty: MessageType::Signal,
1663                    interface: Some("org.freedesktop.DBus"),
1664                    member: Some("NameOwnerChanged"),
1665                    ..
1666                } => {
1667                    let Ok((name, _old_owner, new_owner)) =
1668                        message.read3::<String, String, String>()
1669                    else {
1670                        continue;
1671                    };
1672
1673                    if !new_owner.is_empty() {
1674                        if name == "org.kde.StatusNotifierWatcher" && self.intl_watcher_op.is_none()
1675                        {
1676                            match self
1677                                .channel
1678                                .send(Message::call_with_args(
1679                                    "org.kde.StatusNotifierWatcher",
1680                                    "/StatusNotifierWatcher",
1681                                    "org.kde.StatusNotifierWatcher",
1682                                    "RegisterStatusNotifierHost",
1683                                    ((&self.bus_name),),
1684                                ))
1685                                .map_err(|()| {
1686                                    Error::new(Operation::RegisterHost, ErrorKind::SendFailed)
1687                                }) {
1688                                Ok(serial) => {
1689                                    self.pending_replies
1690                                        .insert(serial, (Instant::now(), ReplyTo::RegisterHost));
1691                                },
1692                                Err(e) => error_fn(e),
1693                            }
1694                        }
1695
1696                        continue;
1697                    }
1698
1699                    let Some(watcher) = self.intl_watcher_op.as_mut() else {
1700                        if name == "org.kde.StatusNotifierWatcher" {
1701                            for (item_name, intl_item) in self.items.drain() {
1702                                if let Some(item) = intl_item.item_op {
1703                                    event_fn(item_name, &item, Event::Removed);
1704                                }
1705                            }
1706
1707                            error_fn(Error::new(Operation::RegisterHost, ErrorKind::WatcherLost));
1708                        }
1709
1710                        continue;
1711                    };
1712
1713                    if watcher.hosts.remove(&name) && watcher.hosts.is_empty() {
1714                        send_signal(
1715                            &self.channel,
1716                            Message::new_signal(
1717                                "/StatusNotifierWatcher",
1718                                "org.kde.StatusNotifierWatcher",
1719                                "StatusNotifierHostUnregistered",
1720                            )
1721                            .unwrap(),
1722                            &mut error_fn,
1723                            Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
1724                        );
1725                    }
1726
1727                    if watcher.items.remove(&name) {
1728                        send_signal(
1729                            &self.channel,
1730                            Message::new_signal(
1731                                "/StatusNotifierWatcher",
1732                                "org.kde.StatusNotifierWatcher",
1733                                "StatusNotifierItemUnregistered",
1734                            )
1735                            .unwrap()
1736                            .append1(&name),
1737                            &mut error_fn,
1738                            Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
1739                        );
1740                    }
1741                },
1742                MsgMatch {
1743                    sender: Some(sender),
1744                    ty: MessageType::MethodReturn,
1745                    ..
1746                } => {
1747                    let Some(reply_serial) = message.get_reply_serial() else {
1748                        error_fn(Error::with_peer(
1749                            Operation::Reply,
1750                            ErrorKind::InvalidData,
1751                            sender,
1752                        ));
1753                        continue;
1754                    };
1755
1756                    let Some((_, reply_to)) = self.pending_replies.remove(&reply_serial) else {
1757                        error_fn(Error::with_peer(
1758                            Operation::Reply,
1759                            ErrorKind::InvalidData,
1760                            sender,
1761                        ));
1762                        continue;
1763                    };
1764
1765                    match reply_to {
1766                        ReplyTo::RegisterHost => {
1767                            if self.intl_watcher_op.is_some() {
1768                                continue;
1769                            }
1770
1771                            match self
1772                                .channel
1773                                .send(Message::call_with_args(
1774                                    "org.kde.StatusNotifierWatcher",
1775                                    "/StatusNotifierWatcher",
1776                                    "org.freedesktop.DBus.Properties",
1777                                    "Get",
1778                                    (
1779                                        "org.kde.StatusNotifierWatcher",
1780                                        "RegisteredStatusNotifierItems",
1781                                    ),
1782                                ))
1783                                .map_err(|()| {
1784                                    Error::new(Operation::GetItems, ErrorKind::SendFailed)
1785                                }) {
1786                                Ok(serial) => {
1787                                    self.pending_replies
1788                                        .insert(serial, (Instant::now(), ReplyTo::NotifierItems));
1789                                },
1790                                Err(e) => error_fn(e),
1791                            }
1792                        },
1793                        ReplyTo::NotifierItems => {
1794                            let Ok(items) = message.read1::<Variant<Vec<String>>>() else {
1795                                error_fn(Error::with_peer(
1796                                    Operation::ItemGet,
1797                                    ErrorKind::InvalidData,
1798                                    message.sender().unwrap().to_string(),
1799                                ));
1800                                continue;
1801                            };
1802
1803                            for item_name in items.0 {
1804                                self.items.insert(
1805                                    item_name.clone(),
1806                                    IntlItem {
1807                                        menu_path: String::new(),
1808                                        menu_revision: 0,
1809                                        item_op: None,
1810                                    },
1811                                );
1812
1813                                match self.channel.send(msg_item_get_all(&item_name)) {
1814                                    Ok(serial) => {
1815                                        self.pending_replies.insert(
1816                                            serial,
1817                                            (
1818                                                Instant::now(),
1819                                                ReplyTo::ItemGetAll {
1820                                                    item_name: item_name.clone(),
1821                                                },
1822                                            ),
1823                                        );
1824                                    },
1825                                    Err(()) => {
1826                                        error_fn(Error::with_peer(
1827                                            Operation::ItemGet,
1828                                            ErrorKind::SendFailed,
1829                                            item_name.clone(),
1830                                        ));
1831                                    },
1832                                }
1833                            }
1834                        },
1835                        ReplyTo::ItemGetAll {
1836                            item_name,
1837                        } => {
1838                            let Some(intl_item) = self.items.get_mut(&item_name) else {
1839                                error_fn(Error::with_peer(
1840                                    Operation::ItemGet,
1841                                    ErrorKind::InvalidData,
1842                                    item_name,
1843                                ));
1844                                continue;
1845                            };
1846
1847                            let Ok(mut fields) =
1848                                message.read1::<HashMap<String, Variant<Box<dyn RefArg>>>>()
1849                            else {
1850                                error_fn(Error::with_peer(
1851                                    Operation::ItemGet,
1852                                    ErrorKind::InvalidData,
1853                                    item_name,
1854                                ));
1855                                continue;
1856                            };
1857
1858                            let mut item = Item {
1859                                bus_name: item_name.clone(),
1860                                ..Item::default()
1861                            };
1862
1863                            macro_rules! parse_string_fields {
1864                                (
1865                                    $item:expr,
1866                                    $fields:expr,
1867                                    { $($field:ident => $key:expr),* $(,)? }
1868                                ) => {
1869                                    $(
1870                                        $item.$field = $fields
1871                                            .remove($key)
1872                                            .and_then(|arg| arg.as_str().map(|s| s.to_string()))
1873                                            .unwrap_or_default();
1874                                    )*
1875                                };
1876                            }
1877
1878                            parse_string_fields!(
1879                                item,
1880                                fields,
1881                                {
1882                                    category => "Category",
1883                                    id => "Id",
1884                                    title => "Title",
1885                                    status => "Status",
1886                                    icon_theme_path => "IconThemePath",
1887                                    icon_name => "IconName",
1888                                    overlay_icon_name => "OverlayIconName",
1889                                    attention_icon_name => "AttentionIconName",
1890                                    attention_movie_name => "AttentionMovieName",
1891                                }
1892                            );
1893
1894                            parse_string_fields!(intl_item, fields, { menu_path => "Menu" });
1895
1896                            item.window_id = fields
1897                                .remove("WindowId")
1898                                .and_then(|arg| arg.as_u64())
1899                                .unwrap_or_default();
1900
1901                            item.item_is_menu = fields
1902                                .remove("ItemIsMenu")
1903                                .and_then(|arg| arg.as_i64().map(|val| val == 1))
1904                                .unwrap_or_default();
1905
1906                            macro_rules! parse_pixmap_fields {
1907                                (
1908                                    $item:expr,
1909                                    $fields:expr,
1910                                    { $($field:ident => $key:expr),* $(,)? }
1911                                ) => {
1912                                    $(
1913                                        $item.$field = $fields
1914                                            .remove($key)
1915                                            .map(|arg| parse_pixmap_arg(&arg.0))
1916                                            .unwrap_or_default();
1917                                    )*
1918                                };
1919                            }
1920
1921                            parse_pixmap_fields!(
1922                                item,
1923                                fields,
1924                                {
1925                                    icon_pixmap => "IconPixmap",
1926                                    overlay_icon_pixmap => "OverlayIconPixmap",
1927                                    attention_icon_pixmap => "AttentionIconPixmap",
1928                                }
1929                            );
1930
1931                            item.tool_tip = fields
1932                                .remove("ToolTip")
1933                                .map(|arg| parse_tool_tip_arg(&arg.0))
1934                                .unwrap_or_default();
1935
1936                            if !intl_item.menu_path.is_empty() {
1937                                let args: (i32, i32, &[&str]) = (0, -1, &[]);
1938
1939                                match self.channel.send(Message::call_with_args(
1940                                    &item_name,
1941                                    &intl_item.menu_path,
1942                                    "com.canonical.dbusmenu",
1943                                    "GetLayout",
1944                                    args,
1945                                )) {
1946                                    Ok(serial) => {
1947                                        self.pending_replies.insert(
1948                                            serial,
1949                                            (
1950                                                Instant::now(),
1951                                                ReplyTo::MenuGetLayout {
1952                                                    item_name: item_name.clone(),
1953                                                    parent_id: 0,
1954                                                },
1955                                            ),
1956                                        );
1957                                    },
1958                                    Err(()) => {
1959                                        error_fn(Error::with_peer(
1960                                            Operation::MenuGetLayout,
1961                                            ErrorKind::SendFailed,
1962                                            item_name.clone(),
1963                                        ));
1964                                    },
1965                                }
1966                            }
1967
1968                            if intl_item.item_op.replace(item).is_none() {
1969                                event_fn(
1970                                    item_name,
1971                                    intl_item.item_op.as_ref().expect("unreachable"),
1972                                    Event::Added,
1973                                );
1974                            }
1975                        },
1976                        ReplyTo::ItemGet {
1977                            item_name,
1978                            property,
1979                        } => {
1980                            let Some(intl_item) = self.items.get_mut(&item_name) else {
1981                                error_fn(Error::with_peer(
1982                                    Operation::ItemGet,
1983                                    ErrorKind::InvalidData,
1984                                    item_name,
1985                                ));
1986                                continue;
1987                            };
1988
1989                            let Some(item) = intl_item.item_op.as_mut() else {
1990                                error_fn(Error::with_peer(
1991                                    Operation::ItemGet,
1992                                    ErrorKind::InvalidData,
1993                                    item_name,
1994                                ));
1995                                continue;
1996                            };
1997
1998                            match property {
1999                                "Title" => {
2000                                    if let Ok(title) = message.read1::<Variant<String>>()
2001                                        && title.0 != item.title
2002                                    {
2003                                        item.title = title.0;
2004                                        event_fn(item_name, item, Event::UpdatedTitle);
2005                                    }
2006                                },
2007                                "IconThemePath" => {
2008                                    if let Ok(path) = message.read1::<Variant<String>>()
2009                                        && path.0 != item.icon_theme_path
2010                                    {
2011                                        item.icon_theme_path = path.0;
2012                                        event_fn(item_name, item, Event::UpdatedIconThemePath);
2013                                    }
2014                                },
2015                                "IconName" => {
2016                                    if let Ok(name) = message.read1::<Variant<String>>()
2017                                        && name.0 != item.icon_name
2018                                    {
2019                                        item.icon_name = name.0;
2020                                        event_fn(item_name, item, Event::UpdatedIconName);
2021                                    }
2022                                },
2023                                "IconPixmap" => {
2024                                    if let Some(pixmap) = message
2025                                        .read1::<Variant<Box<dyn RefArg>>>()
2026                                        .ok()
2027                                        .map(|arg| parse_pixmap_arg(&arg.0))
2028                                        && pixmap != item.icon_pixmap
2029                                    {
2030                                        item.icon_pixmap = pixmap;
2031                                        event_fn(item_name, item, Event::UpdatedIconPixmap);
2032                                    }
2033                                },
2034                                "AttentionIconName" => {
2035                                    if let Ok(name) = message.read1::<Variant<String>>()
2036                                        && name.0 != item.attention_icon_name
2037                                    {
2038                                        item.attention_icon_name = name.0;
2039                                        event_fn(item_name, item, Event::UpdatedAttentionIconName);
2040                                    }
2041                                },
2042                                "AttentionIconPixmap" => {
2043                                    if let Some(pixmap) = message
2044                                        .read1::<Variant<Box<dyn RefArg>>>()
2045                                        .ok()
2046                                        .map(|arg| parse_pixmap_arg(&arg.0))
2047                                        && pixmap != item.attention_icon_pixmap
2048                                    {
2049                                        item.attention_icon_pixmap = pixmap;
2050                                        event_fn(
2051                                            item_name,
2052                                            item,
2053                                            Event::UpdatedAttentionIconPixmap,
2054                                        );
2055                                    }
2056                                },
2057                                "OverlayIconName" => {
2058                                    if let Ok(name) = message.read1::<Variant<String>>()
2059                                        && name.0 != item.overlay_icon_name
2060                                    {
2061                                        item.overlay_icon_name = name.0;
2062                                        event_fn(item_name, item, Event::UpdatedOverlayIconName);
2063                                    }
2064                                },
2065                                "OverlayIconPixmap" => {
2066                                    if let Some(pixmap) = message
2067                                        .read1::<Variant<Box<dyn RefArg>>>()
2068                                        .ok()
2069                                        .map(|arg| parse_pixmap_arg(&arg.0))
2070                                        && pixmap != item.overlay_icon_pixmap
2071                                    {
2072                                        item.overlay_icon_pixmap = pixmap;
2073                                        event_fn(item_name, item, Event::UpdatedOverlayIconPixmap);
2074                                    }
2075                                },
2076                                "ToolTip" => {
2077                                    if let Some(tool_tip) = message
2078                                        .read1::<Variant<Box<dyn RefArg>>>()
2079                                        .ok()
2080                                        .map(|arg| parse_tool_tip_arg(&arg.0))
2081                                        && tool_tip != item.tool_tip
2082                                    {
2083                                        item.tool_tip = tool_tip;
2084                                        event_fn(item_name, item, Event::UpdatedToolTip);
2085                                    }
2086                                },
2087                                _ => (),
2088                            }
2089                        },
2090                        ReplyTo::MenuGetLayout {
2091                            item_name,
2092                            parent_id,
2093                        } => {
2094                            let Some(intl_item) = self.items.get_mut(&item_name) else {
2095                                error_fn(Error::with_peer(
2096                                    Operation::MenuGetLayout,
2097                                    ErrorKind::InvalidData,
2098                                    item_name,
2099                                ));
2100                                continue;
2101                            };
2102
2103                            let Some(item) = intl_item.item_op.as_mut() else {
2104                                error_fn(Error::with_peer(
2105                                    Operation::MenuGetLayout,
2106                                    ErrorKind::InvalidData,
2107                                    item_name,
2108                                ));
2109                                continue;
2110                            };
2111
2112                            let (node, depth) = match parent_id {
2113                                0 => (&mut item.menu, 0),
2114                                _ => {
2115                                    match find_menu_node(&mut item.menu, parent_id, 0) {
2116                                        Some(some) => some,
2117                                        None => {
2118                                            error_fn(Error::with_peer(
2119                                                Operation::MenuGetLayout,
2120                                                ErrorKind::InvalidData,
2121                                                item_name,
2122                                            ));
2123                                            continue;
2124                                        },
2125                                    }
2126                                },
2127                            };
2128
2129                            let (Some(revision), Some(arg)) =
2130                                message.get2::<u32, Box<dyn RefArg>>()
2131                            else {
2132                                error_fn(Error::with_peer(
2133                                    Operation::MenuGetLayout,
2134                                    ErrorKind::InvalidData,
2135                                    item_name,
2136                                ));
2137                                continue;
2138                            };
2139
2140                            let Ok(new_node) = parse_menu(arg.as_ref(), depth) else {
2141                                error_fn(Error::with_peer(
2142                                    Operation::MenuGetLayout,
2143                                    ErrorKind::InvalidData,
2144                                    item_name,
2145                                ));
2146                                continue;
2147                            };
2148
2149                            *node = new_node;
2150                            intl_item.menu_revision = revision;
2151                            event_fn(item_name, item, Event::UpdatedMenu);
2152                        },
2153                        ReplyTo::ItemMethod {
2154                            ..
2155                        }
2156                        | ReplyTo::MenuEvent {
2157                            ..
2158                        } => (),
2159                    }
2160                },
2161                MsgMatch {
2162                    sender: Some(sender),
2163                    ty: MessageType::Error,
2164                    ..
2165                } => {
2166                    let Some(reply_serial) = message.get_reply_serial() else {
2167                        error_fn(Error::with_peer(
2168                            Operation::Reply,
2169                            ErrorKind::InvalidData,
2170                            sender,
2171                        ));
2172                        continue;
2173                    };
2174
2175                    let Some((_, reply_to)) = self.pending_replies.remove(&reply_serial) else {
2176                        error_fn(Error::with_peer(
2177                            Operation::Reply,
2178                            ErrorKind::InvalidData,
2179                            sender,
2180                        ));
2181                        continue;
2182                    };
2183
2184                    let Err(e) = message.as_result() else {
2185                        continue;
2186                    };
2187
2188                    match reply_to {
2189                        ReplyTo::RegisterHost => {
2190                            error_fn(Error::new(Operation::RegisterHost, ErrorKind::Dbus(e)));
2191                        },
2192                        ReplyTo::NotifierItems => {
2193                            error_fn(Error::new(Operation::GetItems, ErrorKind::Dbus(e)));
2194                        },
2195                        ReplyTo::ItemGetAll {
2196                            item_name,
2197                        }
2198                        | ReplyTo::ItemGet {
2199                            item_name, ..
2200                        } => {
2201                            error_fn(Error::with_peer(
2202                                Operation::ItemGet,
2203                                ErrorKind::Dbus(e),
2204                                item_name,
2205                            ));
2206                        },
2207                        ReplyTo::MenuGetLayout {
2208                            item_name, ..
2209                        } => {
2210                            error_fn(Error::with_peer(
2211                                Operation::MenuGetLayout,
2212                                ErrorKind::Dbus(e),
2213                                item_name,
2214                            ));
2215                        },
2216                        ReplyTo::ItemMethod {
2217                            item_name,
2218                        } => {
2219                            error_fn(Error::with_peer(
2220                                Operation::ItemMethod,
2221                                ErrorKind::Dbus(e),
2222                                item_name,
2223                            ));
2224                        },
2225                        ReplyTo::MenuEvent {
2226                            item_name,
2227                        } => {
2228                            error_fn(Error::with_peer(
2229                                Operation::MenuEvent,
2230                                ErrorKind::Dbus(e),
2231                                item_name,
2232                            ));
2233                        },
2234                    }
2235                },
2236                MsgMatch {
2237                    ty: MessageType::MethodCall,
2238                    ..
2239                } => {
2240                    let _ = self
2241                        .channel
2242                        .send(reply_error(&message, "org.freedesktop.DBus.Error.Failed"));
2243                },
2244                _ => (),
2245            }
2246        }
2247
2248        self.pending_replies.retain(|_, (inst_sent, reply_to)| {
2249            if inst_sent.elapsed() > Duration::from_millis(500) {
2250                match reply_to {
2251                    ReplyTo::RegisterHost => {
2252                        error_fn(Error::new(Operation::RegisterHost, ErrorKind::Timeout));
2253                    },
2254                    ReplyTo::NotifierItems => {
2255                        error_fn(Error::new(Operation::GetItems, ErrorKind::Timeout));
2256                    },
2257                    ReplyTo::ItemGetAll {
2258                        item_name,
2259                    }
2260                    | ReplyTo::ItemGet {
2261                        item_name, ..
2262                    } => {
2263                        error_fn(Error::with_peer(
2264                            Operation::ItemGet,
2265                            ErrorKind::Timeout,
2266                            item_name.clone(),
2267                        ));
2268                    },
2269                    ReplyTo::MenuGetLayout {
2270                        item_name, ..
2271                    } => {
2272                        error_fn(Error::with_peer(
2273                            Operation::MenuGetLayout,
2274                            ErrorKind::Timeout,
2275                            item_name.clone(),
2276                        ));
2277                    },
2278                    ReplyTo::ItemMethod {
2279                        item_name,
2280                    } => {
2281                        error_fn(Error::with_peer(
2282                            Operation::ItemMethod,
2283                            ErrorKind::Timeout,
2284                            item_name.clone(),
2285                        ));
2286                    },
2287                    ReplyTo::MenuEvent {
2288                        item_name,
2289                    } => {
2290                        error_fn(Error::with_peer(
2291                            Operation::MenuEvent,
2292                            ErrorKind::Timeout,
2293                            item_name.clone(),
2294                        ));
2295                    },
2296                }
2297
2298                false
2299            } else {
2300                true
2301            }
2302        });
2303
2304        Ok(self.channel.watch().write)
2305    }
2306}
2307
2308impl AsRawFd for Host {
2309    fn as_raw_fd(&self) -> RawFd {
2310        self.channel.watch().fd
2311    }
2312}
2313
2314impl AsFd for Host {
2315    fn as_fd(&self) -> BorrowedFd<'_> {
2316        unsafe { BorrowedFd::borrow_raw(self.channel.watch().fd) }
2317    }
2318}
2319
2320fn reply_error(message: &Message, error: &str) -> Message {
2321    message.error(&dbus::strings::ErrorName::new(error).unwrap(), c"")
2322}
2323
2324fn msg_item_get_all<I>(item_name: &I) -> Message
2325where
2326    I: AsRef<str>,
2327{
2328    Message::call_with_args(
2329        item_name.as_ref(),
2330        "/StatusNotifierItem",
2331        "org.freedesktop.DBus.Properties",
2332        "GetAll",
2333        ("org.kde.StatusNotifierItem",),
2334    )
2335}
2336
2337fn msg_item_get_prop(item_name: &str, property: &'static str) -> Message {
2338    Message::call_with_args(
2339        item_name,
2340        "/StatusNotifierItem",
2341        "org.freedesktop.DBus.Properties",
2342        "Get",
2343        ("org.kde.StatusNotifierItem", property),
2344    )
2345}
2346
2347fn send_signal(
2348    channel: &Channel,
2349    message: Message,
2350    error_fn: &mut impl FnMut(Error),
2351    error: Error,
2352) {
2353    if channel.send(message).is_err() {
2354        error_fn(error);
2355    }
2356}
2357
2358fn parse_pixmap_arg(value: &dyn RefArg) -> Vec<Pixmap> {
2359    let mut pixmaps = Vec::new();
2360
2361    let Some(iter) = value.as_iter() else {
2362        return pixmaps;
2363    };
2364
2365    for item in iter {
2366        let Some(mut fields) = item.as_iter() else {
2367            continue;
2368        };
2369
2370        let Some(width) = fields.next().and_then(RefArg::as_i64) else {
2371            continue;
2372        };
2373
2374        let Some(height) = fields.next().and_then(RefArg::as_i64) else {
2375            continue;
2376        };
2377
2378        let Some(bytes_arg) = fields.next() else {
2379            continue;
2380        };
2381
2382        let Some(byte_iter) = bytes_arg.as_iter() else {
2383            continue;
2384        };
2385
2386        let bytes: Vec<u8> = byte_iter
2387            .filter_map(|b| b.as_u64().map(|v| v as u8))
2388            .collect();
2389
2390        if width < 1
2391            || width > i32::MAX as i64
2392            || height < 1
2393            || height > i32::MAX as i64
2394            || width as usize * height as usize * 4 != bytes.len()
2395        {
2396            continue;
2397        }
2398
2399        pixmaps.push(Pixmap {
2400            dimensions: [width as i32, height as i32],
2401            image_data: bytes,
2402        });
2403    }
2404
2405    pixmaps
2406}
2407
2408fn parse_tool_tip_arg(value: &dyn RefArg) -> ToolTip {
2409    let Some(mut iter) = value.as_iter() else {
2410        return ToolTip::default();
2411    };
2412
2413    let Some(icon_name) = iter
2414        .next()
2415        .and_then(|arg| arg.as_str())
2416        .map(|arg| arg.to_string())
2417    else {
2418        return ToolTip::default();
2419    };
2420
2421    let Some(icon_pixmap) = iter.next().map(|arg| parse_pixmap_arg(&arg)) else {
2422        return ToolTip::default();
2423    };
2424
2425    let Some(title) = iter
2426        .next()
2427        .and_then(|arg| arg.as_str())
2428        .map(|arg| arg.to_string())
2429    else {
2430        return ToolTip::default();
2431    };
2432
2433    let Some(description) = iter
2434        .next()
2435        .and_then(|arg| arg.as_str())
2436        .map(|arg| arg.to_string())
2437    else {
2438        return ToolTip::default();
2439    };
2440
2441    ToolTip {
2442        icon_name,
2443        icon_pixmap,
2444        title,
2445        description,
2446    }
2447}
2448
2449fn find_menu_node(
2450    node: &mut MenuNode,
2451    find_id: i32,
2452    depth: usize,
2453) -> Option<(&mut MenuNode, usize)> {
2454    match node {
2455        MenuNode::Empty => None,
2456        MenuNode::Menu {
2457            id, ..
2458        } if *id == find_id => Some((node, depth)),
2459        MenuNode::Menu {
2460            children, ..
2461        } => {
2462            children
2463                .iter_mut()
2464                .find_map(|child| find_menu_node(child, find_id, depth + 1))
2465        },
2466        MenuNode::Item {
2467            id, ..
2468        }
2469        | MenuNode::Separator {
2470            id, ..
2471        } if *id == find_id => Some((node, depth)),
2472        _ => None,
2473    }
2474}
2475
2476fn parse_menu(arg: &dyn RefArg, depth: usize) -> Result<MenuNode, ()> {
2477    if depth > 8 {
2478        return Err(());
2479    }
2480
2481    let mut struct_iter = arg.as_iter().ok_or(())?;
2482    let menu_id = struct_iter.next().ok_or(())?.as_i64().ok_or(())? as i32;
2483    let mut property_iter = struct_iter.next().ok_or(())?.as_iter().ok_or(())?;
2484
2485    let mut is_submenu = false;
2486    let mut is_separator = false;
2487    let mut visible = true;
2488    let mut enabled = true;
2489    let mut label = String::new();
2490    let mut icon_name = String::new();
2491    let mut icon_data = IconData(Vec::new());
2492    let mut toggle_state = ToggleState::Unknown;
2493    let mut toggle_type = ToggleType::None;
2494
2495    while let Some(p_name_arg) = property_iter.next() {
2496        let Some(p_name) = p_name_arg.as_str() else {
2497            continue;
2498        };
2499
2500        let Some(p_value_arg) = property_iter.next() else {
2501            continue;
2502        };
2503
2504        match p_name {
2505            "children-display" => {
2506                let Some(p_value) = p_value_arg.as_str() else {
2507                    continue;
2508                };
2509
2510                if p_value != "submenu" {
2511                    continue;
2512                }
2513
2514                is_submenu = true;
2515            },
2516            "visible" => {
2517                let Some(p_value) = p_value_arg.as_i64() else {
2518                    continue;
2519                };
2520
2521                visible = p_value == 1;
2522            },
2523            "enabled" => {
2524                let Some(p_value) = p_value_arg.as_i64() else {
2525                    continue;
2526                };
2527
2528                enabled = p_value == 1;
2529            },
2530            "type" => {
2531                let Some(p_value) = p_value_arg.as_str() else {
2532                    continue;
2533                };
2534
2535                if p_value != "separator" {
2536                    continue;
2537                }
2538
2539                is_separator = true;
2540            },
2541            "label" => {
2542                let Some(p_value) = p_value_arg.as_str() else {
2543                    continue;
2544                };
2545
2546                label = p_value.to_string();
2547            },
2548            "icon-name" => {
2549                let Some(p_value) = p_value_arg.as_str() else {
2550                    continue;
2551                };
2552
2553                icon_name = p_value.to_string();
2554            },
2555            "icon-data" => {
2556                let Some(new_icon_data) = parse_icon_data_arg(&p_value_arg) else {
2557                    continue;
2558                };
2559
2560                icon_data = new_icon_data;
2561            },
2562            "toggle-state" => {
2563                let Some(new_toggle_state) = parse_toggle_state_arg(&p_value_arg) else {
2564                    continue;
2565                };
2566
2567                toggle_state = new_toggle_state;
2568            },
2569            "toggle-type" => {
2570                let Some(new_toggle_type) = parse_toggle_type_arg(&p_value_arg) else {
2571                    continue;
2572                };
2573
2574                toggle_type = new_toggle_type;
2575            },
2576            _ => (),
2577        }
2578    }
2579
2580    if depth == 0 || is_submenu {
2581        let mut children = Vec::new();
2582        let submenu_iter = struct_iter.next().ok_or(())?.as_iter().ok_or(())?;
2583
2584        for menu_variant in submenu_iter {
2585            if let Some(mut menu_variant_iter) = menu_variant.as_iter()
2586                && let Some(menu_struct) = menu_variant_iter.next()
2587                && let Ok(submenu) = parse_menu(menu_struct, depth + 1)
2588            {
2589                children.push(submenu);
2590            }
2591        }
2592
2593        Ok(MenuNode::Menu {
2594            id: menu_id,
2595            label,
2596            enabled,
2597            visible,
2598            children,
2599        })
2600    } else if is_separator {
2601        Ok(MenuNode::Separator {
2602            id: menu_id,
2603            visible,
2604        })
2605    } else {
2606        Ok(MenuNode::Item {
2607            id: menu_id,
2608            label,
2609            enabled,
2610            visible,
2611            icon_name,
2612            icon_data,
2613            toggle_type,
2614            toggle_state,
2615        })
2616    }
2617}
2618
2619fn parse_icon_data_arg(arg: &dyn RefArg) -> Option<IconData> {
2620    let mut bytes_variant_iter = arg.as_iter()?;
2621    let bytes_array = bytes_variant_iter.next()?;
2622    let bytes_iter = bytes_array.as_iter()?;
2623    let mut icon_data = Vec::new();
2624
2625    for byte_arg in bytes_iter {
2626        let byte_u64 = byte_arg.as_u64()?;
2627
2628        if byte_u64 > 255 {
2629            return None;
2630        }
2631
2632        icon_data.push(byte_u64 as u8);
2633    }
2634
2635    Some(IconData(icon_data))
2636}
2637
2638fn parse_toggle_state_arg(arg: &dyn RefArg) -> Option<ToggleState> {
2639    Some(match arg.as_i64()? {
2640        0 => ToggleState::Off,
2641        1 => ToggleState::On,
2642        _ => ToggleState::Unknown,
2643    })
2644}
2645
2646fn parse_toggle_type_arg(arg: &dyn RefArg) -> Option<ToggleType> {
2647    match arg.as_str()? {
2648        "checkmark" => Some(ToggleType::Checkmark),
2649        "radio" => Some(ToggleType::Radio),
2650        _ => None,
2651    }
2652}