Shortcut.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Geordie Hall <me@geordiehall.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Traits.h>
  9. #include <Kernel/API/KeyCode.h>
  10. #include <LibGUI/Event.h>
  11. namespace GUI {
  12. class Shortcut {
  13. public:
  14. Shortcut() = default;
  15. Shortcut(u8 modifiers, KeyCode key)
  16. : m_type(Type::Keyboard)
  17. , m_modifiers(modifiers)
  18. , m_keyboard_key(key)
  19. {
  20. }
  21. Shortcut(KeyCode key)
  22. : m_type(Type::Keyboard)
  23. , m_modifiers(0)
  24. , m_keyboard_key(key)
  25. {
  26. }
  27. Shortcut(u8 modifiers, MouseButton button)
  28. : m_type(Type::Mouse)
  29. , m_modifiers(modifiers)
  30. , m_mouse_button(button)
  31. {
  32. }
  33. Shortcut(MouseButton button)
  34. : m_type(Type::Mouse)
  35. , m_modifiers(0)
  36. , m_mouse_button(button)
  37. {
  38. }
  39. enum class Type : u8 {
  40. Keyboard,
  41. Mouse,
  42. };
  43. String to_string() const;
  44. Type type() const { return m_type; }
  45. bool is_valid() const { return m_type == Type::Keyboard ? (m_keyboard_key != Key_Invalid) : (m_mouse_button != MouseButton::None); }
  46. u8 modifiers() const { return m_modifiers; }
  47. KeyCode key() const
  48. {
  49. VERIFY(m_type == Type::Keyboard);
  50. return m_keyboard_key;
  51. }
  52. MouseButton mouse_button() const
  53. {
  54. VERIFY(m_type == Type::Mouse);
  55. return m_mouse_button;
  56. }
  57. bool operator==(Shortcut const& other) const
  58. {
  59. return m_modifiers == other.m_modifiers && m_type == other.m_type && m_keyboard_key == other.m_keyboard_key && m_mouse_button == other.m_mouse_button;
  60. }
  61. private:
  62. Type m_type { Type::Keyboard };
  63. u8 m_modifiers { 0 };
  64. KeyCode m_keyboard_key { KeyCode::Key_Invalid };
  65. MouseButton m_mouse_button { MouseButton::None };
  66. };
  67. }
  68. namespace AK {
  69. template<>
  70. struct Traits<GUI::Shortcut> : public GenericTraits<GUI::Shortcut> {
  71. static unsigned hash(const GUI::Shortcut& shortcut)
  72. {
  73. auto base_hash = pair_int_hash(shortcut.modifiers(), (u32)shortcut.type());
  74. if (shortcut.type() == GUI::Shortcut::Type::Keyboard) {
  75. return pair_int_hash(base_hash, shortcut.key());
  76. } else {
  77. return pair_int_hash(base_hash, shortcut.mouse_button());
  78. }
  79. }
  80. };
  81. }