master ohmu/fastfetch-openbsd / src / detection / terminalsize / terminalsize_windows.c
ohmu  ·  2026-10-15
 1#include "terminalsize.h"
 2#include "common/io.h"
 3
 4#include <windows.h>
 5
 6bool ffDetectTerminalSize(FFTerminalSizeResult* result, bool fastOnly) {
 7    *result = (FFTerminalSizeResult){};
 8
 9    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
10    FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE;
11    {
12        DWORD outputMode;
13        if (!GetConsoleMode(hOutput, &outputMode)) {
14            hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, nullptr);
15            hOutput = hConout;
16        }
17    }
18    {
19        CONSOLE_SCREEN_BUFFER_INFO csbi;
20        if (GetConsoleScreenBufferInfo(hOutput, &csbi)) {
21            result->columns = (uint16_t) (csbi.srWindow.Right - csbi.srWindow.Left + 1);
22            result->rows = (uint16_t) (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
23        } else if (!fastOnly) {
24            // Windows Terminal doesn't report `\e` for some reason
25            ffGetTerminalResponse("\e[18t", 2, "%*[^;];%hu;%hut", &result->rows, &result->columns);
26        }
27    }
28
29    if (result->columns == 0 || result->rows == 0) {
30        return false;
31    }
32
33    if (fastOnly) {
34        return true;
35    }
36
37    {
38        CONSOLE_FONT_INFOEX cfi = { .cbSize = sizeof(cfi) };
39        if (GetCurrentConsoleFontEx(hOutput, FALSE, &cfi)) // Only works for ConHost
40        {
41            result->width = result->columns * (uint16_t) cfi.dwFontSize.X;
42            result->height = result->rows * (uint16_t) cfi.dwFontSize.Y;
43        }
44        if (result->width == 0 || result->height == 0) {
45            // Windows Terminal doesn't report `\e` for some reason
46            ffGetTerminalResponse("\e[14t", 2, "%*[^;];%hu;%hut", &result->height, &result->width);
47        }
48    }
49
50    return true;
51}