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