1use 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#[derive(Debug, Clone, PartialEq)]
21pub enum MenuRow<Message> {
22 Item { label: String, hint: Option<String>, on: Option<Message> },
27 Separator,
29}
30
31impl<Message> MenuRow<Message> {
32 pub fn item(label: impl Into<String>, on: Message) -> Self {
34 MenuRow::Item { label: label.into(), hint: None, on: Some(on) }
35 }
36
37 pub fn disabled(label: impl Into<String>) -> Self {
39 MenuRow::Item { label: label.into(), hint: None, on: None }
40 }
41
42 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
51pub const MENU_WIDTH: f32 = 260.0;
54pub const MENU_SEPARATOR: f32 = 9.0;
56
57pub fn menu_padding(scale: FontScale) -> f32 {
59 scale.apply(spacing::XS)
60}
61
62pub fn menu_separator_height(scale: FontScale) -> f32 {
64 scale.apply(MENU_SEPARATOR)
65}
66
67pub 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 let chrome = 2.0 * menu_padding(scale) + 2.0;
74 (scale.apply(MENU_WIDTH), rows + chrome)
75}
76
77pub 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
98pub 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 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
148pub 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
165pub 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
182pub 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 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 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}