Skip to main content

egui_pop_platform/
tray.rs

1//! A tray icon (a status icon in the panel, the notification area, the
2//! menu bar) with a declared menu.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! The tray's menu is an egui-pop menu, [`MENU_TRAY`]: plugins fill it as
8//! any other (`CommandSpec::menu(MENU_TRAY, ...)`, `Ctx::menu_item`,
9//! submenus, lists), its items' titles, `when` clauses, ticks and
10//! greying come from the commands, and a pick runs the command through
11//! the host. The plugin keeps the system's menu current at each pass.
12//!
13//! Its step (ADR 0011):
14//!
15//! - `tray.activate`: the icon was clicked, `{ "button" }` (`left`,
16//!   `middle`, `double`; the right button opens the menu). By default the
17//!   main window comes to the front ([`crate::window::raise`]). Replace it
18//!   to toggle a quick panel, veto it to do nothing.
19//!
20//! [`System`] is the system's tray through tray-icon (StatusNotifierItem
21//! over D-Bus on Linux and BSD, through ksni, with no GTK; the
22//! notification area on Windows; the menu bar on macOS). [`Simulated`]
23//! records the menu and clicks as a user would, for tests and the
24//! gallery.
25//!
26//! ```
27//! use egui_pop_api::{App, Ctx, Plugin, PluginError};
28//! use egui_pop_model::commands::CommandSpec;
29//! use egui_pop_model::ids::{CommandId, PluginId};
30//! use egui_pop_platform::tray::{Entry, MENU_TRAY, Simulated, TrayPlugin};
31//!
32//! struct Sync;
33//!
34//! impl Plugin for Sync {
35//!     fn id(&self) -> PluginId { PluginId::from_static("sync") }
36//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
37//!         ctx.command(
38//!             CommandSpec::new(CommandId::from_static("sync.now"), "Sync now", "Sync")
39//!                 .menu(MENU_TRAY, "1_sync", 0),
40//!             |_| Ok(serde_json::Value::Null),
41//!         )?;
42//!         Ok(())
43//!     }
44//! }
45//!
46//! let tray = Simulated::default();
47//! let ctx = egui::Context::default();
48//! let mut app = App::builder()
49//!     .plugin(Sync)
50//!     .plugin(TrayPlugin::new("Demo").backend(tray.clone()))
51//!     .build(&ctx)
52//!     .unwrap();
53//! app.logic(&ctx);
54//! assert!(matches!(&tray.menu()[0], Entry::Item { label, .. } if label == "Sync now"));
55//! ```
56
57use std::cell::RefCell;
58use std::collections::BTreeMap;
59use std::rc::Rc;
60use std::sync::mpsc::{Receiver, Sender, channel};
61use std::sync::{Arc, Mutex};
62
63use egui_pop_api::hooks::On;
64use egui_pop_api::services::ServiceToken;
65use egui_pop_api::steps::StepSpec;
66use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
67use egui_pop_core::lock;
68use egui_pop_core::strings;
69use egui_pop_model::commands::Origin;
70use egui_pop_model::ids::{CommandId, MenuId, PluginId, StepId};
71use egui_pop_model::menus::{Item, Shown, show_items};
72use egui_pop_model::when::{When, WhenContext};
73use serde::Serialize;
74use serde_json::{Value as Json, json};
75
76/// The plugin's id.
77pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.tray");
78/// The tray icon's menu.
79pub const MENU_TRAY: MenuId = MenuId::from_static("app.tray");
80/// The icon was clicked: `{ "button" }`.
81pub const STEP_ACTIVATE: StepId = StepId::from_static("tray.activate");
82/// The tray, as a service: what it shows, whether it is there.
83pub const TRAY: ServiceToken<Tray> = ServiceToken::new("platform.tray");
84/// How deep submenus go.
85const MAX_DEPTH: u32 = 4;
86
87/// A menu entry as the tray shows it.
88#[derive(Clone, Debug, PartialEq, Serialize)]
89#[serde(tag = "kind", rename_all = "lowercase")]
90pub enum Entry {
91    /// A command: `id` is the entry's own (a pick names it).
92    Item {
93        id: String,
94        label: String,
95        enabled: bool,
96        /// Ticked or not when it is a toggle; none otherwise.
97        checked: Option<bool>,
98    },
99    Separator,
100    Submenu {
101        label: String,
102        enabled: bool,
103        entries: Vec<Entry>,
104    },
105}
106
107/// The icon's picture: RGBA pixels, row by row.
108#[derive(Clone, Debug, PartialEq)]
109pub struct Icon {
110    pub rgba: Vec<u8>,
111    pub width: u32,
112    pub height: u32,
113}
114
115impl Icon {
116    /// A plain disc of `rgb` on transparency, `size` pixels square:
117    /// the icon when the application gives none.
118    pub fn disc(size: u32, rgb: [u8; 3]) -> Icon {
119        let mut rgba = Vec::with_capacity((size * size * 4) as usize);
120        let c = (size as f32 - 1.0) / 2.0;
121        let r = size as f32 / 2.0 - 1.0;
122        for y in 0..size {
123            for x in 0..size {
124                let d = ((x as f32 - c).powi(2) + (y as f32 - c).powi(2)).sqrt();
125                let alpha = (r - d + 0.5).clamp(0.0, 1.0);
126                rgba.extend_from_slice(&[rgb[0], rgb[1], rgb[2], (alpha * 255.0) as u8]);
127            }
128        }
129        Icon {
130            rgba,
131            width: size,
132            height: size,
133        }
134    }
135}
136
137/// What the tray shows besides its menu.
138#[derive(Clone, Debug, PartialEq)]
139pub struct Spec {
140    /// The application's id (`org.example.App`), for the system.
141    pub id: String,
142    pub title: String,
143    /// The text over the icon.
144    pub tooltip: String,
145    pub icon: Icon,
146}
147
148/// What the tray says back.
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub enum Event {
151    /// The icon was clicked with this button (`left`, `middle`,
152    /// `double`).
153    Click(String),
154    /// A menu entry was picked, by its id.
155    Pick(String),
156}
157
158/// Hands events to the plugin from any thread, waking the interface.
159#[derive(Clone, Debug)]
160pub struct Events {
161    tx: Sender<Event>,
162    waker: egui::Context,
163}
164
165impl Events {
166    pub fn send(&self, e: Event) {
167        let _ = self.tx.send(e);
168        self.waker.request_repaint();
169    }
170}
171
172/// What shows the tray icon. It lives on the interface thread (the
173/// system's tray objects are tied to it on Windows and macOS).
174pub trait Backend: 'static {
175    /// A short name: `sni`, `windows`, `macos`, `simulated`.
176    fn name(&self) -> String;
177    /// Shows the icon.
178    fn start(&mut self, spec: &Spec, events: Events) -> Result<(), String>;
179    /// Shows this menu from now on.
180    fn set_menu(&mut self, entries: &[Entry]) -> Result<(), String>;
181    /// Takes the icon away.
182    fn stop(&mut self);
183}
184
185/// The system's tray, through tray-icon (see the module).
186#[derive(Default)]
187pub struct System {
188    #[cfg(not(target_arch = "wasm32"))]
189    icon: Option<tray_icon::TrayIcon>,
190}
191
192impl std::fmt::Debug for System {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("System").finish_non_exhaustive()
195    }
196}
197
198#[cfg(not(target_arch = "wasm32"))]
199fn muda_menu(entries: &[Entry]) -> Result<tray_icon::menu::Menu, String> {
200    use tray_icon::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
201
202    fn fill(
203        entries: &[Entry],
204        append: &mut dyn FnMut(&dyn IsMenuItem) -> Result<(), String>,
205    ) -> Result<(), String> {
206        for e in entries {
207            match e {
208                Entry::Item {
209                    id,
210                    label,
211                    enabled,
212                    checked: None,
213                } => append(&MenuItem::with_id(id.as_str(), label, *enabled, None))?,
214                Entry::Item {
215                    id,
216                    label,
217                    enabled,
218                    checked: Some(on),
219                } => append(&CheckMenuItem::with_id(
220                    id.as_str(),
221                    label,
222                    *enabled,
223                    *on,
224                    None,
225                ))?,
226                Entry::Separator => append(&PredefinedMenuItem::separator())?,
227                Entry::Submenu {
228                    label,
229                    enabled,
230                    entries,
231                } => {
232                    let sub = Submenu::new(label, *enabled);
233                    fill(entries, &mut |i| sub.append(i).map_err(|e| e.to_string()))?;
234                    append(&sub)?;
235                }
236            }
237        }
238        Ok(())
239    }
240
241    let menu = Menu::new();
242    fill(entries, &mut |i| menu.append(i).map_err(|e| e.to_string()))?;
243    Ok(menu)
244}
245
246impl Backend for System {
247    fn name(&self) -> String {
248        if cfg!(windows) {
249            "windows"
250        } else if cfg!(target_os = "macos") {
251            "macos"
252        } else if cfg!(target_arch = "wasm32") {
253            "none"
254        } else {
255            "sni"
256        }
257        .into()
258    }
259
260    #[cfg(not(target_arch = "wasm32"))]
261    fn start(&mut self, spec: &Spec, events: Events) -> Result<(), String> {
262        use tray_icon::menu::MenuEvent;
263        use tray_icon::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
264
265        let icon =
266            tray_icon::Icon::from_rgba(spec.icon.rgba.clone(), spec.icon.width, spec.icon.height)
267                .map_err(|e| e.to_string())?;
268        let tray = TrayIconBuilder::new()
269            .with_id(spec.id.as_str())
270            .with_title(&spec.title)
271            .with_tooltip(&spec.tooltip)
272            .with_icon(icon)
273            .with_menu(Box::new(muda_menu(&[])?))
274            .with_menu_on_left_click(false)
275            .build()
276            .map_err(|e| e.to_string())?;
277        let clicks = events.clone();
278        TrayIconEvent::set_event_handler(Some(move |e: TrayIconEvent| {
279            let button = match e {
280                TrayIconEvent::Click {
281                    button,
282                    button_state: MouseButtonState::Up,
283                    ..
284                } => match button {
285                    MouseButton::Left => Some("left"),
286                    MouseButton::Middle => Some("middle"),
287                    MouseButton::Right => None,
288                },
289                TrayIconEvent::DoubleClick {
290                    button: MouseButton::Left,
291                    ..
292                } => Some("double"),
293                _ => None,
294            };
295            if let Some(b) = button {
296                clicks.send(Event::Click(b.into()));
297            }
298        }));
299        MenuEvent::set_event_handler(Some(move |e: MenuEvent| {
300            events.send(Event::Pick(e.id().0.clone()));
301        }));
302        self.icon = Some(tray);
303        Ok(())
304    }
305
306    #[cfg(target_arch = "wasm32")]
307    fn start(&mut self, _: &Spec, _: Events) -> Result<(), String> {
308        Err("no tray on the web".into())
309    }
310
311    #[cfg(not(target_arch = "wasm32"))]
312    fn set_menu(&mut self, entries: &[Entry]) -> Result<(), String> {
313        let menu = muda_menu(entries)?;
314        if let Some(icon) = &self.icon {
315            icon.set_menu(Some(Box::new(menu)));
316        }
317        Ok(())
318    }
319
320    #[cfg(target_arch = "wasm32")]
321    fn set_menu(&mut self, _: &[Entry]) -> Result<(), String> {
322        Ok(())
323    }
324
325    fn stop(&mut self) {
326        #[cfg(not(target_arch = "wasm32"))]
327        {
328            use tray_icon::TrayIconEvent;
329            use tray_icon::menu::MenuEvent;
330            TrayIconEvent::set_event_handler(None::<fn(TrayIconEvent)>);
331            MenuEvent::set_event_handler(None::<fn(MenuEvent)>);
332            self.icon = None;
333        }
334    }
335}
336
337#[derive(Debug, Default)]
338struct SimState {
339    started: Option<Spec>,
340    menu: Vec<Entry>,
341    events: Option<Events>,
342}
343
344/// A tray that records what it shows and clicks as a user would. For
345/// tests and the gallery.
346#[derive(Clone, Debug, Default)]
347pub struct Simulated(Arc<Mutex<SimState>>);
348
349impl Simulated {
350    /// What it shows, while started.
351    pub fn spec(&self) -> Option<Spec> {
352        lock(&self.0).started.clone()
353    }
354
355    /// The menu it shows.
356    pub fn menu(&self) -> Vec<Entry> {
357        lock(&self.0).menu.clone()
358    }
359
360    /// The user clicks the icon (`left`, `middle`, `double`).
361    pub fn click(&self, button: &str) {
362        if let Some(e) = lock(&self.0).events.clone() {
363            e.send(Event::Click(button.into()));
364        }
365    }
366
367    /// The user picks the menu entry labelled `label` (in submenus too);
368    /// false when there is none, or it is greyed.
369    pub fn pick(&self, label: &str) -> bool {
370        fn find(entries: &[Entry], label: &str) -> Option<String> {
371            entries.iter().find_map(|e| match e {
372                Entry::Item {
373                    id,
374                    label: l,
375                    enabled: true,
376                    ..
377                } if l == label => Some(id.clone()),
378                Entry::Submenu {
379                    entries,
380                    enabled: true,
381                    ..
382                } => find(entries, label),
383                _ => None,
384            })
385        }
386        let s = lock(&self.0);
387        match (find(&s.menu, label), s.events.clone()) {
388            (Some(id), Some(e)) => {
389                drop(s);
390                e.send(Event::Pick(id));
391                true
392            }
393            _ => false,
394        }
395    }
396}
397
398impl Backend for Simulated {
399    fn name(&self) -> String {
400        "simulated".into()
401    }
402
403    fn start(&mut self, spec: &Spec, events: Events) -> Result<(), String> {
404        let mut s = lock(&self.0);
405        s.started = Some(spec.clone());
406        s.events = Some(events);
407        Ok(())
408    }
409
410    fn set_menu(&mut self, entries: &[Entry]) -> Result<(), String> {
411        lock(&self.0).menu = entries.to_vec();
412        Ok(())
413    }
414
415    fn stop(&mut self) {
416        let mut s = lock(&self.0);
417        s.started = None;
418        s.events = None;
419        s.menu.clear();
420    }
421}
422
423#[derive(Debug, Default)]
424struct TrayState {
425    backend: String,
426    /// Whether the icon shows, or why not.
427    status: Option<Result<(), String>>,
428    menu: Vec<Entry>,
429}
430
431/// The tray's state, as a service.
432#[derive(Clone, Debug, Default)]
433pub struct Tray(Arc<Mutex<TrayState>>);
434
435impl Tray {
436    /// The backend's name.
437    pub fn backend(&self) -> String {
438        lock(&self.0).backend.clone()
439    }
440
441    /// Whether the icon shows, or why not; none before the first pass.
442    pub fn status(&self) -> Option<Result<(), String>> {
443        lock(&self.0).status.clone()
444    }
445
446    /// The menu it shows.
447    pub fn menu(&self) -> Vec<Entry> {
448        lock(&self.0).menu.clone()
449    }
450}
451
452/// What each entry runs, by the entry's id.
453pub type Targets = BTreeMap<String, (CommandId, Json)>;
454
455/// The tray's menu now, and what each entry runs.
456pub fn entries(app: &AppHandle) -> (Vec<Entry>, Targets) {
457    let mut targets = Targets::new();
458    let cx = app.when_context();
459    let mut next = 0;
460    let out = menu_entries(app, &MENU_TRAY, &cx, &mut targets, &mut next, 0);
461    (out, targets)
462}
463
464fn menu_entries(
465    app: &AppHandle,
466    menu: &MenuId,
467    cx: &WhenContext,
468    targets: &mut Targets,
469    next: &mut u32,
470    depth: u32,
471) -> Vec<Entry> {
472    let ctx = app.egui();
473    let mut out = Vec::new();
474    if depth > MAX_DEPTH {
475        return out;
476    }
477    let add = |targets: &mut Targets,
478               next: &mut u32,
479               label: String,
480               enabled: bool,
481               checked: Option<bool>,
482               target: (CommandId, Json)| {
483        *next += 1;
484        let id = format!("egui_pop.tray.{next}");
485        targets.insert(id.clone(), target);
486        Entry::Item {
487            id,
488            label,
489            enabled,
490            checked,
491        }
492    };
493    let mut items = Vec::new();
494    for shown in show_items(&app.menu(menu), cx) {
495        match shown {
496            Shown::Separator => items.push(None),
497            Shown::Item {
498                item,
499                enabled,
500                checked,
501                checkable,
502                ..
503            } => items.push(Some((item, enabled, checked, checkable))),
504        }
505    }
506    for i in items {
507        let Some((item, enabled, checked, checkable)) = i else {
508            out.push(Entry::Separator);
509            continue;
510        };
511        match item {
512            Item::Command { id, args, label } => {
513                let Some(spec) = app.command(&id) else {
514                    continue;
515                };
516                let applies =
517                    spec.when.is_empty() || When::parse(&spec.when).is_ok_and(|w| w.eval(cx));
518                let ticked = checkable || !spec.checked.is_empty();
519                let on = checked
520                    || (!spec.checked.is_empty()
521                        && When::parse(&spec.checked).is_ok_and(|w| w.eval(cx)));
522                let label = label.unwrap_or_else(|| app.command_menu_title(&spec));
523                let enabled = enabled && applies && !app.running(&id);
524                out.push(add(
525                    targets,
526                    next,
527                    label,
528                    enabled,
529                    ticked.then_some(on),
530                    (id, args),
531                ));
532            }
533            Item::Submenu { menu: sub, label } => {
534                let label = strings::menu_label(&ctx, sub.as_str(), &label);
535                let entries = menu_entries(app, &sub, cx, targets, next, depth + 1);
536                out.push(Entry::Submenu {
537                    label,
538                    enabled,
539                    entries,
540                });
541            }
542            Item::List { name } => {
543                for l in app.list_items(&name, cx) {
544                    let checked = l.checked.then_some(true);
545                    out.push(add(
546                        targets,
547                        next,
548                        l.label,
549                        enabled && l.enabled,
550                        checked,
551                        (l.command, l.args),
552                    ));
553                }
554            }
555        }
556    }
557    out
558}
559
560/// The backend while the plugin is connected.
561type Running = Rc<RefCell<Option<Box<dyn Backend>>>>;
562
563/// The tray icon, as a plugin (see the module).
564pub struct TrayPlugin {
565    spec: Spec,
566    backend: Option<Box<dyn Backend>>,
567    /// The backend while connected, to stop it at disconnect.
568    running: Option<Running>,
569}
570
571impl std::fmt::Debug for TrayPlugin {
572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
573        f.debug_struct("TrayPlugin")
574            .field("spec", &self.spec.title)
575            .finish_non_exhaustive()
576    }
577}
578
579impl TrayPlugin {
580    /// The system's tray, titled `title`.
581    pub fn new(title: &str) -> Self {
582        Self {
583            spec: Spec {
584                id: title.into(),
585                title: title.into(),
586                tooltip: title.into(),
587                icon: Icon::disc(32, [0x35, 0x84, 0xe4]),
588            },
589            backend: Some(Box::new(System::default())),
590            running: None,
591        }
592    }
593
594    /// The application's id for the system (`org.example.App`).
595    pub fn app_id(mut self, id: &str) -> Self {
596        self.spec.id = id.into();
597        self
598    }
599
600    pub fn tooltip(mut self, text: &str) -> Self {
601        self.spec.tooltip = text.into();
602        self
603    }
604
605    pub fn icon(mut self, icon: Icon) -> Self {
606        self.spec.icon = icon;
607        self
608    }
609
610    /// Another backend ([`Simulated`] in tests).
611    pub fn backend(mut self, backend: impl Backend) -> Self {
612        self.backend = Some(Box::new(backend));
613        self
614    }
615}
616
617impl Plugin for TrayPlugin {
618    fn id(&self) -> PluginId {
619        PLUGIN
620    }
621
622    fn title(&self) -> String {
623        "Tray icon".into()
624    }
625
626    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
627        ctx.step(
628            StepSpec::new(
629                STEP_ACTIVATE,
630                "The tray icon was clicked (`button`: left, middle, double); by default the window comes to the front.",
631            )
632            .args(json!({ "button": "left" })),
633        )?;
634        let mut backend = self
635            .backend
636            .take()
637            .unwrap_or_else(|| Box::new(System::default()));
638        let tray = Tray::default();
639        lock(&tray.0).backend = backend.name();
640        ctx.service(&TRAY, tray.clone())?;
641        let (tx, rx): (Sender<Event>, Receiver<Event>) = channel();
642        let events = Events {
643            tx,
644            waker: ctx.app().egui(),
645        };
646        let started = backend.start(&self.spec, events);
647        if let Err(e) = &started {
648            log::warn!(target: "egui_pop", "tray icon: {e}");
649        }
650        lock(&tray.0).status = Some(started.clone());
651        let shown: Arc<Mutex<(Vec<Entry>, Targets)>> = Arc::default();
652        let backend = Rc::new(RefCell::new(Some(backend)));
653        self.running = Some(backend.clone());
654        ctx.on(On::Pass, move |app, _| {
655            let (menu, targets) = entries(app);
656            {
657                let mut s = lock(&shown);
658                if started.is_ok() && s.0 != menu {
659                    if let Some(b) = backend.borrow_mut().as_mut()
660                        && let Err(e) = b.set_menu(&menu)
661                    {
662                        log::warn!(target: "egui_pop", "tray menu: {e}");
663                    }
664                    lock(&tray.0).menu = menu.clone();
665                    s.0 = menu;
666                }
667                s.1 = targets;
668            }
669            for e in rx.try_iter() {
670                match e {
671                    Event::Click(button) => {
672                        app.step(&STEP_ACTIVATE, json!({ "button": button }), |app, args| {
673                            crate::window::raise_app(app);
674                            Ok(json!({ "raised": true, "button": args["button"] }))
675                        });
676                    }
677                    Event::Pick(id) => {
678                        let target = lock(&shown).1.get(&id).cloned();
679                        if let Some((command, args)) = target {
680                            app.run_as(command, args, Origin::User);
681                        }
682                    }
683                }
684            }
685        });
686        Ok(())
687    }
688
689    fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
690        if let Some(b) = self.running.take()
691            && let Some(mut b) = b.borrow_mut().take()
692        {
693            b.stop();
694            self.backend = Some(b);
695        }
696    }
697}