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 hwrite1
= INVALID_HANDLE_VALUE
, hwrite2
= INVALID_HANDLE_VALUE
;
24 static HANDLE hconsole1
, hconsole2
;
27 typedef struct _CONSOLE_FONT_INFOEX
{
33 WCHAR FaceName
[LF_FACESIZE
];
34 } CONSOLE_FONT_INFOEX
, *PCONSOLE_FONT_INFOEX
;
37 typedef BOOL (WINAPI
*PGETCURRENTCONSOLEFONTEX
)(HANDLE
, BOOL
,
38 PCONSOLE_FONT_INFOEX
);
40 static void warn_if_raster_font(void)
43 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx
;
45 /* don't bother if output was ascii only */
49 /* GetCurrentConsoleFontEx is available since Vista */
50 pGetCurrentConsoleFontEx
= (PGETCURRENTCONSOLEFONTEX
) GetProcAddress(
51 GetModuleHandle("kernel32.dll"),
52 "GetCurrentConsoleFontEx");
53 if (pGetCurrentConsoleFontEx
) {
54 CONSOLE_FONT_INFOEX cfi
;
55 cfi
.cbSize
= sizeof(cfi
);
56 if (pGetCurrentConsoleFontEx(console
, 0, &cfi
))
57 fontFamily
= cfi
.FontFamily
;
59 /* pre-Vista: check default console font in registry */
61 if (ERROR_SUCCESS
== RegOpenKeyExA(HKEY_CURRENT_USER
, "Console",
62 0, KEY_READ
, &hkey
)) {
63 DWORD size
= sizeof(fontFamily
);
64 RegQueryValueExA(hkey
, "FontFamily", NULL
, NULL
,
65 (LPVOID
) &fontFamily
, &size
);
70 if (!(fontFamily
& TMPF_TRUETYPE
)) {
71 const wchar_t *msg
= L
"\nWarning: Your console font probably "
72 L
"doesn\'t support Unicode. If you experience strange "
73 L
"characters in the output, consider switching to a "
74 L
"TrueType font such as Lucida Console!\n";
76 WriteConsoleW(console
, msg
, wcslen(msg
), &dummy
, NULL
);
80 static int is_console(int fd
)
82 CONSOLE_SCREEN_BUFFER_INFO sbi
;
85 static int initialized
= 0;
87 /* get OS handle of the file descriptor */
88 hcon
= (HANDLE
) _get_osfhandle(fd
);
89 if (hcon
== INVALID_HANDLE_VALUE
)
92 /* check if its a device (i.e. console, printer, serial port) */
93 if (GetFileType(hcon
) != FILE_TYPE_CHAR
)
96 /* check if its a handle to a console output screen buffer */
97 if (!GetConsoleScreenBufferInfo(hcon
, &sbi
))
100 /* initialize attributes */
103 attr
= plain_attr
= sbi
.wAttributes
;
111 #define BUFFER_SIZE 4096
112 #define MAX_PARAMS 16
114 static void write_console(unsigned char *str
, size_t len
)
116 /* only called from console_thread, so a static buffer will do */
117 static wchar_t wbuf
[2 * BUFFER_SIZE
+ 1];
120 /* convert utf-8 to utf-16 */
121 int wlen
= xutftowcsn(wbuf
, (char*) str
, ARRAY_SIZE(wbuf
), len
);
123 /* write directly to console */
124 WriteConsoleW(console
, wbuf
, wlen
, &dummy
, NULL
);
126 /* remember if non-ascii characters are printed */
131 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
132 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
134 static void set_console_attr(void)
136 WORD attributes
= attr
;
138 attributes
&= ~FOREGROUND_ALL
;
139 attributes
&= ~BACKGROUND_ALL
;
141 /* This could probably use a bitmask
142 instead of a series of ifs */
143 if (attr
& FOREGROUND_RED
)
144 attributes
|= BACKGROUND_RED
;
145 if (attr
& FOREGROUND_GREEN
)
146 attributes
|= BACKGROUND_GREEN
;
147 if (attr
& FOREGROUND_BLUE
)
148 attributes
|= BACKGROUND_BLUE
;
150 if (attr
& BACKGROUND_RED
)
151 attributes
|= FOREGROUND_RED
;
152 if (attr
& BACKGROUND_GREEN
)
153 attributes
|= FOREGROUND_GREEN
;
154 if (attr
& BACKGROUND_BLUE
)
155 attributes
|= FOREGROUND_BLUE
;
157 SetConsoleTextAttribute(console
, attributes
);
160 static void erase_in_line(void)
162 CONSOLE_SCREEN_BUFFER_INFO sbi
;
163 DWORD dummy
; /* Needed for Windows 7 (or Vista) regression */
168 GetConsoleScreenBufferInfo(console
, &sbi
);
169 FillConsoleOutputCharacterA(console
, ' ',
170 sbi
.dwSize
.X
- sbi
.dwCursorPosition
.X
, sbi
.dwCursorPosition
,
174 static void set_attr(char func
, const int *params
, int paramlen
)
179 for (i
= 0; i
< paramlen
; i
++) {
186 attr
|= FOREGROUND_INTENSITY
;
189 case 22: /* normal */
190 attr
&= ~FOREGROUND_INTENSITY
;
195 case 4: /* underline */
196 case 21: /* double underline */
197 /* Wikipedia says this flag does nothing */
198 /* Furthermore, mingw doesn't define this flag
199 attr |= COMMON_LVB_UNDERSCORE; */
201 case 24: /* no underline */
202 /* attr &= ~COMMON_LVB_UNDERSCORE; */
204 case 5: /* slow blink */
205 case 6: /* fast blink */
206 /* We don't have blink, but we do have
207 background intensity */
208 attr
|= BACKGROUND_INTENSITY
;
210 case 25: /* no blink */
211 attr
&= ~BACKGROUND_INTENSITY
;
213 case 7: /* negative */
216 case 27: /* positive */
219 case 8: /* conceal */
220 case 28: /* reveal */
224 attr
&= ~FOREGROUND_ALL
;
227 attr
&= ~FOREGROUND_ALL
;
228 attr
|= FOREGROUND_RED
;
231 attr
&= ~FOREGROUND_ALL
;
232 attr
|= FOREGROUND_GREEN
;
234 case 33: /* Yellow */
235 attr
&= ~FOREGROUND_ALL
;
236 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
;
239 attr
&= ~FOREGROUND_ALL
;
240 attr
|= FOREGROUND_BLUE
;
242 case 35: /* Magenta */
243 attr
&= ~FOREGROUND_ALL
;
244 attr
|= FOREGROUND_RED
| FOREGROUND_BLUE
;
247 attr
&= ~FOREGROUND_ALL
;
248 attr
|= FOREGROUND_GREEN
| FOREGROUND_BLUE
;
251 attr
|= FOREGROUND_RED
|
255 case 38: /* Unknown */
258 attr
&= ~FOREGROUND_ALL
;
259 attr
|= (plain_attr
& FOREGROUND_ALL
);
262 attr
&= ~BACKGROUND_ALL
;
265 attr
&= ~BACKGROUND_ALL
;
266 attr
|= BACKGROUND_RED
;
269 attr
&= ~BACKGROUND_ALL
;
270 attr
|= BACKGROUND_GREEN
;
272 case 43: /* Yellow */
273 attr
&= ~BACKGROUND_ALL
;
274 attr
|= BACKGROUND_RED
| BACKGROUND_GREEN
;
277 attr
&= ~BACKGROUND_ALL
;
278 attr
|= BACKGROUND_BLUE
;
280 case 45: /* Magenta */
281 attr
&= ~BACKGROUND_ALL
;
282 attr
|= BACKGROUND_RED
| BACKGROUND_BLUE
;
285 attr
&= ~BACKGROUND_ALL
;
286 attr
|= BACKGROUND_GREEN
| BACKGROUND_BLUE
;
289 attr
|= BACKGROUND_RED
|
293 case 48: /* Unknown */
296 attr
&= ~BACKGROUND_ALL
;
297 attr
|= (plain_attr
& BACKGROUND_ALL
);
300 /* Unsupported code */
310 /* Unsupported code */
316 TEXT
= 0, ESCAPE
= 033, BRACKET
= '['
319 static DWORD WINAPI
console_thread(LPVOID unused
)
321 unsigned char buffer
[BUFFER_SIZE
];
323 int start
, end
= 0, c
, parampos
= 0, state
= TEXT
;
324 int params
[MAX_PARAMS
];
327 /* read next chunk of bytes from the pipe */
328 if (!ReadFile(hread
, buffer
+ end
, BUFFER_SIZE
- end
, &bytes
,
330 /* exit if pipe has been closed or disconnected */
331 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED
||
332 GetLastError() == ERROR_BROKEN_PIPE
)
334 /* ignore other errors */
338 /* scan the bytes and handle ANSI control codes */
341 while (end
< bytes
) {
346 /* print text seen so far */
348 write_console(buffer
+ start
,
351 /* then start parsing escape sequence */
353 memset(params
, 0, sizeof(params
));
360 /* continue if "\033[", otherwise bail out */
361 state
= (c
== BRACKET
) ? BRACKET
: TEXT
;
365 /* parse [0-9;]* into array of parameters */
366 if (c
>= '0' && c
<= '9') {
367 params
[parampos
] *= 10;
368 params
[parampos
] += c
- '0';
369 } else if (c
== ';') {
371 * next parameter, bail out if out of
375 if (parampos
>= MAX_PARAMS
)
379 * end of escape sequence, change
382 set_attr(c
, params
, parampos
+ 1);
390 /* print remaining text unless parsing an escape sequence */
391 if (state
== TEXT
&& end
> start
) {
392 /* check for incomplete UTF-8 sequences and fix end */
393 if (buffer
[end
- 1] >= 0x80) {
394 if (buffer
[end
-1] >= 0xc0)
396 else if (end
- 1 > start
&&
397 buffer
[end
- 2] >= 0xe0)
399 else if (end
- 2 > start
&&
400 buffer
[end
- 3] >= 0xf0)
404 /* print remaining complete UTF-8 sequences */
406 write_console(buffer
+ start
, end
- start
);
408 /* move remaining bytes to the front */
410 memmove(buffer
, buffer
+ end
, bytes
- end
);
413 /* all data has been consumed, mark buffer empty */
418 /* check if the console font supports unicode */
419 warn_if_raster_font();
425 static void winansi_exit(void)
427 /* flush all streams */
430 /* signal console thread to exit */
431 FlushFileBuffers(hwrite
);
432 DisconnectNamedPipe(hwrite
);
434 /* wait for console thread to copy remaining data */
435 WaitForSingleObject(hthread
, INFINITE
);
437 /* cleanup handles... */
438 if (hwrite1
!= INVALID_HANDLE_VALUE
)
439 CloseHandle(hwrite1
);
440 if (hwrite2
!= INVALID_HANDLE_VALUE
)
441 CloseHandle(hwrite2
);
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", (long) hnd
);
466 * Make MSVCRT's internal file descriptor control structure accessible
467 * so that we can tweak OS handles and flags directly (we need MSVCRT
468 * to treat our pipe handle as if it were a console).
470 * We assume that the ioinfo structure (exposed by MSVCRT.dll via
471 * __pioinfo) starts with the OS handle and the flags. The exact size
472 * varies between MSVCRT versions, so we try different sizes until
473 * toggling the FDEV bit of _pioinfo(1)->osflags is reflected in
481 extern __declspec(dllimport
) ioinfo
*__pioinfo
[];
483 static size_t sizeof_ioinfo
= 0;
486 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
490 static inline ioinfo
* _pioinfo(int fd
)
492 return (ioinfo
*)((char*)__pioinfo
[fd
>> IOINFO_L2E
] +
493 (fd
& (IOINFO_ARRAY_ELTS
- 1)) * sizeof_ioinfo
);
496 static int init_sizeof_ioinfo()
499 /* don't init twice */
501 return sizeof_ioinfo
>= 256;
503 sizeof_ioinfo
= sizeof(ioinfo
);
505 while (sizeof_ioinfo
< 256) {
506 /* toggle FDEV flag, check isatty, then toggle back */
507 _pioinfo(1)->osflags
^= FDEV
;
509 _pioinfo(1)->osflags
^= FDEV
;
510 /* return if we found the correct size */
513 sizeof_ioinfo
+= sizeof(void*);
515 error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
519 static HANDLE
swap_osfhnd(int fd
, HANDLE new_handle
)
524 /* init ioinfo size if we haven't done so */
525 if (init_sizeof_ioinfo())
526 return INVALID_HANDLE_VALUE
;
528 /* get ioinfo pointer and change the handles */
529 pioinfo
= _pioinfo(fd
);
530 old_handle
= pioinfo
->osfhnd
;
531 pioinfo
->osfhnd
= new_handle
;
535 void winansi_init(void)
540 /* check if either stdout or stderr is a console output screen buffer */
541 con1
= is_console(1);
542 con2
= is_console(2);
546 /* create a named pipe to communicate with the console thread */
547 sprintf(name
, "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
548 hwrite
= CreateNamedPipe(name
, PIPE_ACCESS_OUTBOUND
,
549 PIPE_TYPE_BYTE
| PIPE_WAIT
, 1, BUFFER_SIZE
, 0, 0, NULL
);
550 if (hwrite
== INVALID_HANDLE_VALUE
)
551 die_lasterr("CreateNamedPipe failed");
553 hread
= CreateFile(name
, GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
554 if (hread
== INVALID_HANDLE_VALUE
)
555 die_lasterr("CreateFile for named pipe failed");
557 /* start console spool thread on the pipe's read end */
558 hthread
= CreateThread(NULL
, 0, console_thread
, NULL
, 0, NULL
);
559 if (hthread
== INVALID_HANDLE_VALUE
)
560 die_lasterr("CreateThread(console_thread) failed");
562 /* schedule cleanup routine */
563 if (atexit(winansi_exit
))
564 die_errno("atexit(winansi_exit) failed");
566 /* redirect stdout / stderr to the pipe */
568 hconsole1
= swap_osfhnd(1, hwrite1
= duplicate_handle(hwrite
));
570 hconsole2
= swap_osfhnd(2, hwrite2
= duplicate_handle(hwrite
));
573 static int is_same_handle(HANDLE hnd
, int fd
)
575 return hnd
!= INVALID_HANDLE_VALUE
&& hnd
== (HANDLE
) _get_osfhandle(fd
);
579 * Returns the real console handle if stdout / stderr is a pipe redirecting
580 * to the console. Allows spawn / exec to pass the console to the next process.
582 HANDLE
winansi_get_osfhandle(int fd
)
584 if (fd
== 1 && is_same_handle(hwrite1
, 1))
586 else if (fd
== 2 && is_same_handle(hwrite2
, 2))
589 return (HANDLE
) _get_osfhandle(fd
);