2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
6 #include "../git-compat-util.h"
10 /* In this file, we actually want to use Windows' own isatty(). */
14 ANSI codes used by git: m, K
16 This file is git-specific. Therefore, this file does not attempt
17 to implement any codes that are not used by git.
20 static HANDLE console
;
21 static WORD plain_attr
;
24 static int non_ascii_used
= 0;
25 static HANDLE hthread
, hread
, hwrite
;
26 static HANDLE hconsole1
, hconsole2
;
29 #if !defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 5
30 typedef struct _CONSOLE_FONT_INFOEX
{
36 WCHAR FaceName
[LF_FACESIZE
];
37 } CONSOLE_FONT_INFOEX
, *PCONSOLE_FONT_INFOEX
;
41 typedef BOOL (WINAPI
*PGETCURRENTCONSOLEFONTEX
)(HANDLE
, BOOL
,
42 PCONSOLE_FONT_INFOEX
);
44 static void warn_if_raster_font(void)
47 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx
;
49 /* don't bother if output was ascii only */
53 /* GetCurrentConsoleFontEx is available since Vista */
54 pGetCurrentConsoleFontEx
= (PGETCURRENTCONSOLEFONTEX
) GetProcAddress(
55 GetModuleHandle("kernel32.dll"),
56 "GetCurrentConsoleFontEx");
57 if (pGetCurrentConsoleFontEx
) {
58 CONSOLE_FONT_INFOEX cfi
;
59 cfi
.cbSize
= sizeof(cfi
);
60 if (pGetCurrentConsoleFontEx(console
, 0, &cfi
))
61 fontFamily
= cfi
.FontFamily
;
63 /* pre-Vista: check default console font in registry */
65 if (ERROR_SUCCESS
== RegOpenKeyExA(HKEY_CURRENT_USER
, "Console",
66 0, KEY_READ
, &hkey
)) {
67 DWORD size
= sizeof(fontFamily
);
68 RegQueryValueExA(hkey
, "FontFamily", NULL
, NULL
,
69 (LPVOID
) &fontFamily
, &size
);
74 if (!(fontFamily
& TMPF_TRUETYPE
)) {
75 const wchar_t *msg
= L
"\nWarning: Your console font probably "
76 L
"doesn\'t support Unicode. If you experience strange "
77 L
"characters in the output, consider switching to a "
78 L
"TrueType font such as Consolas!\n";
80 WriteConsoleW(console
, msg
, wcslen(msg
), &dummy
, NULL
);
84 static int is_console(int fd
)
86 CONSOLE_SCREEN_BUFFER_INFO sbi
;
89 static int initialized
= 0;
91 /* get OS handle of the file descriptor */
92 hcon
= (HANDLE
) _get_osfhandle(fd
);
93 if (hcon
== INVALID_HANDLE_VALUE
)
96 /* check if its a device (i.e. console, printer, serial port) */
97 if (GetFileType(hcon
) != FILE_TYPE_CHAR
)
100 /* check if its a handle to a console output screen buffer */
101 if (!GetConsoleScreenBufferInfo(hcon
, &sbi
))
104 /* initialize attributes */
107 attr
= plain_attr
= sbi
.wAttributes
;
115 #define BUFFER_SIZE 4096
116 #define MAX_PARAMS 16
118 static void write_console(unsigned char *str
, size_t len
)
120 /* only called from console_thread, so a static buffer will do */
121 static wchar_t wbuf
[2 * BUFFER_SIZE
+ 1];
124 /* convert utf-8 to utf-16 */
125 int wlen
= xutftowcsn(wbuf
, (char*) str
, ARRAY_SIZE(wbuf
), len
);
127 /* write directly to console */
128 WriteConsoleW(console
, wbuf
, wlen
, &dummy
, NULL
);
130 /* remember if non-ascii characters are printed */
135 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
136 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
138 static void set_console_attr(void)
140 WORD attributes
= attr
;
142 attributes
&= ~FOREGROUND_ALL
;
143 attributes
&= ~BACKGROUND_ALL
;
145 /* This could probably use a bitmask
146 instead of a series of ifs */
147 if (attr
& FOREGROUND_RED
)
148 attributes
|= BACKGROUND_RED
;
149 if (attr
& FOREGROUND_GREEN
)
150 attributes
|= BACKGROUND_GREEN
;
151 if (attr
& FOREGROUND_BLUE
)
152 attributes
|= BACKGROUND_BLUE
;
154 if (attr
& BACKGROUND_RED
)
155 attributes
|= FOREGROUND_RED
;
156 if (attr
& BACKGROUND_GREEN
)
157 attributes
|= FOREGROUND_GREEN
;
158 if (attr
& BACKGROUND_BLUE
)
159 attributes
|= FOREGROUND_BLUE
;
161 SetConsoleTextAttribute(console
, attributes
);
164 static void erase_in_line(void)
166 CONSOLE_SCREEN_BUFFER_INFO sbi
;
167 DWORD dummy
; /* Needed for Windows 7 (or Vista) regression */
172 GetConsoleScreenBufferInfo(console
, &sbi
);
173 FillConsoleOutputCharacterA(console
, ' ',
174 sbi
.dwSize
.X
- sbi
.dwCursorPosition
.X
, sbi
.dwCursorPosition
,
178 static void set_attr(char func
, const int *params
, int paramlen
)
183 for (i
= 0; i
< paramlen
; i
++) {
190 attr
|= FOREGROUND_INTENSITY
;
193 case 22: /* normal */
194 attr
&= ~FOREGROUND_INTENSITY
;
199 case 4: /* underline */
200 case 21: /* double underline */
201 /* Wikipedia says this flag does nothing */
202 /* Furthermore, mingw doesn't define this flag
203 attr |= COMMON_LVB_UNDERSCORE; */
205 case 24: /* no underline */
206 /* attr &= ~COMMON_LVB_UNDERSCORE; */
208 case 5: /* slow blink */
209 case 6: /* fast blink */
210 /* We don't have blink, but we do have
211 background intensity */
212 attr
|= BACKGROUND_INTENSITY
;
214 case 25: /* no blink */
215 attr
&= ~BACKGROUND_INTENSITY
;
217 case 7: /* negative */
220 case 27: /* positive */
223 case 8: /* conceal */
224 case 28: /* reveal */
228 attr
&= ~FOREGROUND_ALL
;
231 attr
&= ~FOREGROUND_ALL
;
232 attr
|= FOREGROUND_RED
;
235 attr
&= ~FOREGROUND_ALL
;
236 attr
|= FOREGROUND_GREEN
;
238 case 33: /* Yellow */
239 attr
&= ~FOREGROUND_ALL
;
240 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
;
243 attr
&= ~FOREGROUND_ALL
;
244 attr
|= FOREGROUND_BLUE
;
246 case 35: /* Magenta */
247 attr
&= ~FOREGROUND_ALL
;
248 attr
|= FOREGROUND_RED
| FOREGROUND_BLUE
;
251 attr
&= ~FOREGROUND_ALL
;
252 attr
|= FOREGROUND_GREEN
| FOREGROUND_BLUE
;
255 attr
|= FOREGROUND_RED
|
259 case 38: /* Unknown */
262 attr
&= ~FOREGROUND_ALL
;
263 attr
|= (plain_attr
& FOREGROUND_ALL
);
266 attr
&= ~BACKGROUND_ALL
;
269 attr
&= ~BACKGROUND_ALL
;
270 attr
|= BACKGROUND_RED
;
273 attr
&= ~BACKGROUND_ALL
;
274 attr
|= BACKGROUND_GREEN
;
276 case 43: /* Yellow */
277 attr
&= ~BACKGROUND_ALL
;
278 attr
|= BACKGROUND_RED
| BACKGROUND_GREEN
;
281 attr
&= ~BACKGROUND_ALL
;
282 attr
|= BACKGROUND_BLUE
;
284 case 45: /* Magenta */
285 attr
&= ~BACKGROUND_ALL
;
286 attr
|= BACKGROUND_RED
| BACKGROUND_BLUE
;
289 attr
&= ~BACKGROUND_ALL
;
290 attr
|= BACKGROUND_GREEN
| BACKGROUND_BLUE
;
293 attr
|= BACKGROUND_RED
|
297 case 48: /* Unknown */
300 attr
&= ~BACKGROUND_ALL
;
301 attr
|= (plain_attr
& BACKGROUND_ALL
);
304 /* Unsupported code */
314 /* Unsupported code */
320 TEXT
= 0, ESCAPE
= 033, BRACKET
= '['
323 static DWORD WINAPI
console_thread(LPVOID unused
)
325 unsigned char buffer
[BUFFER_SIZE
];
327 int start
, end
= 0, c
, parampos
= 0, state
= TEXT
;
328 int params
[MAX_PARAMS
];
331 /* read next chunk of bytes from the pipe */
332 if (!ReadFile(hread
, buffer
+ end
, BUFFER_SIZE
- end
, &bytes
,
334 /* exit if pipe has been closed or disconnected */
335 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED
||
336 GetLastError() == ERROR_BROKEN_PIPE
)
338 /* ignore other errors */
342 /* scan the bytes and handle ANSI control codes */
345 while (end
< bytes
) {
350 /* print text seen so far */
352 write_console(buffer
+ start
,
355 /* then start parsing escape sequence */
357 memset(params
, 0, sizeof(params
));
364 /* continue if "\033[", otherwise bail out */
365 state
= (c
== BRACKET
) ? BRACKET
: TEXT
;
369 /* parse [0-9;]* into array of parameters */
370 if (c
>= '0' && c
<= '9') {
371 params
[parampos
] *= 10;
372 params
[parampos
] += c
- '0';
373 } else if (c
== ';') {
375 * next parameter, bail out if out of
379 if (parampos
>= MAX_PARAMS
)
383 * end of escape sequence, change
386 set_attr(c
, params
, parampos
+ 1);
394 /* print remaining text unless parsing an escape sequence */
395 if (state
== TEXT
&& end
> start
) {
396 /* check for incomplete UTF-8 sequences and fix end */
397 if (buffer
[end
- 1] >= 0x80) {
398 if (buffer
[end
-1] >= 0xc0)
400 else if (end
- 1 > start
&&
401 buffer
[end
- 2] >= 0xe0)
403 else if (end
- 2 > start
&&
404 buffer
[end
- 3] >= 0xf0)
408 /* print remaining complete UTF-8 sequences */
410 write_console(buffer
+ start
, end
- start
);
412 /* move remaining bytes to the front */
414 memmove(buffer
, buffer
+ end
, bytes
- end
);
417 /* all data has been consumed, mark buffer empty */
422 /* check if the console font supports unicode */
423 warn_if_raster_font();
429 static void winansi_exit(void)
431 /* flush all streams */
434 /* signal console thread to exit */
435 FlushFileBuffers(hwrite
);
436 DisconnectNamedPipe(hwrite
);
438 /* wait for console thread to copy remaining data */
439 WaitForSingleObject(hthread
, INFINITE
);
441 /* cleanup handles... */
443 CloseHandle(hthread
);
446 static void die_lasterr(const char *fmt
, ...)
449 va_start(params
, fmt
);
450 errno
= err_win_to_posix(GetLastError());
451 die_errno(fmt
, params
);
455 static HANDLE
duplicate_handle(HANDLE hnd
)
457 HANDLE hresult
, hproc
= GetCurrentProcess();
458 if (!DuplicateHandle(hproc
, hnd
, hproc
, &hresult
, 0, TRUE
,
459 DUPLICATE_SAME_ACCESS
))
460 die_lasterr("DuplicateHandle(%li) failed",
461 (long) (intptr_t) hnd
);
467 * Make MSVCRT's internal file descriptor control structure accessible
468 * so that we can tweak OS handles and flags directly (we need MSVCRT
469 * to treat our pipe handle as if it were a console).
471 * We assume that the ioinfo structure (exposed by MSVCRT.dll via
472 * __pioinfo) starts with the OS handle and the flags. The exact size
473 * varies between MSVCRT versions, so we try different sizes until
474 * toggling the FDEV bit of _pioinfo(1)->osflags is reflected in
482 extern __declspec(dllimport
) ioinfo
*__pioinfo
[];
484 static size_t sizeof_ioinfo
= 0;
487 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
492 static inline ioinfo
* _pioinfo(int fd
)
494 return (ioinfo
*)((char*)__pioinfo
[fd
>> IOINFO_L2E
] +
495 (fd
& (IOINFO_ARRAY_ELTS
- 1)) * sizeof_ioinfo
);
498 static int init_sizeof_ioinfo(void)
501 /* don't init twice */
503 return sizeof_ioinfo
>= 256;
505 sizeof_ioinfo
= sizeof(ioinfo
);
507 while (sizeof_ioinfo
< 256) {
508 /* toggle FDEV flag, check isatty, then toggle back */
509 _pioinfo(1)->osflags
^= FDEV
;
511 _pioinfo(1)->osflags
^= FDEV
;
512 /* return if we found the correct size */
515 sizeof_ioinfo
+= sizeof(void*);
517 error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
521 static HANDLE
swap_osfhnd(int fd
, HANDLE new_handle
)
526 /* init ioinfo size if we haven't done so */
527 if (init_sizeof_ioinfo())
528 return INVALID_HANDLE_VALUE
;
530 /* get ioinfo pointer and change the handles */
531 pioinfo
= _pioinfo(fd
);
532 old_handle
= pioinfo
->osfhnd
;
533 pioinfo
->osfhnd
= new_handle
;
537 #ifdef DETECT_MSYS_TTY
539 #include <winternl.h>
540 #include <ntstatus.h>
542 static void detect_msys_tty(int fd
)
546 POBJECT_NAME_INFORMATION nameinfo
= (POBJECT_NAME_INFORMATION
) buffer
;
549 /* check if fd is a pipe */
550 HANDLE h
= (HANDLE
) _get_osfhandle(fd
);
551 if (GetFileType(h
) != FILE_TYPE_PIPE
)
555 if (!NT_SUCCESS(NtQueryObject(h
, ObjectNameInformation
,
556 buffer
, sizeof(buffer
) - 2, &result
)))
558 name
= nameinfo
->Name
.Buffer
;
559 name
[nameinfo
->Name
.Length
] = 0;
561 /* check if this could be a MSYS2 pty pipe ('msys-XXXX-ptyN-XX') */
562 if (!wcsstr(name
, L
"msys-") || !wcsstr(name
, L
"-pty"))
565 /* init ioinfo size if we haven't done so */
566 if (init_sizeof_ioinfo())
569 /* set FDEV flag, reset FPIPE flag */
570 _pioinfo(fd
)->osflags
&= ~FPIPE
;
571 _pioinfo(fd
)->osflags
|= FDEV
;
576 int winansi_isatty(int fd
)
578 int res
= isatty(fd
);
582 * Make sure that /dev/null is not fooling Git into believing
583 * that we are connected to a terminal, as "_isatty() returns a
584 * nonzero value if the descriptor is associated with a
585 * character device."; for more information, see
587 * https://msdn.microsoft.com/en-us/library/f4s0ddew.aspx
589 HANDLE handle
= (HANDLE
)_get_osfhandle(fd
);
590 if (fd
== STDIN_FILENO
) {
593 if (!GetConsoleMode(handle
, &dummy
))
595 } else if (fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
) {
596 CONSOLE_SCREEN_BUFFER_INFO dummy
;
598 if (!GetConsoleScreenBufferInfo(handle
, &dummy
))
606 void winansi_init(void)
611 /* check if either stdout or stderr is a console output screen buffer */
612 con1
= is_console(1);
613 con2
= is_console(2);
614 if (!con1
&& !con2
) {
615 #ifdef DETECT_MSYS_TTY
616 /* check if stdin / stdout / stderr are MSYS2 pty pipes */
624 /* create a named pipe to communicate with the console thread */
625 xsnprintf(name
, sizeof(name
), "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
626 hwrite
= CreateNamedPipe(name
, PIPE_ACCESS_OUTBOUND
,
627 PIPE_TYPE_BYTE
| PIPE_WAIT
, 1, BUFFER_SIZE
, 0, 0, NULL
);
628 if (hwrite
== INVALID_HANDLE_VALUE
)
629 die_lasterr("CreateNamedPipe failed");
631 hread
= CreateFile(name
, GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
632 if (hread
== INVALID_HANDLE_VALUE
)
633 die_lasterr("CreateFile for named pipe failed");
635 /* start console spool thread on the pipe's read end */
636 hthread
= CreateThread(NULL
, 0, console_thread
, NULL
, 0, NULL
);
637 if (hthread
== INVALID_HANDLE_VALUE
)
638 die_lasterr("CreateThread(console_thread) failed");
640 /* schedule cleanup routine */
641 if (atexit(winansi_exit
))
642 die_errno("atexit(winansi_exit) failed");
644 /* redirect stdout / stderr to the pipe */
646 hconsole1
= swap_osfhnd(1, duplicate_handle(hwrite
));
648 hconsole2
= swap_osfhnd(2, duplicate_handle(hwrite
));
652 * Returns the real console handle if stdout / stderr is a pipe redirecting
653 * to the console. Allows spawn / exec to pass the console to the next process.
655 HANDLE
winansi_get_osfhandle(int fd
)
657 HANDLE hnd
= (HANDLE
) _get_osfhandle(fd
);
658 if (isatty(fd
) && GetFileType(hnd
) == FILE_TYPE_PIPE
) {
659 if (fd
== 1 && hconsole1
)
661 else if (fd
== 2 && hconsole2
)