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