aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/consoletui.cpp
blob: 1621b71985b95480af034dc489fcc0c470c94497 (plain) (blame)
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenutil/consoletui.h>

#include <zencore/zencore.h>

#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
#else
#	include <poll.h>
#	include <sys/ioctl.h>
#	include <termios.h>
#	include <unistd.h>
#endif

#include <cstdio>

namespace zen {

//////////////////////////////////////////////////////////////////////////
// Platform-specific terminal helpers

#if ZEN_PLATFORM_WINDOWS

static bool
CheckIsInteractiveTerminal()
{
	DWORD dwMode = 0;
	return GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwMode) && GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &dwMode);
}

static void
EnableVirtualTerminal()
{
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	DWORD  dwMode  = 0;
	if (GetConsoleMode(hStdOut, &dwMode))
	{
		SetConsoleMode(hStdOut, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
	}
}

// RAII guard: sets the console output code page for the lifetime of the object and
// restores the original on destruction. Required for UTF-8 glyphs to render correctly
// via printf/fflush since the default console code page is not UTF-8.
class ConsoleCodePageGuard
{
public:
	explicit ConsoleCodePageGuard(UINT NewCP) : m_OldCP(GetConsoleOutputCP()) { SetConsoleOutputCP(NewCP); }
	~ConsoleCodePageGuard() { SetConsoleOutputCP(m_OldCP); }

private:
	UINT m_OldCP;
};

enum class ConsoleKey
{
	Unknown,
	ArrowUp,
	ArrowDown,
	Enter,
	Escape,
};

static ConsoleKey
ReadKey()
{
	HANDLE		 hStdin = GetStdHandle(STD_INPUT_HANDLE);
	INPUT_RECORD Record{};
	DWORD		 dwRead = 0;
	while (true)
	{
		if (!ReadConsoleInputA(hStdin, &Record, 1, &dwRead))
		{
			return ConsoleKey::Escape;	// treat read error as cancel
		}
		if (Record.EventType == KEY_EVENT && Record.Event.KeyEvent.bKeyDown)
		{
			switch (Record.Event.KeyEvent.wVirtualKeyCode)
			{
				case VK_UP:
					return ConsoleKey::ArrowUp;
				case VK_DOWN:
					return ConsoleKey::ArrowDown;
				case VK_RETURN:
					return ConsoleKey::Enter;
				case VK_ESCAPE:
					return ConsoleKey::Escape;
				default:
					break;
			}
		}
	}
}

#else  // POSIX

static bool
CheckIsInteractiveTerminal()
{
	return isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);
}

static void
EnableVirtualTerminal()
{
	// ANSI escape codes are native on POSIX terminals; nothing to do
}

