[gjs/ewlsh/whatwg-console: 3/3] modules: Implement console.clear()




commit b44238cd8cfaa7058b66662578c7ce1cc915167e
Author: Evan Welsh <contact evanwelsh com>
Date:   Tue Jun 29 01:07:13 2021 -0700

    modules: Implement console.clear()

 meson.build            | 10 ++++++++++
 modules/console.cpp    | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 modules/esm/console.js |  9 ++++++---
 3 files changed, 63 insertions(+), 3 deletions(-)
---
diff --git a/meson.build b/meson.build
index 9214a5fe..57ea3096 100644
--- a/meson.build
+++ b/meson.build
@@ -124,6 +124,10 @@ gi = dependency('gobject-introspection-1.0', version: '>= 1.66.0',
     fallback: ['gobject-introspection', 'girepo_dep'])
 spidermonkey = dependency('mozjs-78', version: '>= 78.2.0')
 
+gio_unix = dependency('gio-unix-2.0', version: glib_required_version, required: false)
+
+has_gio_unix = gio_unix.found()
+
 # We might need to look for the headers and lib's for Cairo
 # manually on MSVC/clang-cl builds...
 cairo = dependency('cairo', required: get_option('cairo').enabled() and cxx.get_argument_syntax() != 'msvc')
@@ -313,6 +317,8 @@ header_conf.set('HAVE_SIGNAL_H', cxx.check_header('signal.h',
 # enable GNU extensions on systems that have them
 header_conf.set('_GNU_SOURCE', 1)
 
+header_conf.set('HAVE_GIO_UNIX', has_gio_unix)
+
 configure_file(output: 'config.h', configuration: header_conf)
 
 ### Check for environment ######################################################
@@ -484,6 +490,10 @@ if build_readline
     libgjs_dependencies += readline_deps
 endif
 
+if has_gio_unix
+    libgjs_dependencies += gio_unix
+endif
+
 libgjs_cpp_args = ['-DGJS_COMPILATION'] + directory_defines
 
 # Check G-I and/or Meson on this one.
diff --git a/modules/console.cpp b/modules/console.cpp
index d01eaea0..776eea20 100644
--- a/modules/console.cpp
+++ b/modules/console.cpp
@@ -39,6 +39,13 @@
 #    endif
 #endif
 
+#ifdef HAVE_GIO_UNIX
+#    include <gio/gio.h>
+#    include <gio/gunixoutputstream.h>  // IWYU pragma: keep
+#    include <glib-object.h>
+#    include <string.h>
+#endif
+
 #include <js/CallArgs.h>
 #include <js/CompilationAndEvaluation.h>
 #include <js/CompileOptions.h>
@@ -328,6 +335,43 @@ bool gjs_console_get_terminal_size(JSContext* cx, unsigned argc,
     return true;
 }
 
+/**
+ * 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.
+ *
+ * See https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
+ */
+constexpr const char* ANSI_CODE [[maybe_unused]] = "\x1b[2J";
+
+bool gjs_console_clear_terminal(JSContext* cx, unsigned argc, JS::Value* vp) {
+    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
+
+#ifdef HAVE_GIO_UNIX
+    int fd = fileno(stdout);
+    if (fd >= 0) {
+        GjsAutoUnref<GOutputStream> ostream(
+            g_unix_output_stream_new(fd, false));
+        size_t bytes_written;
+        GError* error = nullptr;
+
+        if (!g_output_stream_write_all(ostream, ANSI_CODE, strlen(ANSI_CODE),
+                                       &bytes_written, nullptr, &error))
+            return gjs_throw_gerror_message(cx, error);
+
+        if (!g_output_stream_flush(ostream, nullptr, &error))
+            return gjs_throw_gerror_message(cx, error);
+
+        if (!g_output_stream_close(ostream, nullptr, &error))
+            return gjs_throw_gerror_message(cx, error);
+    }
+#endif
+
+    args.rval().setUndefined();
+    return true;
+}
+
 bool
 gjs_define_console_stuff(JSContext              *context,
                          JS::MutableHandleObject module)
@@ -337,6 +381,9 @@ gjs_define_console_stuff(JSContext              *context,
     return JS_DefineFunction(context, module, "getTerminalSize",
                              gjs_console_get_terminal_size, 1,
                              GJS_MODULE_PROP_FLAGS) &&
+           JS_DefineFunction(context, module, "clearTerminal",
+                             gjs_console_clear_terminal, 1,
+                             GJS_MODULE_PROP_FLAGS) &&
            JS_DefineFunctionById(context, module, atoms.interact(),
                                  gjs_console_interact, 1,
                                  GJS_MODULE_PROP_FLAGS);
diff --git a/modules/esm/console.js b/modules/esm/console.js
index 6521fcd0..952cd825 100644
--- a/modules/esm/console.js
+++ b/modules/esm/console.js
@@ -9,11 +9,11 @@
 // @ts-expect-error
 import GLib from 'gi://GLib';
 
-const {getTerminalSize: getNativeTerminalSize } =
+const {getTerminalSize: getNativeTerminalSize, clearTerminal} =
     // @ts-expect-error
     import.meta.importSync('console');
 
-export { getNativeTerminalSize };
+export {getNativeTerminalSize};
 
 /**
  * @typedef TerminalSize
@@ -172,7 +172,10 @@ export class Console {
 
     // 1.1.2 clear()
     clear() {
-        throw new Error('clear() is not implemented.');
+        try {
+            // clearTerminal can throw Gio-related errors.
+            clearTerminal();
+        } catch {}
     }
 
     // 1.1.3 debug(...data)


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]