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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Menu bar functionality (very basic so far).
//!
//! Usage:
//! ```
//! fn show_menu(ui: &mut egui::Ui) {
//!     use egui::{menu, Button};
//!
//!     menu::bar(ui, |ui| {
//!         ui.menu_button("File", |ui| {
//!             if ui.button("Open").clicked() {
//!                 // …
//!             }
//!         });
//!     });
//! }
//! ```

use super::{
    style::WidgetVisuals, Align, Context, Id, InnerResponse, PointerState, Pos2, Rect, Response,
    Sense, TextStyle, Ui, Vec2,
};
use crate::{widgets::*, *};
use epaint::mutex::RwLock;
use std::sync::Arc;

/// What is saved between frames.
#[derive(Clone, Default)]
pub(crate) struct BarState {
    open_menu: MenuRootManager,
}

impl BarState {
    fn load(ctx: &Context, bar_id: Id) -> Self {
        ctx.data_mut(|d| d.get_temp::<Self>(bar_id).unwrap_or_default())
    }

    fn store(self, ctx: &Context, bar_id: Id) {
        ctx.data_mut(|d| d.insert_temp(bar_id, self));
    }

    /// Show a menu at pointer if primary-clicked response.
    /// Should be called from [`Context`] on a [`Response`]
    pub fn bar_menu<R>(
        &mut self,
        response: &Response,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> Option<InnerResponse<R>> {
        MenuRoot::stationary_click_interaction(response, &mut self.open_menu, response.id);
        self.open_menu.show(response, add_contents)
    }

    pub(crate) fn has_root(&self) -> bool {
        self.open_menu.inner.is_some()
    }
}

impl std::ops::Deref for BarState {
    type Target = MenuRootManager;

    fn deref(&self) -> &Self::Target {
        &self.open_menu
    }
}

impl std::ops::DerefMut for BarState {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.open_menu
    }
}

fn set_menu_style(style: &mut Style) {
    style.spacing.button_padding = vec2(2.0, 0.0);
    style.visuals.widgets.active.bg_stroke = Stroke::NONE;
    style.visuals.widgets.hovered.bg_stroke = Stroke::NONE;
    style.visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT;
    style.visuals.widgets.inactive.bg_stroke = Stroke::NONE;
}

/// The menu bar goes well in a [`TopBottomPanel::top`],
/// but can also be placed in a [`Window`].
/// In the latter case you may want to wrap it in [`Frame`].
pub fn bar<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
    ui.horizontal(|ui| {
        set_menu_style(ui.style_mut());

        // Take full width and fixed height:
        let height = ui.spacing().interact_size.y;
        ui.set_min_size(vec2(ui.available_width(), height));

        add_contents(ui)
    })
}

/// Construct a top level menu in a menu bar. This would be e.g. "File", "Edit" etc.
///
/// Responds to primary clicks.
///
/// Returns `None` if the menu is not open.
pub fn menu_button<R>(
    ui: &mut Ui,
    title: impl Into<WidgetText>,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
    stationary_menu_impl(ui, title, Box::new(add_contents))
}

/// Construct a top level menu with an image in a menu bar. This would be e.g. "File", "Edit" etc.
///
/// Responds to primary clicks.
///
/// Returns `None` if the menu is not open.
pub fn menu_image_button<R>(
    ui: &mut Ui,
    image_button: ImageButton<'_>,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
    stationary_menu_image_impl(ui, image_button, Box::new(add_contents))
}

