|
| 1 | +#include "ansi_code.hpp" |
| 2 | +#include "input_output.hpp" |
| 3 | + |
| 4 | +// OS-specific libraries. |
| 5 | +#include <sys/ioctl.h> |
| 6 | + |
| 7 | +cursor_hider::cursor_hider(bool hide /* = true */) |
| 8 | + : m_hide(hide) |
| 9 | +{ |
| 10 | + std::cout << (m_hide ? ansi_code::hide_cursor : ansi_code::show_cursor); |
| 11 | +} |
| 12 | + |
| 13 | +cursor_hider::~cursor_hider() |
| 14 | +{ |
| 15 | + std::cout << (m_hide ? ansi_code::show_cursor : ansi_code::hide_cursor); |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +alternative_buffer::alternative_buffer() |
| 20 | +{ |
| 21 | + tcgetattr(fileno(stdin), &m_previous_termios); |
| 22 | + auto new_termios = m_previous_termios; |
| 23 | + // Disable canonical mode (buffered I/O) and echo from stdin to stdout. |
| 24 | + new_termios.c_lflag &= (~ICANON & ~ECHO); |
| 25 | + tcsetattr(fileno(stdin), TCSANOW, &new_termios); |
| 26 | + |
| 27 | + std::cout << ansi_code::enable_alternative_buffer; |
| 28 | +} |
| 29 | + |
| 30 | +alternative_buffer::~alternative_buffer() |
| 31 | +{ |
| 32 | + std::cout << ansi_code::disable_alternative_buffer; |
| 33 | + |
| 34 | + // Restore previous termios settings. |
| 35 | + tcsetattr(fileno(stdin), TCSANOW, &m_previous_termios); |
| 36 | +} |
| 37 | + |
| 38 | +echo_control::echo_control(bool echo) |
| 39 | + : m_echo(echo) |
| 40 | +{ |
| 41 | + if (!m_echo) { |
| 42 | + tcgetattr(fileno(stdin), &m_previous_termios); |
| 43 | + auto new_termios = m_previous_termios; |
| 44 | + new_termios.c_lflag &= ~ECHO; |
| 45 | + tcsetattr(fileno(stdin), TCSANOW, &new_termios); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +echo_control::~echo_control() |
| 50 | +{ |
| 51 | + if (!m_echo) { |
| 52 | + // Restore previous termios settings. |
| 53 | + tcsetattr(fileno(stdin), TCSANOW, &m_previous_termios); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +std::string prompt_input(const std::string_view prompt, bool echo /* = true */) |
| 59 | +{ |
| 60 | + std::cout << prompt; |
| 61 | + |
| 62 | + echo_control ec(echo); |
| 63 | + std::string input; |
| 64 | + |
| 65 | + cursor_hider ch(false); // Re-enable cursor if currently hidden. |
| 66 | + std::getline(std::cin, input); |
| 67 | + |
| 68 | + if (!echo) { |
| 69 | + std::cout << std::endl; |
| 70 | + } |
| 71 | + |
| 72 | + // Maybe sanitise input, removing escape codes? |
| 73 | + return input; |
| 74 | +} |
0 commit comments