rat_menu/
menubar.rs

1//! This widget will render a menubar and one level of menus.
2//!
3//! It is not a Widget itself, instead it will [split into](Menubar::into_widgets)
4//! a [MenubarLine] and a [MenubarPopup] widget that can be rendered.
5//! The MenubarLine can be rendered in its designated area anytime.
6//! The MenubarPopup must be rendered at the end of rendering,
7//! for it to be able to render above the other widgets.
8//!
9//! Event handling for the menubar must happen before handling
10//! events for the widgets that might be rendered in the background.
11//! Otherwise, mouse navigation will not work correctly.
12//!
13//! The structure of the menubar is defined with the trait
14//! [MenuStructure], and there is [StaticMenu](crate::StaticMenu)
15//! which can define the structure as static data.
16//!
17//! [Example](https://github.com/thscharler/rat-salsa/blob/master/rat-widget/examples/menubar1.rs)
18//!
19#![allow(clippy::uninlined_format_args)]
20use crate::event::MenuOutcome;
21use crate::menuline::{MenuLine, MenuLineState};
22use crate::popup_menu::{PopupMenu, PopupMenuState};
23use crate::{MenuStructure, MenuStyle};
24use rat_event::{ConsumedEvent, HandleEvent, MouseOnly, Popup, Regular};
25use rat_focus::{FocusBuilder, FocusFlag, HasFocus, Navigation};
26use rat_popup::Placement;
27use ratatui::buffer::Buffer;
28use ratatui::layout::{Alignment, Rect};
29use ratatui::style::Style;
30use ratatui::text::Line;
31use ratatui::widgets::{Block, StatefulWidget};
32use std::fmt::Debug;
33
34/// Menubar widget.
35///
36/// This handles the configuration only, to get the widgets for rendering
37/// call [Menubar::into_widgets] and use both results for rendering.
38#[derive(Debug, Clone)]
39pub struct Menubar<'a> {
40    structure: Option<&'a dyn MenuStructure<'a>>,
41
42    title: Line<'a>,
43    style: Style,
44    title_style: Option<Style>,
45    focus_style: Option<Style>,
46    highlight_style: Option<Style>,
47    disabled_style: Option<Style>,
48    right_style: Option<Style>,
49
50    popup_alignment: Alignment,
51    popup_placement: Placement,
52    popup: PopupMenu<'a>,
53}
54
55/// Menubar line widget.
56///
57/// This will render the main menu bar.
58#[derive(Debug, Clone)]
59pub struct MenubarLine<'a> {
60    structure: Option<&'a dyn MenuStructure<'a>>,
61
62    title: Line<'a>,
63    style: Style,
64    title_style: Option<Style>,
65    focus_style: Option<Style>,
66    highlight_style: Option<Style>,
67    disabled_style: Option<Style>,
68    right_style: Option<Style>,
69}
70
71/// Menubar popup widget.
72///
73/// Separate renderer for the popup part of the menu bar.
74#[derive(Debug, Clone)]
75pub struct MenubarPopup<'a> {
76    structure: Option<&'a dyn MenuStructure<'a>>,
77
78    style: Style,
79    focus_style: Option<Style>,
80    highlight_style: Option<Style>,
81    disabled_style: Option<Style>,
82    right_style: Option<Style>,
83
84    popup_alignment: Alignment,
85    popup_placement: Placement,
86    popup: PopupMenu<'a>,
87}
88
89/// State & event-handling.
90#[derive(Debug, Default, Clone)]
91pub struct MenubarState {
92    /// Area for the menubar.
93    /// __readonly__. renewed for each render.
94    pub area: Rect,
95    /// State for the menu.
96    pub bar: MenuLineState,
97    /// State for the last rendered popup menu.
98    pub popup: PopupMenuState,
99}
100
101impl Default for Menubar<'_> {
102    fn default() -> Self {
103        Self {
104            structure: Default::default(),
105            title: Default::default(),
106            style: Default::default(),
107            title_style: Default::default(),
108            focus_style: Default::default(),
109            highlight_style: Default::default(),
110            disabled_style: Default::default(),
111            right_style: Default::default(),
112            popup_alignment: Alignment::Left,
113            popup_placement: Placement::AboveOrBelow,
114            popup: Default::default(),
115        }
116    }
117}
118
119impl<'a> Menubar<'a> {
120    pub fn new(structure: &'a dyn MenuStructure<'a>) -> Self {
121        Self {
122            structure: Some(structure),
123            ..Default::default()
124        }
125    }
126
127    /// Title text.
128    #[inline]
129    pub fn title(mut self, title: impl Into<Line<'a>>) -> Self {
130        self.title = title.into();
131        self
132    }
133
134    /// Combined style.
135    #[inline]
136    pub fn styles(mut self, styles: MenuStyle) -> Self {
137        self.popup = self.popup.styles(styles.clone());
138
139        self.style = styles.style;
140        if styles.highlight.is_some() {
141            self.highlight_style = styles.highlight;
142        }
143        if styles.disabled.is_some() {
144            self.disabled_style = styles.disabled;
145        }
146        if styles.focus.is_some() {
147            self.focus_style = styles.focus;
148        }
149        if styles.title.is_some() {
150            self.title_style = styles.title;
151        }
152        if styles.focus.is_some() {
153            self.focus_style = styles.focus;
154        }
155        if styles.right.is_some() {
156            self.right_style = styles.right;
157        }
158        if let Some(alignment) = styles.popup.alignment {
159            self.popup_alignment = alignment;
160        }
161        if let Some(placement) = styles.popup.placement {
162            self.popup_placement = placement;
163        }
164        self
165    }
166
167    /// Base style.
168    #[inline]
169    pub fn style(mut self, style: Style) -> Self {
170        self.style = style;
171        self
172    }
173
174    /// Menu-title style.
175    #[inline]
176    pub fn title_style(mut self, style: Style) -> Self {
177        self.title_style = Some(style);
178        self
179    }
180
181    /// Selection + Focus
182    #[inline]
183    pub fn focus_style(mut self, style: Style) -> Self {
184        self.focus_style = Some(style);
185        self
186    }
187
188    /// Selection + Focus
189    #[inline]
190    pub fn right_style(mut self, style: Style) -> Self {
191        self.right_style = Some(style);
192        self
193    }
194
195    /// Fixed width for the menu.
196    /// If not set it uses 1.5 times the length of the longest item.
197    pub fn popup_width(mut self, width: u16) -> Self {
198        self.popup = self.popup.width(width);
199        self
200    }
201
202    /// Placement relative to the render-area.
203    pub fn popup_alignment(mut self, alignment: Alignment) -> Self {
204        self.popup_alignment = alignment;
205        self
206    }
207
208    /// Placement relative to the render-area.
209    pub fn popup_placement(mut self, placement: Placement) -> Self {
210        self.popup_placement = placement;
211        self
212    }
213
214    /// Block for the popup menus.
215    pub fn popup_block(mut self, block: Block<'a>) -> Self {
216        self.popup = self.popup.block(block);
217        self
218    }
219
220    /// Create the widgets for the Menubar. This returns a widget
221    /// for the menu-line and for the menu-popup.
222    ///
223    /// The menu-popup should be rendered after all widgets
224    /// that might be below the popup have been rendered.
225    pub fn into_widgets(self) -> (MenubarLine<'a>, MenubarPopup<'a>) {
226        (
227            MenubarLine {
228                structure: self.structure,
229                title: self.title,
230                style: self.style,
231                title_style: self.title_style,
232                focus_style: self.focus_style,
233                highlight_style: self.highlight_style,
234                disabled_style: self.disabled_style,
235                right_style: self.right_style,
236            },
237            MenubarPopup {
238                structure: self.structure,
239                style: self.style,
240                focus_style: self.focus_style,
241                highlight_style: self.highlight_style,
242                disabled_style: self.disabled_style,
243                right_style: self.right_style,
244                popup_alignment: self.popup_alignment,
245                popup_placement: self.popup_placement,
246                popup: self.popup,
247            },
248        )
249    }
250}
251
252impl StatefulWidget for MenubarLine<'_> {
253    type State = MenubarState;
254
255    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
256        render_menubar(&self, area, buf, state);
257    }
258}
259
260fn render_menubar(
261    widget: &MenubarLine<'_>,
262    area: Rect,
263    buf: &mut Buffer,
264    state: &mut MenubarState,
265) {
266    let mut menu = MenuLine::new()
267        .title(widget.title.clone())
268        .style(widget.style)
269        .title_style_opt(widget.title_style)
270        .focus_style_opt(widget.focus_style)
271        .highlight_style_opt(widget.highlight_style)
272        .disabled_style_opt(widget.disabled_style)
273        .right_style_opt(widget.right_style);
274
275    if let Some(structure) = &widget.structure {
276        structure.menus(&mut menu.menu);
277    }
278    menu.render(area, buf, &mut state.bar);
279
280    // Combined area + each part with a z-index.
281    state.area = state.bar.area;
282}
283
284impl StatefulWidget for MenubarPopup<'_> {
285    type State = MenubarState;
286
287    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
288        render_menu_popup(self, area, buf, state);
289    }
290}
291
292fn render_menu_popup(
293    widget: MenubarPopup<'_>,
294    _area: Rect,
295    buf: &mut Buffer,
296    state: &mut MenubarState,
297) {
298    // Combined area + each part with a z-index.
299    state.area = state.bar.area;
300
301    let Some(selected) = state.bar.selected() else {
302        return;
303    };
304    let Some(structure) = widget.structure else {
305        return;
306    };
307
308    if state.popup.is_active() {
309        let item = state.bar.item_areas[selected];
310
311        let popup_padding = widget.popup.get_block_padding();
312        let sub_offset = (-(popup_padding.left as i16 + 1), 0);
313
314        let mut popup = widget
315            .popup
316            .constraint(
317                widget
318                    .popup_placement
319                    .into_constraint(widget.popup_alignment, item),
320            )
321            .offset(sub_offset)
322            .style(widget.style)
323            .focus_style_opt(widget.focus_style)
324            .highlight_style_opt(widget.highlight_style)
325            .disabled_style_opt(widget.disabled_style)
326            .right_style_opt(widget.right_style);
327
328        structure.submenu(selected, &mut popup.menu);
329
330        if !popup.menu.items.is_empty() {
331            let area = state.bar.item_areas[selected];
332            popup.render(area, buf, &mut state.popup);
333
334            // Combined area + each part with a z-index.
335            state.area = state.bar.area.union(state.popup.popup.area);
336        }
337    } else {
338        state.popup = Default::default();
339    }
340}
341
342impl MenubarState {
343    /// State.
344    /// For the specifics use the public fields `menu` and `popup`.
345    pub fn new() -> Self {
346        Self::default()
347    }
348
349    /// New state with a focus name.
350    pub fn named(name: &'static str) -> Self {
351        Self {
352            bar: MenuLineState::named(format!("{}.bar", name).to_string().leak()),
353            popup: PopupMenuState::new(),
354            ..Default::default()
355        }
356    }
357
358    /// Submenu visible/active.
359    pub fn popup_active(&self) -> bool {
360        self.popup.is_active()
361    }
362
363    /// Submenu visible/active.
364    pub fn set_popup_active(&mut self, active: bool) {
365        self.popup.set_active(active);
366    }
367
368    /// Set the z-value for the popup-menu.
369    ///
370    /// This is the z-index used when adding the menubar to
371    /// the focus list.
372    pub fn set_popup_z(&mut self, z: u16) {
373        self.popup.set_popup_z(z)
374    }
375
376    /// The z-index for the popup-menu.
377    pub fn popup_z(&self) -> u16 {
378        self.popup.popup_z()
379    }
380
381    /// Selected as menu/submenu
382    pub fn selected(&self) -> (Option<usize>, Option<usize>) {
383        (self.bar.selected, self.popup.selected)
384    }
385}
386
387impl HasFocus for MenubarState {
388    fn build(&self, builder: &mut FocusBuilder) {
389        builder.widget_with_flags(self.focus(), self.area(), self.area_z(), self.navigable());
390        builder.widget_with_flags(
391            self.focus(),
392            self.popup.popup.area,
393            self.popup.popup.area_z,
394            Navigation::Mouse,
395        );
396    }
397
398    fn focus(&self) -> FocusFlag {
399        self.bar.focus.clone()
400    }
401
402    fn area(&self) -> Rect {
403        self.area
404    }
405}
406
407impl HandleEvent<crossterm::event::Event, Popup, MenuOutcome> for MenubarState {
408    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: Popup) -> MenuOutcome {
409        handle_menubar(self, event, Popup, Regular)
410    }
411}
412
413impl HandleEvent<crossterm::event::Event, MouseOnly, MenuOutcome> for MenubarState {
414    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: MouseOnly) -> MenuOutcome {
415        handle_menubar(self, event, MouseOnly, MouseOnly)
416    }
417}
418
419fn handle_menubar<Q1, Q2>(
420    state: &mut MenubarState,
421    event: &crossterm::event::Event,
422    qualifier1: Q1,
423    qualifier2: Q2,
424) -> MenuOutcome
425where
426    PopupMenuState: HandleEvent<crossterm::event::Event, Q1, MenuOutcome>,
427    MenuLineState: HandleEvent<crossterm::event::Event, Q2, MenuOutcome>,
428    MenuLineState: HandleEvent<crossterm::event::Event, MouseOnly, MenuOutcome>,
429{
430    if !state.is_focused() {
431        state.set_popup_active(false);
432    }
433
434    if state.bar.is_focused() {
435        let mut r = if let Some(selected) = state.bar.selected() {
436            if state.popup_active() {
437                match state.popup.handle(event, qualifier1) {
438                    MenuOutcome::Hide => {
439                        // only hide on focus lost. ignore this one.
440                        MenuOutcome::Continue
441                    }
442                    MenuOutcome::Selected(n) => MenuOutcome::MenuSelected(selected, n),
443                    MenuOutcome::Activated(n) => MenuOutcome::MenuActivated(selected, n),
444                    r => r,
445                }
446            } else {
447                MenuOutcome::Continue
448            }
449        } else {
450            MenuOutcome::Continue
451        };
452
453        r = r.or_else(|| {
454            let old_selected = state.bar.selected();
455            let r = state.bar.handle(event, qualifier2);
456            match r {
457                MenuOutcome::Selected(_) => {
458                    if state.bar.selected == old_selected {
459                        state.popup.flip_active();
460                    } else {
461                        state.popup.select(None);
462                        state.popup.set_active(true);
463                    }
464                }
465                MenuOutcome::Activated(_) => {
466                    state.popup.flip_active();
467                }
468                _ => {}
469            }
470            r
471        });
472
473        r
474    } else {
475        state.bar.handle(event, MouseOnly)
476    }
477}
478
479/// Handle menu events for the popup-menu.
480///
481/// This one is separate, as it needs to be called before other event-handlers
482/// to cope with overlapping regions.
483///
484/// focus - is the menubar focused?
485pub fn handle_popup_events(
486    state: &mut MenubarState,
487    focus: bool,
488    event: &crossterm::event::Event,
489) -> MenuOutcome {
490    state.bar.focus.set(focus);
491    state.handle(event, Popup)
492}
493
494/// Handle only mouse-events.
495pub fn handle_mouse_events(
496    state: &mut MenuLineState,
497    event: &crossterm::event::Event,
498) -> MenuOutcome {
499    state.handle(event, MouseOnly)
500}