From 38332f683c6744725d8f197f16fe513d4a287ee9 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Thu, 11 Nov 2021 15:22:39 +0100 Subject: [PATCH] Add util function to get terminal size --- app/meson.build | 2 ++ app/src/util/term.c | 51 +++++++++++++++++++++++++++++++++++++++++++++ app/src/util/term.h | 21 +++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 app/src/util/term.c create mode 100644 app/src/util/term.h diff --git a/app/meson.build b/app/meson.build index 0e33c084..d13e421e 100644 --- a/app/meson.build +++ b/app/meson.build @@ -29,6 +29,7 @@ src = [ 'src/util/process.c', 'src/util/strbuf.c', 'src/util/str_util.c', + 'src/util/term.c', 'src/util/thread.c', 'src/util/tick.c', ] @@ -189,6 +190,7 @@ if get_option('buildtype') == 'debug' 'src/options.c', 'src/util/strbuf.c', 'src/util/str_util.c', + 'src/util/term.c', ]], ['test_clock', [ 'tests/test_clock.c', diff --git a/app/src/util/term.c b/app/src/util/term.c new file mode 100644 index 00000000..ff6bc4b1 --- /dev/null +++ b/app/src/util/term.c @@ -0,0 +1,51 @@ +#include "term.h" + +#include + +#ifdef _WIN32 +# include +#else +# include +# include +#endif + +bool +sc_term_get_size(unsigned *rows, unsigned *cols) { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbi; + + bool ok = + GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); + if (!ok) { + return false; + } + + if (rows) { + assert(csbi.srWindow.Bottom >= csbi.srWindow.Top); + *rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; + } + + if (cols) { + assert(csbi.srWindow.Right >= csbi.srWindow.Left); + *cols = csbi.srWindow.Right - csbi.srWindow.Left + 1; + } + + return true; +#else + struct winsize ws; + int r = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws); + if (r == -1) { + return false; + } + + if (rows) { + *rows = ws.ws_row; + } + + if (cols) { + *cols = ws.ws_col; + } + + return true; +#endif +} diff --git a/app/src/util/term.h b/app/src/util/term.h new file mode 100644 index 00000000..0211bcb4 --- /dev/null +++ b/app/src/util/term.h @@ -0,0 +1,21 @@ +#ifndef SC_TERM_H +#define SC_TERM_H + +#include "common.h" + +#include + +/** + * Return the terminal dimensions + * + * Return false if the dimensions could not be retrieved. + * + * Otherwise, return true, and: + * - if `rows` is not NULL, then the number of rows is written to `*rows`. + * - if `columns` is not NULL, then the number of columns is written to + * `*columns`. + */ +bool +sc_term_get_size(unsigned *rows, unsigned *cols); + +#endif