Skip to main content

mitsuami_linux/
tray.rs

1//! The tray icon on Linux, for both backends: a StatusNotifierItem, the
2//! spec Plasma's system tray, waybar, swaybar and GNOME's AppIndicator
3//! extension show, with its menu as `com.canonical.dbusmenu`. GTK 4 has no
4//! tray, and KDE's `KStatusNotifierItem` needs KDE Frameworks, which the
5//! Kirigami shim doesn't link, so both backends export the item here, over
6//! GIO's D-Bus: GTK runs GLib's loop, and Qt's loop on Linux is GLib's too
7//! (its GLib event dispatcher), so the calls come in on either.
8//!
9//! The item owns `org.kde.StatusNotifierItem-<pid>-1` and registers with
10//! `org.kde.StatusNotifierWatcher`, again whenever the watcher comes back
11//! (a panel restarting). It says `ItemIsMenu`, so hosts open the menu on a
12//! click rather than calling `Activate`. Whether it shows is whether a
13//! watcher with a host is there; plain GNOME has none.
14//!
15//! Plasma's tray and GNOME's AppIndicator extension call
16//! `ProvideXdgActivationToken` before they send a menu item's click: the
17//! compositor's token for that click, which the backend gets just before
18//! the item runs, so a window the item opens or presents can take the
19//! focus on Wayland.
20
21use std::cell::RefCell;
22use std::collections::HashMap;
23use std::rc::{Rc, Weak};
24
25use gio::prelude::*;
26use glib::{Variant, VariantTy};
27use mitsuami_core::AppIcon;
28use mitsuami_core::services::{MenuCheck, MenuEntry, TrayData};
29
30const ITEM_PATH: &str = "/StatusNotifierItem";
31const MENU_PATH: &str = "/MenuBar";
32const ITEM: &str = "org.kde.StatusNotifierItem";
33const MENU: &str = "com.canonical.dbusmenu";
34const WATCHER: &str = "org.kde.StatusNotifierWatcher";
35const WATCHER_PATH: &str = "/StatusNotifierWatcher";
36
37/// Separators and submenus have no ids of their own in the core's menus:
38/// theirs are counted from here, above any item's.
39const OWN_IDS: i32 = 0x4000_0000;
40
41const XML: &str = r#"<node>
42  <interface name="org.kde.StatusNotifierItem">
43    <property name="Category" type="s" access="read"/>
44    <property name="Id" type="s" access="read"/>
45    <property name="Title" type="s" access="read"/>
46    <property name="Status" type="s" access="read"/>
47    <property name="WindowId" type="i" access="read"/>
48    <property name="IconThemePath" type="s" access="read"/>
49    <property name="IconName" type="s" access="read"/>
50    <property name="IconPixmap" type="a(iiay)" access="read"/>
51    <property name="OverlayIconName" type="s" access="read"/>
52    <property name="OverlayIconPixmap" type="a(iiay)" access="read"/>
53    <property name="AttentionIconName" type="s" access="read"/>
54    <property name="AttentionIconPixmap" type="a(iiay)" access="read"/>
55    <property name="AttentionMovieName" type="s" access="read"/>
56    <property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
57    <property name="ItemIsMenu" type="b" access="read"/>
58    <property name="Menu" type="o" access="read"/>
59    <method name="ContextMenu"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
60    <method name="Activate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
61    <method name="SecondaryActivate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
62    <method name="Scroll"><arg name="delta" type="i" direction="in"/><arg name="orientation" type="s" direction="in"/></method>
63    <method name="ProvideXdgActivationToken"><arg name="token" type="s" direction="in"/></method>
64    <signal name="NewTitle"/>
65    <signal name="NewIcon"/>
66    <signal name="NewAttentionIcon"/>
67    <signal name="NewOverlayIcon"/>
68    <signal name="NewToolTip"/>
69    <signal name="NewStatus"><arg name="status" type="s"/></signal>
70  </interface>
71  <interface name="com.canonical.dbusmenu">
72    <property name="Version" type="u" access="read"/>
73    <property name="TextDirection" type="s" access="read"/>
74    <property name="Status" type="s" access="read"/>
75    <property name="IconThemePath" type="as" access="read"/>
76    <method name="GetLayout">
77      <arg name="parentId" type="i" direction="in"/>
78      <arg name="recursionDepth" type="i" direction="in"/>
79      <arg name="propertyNames" type="as" direction="in"/>
80      <arg name="revision" type="u" direction="out"/>
81      <arg name="layout" type="(ia{sv}av)" direction="out"/>
82    </method>
83    <method name="GetGroupProperties">
84      <arg name="ids" type="ai" direction="in"/>
85      <arg name="propertyNames" type="as" direction="in"/>
86      <arg name="properties" type="a(ia{sv})" direction="out"/>
87    </method>
88    <method name="GetProperty">
89      <arg name="id" type="i" direction="in"/>
90      <arg name="name" type="s" direction="in"/>
91      <arg name="value" type="v" direction="out"/>
92    </method>
93    <method name="Event">
94      <arg name="id" type="i" direction="in"/>
95      <arg name="eventId" type="s" direction="in"/>
96      <arg name="data" type="v" direction="in"/>
97      <arg name="timestamp" type="u" direction="in"/>
98    </method>
99    <method name="EventGroup">
100      <arg name="events" type="a(isvu)" direction="in"/>
101      <arg name="idErrors" type="ai" direction="out"/>
102    </method>
103    <method name="AboutToShow">
104      <arg name="id" type="i" direction="in"/>
105      <arg name="needUpdate" type="b" direction="out"/>
106    </method>
107    <method name="AboutToShowGroup">
108      <arg name="ids" type="ai" direction="in"/>
109      <arg name="updatesNeeded" type="ai" direction="out"/>
110      <arg name="idErrors" type="ai" direction="out"/>
111    </method>
112    <signal name="ItemsPropertiesUpdated">
113      <arg name="updatedProps" type="a(ia{sv})"/>
114      <arg name="removedProps" type="a(ias)"/>
115    </signal>
116    <signal name="LayoutUpdated"><arg name="revision" type="u"/><arg name="parent" type="i"/></signal>
117    <signal name="ItemActivationRequested"><arg name="id" type="i"/><arg name="timestamp" type="u"/></signal>
118  </interface>
119</node>"#;
120
121type Activate = Rc<dyn Fn(u32)>;
122type Shown = Rc<dyn Fn(bool)>;
123type Token = Rc<dyn Fn(String)>;
124
125/// The app's tray icon: give it to the backend's services and pass
126/// `Services::set_tray` on.
127pub struct Tray {
128    state: Rc<RefCell<State>>,
129}
130
131struct State {
132    app_id: Option<String>,
133    data: Option<TrayData>,
134    menu: Menu,
135    revision: u32,
136    activate: Option<Activate>,
137    shown: Option<Shown>,
138    showing: bool,
139    exported: Option<Exported>,
140    /// Whether putting the item on the bus failed (no session bus): it's
141    /// tried again once the icon is taken away and set again, not on each
142    /// change.
143    export_failed: bool,
144    /// The icon as a pixmap, made when it changes: hosts read every
145    /// property again after each signal, a tooltip's too.
146    pixmap: Option<Variant>,
147    /// Hands the backend a host's activation token for the click that
148    /// follows.
149    on_token: Token,
150    /// The token the host gave for the next click.
151    token: Option<String>,
152}
153
154/// What's on the bus while the icon is set.
155struct Exported {
156    bus: gio::DBusConnection,
157    name: String,
158    registrations: Vec<gio::RegistrationId>,
159    owner: Option<gio::OwnerId>,
160    /// Stops following the watcher (gio names its id type twice, so it's
161    /// kept in here).
162    unwatch: Option<Box<dyn FnOnce()>>,
163    hosts: Vec<gio::SignalSubscription>,
164}
165
166impl Tray {
167    /// `on_token` gets a host's activation token for a menu click, just
168    /// before the item runs: the backend brings forward with it the window
169    /// the item presents or opens.
170    pub fn new(on_token: impl Fn(String) + 'static) -> Tray {
171        let state = State {
172            app_id: None,
173            data: None,
174            menu: Menu::default(),
175            revision: 0,
176            activate: None,
177            shown: None,
178            showing: false,
179            exported: None,
180            export_failed: false,
181            pixmap: None,
182            on_token: Rc::new(on_token),
183            token: None,
184        };
185        Tray { state: Rc::new(RefCell::new(state)) }
186    }
187
188    /// The app's id: the icon theme's name for the app's own icon, shown
189    /// when the app gives none, and the item's `Id`.
190    pub fn set_app_id(&self, id: Option<&str>) {
191        self.state.borrow_mut().app_id = id.map(str::to_owned);
192    }
193
194    /// `Services::set_tray`: exports the item the first time, sends what
195    /// changed afterwards, and takes it off the bus for `None`.
196    pub fn set(&self, tray: Option<&TrayData>, activate: Activate, shown: Shown) {
197        {
198            let mut state = self.state.borrow_mut();
199            state.activate = Some(activate);
200            state.shown = Some(shown);
201        }
202        let Some(tray) = tray else {
203            let exported = {
204                let mut state = self.state.borrow_mut();
205                state.data = None;
206                state.pixmap = None;
207                state.export_failed = false;
208                state.exported.take()
209            };
210            if let Some(exported) = exported {
211                exported.remove();
212            }
213            report(&self.state, false);
214            return;
215        };
216        let previous = self.state.borrow_mut().data.replace(tray.clone());
217        if previous.as_ref().is_none_or(|previous| previous.icon != tray.icon) {
218            self.state.borrow_mut().pixmap = tray.icon.as_ref().and_then(pixmap);
219        }
220        let menu = Menu::new(&tray.menu);
221        let menu_changed = self.state.borrow().menu != menu;
222        if menu_changed {
223            let mut state = self.state.borrow_mut();
224            state.menu = menu;
225            state.revision += 1;
226        }
227        let Some(previous) = previous.filter(|_| self.state.borrow().exported.is_some()) else {
228            if !self.state.borrow().export_failed {
229                export(&self.state);
230            }
231            return;
232        };
233        let state = self.state.borrow();
234        let Some(exported) = &state.exported else { return };
235        let emit = |path: &str, interface: &str, signal: &str, args: Option<Variant>| {
236            _ = exported.bus.emit_signal(None, path, interface, signal, args.as_ref());
237        };
238        if previous.title != tray.title {
239            emit(ITEM_PATH, ITEM, "NewTitle", None);
240        }
241        if previous.icon != tray.icon {
242            emit(ITEM_PATH, ITEM, "NewIcon", None);
243        }
244        if previous.tooltip != tray.tooltip || previous.title != tray.title {
245            emit(ITEM_PATH, ITEM, "NewToolTip", None);
246        }
247        if menu_changed {
248            emit(MENU_PATH, MENU, "LayoutUpdated", Some((state.revision, 0i32).to_variant()));
249        }
250    }
251}
252
253impl Drop for Tray {
254    fn drop(&mut self) {
255        if let Some(exported) = self.state.borrow_mut().exported.take() {
256            exported.remove();
257        }
258    }
259}
260
261/// A connection of the item's own to the session bus. Taking the item
262/// away closes it, so its unique name goes and every watcher drops the
263/// item: one registered by its unique name (below) would otherwise stay
264/// with hosts, as the app's shared connection lives as long as it does.
265fn private_bus() -> Result<gio::DBusConnection, glib::Error> {
266    let address = gio::dbus_address_get_for_bus_sync(gio::BusType::Session, None::<&gio::Cancellable>)?;
267    let bus = gio::DBusConnection::for_address_sync(
268        &address,
269        gio::DBusConnectionFlags::AUTHENTICATION_CLIENT | gio::DBusConnectionFlags::MESSAGE_BUS_CONNECTION,
270        None,
271        None::<&gio::Cancellable>,
272    )?;
273    bus.set_exit_on_close(false);
274    Ok(bus)
275}
276
277impl Exported {
278    fn remove(self) {
279        for registration in self.registrations {
280            _ = self.bus.unregister_object(registration);
281        }
282        if let Some(unwatch) = self.unwatch {
283            unwatch();
284        }
285        if let Some(owner) = self.owner {
286            gio::bus_unown_name(owner);
287        }
288        drop(self.hosts);
289        self.bus.close(None::<&gio::Cancellable>, |_| {});
290    }
291}
292
293/// Tells the app whether the icon shows, when that changes.
294fn report(state: &Rc<RefCell<State>>, showing: bool) {
295    let shown = {
296        let mut state = state.borrow_mut();
297        if state.showing == showing {
298            return;
299        }
300        state.showing = showing;
301        state.shown.clone()
302    };
303    if let Some(shown) = shown {
304        shown(showing);
305    }
306}
307
308fn export(state: &Rc<RefCell<State>>) {
309    let bus = match private_bus() {
310        Ok(bus) => bus,
311        Err(_) => {
312            state.borrow_mut().export_failed = true;
313            return report(state, false);
314        }
315    };
316    let node = gio::DBusNodeInfo::for_xml(XML).expect("the tray's D-Bus interfaces");
317    let mut registrations = Vec::new();
318    let weak = Rc::downgrade(state);
319    let item = bus
320        .register_object(ITEM_PATH, &node.lookup_interface(ITEM).expect("the item's interface"))
321        .method_call({
322            let weak = weak.clone();
323            move |_, _, _, _, method, args, invocation| {
324                if method == "ProvideXdgActivationToken" {
325                    let token = args.child_value(0).get::<String>().filter(|token| !token.is_empty());
326                    if let Some(state) = weak.upgrade() {
327                        state.borrow_mut().token = token;
328                    }
329                }
330                invocation.return_value(None)
331            }
332        })
333        .property({
334            let weak = weak.clone();
335            move |_, _, _, _, name| item_property(&weak, name)
336        })
337        .build();
338    let menu = bus
339        .register_object(MENU_PATH, &node.lookup_interface(MENU).expect("the menu's interface"))
340        .method_call({
341            let weak = weak.clone();
342            move |_, _, _, _, method, args, invocation| menu_call(&weak, method, &args, invocation)
343        })
344        .property(|_, _, _, _, name| match name {
345            "Version" => 3u32.to_variant(),
346            "TextDirection" => "ltr".to_variant(),
347            "Status" => "normal".to_variant(),
348            _ => Vec::<String>::new().to_variant(),
349        })
350        .build();
351    registrations.extend(item.ok());
352    registrations.extend(menu.ok());
353    let name = format!("{ITEM}-{}-1", std::process::id());
354    state.borrow_mut().exported = Some(Exported {
355        bus: bus.clone(),
356        name: name.clone(),
357        registrations,
358        owner: None,
359        unwatch: None,
360        hosts: Vec::new(),
361    });
362    // Registered with the watcher once the name is ours, so the watcher
363    // finds it there. The name has the pid, which isn't unique across PID
364    // namespaces sharing the bus (each Flatpak app is pid 2), and a sandbox
365    // may not let the app own it: then the item registers by the
366    // connection's unique name, as watchers allow (libayatana-appindicator
367    // does the same).
368    let owner = gio::bus_own_name_on_connection(
369        &bus,
370        &name,
371        gio::BusNameOwnerFlags::DO_NOT_QUEUE,
372        {
373            let weak = weak.clone();
374            move |bus, _| watch(&weak, &bus)
375        },
376        {
377            let weak = weak.clone();
378            move |bus, _| {
379                let Some(state) = weak.upgrade() else { return };
380                let Some(unique) = bus.unique_name() else { return };
381                let first = {
382                    let mut state = state.borrow_mut();
383                    let Some(exported) = state.exported.as_mut() else { return };
384                    exported.name = unique.to_string();
385                    exported.unwatch.is_none()
386                };
387                if first {
388                    watch(&weak, &bus);
389                }
390            }
391        },
392    );
393    if let Some(exported) = state.borrow_mut().exported.as_mut() {
394        exported.owner = Some(owner);
395    }
396}
397
398/// Follows the watcher: registers with it each time it appears, and asks
399/// whether a host shows items, again whenever one comes or goes.
400fn watch(weak: &Weak<RefCell<State>>, bus: &gio::DBusConnection) {
401    let Some(state) = weak.upgrade() else { return };
402    let appeared = {
403        let weak = weak.clone();
404        move |bus: gio::DBusConnection, _: &str, _: &str| {
405            let Some(state) = weak.upgrade() else { return };
406            let Some(name) = state.borrow().exported.as_ref().map(|e| e.name.clone()) else { return };
407            let weak = weak.clone();
408            bus.call(
409                Some(WATCHER),
410                WATCHER_PATH,
411                WATCHER,
412                "RegisterStatusNotifierItem",
413                Some(&(name,).to_variant()),
414                None,
415                gio::DBusCallFlags::NONE,
416                -1,
417                None::<&gio::Cancellable>,
418                move |registered| match registered {
419                    Ok(_) => ask_hosts(&weak),
420                    Err(_) => {
421                        if let Some(state) = weak.upgrade() {
422                            report(&state, false);
423                        }
424                    }
425                },
426            );
427        }
428    };
429    let vanished = {
430        let weak = weak.clone();
431        move |_: gio::DBusConnection, _: &str| {
432            if let Some(state) = weak.upgrade() {
433                report(&state, false);
434            }
435        }
436    };
437    let watcher = gio::bus_watch_name_on_connection(bus, WATCHER, gio::BusNameWatcherFlags::NONE, appeared, vanished);
438    let hosts = ["StatusNotifierHostRegistered", "StatusNotifierHostUnregistered"].map(|signal| {
439        let weak = weak.clone();
440        bus.subscribe_to_signal(
441            Some(WATCHER),
442            Some(WATCHER),
443            Some(signal),
444            Some(WATCHER_PATH),
445            None,
446            gio::DBusSignalFlags::NONE,
447            move |_| ask_hosts(&weak),
448        )
449    });
450    if let Some(exported) = state.borrow_mut().exported.as_mut() {
451        exported.unwatch = Some(Box::new(move || gio::bus_unwatch_name(watcher)));
452        exported.hosts.extend(hosts);
453    }
454}
455
456/// Reads the watcher's `IsStatusNotifierHostRegistered`: the icon shows
457/// while a host does.
458fn ask_hosts(weak: &Weak<RefCell<State>>) {
459    let Some(state) = weak.upgrade() else { return };
460    let Some(bus) = state.borrow().exported.as_ref().map(|e| e.bus.clone()) else { return };
461    let weak = weak.clone();
462    bus.call(
463        Some(WATCHER),
464        WATCHER_PATH,
465        "org.freedesktop.DBus.Properties",
466        "Get",
467        Some(&(WATCHER, "IsStatusNotifierHostRegistered").to_variant()),
468        Some(VariantTy::new("(v)").unwrap()),
469        gio::DBusCallFlags::NONE,
470        -1,
471        None::<&gio::Cancellable>,
472        move |reply| {
473            let Some(state) = weak.upgrade() else { return };
474            let hosts = reply.ok().and_then(|reply| reply.child_value(0).as_variant()).and_then(|v| v.get::<bool>());
475            // A watcher that doesn't say is taken at its word that it's there.
476            report(&state, state.borrow().data.is_some() && hosts.unwrap_or(true));
477        },
478    );
479}
480
481fn item_property(weak: &Weak<RefCell<State>>, name: &str) -> Variant {
482    let Some(state) = weak.upgrade() else { return "".to_variant() };
483    let state = state.borrow();
484    let data = state.data.as_ref();
485    let title = data.map(|d| d.title.clone()).unwrap_or_default();
486    let no_pixmaps =
487        || Variant::array_from_iter_with_type(VariantTy::new("(iiay)").unwrap(), std::iter::empty::<Variant>());
488    match name {
489        "Category" => "ApplicationStatus".to_variant(),
490        "Id" => state.app_id.clone().unwrap_or_else(|| title.clone()).to_variant(),
491        "Title" => title.to_variant(),
492        "Status" => "Active".to_variant(),
493        "WindowId" => 0i32.to_variant(),
494        "IconName" => match data.and_then(|d| d.icon.as_ref()) {
495            Some(icon) => icon.name().unwrap_or_default().to_variant(),
496            // The app's own icon, which its theme has under its id.
497            None => state.app_id.clone().unwrap_or_default().to_variant(),
498        },
499        "IconPixmap" => match state.pixmap.clone() {
500            Some(pixmap) => Variant::array_from_iter_with_type(VariantTy::new("(iiay)").unwrap(), [pixmap]),
501            None => no_pixmaps(),
502        },
503        "OverlayIconPixmap" | "AttentionIconPixmap" => no_pixmaps(),
504        "ToolTip" => {
505            let tooltip = data.map(|d| d.tooltip.clone()).unwrap_or_default();
506            Variant::tuple_from_iter(["".to_variant(), no_pixmaps(), title.to_variant(), tooltip.to_variant()])
507        }
508        "ItemIsMenu" => true.to_variant(),
509        "Menu" => glib::variant::ObjectPath::try_from(MENU_PATH.to_owned()).unwrap().to_variant(),
510        _ => "".to_variant(),
511    }
512}
513
514/// An image as the spec's pixmap: width, height and ARGB32 in network byte
515/// order. Only a named icon's name is shown where it has one, as hosts
516/// take the theme's icon over a pixmap.
517fn pixmap(icon: &AppIcon) -> Option<Variant> {
518    if icon.name().is_some_and(|name| !name.is_empty()) {
519        return None;
520    }
521    let bytes = icon.read()?;
522    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes.as_ref()));
523    decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
524    let mut reader = decoder.read_info().ok()?;
525    let mut buffer = vec![0; reader.output_buffer_size()?];
526    let frame = reader.next_frame(&mut buffer).ok()?;
527    let pixels = &buffer[..frame.buffer_size()];
528    let argb: Vec<u8> = match frame.color_type {
529        png::ColorType::Rgba => pixels.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect(),
530        png::ColorType::Rgb => pixels.chunks_exact(3).flat_map(|p| [255, p[0], p[1], p[2]]).collect(),
531        png::ColorType::GrayscaleAlpha => pixels.chunks_exact(2).flat_map(|p| [p[1], p[0], p[0], p[0]]).collect(),
532        png::ColorType::Grayscale => pixels.iter().flat_map(|&g| [255, g, g, g]).collect(),
533        png::ColorType::Indexed => return None,
534    };
535    Some(Variant::tuple_from_iter([
536        (frame.width as i32).to_variant(),
537        (frame.height as i32).to_variant(),
538        Variant::array_from_fixed_array(&argb),
539    ]))
540}
541
542/// The menu as dbusmenu has it: items by id, the root's (0) and
543/// submenus' children in order.
544#[derive(Default, PartialEq)]
545struct Menu {
546    items: HashMap<i32, MenuItem>,
547}
548
549#[derive(PartialEq)]
550struct MenuItem {
551    props: Vec<(&'static str, Prop)>,
552    children: Vec<i32>,
553    /// What a click activates: the core's id, for items.
554    activates: Option<u32>,
555}
556
557#[derive(Clone, PartialEq)]
558enum Prop {
559    Str(String),
560    Bool(bool),
561    Int(i32),
562}
563
564impl Prop {
565    fn variant(&self) -> Variant {
566        match self {
567            Prop::Str(s) => s.to_variant(),
568            Prop::Bool(b) => b.to_variant(),
569            Prop::Int(i) => i.to_variant(),
570        }
571    }
572}
573
574impl Menu {
575    fn new(entries: &[MenuEntry]) -> Menu {
576        let mut menu = Menu::default();
577        let mut own = OWN_IDS;
578        let children = menu.add(entries, &mut own);
579        let root = vec![("children-display", Prop::Str("submenu".into()))];
580        menu.items.insert(0, MenuItem { props: root, children, activates: None });
581        menu
582    }
583
584    fn add(&mut self, entries: &[MenuEntry], own: &mut i32) -> Vec<i32> {
585        let mut ids = Vec::new();
586        for entry in entries {
587            let (id, item) = match entry {
588                MenuEntry::Item(item) => {
589                    let mut props = vec![
590                        // dbusmenu takes `_` for a mnemonic.
591                        ("label", Prop::Str(item.title.replace('_', "__"))),
592                        ("enabled", Prop::Bool(item.enabled)),
593                    ];
594                    match item.check {
595                        MenuCheck::None => {}
596                        MenuCheck::Check(on) => props.extend([
597                            ("toggle-type", Prop::Str("checkmark".into())),
598                            ("toggle-state", Prop::Int(on.into())),
599                        ]),
600                        MenuCheck::Radio(on) => props.extend([
601                            ("toggle-type", Prop::Str("radio".into())),
602                            ("toggle-state", Prop::Int(on.into())),
603                        ]),
604                    }
605                    (item.id as i32, MenuItem { props, children: Vec::new(), activates: Some(item.id) })
606                }
607                MenuEntry::Separator => {
608                    *own += 1;
609                    let props = vec![("type", Prop::Str("separator".into()))];
610                    (*own, MenuItem { props, children: Vec::new(), activates: None })
611                }
612                MenuEntry::Submenu(submenu) => {
613                    *own += 1;
614                    let id = *own;
615                    let children = self.add(&submenu.entries, own);
616                    let props = vec![
617                        ("label", Prop::Str(submenu.title.replace('_', "__"))),
618                        ("children-display", Prop::Str("submenu".into())),
619                    ];
620                    (id, MenuItem { props, children, activates: None })
621                }
622            };
623            self.items.insert(id, item);
624            ids.push(id);
625        }
626        ids
627    }
628
629    /// An item's properties, those named or all.
630    fn props(&self, id: i32, names: &[String]) -> Variant {
631        let dict = glib::VariantDict::new(None);
632        if let Some(item) = self.items.get(&id) {
633            for (name, value) in &item.props {
634                if names.is_empty() || names.iter().any(|n| n == name) {
635                    dict.insert_value(name, &value.variant());
636                }
637            }
638        }
639        dict.end()
640    }
641
642    /// `(ia{sv}av)`, with children down to `depth` (-1: all).
643    fn layout(&self, id: i32, depth: i32, names: &[String]) -> Variant {
644        // Any negative depth is all of it, and `i32::MIN - 1` would overflow.
645        let next = if depth < 0 { -1 } else { depth - 1 };
646        let children: Vec<Variant> = match self.items.get(&id) {
647            Some(item) if depth != 0 => {
648                item.children.iter().map(|child| Variant::from_variant(&self.layout(*child, next, names))).collect()
649            }
650            _ => Vec::new(),
651        };
652        Variant::tuple_from_iter([
653            id.to_variant(),
654            self.props(id, names),
655            Variant::array_from_iter_with_type(VariantTy::VARIANT, children),
656        ])
657    }
658}
659
660fn menu_call(weak: &Weak<RefCell<State>>, method: &str, args: &Variant, invocation: gio::DBusMethodInvocation) {
661    let Some(state) = weak.upgrade() else { return invocation.return_value(None) };
662    let reply = match method {
663        "GetLayout" => {
664            let (parent, depth, names) = args.get::<(i32, i32, Vec<String>)>().unwrap_or_default();
665            let state = state.borrow();
666            Some(Variant::tuple_from_iter([state.revision.to_variant(), state.menu.layout(parent, depth, &names)]))
667        }
668        "GetGroupProperties" => {
669            let (ids, names) = args.get::<(Vec<i32>, Vec<String>)>().unwrap_or_default();
670            let state = state.borrow();
671            let ids: Vec<i32> = if ids.is_empty() { state.menu.items.keys().copied().collect() } else { ids };
672            // Each item once, however often it's asked for: the reply is
673            // built in memory, and any client on the bus may ask.
674            let mut seen = std::collections::HashSet::new();
675            let entries = ids
676                .into_iter()
677                .filter(|id| state.menu.items.contains_key(id) && seen.insert(*id))
678                .map(|id| Variant::tuple_from_iter([id.to_variant(), state.menu.props(id, &names)]));
679            let array = Variant::array_from_iter_with_type(VariantTy::new("(ia{sv})").unwrap(), entries);
680            Some(Variant::tuple_from_iter([array]))
681        }
682        "GetProperty" => {
683            let (id, name) = args.get::<(i32, String)>().unwrap_or_default();
684            let state = state.borrow();
685            let value = state
686                .menu
687                .items
688                .get(&id)
689                .and_then(|item| item.props.iter().find(|(n, _)| *n == name))
690                .map_or_else(|| "".to_variant(), |(_, value)| value.variant());
691            Some(Variant::tuple_from_iter([Variant::from_variant(&value)]))
692        }
693        "Event" => {
694            let id = args.child_value(0).get::<i32>().unwrap_or_default();
695            let event = args.child_value(1).get::<String>().unwrap_or_default();
696            invocation.return_value(None);
697            event_on(&state, id, &event);
698            return;
699        }
700        "EventGroup" => {
701            let events = args.child_value(0);
702            let mut errors = Vec::new();
703            let mut clicked = Vec::new();
704            for event in events.iter() {
705                let id = event.child_value(0).get::<i32>().unwrap_or_default();
706                let name = event.child_value(1).get::<String>().unwrap_or_default();
707                if state.borrow().menu.items.contains_key(&id) {
708                    clicked.push((id, name));
709                } else {
710                    errors.push(id);
711                }
712            }
713            invocation.return_value(Some(&(errors,).to_variant()));
714            for (id, name) in clicked {
715                event_on(&state, id, &name);
716            }
717            return;
718        }
719        "AboutToShow" => Some((false,).to_variant()),
720        "AboutToShowGroup" => Some((Vec::<i32>::new(), Vec::<i32>::new()).to_variant()),
721        _ => None,
722    };
723    invocation.return_value(reply.as_ref());
724}
725
726/// A host reports an event on an item: a click chooses it, with the
727/// activation token the host gave for it, if any.
728fn event_on(state: &Rc<RefCell<State>>, id: i32, event: &str) {
729    if event != "clicked" {
730        return;
731    }
732    let (activates, activate, token, on_token) = {
733        let mut state = state.borrow_mut();
734        let activates = state.menu.items.get(&id).and_then(|item| item.activates);
735        (activates, state.activate.clone(), state.token.take(), state.on_token.clone())
736    };
737    let (Some(id), Some(activate)) = (activates, activate) else { return };
738    if let Some(token) = token {
739        on_token(token);
740    }
741    activate(id);
742}