1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//!
//! A menubar widget with sub-menus.
//!
//! Combines [MenuLine] and [PopupMenu] and adds a [MenuStructure] trait
//! to bind all together.
//!
//! Rendering is split in two widgets [MenuBar] and [MenuPopup].
//! This should help with front/back rendering.
//!
//! Event-handling for the popup menu is split via the [Popup] qualifier.
//! All `Popup` event-handling should be called before the regular
//! `FocusKeys` handling.
//!
use crate::event::Popup;
use crate::menuline::{MenuLine, MenuLineState, MenuOutcome, MenuStyle};
use crate::popup_menu::{Placement, PopupMenu, PopupMenuState};
use crate::util::menu_str;
use rat_event::{flow, FocusKeys, HandleEvent, MouseOnly};
use rat_focus::{FocusFlag, HasFocusFlag, ZRect};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::{Line, StatefulWidget, Style};
use ratatui::widgets::{Block, StatefulWidgetRef};
use std::fmt::{Debug, Formatter};

/// Trait for the structural data of the MenuBar.
pub trait MenuStructure<'a> {
    /// Main menu.
    fn menus(&'a self) -> Vec<(Line<'a>, Option<char>)>;
    /// Submenus.
    fn submenu(&'a self, n: usize) -> Vec<(Line<'a>, Option<char>)>;
}

/// Static menu structure.
#[derive(Debug)]
pub struct StaticMenu {
    pub menu: &'static [(&'static str, &'static [&'static str])],
}

impl MenuStructure<'static> for StaticMenu {
    fn menus(&'static self) -> Vec<(Line<'static>, Option<char>)> {
        self.menu.iter().map(|v| menu_str(v.0)).collect()
    }

    fn submenu(&'static self, n: usize) -> Vec<(Line<'static>, Option<char>)> {
        self.menu[n].1.iter().map(|v| menu_str(v)).collect()
    }
}

/// MenuBar widget.
///
/// This is only half of the widget. For popup rendering there is the separate
/// [MenuPopup].
#[derive(Debug, Default, Clone)]
pub struct MenuBar<'a> {
    menu: MenuLine<'a>,
}

/// Menubar widget.
///
/// Separate renderer for the popup part of the menubar.
#[derive(Default, Clone)]
pub struct MenuPopup<'a> {
    structure: Option<&'a dyn MenuStructure<'a>>,
    popup: PopupMenu<'a>,
}

/// State for the menubar.
#[derive(Debug, Default, Clone)]
pub struct MenuBarState {
    /// State for the menu.
    pub menu: MenuLineState,
    /// State for the last rendered popup menu.
    pub popup: PopupMenuState,

    pub area: Rect,
    pub z_areas: [ZRect; 2],
}

impl<'a> MenuBar<'a> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Title text.
    #[inline]
    pub fn title(mut self, title: impl Into<Line<'a>>) -> Self {
        self.menu = self.menu.title(title);
        self
    }

    /// Menu-Structure
    pub fn menu(mut self, structure: &'a dyn MenuStructure<'a>) -> Self {
        for (m, n) in structure.menus() {
            self.menu = self.menu.add(m, n);
        }
        self
    }

    /// Combined style.
    #[inline]
    pub fn styles(mut self, styles: MenuStyle) -> Self {
        self.menu = self.menu.styles(styles.clone());
        self
    }

    /// Base style.
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.menu = self.menu.style(style);
        self
    }

    /// Menu-title style.
    #[inline]
    pub fn title_style(mut self, style: Style) -> Self {
        self.menu = self.menu.title_style(style);
        self
    }

    /// Selection
    #[inline]
    pub fn select_style(mut self, style: Style) -> Self {
        self.menu = self.menu.select_style(style);
        self
    }

    /// Selection + Focus
    #[inline]
    pub fn focus_style(mut self, style: Style) -> Self {
        self.menu = self.menu.focus_style(style);
        self
    }
}

impl<'a> Debug for MenuPopup<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MenuPopup")
            .field("popup", &self.popup)
            .finish()
    }
}

impl<'a> MenuPopup<'a> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Menu.
    pub fn menu(mut self, structure: &'a dyn MenuStructure<'a>) -> Self {
        self.structure = Some(structure);
        self
    }

    /// Fixed width for the menu.
    /// If not set it uses 1.5 times the length of the longest item.
    pub fn width(mut self, width: u16) -> Self {
        self.popup = self.popup.width(width);
        self
    }

    /// Placement relative to the render-area.
    pub fn placement(mut self, placement: Placement) -> Self {
        self.popup = self.popup.placement(placement);
        self
    }

    /// Combined style.
    #[inline]
    pub fn styles(mut self, styles: MenuStyle) -> Self {
        self.popup = self.popup.styles(styles.clone());
        self
    }

    /// Base style.
    pub fn style(mut self, style: Style) -> Self {
        self.popup = self.popup.style(style);
        self
    }

    /// Focus/Selection style.
    pub fn focus_style(mut self, style: Style) -> Self {
        self.popup = self.popup.focus_style(style);
        self
    }

    /// Block for borders.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.popup = self.popup.block(block);
        self
    }
}

impl<'a> StatefulWidgetRef for MenuBar<'a> {
    type State = MenuBarState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_menubar(self, area, buf, state);
    }
}

impl<'a> StatefulWidget for MenuBar<'a> {
    type State = MenuBarState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_menubar(&self, area, buf, state);
    }
}

fn render_menubar(widget: &MenuBar<'_>, area: Rect, buf: &mut Buffer, state: &mut MenuBarState) {
    widget.menu.render_ref(area, buf, &mut state.menu);

    // Combined area + each part with a z-index.
    state.area = state.menu.area;
    state.z_areas = [ZRect::from((0, state.menu.area)), ZRect::default()];
}

