Skip to main content

crabshell_services/tray/
widget.rs

1//! [`Tray`]: one button per tray item, each opening its menu in a popup.
2//! It lives here rather than in `crabshell-ui` because it needs the tray
3//! service, and it is built only from `crabshell-ui`'s widgets.
4
5use std::rc::Rc;
6
7use crabshell_reactive::{Memo, Signal};
8use crabshell_ui::{
9  Align, Button, Color, Cx, Element, Icon, IconSource, IntoProp, Menu, PopupWindow, Prop, Rect,
10  Row, Style, Widget,
11};
12
13use super::{TrayHost, TrayItem};
14use crate::ServicesExt;
15
16/// A menu's popup unless [`Tray::menu_style`] sets another: light text on
17/// dark gray.
18const MENU: Style = Style::new()
19  .background(Color::rgb(0x2b, 0x2b, 0x2b))
20  .color(Color::rgb(0xe6, 0xe6, 0xe6))
21  .radius(6.0)
22  .padding(4, 0);
23
24/// Room around each icon.
25const BUTTON: Style = Style::new().padding(2, 4).radius(4.0);
26
27/// The icons' size unless [`Tray::icon_size`] sets another.
28const ICON_SIZE: u32 = 16;
29
30/// Shown for an item that gives no icon at all.
31const NO_ICON: &str = "image-missing";
32
33type Shared<T> = Rc<dyn Fn() -> T>;
34
35/// The system tray: one icon button per tray item, in the order the items
36/// registered. A left click activates an item, or opens its menu when the
37/// item is only a menu. A right click opens the menu, a middle click is the
38/// item's secondary activation, and scrolling over an icon scrolls it.
39///
40/// A menu opens as a [`PopupWindow`] holding a [`Menu`], next to its icon.
41/// Clicking an entry tells the app and closes the menu.
42///
43/// ```
44/// use crabshell_services::Tray;
45///
46/// let tray = Tray::new().icon_size(18);
47/// ```
48#[derive(Default)]
49pub struct Tray {
50  icon_size: Option<Prop<u32>>,
51  menu_style: Option<Prop<Style>>,
52  visible: Option<Prop<bool>>,
53  geometry: Option<Signal<Rect>>,
54  mapped_geometry: Option<Signal<Rect>>,
55}
56
57impl Tray {
58  /// A tray with 16 px icons.
59  pub fn new() -> Tray {
60    Tray::default()
61  }
62
63  /// Sets the icons' size in logical pixels.
64  pub fn icon_size(mut self, size: impl IntoProp<u32>) -> Tray {
65    self.icon_size = Some(size.into_prop());
66    self
67  }
68
69  /// Sets the style of each menu's popup: its background, border, padding,
70  /// and the text's color and font. The default is light text on dark
71  /// gray.
72  pub fn menu_style(mut self, style: impl IntoProp<Style>) -> Tray {
73    self.menu_style = Some(style.into_prop());
74    self
75  }
76
77  /// Shows or hides the tray, as [`Row::visible`] does for a row.
78  pub fn visible(mut self, visible: impl IntoProp<bool>) -> Tray {
79    self.visible = Some(visible.into_prop());
80    self
81  }
82
83  /// Shares where the tray is after each layout that moves it, as
84  /// [`Row::geometry`] does for a row.
85  pub fn geometry(mut self, geometry: Signal<Rect>) -> Tray {
86    self.geometry = Some(geometry);
87    self
88  }
89
90  /// Shares where the tray is drawn, through every transform, as
91  /// [`Row::mapped_geometry`] does for a row.
92  pub fn mapped_geometry(mut self, geometry: Signal<Rect>) -> Tray {
93    self.mapped_geometry = Some(geometry);
94    self
95  }
96}
97
98impl Widget for Tray {
99  fn into_element(self: Box<Self>) -> Element {
100    let size: Shared<u32> = self
101      .icon_size
102      .map_or_else(|| Rc::new(|| ICON_SIZE), Prop::shared);
103    let style: Shared<Style> = self
104      .menu_style
105      .map_or_else(|| Rc::new(|| MENU), Prop::shared);
106    // `cx.tray()` needs a context, which a keyed child's view gets, so the
107    // tray is one such child: a row of the items.
108    let mut tray = Row::new().children_keyed(
109      || vec![()],
110      |_| (),
111      move |cx, _| {
112        let host = cx.tray();
113        let items = host.items();
114        let (size, style) = (Rc::clone(&size), Rc::clone(&style));
115        Row::new().align(Align::Center).children_keyed(
116          move || items.get(),
117          |item| item.id.clone(),
118          move |_, item| item_button(&host, item, &size, &style),
119        )
120      },
121    );
122    if let Some(visible) = self.visible {
123      tray = tray.visible(visible);
124    }
125    if let Some(geometry) = self.geometry {
126      tray = tray.geometry(geometry);
127    }
128    if let Some(geometry) = self.mapped_geometry {
129      tray = tray.mapped_geometry(geometry);
130    }
131    Box::new(tray).into_element()
132  }
133}
134
135/// The button for one item.
136fn item_button(
137  host: &TrayHost,
138  item: Memo<TrayItem>,
139  size: &Shared<u32>,
140  style: &Shared<Style>,
141) -> Button {
142  // The id is the key, so it stays for the button's life.
143  let id: Rc<str> = item.with_untracked(|item| item.id.as_str().into());
144  let (icon_size, pick) = (Rc::clone(size), Rc::clone(size));
145  let icon = Icon::new(move || {
146    // shortcut: a widget doesn't know its output's scale, so pixmaps are
147    // picked for twice the size, which a 1x output scales down well; pick
148    // for the real scale once a context knows it.
149    let pixels = pick().saturating_mul(2);
150    let source = item.with(|item| item.icon(pixels));
151    source.unwrap_or_else(|| IconSource::Name(NO_ICON.into()))
152  })
153  .size(move || icon_size());
154  let click = {
155    let (host, id, style) = (host.clone(), Rc::clone(&id), Rc::clone(style));
156    move |cx: &Cx| {
157      if item.with_untracked(|item| item.item_is_menu) {
158        open_menu(cx, &host, &id, &style);
159      } else {
160        host.activate(&id);
161      }
162    }
163  };
164  let right_click = {
165    let (host, id, style) = (host.clone(), Rc::clone(&id), Rc::clone(style));
166    move |cx: &Cx| open_menu(cx, &host, &id, &style)
167  };
168  let (middle, scroll) = (host.clone(), host.clone());
169  let middle_id = Rc::clone(&id);
170  Button::new(icon)
171    .style(BUTTON)
172    .accessible_name(move || {
173      item.with(|item| {
174        let name = if item.title.is_empty() {
175          &item.app_id
176        } else {
177          &item.title
178        };
179        name.clone()
180      })
181    })
182    .on_click(click)
183    .on_right_click(right_click)
184    .on_middle_click(move |_| middle.secondary_activate(&middle_id))
185    .on_scroll(move |_, steps| scroll.scroll(&id, steps))
186}
187
188/// Opens item `id`'s menu in a popup next to the button `cx` belongs to.
189/// The popup opens at once, so it grabs the pointer with this click's
190/// serial, and stays empty and clear until the app's layout arrives.
191fn open_menu(cx: &Cx, host: &TrayHost, id: &Rc<str>, style: &Shared<Style>) {
192  let Some(service) = host.service.clone() else {
193    return;
194  };
195  let Some(opened) = service.open_menu(id) else {
196    return;
197  };
198  let (host, id, style) = (host.clone(), Rc::clone(id), Rc::clone(style));
199  cx.open_popup(move |cx| {
200    let _following = cx.signal(Following {
201      service: Rc::clone(&service),
202      opened,
203    });
204    let menu = host.menu();
205    // The popup closes once the tray stops following this opening: the
206    // app's menu went, its first read failed, or the app left.
207    let closer = cx.clone();
208    cx.effect(move || {
209      menu.with(|_| ());
210      if !service.follows(opened) {
211        closer.close_popup();
212      }
213    });
214    let shown = {
215      let id = Rc::clone(&id);
216      move || menu.with(|menu| menu.as_ref().is_some_and(|menu| *menu.item == *id))
217    };
218    let entries = {
219      let id = Rc::clone(&id);
220      move || {
221        menu.with(|menu| {
222          let ours = menu.as_ref().filter(|menu| *menu.item == *id);
223          ours.map(|menu| menu.entries.clone()).unwrap_or_default()
224        })
225      }
226    };
227    let (activate, submenu) = (host.clone(), host);
228    // The style is the menu's, not the popup's, so submenus get it too.
229    let menu = Menu::new(entries)
230      .style(move || if shown() { style() } else { Style::new() })
231      .on_activate(move |_, entry| activate.menu_event(&id, entry))
232      .on_open_submenu(move |_, entry| submenu.open_submenu(entry));
233    PopupWindow::new().child(menu)
234  });
235}
236
237/// Kept under a menu's popup. When the popup goes, the tray stops following
238/// the app's menu, unless another opening has taken over since.
239struct Following {
240  service: Rc<super::Service>,
241  opened: u64,
242}
243
244impl Drop for Following {
245  fn drop(&mut self) {
246    self.service.close_menu_opened(self.opened);
247  }
248}