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    // Several bindings may map to one action
300    // choose based on these rules:
301    // - the fewest modifiers win (Delete vs Ctrl+D)
302    // - if equal then character key over a named one (Ctrl+C over Ctrl+Insert)
303    // - if equal then `Ord` to stay consistent since hashmap is arbitrary
304    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/// Create a list of menu items from a vector of `MenuItem`.
374///
375/// The `MenuItem` can be either an action or a separator.
376///
377/// # Arguments
378/// - `key_binds` - A reference to a `HashMap` that maps `KeyBind` to `A`.
379/// - `children` - A vector of `MenuItem`.
380///
381/// # Returns
382/// - A vector of `MenuTree`.
383#[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                                // Menu folders have no on_press so they take on the disabled style by default
448                                if children.is_empty() {
449                                    // This will make the folder use the disabled style if it has no children
450                                    theme::Button::MenuItem
451                                } else {
452                                    // This will make the folder use the enabled style if it has children
453                                    theme::Button::MenuFolder
454                                },
455                            ),
456                        )),
457                        menu_items(key_binds, children),
458                    ));
459                }
460                MenuItem::Divider => {
461                    // A divider at either end separates nothing
462                    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
474/// Create a menu tree from a widget and a vector of sub trees
475pub 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}