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}
55
56impl Tray {
57  /// A tray with 16 px icons.
58  pub fn new() -> Tray {
59    Tray::default()
60  }
61
62  /// Sets the icons' size in logical pixels.
63  pub fn icon_size(mut self, size: impl IntoProp<u32>) -> Tray {
64    self.icon_size = Some(size.into_prop());
65    self
66  }
67
68  /// Sets the style of each menu's popup: its background, border, padding,
69  /// and the text's color and font. The default is light text on dark
70  /// gray.
71  pub fn menu_style(mut self, style: impl IntoProp<Style>) -> Tray {
72    self.menu_style = Some(style.into_prop());
73    self
74  }
75
76  /// Shows or hides the tray, as [`Row::visible`] does for a row.
77  pub fn visible(mut self, visible: impl IntoProp<bool>) -> Tray {
78    self.visible = Some(visible.into_prop());
79    self
80  }
81
82  /// Shares where the tray is after each layout that moves it, as
83  /// [`Row::geometry`] does for a row.
84  pub fn geometry(mut self, geometry: Signal<Rect>) -> Tray {
85    self.geometry = Some(geometry);
86    self
87  }
88}
89
90impl Widget for Tray {
91  fn into_element(self: Box<Self>) -> Element {
92    let size: Shared<u32> = self
93      .icon_size
94      .map_or_else(|| Rc::new(|| ICON_SIZE), Prop::shared);
95    let style: Shared<Style> = self
96      .menu_style
97      .map_or_else(|| Rc::new(|| MENU), Prop::shared);
98    // `cx.tray()` needs a context, which a keyed child's view gets, so the
99    // tray is one such child: a row of the items.
100    let mut tray = Row::new().children_keyed(
101      || vec![()],
102      |_| (),
103      move |cx, _| {
104        let host = cx.tray();
105        let items = host.items();
106        let (size, style) = (Rc::clone(&size), Rc::clone(&style));
107        Row::new().align(Align::Center).children_keyed(
108          move || items.get(),
109          |item| item.id.clone(),
110          move |_, item| item_button(&host, item, &size, &style),
111        )
112      },
113    );
114    if let Some(visible) = self.visible {
115      tray = tray.visible(visible);
116    }
117    if let Some(geometry) = self.geometry {
118      tray = tray.geometry(geometry);
119    }
120    Box::new(tray).into_element()
121  }
122}
123
124/// The button for one item.
125fn item_button(
126  host: &TrayHost,
127  item: Memo<TrayItem>,
128  size: &Shared<u32>,
129  style: &Shared<Style>,
130) -> Button {
131  // The id is the key, so it stays for the button's life.
132  let id: Rc<str> = item.with_untracked(|item| item.id.as_str().into());
133  let (icon_size, pick) = (Rc::clone(size), Rc::clone(size));
134  let icon = Icon::new(move || {
135    // shortcut: a widget doesn't know its output's scale, so pixmaps are
136    // picked for twice the size, which a 1x output scales down well; pick
137    // for the real scale once a context knows it.
138    let pixels = pick().saturating_mul(2);
139    let source = item.with(|item| item.icon(pixels));
140    source.unwrap_or_else(|| IconSource::Name(NO_ICON.into()))
141  })
142  .size(move || icon_size());
143  let click = {
144    let (host, id, style) = (host.clone(), Rc::clone(&id), Rc::clone(style));
145    move |cx: &Cx| {
146      if item.with_untracked(|item| item.item_is_menu) {
147        open_menu(cx, &host, &id, &style);
148      } else {
149        host.activate(&id);
150      }
151    }
152  };
153  let right_click = {
154    let (host, id, style) = (host.clone(), Rc::clone(&id), Rc::clone(style));
155    move |cx: &Cx| open_menu(cx, &host, &id, &style)
156  };
157  let (middle, scroll) = (host.clone(), host.clone());
158  let middle_id = Rc::clone(&id);
159  Button::new(icon)
160    .style(BUTTON)
161    .on_click(click)
162    .on_right_click(right_click)
163    .on_middle_click(move |_| middle.secondary_activate(&middle_id))
164    .on_scroll(move |_, steps| scroll.scroll(&id, steps))
165}
166
167/// Opens item `id`'s menu in a popup next to the button `cx` belongs to.
168/// The popup opens at once, so it grabs the pointer with this click's
169/// serial, and stays empty and clear until the app's layout arrives.
170fn open_menu(cx: &Cx, host: &TrayHost, id: &Rc<str>, style: &Shared<Style>) {
171  let Some(service) = host.service.clone() else {
172    return;
173  };
174  let Some(opened) = service.open_menu(id) else {
175    return;
176  };
177  let (host, id, style) = (host.clone(), Rc::clone(id), Rc::clone(style));
178  cx.open_popup(move |cx| {
179    let _following = cx.signal(Following {
180      service: Rc::clone(&service),
181      opened,
182    });
183    let menu = host.menu();
184    // The popup closes once the tray stops following this opening: the
185    // app's menu went, its first read failed, or the app left.
186    let closer = cx.clone();
187    cx.effect(move || {
188      menu.with(|_| ());
189      if !service.follows(opened) {
190        closer.close_popup();
191      }
192    });
193    let shown = {
194      let id = Rc::clone(&id);
195      move || menu.with(|menu| menu.as_ref().is_some_and(|menu| *menu.item == *id))
196    };
197    let entries = {
198      let id = Rc::clone(&id);
199      move || {
200        menu.with(|menu| {
201          let ours = menu.as_ref().filter(|menu| *menu.item == *id);
202          ours.map(|menu| menu.entries.clone()).unwrap_or_default()
203        })
204      }
205    };
206    let (activate, submenu) = (host.clone(), host);
207    // The style is the menu's, not the popup's, so submenus get it too.
208    let menu = Menu::new(entries)
209      .style(move || if shown() { style() } else { Style::new() })
210      .on_activate(move |_, entry| activate.menu_event(&id, entry))
211      .on_open_submenu(move |_, entry| submenu.open_submenu(entry));
212    PopupWindow::new().child(menu)
213  });
214}
215
216/// Kept under a menu's popup. When the popup goes, the tray stops following
217/// the app's menu, unless another opening has taken over since.
218struct Following {
219  service: Rc<super::Service>,
220  opened: u64,
221}
222
223impl Drop for Following {
224  fn drop(&mut self) {
225    self.service.close_menu_opened(self.opened);
226  }
227}