Skip to main content

waft_widgets/widgets/
platform_tray_icon.rs

1//! An icon in the system's tray, present while the widget is in the tree: the tray counterpart of
2//! [`PlatformMenuBar`](super::platform_menu_bar::PlatformMenuBar), whose items its menu takes.
3//! Flutter has no tray; the widget draws on three models:
4//!
5//! - **Flutter's `PlatformMenuBar`** for its form: a widget with no look of its own that hands a
6//!   value of [`PlatformMenuItem`]s to the host on each change, and dispatches a choice to the
7//!   item's `on_selected` or intent, by ids it hands out (one id space per icon here).
8//! - **SwiftUI's `MenuBarExtra`** for its lifetime: the icon is there while the widget is in the
9//!   tree. It is added when the widget is mounted, once the host answers it, and removed when the
10//!   widget is unmounted; a rebuild updates its image, tooltip and menu.
11//! - **Electron's `Tray.setContextMenu`** for when its menu shows: on each system's own trigger.
12//!   Where the icon offers a menu the system opens by itself (macOS, Linux), the menu is handed to
13//!   the system; elsewhere (Windows) it is opened at the icon when the user asks for its menu
14//!   (`TrayIconEvent::ContextMenuRequested`). An app that wants another trigger uses the icon's
15//!   capabilities directly (`Platform::tray_icons`).
16//!
17//! The invariant: the icon lives exactly as long as the widget's state, an icon answered after
18//! the widget left the tree is dropped at once, and a choice from a menu set before a later one
19//! finds no item, as the ids only grow.
20
21use std::collections::HashMap;
22use std::fmt::{self, Debug};
23use std::rc::Rc;
24
25use waft_embedder::{IconImage, MenuEntry, MenuId, TrayIcon, TrayIconError, TrayIconEvent};
26use waft_foundation::{App, Handle, VoidCallback};
27
28use crate::WidgetsBinding;
29use crate::framework::{
30    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
31};
32use crate::widgets::basic::SizedBox;
33use crate::widgets::platform_menu_bar::{
34    PlatformMenuItemRef, same_items, select_menu_item, strip_dividers,
35};
36
37/// An icon in the system's tray, with its image, its tooltip, its menu of the same items
38/// [`PlatformMenuBar`](super::platform_menu_bar::PlatformMenuBar) takes, and what a click and a
39/// double click do. It shows nowhere where the host has no tray (`Platform::tray_icons` is
40/// `None`) or the system did not show it.
41///
42/// As far as the framework is concerned, this widget has no visual representation: it returns
43/// its `child` from its build function. Several may be in the tree at once, each its own icon.
44pub struct PlatformTrayIcon {
45    pub key: Option<KeyRef>,
46    /// The widget below this widget in the tree.
47    pub child: Option<WidgetRef>,
48    /// The icon's image; a template image takes the colour the system gives its tray, on macOS.
49    pub image: IconImage,
50    /// The text the system shows when the pointer rests on the icon.
51    pub tooltip: Option<String>,
52    /// The items of the icon's menu. Whenever they change, a new list should be provided.
53    pub menus: Vec<PlatformMenuItemRef>,
54    /// Called when the user clicks the icon, or chooses it from the keyboard.
55    pub on_activated: Option<VoidCallback>,
56    /// Called when the user double-clicks the icon, where the system reports it.
57    pub on_double_clicked: Option<VoidCallback>,
58}
59
60impl PlatformTrayIcon {
61    /// Creates a [`PlatformTrayIcon`] showing `image`.
62    pub fn new(image: IconImage) -> PlatformTrayIcon {
63        PlatformTrayIcon {
64            key: None,
65            child: None,
66            image,
67            tooltip: None,
68            menus: Vec::new(),
69            on_activated: None,
70            on_double_clicked: None,
71        }
72    }
73
74    pub fn key(mut self, key: KeyRef) -> PlatformTrayIcon {
75        self.key = Some(key);
76        self
77    }
78
79    #[cfg_attr(debug_assertions, track_caller)]
80    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> PlatformTrayIcon {
81        self.child = Some(child.into_widget());
82        self
83    }
84
85    pub fn tooltip(mut self, tooltip: impl Into<String>) -> PlatformTrayIcon {
86        self.tooltip = Some(tooltip.into());
87        self
88    }
89
90    pub fn menus(mut self, menus: Vec<PlatformMenuItemRef>) -> PlatformTrayIcon {
91        self.menus = menus;
92        self
93    }
94
95    pub fn on_activated(mut self, on_activated: VoidCallback) -> PlatformTrayIcon {
96        self.on_activated = Some(on_activated);
97        self
98    }
99
100    pub fn on_double_clicked(mut self, on_double_clicked: VoidCallback) -> PlatformTrayIcon {
101        self.on_double_clicked = Some(on_double_clicked);
102        self
103    }
104}
105
106impl Debug for PlatformTrayIcon {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.debug_struct("PlatformTrayIcon")
109            .field("tooltip", &self.tooltip)
110            .field("menus", &self.menus)
111            .finish_non_exhaustive()
112    }
113}
114
115impl StatefulWidget for PlatformTrayIcon {
116    type State = PlatformTrayIconState;
117
118    fn key(&self) -> Option<&KeyRef> {
119        self.key.as_ref()
120    }
121
122    fn create_state(&self) -> PlatformTrayIconState {
123        PlatformTrayIconState {
124            state: StateData::new(),
125            icon: None,
126            entries: Vec::new(),
127            id_map: HashMap::new(),
128            serial: 0,
129            descendants: Vec::new(),
130        }
131    }
132}
133
134pub struct PlatformTrayIconState {
135    state: StateData<PlatformTrayIcon>,
136    /// The icon, once the host has added it.
137    icon: Option<Box<dyn TrayIcon>>,
138    /// The menu as the icon was last given it, which a menu opened at the icon shows.
139    entries: Vec<MenuEntry>,
140    /// The items of that menu, by the ids handed out for them.
141    id_map: HashMap<MenuId, PlatformMenuItemRef>,
142    /// An ever increasing value used to dole out this icon's ids.
143    serial: MenuId,
144    /// The menu's items and their descendants, to tell a changed menu by.
145    descendants: Vec<PlatformMenuItemRef>,
146}
147
148impl PlatformTrayIconState {
149    /// Asks the host for the icon, which becomes this state's once it exists.
150    fn add_icon(self: Handle<Self>, app: &mut App) {
151        let platform = app.platform();
152        let Some(tray_icons) = platform.tray_icons() else {
153            return;
154        };
155        let widget = self.widget(app);
156        let adding = tray_icons.add(&widget.image, widget.tooltip.as_deref());
157        app.spawn(async move |cx| {
158            let added = adding.await;
159            cx.update(|app| self.icon_added(app, added));
160        });
161    }
162
163    /// The host answered the icon: it is shown as the widget is now, and heard. An icon the
164    /// system did not show shows nowhere, and one answered after the widget left the tree goes
165    /// again at once.
166    fn icon_added(
167        self: Handle<Self>,
168        app: &mut App,
169        added: Result<Box<dyn TrayIcon>, TrayIconError>,
170    ) {
171        let Ok(icon) = added else {
172            return;
173        };
174        if !self.mounted(app) {
175            return;
176        }
177        let widget = self.widget(app);
178        icon.set_image(&widget.image);
179        icon.set_tooltip(widget.tooltip.as_deref());
180        let id = icon.id();
181        app.get_mut(self).icon = Some(icon);
182        WidgetsBinding::instance(app).add_tray_icon_listener(
183            app,
184            id,
185            Rc::new(move |app, event| self.handle_event(app, event)),
186        );
187        self.update_menu(app);
188    }
189
190    /// Builds the menu from the widget's items, with ids of this icon's own, and hands it to the
191    /// system where the icon offers a menu the system opens by itself.
192    fn update_menu(self: Handle<Self>, app: &mut App) {
193        let menus = self.widget(app).menus.clone();
194        let delegate = WidgetsBinding::instance(app).platform_menu_delegate(app);
195        let mut serial = app.get(self).serial;
196        let mut id_map = HashMap::new();
197        let mut entries = Vec::new();
198        for item in &menus {
199            entries.extend(Rc::clone(item).to_menu_entries(&*delegate, &mut |item| {
200                serial += 1;
201                id_map.insert(serial, item);
202                serial
203            }));
204        }
205        strip_dividers(&mut entries);
206        let state = app.get_mut(self);
207        state.serial = serial;
208        state.id_map = id_map;
209        state.entries = entries;
210        let state = app.get(self);
211        if let Some(attached) = state.icon.as_ref().and_then(|icon| icon.attached_menu()) {
212            attached.set_menu(&state.entries);
213        }
214    }
215
216    /// What the host reports of the icon.
217    fn handle_event(self: Handle<Self>, app: &mut App, event: TrayIconEvent) {
218        match event {
219            TrayIconEvent::Activated { .. } => {
220                if let Some(on_activated) = self.widget(app).on_activated.clone() {
221                    on_activated(app);
222                }
223            }
224            TrayIconEvent::DoubleClicked => {
225                if let Some(on_double_clicked) = self.widget(app).on_double_clicked.clone() {
226                    on_double_clicked(app);
227                }
228            }
229            TrayIconEvent::ContextMenuRequested { .. } => self.open_menu_at_icon(app),
230            TrayIconEvent::MenuSelected(id) => self.select(app, id),
231            TrayIconEvent::SecondaryActivated { .. } | TrayIconEvent::Scrolled { .. } => {}
232        }
233    }
234
235    /// The user asked for the icon's menu: it opens at the icon where the system opens none by
236    /// itself.
237    fn open_menu_at_icon(self: Handle<Self>, app: &mut App) {
238        let state = app.get(self);
239        let Some(icon) = &state.icon else {
240            return;
241        };
242        if icon.attached_menu().is_some() || state.entries.is_empty() {
243            return;
244        }
245        let Some(at_icon) = icon.menu_at_icon() else {
246            return;
247        };
248        let shown = at_icon.show(&state.entries);
249        app.spawn(async move |cx| {
250            if let Some(id) = shown.await {
251                cx.update(|app| {
252                    if self.mounted(app) {
253                        self.select(app, id);
254                    }
255                });
256            }
257        });
258    }
259
260    /// The item `id` of the icon's menu was chosen: its callback or intent runs. An id of a menu
261    /// set before the last finds nothing.
262    fn select(self: Handle<Self>, app: &mut App, id: MenuId) {
263        let item = app.get(self).id_map.get(&id).cloned();
264        if let Some(item) = item {
265            select_menu_item(app, &item);
266        }
267    }
268}
269
270impl State for PlatformTrayIconState {
271    type Widget = PlatformTrayIcon;
272    crate::state_accessors!();
273
274    fn init_state(self: Handle<Self>, app: &mut App) {
275        let mut descendants = Vec::new();
276        for item in &self.widget(app).menus {
277            descendants.push(Rc::clone(item));
278            descendants.extend(item.descendants());
279        }
280        app.get_mut(self).descendants = descendants;
281        self.add_icon(app);
282    }
283
284    fn dispose(self: Handle<Self>, app: &mut App) {
285        if let Some(icon) = app.get_mut(self).icon.take() {
286            WidgetsBinding::instance(app).remove_tray_icon_listener(app, icon.id());
287        }
288    }
289
290    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &PlatformTrayIcon) {
291        let widget = self.widget(app);
292        let (image, tooltip) = (widget.image.clone(), widget.tooltip.clone());
293        if let Some(icon) = &app.get(self).icon {
294            if image != old_widget.image {
295                icon.set_image(&image);
296            }
297            if tooltip != old_widget.tooltip {
298                icon.set_tooltip(tooltip.as_deref());
299            }
300        }
301        let mut new_descendants = Vec::new();
302        for item in &self.widget(app).menus {
303            new_descendants.push(Rc::clone(item));
304            new_descendants.extend(item.descendants());
305        }
306        if !same_items(&new_descendants, &app.get(self).descendants) {
307            app.get_mut(self).descendants = new_descendants;
308            if app.get(self).icon.is_some() {
309                self.update_menu(app);
310            }
311        }
312    }
313
314    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
315        self.widget(app)
316            .child
317            .clone()
318            .unwrap_or_else(|| SizedBox::new().into_widget())
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use std::cell::RefCell;
325    use std::sync::Arc;
326    use std::time::Duration;
327
328    use waft_embedder::{Offset, TargetPlatform};
329    use waft_test::{MockTrayIcons, TestPlatform};
330
331    use super::*;
332    use crate::testing::WidgetTester;
333    use crate::widgets::platform_menu_bar::{
334        PlainPlatformMenuItem, PlatformMenuItemGroup, PlatformProvidedMenuItem,
335        PlatformProvidedMenuItemType,
336    };
337
338    type Heard = Rc<RefCell<Vec<&'static str>>>;
339
340    /// A tester on a Mac, whose tray is `tray`.
341    fn tester_with_tray(tray: &MockTrayIcons) -> WidgetTester {
342        WidgetTester::with_platform(
343            TestPlatform::new()
344                .on(TargetPlatform::MacOS)
345                .with_tray_icons(Rc::new(tray.clone())),
346        )
347    }
348
349    /// Pumps `widget`, and lets the icon the host answers arrive.
350    fn mount(tester: &mut WidgetTester, widget: WidgetRef) {
351        tester.pump_widget(widget);
352        tester.pump_by(Duration::ZERO);
353    }
354
355    fn image() -> IconImage {
356        IconImage {
357            width: 1,
358            height: 1,
359            rgba: Arc::from([0u8, 0, 0, 255]),
360            template: true,
361        }
362    }
363
364    fn heard(heard: &Heard, what: &'static str) -> VoidCallback {
365        let heard = Rc::clone(heard);
366        Rc::new(move |_app| heard.borrow_mut().push(what))
367    }
368
369    /// An icon whose menu is Open, a group holding Save, disabled, and the system's Copy, and
370    /// whose clicks are heard into `heard`.
371    fn icon(heard_into: &Heard, tooltip: &str) -> PlatformTrayIcon {
372        PlatformTrayIcon::new(image())
373            .tooltip(tooltip)
374            .menus(vec![
375                Rc::new(PlainPlatformMenuItem::new("Open").on_selected(heard(heard_into, "Open"))),
376                Rc::new(PlatformMenuItemGroup::new(vec![Rc::new(
377                    PlainPlatformMenuItem::new("Save"),
378                )])),
379                Rc::new(PlatformProvidedMenuItem::new(
380                    PlatformProvidedMenuItemType::Copy,
381                )),
382            ])
383            .on_activated(heard(heard_into, "activated"))
384            .on_double_clicked(heard(heard_into, "double clicked"))
385    }
386
387    /// Reports `event` of the icon `id` as the host does.
388    fn report(tester: &mut WidgetTester, id: u64, event: TrayIconEvent) {
389        tester.update(|app| {
390            let callback = app
391                .platform_callbacks()
392                .on_tray_icon_event
393                .clone()
394                .expect("the binding hears tray icon events");
395            callback(app, id, event);
396        });
397        tester.pump_by(Duration::ZERO);
398    }
399
400    fn the_menu() -> Vec<MenuEntry> {
401        vec![
402            MenuEntry::Item {
403                id: 1,
404                item: waft_embedder::MenuItem::new("Open"),
405            },
406            MenuEntry::Separator,
407            MenuEntry::Item {
408                id: 2,
409                item: waft_embedder::MenuItem::new("Save").enabled(false),
410            },
411            MenuEntry::Separator,
412            MenuEntry::Provided {
413                id: 3,
414                item: waft_embedder::ProvidedItem::Copy,
415                enabled: true,
416            },
417        ]
418    }
419
420    #[test]
421    fn where_the_system_opens_the_menu_it_is_handed_the_menu_and_reports_the_choice() {
422        let tray = MockTrayIcons::new().without_menus_at_icon();
423        let tester = &mut tester_with_tray(&tray);
424        let heard = Heard::default();
425        mount(tester, icon(&heard, "Notes").into_widget());
426
427        let [shown] = &tray.icons()[..] else {
428            panic!("one icon: {:?}", tray.icons());
429        };
430        assert_eq!(shown.tooltip.as_deref(), Some("Notes"));
431        assert_eq!(shown.attached_menu, the_menu());
432        report(tester, shown.id, TrayIconEvent::MenuSelected(1));
433        report(
434            tester,
435            shown.id,
436            TrayIconEvent::ContextMenuRequested {
437                position: Offset::ZERO,
438            },
439        );
440        assert!(
441            tray.icons()[0].menus_opened.is_empty(),
442            "the system opens the menu itself"
443        );
444        report(
445            tester,
446            shown.id,
447            TrayIconEvent::Activated {
448                position: Offset::ZERO,
449            },
450        );
451        report(tester, shown.id, TrayIconEvent::DoubleClicked);
452        assert_eq!(*heard.borrow(), ["Open", "activated", "double clicked"]);
453    }
454
455    #[test]
456    fn elsewhere_the_menu_opens_at_the_icon_when_the_user_asks_for_it() {
457        let tray = MockTrayIcons::new()
458            .without_attached_menus()
459            .answering(Some(1));
460        let tester = &mut tester_with_tray(&tray);
461        let heard = Heard::default();
462        mount(tester, icon(&heard, "Notes").into_widget());
463
464        let id = tray.icons()[0].id;
465        assert!(heard.borrow().is_empty());
466        report(
467            tester,
468            id,
469            TrayIconEvent::ContextMenuRequested {
470                position: Offset::ZERO,
471            },
472        );
473        assert_eq!(tray.icons()[0].menus_opened, [the_menu()]);
474        assert_eq!(*heard.borrow(), ["Open"], "the choice reaches its item");
475    }
476
477    #[test]
478    fn the_icon_is_there_while_the_widget_is_and_follows_its_rebuilds() {
479        let tray = MockTrayIcons::new();
480        let tester = &mut tester_with_tray(&tray);
481        let heard = Heard::default();
482        mount(tester, icon(&heard, "Notes").into_widget());
483        let id = tray.icons()[0].id;
484
485        mount(
486            tester,
487            icon(&heard, "Notes, 3 new")
488                .menus(vec![Rc::new(PlainPlatformMenuItem::new("Quit"))])
489                .into_widget(),
490        );
491        let [shown] = &tray.icons()[..] else {
492            panic!("the same icon: {:?}", tray.icons());
493        };
494        assert_eq!(shown.id, id, "a rebuild keeps the icon");
495        assert_eq!(shown.tooltip.as_deref(), Some("Notes, 3 new"));
496        let [MenuEntry::Item { item, .. }] = &shown.attached_menu[..] else {
497            panic!("the new menu: {:?}", shown.attached_menu);
498        };
499        assert_eq!(item.label, "Quit");
500
501        mount(tester, SizedBox::new().into_widget());
502        assert!(tray.icons().is_empty(), "the icon goes with the widget");
503    }
504
505    #[test]
506    fn several_icons_are_each_their_own() {
507        let tray = MockTrayIcons::new();
508        let tester = &mut tester_with_tray(&tray);
509        let (first, second) = (Heard::default(), Heard::default());
510        mount(
511            tester,
512            icon(&first, "First")
513                .child(icon(&second, "Second"))
514                .into_widget(),
515        );
516        let icons = tray.icons();
517        assert_eq!(icons.len(), 2);
518        report(tester, icons[1].id, TrayIconEvent::MenuSelected(1));
519        assert!(first.borrow().is_empty());
520        assert_eq!(*second.borrow(), ["Open"], "ids are each icon's own");
521    }
522
523    #[test]
524    fn an_icon_the_system_refuses_shows_nowhere() {
525        let tray = MockTrayIcons::new().refusing("no tray");
526        let tester = &mut tester_with_tray(&tray);
527        mount(tester, icon(&Heard::default(), "Notes").into_widget());
528        assert!(tray.icons().is_empty());
529    }
530}