[#1487] ensure that when printing color text the background color of the terminal on windows is preserved (#1865)

Co-authored-by: dominic <510002+dmah42@users.noreply.github.com>
This commit is contained in:
Richard Cole 2024-10-24 12:31:06 +01:00 committed by GitHub
parent ffc727a859
commit 4e3f2d8b67
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -135,19 +135,25 @@ void ColorPrintf(std::ostream& out, LogColor color, const char* fmt,
// Gets the current text color. // Gets the current text color.
CONSOLE_SCREEN_BUFFER_INFO buffer_info; CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
const WORD old_color_attrs = buffer_info.wAttributes; const WORD original_color_attrs = buffer_info.wAttributes;
// We need to flush the stream buffers into the console before each // We need to flush the stream buffers into the console before each
// SetConsoleTextAttribute call lest it affect the text that is already // SetConsoleTextAttribute call lest it affect the text that is already
// printed but has not yet reached the console. // printed but has not yet reached the console.
out.flush(); out.flush();
SetConsoleTextAttribute(stdout_handle,
GetPlatformColorCode(color) | FOREGROUND_INTENSITY); const WORD original_background_attrs =
original_color_attrs & (BACKGROUND_RED | BACKGROUND_GREEN |
BACKGROUND_BLUE | BACKGROUND_INTENSITY);
SetConsoleTextAttribute(stdout_handle, GetPlatformColorCode(color) |
FOREGROUND_INTENSITY |
original_background_attrs);
out << FormatString(fmt, args); out << FormatString(fmt, args);
out.flush(); out.flush();
// Restores the text color. // Restores the text and background color.
SetConsoleTextAttribute(stdout_handle, old_color_attrs); SetConsoleTextAttribute(stdout_handle, original_color_attrs);
#else #else
const char* color_code = GetPlatformColorCode(color); const char* color_code = GetPlatformColorCode(color);
if (color_code) out << FormatString("\033[0;3%sm", color_code); if (color_code) out << FormatString("\033[0;3%sm", color_code);