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 key = key_binds
300 .iter()
301 .find(|(_, a)| **a == action)
302 .map_or_else(String::new, |(k, _)| k.to_string());
303
304 let mut items: Vec<crate::Element<'static, Message>> = Vec::with_capacity(7);
305
306 if let Some(checked) = checked {
307 items.push(if checked {
308 widget::icon::from_name("object-select-symbolic")
309 .size(16)
310 .icon()
311 .class(theme::Svg::Custom(Rc::new(|theme| {
312 iced_widget::svg::Style {
313 color: Some(theme.cosmic().accent_text_color().into()),
314 }
315 })))
316 .width(Length::Fixed(16.0))
317 .into()
318 } else {
319 widget::space::horizontal()
320 .width(Length::Fixed(16.0))
321 .into()
322 });
323 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
324 }
325
326 match icon {
327 IconSlot::Icon(icon) => {
328 items.push(widget::icon::icon(icon).size(14).into());
329 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
330 }
331 IconSlot::Reserved => {
332 items.push(
333 widget::space::horizontal()
334 .width(Length::Fixed(14.0))
335 .into(),
336 );
337 items.push(widget::space::horizontal().width(spacing.space_xxs).into());
338 }
339 IconSlot::None => {}
340 }
341
342 let ellipsize =
343 iced_core::text::Ellipsize::Middle(iced_core::text::EllipsizeHeightLimit::Lines(1));
344 items.push(widget::text(label.into()).ellipsize(ellipsize).into());
345 items.push(widget::space::horizontal().into());
346 items.push(
347 widget::text(key)
348 .class(key_class)
349 .ellipsize(ellipsize)
350 .into(),
351 );
352
353 let mut button = menu_button(items);
354 if enabled {
355 button = button.on_press(action.message());
356 }
357 MenuTree::from(Element::from(button))
358}
359
360#[must_use]
371pub fn menu_items<
372 A: MenuAction<Message = Message>,
373 L: Into<Cow<'static, str>> + 'static,
374 Message: 'static + std::clone::Clone,
375>(
376 key_binds: &HashMap<KeyBind, A>,
377 children: Vec<MenuItem<A, L>>,
378) -> Vec<MenuTree<Message>> {
379 fn key_style(theme: &crate::Theme) -> TextStyle {
380 let mut color = theme.cosmic().background(theme.transparent).component.on;
381 color.alpha *= 0.75;
382 TextStyle {
383 color: Some(color.into()),
384 ..Default::default()
385 }
386 }
387 let key_class = theme::Text::Custom(key_style);
388
389 let size = children.len();
390
391 children
392 .into_iter()
393 .enumerate()
394 .flat_map(|(i, item)| {
395 let mut trees = vec![];
396
397 match item {
398 MenuItem::Button(label, icon, action) => {
399 let mut entry = Entry::new(label, action);
400 entry.icon = icon.into();
401 trees.push(entry_tree(entry, key_binds, key_class.clone()));
402 }
403 MenuItem::ButtonDisabled(label, icon, action) => {
404 let mut entry = Entry::new(label, action).enabled(false);
405 entry.icon = icon.into();
406 trees.push(entry_tree(entry, key_binds, key_class.clone()));
407 }
408 MenuItem::CheckBox(label, icon, value, action) => {
409 let mut entry = Entry::new(label, action).checked(value);
410 entry.icon = icon.into();
411 trees.push(entry_tree(entry, key_binds, key_class.clone()));
412 }
413 MenuItem::Entry(entry) => {
414 trees.push(entry_tree(entry, key_binds, key_class.clone()));
415 }
416 MenuItem::Folder(label, children) => {
417 let l: Cow<'static, str> = label.into();
418
419 trees.push(MenuTree::<Message>::with_children(
420 RcElementWrapper::new(crate::Element::from(
421 menu_button::<'static, _>(vec![
422 widget::text(l.clone())
423 .ellipsize(iced_core::text::Ellipsize::Middle(
424 iced_core::text::EllipsizeHeightLimit::Lines(1),
425 ))
426 .into(),
427 widget::space::horizontal().into(),
428 widget::icon::from_name("pan-end-symbolic")
429 .size(16)
430 .icon()
431 .into(),
432 ])
433 .class(
434 if children.is_empty() {
436 theme::Button::MenuItem
438 } else {
439 theme::Button::MenuFolder
441 },
442 ),
443 )),
444 menu_items(key_binds, children),
445 ));
446 }
447 MenuItem::Divider => {
448 if i != size - 1 {
449 trees.push(MenuTree::<Message>::from(Element::from(
450 widget::divider::horizontal::light(),
451 )));
452 }
453 }
454 }
455 trees
456 })
457 .collect()
458}
459
460pub fn nav_context<
462 A: MenuAction<Message = Message>,
463 L: Into<Cow<'static, str>> + From<&'static str> + 'static,
464 Message: 'static + std::clone::Clone,
465>(
466 key_binds: &HashMap<KeyBind, A>,
467 children: Vec<Vec<MenuItem<A, L>>>,
468) -> Vec<MenuTree<Message>> {
469 let menus = children
470 .into_iter()
471 .map(|m| MenuItem::<A, L>::Folder(L::from(""), m));
472 let root = vec![MenuItem::<A, L>::Folder(L::from(""), menus.collect())];
473 menu_items(key_binds, root)
474}