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";
75 WriteConsoleW(console
, msg
, wcslen(msg
), NULL
, NULL
);
79 static int is_console(int fd
)
81 CONSOLE_SCREEN_BUFFER_INFO sbi
;
84 static int initialized
= 0;
86 /* get OS handle of the file descriptor */
87 hcon
= (HANDLE
) _get_osfhandle(fd
);
88 if (hcon
== INVALID_HANDLE_VALUE
)
91 /* check if its a device (i.e. console, printer, serial port) */
92 if (GetFileType(hcon
) != FILE_TYPE_CHAR
)
95 /* check if its a handle to a console output screen buffer */
96 if (!GetConsoleScreenBufferInfo(hcon
, &sbi
))
99 /* initialize attributes */
102 attr
= plain_attr
= sbi
.wAttributes
;
110 #define BUFFER_SIZE 4096
111 #define MAX_PARAMS 16
113 static void write_console(unsigned char *str
, size_t len
)
115 /* only called from console_thread, so a static buffer will do */
116 static wchar_t wbuf
[2 * BUFFER_SIZE
+ 1];
118 /* convert utf-8 to utf-16 */
119 int wlen
= xutftowcsn(wbuf
, (char*) str
, ARRAY_SIZE(wbuf
), len
);
121 /* write directly to console */
122 WriteConsoleW(console
, wbuf
, wlen
, NULL
, NULL
);
124 /* remember if non-ascii characters are printed */
129 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
130 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
132 static void set_console_attr(void)
134 WORD attributes
= attr
;
136 attributes
&= ~FOREGROUND_ALL
;
137 attributes
&= ~BACKGROUND_ALL
;
139 /* This could probably use a bitmask
140 instead of a series of ifs */
141 if (attr
& FOREGROUND_RED
)
142 attributes
|= BACKGROUND_RED
;
143 if (attr
& FOREGROUND_GREEN
)
144 attributes
|= BACKGROUND_GREEN
;
145 if (attr
& FOREGROUND_BLUE
)
146 attributes
|= BACKGROUND_BLUE
;
148 if (attr
& BACKGROUND_RED
)
149 attributes
|= FOREGROUND_RED
;
150 if (attr
& BACKGROUND_GREEN
)
151 attributes
|= FOREGROUND_GREEN
;
152 if (attr
& BACKGROUND_BLUE
)
153 attributes
|= FOREGROUND_BLUE
;
155 SetConsoleTextAttribute(console
, attributes
);
158 static void erase_in_line(void)
160 CONSOLE_SCREEN_BUFFER_INFO sbi
;
161 DWORD dummy
; /* Needed for Windows 7 (or Vista) regression */
166 GetConsoleScreenBufferInfo(console
, &sbi
);
167 FillConsoleOutputCharacterA(console
, ' ',
168 sbi
.dwSize
.X
- sbi
.dwCursorPosition
.X
, sbi
.dwCursorPosition
,
172 static void set_attr(char func
, const int *params
, int paramlen
)
177 for (i
= 0; i
< paramlen
; i
++) {
184 attr
|= FOREGROUND_INTENSITY
;
187 case 22: /* normal */
188 attr
&= ~FOREGROUND_INTENSITY
;
193 case 4: /* underline */
194 case 21: /* double underline */
195 /* Wikipedia says this flag does nothing */
196 /* Furthermore, mingw doesn't define this flag
197 attr |= COMMON_LVB_UNDERSCORE; */
199 case 24: /* no underline */
200 /* attr &= ~COMMON_LVB_UNDERSCORE; */
202 case 5: /* slow blink */
203 case 6: /* fast blink */
204 /* We don't have blink, but we do have
205 background intensity */
206 attr
|= BACKGROUND_INTENSITY
;
208 case 25: /* no blink */
209 attr
&= ~BACKGROUND_INTENSITY
;
211 case 7: /* negative */
214 case 27: /* positive */
217 case 8: /* conceal */
218 case 28: /* reveal */
222 attr
&= ~FOREGROUND_ALL
;
225 attr
&= ~FOREGROUND_ALL
;
226 attr
|= FOREGROUND_RED
;
229 attr
&= ~FOREGROUND_ALL
;
230 attr
|= FOREGROUND_GREEN
;
232 case 33: /* Yellow */
233 attr
&= ~FOREGROUND_ALL
;
234 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
;
237 attr
&= ~FOREGROUND_ALL
;
238 attr
|= FOREGROUND_BLUE
;
240 case 35: /* Magenta */
241 attr
&= ~FOREGROUND_ALL
;
242 attr
|= FOREGROUND_RED
| FOREGROUND_BLUE
;
245 attr
&= ~FOREGROUND_ALL
;
246 attr
|= FOREGROUND_GREEN
| FOREGROUND_BLUE
;
249 attr
|= FOREGROUND_RED
|
253 case 38: /* Unknown */
256 attr
&= ~FOREGROUND_ALL
;
257 attr
|= (plain_attr
& FOREGROUND_ALL
);
260 attr
&= ~BACKGROUND_ALL
;
263 attr
&= ~BACKGROUND_ALL
;
264 attr
|= BACKGROUND_RED
;
267 attr
&= ~BACKGROUND_ALL
;
268 attr
|= BACKGROUND_GREEN
;
270 case 43: /* Yellow */
271 attr
&= ~BACKGROUND_ALL
;
272 attr
|= BACKGROUND_RED
| BACKGROUND_GREEN
;
275 attr
&= ~BACKGROUND_ALL
;
276 attr
|= BACKGROUND_BLUE
;
278 case 45: /* Magenta */
279 attr
&= ~BACKGROUND_ALL
;
280 attr
|= BACKGROUND_RED
| BACKGROUND_BLUE
;
283 attr
&= ~BACKGROUND_ALL
;
284 attr
|= BACKGROUND_GREEN
| BACKGROUND_BLUE
;
287 attr
|= BACKGROUND_RED
|
291 case 48: /* Unknown */
294 attr
&= ~BACKGROUND_ALL
;
295 attr
|= (plain_attr
& BACKGROUND_ALL
);
298 /* Unsupported code */
308 /* Unsupported code */
314 TEXT
= 0, ESCAPE
= 033, BRACKET
= '['
317 static DWORD WINAPI
console_thread(LPVOID unused
)
319 unsigned char buffer
[BUFFER_SIZE
];
321 int start
, end
= 0, c
, parampos
= 0, state
= TEXT
;
322 int params
[MAX_PARAMS
];
325 /* read next chunk of bytes from the pipe */
326 if (!ReadFile(hread
, buffer
+ end
, BUFFER_SIZE
- end
, &bytes
,
328 /* exit if pipe has been closed or disconnected */
329 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED
||
330 GetLastError() == ERROR_BROKEN_PIPE
)
332 /* ignore other errors */
336 /* scan the bytes and handle ANSI control codes */
339 while (end
< bytes
) {
344 /* print text seen so far */
346 write_console(buffer
+ start
,
349 /* then start parsing escape sequence */
351 memset(params
, 0, sizeof(params
));
358 /* continue if "\033[", otherwise bail out */
359 state
= (c
== BRACKET
) ? BRACKET
: TEXT
;
363 /* parse [0-9;]* into array of parameters */
364 if (c
>= '0' && c
<= '9') {
365 params
[parampos
] *= 10;
366 params
[parampos
] += c
- '0';
367 } else if (c
== ';') {
369 * next parameter, bail out if out of
373 if (parampos
>= MAX_PARAMS
)
377 * end of escape sequence, change
380 set_attr(c
, params
, parampos
+ 1);
388 /* print remaining text unless parsing an escape sequence */
389 if (state
== TEXT
&& end
> start
) {
390 /* check for incomplete UTF-8 sequences and fix end */
391 if (buffer
[end
- 1] >= 0x80) {
392 if (buffer
[end
-1] >= 0xc0)
394 else if (end
- 1 > start
&&
395 buffer
[end
- 2] >= 0xe0)
397 else if (end
- 2 > start
&&
398 buffer
[end
- 3] >= 0xf0)
402 /* print remaining complete UTF-8 sequences */
404 write_console(buffer
+ start
, end
- start
);
406 /* move remaining bytes to the front */
408 memmove(buffer
, buffer
+ end
, bytes
- end
);
411 /* all data has been consumed, mark buffer empty */
416 /* check if the console font supports unicode */
417 warn_if_raster_font();
423 static void winansi_exit(void)
425 /* flush all streams */
428 /* signal console thread to exit */
429 FlushFileBuffers(hwrite
);
430 DisconnectNamedPipe(hwrite
);
432 /* wait for console thread to copy remaining data */
433 WaitForSingleObject(hthread
, INFINITE
);
435 /* cleanup handles... */
436 if (hwrite1
!= INVALID_HANDLE_VALUE
)
437 CloseHandle(hwrite1
);
438 if (hwrite2
!= INVALID_HANDLE_VALUE
)
439 CloseHandle(hwrite2
);
441 CloseHandle(hthread
);
444 static void die_lasterr(const char *fmt
, ...)
447 va_start(params
, fmt
);
448 errno
= err_win_to_posix(GetLastError());
449 die_errno(fmt
, params
);
453 static HANDLE
duplicate_handle(HANDLE hnd
)
455 HANDLE hresult
, hproc
= GetCurrentProcess();
456 if (!DuplicateHandle(hproc
, hnd
, hproc
, &hresult
, 0, TRUE
,
457 DUPLICATE_SAME_ACCESS
))
458 die_lasterr("DuplicateHandle(%li) failed", (long) 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)
488 static inline ioinfo
* _pioinfo(int fd
)
490 return (ioinfo
*)((char*)__pioinfo
[fd
>> IOINFO_L2E
] +
491 (fd
& (IOINFO_ARRAY_ELTS
- 1)) * sizeof_ioinfo
);
494 static int init_sizeof_ioinfo()
497 /* don't init twice */
499 return sizeof_ioinfo
>= 256;
501 sizeof_ioinfo
= sizeof(ioinfo
);
503 while (sizeof_ioinfo
< 256) {
504 /* toggle FDEV flag, check isatty, then toggle back */
505 _pioinfo(1)->osflags
^= FDEV
;
507 _pioinfo(1)->osflags
^= FDEV
;
508 /* return if we found the correct size */
511 sizeof_ioinfo
+= sizeof(void*);
513 error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
517 static HANDLE
swap_osfhnd(int fd
, HANDLE new_handle
)
522 /* init ioinfo size if we haven't done so */
523 if (init_sizeof_ioinfo())
524 return INVALID_HANDLE_VALUE
;
526 /* get ioinfo pointer and change the handles */
527 pioinfo
= _pioinfo(fd
);
528 old_handle
= pioinfo
->osfhnd
;
529 pioinfo
->osfhnd
= new_handle
;
533 void winansi_init(void)
538 /* check if either stdout or stderr is a console output screen buffer */
539 con1
= is_console(1);
540 con2
= is_console(2);
544 /* create a named pipe to communicate with the console thread */
545 sprintf(name
, "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
546 hwrite
= CreateNamedPipe(name
, PIPE_ACCESS_OUTBOUND
,
547 PIPE_TYPE_BYTE
| PIPE_WAIT
, 1, BUFFER_SIZE
, 0, 0, NULL
);
548 if (hwrite
== INVALID_HANDLE_VALUE
)
549 die_lasterr("CreateNamedPipe failed");
551 hread
= CreateFile(name
, GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
552 if (hread
== INVALID_HANDLE_VALUE
)
553 die_lasterr("CreateFile for named pipe failed");
555 /* start console spool thread on the pipe's read end */
556 hthread
= CreateThread(NULL
, 0, console_thread
, NULL
, 0, NULL
);
557 if (hthread
== INVALID_HANDLE_VALUE
)
558 die_lasterr("CreateThread(console_thread) failed");
560 /* schedule cleanup routine */
561 if (atexit(winansi_exit
))
562 die_errno("atexit(winansi_exit) failed");
564 /* redirect stdout / stderr to the pipe */
566 hconsole1
= swap_osfhnd(1, hwrite1
= duplicate_handle(hwrite
));
568 hconsole2
= swap_osfhnd(2, hwrite2
= duplicate_handle(hwrite
));
571 static int is_same_handle(HANDLE hnd
, int fd
)
573 return hnd
!= INVALID_HANDLE_VALUE
&& hnd
== (HANDLE
) _get_osfhandle(fd
);
577 * Returns the real console handle if stdout / stderr is a pipe redirecting
578 * to the console. Allows spawn / exec to pass the console to the next process.
580 HANDLE
winansi_get_osfhandle(int fd
)
582 if (fd
== 1 && is_same_handle(hwrite1
, 1))
584 else if (fd
== 2 && is_same_handle(hwrite2
, 2))
587 return (HANDLE
) _get_osfhandle(fd
);