Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[20761] Add command history navigation in user interface #128

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cpp_utils/include/cpp_utils/event/StdinEventHandler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <thread>

#include <cpp_utils/event/EventHandler.hpp>
#include <cpp_utils/history/CommandHistoryHandler.hpp>
#include <cpp_utils/library/library_dll.h>
#include <cpp_utils/time/time_utils.hpp>
#include <cpp_utils/wait/CounterWaitHandler.hpp>
Expand Down Expand Up @@ -83,6 +84,13 @@ class StdinEventHandler : public EventHandler<std::string>

protected:

/**
* @brief TODO
*/
CPP_UTILS_DllAPI
void set_terminal_mode_(
bool enable) noexcept;

/**
* @brief Internal thread to read from \c source_ .
*
Expand Down Expand Up @@ -120,6 +128,8 @@ class StdinEventHandler : public EventHandler<std::string>
//! Counter that contains the number of times the thread is allowed to start waiting for data from source_.
CounterWaitHandler activation_times_;

history::CommandHistoryHandler history_handler_;

/**
* @brief istream source from where to read.
*
Expand Down
55 changes: 55 additions & 0 deletions cpp_utils/include/cpp_utils/history/CommandHistoryHandler.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include <string>
#include <vector>

#include <cpp_utils/library/library_dll.h>

namespace eprosima {
namespace utils {
namespace history {

class CommandHistoryHandler
{
public:

/**
* @brief TODO
*/
CPP_UTILS_DllAPI
CommandHistoryHandler();

CPP_UTILS_DllAPI
void add_command(
const std::string& command);

CPP_UTILS_DllAPI
std::string get_previous_command();

CPP_UTILS_DllAPI
std::string get_next_command();

private:

std::vector<std::string> command_history_;

size_t current_index_;
};

} /* namespace history */
} /* namespace utils */
} /* namespace eprosima */
151 changes: 142 additions & 9 deletions cpp_utils/src/cpp/event/StdinEventHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,17 @@

#include <thread>

#include <cpp_utils/Log.hpp>
#if defined(_WIN32) || defined(_WIN64)
#define NOMINMAX
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif

#include <cpp_utils/event/StdinEventHandler.hpp>
#include <cpp_utils/exception/InitializationException.hpp>
#include <cpp_utils/Log.hpp>

namespace eprosima {
namespace utils {
Expand Down Expand Up @@ -44,26 +52,151 @@ void StdinEventHandler::read_one_more_line()
++activation_times_;
}

void StdinEventHandler::set_terminal_mode_(bool enable) noexcept
{
#if defined(_WIN32) || defined(_WIN64)
static DWORD old_mode;
static HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);

if (enable)
{
// Save actual configuration in 'old_mode'
GetConsoleMode(hStdin, &old_mode);

// Modify line mode flags
// - ENABLE_ECHO_INPUT: Desactivate echo (does not print what the user writes on terminal)
// - ENABLE_LINE_INPUT: Desactivate line mode (process each character)
DWORD new_mode = old_mode;
new_mode &= ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
SetConsoleMode(hStdin, new_mode);
std::cout << "New console mode set" << std::endl;
}
else
{
// Restore original terminal configuration
SetConsoleMode(hStdin, old_mode);
}

#else

static struct termios oldt, newt;
if (enable)
{
// Save actual configuration in 'oldt'
tcgetattr(STDIN_FILENO, &oldt);

// Copy actual configuration in 'newt'
newt = oldt;

// Modify line mode flags
// - ICANON: Desactivate canonic mode (process each character)
// - ECHO: Desactivate echo (does not print what the user writes on terminal)
newt.c_lflag &= ~(ICANON | ECHO);

// Apply new configuration
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
}
else
{
// Restore original terminal configuration
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}
#endif
}

void StdinEventHandler::stdin_listener_thread_routine_() noexcept
{
set_terminal_mode_(true);

auto awake_reason = activation_times_.wait_and_decrement();
while (awake_reason == AwakeReason::condition_met)
{
std::string read_str;
char c;

// Read lines or separated by spaces
if (read_lines_)
while (true)
{
getline(source_, read_str);
}
else
{
source_ >> read_str;
c = getchar(); // Read first character

#if defined(_WIN32) || defined(_WIN64)
if (c == 0 || c == 224) // Special key prefix for arrow keys on Windows
{
c = getchar(); // Get next character to determine arrow key
switch (c)
{
case 72: // Arrow up
#else
if (c == '\033')
{
getchar(); // Ignore next character '['
switch (getchar())
{
case 'A':
#endif
{
std::string prev_command = history_handler_.get_previous_command();
if (!prev_command.empty())
{
read_str = prev_command;
std::cout << "\r\033[K";
std::cout << "\033[38;5;82m>>\033[0m " << read_str << std::flush;
}

break;
}

#if defined(_WIN32) || defined(_WIN64)
case 80: // Arrow down
#else
case 'B': // Arrow down
#endif
{
std::string next_command = history_handler_.get_next_command();
if (!next_command.empty())
{
read_str = next_command;
std::cout << "\r\033[K";
std::cout << "\033[38;5;82m>>\033[0m " << read_str << std::flush;
}
else
{
read_str = "";
std::cout << "\r\033[K";
std::cout << "\033[1;36m>>\033[0m " << std::flush;
}

break;
}
}
}
else if (c == '\n' || c == '\r')
{
std::cout << std::endl;
event_occurred_(read_str);
history_handler_.add_command(read_str);
read_str = "";
break;
}
else if (c == '\b' || c == 127)
{
if (!read_str.empty())
{
read_str.pop_back();
std::cout << "\b \b";
}
}
else
{
read_str += c;
std::cout << c;
std::cout.flush();
}
}
event_occurred_(read_str);

awake_reason = activation_times_.wait_and_decrement();
}

set_terminal_mode_(false);
}

void StdinEventHandler::callback_set_nts_() noexcept
Expand Down
62 changes: 62 additions & 0 deletions cpp_utils/src/cpp/history/CommandHistoryHandler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2024 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cpp_utils/history/CommandHistoryHandler.hpp>

namespace eprosima {
namespace utils {
namespace history {

CommandHistoryHandler::CommandHistoryHandler()
: current_index_(-1)
{
}

void CommandHistoryHandler::add_command(const std::string& command)
{
if (!command.empty())
{
command_history_.push_back(command);
current_index_ = command_history_.size();
}
}

std::string CommandHistoryHandler::get_previous_command()
{
if (!command_history_.empty() && current_index_ > 0)
{
--current_index_;
return command_history_[current_index_];
}
return "";
}

std::string CommandHistoryHandler::get_next_command()
{
if (current_index_ < command_history_.size() - 1)
{
++current_index_;
return command_history_[current_index_];
}
else if (current_index_ == command_history_.size() - 1)
{
++current_index_;
return "";
}
return "";
}

} /* namespace history */
} /* namespace utils */
} /* namespace eprosima */
Loading
Loading