Skip to main content

system_tray/
client.rs

1#[cfg(feature = "data")]
2use crate::data::apply_menu_diffs;
3use crate::data::TrayItemMap;
4use crate::dbus::dbus_menu_proxy::{DBusMenuProxy, PropertiesUpdate};
5use crate::dbus::notifier_item_proxy::StatusNotifierItemProxy;
6use crate::dbus::notifier_watcher_proxy::StatusNotifierWatcherProxy;
7use crate::dbus::status_notifier_watcher::StatusNotifierWatcher;
8use crate::dbus::{self, OwnedValueExt};
9use crate::error::{Error, Result};
10use crate::item::{self, IconPixmap, Status, StatusNotifierItem, Tooltip};
11use crate::menu::{MenuDiff, TrayMenu};
12use crate::names;
13use dbus::DBusProps;
14use futures_lite::StreamExt;
15use std::sync::{Arc, Mutex};
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use tokio::spawn;
18use tokio::sync::{broadcast, mpsc};
19use tokio::time::{sleep, timeout, Instant};
20use tracing::{debug, error, trace, warn};
21use zbus::fdo::{DBusProxy, PropertiesProxy};
22use zbus::names::InterfaceName;
23use zbus::zvariant::{Array, Structure, Value};
24use zbus::{Connection, Message};
25
26use self::names::ITEM_OBJECT;
27
28/// An event emitted by the client
29/// representing a change from either the `StatusNotifierItem`
30/// or `DBusMenu` protocols.
31#[derive(Debug, Clone)]
32pub enum Event {
33    /// A new `StatusNotifierItem` was added.
34    Add(String, Box<StatusNotifierItem>),
35    /// An update was received for an existing `StatusNotifierItem`.
36    /// This could be either an update to the item itself,
37    /// or an update to the associated menu.
38    Update(String, UpdateEvent),
39    /// A `StatusNotifierItem` was unregistered.
40    Remove(String),
41}
42
43/// The specific change associated with an update event.
44#[derive(Debug, Clone)]
45pub enum UpdateEvent {
46    AttentionIcon(Option<String>),
47    Icon {
48        icon_name: Option<String>,
49        icon_pixmap: Option<Vec<IconPixmap>>,
50    },
51    OverlayIcon(Option<String>),
52    Status(Status),
53    Title(Option<String>),
54    Tooltip(Option<Tooltip>),
55    /// A menu layout has changed.
56    /// The entire layout is sent.
57    Menu(TrayMenu),
58    /// One or more menu properties have changed.
59    /// Only the updated properties are sent.
60    MenuDiff(Vec<MenuDiff>),
61    /// A new menu has connected to the item.
62    /// Its name on bus is sent.
63    MenuConnect(String),
64}
65
66/// A request to 'activate' one of the menu items,
67/// typically sent when it is clicked.
68#[derive(Debug, Clone, Eq, PartialEq)]
69pub enum ActivateRequest {
70    /// Submenu ID
71    MenuItem {
72        address: String,
73        menu_path: String,
74        submenu_id: i32,
75    },
76    /// Default activation for the tray.
77    /// The parameter(x and y) represents screen coordinates and is to be considered an hint to the item where to show eventual windows (if any).
78    Default { address: String, x: i32, y: i32 },
79    /// Secondary activation(less important) for the tray.
80    /// The parameter(x and y) represents screen coordinates and is to be considered an hint to the item where to show eventual windows (if any).
81    Secondary { address: String, x: i32, y: i32 },
82}
83
84const PROPERTIES_INTERFACE: &str = "org.kde.StatusNotifierItem";
85
86/// Client for watching the tray.
87#[derive(Debug)]
88pub struct Client {
89    tx: broadcast::Sender<Event>,
90    _rx: broadcast::Receiver<Event>,
91    connection: Connection,
92
93    #[cfg(feature = "data")]
94    items: TrayItemMap,
95}
96
97impl Client {
98    /// Creates and initializes the client.
99    ///
100    /// The client will begin listening to items and menus and sending events immediately.
101    /// It is recommended that consumers immediately follow the call to `new` with a `subscribe` call,
102    /// then immediately follow that with a call to `items` to get the state to not miss any events.
103    ///
104    /// The value of `service_name` must be unique on the session bus.
105    /// It is recommended to use something similar to the format of `appid-numid`,
106    /// where `numid` is a short-ish random integer.
107    ///
108    /// # Errors
109    ///
110    /// If the initialization fails for any reason,
111    /// for example if unable to connect to the bus,
112    /// this method will return an error.
113    ///
114    /// # Panics
115    ///
116    /// If the generated well-known name is invalid, the library will panic
117    /// as this indicates a major bug.
118    ///
119    /// Likewise, the spawned tasks may panic if they cannot get a `Mutex` lock.
120    pub async fn new() -> Result<Self> {
121        let connection = Connection::session().await?;
122        let (tx, rx) = broadcast::channel(32);
123
124        // first start server...
125        StatusNotifierWatcher::new().attach_to(&connection).await?;
126
127        // ...then connect to it
128        let watcher_proxy = StatusNotifierWatcherProxy::new(&connection).await?;
129
130        // register a host on the watcher to declare we want to watch items
131        // get a well-known name
132        let pid = std::process::id();
133        let mut i = 0;
134        let wellknown = loop {
135            use zbus::fdo::RequestNameReply::{AlreadyOwner, Exists, InQueue, PrimaryOwner};
136
137            i += 1;
138            let wellknown = format!("org.freedesktop.StatusNotifierHost-{pid}-{i}");
139            let wellknown: zbus::names::WellKnownName = wellknown
140                .try_into()
141                .expect("generated well-known name is invalid");
142
143            let flags = [zbus::fdo::RequestNameFlags::DoNotQueue];
144            match connection
145                .request_name_with_flags(&wellknown, flags.into_iter().collect())
146                .await?
147            {
148                PrimaryOwner => break wellknown,
149                Exists | AlreadyOwner => {}
150                InQueue => unreachable!(
151                    "request_name_with_flags returned InQueue even though we specified DoNotQueue"
152                ),
153            };
154        };
155
156        debug!("wellknown: {wellknown}");
157        watcher_proxy
158            .register_status_notifier_host(&wellknown)
159            .await?;
160        let items = TrayItemMap::new();
161
162        // handle new items
163        {
164            let connection = connection.clone();
165            let tx = tx.clone();
166            let items = items.clone();
167
168            let mut stream = watcher_proxy
169                .receive_status_notifier_item_registered()
170                .await?;
171
172            spawn(async move {
173                while let Some(item) = stream.next().await {
174                    let address = item.args().map(|args| args.service);
175
176                    if let Ok(address) = address {
177                        debug!("received new item: {address}");
178                        if let Err(err) = Self::handle_item(
179                            address,
180                            connection.clone(),
181                            tx.clone(),
182                            items.clone(),
183                        )
184                        .await
185                        {
186                            error!("{err}");
187                            break;
188                        }
189                    }
190                }
191
192                Ok::<(), Error>(())
193            });
194        }
195
196        // then lastly get all items
197        // it can take so long to fetch all items that we have to do this last,
198        // otherwise some incoming items get missed
199        {
200            let connection = connection.clone();
201            let tx = tx.clone();
202            let items = items.clone();
203
204            spawn(async move {
205                let initial_items = watcher_proxy.registered_status_notifier_items().await?;
206                debug!("initial items: {initial_items:?}");
207
208                for item in initial_items {
209                    if let Err(err) =
210                        Self::handle_item(&item, connection.clone(), tx.clone(), items.clone())
211                            .await
212                    {
213                        error!("{err}");
214                    }
215                }
216
217                Ok::<(), Error>(())
218            });
219        }
220
221        // Handle other watchers unregistering and this one taking over
222        // It is necessary to clear all items as our watcher will then re-send them all
223        {
224            let tx = tx.clone();
225            let items = items.clone();
226
227            let dbus_proxy = DBusProxy::new(&connection).await?;
228
229            let mut stream = dbus_proxy.receive_name_acquired().await?;
230
231            spawn(async move {
232                while let Some(thing) = stream.next().await {
233                    let body = thing.args()?;
234                    if body.name == names::WATCHER_BUS {
235                        for dest in items.clear_items() {
236                            tx.send(Event::Remove(dest))?;
237                        }
238                    }
239                }
240
241                Ok::<(), Error>(())
242            });
243        }
244
245        debug!("tray client initialized");
246
247        Ok(Self {
248            connection,
249            tx,
250            _rx: rx,
251            #[cfg(feature = "data")]
252            items,
253        })
254    }
255
256    /// Processes an incoming item to send the initial add event,
257    /// then set up listeners for it and its menu.
258    async fn handle_item(
259        address: &str,
260        connection: Connection,
261        tx: broadcast::Sender<Event>,
262        items: TrayItemMap,
263    ) -> Result<()> {
264        let (destination, path) = parse_address(address);
265
266        let properties_proxy = PropertiesProxy::builder(&connection)
267            .destination(destination.to_string())?
268            .path(path.clone())?
269            .build()
270            .await?;
271
272        let properties = Self::get_item_properties(destination, &path, &properties_proxy).await?;
273
274        items.new_item(destination.into(), &properties);
275
276        tx.send(Event::Add(
277            destination.to_string(),
278            properties.clone().into(),
279        ))?;
280
281        {
282            let connection = connection.clone();
283            let destination = destination.to_string();
284            let items = items.clone();
285            let tx = tx.clone();
286
287            spawn(async move {
288                Self::watch_item_properties(
289                    &destination,
290                    &path,
291                    &connection,
292                    properties_proxy,
293                    tx,
294                    items,
295                )
296                .await?;
297
298                debug!("Stopped watching {destination}{path}");
299                Ok::<(), Error>(())
300            });
301        }
302
303        if let Some(menu) = properties.menu {
304            let destination = destination.to_string();
305
306            tx.send(Event::Update(
307                destination.clone(),
308                UpdateEvent::MenuConnect(menu.clone()),
309            ))?;
310
311            spawn(async move {
312                Self::watch_menu(destination, &menu, &connection, tx, items).await?;
313                Ok::<(), Error>(())
314            });
315        }
316
317        Ok(())
318    }
319
320    /// Gets the properties for an SNI item.
321    async fn get_item_properties(
322        destination: &str,
323        path: &str,
324        properties_proxy: &PropertiesProxy<'_>,
325    ) -> Result<StatusNotifierItem> {
326        let properties = properties_proxy
327            .get_all(
328                InterfaceName::from_static_str(PROPERTIES_INTERFACE)
329                    .expect("to be valid interface name"),
330            )
331            .await;
332
333        let properties = match properties {
334            Ok(properties) => properties,
335            Err(err) => {
336                error!("Error fetching properties from {destination}{path}: {err:?}");
337                return Err(err.into());
338            }
339        };
340
341        StatusNotifierItem::try_from(DBusProps(properties))
342    }
343
344    /// Watches an SNI item's properties,
345    /// sending an update event whenever they change.
346    async fn watch_item_properties(
347        destination: &str,
348        path: &str,
349        connection: &Connection,
350        properties_proxy: PropertiesProxy<'_>,
351        tx: broadcast::Sender<Event>,
352        items: TrayItemMap,
353    ) -> Result<()> {
354        let notifier_item_proxy = StatusNotifierItemProxy::builder(connection)
355            .destination(destination)?
356            .path(path)?
357            .build()
358            .await?;
359
360        let dbus_proxy = DBusProxy::new(connection).await?;
361
362        let mut disconnect_stream = dbus_proxy.receive_name_owner_changed().await?;
363        let mut props_changed = notifier_item_proxy.inner().receive_all_signals().await?;
364
365        loop {
366            tokio::select! {
367                Some(change) = props_changed.next() => {
368                    match Self::get_update_event(change, &properties_proxy).await {
369                        Ok(Some(event)) => {
370                            debug!("[{destination}{path}] received property change: {event:?}");
371
372                            cfg_if::cfg_if! {
373                                if #[cfg(feature = "data")] {
374                                    items.apply_update_event(destination, &event);
375                                }
376                            }
377
378                            tx.send(Event::Update(destination.to_string(), event))?;
379                        }
380                        Err(e) => {
381                            error!("Error parsing update properties from {destination}{path}: {e:?}");
382                        }
383                        _ => {}
384                    }
385                }
386                Some(signal) = disconnect_stream.next() => {
387                    let args = signal.args()?;
388                    let old = args.old_owner();
389                    let new = args.new_owner();
390
391                    if let (Some(old), None) = (old.as_ref(), new.as_ref()) {
392                        if old == destination {
393                            debug!("[{destination}{path}] disconnected");
394
395                            let watcher_proxy = StatusNotifierWatcherProxy::new(connection)
396                                .await
397                                .expect("Failed to open StatusNotifierWatcherProxy");
398
399                            if let Err(error) = watcher_proxy.unregister_status_notifier_item(old).await {
400                                error!("{error:?}");
401                            }
402
403
404                            items.remove_item(destination);
405
406                            tx.send(Event::Remove(destination.to_string()))?;
407                            break Ok(());
408                        }
409                    }
410                }
411            }
412        }
413    }
414
415    /// Gets the update event for a `DBus` properties change message.
416    async fn get_update_event(
417        change: Message,
418        properties_proxy: &PropertiesProxy<'_>,
419    ) -> Result<Option<UpdateEvent>> {
420        use UpdateEvent::{AttentionIcon, Icon, OverlayIcon, Status, Title, Tooltip};
421
422        let header = change.header();
423        let member = header
424            .member()
425            .ok_or(Error::InvalidData("Update message header missing `member`"))?;
426
427        macro_rules! get_property {
428            ($name:expr) => {
429                match properties_proxy
430                    .get(
431                        InterfaceName::from_static_str(PROPERTIES_INTERFACE)
432                            .expect("to be valid interface name"),
433                        $name,
434                    )
435                    .await
436                {
437                    Ok(v) => Ok(Some(v)),
438                    Err(e) => match e {
439                        // Some properties may not be set, and this error will be raised.
440                        zbus::fdo::Error::InvalidArgs(_) => {
441                            warn!("{e}");
442                            Ok(None)
443                        }
444                        _ => Err(Into::<Error>::into(e)),
445                    },
446                }
447            };
448        }
449
450        let property = match member.as_str() {
451            "NewAttentionIcon" => Some(AttentionIcon(
452                get_property!("AttentionIconName")?
453                    .as_ref()
454                    .map(OwnedValueExt::to_string)
455                    .transpose()?,
456            )),
457            "NewIcon" => {
458                let icon_name = get_property!("IconName")
459                    .unwrap_or_else(|e| {
460                        warn!("Error getting IconName: {e:?}");
461                        None
462                    })
463                    .as_ref()
464                    .map(OwnedValueExt::to_string)
465                    .transpose()
466                    .ok()
467                    .flatten();
468
469                let icon_pixmap = get_property!("IconPixmap")
470                    .unwrap_or_else(|e| {
471                        warn!("Error getting IconPixmap: {e:?}");
472                        None
473                    })
474                    .as_deref()
475                    .map(Value::downcast_ref::<&Array>)
476                    .transpose()?
477                    .map(IconPixmap::from_array)
478                    .transpose()?;
479
480                Some(Icon {
481                    icon_name,
482                    icon_pixmap,
483                })
484            }
485            "NewOverlayIcon" => Some(OverlayIcon(
486                get_property!("OverlayIconName")?
487                    .as_ref()
488                    .map(OwnedValueExt::to_string)
489                    .transpose()?,
490            )),
491            "NewStatus" => Some(Status(
492                get_property!("Status")?
493                    .as_deref()
494                    .map(Value::downcast_ref::<&str>)
495                    .transpose()?
496                    .map(item::Status::from)
497                    .unwrap_or_default(), // NOTE: i'm assuming status is always set
498            )),
499            "NewTitle" => Some(Title(
500                get_property!("Title")?
501                    .as_ref()
502                    .map(OwnedValueExt::to_string)
503                    .transpose()?,
504            )),
505            "NewToolTip" => Some(Tooltip(
506                get_property!("ToolTip")?
507                    .as_deref()
508                    .map(Value::downcast_ref::<&Structure>)
509                    .transpose()?
510                    .map(crate::item::Tooltip::try_from)
511                    .transpose()?,
512            )),
513            _ => {
514                warn!("received unhandled update event: {member}");
515                None
516            }
517        };
518
519        debug!("received tray item update: {member} -> {property:?}");
520
521        Ok(property)
522    }
523
524    /// Watches the `DBusMenu` associated with an SNI item.
525    ///
526    /// This gets the initial menu, sending an update event immediately.
527    /// Update events are then sent for any further updates
528    /// until the item is removed.
529    async fn watch_menu(
530        destination: String,
531        menu_path: &str,
532        connection: &Connection,
533        tx: broadcast::Sender<Event>,
534        items: TrayItemMap,
535    ) -> Result<()> {
536        const LAYOUT_UPDATE_INTERVAL_MS: Duration = Duration::from_millis(50);
537
538        let dbus_menu_proxy = DBusMenuProxy::builder(connection)
539            .destination(destination.as_str())?
540            .path(menu_path)?
541            .build()
542            .await?;
543
544        debug!("[{destination}{menu_path}] getting initial menu");
545        let menu = dbus_menu_proxy.get_layout(0, -1, &[]).await?;
546        let menu = TrayMenu::try_from(menu)?;
547
548        items.update_menu(&destination, &menu);
549
550        tx.send(Event::Update(destination.clone(), UpdateEvent::Menu(menu)))?;
551
552        let mut layout_updated = dbus_menu_proxy.receive_layout_updated().await?;
553        let mut properties_updated = dbus_menu_proxy.receive_items_properties_updated().await?;
554
555        let last_layout_update = Arc::new(Mutex::new(Instant::now()));
556        let (layout_tx, mut layout_rx) = mpsc::channel(4);
557
558        loop {
559            tokio::select!(
560                Some(ev) = layout_updated.next() => {
561                    trace!("received layout update");
562
563                    let now = Instant::now();
564                    *last_layout_update.lock().expect("should get lock") = now;
565
566                    let args = ev.args()?;
567
568                    let last_layout_update = last_layout_update.clone();
569                    let layout_tx = layout_tx.clone();
570                    spawn(async move {
571                        sleep(LAYOUT_UPDATE_INTERVAL_MS).await;
572                        if *last_layout_update.lock().expect("should get lock") == now {
573                            trace!("dispatching layout update");
574                            layout_tx.send(args.parent).await.expect("should send");
575                        }
576                    });
577                }
578                Some(layout_parent) = layout_rx.recv() => {
579                    debug!("[{destination}{menu_path}] layout update");
580
581                    let get_layout = dbus_menu_proxy.get_layout(layout_parent, -1, &[]);
582
583                    let menu = match timeout(Duration::from_secs(1), get_layout).await {
584                        Ok(Ok(menu)) => {
585                            debug!("got new menu layout");
586                            menu
587                        }
588                        Ok(Err(err)) => {
589                            error!("error fetching layout: {err:?}");
590                            break;
591                        }
592                        Err(_) => {
593                            error!("Timeout getting layout");
594                            break;
595                        }
596                    };
597
598                    let menu = TrayMenu::try_from(menu)?;
599
600                    items.update_menu(&destination, &menu);
601
602                    debug!("sending new menu for '{destination}'");
603                    trace!("new menu for '{destination}': {menu:?}");
604                    tx.send(Event::Update(
605                        destination.clone(),
606                        UpdateEvent::Menu(menu),
607                    ))?;
608                }
609                Some(change) = properties_updated.next() => {
610                    let body = change.message().body();
611                    let update: PropertiesUpdate= body.deserialize::<PropertiesUpdate>()?;
612                    let diffs = Vec::try_from(update)?;
613
614                    #[cfg(feature = "data")]
615                    if let Some((_, Some(menu))) = items
616                        .get_map()
617                        .lock()
618                        .expect("mutex lock should succeed")
619                        .get_mut(&destination)
620                    {
621                        apply_menu_diffs(menu, &diffs);
622                    } else {
623                        error!("could not find item in state");
624                    }
625
626                    tx.send(Event::Update(
627                        destination.clone(),
628                        UpdateEvent::MenuDiff(diffs),
629                    ))?;
630
631                    // FIXME: Menu cache gonna be out of sync
632                }
633            );
634        }
635
636        Ok(())
637    }
638
639    async fn get_notifier_item_proxy(
640        &self,
641        address: String,
642    ) -> Result<StatusNotifierItemProxy<'_>> {
643        let proxy = StatusNotifierItemProxy::builder(&self.connection)
644            .destination(address)?
645            .path(ITEM_OBJECT)?
646            .build()
647            .await?;
648        Ok(proxy)
649    }
650
651    async fn get_menu_proxy(
652        &self,
653        address: String,
654        menu_path: String,
655    ) -> Result<DBusMenuProxy<'_>> {
656        let proxy = DBusMenuProxy::builder(&self.connection)
657            .destination(address)?
658            .path(menu_path)?
659            .build()
660            .await?;
661
662        Ok(proxy)
663    }
664
665    /// Subscribes to the events broadcast channel,
666    /// returning a new receiver.
667    ///
668    /// Once the client is dropped, the receiver will close.
669    #[must_use]
670    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
671        self.tx.subscribe()
672    }
673
674    /// Gets all current items, including their menus if present.
675    #[cfg(feature = "data")]
676    #[must_use]
677    pub fn items(&self) -> std::sync::Arc<std::sync::Mutex<crate::data::BaseMap>> {
678        self.items.get_map()
679    }
680
681    /// One should call this method with id=0 when opening the root menu.
682    ///
683    /// ID refers to the menuitem id.
684    /// Returns `needsUpdate`
685    ///
686    /// # Errors
687    ///
688    /// Errors if the proxy cannot be created.
689    pub async fn about_to_show_menuitem(
690        &self,
691        address: String,
692        menu_path: String,
693        id: i32,
694    ) -> Result<bool> {
695        let proxy = self.get_menu_proxy(address, menu_path).await?;
696        Ok(proxy.about_to_show(id).await?)
697    }
698
699    /// Sends an activate request for a menu item.
700    ///
701    /// # Errors
702    ///
703    /// The method will return an error if the connection to the `DBus` object fails,
704    /// or if sending the event fails for any reason.
705    ///
706    /// # Panics
707    ///
708    /// If the system time is somehow before the Unix epoch.
709    pub async fn activate(&self, req: ActivateRequest) -> Result<()> {
710        macro_rules! timeout_event {
711            ($event:expr) => {
712                if timeout(Duration::from_secs(1), $event).await.is_err() {
713                    error!("Timed out sending activate event");
714                }
715            };
716        }
717        match req {
718            ActivateRequest::MenuItem {
719                address,
720                menu_path,
721                submenu_id,
722            } => {
723                let proxy = self.get_menu_proxy(address, menu_path).await?;
724                let timestamp = SystemTime::now()
725                    .duration_since(UNIX_EPOCH)
726                    .expect("time should flow forwards");
727
728                let event = proxy.event(
729                    submenu_id,
730                    "clicked",
731                    &Value::I32(0),
732                    timestamp.as_secs() as u32,
733                );
734
735                timeout_event!(event);
736            }
737            ActivateRequest::Default { address, x, y } => {
738                let proxy = self.get_notifier_item_proxy(address).await?;
739                let event = proxy.activate(x, y);
740
741                timeout_event!(event);
742            }
743            ActivateRequest::Secondary { address, x, y } => {
744                let proxy = self.get_notifier_item_proxy(address).await?;
745                let event = proxy.secondary_activate(x, y);
746
747                timeout_event!(event);
748            }
749        }
750
751        Ok(())
752    }
753}
754
755fn parse_address(address: &str) -> (&str, String) {
756    address
757        .split_once('/')
758        .map_or((address, String::from("/StatusNotifierItem")), |(d, p)| {
759            (d, format!("/{p}"))
760        })
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn parse_unnamed() {
769        let address = ":1.58/StatusNotifierItem";
770        let (destination, path) = parse_address(address);
771
772        assert_eq!(":1.58", destination);
773        assert_eq!("/StatusNotifierItem", path);
774    }
775
776    #[test]
777    fn parse_named() {
778        let address = ":1.72/org/ayatana/NotificationItem/dropbox_client_1398";
779        let (destination, path) = parse_address(address);
780
781        assert_eq!(":1.72", destination);
782        assert_eq!("/org/ayatana/NotificationItem/dropbox_client_1398", path);
783    }
784}