From 88544847c51397004a31cf2817c334624c6350cf Mon Sep 17 00:00:00 2001 From: Ben Lawrence Date: Fri, 22 Mar 2024 17:03:03 +0000 Subject: [PATCH] Query /dev/tty for the terminal size The device file /dev/tty is available even if stdout is closed or redirected, in which case the width would have been reported as 0 rather than the size of the terminal that we're running in. Tested on both macOS and Linux and behaves as expected. --- include/indicators/terminal_size.hpp | 11 ++++++++--- single_include/indicators/indicators.hpp | 11 ++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/include/indicators/terminal_size.hpp b/include/indicators/terminal_size.hpp index 0d03077..bf82c9f 100644 --- a/include/indicators/terminal_size.hpp +++ b/include/indicators/terminal_size.hpp @@ -24,14 +24,19 @@ static inline size_t terminal_width() { return terminal_size().second; } #else -#include //ioctl() and TIOCGWINSZ -#include // for STDOUT_FILENO +#include // open and O_RDWR +#include // ioctl() and TIOCGWINSZ +#include // close namespace indicators { static inline std::pair terminal_size() { struct winsize size{}; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &size); + int fd = open("/dev/tty", O_RDWR); + if (fd >= 0) { + ioctl(fd, TIOCGWINSZ, &size); + close(fd); + } return {static_cast(size.ws_row), static_cast(size.ws_col)}; } diff --git a/single_include/indicators/indicators.hpp b/single_include/indicators/indicators.hpp index 3832d66..b8b053c 100644 --- a/single_include/indicators/indicators.hpp +++ b/single_include/indicators/indicators.hpp @@ -975,14 +975,19 @@ static inline size_t terminal_width() { return terminal_size().second; } #else -#include //ioctl() and TIOCGWINSZ -#include // for STDOUT_FILENO +#include // open and O_RDWR +#include // ioctl() and TIOCGWINSZ +#include // close namespace indicators { static inline std::pair terminal_size() { struct winsize size{}; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &size); + int fd = open("/dev/tty", O_RDWR); + if (fd >= 0) { + ioctl(fd, TIOCGWINSZ, &size); + close(fd); + } return {static_cast(size.ws_row), static_cast(size.ws_col)}; }