/// Construct a nested sub menu in another menu.
///
/// Opens on hover.
///
/// Returns `None` if the menu is not open.
pub(crate) fn submenu_button<R>(
    ui: &mut Ui,
    parent_state: Arc<RwLock<MenuState>>,
    title: impl Into<WidgetText>,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> InnerResponse<Option<R>> {
    SubMenu::new(parent_state, title).show(ui, add_contents)
}

/// wrapper for the contents of every menu.
pub(crate) fn menu_ui<'c, R>(
    ctx: &Context,
    menu_id: impl Into<Id>,
    menu_state_arc: &Arc<RwLock<MenuState>>,
    add_contents: impl FnOnce(&mut Ui) -> R + 'c,
) -> InnerResponse<R> {
    let pos = {
        let mut menu_state = menu_state_arc.write();
        menu_state.entry_count = 0;
        menu_state.rect.min
    };

    let area = Area::new(menu_id)
        .order(Order::Foreground)
        .fixed_pos(pos)
        .constrain_to(ctx.screen_rect())
        .interactable(true);

    area.show(ctx, |ui| {
        set_menu_style(ui.style_mut());

        let frame = Frame::menu(ui.style()).show(ui, |ui| {
            ui.set_max_width(ui.spacing().menu_width);
            ui.set_menu_state(Some(menu_state_arc.clone()));
            ui.with_layout(Layout::top_down_justified(Align::LEFT), add_contents)
                .inner
        });

        menu_state_arc.write().rect = frame.response.rect;

        frame.inner
    })
}

/// Build a top level menu with a button.
///
/// Responds to primary clicks.
fn stationary_menu_impl<'c, R>(
    ui: &mut Ui,
    title: impl Into<WidgetText>,
    add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<Option<R>> {
    let title = title.into();
    let bar_id = ui.id();
    let menu_id = bar_id.with(title.text());

    let mut bar_state = BarState::load(ui.ctx(), bar_id);

    let mut button = Button::new(title);

    if bar_state.open_menu.is_menu_open(menu_id) {
        button = button.fill(ui.visuals().widgets.open.weak_bg_fill);
        button = button.stroke(ui.visuals().widgets.open.bg_stroke);
    }

    let button_response = ui.add(button);
    let inner = bar_state.bar_menu(&button_response, add_contents);

    bar_state.store(ui.ctx(), bar_id);
    InnerResponse::new(inner.map(|r| r.inner), button_response)
}

/// Build a top level menu with an image button.
///
/// Responds to primary clicks.
fn stationary_menu_image_impl<'c, R>(
    ui: &mut Ui,
    image_button: ImageButton<'_>,
    add_contents: Box<dyn FnOnce(&mut Ui) -> R + 'c>,
) -> InnerResponse<Option<R>> {
    let bar_id = ui.id();

    let mut bar_state = BarState::load(ui.ctx(), bar_id);
    let button_response = ui.add(image_button);
    let inner = bar_state.bar_menu(&button_response, add_contents);

    bar_state.store(ui.ctx(), bar_id);
    InnerResponse::new(inner.map(|r| r.inner), button_response)
}

pub(crate) const CONTEXT_MENU_ID_STR: &str = "__egui::context_menu";

/// Response to secondary clicks (right-clicks) by showing the given menu.
pub(crate) fn context_menu(
    response: &Response,
    add_contents: impl FnOnce(&mut Ui),
) -> Option<InnerResponse<()>> {
    let menu_id = Id::new(CONTEXT_MENU_ID_STR);
    let mut bar_state = BarState::load(&response.ctx, menu_id);

    MenuRoot::context_click_interaction(response, &mut bar_state, response.id);
    let inner_response = bar_state.show(response, add_contents);

    bar_state.store(&response.ctx, menu_id);
    inner_response
}

/// Stores the state for the context menu.
#[derive(Clone, Default)]
pub(crate) struct MenuRootManager {
    inner: Option<MenuRoot>,
}