// RAII guard: switches the terminal to raw/unbuffered input mode and restores
// the original attributes on destruction.
class RawModeGuard
{
public:
	RawModeGuard()
	{
		if (tcgetattr(STDIN_FILENO, &m_OldAttrs) != 0)
		{
			return;
		}

		struct termios Raw = m_OldAttrs;
		Raw.c_iflag &= ~static_cast<tcflag_t>(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
		Raw.c_cflag |= CS8;
		Raw.c_lflag &= ~static_cast<tcflag_t>(ECHO | ICANON | IEXTEN | ISIG);
		Raw.c_cc[VMIN]	= 1;
		Raw.c_cc[VTIME] = 0;
		if (tcsetattr(STDIN_FILENO, TCSANOW, &Raw) == 0)
		{
			m_Valid = true;
		}
	}

	~RawModeGuard()
	{
		if (m_Valid)
		{
			tcsetattr(STDIN_FILENO, TCSANOW, &m_OldAttrs);
		}
	}

	bool IsValid() const { return m_Valid; }

private:
	struct termios m_OldAttrs = {};
	bool		   m_Valid	  = false;
};

static int
ReadByteWithTimeout(int TimeoutMs)
{
	struct pollfd Pfd
	{
		STDIN_FILENO, POLLIN, 0
	};
	if (poll(&Pfd, 1, TimeoutMs) > 0 && (Pfd.revents & POLLIN))
	{
		unsigned char c = 0;
		if (read(STDIN_FILENO, &c, 1) == 1)
		{
			return static_cast<int>(c);
		}
	}
	return -1;
}

// State for fullscreen live mode (alternate screen + raw input)
static struct termios s_SavedAttrs = {};
static bool			  s_InLiveMode = false;

enum class ConsoleKey
{
	Unknown,
	ArrowUp,
	ArrowDown,
	Enter,
	Escape,
};

static ConsoleKey
ReadKey()
{
	unsigned char c = 0;
	if (read(STDIN_FILENO, &c, 1) != 1)
	{
		return ConsoleKey::Escape;	// treat read error as cancel
	}

	if (c == 27)  // ESC byte or start of an escape sequence
	{
		int Next = ReadByteWithTimeout(50);
		if (Next == '[')
		{
			int Final = ReadByteWithTimeout(50);
			if (Final == 'A')
			{
				return ConsoleKey::ArrowUp;
			}
			if (Final == 'B')
			{
				return ConsoleKey::ArrowDown;
			}
		}
		return ConsoleKey::Escape;
	}

	if (c == '\r' || c == '\n')
	{
		return ConsoleKey::Enter;
	}

	return ConsoleKey::Unknown;
}

#endif	// ZEN_PLATFORM_WINDOWS / POSIX

//////////////////////////////////////////////////////////////////////////
// Public API

uint32_t
TuiConsoleColumns(uint32_t Default)
{
#if ZEN_PLATFORM_WINDOWS
	CONSOLE_SCREEN_BUFFER_INFO Csbi = {};
	if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &Csbi))
	{
		return static_cast<uint32_t>(Csbi.dwSize.X);
	}
#else
	struct winsize Ws = {};
	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &Ws) == 0 && Ws.ws_col > 0)
	{
		return static_cast<uint32_t>(Ws.ws_col);
	}
#endif
	return Default;
}

void
TuiEnableOutput()
{
	EnableVirtualTerminal();
#if ZEN_PLATFORM_WINDOWS
	SetConsoleOutputCP(CP_UTF8);
#endif
}

bool
TuiIsStdoutTty()
{
#if ZEN_PLATFORM_WINDOWS
	static bool Cached = [] {
		DWORD dwMode = 0;
		return GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &dwMode) != 0;
	}();
	return Cached;
#else
	static bool Cached = isatty(STDOUT_FILENO) != 0;
	return Cached;
#endif
}

bool
IsTuiAvailable()
{
	static bool Cached = CheckIsInteractiveTerminal();
	return Cached;
}

