From fb14ceb0d0f4937e7b00aaa5b63ce6c28daa8f10 Mon Sep 17 00:00:00 2001 From: Chris Antos Date: Fri, 17 Nov 2023 14:49:54 -0800 Subject: [PATCH] Detect light/dark theme when using legacy conhost. Can't work in Windows Terminal until Terminal#10639 is fixed. https://github.com/microsoft/terminal/issues/10639 --- clink/app/src/host/host.cpp | 7 +++++++ clink/lua/src/console_api.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/clink/app/src/host/host.cpp b/clink/app/src/host/host.cpp index 4156841b1..07fcc5eb9 100644 --- a/clink/app/src/host/host.cpp +++ b/clink/app/src/host/host.cpp @@ -872,6 +872,13 @@ bool host::edit_line(const char* prompt, const char* rprompt, str_base& out, boo lua.load_scripts(); } + // Detect light vs dark console theme. + if (send_event) + { + extern void detect_console_default_attr(); + detect_console_default_attr(); + } + // Send oninject event; one time only. static bool s_injected = false; if (send_event && !s_injected) diff --git a/clink/lua/src/console_api.cpp b/clink/lua/src/console_api.cpp index 50e26a49e..8b47447d4 100644 --- a/clink/lua/src/console_api.cpp +++ b/clink/lua/src/console_api.cpp @@ -31,6 +31,20 @@ static SHORT GetConsoleNumLines(const CONSOLE_SCREEN_BUFFER_INFO& csbi) return bottom_Y + 1; } +//------------------------------------------------------------------------------ +static uint16 s_default_attr = 0x07; +void detect_console_default_attr() +{ + s_default_attr = 0x07; + + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); + if (!GetConsoleScreenBufferInfo(h, &csbiInfo)) + return; + + s_default_attr = csbiInfo.wAttributes; +} + //------------------------------------------------------------------------------ class input_scope { @@ -813,6 +827,22 @@ static int32 get_color_table(lua_State* state) lua_rawset(state, -3); } + // Luminance range is 0..3000 inclusive. + #define luminance(cr) \ + (((299 * DWORD(GetRValue(cr))) + \ + (587 * DWORD(GetGValue(cr))) + \ + (114 * DWORD(GetBValue(cr)))) / 85) + + const uint32 lum_bg = luminance(csbix.ColorTable[(s_default_attr & 0xf0) >> 4]); + if (lum_bg > luminance(RGB(128, 128, 128))) + { + lua_pushliteral(state, "light"); + lua_pushboolean(state, true); + lua_rawset(state, -3); + } + + #undef luminance + return 1; }