Skip to content

Commit

Permalink
console, feat: output ANSI colors directly on Windows 10.
Browse files Browse the repository at this point in the history
  • Loading branch information
xicilion committed Feb 6, 2021
1 parent b41016e commit 4d138b2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 12 deletions.
41 changes: 30 additions & 11 deletions fibjs/src/console/console_std.cpp
Expand Up @@ -21,12 +21,8 @@ void std_logger::out(exlib::string& txt)
color_out()
{
tty_base::isatty(_fileno(stdout), m_tty);

if (!m_tty) {
m_handle = GetStdHandle(STD_OUTPUT_HANDLE);
m_Now = m_wAttr = 0x7;
m_wLight = m_wAttr & FOREGROUND_INTENSITY;
}
m_handle = NULL;
m_ansi = false;
}

void WriteConsole(exlib::wchar* ptr, size_t sz)
Expand All @@ -43,6 +39,17 @@ void std_logger::out(exlib::string& txt)
}
}

void set_ansi()
{
DWORD consoleMode = 0;

GetConsoleMode(m_handle, &consoleMode);
if ((consoleMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == ENABLE_VIRTUAL_TERMINAL_PROCESSING)
m_ansi = true;
else if (SetConsoleMode(m_handle, consoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
m_ansi = true;
}

void out(exlib::string& s)
{
static HANDLE s_console;
Expand All @@ -54,13 +61,19 @@ void std_logger::out(exlib::string& txt)

if (!m_handle) {
if (!s_console) {
AllocConsole();
s_console = GetStdHandle(STD_OUTPUT_HANDLE);

freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
if (s_console == NULL) {
AllocConsole();

s_console = GetStdHandle(STD_OUTPUT_HANDLE);
s_console = GetStdHandle(STD_OUTPUT_HANDLE);
set_ansi();

freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
} else
set_ansi();
}

m_handle = s_console;
Expand All @@ -74,6 +87,11 @@ void std_logger::out(exlib::string& txt)
exlib::wchar* ptr1;
exlib::wchar* ptr2;

if (m_ansi) {
WriteConsole(ptr, ws.length());
return;
}

while (ptr1 = (exlib::wchar*)qstrstr(ptr, L"\x1b[")) {
for (ptr2 = ptr1 + 2; *ptr2 == ';' || qisdigit(ptr2[0]); ptr2++)
;
Expand Down Expand Up @@ -131,6 +149,7 @@ void std_logger::out(exlib::string& txt)
WORD m_wAttr, m_Now;
WORD m_wLight;
bool m_tty;
bool m_ansi;
};

static color_out s_out;
Expand Down
10 changes: 9 additions & 1 deletion fibjs/src/console/tty.cpp
Expand Up @@ -10,12 +10,20 @@ DECLARE_MODULE(tty);

result_t tty_base::isatty(int32_t fd, bool& retVal)
{
#ifndef _WIN32
if (fd < 0)
return CHECK_ERROR(CALL_E_INVALID_CALL);

#ifndef _WIN32
int32_t hr = ::isatty(fd);
#else
if (fd == -2) {
retVal = true;
return 0;
}

if (fd < 0)
return CHECK_ERROR(CALL_E_INVALID_CALL);

int32_t hr = _isatty(fd);
if (hr == FALSE && _lseek(fd, 0, SEEK_CUR) < 0)
hr = TRUE;
Expand Down

0 comments on commit 4d138b2

Please sign in to comment.