2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
6 #include "../git-compat-util.h"
11 ANSI codes used by git: m, K
13 This file is git-specific. Therefore, this file does not attempt
14 to implement any codes that are not used by git.
17 static HANDLE console;
18 static WORD plain_attr;
21 static int non_ascii_used = 0;
22 static HANDLE hthread, hread, hwrite;
23 static HANDLE hconsole1, hconsole2;
26 #if !defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 5
27 typedef struct _CONSOLE_FONT_INFOEX {
33 WCHAR FaceName[LF_FACESIZE];
34 } CONSOLE_FONT_INFOEX, *PCONSOLE_FONT_INFOEX;
38 typedef BOOL (WINAPI *PGETCURRENTCONSOLEFONTEX)(HANDLE, BOOL,
39 PCONSOLE_FONT_INFOEX);
41 static void warn_if_raster_font(void)
44 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx;
46 /* don't bother if output was ascii only */
50 /* GetCurrentConsoleFontEx is available since Vista */
51 pGetCurrentConsoleFontEx = (PGETCURRENTCONSOLEFONTEX) GetProcAddress(
52 GetModuleHandle("kernel32.dll"),
53 "GetCurrentConsoleFontEx");
54 if (pGetCurrentConsoleFontEx) {
55 CONSOLE_FONT_INFOEX cfi;
56 cfi.cbSize = sizeof(cfi);
57 if (pGetCurrentConsoleFontEx(console, 0, &cfi))
58 fontFamily = cfi.FontFamily;
60 /* pre-Vista: check default console font in registry */
62 if (ERROR_SUCCESS == RegOpenKeyExA(HKEY_CURRENT_USER, "Console",
63 0, KEY_READ, &hkey)) {
64 DWORD size = sizeof(fontFamily);
65 RegQueryValueExA(hkey, "FontFamily", NULL, NULL,
66 (LPVOID) &fontFamily, &size);
71 if (!(fontFamily & TMPF_TRUETYPE)) {
72 const wchar_t *msg = L"\nWarning: Your console font probably "
73 L"doesn\'t support Unicode. If you experience strange "
74 L"characters in the output, consider switching to a "
75 L"TrueType font such as Consolas!\n";
77 WriteConsoleW(console, msg, wcslen(msg), &dummy, NULL);
81 static int is_console(int fd)
83 CONSOLE_SCREEN_BUFFER_INFO sbi;
86 static int initialized = 0;
88 /* get OS handle of the file descriptor */
89 hcon = (HANDLE) _get_osfhandle(fd);
90 if (hcon == INVALID_HANDLE_VALUE)
93 /* check if its a device (i.e. console, printer, serial port) */
94 if (GetFileType(hcon) != FILE_TYPE_CHAR)
97 /* check if its a handle to a console output screen buffer */
98 if (!GetConsoleScreenBufferInfo(hcon, &sbi))
101 /* initialize attributes */
104 attr = plain_attr = sbi.wAttributes;
112 #define BUFFER_SIZE 4096
113 #define MAX_PARAMS 16
115 static void write_console(unsigned char *str, size_t len)
117 /* only called from console_thread, so a static buffer will do */
118 static wchar_t wbuf[2 * BUFFER_SIZE + 1];
121 /* convert utf-8 to utf-16 */
122 int wlen = xutftowcsn(wbuf, (char*) str, ARRAY_SIZE(wbuf), len);
124 /* write directly to console */
125 WriteConsoleW(console, wbuf, wlen, &dummy, NULL);
127 /* remember if non-ascii characters are printed */
132 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
133 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
135 static void set_console_attr(void)
137 WORD attributes = attr;
139 attributes &= ~FOREGROUND_ALL;
140 attributes &= ~BACKGROUND_ALL;
142 /* This could probably use a bitmask
143 instead of a series of ifs */
144 if (attr & FOREGROUND_RED)
145 attributes |= BACKGROUND_RED;
146 if (attr & FOREGROUND_GREEN)
147 attributes |= BACKGROUND_GREEN;
148 if (attr & FOREGROUND_BLUE)
149 attributes |= BACKGROUND_BLUE;
151 if (attr & BACKGROUND_RED)
152 attributes |= FOREGROUND_RED;
153 if (attr & BACKGROUND_GREEN)
154 attributes |= FOREGROUND_GREEN;
155 if (attr & BACKGROUND_BLUE)
156 attributes |= FOREGROUND_BLUE;
158 SetConsoleTextAttribute(console, attributes);
161 static void erase_in_line(void)
163 CONSOLE_SCREEN_BUFFER_INFO sbi;
164 DWORD dummy; /* Needed for Windows 7 (or Vista) regression */
169 GetConsoleScreenBufferInfo(console, &sbi);
170 FillConsoleOutputCharacterA(console, ' ',
171 sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
175 static void set_attr(char func, const int *params, int paramlen)
180 for (i = 0; i < paramlen; i++) {
187 attr |= FOREGROUND_INTENSITY;
190 case 22: /* normal */
191 attr &= ~FOREGROUND_INTENSITY;
196 case 4: /* underline */
197 case 21: /* double underline */
198 /* Wikipedia says this flag does nothing */
199 /* Furthermore, mingw doesn't define this flag
200 attr |= COMMON_LVB_UNDERSCORE; */
202 case 24: /* no underline */
203 /* attr &= ~COMMON_LVB_UNDERSCORE; */
205 case 5: /* slow blink */
206 case 6: /* fast blink */
207 /* We don't have blink, but we do have
208 background intensity */
209 attr |= BACKGROUND_INTENSITY;
211 case 25: /* no blink */
212 attr &= ~BACKGROUND_INTENSITY;
214 case 7: /* negative */
217 case 27: /* positive */
220 case 8: /* conceal */
221 case 28: /* reveal */
225 attr &= ~FOREGROUND_ALL;
228 attr &= ~FOREGROUND_ALL;
229 attr |= FOREGROUND_RED;
232 attr &= ~FOREGROUND_ALL;
233 attr |= FOREGROUND_GREEN;
235 case 33: /* Yellow */
236 attr &= ~FOREGROUND_ALL;
237 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
240 attr &= ~FOREGROUND_ALL;
241 attr |= FOREGROUND_BLUE;
243 case 35: /* Magenta */
244 attr &= ~FOREGROUND_ALL;
245 attr |= FOREGROUND_RED | FOREGROUND_BLUE;
248 attr &= ~FOREGROUND_ALL;
249 attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
252 attr |= FOREGROUND_RED |
256 case 38: /* Unknown */
259 attr &= ~FOREGROUND_ALL;
260 attr |= (plain_attr & FOREGROUND_ALL);
263 attr &= ~BACKGROUND_ALL;
266 attr &= ~BACKGROUND_ALL;
267 attr |= BACKGROUND_RED;
270 attr &= ~BACKGROUND_ALL;
271 attr |= BACKGROUND_GREEN;
273 case 43: /* Yellow */
274 attr &= ~BACKGROUND_ALL;
275 attr |= BACKGROUND_RED | BACKGROUND_GREEN;
278 attr &= ~BACKGROUND_ALL;
279 attr |= BACKGROUND_BLUE;
281 case 45: /* Magenta */
282 attr &= ~BACKGROUND_ALL;
283 attr |= BACKGROUND_RED | BACKGROUND_BLUE;
286 attr &= ~BACKGROUND_ALL;
287 attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
290 attr |= BACKGROUND_RED |
294 case 48: /* Unknown */
297 attr &= ~BACKGROUND_ALL;
298 attr |= (plain_attr & BACKGROUND_ALL);
301 /* Unsupported code */
311 /* Unsupported code */
317 TEXT = 0, ESCAPE = 033, BRACKET = '['
320 static DWORD WINAPI console_thread(LPVOID unused)
322 unsigned char buffer[BUFFER_SIZE];
324 int start, end = 0, c, parampos = 0, state = TEXT;
325 int params[MAX_PARAMS];
328 /* read next chunk of bytes from the pipe */
329 if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
331 /* exit if pipe has been closed or disconnected */
332 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
333 GetLastError() == ERROR_BROKEN_PIPE)
335 /* ignore other errors */
339 /* scan the bytes and handle ANSI control codes */
342 while (end < bytes) {
347 /* print text seen so far */
349 write_console(buffer + start,
352 /* then start parsing escape sequence */
354 memset(params, 0, sizeof(params));
361 /* continue if "\033[", otherwise bail out */
362 state = (c == BRACKET) ? BRACKET : TEXT;
366 /* parse [0-9;]* into array of parameters */
367 if (c >= '0' && c <= '9') {
368 params[parampos] *= 10;
369 params[parampos] += c - '0';
370 } else if (c == ';') {
372 * next parameter, bail out if out of
376 if (parampos >= MAX_PARAMS)
380 * end of escape sequence, change
383 set_attr(c, params, parampos + 1);
391 /* print remaining text unless parsing an escape sequence */
392 if (state == TEXT && end > start) {
393 /* check for incomplete UTF-8 sequences and fix end */
394 if (buffer[end - 1] >= 0x80) {
395 if (buffer[end -1] >= 0xc0)
397 else if (end - 1 > start &&
398 buffer[end - 2] >= 0xe0)
400 else if (end - 2 > start &&
401 buffer[end - 3] >= 0xf0)
405 /* print remaining complete UTF-8 sequences */
407 write_console(buffer + start, end - start);
409 /* move remaining bytes to the front */
411 memmove(buffer, buffer + end, bytes - end);
414 /* all data has been consumed, mark buffer empty */
419 /* check if the console font supports unicode */
420 warn_if_raster_font();
426 static void winansi_exit(void)
428 /* flush all streams */
431 /* signal console thread to exit */
432 FlushFileBuffers(hwrite);
433 DisconnectNamedPipe(hwrite);
435 /* wait for console thread to copy remaining data */
436 WaitForSingleObject(hthread, INFINITE);
438 /* cleanup handles... */
440 CloseHandle(hthread);
443 static void die_lasterr(const char *fmt, ...)
446 va_start(params, fmt);
447 errno = err_win_to_posix(GetLastError());
448 die_errno(fmt, params);
452 static HANDLE duplicate_handle(HANDLE hnd)
454 HANDLE hresult, hproc = GetCurrentProcess();
455 if (!DuplicateHandle(hproc, hnd, hproc, &hresult, 0, TRUE,
456 DUPLICATE_SAME_ACCESS))
457 die_lasterr("DuplicateHandle(%li) failed",
458 (long) (intptr_t) hnd);
464 * Make MSVCRT's internal file descriptor control structure accessible
465 * so that we can tweak OS handles and flags directly (we need MSVCRT
466 * to treat our pipe handle as if it were a console).
468 * We assume that the ioinfo structure (exposed by MSVCRT.dll via
469 * __pioinfo) starts with the OS handle and the flags. The exact size
470 * varies between MSVCRT versions, so we try different sizes until
471 * toggling the FDEV bit of _pioinfo(1)->osflags is reflected in
479 extern __declspec(dllimport) ioinfo *__pioinfo[];
481 static size_t sizeof_ioinfo = 0;
484 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
489 static inline ioinfo* _pioinfo(int fd)
491 return (ioinfo*)((char*)__pioinfo[fd >> IOINFO_L2E] +
492 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
495 static int init_sizeof_ioinfo()
498 /* don't init twice */
500 return sizeof_ioinfo >= 256;
502 sizeof_ioinfo = sizeof(ioinfo);
504 while (sizeof_ioinfo < 256) {
505 /* toggle FDEV flag, check isatty, then toggle back */
506 _pioinfo(1)->osflags ^= FDEV;
508 _pioinfo(1)->osflags ^= FDEV;
509 /* return if we found the correct size */
512 sizeof_ioinfo += sizeof(void*);
514 error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
518 static HANDLE swap_osfhnd(int fd, HANDLE new_handle)
523 /* init ioinfo size if we haven't done so */
524 if (init_sizeof_ioinfo())
525 return INVALID_HANDLE_VALUE;
527 /* get ioinfo pointer and change the handles */
528 pioinfo = _pioinfo(fd);
529 old_handle = pioinfo->osfhnd;
530 pioinfo->osfhnd = new_handle;
534 #ifdef DETECT_MSYS_TTY
536 #include <winternl.h>
537 #include <ntstatus.h>
539 static void detect_msys_tty(int fd)
543 POBJECT_NAME_INFORMATION nameinfo = (POBJECT_NAME_INFORMATION) buffer;
546 /* check if fd is a pipe */
547 HANDLE h = (HANDLE) _get_osfhandle(fd);
548 if (GetFileType(h) != FILE_TYPE_PIPE)
552 if (!NT_SUCCESS(NtQueryObject(h, ObjectNameInformation,
553 buffer, sizeof(buffer) - 2, &result)))
555 name = nameinfo->Name.Buffer;
556 name[nameinfo->Name.Length] = 0;
558 /* check if this could be a MSYS2 pty pipe ('msys-XXXX-ptyN-XX') */
559 if (!wcsstr(name, L"msys-") || !wcsstr(name, L"-pty"))
562 /* init ioinfo size if we haven't done so */
563 if (init_sizeof_ioinfo())
566 /* set FDEV flag, reset FPIPE flag */
567 _pioinfo(fd)->osflags &= ~FPIPE;
568 _pioinfo(fd)->osflags |= FDEV;
573 void winansi_init(void)
578 /* check if either stdout or stderr is a console output screen buffer */
579 con1 = is_console(1);
580 con2 = is_console(2);
581 if (!con1 && !con2) {
582 #ifdef DETECT_MSYS_TTY
583 /* check if stdin / stdout / stderr are MSYS2 pty pipes */
591 /* create a named pipe to communicate with the console thread */
592 xsnprintf(name, sizeof(name), "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
593 hwrite = CreateNamedPipe(name, PIPE_ACCESS_OUTBOUND,
594 PIPE_TYPE_BYTE | PIPE_WAIT, 1, BUFFER_SIZE, 0, 0, NULL);
595 if (hwrite == INVALID_HANDLE_VALUE)
596 die_lasterr("CreateNamedPipe failed");
598 hread = CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
599 if (hread == INVALID_HANDLE_VALUE)
600 die_lasterr("CreateFile for named pipe failed");
602 /* start console spool thread on the pipe's read end */
603 hthread = CreateThread(NULL, 0, console_thread, NULL, 0, NULL);
604 if (hthread == INVALID_HANDLE_VALUE)
605 die_lasterr("CreateThread(console_thread) failed");
607 /* schedule cleanup routine */
608 if (atexit(winansi_exit))
609 die_errno("atexit(winansi_exit) failed");
611 /* redirect stdout / stderr to the pipe */
613 hconsole1 = swap_osfhnd(1, duplicate_handle(hwrite));
615 hconsole2 = swap_osfhnd(2, duplicate_handle(hwrite));
619 * Returns the real console handle if stdout / stderr is a pipe redirecting
620 * to the console. Allows spawn / exec to pass the console to the next process.
622 HANDLE winansi_get_osfhandle(int fd)
624 HANDLE hnd = (HANDLE) _get_osfhandle(fd);
625 if (isatty(fd) && GetFileType(hnd) == FILE_TYPE_PIPE) {
626 if (fd == 1 && hconsole1)
628 else if (fd == 2 && hconsole2)