1use std::borrow::Cow;
6use std::collections::HashMap;
7use std::rc::Rc;
8
9use iced::advanced::widget::text::Style as TextStyle;
10use iced_widget::core::{Element, renderer};
11
12use crate::widget::menu::action::MenuAction;
13use crate::widget::menu::key_bind::KeyBind;
14use crate::widget::{Button, RcElementWrapper, icon};
15use crate::{theme, widget};
16use iced_core::{Alignment, Length};
17
18#[allow(missing_debug_implementations)]
27#[derive(Clone)]
28pub struct MenuTree<Message> {
29 pub(crate) index: usize,
32
33 pub(crate) item: RcElementWrapper<Message>,
35 pub(crate) children: Vec<MenuTree<Message>>,
37 pub(crate) width: Option<u16>,
39 pub(crate) height: Option<u16>,
41}
42
43impl<Message: Clone + 'static> MenuTree<Message> {
44 pub fn new(item: impl Into<RcElementWrapper<Message>>) -> Self {
46 Self {
47 index: 0,
48 item: item.into(),
49 children: Vec::new(),
50 width: None,
51 height: None,
52 }
53 }
54
55 pub fn with_children(
57 item: impl Into<RcElementWrapper<Message>>,
58 children: Vec<impl Into<MenuTree<Message>>>,
59 ) -> Self {
60 Self {
61 index: 0,
62 item: item.into(),
63 children: children.into_iter().map(Into::into).collect(),
64 width: None,
65 height: None,
66 }
67 }
68
69 #[must_use]
74 pub fn width(mut self, width: u16) -> Self {
75 self.width = Some(width);
76 self
77 }
78
79 #[must_use]
84 pub fn height(mut self, height: u16) -> Self {
85 self.height = Some(height);
86 self
87 }
88
89 pub(crate) fn set_index(&mut self) {
93 fn rec<Message: Clone + 'static>(mt: &mut MenuTree<Message>, count: &mut usize) {
95 mt.children.iter_mut().for_each(|c| {
97 c.index = *count;
98 *count += 1;
99 });
100
101 mt.children.iter_mut().for_each(|c| rec(c, count));
102 }
103
104 let mut count = 0;
105 self.index = count;
106 count += 1;
107 rec(self, &mut count);
108 }
109
110 pub(crate) fn flattern(&self) -> Vec<&Self> {
112 fn rec<'a, Message: Clone + 'static>(
114 mt: &'a MenuTree<Message>,
115 flat: &mut Vec<&'a MenuTree<Message>>,
116 ) {
117 mt.children.iter().for_each(|c| {
118 flat.push(c);
119 });
120
121 mt.children.iter().for_each(|c| {
122 rec(c, flat);
123 });
124 }
125
126 let mut flat = Vec::new();
127 flat.push(self);
128 rec(self, &mut flat);
129
130 flat
131 }
132}
133
134impl<Message: Clone + 'static> From<crate::Element<'static, Message>> for MenuTree<Message> {
135 fn from(value: crate::Element<'static, Message>) -> Self {
136 Self::new(RcElementWrapper::new(value))
137 }
138}
139
140pub fn menu_button<'a, Message>(
141 children: Vec<crate::Element<'a, Message>>,
142) -> crate::widget::Button<'a, Message>
143where
144 Message: std::clone::Clone + 'a,
145{
146 widget::button::custom(
147 widget::Row::from_vec(children)
148 .align_y(Alignment::Center)
149 .height(Length::Fill)
150 .width(Length::Fill),
151 )
152 .height(Length::Fixed(36.0))
153 .padding([4, 16])
154 .width(Length::Fill)
155 .class(theme::Button::MenuItem)
156}
157
158#[derive(Clone)]
159pub enum MenuItem<A: MenuAction, L: Into<Cow<'static, str>>> {
173 Button(L, Option<icon::Handle>, A),
175 ButtonDisabled(L, Option<icon::Handle>, A),
177 CheckBox(L, Option<icon::Handle>, bool, A),
179 Folder(L, Vec<MenuItem<A, L>>),
181 Divider,
183 Entry(Entry<A, L>),
185}
186
187impl<A: MenuAction, L: Into<Cow<'static, str>>> MenuItem<A, L> {
188 pub fn entry(label: L, action: A) -> Self {
190 MenuItem::Entry(Entry::new(label, action))
191 }
192}
193
194#[derive(Clone, Debug, Default)]
196pub enum IconSlot {
197 #[default]
199 None,
200 Reserved,
202 Icon(icon::Handle),
204}
205
206impl From<Option<icon::Handle>> for IconSlot {
207 fn from(icon: Option<icon::Handle>) -> Self {
208 icon.map_or(IconSlot::None, IconSlot::Icon)
209 }
210}
211
212#[derive(Clone)]
214pub struct Entry<A, L> {
215 label: L,
216 icon: IconSlot,
217 checked: Option<bool>,
219 enabled: bool,
220 action: A,
221}
222
223impl<A, L> Entry<A, L> {
224 pub fn new(label: L, action: A) -> Self {
225 Self {
226 label,
227 icon: IconSlot::None,
228 checked: None,
229 enabled: true,
230 action,
231 }
232 }
233
234 #[must_use]
236 pub fn icon(mut self, icon: icon::Handle) -> Self {
237 self.icon = IconSlot::Icon(icon);
238 self
239 }
240
241 #[must_use]
243 pub fn reserve_icon(mut self) -> Self {
244 self.icon = IconSlot::Reserved;
245 self
246 }
247
248 #[must_use]
250 pub fn checked(mut self, checked: bool) -> Self {
251 self.checked = Some(checked);
252 self
253 }
254
255 #[must_use]
257 pub fn enabled(mut self, enabled: bool) -> Self {
258 self.enabled = enabled;
259 self
260 }
261}
262
263pub fn menu_root<'a, Message, Renderer: renderer::Renderer>(
271 label: impl Into<Cow<'a, str>> + 'a,
272) -> Button<'a, Message>
273where
274 Element<'a, Message, crate::Theme, Renderer>: From<widget::Button<'a, Message>>,
275 Message: std::clone::Clone + 'a,
276{
277 widget::button::custom(widget::text(label))
278 .padding([4, 12])
279 .class(theme::Button::MenuRoot)
280}
281
282fn entry_tree<
283 A: MenuAction<Message = Message>,
284 L: Into<Cow<'static, str>>,
285 Message: Clone + 'static,
286>(
287 entry: Entry<A, L>,
288 key_binds: &HashMap<KeyBind, A>,
289 key_class: theme::Text,
290) -> MenuTree<Message> {
291 let Entry {
292 label,
293 icon,
294 checked,
295 enabled,
296 action,
297 } = entry;
298 let spacing = crate::theme::spacing();
299 let rank = |k: &KeyBind| {
305 (
306 k.modifiers.len(),
307 matches!(k.key, iced_core::keyboard::Key::Named(_)),
308 )
309 };
310 let key = key_binds
311 .iter()
312 .filter(|(_, a)| **a == action)
313 .map(|(k, _)| k)
314 .min_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| a.cmp(b)))
315 .map_or_else(String::new, ToString::to_string);
316
317 let mut items: Vec<crate::Element<'static, Message>> = Vec::with_capacity(7);
318
319 if let Some(checked) = checked {
320 items.push(if checked {
321 widget::icon::from_name("object-select-symbolic")
322 .size(16)
323 .icon()
324 .class(theme::Svg::Custom(Rc::new(|theme| {
325 iced_widget::svg::Style {
326 color: Some(theme.cosmic().accent_text_color().into()),
327 }
328 })))
329 .width(Length::Fixed(16.0))
330 .into()
331 } else {
332 widget::space::horizontal()
333 .width(Length::Fixed(16.0))
334 .into()
335 });
336 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
337 }
338
339 match icon {
340 IconSlot::Icon(icon) => {
341 items.push(widget::icon::icon(icon).size(14).into());
342 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
343 }
344 IconSlot::Reserved => {
345 items.push(
346 widget::space::horizontal()
347 .width(Length::Fixed(14.0))
348 .into(),
349 );
350 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
351 }
352 IconSlot::None => {}
353 }
354
355 let ellipsize =
356 iced_core::text::Ellipsize::Middle(iced_core::text::EllipsizeHeightLimit::Lines(1));
357 items.push(widget::text(label.into()).ellipsize(ellipsize).into());
358 items.push(widget::space::horizontal().into());
359 items.push(
360 widget::text(key)
361 .class(key_class)
362 .ellipsize(ellipsize)
363 .into(),
364 );
365
366 let mut button = menu_button(items);
367 if enabled {
368 button = button.on_press(action.message());
369 }
370 MenuTree::from(Element::from(button))
371}
372
373#[must_use]
384pub fn menu_items<
385 A: MenuAction<Message = Message>,
386 L: Into<Cow<'static, str>> + 'static,
387 Message: 'static + std::clone::Clone,
388>(
389 key_binds: &HashMap<KeyBind, A>,
390 children: Vec<MenuItem<A, L>>,
391) -> Vec<MenuTree<Message>> {
392 fn key_style(theme: &crate::Theme) -> TextStyle {
393 let mut color = theme.cosmic().background(theme.transparent).component.on;
394 color.alpha *= 0.75;
395 TextStyle {
396 color: Some(color.into()),
397 ..Default::default()
398 }
399 }
400 let key_class = theme::Text::Custom(key_style);
401
402 let size = children.len();
403
404 children
405 .into_iter()
406 .enumerate()
407 .flat_map(|(i, item)| {
408 let mut trees = vec![];
409
410 match item {
411 MenuItem::Button(label, icon, action) => {
412 let mut entry = Entry::new(label, action);
413 entry.icon = icon.into();
414 trees.push(entry_tree(entry, key_binds, key_class.clone()));
415 }
416 MenuItem::ButtonDisabled(label, icon, action) => {
417 let mut entry = Entry::new(label, action).enabled(false);
418 entry.icon = icon.into();
419 trees.push(entry_tree(entry, key_binds, key_class.clone()));
420 }
421 MenuItem::CheckBox(label, icon, value, action) => {
422 let mut entry = Entry::new(label, action).checked(value);
423 entry.icon = icon.into();
424 trees.push(entry_tree(entry, key_binds, key_class.clone()));
425 }
426 MenuItem::Entry(entry) => {
427 trees.push(entry_tree(entry, key_binds, key_class.clone()));
428 }
429 MenuItem::Folder(label, children) => {
430 let l: Cow<'static, str> = label.into();
431
432 trees.push(MenuTree::<Message>::with_children(
433 RcElementWrapper::new(crate::Element::from(
434 menu_button::<'static, _>(vec![
435 widget::text(l.clone())
436 .ellipsize(iced_core::text::Ellipsize::Middle(
437 iced_core::text::EllipsizeHeightLimit::Lines(1),
438 ))
439 .into(),
440 widget::space::horizontal().into(),
441 widget::icon::from_name("pan-end-symbolic")
442 .size(16)
443 .icon()
444 .into(),
445 ])
446 .class(
447 if children.is_empty() {
449 theme::Button::MenuItem
451 } else {
452 theme::Button::MenuFolder
454 },
455 ),
456 )),
457 menu_items(key_binds, children),
458 ));
459 }
460 MenuItem::Divider => {
461 if i != 0 && i != size - 1 {
463 trees.push(MenuTree::<Message>::from(Element::from(
464 widget::divider::horizontal::light(),
465 )));
466 }
467 }
468 }
469 trees
470 })
471 .collect()
472}
473
474pub fn nav_context<
476 A: MenuAction<Message = Message>,
477 L: Into<Cow<'static, str>> + From<&'static str> + 'static,
478 Message: 'static + std::clone::Clone,
479>(
480 key_binds: &HashMap<KeyBind, A>,
481 children: Vec<Vec<MenuItem<A, L>>>,
482) -> Vec<MenuTree<Message>> {
483 let menus = children
484 .into_iter()
485 .map(|m| MenuItem::<A, L>::Folder(L::from(""), m));
486 let root = vec![MenuItem::<A, L>::Folder(L::from(""), menus.collect())];
487 menu_items(key_binds, root)
488}