Skip to main content

day_platform_linux/dbus/
sni.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! A `StatusNotifierItem` server with its `com.canonical.dbusmenu` menu: the Linux status item
5//! ("tray icon") that KDE Plasma, GNOME with the AppIndicator extension, Xfce, LXQt, Budgie,
6//! Cinnamon and the wlroots bars (waybar, …) display.
7//!
8//! The server is toolkit-agnostic. It takes a neutral [`Item`] (id, title, tooltip, icon as
9//! ARGB32 pixmaps and/or a theme icon name, status) and a neutral menu tree of [`MenuEntry`],
10//! exports `/StatusNotifierItem` and `/MenuBar`, registers with the
11//! `org.kde.StatusNotifierWatcher`, and re-registers whenever the watcher (re)appears. Clicks and
12//! menu selections arrive as [`Event`]s through a callback on the connection's reader thread; a
13//! toolkit backend forwards them to its UI thread.
14//!
15//! The item owns `org.kde.StatusNotifierItem-<pid>-<n>`, except inside Flatpak or Snap, where
16//! the sandbox does not let an app own that name; there it registers by its unique bus name,
17//! which every watcher accepts.
18//!
19//! One connection serves one item, because the object paths are fixed by the protocol; open a
20//! further [`Connection`] for a second item.
21
22use std::path::Path;
23use std::sync::atomic::{AtomicU32, Ordering};
24use std::sync::{Arc, Mutex};
25
26use super::{
27    BUS_INTERFACE, BUS_NAME, Connection, Error, Message, MethodCall, MethodError,
28    NAME_FLAG_DO_NOT_QUEUE, NAME_REPLY_ALREADY_OWNER, NAME_REPLY_PRIMARY_OWNER,
29    PROPERTIES_INTERFACE, SignalFilter, SubscriptionId, Value, introspection_xml, lock,
30};
31
32/// The item's object path.
33pub const ITEM_PATH: &str = "/StatusNotifierItem";
34/// The menu's object path.
35pub const MENU_PATH: &str = "/MenuBar";
36/// The item interface.
37pub const ITEM_INTERFACE: &str = "org.kde.StatusNotifierItem";
38/// The menu interface.
39pub const MENU_INTERFACE: &str = "com.canonical.dbusmenu";
40/// The watcher's well-known name, which is also its interface.
41pub const WATCHER_NAME: &str = "org.kde.StatusNotifierWatcher";
42/// The watcher's object path.
43pub const WATCHER_PATH: &str = "/StatusNotifierWatcher";
44
45/// Whether a `StatusNotifierWatcher` is on the bus, that is, whether a status item can show.
46pub fn watcher_available(conn: &Connection) -> bool {
47    conn.name_has_owner(WATCHER_NAME)
48}
49
50/// One icon image: `width × height` pixels of ARGB32, row by row. Each `u32` is
51/// `0xAARRGGBB` (non-premultiplied); on the wire it goes out in network byte order (big-endian
52/// A, R, G, B), as the specification requires whatever the host's byte order.
53#[derive(Clone, Debug, Default, PartialEq, Eq)]
54pub struct Pixmap {
55    /// Width in pixels.
56    pub width: i32,
57    /// Height in pixels.
58    pub height: i32,
59    /// `width × height` pixels, `0xAARRGGBB` each.
60    pub argb: Vec<u32>,
61}
62
63impl Pixmap {
64    /// Converts straight (non-premultiplied) RGBA8 bytes; `None` when the length is not
65    /// `width × height × 4` or a dimension does not fit `i32`.
66    pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Option<Pixmap> {
67        let pixels = usize::try_from(u64::from(width) * u64::from(height)).ok()?;
68        if rgba.len() != pixels.checked_mul(4)? {
69            return None;
70        }
71        Some(Pixmap {
72            width: i32::try_from(width).ok()?,
73            height: i32::try_from(height).ok()?,
74            argb: rgba
75                .as_chunks::<4>()
76                .0
77                .iter()
78                .map(|[r, g, b, a]| u32::from_be_bytes([*a, *r, *g, *b]))
79                .collect(),
80        })
81    }
82
83    /// The `(iiay)` struct, or `None` when the pixel count does not match the size.
84    fn to_value(&self) -> Option<Value> {
85        let expected = usize::try_from(self.width).ok()? * usize::try_from(self.height).ok()?;
86        if expected != self.argb.len() {
87            return None;
88        }
89        let mut bytes = Vec::with_capacity(expected * 4);
90        for px in &self.argb {
91            bytes.extend_from_slice(&px.to_be_bytes());
92        }
93        Some(Value::Struct(vec![
94            Value::I32(self.width),
95            Value::I32(self.height),
96            Value::bytes(&bytes),
97        ]))
98    }
99}
100
101fn pixmaps_value(pixmaps: &[Pixmap]) -> Value {
102    Value::array(
103        "(iiay)",
104        pixmaps.iter().filter_map(Pixmap::to_value).collect(),
105    )
106}
107
108/// The item's status, which hosts use to show or hide it.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110pub enum Status {
111    /// Shown normally.
112    #[default]
113    Active,
114    /// Present but unimportant; hosts may hide it in an overflow area.
115    Passive,
116    /// Asks for the user's attention.
117    NeedsAttention,
118}
119
120impl Status {
121    fn as_str(self) -> &'static str {
122        match self {
123            Status::Active => "Active",
124            Status::Passive => "Passive",
125            Status::NeedsAttention => "NeedsAttention",
126        }
127    }
128}
129
130/// What kind of item this is, which some hosts use to group items.
131#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub enum Category {
133    /// An application's own status (the usual choice).
134    #[default]
135    ApplicationStatus,
136    /// A communication app (chat, mail).
137    Communications,
138    /// A system service.
139    SystemServices,
140    /// A hardware indicator (battery, network).
141    Hardware,
142}
143
144impl Category {
145    fn as_str(self) -> &'static str {
146        match self {
147            Category::ApplicationStatus => "ApplicationStatus",
148            Category::Communications => "Communications",
149            Category::SystemServices => "SystemServices",
150            Category::Hardware => "Hardware",
151        }
152    }
153}
154
155/// The item's description.
156#[derive(Clone, Debug, Default, PartialEq)]
157pub struct Item {
158    /// A stable identifier for the item, such as the app id.
159    pub id: String,
160    /// The item's title (shown by some hosts, and read by screen readers).
161    pub title: String,
162    /// The tooltip text; empty uses the title.
163    pub tooltip: String,
164    /// A freedesktop icon theme name; hosts prefer it over pixmaps when they find it.
165    pub icon_name: String,
166    /// Extra directory searched for `icon_name`, or empty.
167    pub icon_theme_path: String,
168    /// The icon at several sizes, for hosts without the theme icon.
169    pub icon_pixmaps: Vec<Pixmap>,
170    /// Active, passive or needs-attention.
171    pub status: Status,
172    /// The item's category.
173    pub category: Category,
174    /// Whether a primary click opens the menu instead of sending [`Event::Activate`].
175    pub item_is_menu: bool,
176}
177
178/// A menu entry's checkmark.
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180pub enum Check {
181    /// Not checkable.
182    #[default]
183    None,
184    /// Checkable and checked.
185    On,
186    /// Checkable and unchecked.
187    Off,
188}
189
190/// One menu entry. Ids are chosen by the caller, must be unique within the menu, and must not be
191/// 0 (the root). A separator ignores its label; an entry with children is a submenu.
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct MenuEntry {
194    /// The id reported in [`Event::MenuItem`].
195    pub id: i32,
196    /// The label, shown literally (underscores are escaped from dbusmenu's mnemonic syntax).
197    pub label: String,
198    /// Whether the entry can be chosen.
199    pub enabled: bool,
200    /// Whether the entry is shown.
201    pub visible: bool,
202    /// The checkmark state.
203    pub check: Check,
204    /// Whether the entry is a separator line.
205    pub separator: bool,
206    /// The submenu's entries.
207    pub children: Vec<MenuEntry>,
208}
209
210impl MenuEntry {
211    /// An enabled, visible, uncheckable entry.
212    pub fn item(id: i32, label: impl Into<String>) -> Self {
213        MenuEntry {
214            id,
215            label: label.into(),
216            enabled: true,
217            visible: true,
218            check: Check::None,
219            separator: false,
220            children: Vec::new(),
221        }
222    }
223
224    /// A separator.
225    pub fn separator(id: i32) -> Self {
226        MenuEntry {
227            separator: true,
228            ..MenuEntry::item(id, "")
229        }
230    }
231
232    /// A submenu.
233    pub fn submenu(id: i32, label: impl Into<String>, children: Vec<MenuEntry>) -> Self {
234        MenuEntry {
235            children,
236            ..MenuEntry::item(id, label)
237        }
238    }
239
240    /// The same entry with a checkmark state.
241    pub fn with_check(mut self, check: Check) -> Self {
242        self.check = check;
243        self
244    }
245
246    /// The same entry with `enabled` set.
247    pub fn with_enabled(mut self, enabled: bool) -> Self {
248        self.enabled = enabled;
249        self
250    }
251}
252
253/// What the user did with the item.
254#[derive(Clone, Debug, PartialEq, Eq)]
255pub enum Event {
256    /// Primary click at screen position `(x, y)`.
257    Activate {
258        /// Screen x.
259        x: i32,
260        /// Screen y.
261        y: i32,
262    },
263    /// Middle click.
264    SecondaryActivate {
265        /// Screen x.
266        x: i32,
267        /// Screen y.
268        y: i32,
269    },
270    /// The host asks the app to show its own context menu (hosts that use the exported menu
271    /// never send this).
272    ContextMenu {
273        /// Screen x.
274        x: i32,
275        /// Screen y.
276        y: i32,
277    },
278    /// Scroll over the item.
279    Scroll {
280        /// Steps scrolled.
281        delta: i32,
282        /// Horizontal rather than vertical.
283        horizontal: bool,
284    },
285    /// A menu entry was chosen.
286    MenuItem {
287        /// The entry's id.
288        id: i32,
289    },
290}
291
292struct State {
293    item: Item,
294    menu: Vec<MenuEntry>,
295    revision: u32,
296}
297
298type EventFn = dyn FnMut(Event) + Send;
299
300struct Core {
301    state: Mutex<State>,
302    on_event: Mutex<Box<EventFn>>,
303}
304
305impl Core {
306    fn deliver(&self, event: Event) {
307        let mut callback = lock(&self.on_event);
308        (callback)(event);
309    }
310}
311
312/// A live status item. Dropping it removes the item from the bus.
313pub struct StatusItem {
314    conn: Connection,
315    core: Arc<Core>,
316    service: String,
317    owns_name: bool,
318    subscription: Option<SubscriptionId>,
319    match_rule: String,
320}
321
322static NEXT_ITEM: AtomicU32 = AtomicU32::new(1);
323
324fn sandboxed() -> bool {
325    Path::new("/.flatpak-info").exists() || std::env::var_os("SNAP").is_some()
326}
327
328impl StatusItem {
329    /// Exports the item and its menu on `conn` and registers with the watcher if one is
330    /// running (and again whenever one starts). `on_event` runs on the connection's reader
331    /// thread, so it should hand the event on rather than block.
332    pub fn new<F>(
333        conn: &Connection,
334        item: Item,
335        menu: Vec<MenuEntry>,
336        on_event: F,
337    ) -> Result<StatusItem, Error>
338    where
339        F: FnMut(Event) + Send + 'static,
340    {
341        let core = Arc::new(Core {
342            state: Mutex::new(State {
343                item,
344                menu,
345                revision: 1,
346            }),
347            on_event: Mutex::new(Box::new(on_event)),
348        });
349        let item_core = core.clone();
350        conn.export(ITEM_PATH, move |call| item_call(&item_core, call))?;
351        let menu_core = core.clone();
352        if let Err(e) = conn.export(MENU_PATH, move |call| menu_call(&menu_core, call)) {
353            // MENU_PATH belongs to someone else; only ITEM_PATH is ours to remove.
354            conn.unexport(ITEM_PATH);
355            return Err(e);
356        }
357        // From here on, Drop undoes whatever succeeded.
358        let mut this = StatusItem {
359            conn: conn.clone(),
360            core,
361            service: conn.unique_name().to_owned(),
362            owns_name: false,
363            subscription: None,
364            match_rule: String::new(),
365        };
366
367        if !sandboxed() {
368            let n = NEXT_ITEM.fetch_add(1, Ordering::Relaxed);
369            let name = format!("org.kde.StatusNotifierItem-{}-{n}", std::process::id());
370            match conn.request_name(&name, NAME_FLAG_DO_NOT_QUEUE)? {
371                NAME_REPLY_PRIMARY_OWNER | NAME_REPLY_ALREADY_OWNER => {
372                    this.service = name;
373                    this.owns_name = true;
374                }
375                code => {
376                    return Err(Error::Protocol(format!(
377                        "could not own {name} (RequestName answered {code})"
378                    )));
379                }
380            }
381        }
382
383        // Subscribe before looking for the watcher, so one that starts in between is not
384        // missed.
385        let rule = format!(
386            "type='signal',sender='{BUS_NAME}',interface='{BUS_INTERFACE}',\
387             member='NameOwnerChanged',arg0='{WATCHER_NAME}'"
388        );
389        conn.add_match(&rule)?;
390        this.match_rule = rule;
391        let service = this.service.clone();
392        this.subscription = Some(
393            conn.on_signal(
394                SignalFilter::new()
395                    .sender(BUS_NAME)
396                    .interface(BUS_INTERFACE)
397                    .member("NameOwnerChanged"),
398                move |conn, msg| watcher_changed(conn, msg, &service),
399            ),
400        );
401        if watcher_available(conn) {
402            conn.call(
403                WATCHER_NAME,
404                WATCHER_PATH,
405                WATCHER_NAME,
406                "RegisterStatusNotifierItem",
407                &[Value::str(&this.service)],
408            )?;
409        }
410        Ok(this)
411    }
412
413    /// The bus name the item registered under: its own well-known name, or the connection's
414    /// unique name inside a sandbox.
415    pub fn service(&self) -> &str {
416        &self.service
417    }
418
419    fn emit(&self, member: &str, args: &[Value]) -> Result<(), Error> {
420        self.conn
421            .emit_signal(ITEM_PATH, ITEM_INTERFACE, member, args)
422    }
423
424    /// Replaces the menu and tells hosts to fetch it again.
425    pub fn set_menu(&self, menu: Vec<MenuEntry>) -> Result<(), Error> {
426        let revision = {
427            let mut state = lock(&self.core.state);
428            state.menu = menu;
429            state.revision = state.revision.wrapping_add(1);
430            state.revision
431        };
432        self.conn.emit_signal(
433            MENU_PATH,
434            MENU_INTERFACE,
435            "LayoutUpdated",
436            &[Value::U32(revision), Value::I32(0)],
437        )
438    }
439
440    /// Replaces the icon (theme name and pixmaps).
441    pub fn set_icon(&self, icon_name: &str, pixmaps: Vec<Pixmap>) -> Result<(), Error> {
442        {
443            let mut state = lock(&self.core.state);
444            state.item.icon_name = icon_name.to_owned();
445            state.item.icon_pixmaps = pixmaps;
446        }
447        self.emit("NewIcon", &[])
448    }
449
450    /// Replaces the title.
451    pub fn set_title(&self, title: &str) -> Result<(), Error> {
452        lock(&self.core.state).item.title = title.to_owned();
453        self.emit("NewTitle", &[])
454    }
455
456    /// Replaces the tooltip text.
457    pub fn set_tooltip(&self, tooltip: &str) -> Result<(), Error> {
458        lock(&self.core.state).item.tooltip = tooltip.to_owned();
459        self.emit("NewToolTip", &[])
460    }
461
462    /// Changes the status.
463    pub fn set_status(&self, status: Status) -> Result<(), Error> {
464        lock(&self.core.state).item.status = status;
465        self.emit("NewStatus", &[Value::str(status.as_str())])
466    }
467}
468
469impl Drop for StatusItem {
470    fn drop(&mut self) {
471        // Nothing here waits for the bus: a drop may run on the reader thread.
472        self.conn.unexport(ITEM_PATH);
473        self.conn.unexport(MENU_PATH);
474        if let Some(id) = self.subscription.take() {
475            self.conn.remove_signal_handler(id);
476        }
477        if !self.match_rule.is_empty() {
478            let _ = self.conn.remove_match(&self.match_rule);
479        }
480        if self.owns_name {
481            let _ = self.conn.release_name(&self.service);
482        }
483    }
484}
485
486fn watcher_changed(conn: &Connection, msg: &Message, service: &str) {
487    if let [Value::Str(name), _, Value::Str(new_owner)] = msg.body.as_slice()
488        && name == WATCHER_NAME
489        && !new_owner.is_empty()
490    {
491        // The reader thread cannot wait for a reply; registration needs none.
492        let _ = conn.call_no_reply(
493            WATCHER_NAME,
494            WATCHER_PATH,
495            WATCHER_NAME,
496            "RegisterStatusNotifierItem",
497            &[Value::str(service)],
498        );
499    }
500}
501
502// ---------------------------------------------------------------------------
503// org.kde.StatusNotifierItem
504// ---------------------------------------------------------------------------
505
506fn item_property(item: &Item, name: &str) -> Option<Value> {
507    let empty_pixmaps = || pixmaps_value(&[]);
508    Some(match name {
509        "Category" => Value::str(item.category.as_str()),
510        "Id" => Value::str(&item.id),
511        "Title" => Value::str(&item.title),
512        "Status" => Value::str(item.status.as_str()),
513        "WindowId" => Value::I32(0),
514        "IconName" => Value::str(&item.icon_name),
515        "IconThemePath" => Value::str(&item.icon_theme_path),
516        "IconPixmap" => pixmaps_value(&item.icon_pixmaps),
517        "OverlayIconName" | "AttentionIconName" | "AttentionMovieName" => Value::str(""),
518        "OverlayIconPixmap" | "AttentionIconPixmap" => empty_pixmaps(),
519        "ToolTip" => Value::Struct(vec![
520            Value::str(""),
521            empty_pixmaps(),
522            Value::str(if item.tooltip.is_empty() {
523                &item.title
524            } else {
525                &item.tooltip
526            }),
527            Value::str(""),
528        ]),
529        "ItemIsMenu" => Value::Bool(item.item_is_menu),
530        "Menu" => Value::path(MENU_PATH),
531        _ => return None,
532    })
533}
534
535const ITEM_PROPERTIES: &[&str] = &[
536    "Category",
537    "Id",
538    "Title",
539    "Status",
540    "WindowId",
541    "IconName",
542    "IconThemePath",
543    "IconPixmap",
544    "OverlayIconName",
545    "OverlayIconPixmap",
546    "AttentionIconName",
547    "AttentionIconPixmap",
548    "AttentionMovieName",
549    "ToolTip",
550    "ItemIsMenu",
551    "Menu",
552];
553
554const ITEM_XML: &str = r#" <interface name="org.kde.StatusNotifierItem">
555  <property name="Category" type="s" access="read"/>
556  <property name="Id" type="s" access="read"/>
557  <property name="Title" type="s" access="read"/>
558  <property name="Status" type="s" access="read"/>
559  <property name="WindowId" type="i" access="read"/>
560  <property name="IconName" type="s" access="read"/>
561  <property name="IconThemePath" type="s" access="read"/>
562  <property name="IconPixmap" type="a(iiay)" access="read"/>
563  <property name="OverlayIconName" type="s" access="read"/>
564  <property name="OverlayIconPixmap" type="a(iiay)" access="read"/>
565  <property name="AttentionIconName" type="s" access="read"/>
566  <property name="AttentionIconPixmap" type="a(iiay)" access="read"/>
567  <property name="AttentionMovieName" type="s" access="read"/>
568  <property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
569  <property name="ItemIsMenu" type="b" access="read"/>
570  <property name="Menu" type="o" access="read"/>
571  <method name="ContextMenu"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
572  <method name="Activate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
573  <method name="SecondaryActivate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
574  <method name="Scroll"><arg name="delta" type="i" direction="in"/><arg name="orientation" type="s" direction="in"/></method>
575  <signal name="NewTitle"/>
576  <signal name="NewIcon"/>
577  <signal name="NewAttentionIcon"/>
578  <signal name="NewOverlayIcon"/>
579  <signal name="NewToolTip"/>
580  <signal name="NewStatus"><arg name="status" type="s"/></signal>
581 </interface>
582 <interface name="org.freedesktop.DBus.Properties">
583  <method name="Get"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
584  <method name="GetAll"><arg type="s" direction="in"/><arg type="a{sv}" direction="out"/></method>
585 </interface>
586"#;
587
588/// The two `i` arguments of `Activate`-style methods.
589fn point(args: &[Value]) -> Result<(i32, i32), MethodError> {
590    match args {
591        [Value::I32(x), Value::I32(y)] => Ok((*x, *y)),
592        _ => Err(MethodError::invalid_args("expected (ii)")),
593    }
594}
595
596fn string_arg(args: &[Value], at: usize) -> Result<&str, MethodError> {
597    match args.get(at) {
598        Some(Value::Str(s)) => Ok(s),
599        _ => Err(MethodError::invalid_args(format!(
600            "argument {at} must be a string"
601        ))),
602    }
603}
604
605/// Answers `Properties.Get`/`GetAll`/`Set` for one interface's read-only properties.
606fn properties(
607    call: &MethodCall,
608    interface: &str,
609    names: &[&str],
610    get: impl Fn(&str) -> Option<Value>,
611) -> Result<Vec<Value>, MethodError> {
612    match call.member.as_str() {
613        "Get" => {
614            let (iface, name) = (string_arg(&call.args, 0)?, string_arg(&call.args, 1)?);
615            match get(name) {
616                Some(v) if iface == interface || iface.is_empty() => Ok(vec![Value::variant(v)]),
617                _ => Err(MethodError::unknown_property(name)),
618            }
619        }
620        "GetAll" => {
621            let iface = string_arg(&call.args, 0)?;
622            let all = if iface == interface || iface.is_empty() {
623                names
624                    .iter()
625                    .filter_map(|n| get(n).map(|v| (*n, v)))
626                    .collect()
627            } else {
628                Vec::new()
629            };
630            Ok(vec![Value::props(all)])
631        }
632        "Set" => Err(MethodError::new(
633            "org.freedesktop.DBus.Error.PropertyReadOnly",
634            "properties are read-only",
635        )),
636        _ => Err(MethodError::unknown_method(call)),
637    }
638}
639
640fn item_call(core: &Core, call: &MethodCall) -> Result<Vec<Value>, MethodError> {
641    match call.interface.as_deref() {
642        Some(PROPERTIES_INTERFACE) => {
643            let item = lock(&core.state).item.clone();
644            return properties(call, ITEM_INTERFACE, ITEM_PROPERTIES, |n| {
645                item_property(&item, n)
646            });
647        }
648        Some(super::INTROSPECTABLE_INTERFACE) | None if call.member == "Introspect" => {
649            return Ok(vec![Value::Str(introspection_xml(ITEM_XML, &[]))]);
650        }
651        Some(ITEM_INTERFACE) | None => {}
652        Some(_) => return Err(MethodError::unknown_method(call)),
653    }
654    let event = match call.member.as_str() {
655        "Activate" => {
656            let (x, y) = point(&call.args)?;
657            Event::Activate { x, y }
658        }
659        "SecondaryActivate" => {
660            let (x, y) = point(&call.args)?;
661            Event::SecondaryActivate { x, y }
662        }
663        "ContextMenu" => {
664            let (x, y) = point(&call.args)?;
665            Event::ContextMenu { x, y }
666        }
667        "Scroll" => match call.args.as_slice() {
668            [Value::I32(delta), Value::Str(orientation)] => Event::Scroll {
669                delta: *delta,
670                horizontal: orientation.eq_ignore_ascii_case("horizontal"),
671            },
672            _ => return Err(MethodError::invalid_args("expected (is)")),
673        },
674        // Newer hosts hand over an activation token before Activate; nothing to do with it.
675        "ProvideXdgActivationToken" => return Ok(Vec::new()),
676        _ => return Err(MethodError::unknown_method(call)),
677    };
678    core.deliver(event);
679    Ok(Vec::new())
680}
681
682// ---------------------------------------------------------------------------
683// com.canonical.dbusmenu
684// ---------------------------------------------------------------------------
685
686const MENU_XML: &str = r#" <interface name="com.canonical.dbusmenu">
687  <property name="Version" type="u" access="read"/>
688  <property name="TextDirection" type="s" access="read"/>
689  <property name="Status" type="s" access="read"/>
690  <property name="IconThemePath" type="as" access="read"/>
691  <method name="GetLayout"><arg type="i" name="parentId" direction="in"/><arg type="i" name="recursionDepth" direction="in"/><arg type="as" name="propertyNames" direction="in"/><arg type="u" name="revision" direction="out"/><arg type="(ia{sv}av)" name="layout" direction="out"/></method>
692  <method name="GetGroupProperties"><arg type="ai" name="ids" direction="in"/><arg type="as" name="propertyNames" direction="in"/><arg type="a(ia{sv})" name="properties" direction="out"/></method>
693  <method name="GetProperty"><arg type="i" name="id" direction="in"/><arg type="s" name="name" direction="in"/><arg type="v" name="value" direction="out"/></method>
694  <method name="Event"><arg type="i" name="id" direction="in"/><arg type="s" name="eventId" direction="in"/><arg type="v" name="data" direction="in"/><arg type="u" name="timestamp" direction="in"/></method>
695  <method name="EventGroup"><arg type="a(isvu)" name="events" direction="in"/><arg type="ai" name="idErrors" direction="out"/></method>
696  <method name="AboutToShow"><arg type="i" name="id" direction="in"/><arg type="b" name="needUpdate" direction="out"/></method>
697  <method name="AboutToShowGroup"><arg type="ai" name="ids" direction="in"/><arg type="ai" name="updatesNeeded" direction="out"/><arg type="ai" name="idErrors" direction="out"/></method>
698  <signal name="ItemsPropertiesUpdated"><arg type="a(ia{sv})" name="updatedProps"/><arg type="a(ias)" name="removedProps"/></signal>
699  <signal name="LayoutUpdated"><arg type="u" name="revision"/><arg type="i" name="parent"/></signal>
700  <signal name="ItemActivationRequested"><arg type="i" name="id"/><arg type="u" name="timestamp"/></signal>
701 </interface>
702 <interface name="org.freedesktop.DBus.Properties">
703  <method name="Get"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
704  <method name="GetAll"><arg type="s" direction="in"/><arg type="a{sv}" direction="out"/></method>
705 </interface>
706"#;
707
708const MENU_PROPERTIES: &[&str] = &["Version", "TextDirection", "Status", "IconThemePath"];
709
710fn menu_property(name: &str) -> Option<Value> {
711    Some(match name {
712        "Version" => Value::U32(3),
713        "TextDirection" => Value::str("ltr"),
714        "Status" => Value::str("normal"),
715        "IconThemePath" => Value::strings::<&str>(&[]),
716        _ => return None,
717    })
718}
719
720fn find(entries: &[MenuEntry], id: i32) -> Option<&MenuEntry> {
721    entries.iter().find_map(|e| {
722        if e.id == id {
723            Some(e)
724        } else {
725            find(&e.children, id)
726        }
727    })
728}
729
730fn all_entries(entries: &[MenuEntry], out: &mut Vec<(i32, Vec<(&'static str, Value)>)>) {
731    for e in entries {
732        out.push((e.id, entry_props(e)));
733        all_entries(&e.children, out);
734    }
735}
736
737/// dbusmenu treats `_` as the mnemonic marker; a literal one is doubled.
738fn escape_label(label: &str) -> String {
739    label.replace('_', "__")
740}
741
742/// An entry's properties, all of them; the caller filters by requested names.
743fn entry_props(e: &MenuEntry) -> Vec<(&'static str, Value)> {
744    let mut props = Vec::new();
745    if e.separator {
746        props.push(("type", Value::str("separator")));
747    } else {
748        props.push(("label", Value::str(escape_label(&e.label))));
749        props.push(("enabled", Value::Bool(e.enabled)));
750    }
751    props.push(("visible", Value::Bool(e.visible)));
752    if e.check != Check::None && !e.separator {
753        props.push(("toggle-type", Value::str("checkmark")));
754        props.push(("toggle-state", Value::I32(i32::from(e.check == Check::On))));
755    }
756    if !e.children.is_empty() {
757        props.push(("children-display", Value::str("submenu")));
758    }
759    props
760}
761
762fn root_props() -> Vec<(&'static str, Value)> {
763    vec![("children-display", Value::str("submenu"))]
764}
765
766fn filtered(props: Vec<(&'static str, Value)>, names: &[String]) -> Value {
767    Value::props(
768        props
769            .into_iter()
770            .filter(|(k, _)| names.is_empty() || names.iter().any(|n| n == k)),
771    )
772}
773
774fn layout(
775    id: i32,
776    props: Vec<(&'static str, Value)>,
777    children: &[MenuEntry],
778    depth: i32,
779    names: &[String],
780) -> Value {
781    let kids = if depth == 0 {
782        Vec::new()
783    } else {
784        let next = if depth < 0 { -1 } else { depth - 1 };
785        children
786            .iter()
787            .map(|c| Value::variant(layout(c.id, entry_props(c), &c.children, next, names)))
788            .collect()
789    };
790    Value::Struct(vec![
791        Value::I32(id),
792        filtered(props, names),
793        Value::array("v", kids),
794    ])
795}
796
797fn string_list(v: Option<&Value>) -> Vec<String> {
798    v.and_then(Value::as_array)
799        .unwrap_or_default()
800        .iter()
801        .filter_map(|s| s.as_str().map(str::to_owned))
802        .collect()
803}
804
805fn int_list(v: Option<&Value>) -> Vec<i32> {
806    v.and_then(Value::as_array)
807        .unwrap_or_default()
808        .iter()
809        .filter_map(|n| match n {
810            Value::I32(n) => Some(*n),
811            _ => None,
812        })
813        .collect()
814}
815
816/// Handles one `Event`; `false` when the id is unknown.
817fn menu_event(core: &Core, id: i32, event_id: &str) -> bool {
818    let clickable = {
819        let state = lock(&core.state);
820        if id == 0 {
821            Some(false)
822        } else {
823            find(&state.menu, id).map(|e| e.enabled && !e.separator)
824        }
825    };
826    match clickable {
827        None => false,
828        Some(clickable) => {
829            if clickable && event_id == "clicked" {
830                core.deliver(Event::MenuItem { id });
831            }
832            true
833        }
834    }
835}
836
837fn menu_call(core: &Core, call: &MethodCall) -> Result<Vec<Value>, MethodError> {
838    match call.interface.as_deref() {
839        Some(PROPERTIES_INTERFACE) => {
840            return properties(call, MENU_INTERFACE, MENU_PROPERTIES, menu_property);
841        }
842        Some(super::INTROSPECTABLE_INTERFACE) | None if call.member == "Introspect" => {
843            return Ok(vec![Value::Str(introspection_xml(MENU_XML, &[]))]);
844        }
845        Some(MENU_INTERFACE) | None => {}
846        Some(_) => return Err(MethodError::unknown_method(call)),
847    }
848    let args = call.args.as_slice();
849    match call.member.as_str() {
850        "GetLayout" => {
851            let [Value::I32(parent), Value::I32(depth), names] = args else {
852                return Err(MethodError::invalid_args("expected (iias)"));
853            };
854            let names = string_list(Some(names));
855            let state = lock(&core.state);
856            let node = if *parent == 0 {
857                layout(0, root_props(), &state.menu, *depth, &names)
858            } else {
859                let entry = find(&state.menu, *parent)
860                    .ok_or_else(|| MethodError::invalid_args(format!("no menu entry {parent}")))?;
861                layout(
862                    entry.id,
863                    entry_props(entry),
864                    &entry.children,
865                    *depth,
866                    &names,
867                )
868            };
869            Ok(vec![Value::U32(state.revision), node])
870        }
871        "GetGroupProperties" => {
872            let ids = int_list(args.first());
873            let names = string_list(args.get(1));
874            let state = lock(&core.state);
875            let mut rows = Vec::new();
876            if ids.is_empty() {
877                all_entries(&state.menu, &mut rows);
878            } else {
879                for id in ids {
880                    if id == 0 {
881                        rows.push((0, root_props()));
882                    } else if let Some(e) = find(&state.menu, id) {
883                        rows.push((id, entry_props(e)));
884                    }
885                }
886            }
887            let rows = rows
888                .into_iter()
889                .map(|(id, props)| Value::Struct(vec![Value::I32(id), filtered(props, &names)]))
890                .collect();
891            Ok(vec![Value::array("(ia{sv})", rows)])
892        }
893        "GetProperty" => {
894            let [Value::I32(id), Value::Str(name)] = args else {
895                return Err(MethodError::invalid_args("expected (is)"));
896            };
897            let state = lock(&core.state);
898            let props = if *id == 0 {
899                root_props()
900            } else {
901                find(&state.menu, *id)
902                    .map(entry_props)
903                    .ok_or_else(|| MethodError::invalid_args(format!("no menu entry {id}")))?
904            };
905            props
906                .into_iter()
907                .find(|(k, _)| k == name)
908                .map(|(_, v)| vec![Value::variant(v)])
909                .ok_or_else(|| MethodError::unknown_property(name))
910        }
911        "Event" => {
912            let [Value::I32(id), Value::Str(event_id), ..] = args else {
913                return Err(MethodError::invalid_args("expected (isvu)"));
914            };
915            if menu_event(core, *id, event_id) {
916                Ok(Vec::new())
917            } else {
918                Err(MethodError::invalid_args(format!("no menu entry {id}")))
919            }
920        }
921        "EventGroup" => {
922            let events = args.first().and_then(Value::as_array).unwrap_or_default();
923            let mut errors = Vec::new();
924            for event in events {
925                if let Some([Value::I32(id), Value::Str(event_id), ..]) = event.as_struct()
926                    && !menu_event(core, *id, event_id)
927                {
928                    errors.push(Value::I32(*id));
929                }
930            }
931            Ok(vec![Value::array("i", errors)])
932        }
933        "AboutToShow" => Ok(vec![Value::Bool(false)]),
934        "AboutToShowGroup" => {
935            let state = lock(&core.state);
936            let errors = int_list(args.first())
937                .into_iter()
938                .filter(|id| *id != 0 && find(&state.menu, *id).is_none())
939                .map(Value::I32)
940                .collect();
941            Ok(vec![
942                Value::array("i", Vec::new()),
943                Value::array("i", errors),
944            ])
945        }
946        _ => Err(MethodError::unknown_method(call)),
947    }
948}
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953
954    #[test]
955    fn pixmaps_go_out_big_endian_argb() {
956        let px = Pixmap::from_rgba(1, 1, &[0x10, 0x20, 0x30, 0xff]).expect("pixmap");
957        assert_eq!(px.argb, vec![0xff10_2030]);
958        let v = px.to_value().expect("value");
959        assert_eq!(
960            v,
961            Value::Struct(vec![
962                Value::I32(1),
963                Value::I32(1),
964                Value::bytes(&[0xff, 0x10, 0x20, 0x30])
965            ])
966        );
967        assert_eq!(pixmaps_value(&[px]).signature(), "a(iiay)");
968        assert!(Pixmap::from_rgba(2, 2, &[0; 4]).is_none());
969        let bad = Pixmap {
970            width: 2,
971            height: 2,
972            argb: vec![0],
973        };
974        assert!(bad.to_value().is_none());
975    }
976
977    #[test]
978    fn tooltip_and_properties_have_spec_signatures() {
979        let item = Item {
980            title: "T".into(),
981            ..Item::default()
982        };
983        for name in ITEM_PROPERTIES {
984            assert!(item_property(&item, name).is_some(), "{name}");
985        }
986        let tip = item_property(&item, "ToolTip").expect("tooltip");
987        assert_eq!(tip.signature(), "(sa(iiay)ss)");
988        assert_eq!(tip.as_struct().map(|f| f[2].clone()), Some(Value::str("T")));
989        assert_eq!(item_property(&item, "Menu"), Some(Value::path(MENU_PATH)));
990        // Everything marshals.
991        let all: Vec<Value> = ITEM_PROPERTIES
992            .iter()
993            .filter_map(|n| item_property(&item, n))
994            .collect();
995        assert!(super::super::marshal(&all).is_ok());
996    }
997
998    #[test]
999    fn layout_respects_depth_and_names() {
1000        let menu = vec![
1001            MenuEntry::item(1, "Open_File").with_check(Check::On),
1002            MenuEntry::separator(2),
1003            MenuEntry::submenu(3, "More", vec![MenuEntry::item(4, "Deep")]),
1004        ];
1005        let full = layout(0, root_props(), &menu, -1, &[]);
1006        assert_eq!(full.signature(), "(ia{sv}av)");
1007        let kids = full.as_struct().expect("struct")[2].as_array().expect("av");
1008        assert_eq!(kids.len(), 3);
1009        let first = kids[0].as_struct().expect("child");
1010        assert_eq!(first[1].dict_get("label"), Some(&Value::str("Open__File")));
1011        assert_eq!(first[1].dict_get("toggle-state"), Some(&Value::I32(1)));
1012        let sub = kids[2].as_struct().expect("submenu");
1013        assert_eq!(sub[2].as_array().map(<[Value]>::len), Some(1));
1014
1015        let shallow = layout(0, root_props(), &menu, 1, &["label".into()]);
1016        let kids = shallow.as_struct().expect("struct")[2]
1017            .as_array()
1018            .expect("av");
1019        let sub = kids[2].as_struct().expect("submenu");
1020        assert_eq!(sub[2].as_array().map(<[Value]>::len), Some(0));
1021        assert_eq!(sub[1].as_array().map(<[Value]>::len), Some(1));
1022        assert!(super::super::marshal(&[full, shallow]).is_ok());
1023    }
1024}