summaryrefslogtreecommitdiffstats
path: root/src/detection/terminalsize/terminalsize_linux.c
blob: e06f958b2ef01b1c191051a5bb6a24298b04c6bc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "terminalsize.h"
#include "common/io.h"

#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>

#ifdef __sun
    #include <sys/termios.h>
#endif

bool ffDetectTerminalSize(FFTerminalSizeResult* result) {
    struct winsize winsize = {};
    static int ttyfd = STDOUT_FILENO;
    if (!isatty(ttyfd)) {
        ttyfd = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC);
    }

    ioctl(ttyfd, TIOCGWINSZ, &winsize);

    if (winsize.ws_row == 0 || winsize.ws_col == 0) {
        ffGetTerminalResponse("\e[18t", 2, "\e[8;%hu;%hut", &winsize.ws_row, &winsize.ws_col);
    }

    if (winsize.ws_ypixel == 0 || winsize.ws_xpixel == 0) {
        ffGetTerminalResponse("\e[14t", 2, "\e[4;%hu;%hut", &winsize.ws_ypixel, &winsize.ws_xpixel);
    }

    if (winsize.ws_row == 0 && winsize.ws_col == 0) {
        return false;
    }

    result->rows = winsize.ws_row;
    result->columns = winsize.ws_col;
    result->width = winsize.ws_xpixel;
    result->height = winsize.ws_ypixel;
    return true;
}