impl<'a> StatefulWidgetRef for MenuPopup<'a> {
    type State = MenuBarState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_menu_popup(self, area, buf, state);
    }
}

impl<'a> StatefulWidget for MenuPopup<'a> {
    type State = MenuBarState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_menu_popup(&self, area, buf, state);
    }
}

fn render_menu_popup(
    widget: &MenuPopup<'_>,
    _area: Rect,
    buf: &mut Buffer,
    state: &mut MenuBarState,
) {
    // Combined area + each part with a z-index.
    state.area = state.menu.area;
    state.z_areas = [ZRect::from((0, state.menu.area)), ZRect::default()];

    let Some(selected) = state.menu.selected() else {
        return;
    };
    let Some(structure) = widget.structure else {
        return;
    };

    if state.popup.is_focused() {
        let mut len = 0;
        let mut popup = widget.popup.clone(); // TODO: ???
        for (item, navchar) in structure.submenu(selected) {
            popup = popup.add(item, navchar);
            len += 1;
        }

        if len > 0 {
            let area = state.menu.item_areas[selected];
            popup.render(area, buf, &mut state.popup);

            // Combined area + each part with a z-index.
            state.area = state.menu.area.union(state.popup.area);
            state.z_areas[1] = ZRect::from((1, state.popup.area));
        }
    } else {
        state.popup = Default::default();
    }
}

impl MenuBarState {
    /// State.
    /// For the specifics use the public fields `menu` and `popup`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Submenu visible/active.
    pub fn popup_active(&self) -> bool {
        self.popup.is_focused()
    }

    /// Submenu visible/active.
    pub fn set_popup_active(&mut self, active: bool) {
        self.popup.focus.set(active);
    }
}

impl HasFocusFlag for MenuBarState {
    fn focus(&self) -> &FocusFlag {
        &self.menu.focus
    }

    fn area(&self) -> Rect {
        self.area
    }

    fn z_areas(&self) -> &[ZRect] {
        &self.z_areas
    }
}

impl HandleEvent<crossterm::event::Event, Popup, MenuOutcome> for MenuBarState {
    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: Popup) -> MenuOutcome {
        if !self.is_focused() {
            self.set_popup_active(false);
        }

        if let Some(selected) = self.menu.selected() {
            if self.popup_active() {
                match self.popup.handle(event, Popup) {
                    MenuOutcome::Selected(n) => MenuOutcome::MenuSelected(selected, n),
                    MenuOutcome::Activated(n) => MenuOutcome::MenuActivated(selected, n),
                    r => r,
                }
            } else {
                MenuOutcome::NotUsed
            }
        } else {
            MenuOutcome::NotUsed
        }
    }
}

impl HandleEvent<crossterm::event::Event, FocusKeys, MenuOutcome> for MenuBarState {
    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: FocusKeys) -> MenuOutcome {
        if !self.is_focused() {
            self.set_popup_active(false);
        }

        if self.menu.is_focused() {
            let old_selected = self.menu.selected();
            match self.menu.handle(event, FocusKeys) {
                r @ MenuOutcome::Selected(_) => {
                    if self.menu.selected == old_selected {
                        self.popup.flip_active();
                    } else {
                        self.popup.set_active(true);
                    }
                    r
                }
                r => r,
            }
        } else {
            self.menu.handle(event, MouseOnly)
        }
    }
}

impl HandleEvent<crossterm::event::Event, MouseOnly, MenuOutcome> for MenuBarState {
    fn handle(&mut self, event: &crossterm::event::Event, _qualifier: MouseOnly) -> MenuOutcome {
        if !self.is_focused() {
            self.set_popup_active(false);
        }

        flow!(if let Some(selected) = self.menu.selected() {
            if self.popup_active() {
                match self.popup.handle(event, MouseOnly) {
                    MenuOutcome::Selected(n) => MenuOutcome::MenuSelected(selected, n),
                    MenuOutcome::Activated(n) => MenuOutcome::MenuActivated(selected, n),
                    r => r,
                }
            } else {
                MenuOutcome::NotUsed
            }
        } else {
            MenuOutcome::NotUsed
        });

        let old_selected = self.menu.selected();
        match self.menu.handle(event, MouseOnly) {
            r @ MenuOutcome::Selected(_) => {
                if self.menu.selected == old_selected {
                    self.popup.flip_active();
                } else {
                    self.popup.set_active(true);
                }
                r
            }
            r => r,
        }
    }
}

/// Handle menu events. Keyboard events are processed if focus is true.
///
/// Attention:
/// For the event-handling of the popup-menus you need to call handle_popup_events().
pub fn handle_events(
    state: &mut MenuBarState,
    focus: bool,
    event: &crossterm::event::Event,
) -> MenuOutcome {
    state.menu.focus.set(focus);
    state.handle(event, FocusKeys)
}

/// Handle menu events for the popup-menu.
///
/// This one is separate, as it needs to be called before other event-handlers
/// to cope with overlapping regions.
///
/// focus - is the menubar focused?
pub fn handle_popup_events(
    state: &mut MenuBarState,
    focus: bool,
    event: &crossterm::event::Event,
) -> MenuOutcome {
    state.menu.focus.set(focus);
    state.handle(event, Popup)
}

/// Handle only mouse-events.
pub fn handle_mouse_events(
    state: &mut MenuLineState,
    event: &crossterm::event::Event,
) -> MenuOutcome {
    state.handle(event, MouseOnly)
}