-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinput_output.cpp
More file actions
118 lines (98 loc) · 2.51 KB
/
input_output.cpp
File metadata and controls
118 lines (98 loc) · 2.51 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "input_output.hpp"
#include <iostream>
#include "ansi_code.hpp"
// OS-specific libraries.
#include <sys/ioctl.h>
unsigned int cursor_hider::s_scope_count = 0;
cursor_hider::cursor_hider(bool hide /* = true */)
: m_hide(hide)
{
s_scope_count++;
write_ansi_code(m_hide);
}
cursor_hider::~cursor_hider()
{
s_scope_count--;
if (s_scope_count == 0)
{
// Ensure cursor is visible when git2cpp exits.
write_ansi_code(false);
}
else
{
write_ansi_code(!m_hide);
}
}
void cursor_hider::write_ansi_code(bool hide)
{
std::cout << (hide ? ansi_code::hide_cursor : ansi_code::show_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;
}
bool prompt_yes_or_no(const std::string_view prompt, bool default_return)
{
while (true)
{
auto input = prompt_input(prompt);
if (input.empty())
{
return default_return;
}
auto first_char = std::tolower(input.front());
if (first_char == 'y')
{
return true;
}
else if (first_char == 'n')
{
return false;
}
// Repeat prompt.
}
}