-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathathr_terminal_win32.c
83 lines (71 loc) · 1.62 KB
/
athr_terminal_win32.c
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "athr_terminal_win32.h"
#include "athr_logger.h"
#include "athr_terminal.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define error(msg) athr_logger_error(athr_logger_format(msg))
static long tput_cols(void)
{
char buff[16] = {0};
FILE *fd = NULL;
long ncols = -1;
if (!(fd = _popen("tput cols", "r")))
{
error("failed to run tput");
goto cleanup;
}
if (!fgets(buff, 16, fd))
{
error("fgets failed");
goto cleanup;
}
if (!buff[0])
{
error("fgets read failed");
goto cleanup;
}
char *end = NULL;
long tentative = strtol(buff, &end, 10);
if (*end == '\n') *end = 0;
if (*end)
{
error("invalid number");
goto cleanup;
}
if (tentative < 0)
{
error("ncols underflow");
goto cleanup;
}
if ((unsigned long)tentative > UINT_MAX)
{
error("ncols overflow");
goto cleanup;
}
ncols = (unsigned)tentative;
cleanup:
if (fd) _pclose(fd);
return ncols;
}
unsigned athr_terminal_win32_width(void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE hdl = GetStdHandle(STD_OUTPUT_HANDLE);
if (hdl == INVALID_HANDLE_VALUE)
{
error("invalid handle");
goto fallback;
}
if (GetConsoleScreenBufferInfo(hdl, &csbi) == 0)
{
error("failed to get screen info");
goto fallback;
}
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
long ncols = -1;
fallback:
ncols = tput_cols();
return ncols == -1 ? athr_terminal_fallback_width() : (unsigned)ncols;
}