KeyCallbackMachine.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/Vector.h>
  10. namespace Line {
  11. class Editor;
  12. struct Key {
  13. enum Modifier : int {
  14. None = 0,
  15. Alt = 1,
  16. };
  17. int modifiers { None };
  18. unsigned key { 0 };
  19. Key(unsigned c)
  20. : modifiers(None)
  21. , key(c) {};
  22. Key(unsigned c, int modifiers)
  23. : modifiers(modifiers)
  24. , key(c)
  25. {
  26. }
  27. bool operator==(Key const& other) const
  28. {
  29. return other.key == key && other.modifiers == modifiers;
  30. }
  31. };
  32. struct KeyCallback {
  33. KeyCallback(Function<bool(Editor&)> cb)
  34. : callback(move(cb))
  35. {
  36. }
  37. Function<bool(Editor&)> callback;
  38. };
  39. class KeyCallbackMachine {
  40. public:
  41. void register_key_input_callback(Vector<Key>, Function<bool(Editor&)> callback);
  42. void key_pressed(Editor&, Key);
  43. void interrupted(Editor&);
  44. bool should_process_last_pressed_key() const { return m_should_process_this_key; }
  45. private:
  46. HashMap<Vector<Key>, NonnullOwnPtr<KeyCallback>> m_key_callbacks;
  47. Vector<Vector<Key>> m_current_matching_keys;
  48. size_t m_sequence_length { 0 };
  49. bool m_should_process_this_key { true };
  50. };
  51. }
  52. namespace AK {
  53. template<>
  54. struct Traits<Line::Key> : public DefaultTraits<Line::Key> {
  55. static constexpr bool is_trivial() { return true; }
  56. static unsigned hash(Line::Key k) { return pair_int_hash(k.key, k.modifiers); }
  57. };
  58. template<>
  59. struct Traits<Vector<Line::Key>> : public DefaultTraits<Vector<Line::Key>> {
  60. static constexpr bool is_trivial() { return false; }
  61. static unsigned hash(Vector<Line::Key> const& ks)
  62. {
  63. unsigned h = 0;
  64. for (auto& k : ks)
  65. h ^= Traits<Line::Key>::hash(k);
  66. return h;
  67. }
  68. };
  69. }