libui: Add support for keyboard shortcuts natively

This commit is contained in:
apio 2024-04-15 19:33:32 +02:00
parent 1176e64a7c
commit 2f56a52489
Signed by: apio
GPG Key ID: B8A7D06E42258954
2 changed files with 39 additions and 0 deletions

View File

@ -26,6 +26,17 @@ namespace ui
System, System,
}; };
struct [[gnu::packed]] Shortcut
{
moon::KeyCode key;
int modifiers;
bool operator==(const Shortcut& other) const
{
return key == other.key && modifiers == other.modifiers;
}
};
class Window class Window
{ {
public: public:
@ -62,6 +73,8 @@ namespace ui
Result<ui::EventResult> handle_mouse_buttons(ui::Point position, int buttons); Result<ui::EventResult> handle_mouse_buttons(ui::Point position, int buttons);
Result<ui::EventResult> handle_key_event(const ui::KeyEventRequest& request); Result<ui::EventResult> handle_key_event(const ui::KeyEventRequest& request);
Result<void> add_keyboard_shortcut(ui::Shortcut shortcut, bool intercept, os::Function<ui::Shortcut>&& action);
int id() const int id() const
{ {
return m_id; return m_id;
@ -80,6 +93,14 @@ namespace ui
Option<int> m_old_mouse_buttons; Option<int> m_old_mouse_buttons;
bool m_decorated { false }; bool m_decorated { false };
struct ShortcutAction
{
bool intercept;
os::Function<Shortcut> action;
};
HashMap<Shortcut, ShortcutAction> m_shortcuts;
Result<void> draw_titlebar(); Result<void> draw_titlebar();
}; };
} }

View File

@ -212,7 +212,25 @@ namespace ui
Result<ui::EventResult> Window::handle_key_event(const ui::KeyEventRequest& request) Result<ui::EventResult> Window::handle_key_event(const ui::KeyEventRequest& request)
{ {
if (request.pressed)
{
auto* shortcut = m_shortcuts.try_get_ref({ request.code, request.modifiers });
if (shortcut)
{
shortcut->action({ request.code, request.modifiers });
if (shortcut->intercept) return ui::EventResult::DidHandle;
}
}
if (!m_main_widget) return ui::EventResult::DidNotHandle; if (!m_main_widget) return ui::EventResult::DidNotHandle;
return m_main_widget->handle_key_event(request); return m_main_widget->handle_key_event(request);
} }
Result<void> Window::add_keyboard_shortcut(ui::Shortcut shortcut, bool intercept,
os::Function<ui::Shortcut>&& action)
{
TRY(m_shortcuts.try_set(shortcut, { intercept, move(action) }));
return {};
}
} }