summaryrefslogtreecommitdiff
path: root/util
diff options
context:
space:
mode:
authorEvan Welsh <contact@evanwelsh.com>2021-06-29 01:07:13 -0700
committerPhilip Chimento <philip.chimento@gmail.com>2021-08-16 20:31:59 -0700
commite24c054839170a1c08d130120ca2a5ea3c913198 (patch)
tree2c5ea122174249d7cd102fa6fa34f6a4006c276f /util
parentf06a570a069409ad0ebfd163fe1de263d898d09e (diff)
downloadgjs-e24c054839170a1c08d130120ca2a5ea3c913198.tar.gz
modules: Implement console.clear()
Diffstat (limited to 'util')
-rw-r--r--util/console.cpp28
-rw-r--r--util/console.h2
2 files changed, 30 insertions, 0 deletions
diff --git a/util/console.cpp b/util/console.cpp
index 49bf77e1..5489ab6b 100644
--- a/util/console.cpp
+++ b/util/console.cpp
@@ -3,14 +3,35 @@
#include <config.h>
+#include <stdio.h>
+
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#elif defined(_WIN32)
# include <io.h>
#endif
+#include <glib.h>
+
#include "util/console.h"
+/**
+ * ANSI escape code sequences to manipulate terminals.
+ *
+ * See
+ * https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
+ */
+namespace ANSICode {
+/**
+ * ANSI escape code sequence to clear the terminal screen.
+ *
+ * Combination of 0x1B (Escape) and the sequence nJ where n=2,
+ * n=2 clears the entire display instead of only after the cursor.
+ */
+constexpr const char CLEAR_SCREEN[] = "\x1b[2J";
+
+} // namespace ANSICode
+
#ifdef HAVE_UNISTD_H
const int stdin_fd = STDIN_FILENO;
const int stdout_fd = STDOUT_FILENO;
@@ -34,3 +55,10 @@ bool gjs_console_is_tty(int fd) {
return false;
#endif
}
+
+bool gjs_console_clear() {
+ if (stdout_fd < 0 || !g_log_writer_supports_color(stdout_fd))
+ return false;
+
+ return fputs(ANSICode::CLEAR_SCREEN, stdout) > 0 && fflush(stdout) > 0;
+}
diff --git a/util/console.h b/util/console.h
index d8acd5ed..df27f305 100644
--- a/util/console.h
+++ b/util/console.h
@@ -24,6 +24,8 @@ extern const int stderr_fd;
GJS_USE
bool gjs_console_is_tty(int fd);
+bool gjs_console_clear(void);
+
G_END_DECLS
#endif // UTIL_CONSOLE_H_