From 6e80640db5a6b04f666342901293bab888a61b78 Mon Sep 17 00:00:00 2001 From: Martchus Date: Fri, 29 Sep 2017 20:56:50 +0200 Subject: [PATCH] Add method to determine terminal size --- application/commandlineutils.cpp | 29 ++++++++++++++++++++++++++++- application/commandlineutils.h | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/application/commandlineutils.cpp b/application/commandlineutils.cpp index 90ab653..385dcba 100644 --- a/application/commandlineutils.cpp +++ b/application/commandlineutils.cpp @@ -3,7 +3,10 @@ #include #include -#ifdef PLATFORM_WINDOWS +#ifndef PLATFORM_WINDOWS +#include +#include +#else #include #include #endif @@ -36,6 +39,30 @@ bool confirmPrompt(const char *message, Response defaultResponse) } } +/*! + * \brief Returns the current size of the terminal. + * \remarks Unknown members of the returned TerminalSize are set to zero. + */ +TerminalSize determineTerminalSize() +{ + TerminalSize size; +#ifndef PLATFORM_WINDOWS + ioctl(STDOUT_FILENO, TIOCGWINSZ, reinterpret_cast(&size)); +#else + CONSOLE_SCREEN_BUFFER_INFO consoleBufferInfo; + if (const HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE)) { + GetConsoleScreenBufferInfo(stdHandle, &consoleBufferInfo); + if (consoleBufferInfo.dwSize.X > 0) { + size.rows = static_cast(consoleBufferInfo.dwSize.X); + } + if (consoleBufferInfo.dwSize.Y > 0) { + size.columns = static_cast(consoleBufferInfo.dwSize.Y); + } + } +#endif + return size; +} + #ifdef PLATFORM_WINDOWS /*! * \brief Closes stdout, stdin and stderr and stops the console. diff --git a/application/commandlineutils.h b/application/commandlineutils.h index 20f63f3..48da79a 100644 --- a/application/commandlineutils.h +++ b/application/commandlineutils.h @@ -32,6 +32,34 @@ std::pair>, std::vector> CPP_UTILITI #define CMD_UTILS_CONVERT_ARGS_TO_UTF8 #endif +/*! + * \brief The TerminalSize struct describes a terminal size. + * \remarks The same as the winsize structure is defined in `sys/ioctl.h`. + * \sa determineTerminalSize() + */ +struct TerminalSize { + TerminalSize(unsigned short rows = 0, unsigned short columns = 0, unsigned short width = 0, unsigned short height = 0); + + /// \brief number of rows + unsigned short rows; + /// \brief number of columns + unsigned short columns; + /// \brief width in pixel + unsigned short width; + /// \brief height in pixel + unsigned short height; +}; + +inline TerminalSize::TerminalSize(unsigned short rows, unsigned short columns, unsigned short width, unsigned short height) + : rows(rows) + , columns(columns) + , width(width) + , height(height) +{ +} + +TerminalSize determineTerminalSize(); + /*! * \brief The Indentation class allows printing indentation conveniently, eg. cout << Indentation(4) << ... */