Simple GUI Library
context_menu.cpp
Go to the documentation of this file.
1/**
2 * @author Nikita Mochalov (github.com/tralf-strues)
3 * @file context_menu.cpp
4 * @date 2021-11-10
5 *
6 * @copyright Copyright (c) 2021
7 */
8
9#include "scene/scene.h"
12
13namespace Sgl
14{
15 MenuItem::MenuItem(const char* label) : Button(new DefaultSkins::MenuItemSkin(), label) {}
16
17 const Insets ContextMenu::DEFAULT_PADDING = {2};
18 const Border ContextMenu::DEFAULT_BORDER = {1, 0xC9'C9'C9'66};
19 const ColorFill ContextMenu::DEFAULT_BACKGROUND_FILL = {0xEE'EE'EE'FF};
20 const Background ContextMenu::DEFAULT_BACKGROUND = {&DEFAULT_BACKGROUND_FILL};
21 const ShadowSpecification ContextMenu::DEFAULT_SHADOW = {{0, 3}, {1.05, 0.95}, 7, 0x22'22'22'18};
22
23 void MenuItem::setOnAction(ActionListener<MenuItem>* listener)
24 {
25 assert(listener);
26
27 Button::setOnAction(reinterpret_cast<ActionListener<Button>*>(listener));
28 }
29
30 class ContextMenuFocusFilter : public FocusListener<ContextMenu>
31 {
32 public:
34
35 virtual void onFocusLost(FocusLostEvent* event) override
36 {
37 if (getComponent()->isAutoHide() && !getComponent()->containsComponent(event->getNewFocus()))
38 {
39 LOG_LIB_INFO("Hide ContextMenu!");
40 getComponent()->hide();
41 }
42 }
43 };
44
45 ContextMenu::ContextMenu(Scene* scene, Component* sourceComponent)
46 : m_Source(sourceComponent)
47 {
48 assert(scene);
49
50 setPadding(DEFAULT_PADDING);
51 setBorder(&DEFAULT_BORDER);
52 setBackground(&DEFAULT_BACKGROUND);
53 setShadow(&DEFAULT_SHADOW);
54
55 setFillAcross(true);
56
57 setScene(scene);
58 scene->registerContextMenu(this);
59 getEventDispatcher()->attachFilter(FocusListener<ContextMenu>::EVENT_TYPES,
60 new ContextMenuFocusFilter(this));
61 }
62
63 ContextMenu::~ContextMenu()
64 {
65 VBox::~VBox();
66
67 m_Source->getScene()->detachContextMenu(this);
68 }
69
70 void ContextMenu::render(const Sml::Rectangle<int32_t>& targetRegion)
71 {
72 Container::render(targetRegion);
73 }
74
75 Component* ContextMenu::getSource() { return m_Source; }
76 void ContextMenu::setSource(Component* source) { m_Source = source; }
77
78 bool ContextMenu::isAutoHide() const { return m_AutoHide; }
79 void ContextMenu::setAutoHide(bool autoHide) { m_AutoHide = autoHide; }
80
81 void ContextMenu::show()
82 {
83 setVisibility(Component::Visibility::VISIBLE_INTERACTABLE);
84 requestFocus();
85 }
86
87 void ContextMenu::hide()
88 {
89 setVisibility(Component::Visibility::INVISIBLE_DISABLED);
90 }
91}