KeyCallbackMachine.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/String.h>
  10. #include <AK/Vector.h>
  11. namespace Line {
  12. class Editor;
  13. struct Key {
  14. enum Modifier : int {
  15. None = 0,
  16. Alt = 1,
  17. };
  18. int modifiers { None };
  19. unsigned key { 0 };
  20. Key(unsigned c)
  21. : modifiers(None)
  22. , key(c) {};
  23. Key(unsigned c, int modifiers)
  24. : modifiers(modifiers)
  25. , key(c)
  26. {
  27. }
  28. bool operator==(const Key& other) const
  29. {
  30. return other.key == key && other.modifiers == modifiers;
  31. }
  32. bool operator!=(const Key& other) const
  33. {
  34. return !(*this == other);
  35. }
  36. };
  37. struct KeyCallback {
  38. KeyCallback(Function<bool(Editor&)> cb)
  39. : callback(move(cb))
  40. {
  41. }
  42. Function<bool(Editor&)> callback;
  43. };
  44. class KeyCallbackMachine {
  45. public:
  46. void register_key_input_callback(Vector<Key>, Function<bool(Editor&)> callback);
  47. void key_pressed(Editor&, Key);
  48. void interrupted(Editor&);
  49. bool should_process_last_pressed_key() const { return m_should_process_this_key; }
  50. private:
  51. HashMap<Vector<Key>, NonnullOwnPtr<KeyCallback>> m_key_callbacks;
  52. Vector<Vector<Key>> m_current_matching_keys;
  53. size_t m_sequence_length { 0 };
  54. bool m_should_process_this_key { true };
  55. };
  56. }
  57. namespace AK {
  58. template<>
  59. struct Traits<Line::Key> : public GenericTraits<Line::Key> {
  60. static constexpr bool is_trivial() { return true; }
  61. static unsigned hash(Line::Key k) { return pair_int_hash(k.key, k.modifiers); }
  62. };
  63. template<>
  64. struct Traits<Vector<Line::Key>> : public GenericTraits<Vector<Line::Key>> {
  65. static constexpr bool is_trivial() { return false; }
  66. static unsigned hash(const Vector<Line::Key>& ks)
  67. {
  68. unsigned h = 0;
  69. for (auto& k : ks)
  70. h ^= Traits<Line::Key>::hash(k);
  71. return h;
  72. }
  73. };
  74. }