int
TuiPickOne(std::string_view Title, std::span<const std::string> Items)
{
	EnableVirtualTerminal();

#if ZEN_PLATFORM_WINDOWS
	ConsoleCodePageGuard CodePageGuard(CP_UTF8);
#else
	RawModeGuard RawMode;
	if (!RawMode.IsValid())
	{
		return -1;
	}
#endif

	const int Count			= static_cast<int>(Items.size());
	int		  SelectedIndex = 0;

	printf("\n%.*s\n\n", static_cast<int>(Title.size()), Title.data());

	// Hide cursor during interaction
	printf("\033[?25l");

	// Renders the full entry list and hint footer.
	// On subsequent calls, moves the cursor back up first to overwrite the previous output.
	bool FirstRender = true;
	auto RenderAll	 = [&] {
		  if (!FirstRender)
		  {
			  printf("\033[%dA", Count + 2);  // move up: entries + blank line + hint line
		  }
		  FirstRender = false;

		  for (int i = 0; i < Count; ++i)
		  {
			  bool IsSelected = (i == SelectedIndex);

			  printf("\r\033[K");  // erase line

			  if (IsSelected)
			  {
				  printf("\033[1;7m");	// bold + reverse video
			  }

			  // \xe2\x96\xb6 = U+25B6 BLACK RIGHT-POINTING TRIANGLE (▶)
			  const char* Indicator = IsSelected ? " \xe2\x96\xb6 " : "   ";

			  printf("%s%s", Indicator, Items[i].c_str());

			  if (IsSelected)
			  {
				  printf("\033[0m");  // reset attributes
			  }

			  printf("\n");
		  }

		  // Blank separator line
		  printf("\r\033[K\n");

		  // Hint footer
		  // \xe2\x86\x91 = U+2191 ↑    \xe2\x86\x93 = U+2193 ↓
		  printf(
			  "\r\033[K  \033[2m\xe2\x86\x91/\xe2\x86\x93\033[0m navigate  "
			  "\033[2mEnter\033[0m confirm  "
			  "\033[2mEsc\033[0m cancel\n");

		  fflush(stdout);
	};

	RenderAll();

	int	 Result = -1;
	bool Done	= false;
	while (!Done)
	{
		ConsoleKey Key = ReadKey();
		switch (Key)
		{
			case ConsoleKey::ArrowUp:
				SelectedIndex = (SelectedIndex - 1 + Count) % Count;
				RenderAll();
				break;

			case ConsoleKey::ArrowDown:
				SelectedIndex = (SelectedIndex + 1) % Count;
				RenderAll();
				break;

			case ConsoleKey::Enter:
				Result = SelectedIndex;
				Done   = true;
				break;

			case ConsoleKey::Escape:
				Done = true;
				break;

			default:
				break;
		}
	}

	// Restore cursor and add a blank line for visual separation
	printf("\033[?25h\n");
	fflush(stdout);

	return Result;
}

void
TuiEnterAlternateScreen()
{
	EnableVirtualTerminal();
#if ZEN_PLATFORM_WINDOWS
	SetConsoleOutputCP(CP_UTF8);
#endif

	printf("\033[?1049h");	// Enter alternate screen buffer
	printf("\033[?25l");	// Hide cursor
	fflush(stdout);

#if !ZEN_PLATFORM_WINDOWS
	if (tcgetattr(STDIN_FILENO, &s_SavedAttrs) == 0)
	{
		struct termios Raw = s_SavedAttrs;
		Raw.c_iflag &= ~static_cast<tcflag_t>(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
		Raw.c_cflag |= CS8;
		Raw.c_lflag &= ~static_cast<tcflag_t>(ECHO | ICANON | IEXTEN | ISIG);
		Raw.c_cc[VMIN]	= 1;
		Raw.c_cc[VTIME] = 0;
		if (tcsetattr(STDIN_FILENO, TCSANOW, &Raw) == 0)
		{
			s_InLiveMode = true;
		}
	}
#endif
}

void
TuiExitAlternateScreen()
{
	printf("\033[?25h");	// Show cursor
	printf("\033[?1049l");	// Exit alternate screen buffer
	fflush(stdout);

#if !ZEN_PLATFORM_WINDOWS
	if (s_InLiveMode)
	{
		tcsetattr(STDIN_FILENO, TCSANOW, &s_SavedAttrs);
		s_InLiveMode = false;
	}
#endif
}

void
TuiCursorHome()
{
	printf("\033[H");
}

uint32_t
TuiConsoleRows(uint32_t Default)
{
#if ZEN_PLATFORM_WINDOWS
	CONSOLE_SCREEN_BUFFER_INFO Csbi = {};
	if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &Csbi))
	{
		return static_cast<uint32_t>(Csbi.srWindow.Bottom - Csbi.srWindow.Top + 1);
	}
#else
	struct winsize Ws = {};
	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &Ws) == 0 && Ws.ws_row > 0)
	{
		return static_cast<uint32_t>(Ws.ws_row);
	}
#endif
	return Default;
}

