1 // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
2 // SPDX-FileCopyrightText: 2021 Evan Welsh <contact@evanwelsh.com>
3 
4 #include <config.h>
5 
6 #include <stdio.h>
7 
8 #ifdef HAVE_UNISTD_H
9 #    include <unistd.h>
10 #elif defined(_WIN32)
11 #    include <io.h>
12 #endif
13 
14 #include <glib.h>
15 
16 #include "util/console.h"
17 
18 /**
19  * ANSI escape code sequences to manipulate terminals.
20  *
21  * See
22  * https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
23  */
24 namespace ANSICode {
25 /**
26  * ANSI escape code sequence to clear the terminal screen.
27  *
28  * Combination of 0x1B (Escape) and the sequence nJ where n=2,
29  * n=2 clears the entire display instead of only after the cursor.
30  */
31 constexpr const char CLEAR_SCREEN[] = "\x1b[2J";
32 
33 }  // namespace ANSICode
34 
35 #ifdef HAVE_UNISTD_H
36 const int stdin_fd = STDIN_FILENO;
37 const int stdout_fd = STDOUT_FILENO;
38 const int stderr_fd = STDERR_FILENO;
39 #elif defined(_WIN32)
40 const int stdin_fd = _fileno(stdin);
41 const int stdout_fd = _fileno(stdout);
42 const int stderr_fd = _fileno(stderr);
43 #else
44 const int stdin_fd = 0;
45 const int stdout_fd = 1;
46 const int stderr_fd = 2;
47 #endif
48 
gjs_console_is_tty(int fd)49 bool gjs_console_is_tty(int fd) {
50 #ifdef HAVE_UNISTD_H
51     return isatty(fd);
52 #elif defined(_WIN32)
53     return _isatty(fd);
54 #else
55     return false;
56 #endif
57 }
58 
gjs_console_clear()59 bool gjs_console_clear() {
60     if (stdout_fd < 0 || !g_log_writer_supports_color(stdout_fd))
61         return false;
62 
63     return fputs(ANSICode::CLEAR_SCREEN, stdout) > 0 && fflush(stdout) > 0;
64 }
65