From 881581820f2af910f2420bf1fcef6ae9a8a57276 Mon Sep 17 00:00:00 2001 From: Tim Ledbetter Date: Thu, 28 Sep 2023 01:03:32 +0100 Subject: [PATCH] GameOfLife: Allow pressing escape to clear the selected pattern --- Userland/Games/GameOfLife/BoardWidget.cpp | 37 ++++++++++++++++------- Userland/Games/GameOfLife/BoardWidget.h | 2 ++ 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/Userland/Games/GameOfLife/BoardWidget.cpp b/Userland/Games/GameOfLife/BoardWidget.cpp index d01780650a..1e78ad99e6 100644 --- a/Userland/Games/GameOfLife/BoardWidget.cpp +++ b/Userland/Games/GameOfLife/BoardWidget.cpp @@ -78,11 +78,7 @@ void BoardWidget::set_running(bool running) if (running == m_running) return; - if (m_selected_pattern) { - m_selected_pattern = nullptr; - if (on_pattern_selection_state_change) - on_pattern_selection_state_change(); - } + clear_selected_pattern(); m_running = running; @@ -206,12 +202,7 @@ void BoardWidget::mousedown_event(GUI::MouseEvent& event) if (m_selected_pattern) { place_pattern(row, column); if (!event.ctrl()) { - m_selected_pattern = nullptr; - if (on_pattern_selection_state_change) - on_pattern_selection_state_change(); - - if (m_pattern_preview_timer->is_active()) - m_pattern_preview_timer->stop(); + clear_selected_pattern(); } } else { toggle_cell(row, column); @@ -219,6 +210,17 @@ void BoardWidget::mousedown_event(GUI::MouseEvent& event) } } +void BoardWidget::keydown_event(GUI::KeyEvent& event) +{ + if (event.key() == Key_Escape) { + clear_selected_pattern(); + update(); + return; + } + + event.ignore(); +} + void BoardWidget::context_menu_event(GUI::ContextMenuEvent& event) { if (!m_context_menu) { @@ -287,6 +289,19 @@ void BoardWidget::place_pattern(size_t row, size_t column) } } +void BoardWidget::clear_selected_pattern() +{ + if (!m_selected_pattern) + return; + + m_selected_pattern = nullptr; + if (on_pattern_selection_state_change) + on_pattern_selection_state_change(); + + if (m_pattern_preview_timer->is_active()) + m_pattern_preview_timer->stop(); +} + void BoardWidget::setup_patterns() { auto add_pattern = [&](auto name, NonnullOwnPtr pattern) { diff --git a/Userland/Games/GameOfLife/BoardWidget.h b/Userland/Games/GameOfLife/BoardWidget.h index 77f48151d7..42dae40336 100644 --- a/Userland/Games/GameOfLife/BoardWidget.h +++ b/Userland/Games/GameOfLife/BoardWidget.h @@ -26,6 +26,7 @@ public: virtual void mousemove_event(GUI::MouseEvent&) override; virtual void mouseup_event(GUI::MouseEvent&) override; virtual void mousedown_event(GUI::MouseEvent&) override; + virtual void keydown_event(GUI::KeyEvent&) override; virtual void context_menu_event(GUI::ContextMenuEvent&) override; void set_toggling_cells(bool toggling) @@ -74,6 +75,7 @@ private: BoardWidget(size_t rows, size_t columns); void setup_patterns(); void place_pattern(size_t row, size_t column); + void clear_selected_pattern(); bool m_toggling_cells { false }; Board::RowAndColumn m_last_cell_toggled {};