impl MenuRootManager {
    /// Show a menu at pointer if right-clicked response.
    /// Should be called from [`Context`] on a [`Response`]
    pub fn show<R>(
        &mut self,
        response: &Response,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> Option<InnerResponse<R>> {
        if let Some(root) = self.inner.as_mut() {
            let (menu_response, inner_response) = root.show(response, add_contents);
            if MenuResponse::Close == menu_response {
                self.inner = None;
            }
            inner_response
        } else {
            None
        }
    }

    fn is_menu_open(&self, id: Id) -> bool {
        self.inner.as_ref().map(|m| m.id) == Some(id)
    }
}

impl std::ops::Deref for MenuRootManager {
    type Target = Option<MenuRoot>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::ops::DerefMut for MenuRootManager {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// Menu root associated with an Id from a Response
#[derive(Clone)]
pub(crate) struct MenuRoot {
    pub menu_state: Arc<RwLock<MenuState>>,
    pub id: Id,
}

impl MenuRoot {
    pub fn new(position: Pos2, id: Id) -> Self {
        Self {
            menu_state: Arc::new(RwLock::new(MenuState::new(position))),
            id,
        }
    }

    pub fn show<R>(
        &mut self,
        response: &Response,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> (MenuResponse, Option<InnerResponse<R>>) {
        if self.id == response.id {
            let inner_response =
                MenuState::show(&response.ctx, &self.menu_state, self.id, add_contents);
            let menu_state = self.menu_state.read();

            if menu_state.response.is_close() {
                return (MenuResponse::Close, Some(inner_response));
            }
        }
        (MenuResponse::Stay, None)
    }

    /// Interaction with a stationary menu, i.e. fixed in another Ui.
    ///
    /// Responds to primary clicks.
    fn stationary_interaction(
        response: &Response,
        root: &mut MenuRootManager,
        id: Id,
    ) -> MenuResponse {
        if (response.clicked() && root.is_menu_open(id))
            || response.ctx.input(|i| i.key_pressed(Key::Escape))
        {
            // menu open and button clicked or esc pressed
            return MenuResponse::Close;
        } else if (response.clicked() && !root.is_menu_open(id))
            || (response.hovered() && root.is_some())
        {
            // menu not open and button clicked
            // or button hovered while other menu is open
            let mut pos = response.rect.left_bottom();
            if let Some(root) = root.inner.as_mut() {
                let menu_rect = root.menu_state.read().rect;
                let screen_rect = response.ctx.input(|i| i.screen_rect);

                if pos.y + menu_rect.height() > screen_rect.max.y {
                    pos.y = screen_rect.max.y - menu_rect.height() - response.rect.height();
                }

                if pos.x + menu_rect.width() > screen_rect.max.x {
                    pos.x = screen_rect.max.x - menu_rect.width();
                }
            }

            return MenuResponse::Create(pos, id);
        } else if response
            .ctx
            .input(|i| i.pointer.any_pressed() && i.pointer.primary_down())
        {
            if let Some(pos) = response.ctx.input(|i| i.pointer.interact_pos()) {
                if let Some(root) = root.inner.as_mut() {
                    if root.id == id {
                        // pressed somewhere while this menu is open
                        let in_menu = root.menu_state.read().area_contains(pos);
                        if !in_menu {
                            return MenuResponse::Close;
                        }
                    }
                }
            }
        }
        MenuResponse::Stay
    }

    /// Interaction with a context menu (secondary clicks).
    fn context_interaction(response: &Response, root: &mut Option<Self>, id: Id) -> MenuResponse {
        let response = response.interact(Sense::click());
        response.ctx.input(|input| {
            let pointer = &input.pointer;
            if let Some(pos) = pointer.interact_pos() {
                let mut in_old_menu = false;
                let mut destroy = false;
                if let Some(root) = root {
                    in_old_menu = root.menu_state.read().area_contains(pos);
                    destroy = !in_old_menu && pointer.any_pressed() && root.id == response.id;
                }
                if !in_old_menu {
                    if response.hovered() && response.secondary_clicked() {
                        return MenuResponse::Create(pos, id);
                    } else if (response.hovered() && pointer.primary_down()) || destroy {
                        return MenuResponse::Close;
                    }
                }
            }
            MenuResponse::Stay
        })
    }

    fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) {
        match menu_response {
            MenuResponse::Create(pos, id) => {
                root.inner = Some(Self::new(pos, id));
            }
            MenuResponse::Close => root.inner = None,
            MenuResponse::Stay => {}
        }
    }

    /// Respond to secondary (right) clicks.
    pub fn context_click_interaction(response: &Response, root: &mut MenuRootManager, id: Id) {
        let menu_response = Self::context_interaction(response, root, id);
        Self::handle_menu_response(root, menu_response);
    }

    // Responds to primary clicks.
    pub fn stationary_click_interaction(response: &Response, root: &mut MenuRootManager, id: Id) {
        let menu_response = Self::stationary_interaction(response, root, id);
        Self::handle_menu_response(root, menu_response);
    }
}

#[derive(Copy, Clone, PartialEq)]
pub(crate) enum MenuResponse {
    Close,
    Stay,
    Create(Pos2, Id),
}

impl MenuResponse {
    pub fn is_close(&self) -> bool {
        *self == Self::Close
    }
}

pub struct SubMenuButton {
    text: WidgetText,
    icon: WidgetText,
    index: usize,
}

impl SubMenuButton {
    /// The `icon` can be an emoji (e.g. `⏵` right arrow), shown right of the label
    fn new(text: impl Into<WidgetText>, icon: impl Into<WidgetText>, index: usize) -> Self {
        Self {
            text: text.into(),
            icon: icon.into(),
            index,
        }
    }

    fn visuals<'a>(
        ui: &'a Ui,
        response: &Response,
        menu_state: &MenuState,
        sub_id: Id,
    ) -> &'a WidgetVisuals {
        if menu_state.is_open(sub_id) && !response.hovered() {
            &ui.style().visuals.widgets.open
        } else {
            ui.style().interact(response)
        }
    }

