From b74611d2b20fc071b8a699f2ce25e61f60118d6e Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 22 May 2022 23:13:29 +0200 Subject: refactor: improve input handling & remove commands --- src/engine/user/input.cpp | 68 +++++++++++++++++------------------------------ 1 file changed, 24 insertions(+), 44 deletions(-) (limited to 'src/engine/user/input.cpp') diff --git a/src/engine/user/input.cpp b/src/engine/user/input.cpp index 7e9fe22..ac6d660 100644 --- a/src/engine/user/input.cpp +++ b/src/engine/user/input.cpp @@ -3,66 +3,46 @@ #include #include -void InputHandler::listen() const noexcept -{ - char character = 0; +#include - while (!std::cin.read(&character, 1).fail()) +void UserInputObserver::listen() noexcept +{ + while (true) { - notify_subscribers(character, nullptr); - } -} + char character = 0; -void InputHandler::subscribe( - const Event &event, - const std::shared_ptr> &subscriber) noexcept -{ - auto event_index = _event_as_index(event); + if (std::cin.read(&character, 1).fail()) + { + continue; + } - _subscribers.at(event_index).push_back(subscriber); -} + _currently_pressed_mutex.lock(); -void InputHandler::notify_subscribers(const Event &event, const Context &context) - const noexcept -{ - auto event_index = _event_as_index(event); + if (character != _currently_pressed) + { + _currently_pressed = character; + } - for (const auto &subscriber : _subscribers.at(event_index)) - { - subscriber->update(context); + _currently_pressed_mutex.unlock(); } } -void InputHandler::enter_raw_mode() noexcept +bool UserInputObserver::is_key_pressed(Key key) noexcept { - if (_original_termios == nullptr) - { - _original_termios = std::make_shared(); - } + _currently_pressed_mutex.lock(); - tcgetattr(STDIN_FILENO, _original_termios.get()); + const auto is_key_pressed = key == _currently_pressed; - auto raw_termios = termios(*_original_termios); + _currently_pressed_mutex.unlock(); - raw_termios.c_lflag &= static_cast(~(ECHO | ICANON | ISIG)); - - tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_termios); + return is_key_pressed; } -void InputHandler::leave_raw_mode() noexcept +void UserInputObserver::clear_currently_pressed() noexcept { - if (_original_termios == nullptr) - { - return; - } - - tcsetattr(STDIN_FILENO, TCSAFLUSH, _original_termios.get()); + _currently_pressed_mutex.lock(); - _original_termios = nullptr; -} + _currently_pressed = 0; -auto InputHandler::_event_as_index(const Event &event) noexcept - -> InputHandler::SubscribersSizeType -{ - return static_cast(static_cast(event)); + _currently_pressed_mutex.unlock(); } -- cgit v1.2.3-18-g5258