Skip to main content

crabshell_ui/
menu.rs

1//! [`Menu`]: a vertical list of buttons built from menu entries, such as a
2//! tray item's DBusMenu, with separators, checkmarks, radio buttons and
3//! submenus that open as nested popups.
4
5use std::rc::Rc;
6
7use crabshell_reactive::Memo;
8
9use crate::cx::Cx;
10use crate::popup::PopupWindow;
11use crate::prop::{IntoProp, Prop};
12use crate::style::{Color, Style};
13use crate::widgets::{
14  Align, Button, Column, Common, Element, ElementKind, Row, Spacer, Stack, Text, Widget,
15  visibility_methods,
16};
17
18/// One entry of a [`Menu`].
19#[derive(Clone, Debug, PartialEq)]
20pub struct MenuEntry {
21  /// The app's id for it, which the menu's handlers get.
22  pub id: i32,
23  /// What it says.
24  pub label: String,
25  /// Whether it is a separator line rather than something to click.
26  pub separator: bool,
27  /// Whether it can be clicked.
28  pub enabled: bool,
29  /// Whether it shows a checkmark or a radio button.
30  pub toggle: Option<MenuToggle>,
31  /// Whether that checkmark or radio button is on.
32  pub checked: bool,
33  /// Whether it opens a submenu. Some apps fill a submenu only when it
34  /// opens, so its `children` may still be empty.
35  pub submenu: bool,
36  /// Its submenu's entries.
37  pub children: Vec<MenuEntry>,
38}
39
40/// What a toggling menu entry shows.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum MenuToggle {
43  /// A checkmark, on or off on its own.
44  Checkmark,
45  /// A radio button, one of a group.
46  Radio,
47}
48
49/// Room around each entry's text.
50const ITEM: Style = Style::new().padding(4, 12);
51/// Laid over an entry under the pointer.
52const HOVER: Style = Style::new().background(Color::rgba(128, 128, 128, 64));
53/// A separator's line: 2 px of gray.
54const SEPARATOR: Style = Style::new()
55  .background(Color::rgba(128, 128, 128, 128))
56  .padding(1, 0);
57/// Laid over an entry that can't be clicked.
58const DISABLED: Style = Style::new().opacity(0.5);
59/// A checkmark or radio button that is off keeps its room.
60const HIDDEN: Style = Style::new().opacity(0.0);
61
62/// A vertical list of buttons, one per entry, as a popup menu shows them.
63///
64/// A click on an entry calls [`on_activate`](Self::on_activate) with its
65/// id, then closes the popups it is in. A click on an entry with a
66/// submenu calls [`on_open_submenu`](Self::on_open_submenu) and opens the
67/// submenu as a popup next to it, with the same styles and handlers.
68/// Disabled entries ignore clicks. Each style takes a value or a closure.
69///
70/// ```
71/// use crabshell_ui::{Menu, MenuEntry, PopupWindow};
72///
73/// let quit = MenuEntry {
74///     id: 1,
75///     label: "Quit".into(),
76///     separator: false,
77///     enabled: true,
78///     toggle: None,
79///     checked: false,
80///     submenu: false,
81///     children: Vec::new(),
82/// };
83/// let popup = PopupWindow::new().child(
84///     Menu::new(vec![quit]).on_activate(|_cx, id| println!("clicked {id}")),
85/// );
86/// ```
87pub struct Menu {
88  entries: Prop<Vec<MenuEntry>>,
89  style: Option<Prop<Style>>,
90  item_style: Option<Prop<Style>>,
91  hover_style: Option<Prop<Style>>,
92  separator_style: Option<Prop<Style>>,
93  on_activate: Option<EntryHandler>,
94  on_open_submenu: Option<EntryHandler>,
95  common: Common,
96}
97
98impl Menu {
99  /// A menu of `entries`: a list, or a closure that returns one.
100  pub fn new(entries: impl IntoProp<Vec<MenuEntry>>) -> Menu {
101    Menu {
102      entries: entries.into_prop(),
103      style: None,
104      item_style: None,
105      hover_style: None,
106      separator_style: None,
107      on_activate: None,
108      on_open_submenu: None,
109      common: Common::default(),
110    }
111  }
112
113  /// Sets the style of the menu's box: its background, border and padding.
114  pub fn style(mut self, style: impl IntoProp<Style>) -> Menu {
115    self.style = Some(style.into_prop());
116    self
117  }
118
119  /// Sets each entry's style. The default pads the text 4 px above and
120  /// below and 12 px left and right.
121  pub fn item_style(mut self, style: impl IntoProp<Style>) -> Menu {
122    self.item_style = Some(style.into_prop());
123    self
124  }
125
126  /// Sets the style laid over an entry under the pointer. The default is
127  /// a faint gray background.
128  pub fn hover_style(mut self, style: impl IntoProp<Style>) -> Menu {
129    self.hover_style = Some(style.into_prop());
130    self
131  }
132
133  /// Sets a separator's style. A separator is as tall as the style's
134  /// vertical padding twice; the default is a 2 px gray line.
135  pub fn separator_style(mut self, style: impl IntoProp<Style>) -> Menu {
136    self.separator_style = Some(style.into_prop());
137    self
138  }
139
140  /// Runs `handler` with an entry's id when that entry is clicked.
141  pub fn on_activate(mut self, handler: impl Fn(&Cx, i32) + 'static) -> Menu {
142    self.on_activate = Some(Rc::new(handler));
143    self
144  }
145
146  /// Runs `handler` with an entry's id when its submenu opens, as a tray
147  /// menu tells its app with `open_submenu`.
148  pub fn on_open_submenu(mut self, handler: impl Fn(&Cx, i32) + 'static) -> Menu {
149    self.on_open_submenu = Some(Rc::new(handler));
150    self
151  }
152
153  visibility_methods!();
154}
155
156/// What a menu and its submenus share: the styles as closures any of them
157/// can call, and the handlers.
158struct Look {
159  menu: Shared<Style>,
160  item: Shared<Style>,
161  hover: Shared<Style>,
162  separator: Shared<Style>,
163  on_activate: Option<EntryHandler>,
164  on_open_submenu: Option<EntryHandler>,
165}
166
167type Shared<T> = Rc<dyn Fn() -> T>;
168
169/// A handler that gets an entry's id.
170type EntryHandler = Rc<dyn Fn(&Cx, i32)>;
171
172/// A property as a closure that submenus can share, or `default`.
173fn shared<T: Clone + 'static>(prop: Option<Prop<T>>, default: T) -> Shared<T> {
174  prop.map_or_else(|| Rc::new(move || default.clone()), Prop::shared)
175}
176
177impl Widget for Menu {
178  fn into_element(self: Box<Self>) -> Element {
179    let look = Rc::new(Look {
180      menu: shared(self.style, Style::new()),
181      item: shared(self.item_style, ITEM),
182      hover: shared(self.hover_style, HOVER),
183      separator: shared(self.separator_style, SEPARATOR),
184      on_activate: self.on_activate,
185      on_open_submenu: self.on_open_submenu,
186    });
187    let mut element = menu(look, shared(Some(self.entries), Vec::new()));
188    element.common.visible = self.common.visible;
189    element.common.geometry = self.common.geometry;
190    element
191  }
192}
193
194/// An element that is already built, so a function can return either
195/// kind of entry.
196struct Built(Element);
197
198impl Widget for Built {
199  fn into_element(self: Box<Self>) -> Element {
200    self.0
201  }
202}
203
204/// A menu of `entries` in `look`: a column with one child per entry id.
205fn menu(look: Rc<Look>, entries: Shared<Vec<MenuEntry>>) -> Element {
206  let style = Rc::clone(&look.menu);
207  let column = Column::new().style(move || style()).children_keyed(
208    move || entries(),
209    // A separator and an entry differ in kind, so an id that changes
210    // between them gets a new child.
211    |entry: &MenuEntry| (entry.id, entry.separator),
212    move |_cx, entry| entry_view(&look, entry),
213  );
214  let mut element = Box::new(column).into_element();
215  element.name = "Menu";
216  element
217}
218
219/// One entry: a separator line, or a button with its checkmark, label and
220/// submenu arrow. Which of the two is fixed when the entry first appears.
221fn entry_view(look: &Rc<Look>, entry: Memo<MenuEntry>) -> Built {
222  if entry.with_untracked(|entry| entry.separator) {
223    let separator = Rc::clone(&look.separator);
224    let line = Stack::new().style(move || separator());
225    return Built(Box::new(Column::new().padding(3, 0).child(line)).into_element());
226  }
227  let mark = move || match entry.get().toggle {
228    Some(MenuToggle::Radio) => "●".to_owned(),
229    _ => "✓".to_owned(),
230  };
231  let shown = move || {
232    let entry = entry.get();
233    if entry.toggle.is_some() && entry.checked {
234      Style::new()
235    } else {
236      HIDDEN
237    }
238  };
239  let arrow = move || if entry.get().submenu { "▸" } else { "" }.to_owned();
240  // The mark's room fits either symbol, so every label lines up.
241  let marks = Stack::new()
242    .child(Text::new("✓").style(HIDDEN))
243    .child(Text::new("●").style(HIDDEN))
244    .child(Text::new(mark).style(shown));
245  let row = Row::new()
246    .gap(8)
247    .align(Align::Center)
248    .child(marks)
249    .child(Text::new(move || entry.get().label))
250    .child(Spacer::new())
251    .child(Text::new(arrow));
252  // A button centers its child; this row fills it instead, so labels
253  // start at the left and arrows sit at the right.
254  let mut row = Box::new(row).into_element();
255  if let ElementKind::Flex(flex) = &mut row.kind {
256    flex.grow = true;
257  }
258  let (item, hover) = (Rc::clone(&look.item), Rc::clone(&look.hover));
259  let clicked = Rc::clone(look);
260  let button = Button::new(Built(row))
261    .style(move || {
262      let style = item();
263      if entry.get().enabled {
264        style
265      } else {
266        style.merge(DISABLED)
267      }
268    })
269    .hover_style(move || {
270      if entry.get().enabled {
271        hover()
272      } else {
273        Style::new()
274      }
275    })
276    .on_click(move |cx| click(&clicked, cx, entry));
277  Built(Box::new(button).into_element())
278}
279
280/// What a click on `entry` does: opens its submenu, or activates it and
281/// closes the menu.
282fn click(look: &Rc<Look>, cx: &Cx, entry: Memo<MenuEntry>) {
283  let (id, enabled, submenu) =
284    entry.with_untracked(|entry| (entry.id, entry.enabled, entry.submenu));
285  if !enabled {
286    return;
287  }
288  if submenu {
289    if let Some(open) = &look.on_open_submenu {
290      open(cx, id);
291    }
292    let look = Rc::clone(look);
293    let children: Shared<Vec<MenuEntry>> = Rc::new(move || {
294      let children = entry.try_with(|entry| entry.children.clone());
295      children.unwrap_or_default()
296    });
297    cx.open_popup(move |_| PopupWindow::new().child(Built(menu(look, children))));
298    return;
299  }
300  if let Some(activate) = &look.on_activate {
301    activate(cx, id);
302  }
303  // A menu in a panel rather than a popup has nothing to close.
304  cx.close_popups_if_any();
305}