bool
TuiPollQuit()
{
#if ZEN_PLATFORM_WINDOWS
	HANDLE hStdin  = GetStdHandle(STD_INPUT_HANDLE);
	DWORD  dwCount = 0;
	if (!GetNumberOfConsoleInputEvents(hStdin, &dwCount) || dwCount == 0)
	{
		return false;
	}
	INPUT_RECORD Record{};
	DWORD		 dwRead = 0;
	while (PeekConsoleInputA(hStdin, &Record, 1, &dwRead) && dwRead > 0)
	{
		ReadConsoleInputA(hStdin, &Record, 1, &dwRead);
		if (Record.EventType == KEY_EVENT && Record.Event.KeyEvent.bKeyDown)
		{
			WORD vk = Record.Event.KeyEvent.wVirtualKeyCode;
			char ch = Record.Event.KeyEvent.uChar.AsciiChar;
			if (vk == VK_ESCAPE || ch == 'q' || ch == 'Q')
			{
				return true;
			}
		}
	}
	return false;
#else
	// Non-blocking read: character 3 = Ctrl+C, 27 = Esc, 'q'/'Q' = quit
	int b = ReadByteWithTimeout(0);
	return (b == 3 || b == 27 || b == 'q' || b == 'Q');
#endif
}

TuiInput
TuiPollInput()
{
#if ZEN_PLATFORM_WINDOWS
	HANDLE hStdin  = GetStdHandle(STD_INPUT_HANDLE);
	DWORD  dwCount = 0;
	if (!GetNumberOfConsoleInputEvents(hStdin, &dwCount) || dwCount == 0)
	{
		return TuiInput::None;
	}
	INPUT_RECORD Record{};
	DWORD		 dwRead = 0;
	while (PeekConsoleInputA(hStdin, &Record, 1, &dwRead) && dwRead > 0)
	{
		ReadConsoleInputA(hStdin, &Record, 1, &dwRead);
		if (Record.EventType == KEY_EVENT && Record.Event.KeyEvent.bKeyDown)
		{
			WORD vk = Record.Event.KeyEvent.wVirtualKeyCode;
			char ch = Record.Event.KeyEvent.uChar.AsciiChar;
			if (vk == VK_ESCAPE || ch == 'q' || ch == 'Q')
			{
				return TuiInput::Quit;
			}
			if (vk == VK_F5)
			{
				return TuiInput::Refresh;
			}
			if (vk == VK_UP)
			{
				return TuiInput::ArrowUp;
			}
			if (vk == VK_DOWN)
			{
				return TuiInput::ArrowDown;
			}
		}
	}
	return TuiInput::None;
#else
	int b = ReadByteWithTimeout(0);
	if (b == 3 || b == 'q' || b == 'Q')
	{
		return TuiInput::Quit;
	}
	if (b == 27)
	{
		// Could be bare Esc or start of an escape sequence (e.g. \033[A)
		int Next = ReadByteWithTimeout(50);
		if (Next == '[')
		{
			int Final = ReadByteWithTimeout(50);
			if (Final == 'A')
			{
				return TuiInput::ArrowUp;
			}
			if (Final == 'B')
			{
				return TuiInput::ArrowDown;
			}
			// F5 = \033[15~
			if (Final == '1')
			{
				int b2 = ReadByteWithTimeout(50);
				if (b2 == '5')
				{
					int b3 = ReadByteWithTimeout(50);
					if (b3 == '~')
					{
						return TuiInput::Refresh;
					}
				}
			}
		}
		return TuiInput::Quit;	// bare Esc
	}
	return TuiInput::None;
#endif
}

bool
TuiWaitForInput(uint32_t TimeoutMs)
{
#if ZEN_PLATFORM_WINDOWS
	HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
	return WaitForSingleObject(hStdin, TimeoutMs) == WAIT_OBJECT_0;
#else
	struct pollfd Pfd
	{
		STDIN_FILENO, POLLIN, 0
	};
	return poll(&Pfd, 1, static_cast<int>(TimeoutMs)) > 0;
#endif
}

void
TuiClearToBottom()
{
	printf("\033[J");
}

}  // namespace zen