From b150c814fe80b5ac92ea50fc356eb4ff4f340e82 Mon Sep 17 00:00:00 2001 From: Ritchie Cunningham Date: Sun, 19 Oct 2025 14:30:59 +0100 Subject: [PATCH] [Add] Command history for terminal. --- client/src/terminal.cpp | 35 ++++++++++++++++++++++++++++++++--- client/src/terminal.h | 2 ++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/client/src/terminal.cpp b/client/src/terminal.cpp index b9378ad..f41ff61 100644 --- a/client/src/terminal.cpp +++ b/client/src/terminal.cpp @@ -11,8 +11,8 @@ #include "ui/window_action.h" Terminal::Terminal(GameState* game_state) - : _game_state(game_state), _should_close(false), _scroll_offset(0), - _prompt(""), _pending_action({ActionType::NONE}) { + : _game_state(game_state), _should_close(false), _command_history_index(0), + _scroll_offset(0), _prompt(""), _pending_action({ActionType::NONE}) { _input_view = std::make_unique(&_input_buffer, false, false); } @@ -54,6 +54,11 @@ WindowAction Terminal::get_pending_action(void) { void Terminal::_on_ret_press(void) { std::string command = _input_buffer.get_line(0); + if(!command.empty()) { + _command_history.push_back(command); + } + _command_history_index = _command_history.size(); + _input_buffer.clear(); if(command == "clear") { @@ -79,7 +84,31 @@ void Terminal::_on_ret_press(void) { void Terminal::handle_input(SDL_Event* event, int window_x, int window_y, int window_gl_y) { /* Pass input to TextView; if true, RET was pressed. */ - if(_input_view->handle_event(event)) { _on_ret_press(); } + if(event->type == SDL_EVENT_KEY_DOWN) { + switch(event->key.key) { + case SDLK_UP: + if(!_command_history.empty()) { + _command_history_index = std::max(0, _command_history_index-1); + _input_buffer.set_text(_command_history[_command_history_index]); + } + break; + case SDLK_DOWN: + if(!_command_history.empty()) { + _command_history_index = + std::min((int)_command_history.size(), _command_history_index+1); + if(_command_history_index < (int)_command_history.size()) { + _input_buffer.set_text(_command_history[_command_history_index]); + } else { + _input_buffer.clear(); + } + } + break; + default: + if(_input_view->handle_event(event)) { _on_ret_press(); } + } + } else { + if(_input_view->handle_event(event)) { _on_ret_press(); } + } } void Terminal::scroll(int amount, int win_content_height) { diff --git a/client/src/terminal.h b/client/src/terminal.h index d422b45..988f757 100644 --- a/client/src/terminal.h +++ b/client/src/terminal.h @@ -31,6 +31,8 @@ private: void _on_ret_press(void); bool _should_close; + std::vector _command_history; + int _command_history_index; std::vector _history; int _scroll_offset; std::string _prompt;