-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStdinEventHandler.cpp
More file actions
663 lines (592 loc) · 22 KB
/
StdinEventHandler.cpp
File metadata and controls
663 lines (592 loc) · 22 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// Copyright 2023 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 <thread>
#if defined(_WIN32) || defined(_WIN64)
#define NOMINMAX
#include <windows.h>
#include <conio.h>
#else
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#endif // if defined(_WIN32) || defined(_WIN64)
#include <cpp_utils/event/StdinEventHandler.hpp>
#include <cpp_utils/exception/InitializationException.hpp>
#include <cpp_utils/Log.hpp>
namespace {
#if defined(_WIN32) || defined(_WIN64)
inline bool consume_tilde_if_present()
{
// Windows special keys don’t have a trailing '~'
return true;
}
#else
inline bool consume_tilde_if_present()
{
// POSIX: ESC [ <num> ~ → read and verify '~'
int t = getchar();
return t == '~';
}
#endif // if defined(_WIN32) || defined(_WIN64)
} // namespace
namespace eprosima {
namespace utils {
namespace event {
int get_terminal_width()
{
#if defined(_WIN32) || defined(_WIN64)
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
#else
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_col;
#endif // if defined(_WIN32) || defined(_WIN64)
}
int compute_lines_needed(
const std::string& prompt,
const std::string& cmd,
int term_width)
{
int total_length = static_cast<int>(prompt.size() + cmd.size());
return (total_length + term_width - 1) / term_width;
}
void clear_lines(
int line_count)
{
for (int i = 0; i < line_count; ++i)
{
std::cout << "\033[2K\r"; // Clear current line
if (i < line_count - 1)
{
std::cout << "\033[1A"; // Move up (not after last line)
}
}
}
void update_line(
const std::string& prompt,
std::string& line,
size_t& cursor_index,
std::function<void(std::string&, size_t&)> line_modifier)
{
int term_width = get_terminal_width();
if (term_width <= 0)
{
term_width = 80;
}
// Save the old line and cursor index before modifying
std::string old_line = line;
size_t old_cursor_index = cursor_index;
// Apply the line modifier function
line_modifier(line, cursor_index);
// If the content does not change, only move the cursor
if (line == old_line)
{
int old_abs_cursor = static_cast<int>(prompt.size() + old_cursor_index);
int new_abs_cursor = static_cast<int>(prompt.size() + cursor_index);
int old_cursor_line = old_abs_cursor / term_width;
int new_cursor_line = new_abs_cursor / term_width;
int line_diff = new_cursor_line - old_cursor_line;
if (line_diff > 0)
{
for (int i = 0; i < line_diff; ++i)
{
std::cout << "\033[1B"; // move down
}
}
else if (line_diff < 0)
{
for (int i = 0; i < -line_diff; ++i)
{
std::cout << "\033[1A"; // move up
}
}
std::cout << "\r";
int new_cursor_col = new_abs_cursor % term_width;
if (new_cursor_col > 0)
{
std::cout << "\033[" << new_cursor_col << "C";
}
std::cout.flush();
return;
}
// Remove the old line
std::string full_line_before = prompt + old_line;
int old_lines = (static_cast<int>(full_line_before.size()) + term_width - 1) / term_width;
// Move to the line where the cursor was
// Calculate the absolute cursor position
// and the line number where it was
int old_abs_cursor = static_cast<int>(prompt.size() + old_cursor_index);
int old_cursor_line = old_abs_cursor / term_width;
int lines_to_go_down = old_lines - 1 - old_cursor_line;
for (int i = 0; i < lines_to_go_down; ++i)
{
std::cout << "\033[1B";
}
for (int i = 0; i < old_lines; ++i)
{
std::cout << "\033[2K\r";
if (i < old_lines - 1)
{
std::cout << "\033[1A";
}
}
// Print the new line
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << line << std::flush;
// Position the cursor
int abs_cursor = static_cast<int>(prompt.size() + cursor_index);
int total_lines = (static_cast<int>(prompt.size() + line.size()) + term_width - 1) / term_width;
int cursor_line = abs_cursor / term_width;
int cursor_col = abs_cursor % term_width;
int lines_to_move_up = total_lines - 1 - cursor_line;
for (int i = 0; i < lines_to_move_up; ++i)
{
std::cout << "\033[1A";
}
std::cout << "\r";
if (cursor_col > 0)
{
std::cout << "\033[" << cursor_col << "C";
}
std::cout.flush();
}
StdinEventHandler::StdinEventHandler(
std::function<void(std::string)> callback,
const bool read_lines /* = true */,
const int lines_to_read /* = 0 */,
std::istream& source /* = std::cin */)
: activation_times_(0, lines_to_read, false)
, source_(source)
, read_lines_(read_lines)
{
set_callback(callback);
}
StdinEventHandler::~StdinEventHandler()
{
unset_callback();
}
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 current input mode
GetConsoleMode(hStdin, &old_mode);
// Disable echo and line input
DWORD new_mode = old_mode;
new_mode &= ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT);
SetConsoleMode(hStdin, new_mode);
SetConsoleCtrlHandler(NULL, TRUE);
}
else
{
// Restore input and output modes
SetConsoleMode(hStdin, old_mode);
SetConsoleCtrlHandler(NULL, FALSE);
}
#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)
// - ISIG: Deactivate signals (Ctrl+C, Ctrl+Z)
newt.c_lflag &= ~(ICANON | ECHO | ISIG);
// Apply new configuration
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
}
else
{
// Restore original terminal configuration
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}
#endif // if defined(_WIN32) || defined(_WIN64)
}
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;
size_t cursor_index = 0;
#if defined(_WIN32) || defined(_WIN64)
bool use_getchar = GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_PIPE;
#endif // if defined(_WIN32) || defined(_WIN64)
while (true)
{
#if defined(_WIN32) || defined(_WIN64)
int c;
// Read first character
// Use getchar() for pipes to avoid blocking
// Use _getch() for console input to avoid echoing characters
if (use_getchar)
{
c = getchar();
}
else
{
c = _getch();
}
if (c == 0 || c == 224) // Special key prefix for arrow keys on Windows
{
c = _getch(); // Get next character to determine arrow key
switch (c)
{
case 72: // Arrow up
#else
char c;
c = getchar(); // Read first character
if (c == '\033')
{
getchar(); // Ignore next character '['
switch (getchar())
{
case 'A':
#endif // if defined(_WIN32) || defined(_WIN64)
{
std::string prev_command = history_handler_.get_previous_command();
if (!prev_command.empty())
{
std::string prompt = ">> ";
int term_width = get_terminal_width();
int lines = compute_lines_needed(prompt, read_str, term_width);
clear_lines(lines);
read_str = prev_command;
cursor_index = read_str.size();
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << read_str << std::flush;
}
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 80: // Arrow down
#else
case 'B': // Arrow down
#endif // if defined(_WIN32) || defined(_WIN64)
{
std::string next_command = history_handler_.get_next_command();
if (!next_command.empty())
{
std::string prompt = ">> ";
int term_width = get_terminal_width();
int lines = compute_lines_needed(prompt, read_str, term_width);
clear_lines(lines);
read_str = next_command;
cursor_index = read_str.size();
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << read_str << std::flush;
}
else
{
std::string prompt = ">> ";
int term_width = get_terminal_width();
int lines = compute_lines_needed(prompt, read_str, term_width);
clear_lines(lines);
read_str = "";
cursor_index = 0;
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << std::flush;
}
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 75: // Arrow LEFT
#else
case 'D': // Arrow LEFT
#endif // if defined(_WIN32) || defined(_WIN64)
{
if (cursor_index > 0)
{
update_line(">> ", read_str, cursor_index,
[](std::string&, size_t& index)
{
if (index > 0)
{
--index;
}
});
}
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 77: // Arrow RIGHT
#else
case 'C': // Arrow RIGHT
#endif // if defined(_WIN32) || defined(_WIN64)
{
update_line(">> ", read_str, cursor_index,
[](std::string& line, size_t& index)
{
if (index < line.size())
{
++index;
}
});
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 82: // Insert
#else
case '2': // Insert: ESC [ 2 ~
#endif // if defined(_WIN32) || defined(_WIN64)
{
int c3 = getchar(); (void)c3; // swallow trailing '~'
// Minimal behavior: do nothing
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 83: // Supr
#else
case '3': // Supr: ESC [ 3 ~
#endif // if defined(_WIN32) || defined(_WIN64)
{
if (consume_tilde_if_present())
{
// delete-forward (char at cursor), if any
if (cursor_index < read_str.size())
{
update_line(">> ", read_str, cursor_index,
[](std::string& line, size_t& index)
{
if (index < line.size())
{
line.erase(line.begin() + index);
}
});
}
}
// do nothing.
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 73: // Page Up
#else
case '5': // Page Up: ESC [ 5 ~ (history prev)
#endif // if defined(_WIN32) || defined(_WIN64)
{
if (consume_tilde_if_present())
{
std::string prev = history_handler_.get_previous_command();
if (!prev.empty())
{
std::string prompt = ">> ";
int term_width = get_terminal_width();
int lines = compute_lines_needed(prompt, read_str, term_width);
clear_lines(lines);
read_str = prev;
cursor_index = read_str.size();
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << read_str << std::flush;
}
}
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 81: // Page Down
#else
case '6': // Page Down: ESC [ 6 ~ (history next)
#endif // if defined(_WIN32) || defined(_WIN64)
{
if (consume_tilde_if_present())
{
std::string next = history_handler_.get_next_command();
std::string prompt = ">> ";
int term_width = get_terminal_width();
int lines = compute_lines_needed(prompt, read_str, term_width);
clear_lines(lines);
if (!next.empty())
{
read_str = next;
cursor_index = read_str.size();
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << read_str << std::flush;
}
else
{
read_str.clear();
cursor_index = 0;
std::cout << "\033[38;5;82m" << prompt << "\033[0m" << std::flush;
}
}
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 71: // Home
#else
case 'H': // Home: ESC [ H
#endif // if defined(_WIN32) || defined(_WIN64)
{
update_line(">> ", read_str, cursor_index,
[](std::string&, size_t& index)
{
index = 0;
});
break;
}
#if defined(_WIN32) || defined(_WIN64)
case 79: // End
#else
case 'F': // End: ESC [ F
#endif // if defined(_WIN32) || defined(_WIN64)
{
update_line(">> ", read_str, cursor_index,
[](std::string& line, size_t& index)
{
index = line.size();
});
break;
}
}
}
else if (c == '\n' || c == '\r')
{
std::cout << std::endl;
event_occurred_(read_str);
if (!is_ignoring_input() && !read_str.empty())
{
history_handler_.add_command(read_str);
}
read_str = "";
cursor_index = 0;
break;
}
else if (c == '\b' || c == 127)
{
if (cursor_index > 0)
{
update_line(">> ", read_str, cursor_index,
[](std::string& line, size_t& index)
{
if (index > 0)
{
line.erase(line.begin() + index - 1);
--index;
}
});
}
}
else if (c == '\x03') // Ctrl+C
{
std::cout << std::endl;
event_occurred_("");
read_str = "";
cursor_index = 0;
break;
}
else if (c == '\t')
{
if (!tab_completion_callback_)
{
continue;
}
std::vector<std::string> suggestions = tab_completion_callback_(read_str);
if (suggestions.empty())
{
continue;
}
// Locate the last whitespace-delimited token in the line
size_t last_space = read_str.find_last_of(" \t");
size_t token_start = (last_space == std::string::npos) ? 0 : last_space + 1;
std::string current_token = read_str.substr(token_start);
// Compute the longest common prefix of all suggestions
std::string lcp = suggestions[0];
for (size_t i = 1; i < suggestions.size(); i++)
{
size_t j = 0;
while (j < lcp.size() && j < suggestions[i].size() && lcp[j] == suggestions[i][j])
{
j++;
}
lcp.resize(j);
}
if (suggestions.size() == 1 || lcp.size() > current_token.size())
{
// Replace the last token with the unique match or the extended common prefix
const std::string completion = (suggestions.size() == 1) ? suggestions[0] : lcp;
std::string new_line = read_str.substr(0, token_start) + completion;
update_line(">> ", read_str, cursor_index,
[new_line](std::string& line, size_t& index)
{
line = new_line;
index = line.size();
});
}
else
{
// Several matches: move cursor to end of line, list candidates, redraw prompt
update_line(">> ", read_str, cursor_index,
[](std::string& line, size_t& index)
{
index = line.size();
});
std::cout << "\n";
for (const auto& s : suggestions)
{
std::cout << " " << s << "\n";
}
std::cout << "\033[38;5;82m" << ">> " << "\033[0m" << read_str << std::flush;
cursor_index = read_str.size();
}
}
else
{
char ch = static_cast<char>(c);
update_line(">> ", read_str, cursor_index,
[ch](std::string& line, size_t& index)
{
line.insert(line.begin() + index, ch);
++index;
});
}
}
awake_reason = activation_times_.wait_and_decrement();
}
set_terminal_mode_(false);
}
void StdinEventHandler::callback_set_nts_() noexcept
{
activation_times_.enable();
stdin_listener_thread_ = std::thread(&StdinEventHandler::stdin_listener_thread_routine_, this);
}
void StdinEventHandler::callback_unset_nts_() noexcept
{
activation_times_.disable();
stdin_listener_thread_.join();
}
void StdinEventHandler::set_ignore_input(
bool ignore) noexcept
{
ignore_input_.store(ignore, std::memory_order_relaxed);
}
bool StdinEventHandler::is_ignoring_input() const noexcept
{
return ignore_input_.load(std::memory_order_relaxed);
}
void StdinEventHandler::set_tab_completion_callback(
std::function<std::vector<std::string>(const std::string&)> callback) noexcept
{
tab_completion_callback_ = std::move(callback);
}
} /* namespace event */
} /* namespace utils */
} /* namespace eprosima */