Skip to main content

hyprforge_ui/widgets/
menu.rs

1//! A context menu: what a right click opens, at the pointer.
2//!
3//! Files drew the first one with its own code; the process manager was
4//! the second app to want one, so it moved here — the look, the sizes it
5//! is placed by, the rule for flipping it away from an edge, and the
6//! overlay that closes it on a click anywhere else. What goes in a menu,
7//! and what choosing a row does, stays the caller's.
8//!
9//! The menu is placed before iced lays it out, so its size is computed
10//! ([`menu_size`]) from the same numbers [`context_menu`] draws with:
11//! the box placed is the box drawn.
12
13use crate::density;
14use crate::theme::{self, spacing, surface, FontScale};
15use crate::widgets::{divider, meta_text, scaled_text};
16use iced::widget::{button, column, container, mouse_area, opaque, pin, row, stack, Space};
17use iced::{Element, Length};
18
19/// One row of a menu.
20#[derive(Debug, Clone, PartialEq)]
21pub enum MenuRow<Message> {
22    /// Something to choose: its label, an optional dim note at the right
23    /// edge (a shortcut, usually), and what choosing it sends — `None`
24    /// draws it dimmed and unchoosable, never hidden, so the rows don't
25    /// move under the pointer from one menu to the next.
26    Item { label: String, hint: Option<String>, on: Option<Message> },
27    /// A line between groups.
28    Separator,
29}
30
31impl<Message> MenuRow<Message> {
32    /// A row that sends `on` when chosen.
33    pub fn item(label: impl Into<String>, on: Message) -> Self {
34        MenuRow::Item { label: label.into(), hint: None, on: Some(on) }
35    }
36
37    /// A row shown but not choosable here.
38    pub fn disabled(label: impl Into<String>) -> Self {
39        MenuRow::Item { label: label.into(), hint: None, on: None }
40    }
41
42    /// The same row with a note at its right edge.
43    pub fn hint(self, note: impl Into<String>) -> Self {
44        match self {
45            MenuRow::Item { label, on, .. } => MenuRow::Item { label, hint: Some(note.into()), on },
46            separator => separator,
47        }
48    }
49}
50
51/// Wide enough for Files' longest label beside its shortcut — "Open in
52/// New Tab" and "Ctrl+Enter" — at 100%.
53pub const MENU_WIDTH: f32 = 260.0;
54/// A separator's whole slot, the line centred in it, at 100%.
55pub const MENU_SEPARATOR: f32 = 9.0;
56
57/// The space inside a menu's border.
58pub fn menu_padding(scale: FontScale) -> f32 {
59    scale.apply(spacing::XS)
60}
61
62/// A separator's slot at this scale.
63pub fn menu_separator_height(scale: FontScale) -> f32 {
64    scale.apply(MENU_SEPARATOR)
65}
66
67/// A menu's `(width, height)` before it is drawn, from what each row is.
68/// Takes only whether each row is a separator, so a caller with its own
69/// row type can ask without building the rows first.
70pub fn menu_size(separators: impl IntoIterator<Item = bool>, scale: FontScale) -> (f32, f32) {
71    let rows: f32 = separators.into_iter().map(|sep| if sep { menu_separator_height(scale) } else { density::row_height(scale) }).sum();
72    // `menu_padding` all round, plus the one-pixel border either side.
73    let chrome = 2.0 * menu_padding(scale) + 2.0;
74    (scale.apply(MENU_WIDTH), rows + chrome)
75}
76
77/// Where a menu's top-left corner goes, given where it was asked for,
78/// its own size and the window's.
79///
80/// It opens down and to the right of the pointer, the way menus do,
81/// unless that would run off the window — then it flips to open up, or
82/// left, from the same point. A menu too large to fit either way is
83/// pinned to the edge it overflows least, so its top-left is always on
84/// screen and the first items are always reachable.
85pub fn place_menu(at: (f32, f32), menu: (f32, f32), window: (f32, f32)) -> (f32, f32) {
86    fn axis(at: f32, size: f32, limit: f32) -> f32 {
87        if at + size <= limit {
88            at
89        } else if at - size >= 0.0 {
90            at - size
91        } else {
92            (limit - size).max(0.0)
93        }
94    }
95    (axis(at.0, menu.0, window.0), axis(at.1, menu.1, window.1))
96}
97
98/// The menu itself: the floating list's surface (`sidebar`, a 1px
99/// `card_border`, `inner_radius`), one row per item. `highlighted` is the
100/// row the keyboard is on, lit the way the pointer lights one.
101pub fn context_menu<'a, Message: Clone + 'a>(rows: Vec<MenuRow<Message>>, highlighted: Option<usize>, scale: FontScale, width: f32) -> Element<'a, Message> {
102    let row_h = density::row_height(scale);
103    let mut list = column![].width(Length::Fill);
104    for (index, item) in rows.into_iter().enumerate() {
105        match item {
106            MenuRow::Separator => {
107                let slot = menu_separator_height(scale);
108                list = list.push(container(divider()).height(Length::Fixed(slot)).center_y(Length::Fixed(slot)).padding([0, spacing::SM as u16]));
109            }
110            MenuRow::Item { label, hint, on } => {
111                let enabled = on.is_some();
112                let lit = highlighted == Some(index);
113                let colour = if enabled { theme::text() } else { theme::text_dim() };
114                // One line, whatever the label: `menu_size` counted one
115                // row per item, and a caller's label can be longer than
116                // any this crate ships.
117                let mut content = row![scaled_text(label, density::ROW_TEXT_BASE, scale)
118                    .color(colour)
119                    .wrapping(iced::widget::text::Wrapping::None)
120                    .width(Length::Fill)]
121                .align_y(iced::Alignment::Center)
122                .spacing(spacing::MD);
123                if let Some(hint) = hint {
124                    content = content.push(meta_text(hint, density::META_TEXT_BASE, scale));
125                }
126                list = list.push(
127                    button(content)
128                        .on_press_maybe(on)
129                        .width(Length::Fill)
130                        .height(Length::Fixed(row_h))
131                        .padding([0, spacing::SM as u16])
132                        .style(move |t: &iced::Theme, status| menu_item_style(t, status, lit, enabled)),
133                );
134            }
135        }
136    }
137    container(list)
138        .padding(menu_padding(scale))
139        .width(Length::Fixed(width))
140        .style(|_t: &iced::Theme| container::Style {
141            background: Some(iced::Background::Color(surface::sidebar())),
142            border: iced::Border { color: surface::card_border(), width: 1.0, radius: density::inner_radius().into() },
143            ..container::Style::default()
144        })
145        .into()
146}
147
148/// A menu item's look.
149///
150/// Unlike a listing row, hover takes the accent here. In a menu the
151/// pointer *is* the choice being made — the item under it is what a
152/// click will run — so hover and the keyboard highlight are the same
153/// state and look the same. A disabled item never lights up.
154pub fn menu_item_style(theme: &iced::Theme, status: button::Status, highlighted: bool, enabled: bool) -> button::Style {
155    let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed);
156    let lit = enabled && (highlighted || hovered);
157    button::Style {
158        background: lit.then(|| iced::Background::Color(theme.extended_palette().primary.weak.color)),
159        text_color: theme::text(),
160        border: iced::Border { radius: density::nested_radius().into(), ..iced::Border::default() },
161        ..button::Style::default()
162    }
163}
164
165/// A menu over the whole window, opened at `at` (window coordinates).
166///
167/// Two layers. Underneath, a transparent area the size of the window
168/// that sends `close` when clicked anywhere, left or right — and takes
169/// that click, so it does not also land on whatever was under it. On
170/// top, the menu, `opaque` so a click on it never falls through to the
171/// closing layer, and `pin`ned where it was asked for, flipped away from
172/// any edge it would run off ([`place_menu`]). Stack it over the window's
173/// content.
174pub fn menu_overlay<'a, Message: Clone + 'a>(rows: Vec<MenuRow<Message>>, at: (f32, f32), window: (f32, f32), close: Message, scale: FontScale) -> Element<'a, Message> {
175    let size = menu_size(rows.iter().map(|r| matches!(r, MenuRow::Separator)), scale);
176    let (x, y) = place_menu(at, size, window);
177    let away = mouse_area(Space::new().width(Length::Fill).height(Length::Fill)).on_press(close.clone()).on_right_press(close);
178    let placed = pin(opaque(context_menu(rows, None, scale, size.0))).x(x).y(y).width(Length::Fill).height(Length::Fill);
179    stack![away, placed].width(Length::Fill).height(Length::Fill).into()
180}
181
182/// Where the pointer last was, for opening a menu at it: iced's
183/// `on_right_press` says that a press happened and not where.
184pub mod pointer {
185    use iced::{event, mouse, Event, Subscription};
186    use std::sync::atomic::{AtomicU32, Ordering};
187
188    static X: AtomicU32 = AtomicU32::new(0);
189    static Y: AtomicU32 = AtomicU32::new(0);
190
191    /// Listens for pointer movement and never produces a message. Add it
192    /// to the application's subscriptions.
193    pub fn track<Message: 'static + Send>() -> Subscription<Message> {
194        event::listen_with(|event, _status, _window| {
195            if let Event::Mouse(mouse::Event::CursorMoved { position }) = event {
196                X.store(position.x.to_bits(), Ordering::Relaxed);
197                Y.store(position.y.to_bits(), Ordering::Relaxed);
198            }
199            None
200        })
201    }
202
203    /// The last pointer position seen, in window coordinates.
204    pub fn last() -> (f32, f32) {
205        (f32::from_bits(X.load(Ordering::Relaxed)), f32::from_bits(Y.load(Ordering::Relaxed)))
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn a_menu_near_an_edge_flips_to_open_the_other_way() {
215        let window = (800.0, 600.0);
216        let menu = (260.0, 200.0);
217        assert_eq!(place_menu((100.0, 100.0), menu, window), (100.0, 100.0), "room: down and right");
218        assert_eq!(place_menu((700.0, 100.0), menu, window), (440.0, 100.0), "the right edge: opens left");
219        assert_eq!(place_menu((100.0, 550.0), menu, window), (100.0, 350.0), "the bottom: opens up");
220    }
221
222    #[test]
223    fn a_menu_too_big_for_either_side_keeps_its_first_rows_on_screen() {
224        assert_eq!(place_menu((50.0, 50.0), (260.0, 900.0), (800.0, 600.0)), (50.0, 0.0));
225    }
226
227    #[test]
228    fn the_size_placed_counts_each_row_as_it_is_drawn() {
229        let scale = FontScale::default();
230        let (w, h) = menu_size([false, true, false], scale);
231        assert_eq!(w, MENU_WIDTH);
232        assert_eq!(h, 2.0 * density::row_height(scale) + MENU_SEPARATOR + 2.0 * spacing::XS + 2.0);
233    }
234
235    #[test]
236    fn a_row_without_a_message_is_shown_but_not_choosable() {
237        let row: MenuRow<u8> = MenuRow::disabled("End as administrator").hint("needs Show everything");
238        assert_eq!(row, MenuRow::Item { label: "End as administrator".into(), hint: Some("needs Show everything".into()), on: None });
239    }
240}