    #[inline]
    pub fn icon(mut self, icon: impl Into<WidgetText>) -> Self {
        self.icon = icon.into();
        self
    }

    pub(crate) fn show(self, ui: &mut Ui, menu_state: &MenuState, sub_id: Id) -> Response {
        let Self { text, icon, .. } = self;

        let text_style = TextStyle::Button;
        let sense = Sense::click();

        let button_padding = ui.spacing().button_padding;
        let total_extra = button_padding + button_padding;
        let text_available_width = ui.available_width() - total_extra.x;
        let text_galley =
            text.into_galley(ui, Some(true), text_available_width, text_style.clone());

        let icon_available_width = text_available_width - text_galley.size().x;
        let icon_galley = icon.into_galley(ui, Some(true), icon_available_width, text_style);
        let text_and_icon_size = Vec2::new(
            text_galley.size().x + icon_galley.size().x,
            text_galley.size().y.max(icon_galley.size().y),
        );
        let mut desired_size = text_and_icon_size + 2.0 * button_padding;
        desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y);

        let (rect, response) = ui.allocate_at_least(desired_size, sense);
        response.widget_info(|| {
            crate::WidgetInfo::labeled(crate::WidgetType::Button, text_galley.text())
        });

        if ui.is_rect_visible(rect) {
            let visuals = Self::visuals(ui, &response, menu_state, sub_id);
            let text_pos = Align2::LEFT_CENTER
                .align_size_within_rect(text_galley.size(), rect.shrink2(button_padding))
                .min;
            let icon_pos = Align2::RIGHT_CENTER
                .align_size_within_rect(icon_galley.size(), rect.shrink2(button_padding))
                .min;

            if ui.visuals().button_frame {
                ui.painter().rect_filled(
                    rect.expand(visuals.expansion),
                    visuals.rounding,
                    visuals.weak_bg_fill,
                );
            }

            let text_color = visuals.text_color();
            ui.painter().galley(text_pos, text_galley, text_color);
            ui.painter().galley(icon_pos, icon_galley, text_color);
        }
        response
    }
}

pub struct SubMenu {
    button: SubMenuButton,
    parent_state: Arc<RwLock<MenuState>>,
}

impl SubMenu {
    fn new(parent_state: Arc<RwLock<MenuState>>, text: impl Into<WidgetText>) -> Self {
        let index = parent_state.write().next_entry_index();
        Self {
            button: SubMenuButton::new(text, "⏵", index),
            parent_state,
        }
    }

    pub fn show<R>(
        self,
        ui: &mut Ui,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> InnerResponse<Option<R>> {
        let sub_id = ui.id().with(self.button.index);
        let response = self.button.show(ui, &self.parent_state.read(), sub_id);
        self.parent_state
            .write()
            .submenu_button_interaction(ui, sub_id, &response);
        let inner = self
            .parent_state
            .write()
            .show_submenu(ui.ctx(), sub_id, add_contents);
        InnerResponse::new(inner, response)
    }
}

pub(crate) struct MenuState {
    /// The opened sub-menu and its [`Id`]
    sub_menu: Option<(Id, Arc<RwLock<MenuState>>)>,

