Skip to content

Commit

Permalink
Detect light/dark theme when using legacy conhost.
Browse files Browse the repository at this point in the history
Can't work in Windows Terminal until Terminal#10639 is fixed.
microsoft/terminal#10639
  • Loading branch information
chrisant996 committed Nov 17, 2023
1 parent 050ca1c commit fb14ceb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions clink/app/src/host/host.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
30 changes: 30 additions & 0 deletions clink/lua/src/console_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit fb14ceb

Please sign in to comment.