Skip to main content

cosmic/widget/menu/
menu_tree.rs

1// From iced_aw, license MIT
2
3//! A tree structure for constructing a hierarchical menu
4
5use 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/// Nested menu is essentially a tree of items, a menu is a collection of items
19/// a menu itself can also be an item of another menu.
20///
21/// A `MenuTree` represents a node in the tree, it holds a widget as a menu item
22/// for its parent, and a list of menu tree as child nodes.
23/// Conceptually a node is either a menu(inner node) or an item(leaf node),
24/// but there's no need to explicitly distinguish them here, if a menu tree
25/// has children, it's a menu, otherwise it's an item
26#[allow(missing_debug_implementations)]
27#[derive(Clone)]
28pub struct MenuTree<Message> {
29    /// The menu tree will be flatten into a vector to build a linear widget tree,
30    /// the `index` field is the index of the item in that vector
31    pub(crate) index: usize,
32
33    /// The item of the menu tree
34    pub(crate) item: RcElementWrapper<Message>,
35    /// The children of the menu tree
36    pub(crate) children: Vec<MenuTree<Message>>,
37    /// The width of the menu tree
38    pub(crate) width: Option<u16>,
39    /// The height of the menu tree
40    pub(crate) height: Option<u16>,
41}
42
43impl<Message: Clone + 'static> MenuTree<Message> {
44    /// Create a new menu tree from a widget
45    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    /// Create a menu tree from a widget and a vector of sub trees
56    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    /// Sets the width of the menu tree.
70    /// See [`ItemWidth`]
71    ///
72    /// [`ItemWidth`]:`super::ItemWidth`
73    #[must_use]
74    pub fn width(mut self, width: u16) -> Self {
75        self.width = Some(width);
76        self
77    }
78
79    /// Sets the height of the menu tree.
80    /// See [`ItemHeight`]
81    ///
82    /// [`ItemHeight`]: `super::ItemHeight`
83    #[must_use]
84    pub fn height(mut self, height: u16) -> Self {
85        self.height = Some(height);
86        self
87    }
88
89    /* Keep `set_index()` and `flattern()` recurse in the same order */
90
91    /// Set the index of each item
92    pub(crate) fn set_index(&mut self) {
93        /// inner counting function.
94        fn rec<Message: Clone + 'static>(mt: &mut MenuTree<Message>, count: &mut usize) {
95            // keep items under the same menu line up
96            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    /// Flatten the menu tree
111    pub(crate) fn flattern(&self) -> Vec<&Self> {
112        /// Inner flattening function
113        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)]
159/// Represents a menu item that performs an action when selected or a separator between menu items.
160///
161/// - `Action` - Represents a menu item that performs an action when selected.
162///     - `L` - The label of the menu item.
163///     - `A` - The action to perform when the menu item is selected, the action must implement the `MenuAction` trait.
164/// - `CheckBox` - Represents a checkbox menu item.
165///     - `L` - The label of the menu item.
166///     - `bool` - The state of the checkbox.
167///     - `A` - The action to perform when the menu item is selected, the action must implement the `MenuAction` trait.
168/// - `Folder` - Represents a folder menu item.
169///     - `L` - The label of the menu item.
170///     - `Vec<MenuItem<A, L>>` - A vector of menu items.
171/// - `Divider` - Represents a divider between menu items.
172pub enum MenuItem<A: MenuAction, L: Into<Cow<'static, str>>> {
173    /// Represents a button menu item.
174    Button(L, Option<icon::Handle>, A),
175    /// Represents a button menu item that is disabled.
176    ButtonDisabled(L, Option<icon::Handle>, A),
177    /// Represents a checkbox menu item.
178    CheckBox(L, Option<icon::Handle>, bool, A),
179    /// Represents a folder menu item.
180    Folder(L, Vec<MenuItem<A, L>>),
181    /// Represents a divider between menu items.
182    Divider,
183    /// A menu entry with every option available; see [`Entry`].
184    Entry(Entry<A, L>),
185}
186
187impl<A: MenuAction, L: Into<Cow<'static, str>>> MenuItem<A, L> {
188    /// Create an [`Entry`] menu item, configure it with the builder methods on [`Entry`].
189    pub fn entry(label: L, action: A) -> Self {
190        MenuItem::Entry(Entry::new(label, action))
191    }
192}
193
194/// The leading icon column of a menu entry.
195#[derive(Clone, Debug, Default)]
196pub enum IconSlot {
197    /// No icon and no space reserved for one.
198    #[default]
199    None,
200    /// No icon, but the space for an icon is reserved (indented entry)
201    Reserved,
202    /// An icon.
203    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/// A menu entry: label, optional leading icon, optional check column, enabled state and action.
213#[derive(Clone)]
214pub struct Entry<A, L> {
215    label: L,
216    icon: IconSlot,
217    /// `Some` draws the check column
218    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    /// Draw a leading icon
235    #[must_use]
236    pub fn icon(mut self, icon: icon::Handle) -> Self {
237        self.icon = IconSlot::Icon(icon);
238        self
239    }
240
241    /// Draw no icon, but resever the space
242    #[must_use]
243    pub fn reserve_icon(mut self) -> Self {
244        self.icon = IconSlot::Reserved;
245        self
246    }
247
248    /// Show a check column, ticked when `checked` is true, empty sapce when false
249    #[must_use]
250    pub fn checked(mut self, checked: bool) -> Self {
251        self.checked = Some(checked);
252        self
253    }
254
255    /// Disabled entries are drawn dimmed and do not react to presses
256    #[must_use]
257    pub fn enabled(mut self, enabled: bool) -> Self {
258        self.enabled = enabled;
259        self
260    }
261}
262
263/// Create a root menu item.
264///
265/// # Arguments
266/// - `label` - The label of the menu item.
267///
268/// # Returns
269/// - A button for the root menu item.
270pub 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/// Create a list of menu items from a vector of `MenuItem`.
361///
362/// The `MenuItem` can be either an action or a separator.
363///
364/// # Arguments
365/// - `key_binds` - A reference to a `HashMap` that maps `KeyBind` to `A`.
366/// - `children` - A vector of `MenuItem`.
367///
368/// # Returns
369/// - A vector of `MenuTree`.
370#[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                                // Menu folders have no on_press so they take on the disabled style by default
435                                if children.is_empty() {
436                                    // This will make the folder use the disabled style if it has no children
437                                    theme::Button::MenuItem
438                                } else {
439                                    // This will make the folder use the enabled style if it has children
440                                    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
460/// Create a menu tree from a widget and a vector of sub trees
461pub 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}