Add util function to get terminal size

This commit is contained in:
Romain Vimont 2021-11-11 15:22:39 +01:00
parent 3f51a2ab43
commit 38332f683c
3 changed files with 74 additions and 0 deletions

View file

@ -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',

51
app/src/util/term.c Normal file
View file

@ -0,0 +1,51 @@
#include "term.h"
#include <assert.h>
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
# include <sys/ioctl.h>
#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
}

21
app/src/util/term.h Normal file
View file

@ -0,0 +1,21 @@
#ifndef SC_TERM_H
#define SC_TERM_H
#include "common.h"
#include <stdbool.h>
/**
* 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