use crate::item::TrayItem;
use crate::menu::Menu;
use crate::prefs::MenuServing;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use zbus::object_server::SignalEmitter;
use zbus::Connection;
pub const TIMEOUT: Duration = Duration::from_secs(5);
pub const ITEM_PATH: &str = "/StatusNotifierItem";
pub const MENU_PATH: &str = "/StatusNotifierItem/Menu";
pub fn declares_menu(serving: MenuServing, menu: Option<&Menu>) -> bool {
serving == MenuServing::Dbusmenu && menu.is_some_and(|m| !m.items.is_empty())
}
pub fn takes_menu_update(declared: bool, next: &Menu) -> bool {
!(declared && next.items.is_empty())
}
#[derive(Debug, thiserror::Error)]
pub enum TrayError {
#[error("no StatusNotifierWatcher is running, so there is no tray to appear in")]
NoWatcher,
#[error("the tray host didn't answer within {0:?}")]
TimedOut(Duration),
#[error("{0}")]
Refused(String),
}
fn classify(e: zbus::Error) -> TrayError {
if let zbus::Error::MethodError(name, _, _) = &e {
let name = name.as_str();
if name.ends_with(".ServiceUnknown") || name.ends_with(".NameHasNoOwner") {
return TrayError::NoWatcher;
}
return TrayError::Refused(e.to_string());
}
TrayError::Refused(e.to_string())
}
async fn bounded<T>(
call: impl std::future::Future<Output = zbus::Result<T>>,
) -> Result<T, TrayError> {
match tokio::time::timeout(TIMEOUT, call).await {
Err(_) => Err(TrayError::TimedOut(TIMEOUT)),
Ok(Ok(v)) => Ok(v),
Ok(Err(e)) => Err(classify(e)),
}
}
#[zbus::proxy(
interface = "org.kde.StatusNotifierWatcher",
default_service = "org.kde.StatusNotifierWatcher",
default_path = "/StatusNotifierWatcher"
)]
trait StatusNotifierWatcher {
fn register_status_notifier_item(&self, service: &str) -> zbus::Result<()>;
#[zbus(property)]
fn is_status_notifier_host_registered(&self) -> zbus::Result<bool>;
#[zbus(property)]
fn registered_status_notifier_items(&self) -> zbus::Result<Vec<String>>;
}
struct ItemInterface {
state: Arc<Mutex<TrayItem>>,
menu: Option<Arc<Mutex<crate::menu::Menu>>>,
clicks: tokio::sync::mpsc::UnboundedSender<String>,
menu_clicks: Option<tokio::sync::mpsc::UnboundedSender<String>>,
}
#[zbus::interface(name = "org.kde.StatusNotifierItem")]
impl ItemInterface {
#[zbus(property)]
async fn category(&self) -> String {
self.state.lock().await.category.as_str().to_string()
}
#[zbus(property)]
async fn id(&self) -> String {
self.state.lock().await.id.clone()
}
#[zbus(property)]
async fn title(&self) -> String {
self.state.lock().await.title.clone()
}
#[zbus(property)]
async fn status(&self) -> String {
self.state.lock().await.status.as_str().to_string()
}
#[zbus(property)]
async fn icon_name(&self) -> String {
self.state.lock().await.icon_name.clone()
}
#[zbus(property)]
async fn icon_pixmap(&self) -> Vec<(i32, i32, Vec<u8>)> {
Vec::new()
}
#[zbus(property)]
async fn item_is_menu(&self) -> bool {
false
}
#[zbus(property)]
async fn tool_tip(&self) -> (String, Vec<(i32, i32, Vec<u8>)>, String, String) {
let state = self.state.lock().await;
(
state.icon_name.clone(),
Vec::new(),
state.tooltip_title.clone(),
state.tooltip_body.clone(),
)
}
#[zbus(property)]
async fn window_id(&self) -> i32 {
0
}
async fn activate(&self, _x: i32, _y: i32) {
let screen = self.state.lock().await.activate_screen();
if let Some(screen) = screen {
let _ = self.clicks.send(screen.to_string());
}
}
async fn secondary_activate(&self, x: i32, y: i32) {
self.activate(x, y).await;
}
async fn context_menu(&self, x: i32, y: i32) {
let (Some(menu), Some(events)) = (self.menu.clone(), self.menu_clicks.clone()) else {
self.activate(x, y).await;
return;
};
let id = self.state.lock().await.id.clone();
let state = self.state.clone();
let clicks = self.clicks.clone();
tokio::spawn(async move {
let snapshot = menu.lock().await.clone();
if let crate::launch::LaunchOutcome::NotInstalled =
crate::launch::show(&id, &snapshot, x, y, &events).await
{
let screen = state.lock().await.activate_screen();
if let Some(screen) = screen {
let _ = clicks.send(screen.to_string());
}
}
});
}
async fn scroll(&self, _delta: i32, _orientation: String) {}
#[zbus(signal)]
async fn new_icon(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_status(emitter: &SignalEmitter<'_>, status: &str) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_tool_tip(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_title(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
}
struct ItemWithMenuInterface {
inner: ItemInterface,
}
#[zbus::interface(name = "org.kde.StatusNotifierItem")]
impl ItemWithMenuInterface {
#[zbus(property)]
async fn category(&self) -> String {
self.inner.category().await
}
#[zbus(property)]
async fn id(&self) -> String {
self.inner.id().await
}
#[zbus(property)]
async fn title(&self) -> String {
self.inner.title().await
}
#[zbus(property)]
async fn status(&self) -> String {
self.inner.status().await
}
#[zbus(property)]
async fn icon_name(&self) -> String {
self.inner.icon_name().await
}
#[zbus(property)]
async fn icon_pixmap(&self) -> Vec<(i32, i32, Vec<u8>)> {
self.inner.icon_pixmap().await
}
#[zbus(property)]
async fn item_is_menu(&self) -> bool {
self.inner.item_is_menu().await
}
#[zbus(property)]
async fn tool_tip(&self) -> (String, Vec<(i32, i32, Vec<u8>)>, String, String) {
self.inner.tool_tip().await
}
#[zbus(property)]
async fn menu(&self) -> zbus::zvariant::OwnedObjectPath {
zbus::zvariant::OwnedObjectPath::try_from(MENU_PATH).expect("MENU_PATH is a valid object path")
}
#[zbus(property)]
async fn window_id(&self) -> i32 {
self.inner.window_id().await
}
async fn activate(&self, x: i32, y: i32) {
self.inner.activate(x, y).await;
}
async fn secondary_activate(&self, x: i32, y: i32) {
self.inner.secondary_activate(x, y).await;
}
async fn context_menu(&self, x: i32, y: i32) {
self.inner.context_menu(x, y).await;
}
async fn scroll(&self, delta: i32, orientation: String) {
self.inner.scroll(delta, orientation).await;
}
#[zbus(signal)]
async fn new_icon(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_status(emitter: &SignalEmitter<'_>, status: &str) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_tool_tip(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_title(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
}
pub struct TrayIcon {
connection: Connection,
bus_name: String,
state: Arc<Mutex<TrayItem>>,
last: Mutex<TrayItem>,
menu: Option<Arc<Mutex<crate::menu::Menu>>>,
serving: MenuServing,
menu_declared: bool,
menu_revision: Arc<Mutex<u32>>,
}
impl TrayIcon {
pub async fn register(
item: TrayItem,
index: u32,
clicks: tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<Self, TrayError> {
Self::build(item, None, MenuServing::Popup, index, clicks, None).await
}
pub async fn register_with_menu(
item: TrayItem,
menu: crate::menu::Menu,
index: u32,
clicks: tokio::sync::mpsc::UnboundedSender<String>,
menu_clicks: tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<Self, TrayError> {
Self::register_serving(item, menu, MenuServing::Popup, index, clicks, menu_clicks).await
}
pub async fn register_serving(
item: TrayItem,
menu: crate::menu::Menu,
serving: MenuServing,
index: u32,
clicks: tokio::sync::mpsc::UnboundedSender<String>,
menu_clicks: tokio::sync::mpsc::UnboundedSender<String>,
) -> Result<Self, TrayError> {
Self::build(item, Some(menu), serving, index, clicks, Some(menu_clicks)).await
}
async fn build(
item: TrayItem,
menu: Option<crate::menu::Menu>,
serving: MenuServing,
index: u32,
clicks: tokio::sync::mpsc::UnboundedSender<String>,
menu_clicks: Option<tokio::sync::mpsc::UnboundedSender<String>>,
) -> Result<Self, TrayError> {
let bus_name = format!("org.kde.StatusNotifierItem-{}-{}", std::process::id(), index);
let menu_declared = declares_menu(serving, menu.as_ref());
let state = Arc::new(Mutex::new(item.clone()));
let menu_state = menu.map(|m| Arc::new(Mutex::new(m)));
let menu_revision = Arc::new(Mutex::new(1u32));
let inner = ItemInterface {
state: state.clone(),
menu: menu_state.clone(),
clicks,
menu_clicks: menu_clicks.clone(),
};
let builder = zbus::connection::Builder::session()
.map_err(classify)?
.name(bus_name.as_str())
.map_err(classify)?;
let builder = match (&menu_state, &menu_clicks) {
(Some(menu), Some(events)) if menu_declared => builder
.serve_at(ITEM_PATH, ItemWithMenuInterface { inner })
.map_err(classify)?
.serve_at(
MENU_PATH,
crate::dbusmenu::MenuInterface::new(
item.id.clone(),
menu.clone(),
menu_revision.clone(),
events.clone(),
),
)
.map_err(classify)?,
_ => builder.serve_at(ITEM_PATH, inner).map_err(classify)?,
};
let connection = builder.build().await.map_err(classify)?;
let icon = TrayIcon {
connection,
bus_name,
state,
last: Mutex::new(item),
menu: menu_state,
serving,
menu_declared,
menu_revision,
};
icon.announce().await?;
Ok(icon)
}
pub async fn release(&self) {
if let Err(e) = self.connection.release_name(self.bus_name.as_str()).await {
tracing::warn!(error = %e, item = %self.bus_name, "could not release a tray item's bus name");
}
}
pub fn serving(&self) -> MenuServing {
self.serving
}
pub fn menu_declared(&self) -> bool {
self.menu_declared
}
pub async fn update_menu(&self, next: crate::menu::Menu) -> Result<(), TrayError> {
let Some(menu) = &self.menu else {
return Ok(());
};
if !takes_menu_update(self.menu_declared, &next) {
tracing::warn!(
item = %self.bus_name,
"kept the last menu rather than serve an empty dbusmenu layout"
);
return Ok(());
}
let mut current = menu.lock().await;
if *current == next {
return Ok(());
}
*current = next;
drop(current);
if self.menu_declared {
let revision = {
let mut revision = self.menu_revision.lock().await;
*revision += 1;
*revision
};
let emitter = SignalEmitter::new(&self.connection, MENU_PATH).map_err(classify)?;
crate::dbusmenu::MenuInterface::layout_updated(&emitter, revision, 0)
.await
.map_err(classify)?;
}
Ok(())
}
pub async fn announce(&self) -> Result<(), TrayError> {
let watcher = bounded(StatusNotifierWatcherProxy::new(&self.connection)).await?;
bounded(watcher.register_status_notifier_item(&self.bus_name)).await
}
pub async fn update(&self, next: TrayItem) -> Result<(), TrayError> {
let mut last = self.last.lock().await;
if *last == next {
return Ok(());
}
let emitter = SignalEmitter::new(&self.connection, ITEM_PATH).map_err(classify)?;
let icon_changed = last.icon_name != next.icon_name;
let status_changed = last.status != next.status;
let title_changed = last.title != next.title;
let tooltip_changed =
last.tooltip_title != next.tooltip_title || last.tooltip_body != next.tooltip_body;
*self.state.lock().await = next.clone();
*last = next.clone();
drop(last);
let declared = self.menu_declared;
if icon_changed {
if declared {
ItemWithMenuInterface::new_icon(&emitter).await
} else {
ItemInterface::new_icon(&emitter).await
}
.map_err(classify)?;
}
if status_changed {
let status = next.status.as_str();
if declared {
ItemWithMenuInterface::new_status(&emitter, status).await
} else {
ItemInterface::new_status(&emitter, status).await
}
.map_err(classify)?;
}
if title_changed {
if declared {
ItemWithMenuInterface::new_title(&emitter).await
} else {
ItemInterface::new_title(&emitter).await
}
.map_err(classify)?;
}
if tooltip_changed {
if declared {
ItemWithMenuInterface::new_tool_tip(&emitter).await
} else {
ItemInterface::new_tool_tip(&emitter).await
}
.map_err(classify)?;
}
Ok(())
}
pub fn bus_name(&self) -> &str {
&self.bus_name
}
}
pub async fn watcher_present(connection: &Connection) -> bool {
match bounded(StatusNotifierWatcherProxy::new(connection)).await {
Ok(watcher) => bounded(watcher.is_status_notifier_host_registered())
.await
.unwrap_or(false),
Err(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::item::{Category, Status};
fn item() -> TrayItem {
TrayItem {
id: "hyprforge-network".to_string(),
category: Category::Hardware,
status: Status::Active,
title: "Network".to_string(),
icon_name: "network-wireless-signal-good".to_string(),
tooltip_title: "Connected".to_string(),
tooltip_body: "home".to_string(),
}
}
#[test]
fn the_bus_name_follows_the_convention_hosts_expect() {
let name = format!("org.kde.StatusNotifierItem-{}-{}", std::process::id(), 1);
assert!(name.starts_with("org.kde.StatusNotifierItem-"));
assert_eq!(name.matches('-').count(), 2);
}
#[test]
fn no_bar_running_is_its_own_state_rather_than_a_failure() {
let message = TrayError::NoWatcher.to_string();
assert!(message.contains("no StatusNotifierWatcher"));
assert!(!matches!(TrayError::NoWatcher, TrayError::Refused(_)));
}
#[test]
fn an_unchanged_item_is_equal_to_itself_so_update_can_skip_it() {
assert_eq!(item(), item());
let mut changed = item();
changed.icon_name = "network-wireless-signal-weak".to_string();
assert_ne!(item(), changed);
}
fn interface(menu: Option<crate::menu::Menu>) -> ItemInterface {
let (clicks, _rx) = tokio::sync::mpsc::unbounded_channel();
let (menu_clicks, _mrx) = tokio::sync::mpsc::unbounded_channel();
ItemInterface {
state: Arc::new(Mutex::new(item())),
menu: menu.map(|m| Arc::new(Mutex::new(m))),
clicks,
menu_clicks: Some(menu_clicks),
}
}
#[tokio::test]
async fn item_is_menu_stays_false_whether_or_not_there_is_a_menu() {
assert!(!interface(None).item_is_menu().await);
assert!(
!interface(Some(crate::menu::Menu::default())).item_is_menu().await
);
}
#[test]
fn a_menu_property_is_declared_only_with_rows_behind_it() {
let rows = crate::menu::Menu::new(vec![crate::menu::MenuItem::standard("Settings…", "settings")]);
let empty = crate::menu::Menu::default();
assert!(declares_menu(MenuServing::Dbusmenu, Some(&rows)));
assert!(!declares_menu(MenuServing::Dbusmenu, Some(&empty)), "no rows, no Menu property");
assert!(!declares_menu(MenuServing::Dbusmenu, None), "no menu, no Menu property");
assert!(!declares_menu(MenuServing::Popup, Some(&rows)), "the popup path never declares one");
}
#[test]
fn an_empty_menu_never_replaces_a_served_dbusmenu_layout() {
let rows = crate::menu::Menu::new(vec![crate::menu::MenuItem::standard("Settings…", "settings")]);
let empty = crate::menu::Menu::default();
assert!(!takes_menu_update(true, &empty));
assert!(takes_menu_update(true, &rows));
assert!(takes_menu_update(false, &empty), "nothing declared, nothing for a bar to draw empty");
}
#[tokio::test]
async fn the_dbusmenu_item_is_the_same_item_with_a_menu_path() {
let with_menu = ItemWithMenuInterface { inner: interface(Some(crate::menu::Menu::default())) };
let plain = interface(None);
assert_eq!(with_menu.id().await, plain.id().await);
assert_eq!(with_menu.icon_name().await, plain.icon_name().await);
assert_eq!(with_menu.tool_tip().await, plain.tool_tip().await);
assert!(!with_menu.item_is_menu().await);
assert_eq!(with_menu.menu().await.as_str(), MENU_PATH);
}
#[tokio::test]
async fn context_menu_with_no_menu_at_all_falls_back_to_the_primary_action() {
let (clicks, mut rx) = tokio::sync::mpsc::unbounded_channel();
let iface = ItemInterface { state: Arc::new(Mutex::new(item())), menu: None, clicks, menu_clicks: None };
iface.context_menu(0, 0).await;
assert_eq!(rx.recv().await.unwrap(), "network", "hyprforge-network opens the network screen");
}
}