    /// Bounding box of this menu (without the sub-menu)
    pub rect: Rect,

    /// Used to check if any menu in the tree wants to close
    pub response: MenuResponse,

    /// Used to hash different [`Id`]s for sub-menus
    entry_count: usize,
}

impl MenuState {
    pub fn new(position: Pos2) -> Self {
        Self {
            rect: Rect::from_min_size(position, Vec2::ZERO),
            sub_menu: None,
            response: MenuResponse::Stay,
            entry_count: 0,
        }
    }

    /// Close menu hierarchy.
    pub fn close(&mut self) {
        self.response = MenuResponse::Close;
    }

    pub fn show<R>(
        ctx: &Context,
        menu_state: &Arc<RwLock<Self>>,
        id: Id,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> InnerResponse<R> {
        crate::menu::menu_ui(ctx, id, menu_state, add_contents)
    }

    fn show_submenu<R>(
        &mut self,
        ctx: &Context,
        id: Id,
        add_contents: impl FnOnce(&mut Ui) -> R,
    ) -> Option<R> {
        let (sub_response, response) = self.submenu(id).map(|sub| {
            let inner_response = Self::show(ctx, sub, id, add_contents);
            (sub.read().response, inner_response.inner)
        })?;
        self.cascade_close_response(sub_response);
        Some(response)
    }

    /// Check if position is in the menu hierarchy's area.
    pub fn area_contains(&self, pos: Pos2) -> bool {
        self.rect.contains(pos)
            || self
                .sub_menu
                .as_ref()
                .map_or(false, |(_, sub)| sub.read().area_contains(pos))
    }

    fn next_entry_index(&mut self) -> usize {
        self.entry_count += 1;
        self.entry_count - 1
    }

    /// Sense button interaction opening and closing submenu.
    fn submenu_button_interaction(&mut self, ui: &Ui, sub_id: Id, button: &Response) {
        let pointer = ui.input(|i| i.pointer.clone());
        let open = self.is_open(sub_id);
        if self.moving_towards_current_submenu(&pointer) {
            // ensure to repaint once even when pointer is not moving
            ui.ctx().request_repaint();
        } else if !open && button.hovered() {
            let pos = button.rect.right_top();
            self.open_submenu(sub_id, pos);
        }
    }

    /// Check if `dir` points from `pos` towards left side of `rect`.
    fn points_at_left_of_rect(pos: Pos2, dir: Vec2, rect: Rect) -> bool {
        let vel_a = dir.angle();
        let top_a = (rect.left_top() - pos).angle();
        let bottom_a = (rect.left_bottom() - pos).angle();
        bottom_a - vel_a >= 0.0 && top_a - vel_a <= 0.0
    }

    /// Check if pointer is moving towards current submenu.
    fn moving_towards_current_submenu(&self, pointer: &PointerState) -> bool {
        if pointer.is_still() {
            return false;
        }
        if let Some(sub_menu) = self.current_submenu() {
            if let Some(pos) = pointer.hover_pos() {
                return Self::points_at_left_of_rect(pos, pointer.velocity(), sub_menu.read().rect);
            }
        }
        false
    }

    /// Cascade close response to menu root.
    fn cascade_close_response(&mut self, response: MenuResponse) {
        if response.is_close() {
            self.response = response;
        }
    }

    fn is_open(&self, id: Id) -> bool {
        self.sub_id() == Some(id)
    }

    fn sub_id(&self) -> Option<Id> {
        self.sub_menu.as_ref().map(|(id, _)| *id)
    }

    fn current_submenu(&self) -> Option<&Arc<RwLock<Self>>> {
        self.sub_menu.as_ref().map(|(_, sub)| sub)
    }

    fn submenu(&mut self, id: Id) -> Option<&Arc<RwLock<Self>>> {
        self.sub_menu
            .as_ref()
            .and_then(|(k, sub)| if id == *k { Some(sub) } else { None })
    }

    /// Open submenu at position, if not already open.
    fn open_submenu(&mut self, id: Id, pos: Pos2) {
        if !self.is_open(id) {
            self.sub_menu = Some((id, Arc::new(RwLock::new(Self::new(pos)))));
        }
    }
}