Skip to main content

rust_glass/widgets/
menu.rs

1//! Menus, menu buttons, combo boxes and context menus.
2
3use crate::accessibility::Role;
4use crate::animation::Tuning;
5use crate::color::Color;
6use crate::context::{Context, Cursor, Response, Sense};
7use crate::geometry::{Rect, Vec2, vec2};
8use crate::icon::Icon;
9use crate::material::{Corner, Glass};
10use crate::text::{TextStyle, Weight};
11use crate::ui::{Ui, Widget};
12use crate::widgets::popup::{popup, popup_presence, popup_progress};
13use crate::widgets::press::PressEffect;
14
15/// Row inside a menu.
16pub struct MenuItem<'a> {
17    label: &'a str,
18    icon: Option<Icon>,
19    shortcut: &'a str,
20    checked: bool,
21    destructive: bool,
22}
23
24impl<'a> MenuItem<'a> {
25    /// Creates a menu item.
26    pub fn new(label: &'a str) -> Self {
27        Self { label, icon: None, shortcut: "", checked: false, destructive: false }
28    }
29    /// Shows `icon` before the label.
30    pub fn icon(mut self, icon: Icon) -> Self {
31        self.icon = Some(icon);
32        self
33    }
34    /// Shows a keyboard shortcut at the end, such as `Ctrl N`. It is only a label.
35    pub fn shortcut(mut self, shortcut: &'a str) -> Self {
36        self.shortcut = shortcut;
37        self
38    }
39    /// Shows a check mark when `checked`.
40    pub fn checked(mut self, checked: bool) -> Self {
41        self.checked = checked;
42        self
43    }
44    /// Shows the item in red, for actions that delete something.
45    pub fn destructive(mut self) -> Self {
46        self.destructive = true;
47        self
48    }
49}
50
51impl Widget for MenuItem<'_> {
52    fn ui(self, ui: &mut Ui) -> Response {
53        let w = ui.available_width();
54        let mut r = ui.allocate_response(vec2(w, 36.0), Sense::Click);
55        ui.ctx.focusable(r.id);
56        if let Some(n) = ui.access(r.id, Role::MenuItem, r.rect) {
57            n.label(self.label);
58            if self.checked {
59                n.selected(true);
60            }
61        }
62        // Press on the menu button, slide, release on an item.
63        if r.rect.contains(ui.ctx.pointer_or(vec2(-1.0, -1.0)))
64            && ui.ctx.input.released
65            && ui.ctx.input.press_origin != ui.ctx.pointer_or(Vec2::ZERO)
66            && ui.opacity > 0.6
67            && (ui.ctx.input.press_origin - ui.ctx.pointer_or(Vec2::ZERO)).length() > 12.0
68        {
69            r.clicked = true;
70        }
71        let h = ui.ctx.animate_bool(r.id, r.hovered, Tuning::SNAP);
72        let st = TextStyle::new(ui.ctx.theme.body_size).weight(Weight::Medium);
73        let l = ui.layout_text(self.label, &st);
74        let s = ui.layout_text(self.shortcut, &TextStyle::new(ui.ctx.theme.caption_size));
75        let c = if self.destructive { Color::RED } else { ui.surface.text_color() };
76        let (fill, sec) = (ui.surface.fill_color(), ui.surface.secondary_color());
77        if r.hovered {
78            ui.ctx.cursor = Cursor::Pointer;
79        }
80        let mut p = ui.painter();
81        p.fill(r.rect, 14.0, fill.fade(h));
82        let cy = r.rect.center().y;
83        let mut x = r.rect.min.x + 12.0;
84        if let Some(i) = self.icon {
85            p.icon(vec2(x + 9.0, cy), 18.0, i, c);
86            x += 30.0;
87        }
88        p.text(vec2(x, cy - l.size.y * 0.5), &l, c);
89        let mut rx = r.rect.max.x - 12.0;
90        if self.checked {
91            p.icon(vec2(rx - 8.0, cy), 16.0, Icon::Check, c);
92            rx -= 24.0;
93        }
94        p.text(vec2(rx - s.size.x, cy - s.size.y * 0.5), &s, sec);
95        ui.focus_ring(r.id, r.rect, 14.0);
96        r
97    }
98}
99
100/// A button that opens a menu. Its glass grows into the menu, and the menu
101/// flows back into the button when it closes.
102pub struct MenuButton<'a> {
103    label: &'a str,
104    icon: Option<Icon>,
105    chevron: bool,
106    width: f32,
107    min_width: f32,
108}
109
110impl<'a> MenuButton<'a> {
111    /// Creates a menu button. Leave `label` empty for an icon only button.
112    pub fn new(label: &'a str) -> Self {
113        Self { label, icon: None, chevron: false, width: 230.0, min_width: 0.0 }
114    }
115    /// Shows `icon` before the label.
116    pub fn icon(mut self, icon: Icon) -> Self {
117        self.icon = Some(icon);
118        self
119    }
120    /// Shows an up and down chevron at the end, as on a combo box.
121    pub fn chevron(mut self) -> Self {
122        self.chevron = true;
123        self
124    }
125    /// Sets the width of the menu. The default is 230.
126    pub fn menu_width(mut self, width: f32) -> Self {
127        self.width = width;
128        self
129    }
130    /// Makes the button at least `width` points wide. Its label then starts
131    /// at the left.
132    pub fn min_width(mut self, width: f32) -> Self {
133        self.min_width = width;
134        self
135    }
136
137    /// Shows the button, and the menu items drawn by `f` while it is open.
138    /// Close the menu with [`Context::set_popup`](crate::Context::set_popup)
139    /// on the returned id when an item is clicked.
140    pub fn show(self, ui: &mut Ui, f: impl FnOnce(&mut Ui)) -> Response {
141        let st = TextStyle::new(ui.ctx.theme.body_size).weight(Weight::Semibold);
142        let l = ui.layout_text(self.label, &st);
143        let h = ui.ctx.theme.control_height;
144        let has_text = !self.label.is_empty();
145        let iw = if self.icon.is_some() { 17.0 } else { 0.0 };
146        let gap = if has_text && self.icon.is_some() { 7.0 } else { 0.0 };
147        let cw = if self.chevron { 18.0 } else { 0.0 };
148        let w = if has_text { (l.size.x + iw + gap + cw + 30.0).max(self.min_width) } else { h };
149        let r = ui.allocate_response(vec2(w, h), Sense::Click);
150        ui.ctx.focusable(r.id);
151        if r.hovered {
152            ui.ctx.cursor = Cursor::Pointer;
153        }
154        if r.clicked && !ui.ctx.popup_open(r.id) {
155            ui.ctx.set_popup(r.id, true);
156        }
157        let open = ui.ctx.popup_open(r.id);
158        let role = if self.chevron { Role::ComboBox } else { Role::Button };
159        if let Some(n) = ui.access(r.id, role, r.rect) {
160            n.label(if has_text { self.label } else { self.icon.map_or("Menu", Icon::name) }).expanded(open);
161        }
162        let t = popup_progress(ui.ctx, r.id);
163        let gel = PressEffect::update(ui.ctx, &r, 1.0);
164        let fade = 1.0 - popup_presence(t);
165        let mut s = ui.surface;
166        if ui.surface.is_glass() {
167            let c = s.fill_color();
168            ui.painter().fill(gel.rect, Corner::Capsule, c.fade(fade * (1.0 + 0.5 * gel.hover)));
169        } else {
170            let mut g = Glass::new(gel.rect, Corner::Capsule, ui.ctx.theme.regular);
171            s = ui.ctx.prepare_glass(r.id, &mut g, true).surface();
172            gel.apply(&mut g);
173            g.presence = fade;
174            ui.painter().glass(&g);
175        }
176        let c = s.text_color().fade(fade);
177        let content = l.size.x + iw + gap + cw;
178        let k = gel.scale;
179        let mut x = if self.min_width > 0.0 && has_text {
180            gel.rect.min.x + 15.0
181        } else {
182            gel.rect.center().x - content * k * 0.5
183        };
184        let cy = gel.rect.center().y;
185        let sec = s.secondary_color().fade(fade);
186        let mut p = ui.painter();
187        if let Some(i) = self.icon {
188            p.icon(vec2(x + iw * k * 0.5, cy), 17.0 * k, i, c);
189            x += (iw + gap) * k;
190        }
191        if has_text {
192            p.text_centered(Rect::from_center_size(vec2(x + l.size.x * k * 0.5, cy), l.size), &l, c, k);
193        }
194        if self.chevron {
195            p.icon(vec2(gel.rect.max.x - 18.0, cy), 15.0, Icon::ChevronsUpDown, sec);
196        }
197        ui.focus_ring(r.id, gel.rect, Corner::Capsule);
198        let anchor = gel.rect;
199        let width = self.width.max(anchor.width());
200        popup(ui.ctx, r.id, anchor, width, f);
201        r
202    }
203}
204
205/// A button that shows the selected option and opens a menu of all options.
206pub struct ComboBox<'a> {
207    selected: &'a mut usize,
208    options: &'a [&'a str],
209    width: f32,
210}
211
212impl<'a> ComboBox<'a> {
213    /// Creates a combo box that sets `selected` to the index of the chosen
214    /// option.
215    pub fn new(selected: &'a mut usize, options: &'a [&'a str]) -> Self {
216        Self { selected, options, width: 180.0 }
217    }
218    /// Sets the width of the button and its menu. The default is 180.
219    pub fn width(mut self, width: f32) -> Self {
220        self.width = width;
221        self
222    }
223
224    /// Shows the combo box. Returns `true` when the selection changed.
225    pub fn show(self, ui: &mut Ui) -> bool {
226        let now = (*self.selected).min(self.options.len().saturating_sub(1));
227        let label = self.options.get(now).copied().unwrap_or("");
228        let mut pick = None;
229        let r =
230            MenuButton::new(label).chevron().min_width(self.width).menu_width(self.width).show(ui, |ui| {
231                for (i, o) in self.options.iter().enumerate() {
232                    if ui.add(MenuItem::new(o).checked(i == now)).clicked {
233                        pick = Some(i);
234                    }
235                }
236            });
237        if let Some(i) = pick {
238            ui.ctx.set_popup(r.id, false);
239            *self.selected = i;
240            return i != now;
241        }
242        false
243    }
244}
245
246/// Menu on secondary click, forming at the pointer.
247pub fn context_menu(ctx: &mut Context, target: &Response, width: f32, f: impl FnOnce(&mut Ui)) {
248    let id = target.id.with("ctx");
249    if target.secondary_clicked {
250        let p = ctx.pointer_or(target.rect.center());
251        ctx.set(id, p);
252        ctx.set_popup(id, true);
253    }
254    let at: Vec2 = ctx.get(id);
255    popup(ctx, id, Rect::from_center_size(at, Vec2::splat(18.0)), width, f);
256}