2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
6 #include "../git-compat-util.h"
11 Functions to be wrapped:
16 ANSI codes used by git: m, K
18 This file is git-specific. Therefore, this file does not attempt
19 to implement any codes that are not used by git.
22 static HANDLE console
;
23 static WORD plain_attr
;
26 static int non_ascii_used
= 0;
27 static HANDLE hthread
, hread
, hwrite
;
28 static HANDLE hwrite1
= INVALID_HANDLE_VALUE
, hwrite2
= INVALID_HANDLE_VALUE
;
29 static HANDLE hconsole1
, hconsole2
;
32 typedef struct _CONSOLE_FONT_INFOEX
{
38 WCHAR FaceName
[LF_FACESIZE
];
39 } CONSOLE_FONT_INFOEX
, *PCONSOLE_FONT_INFOEX
;
42 typedef BOOL (WINAPI
*PGETCURRENTCONSOLEFONTEX
)(HANDLE
, BOOL
,
43 PCONSOLE_FONT_INFOEX
);
45 static void warn_if_raster_font(void)
48 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx
;
50 /* don't bother if output was ascii only */
54 /* GetCurrentConsoleFontEx is available since Vista */
55 pGetCurrentConsoleFontEx
= (PGETCURRENTCONSOLEFONTEX
) GetProcAddress(
56 GetModuleHandle("kernel32.dll"),
57 "GetCurrentConsoleFontEx");
58 if (pGetCurrentConsoleFontEx
) {
59 CONSOLE_FONT_INFOEX cfi
;
60 cfi
.cbSize
= sizeof(cfi
);
61 if (pGetCurrentConsoleFontEx(console
, 0, &cfi
))
62 fontFamily
= cfi
.FontFamily
;
64 /* pre-Vista: check default console font in registry */
66 if (ERROR_SUCCESS
== RegOpenKeyExA(HKEY_CURRENT_USER
, "Console",
67 0, KEY_READ
, &hkey
)) {
68 DWORD size
= sizeof(fontFamily
);
69 RegQueryValueExA(hkey
, "FontFamily", NULL
, NULL
,
70 (LPVOID
) &fontFamily
, &size
);
75 if (!(fontFamily
& TMPF_TRUETYPE
)) {
76 const wchar_t *msg
= L
"\nWarning: Your console font probably "
77 L
"doesn\'t support Unicode. If you experience strange "
78 L
"characters in the output, consider switching to a "
79 L
"TrueType font such as Lucida Console!\n";
80 WriteConsoleW(console
, msg
, wcslen(msg
), NULL
, 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 */
106 attr
= plain_attr
= sbi
.wAttributes
;
114 #define BUFFER_SIZE 4096
115 #define MAX_PARAMS 16
117 static void write_console(unsigned char *str
, size_t len
)
119 /* only called from console_thread, so a static buffer will do */
120 static wchar_t wbuf
[2 * BUFFER_SIZE
+ 1];
122 /* convert utf-8 to utf-16 */
123 int wlen
= xutftowcsn(wbuf
, (char*) str
, ARRAY_SIZE(wbuf
), len
);
125 /* write directly to console */
126 WriteConsoleW(console
, wbuf
, wlen
, NULL
, NULL
);
128 /* remember if non-ascii characters are printed */
133 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
134 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
136 static void set_console_attr(void)
138 WORD attributes
= attr
;
140 attributes
&= ~FOREGROUND_ALL
;
141 attributes
&= ~BACKGROUND_ALL
;
143 /* This could probably use a bitmask
144 instead of a series of ifs */
145 if (attr
& FOREGROUND_RED
)
146 attributes
|= BACKGROUND_RED
;
147 if (attr
& FOREGROUND_GREEN
)
148 attributes
|= BACKGROUND_GREEN
;
149 if (attr
& FOREGROUND_BLUE
)
150 attributes
|= BACKGROUND_BLUE
;
152 if (attr
& BACKGROUND_RED
)
153 attributes
|= FOREGROUND_RED
;
154 if (attr
& BACKGROUND_GREEN
)
155 attributes
|= FOREGROUND_GREEN
;
156 if (attr
& BACKGROUND_BLUE
)
157 attributes
|= FOREGROUND_BLUE
;
159 SetConsoleTextAttribute(console
, attributes
);
162 static void erase_in_line(void)
164 CONSOLE_SCREEN_BUFFER_INFO sbi
;
165 DWORD dummy
; /* Needed for Windows 7 (or Vista) regression */
170 GetConsoleScreenBufferInfo(console
, &sbi
);
171 FillConsoleOutputCharacterA(console
, ' ',
172 sbi
.dwSize
.X
- sbi
.dwCursorPosition
.X
, sbi
.dwCursorPosition
,
176 static void set_attr(char func
, const int *params
, int paramlen
)
181 for (i
= 0; i
< paramlen
; i
++) {
188 attr
|= FOREGROUND_INTENSITY
;
191 case 22: /* normal */
192 attr
&= ~FOREGROUND_INTENSITY
;
197 case 4: /* underline */
198 case 21: /* double underline */
199 /* Wikipedia says this flag does nothing */
200 /* Furthermore, mingw doesn't define this flag
201 attr |= COMMON_LVB_UNDERSCORE; */
203 case 24: /* no underline */
204 /* attr &= ~COMMON_LVB_UNDERSCORE; */
206 case 5: /* slow blink */
207 case 6: /* fast blink */
208 /* We don't have blink, but we do have
209 background intensity */
210 attr
|= BACKGROUND_INTENSITY
;
212 case 25: /* no blink */
213 attr
&= ~BACKGROUND_INTENSITY
;
215 case 7: /* negative */
218 case 27: /* positive */
221 case 8: /* conceal */
222 case 28: /* reveal */
226 attr
&= ~FOREGROUND_ALL
;
229 attr
&= ~FOREGROUND_ALL
;
230 attr
|= FOREGROUND_RED
;
233 attr
&= ~FOREGROUND_ALL
;
234 attr
|= FOREGROUND_GREEN
;
236 case 33: /* Yellow */
237 attr
&= ~FOREGROUND_ALL
;
238 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
;
241 attr
&= ~FOREGROUND_ALL
;
242 attr
|= FOREGROUND_BLUE
;
244 case 35: /* Magenta */
245 attr
&= ~FOREGROUND_ALL
;
246 attr
|= FOREGROUND_RED
| FOREGROUND_BLUE
;
249 attr
&= ~FOREGROUND_ALL
;
250 attr
|= FOREGROUND_GREEN
| FOREGROUND_BLUE
;
253 attr
|= FOREGROUND_RED
|
257 case 38: /* Unknown */
260 attr
&= ~FOREGROUND_ALL
;
261 attr
|= (plain_attr
& FOREGROUND_ALL
);
264 attr
&= ~BACKGROUND_ALL
;
267 attr
&= ~BACKGROUND_ALL
;
268 attr
|= BACKGROUND_RED
;
271 attr
&= ~BACKGROUND_ALL
;
272 attr
|= BACKGROUND_GREEN
;
274 case 43: /* Yellow */
275 attr
&= ~BACKGROUND_ALL
;
276 attr
|= BACKGROUND_RED
| BACKGROUND_GREEN
;
279 attr
&= ~BACKGROUND_ALL
;
280 attr
|= BACKGROUND_BLUE
;
282 case 45: /* Magenta */
283 attr
&= ~BACKGROUND_ALL
;
284 attr
|= BACKGROUND_RED
| BACKGROUND_BLUE
;
287 attr
&= ~BACKGROUND_ALL
;
288 attr
|= BACKGROUND_GREEN
| BACKGROUND_BLUE
;
291 attr
|= BACKGROUND_RED
|
295 case 48: /* Unknown */
298 attr
&= ~BACKGROUND_ALL
;
299 attr
|= (plain_attr
& BACKGROUND_ALL
);
302 /* Unsupported code */
312 /* Unsupported code */
318 TEXT
= 0, ESCAPE
= 033, BRACKET
= '['
321 static DWORD WINAPI
console_thread(LPVOID unused
)
323 unsigned char buffer
[BUFFER_SIZE
];
325 int start
, end
= 0, c
, parampos
= 0, state
= TEXT
;
326 int params
[MAX_PARAMS
];
329 /* read next chunk of bytes from the pipe */
330 if (!ReadFile(hread
, buffer
+ end
, BUFFER_SIZE
- end
, &bytes
,
332 /* exit if pipe has been closed or disconnected */
333 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED
||
334 GetLastError() == ERROR_BROKEN_PIPE
)
336 /* ignore other errors */
340 /* scan the bytes and handle ANSI control codes */
343 while (end
< bytes
) {
348 /* print text seen so far */
350 write_console(buffer
+ start
,
353 /* then start parsing escape sequence */
355 memset(params
, 0, sizeof(params
));
362 /* continue if "\033[", otherwise bail out */
363 state
= (c
== BRACKET
) ? BRACKET
: TEXT
;
367 /* parse [0-9;]* into array of parameters */
368 if (c
>= '0' && c
<= '9') {
369 params
[parampos
] *= 10;
370 params
[parampos
] += c
- '0';
371 } else if (c
== ';') {
373 * next parameter, bail out if out of
377 if (parampos
>= MAX_PARAMS
)
381 * end of escape sequence, change
384 set_attr(c
, params
, parampos
+ 1);
392 /* print remaining text unless parsing an escape sequence */
393 if (state
== TEXT
&& end
> start
) {
394 /* check for incomplete UTF-8 sequences and fix end */
395 if (buffer
[end
- 1] >= 0x80) {
396 if (buffer
[end
-1] >= 0xc0)
398 else if (end
- 1 > start
&&
399 buffer
[end
- 2] >= 0xe0)
401 else if (end
- 2 > start
&&
402 buffer
[end
- 3] >= 0xf0)
406 /* print remaining complete UTF-8 sequences */
408 write_console(buffer
+ start
, end
- start
);
410 /* move remaining bytes to the front */
412 memmove(buffer
, buffer
+ end
, bytes
- end
);
415 /* all data has been consumed, mark buffer empty */
420 /* check if the console font supports unicode */
421 warn_if_raster_font();
427 static void winansi_exit(void)
429 /* flush all streams */
432 /* signal console thread to exit */
433 FlushFileBuffers(hwrite
);
434 DisconnectNamedPipe(hwrite
);
436 /* wait for console thread to copy remaining data */
437 WaitForSingleObject(hthread
, INFINITE
);
439 /* cleanup handles... */
440 if (hwrite1
!= INVALID_HANDLE_VALUE
)
441 CloseHandle(hwrite1
);
442 if (hwrite2
!= INVALID_HANDLE_VALUE
)
443 CloseHandle(hwrite2
);
445 CloseHandle(hthread
);
448 static void die_lasterr(const char *fmt
, ...)
451 va_start(params
, fmt
);
452 errno
= err_win_to_posix(GetLastError());
453 die_errno(fmt
, params
);
457 static HANDLE
duplicate_handle(HANDLE hnd
)
459 HANDLE hresult
, hproc
= GetCurrentProcess();
460 if (!DuplicateHandle(hproc
, hnd
, hproc
, &hresult
, 0, TRUE
,
461 DUPLICATE_SAME_ACCESS
))
462 die_lasterr("DuplicateHandle(%li) failed", (long) hnd
);
466 static HANDLE
redirect_console(FILE *stream
, HANDLE
*phcon
, int new_fd
)
468 /* get original console handle */
469 int fd
= _fileno(stream
);
470 HANDLE hcon
= (HANDLE
) _get_osfhandle(fd
);
471 if (hcon
== INVALID_HANDLE_VALUE
)
472 die_errno("_get_osfhandle(%i) failed", fd
);
474 /* save a copy to phcon and console (used by the background thread) */
475 console
= *phcon
= duplicate_handle(hcon
);
477 /* duplicate new_fd over fd (closes fd and associated handle (hcon)) */
478 if (_dup2(new_fd
, fd
))
479 die_errno("_dup2(%i, %i) failed", new_fd
, fd
);
481 /* no buffering, or stdout / stderr will be out of sync */
482 setbuf(stream
, NULL
);
483 return (HANDLE
) _get_osfhandle(fd
);
486 void winansi_init(void)
488 int con1
, con2
, hwrite_fd
;
491 /* check if either stdout or stderr is a console output screen buffer */
492 con1
= is_console(1);
493 con2
= is_console(2);
497 /* create a named pipe to communicate with the console thread */
498 sprintf(name
, "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
499 hwrite
= CreateNamedPipe(name
, PIPE_ACCESS_OUTBOUND
,
500 PIPE_TYPE_BYTE
| PIPE_WAIT
, 1, BUFFER_SIZE
, 0, 0, NULL
);
501 if (hwrite
== INVALID_HANDLE_VALUE
)
502 die_lasterr("CreateNamedPipe failed");
504 hread
= CreateFile(name
, GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
505 if (hread
== INVALID_HANDLE_VALUE
)
506 die_lasterr("CreateFile for named pipe failed");
508 /* start console spool thread on the pipe's read end */
509 hthread
= CreateThread(NULL
, 0, console_thread
, NULL
, 0, NULL
);
510 if (hthread
== INVALID_HANDLE_VALUE
)
511 die_lasterr("CreateThread(console_thread) failed");
513 /* schedule cleanup routine */
514 if (atexit(winansi_exit
))
515 die_errno("atexit(winansi_exit) failed");
517 /* create a file descriptor for the write end of the pipe */
518 hwrite_fd
= _open_osfhandle((long) duplicate_handle(hwrite
), _O_BINARY
);
520 die_errno("_open_osfhandle(%li) failed", (long) hwrite
);
522 /* redirect stdout / stderr to the pipe */
524 hwrite1
= redirect_console(stdout
, &hconsole1
, hwrite_fd
);
526 hwrite2
= redirect_console(stderr
, &hconsole2
, hwrite_fd
);
528 /* close pipe file descriptor (also closes the duped hwrite) */
532 static int is_same_handle(HANDLE hnd
, int fd
)
534 return hnd
!= INVALID_HANDLE_VALUE
&& hnd
== (HANDLE
) _get_osfhandle(fd
);
538 * Return true if stdout / stderr is a pipe redirecting to the console.
540 int winansi_isatty(int fd
)
542 if (fd
== 1 && is_same_handle(hwrite1
, 1))
544 else if (fd
== 2 && is_same_handle(hwrite2
, 2))
551 * Returns the real console handle if stdout / stderr is a pipe redirecting
552 * to the console. Allows spawn / exec to pass the console to the next process.
554 HANDLE
winansi_get_osfhandle(int fd
)
556 if (fd
== 1 && is_same_handle(hwrite1
, 1))
558 else if (fd
== 2 && is_same_handle(hwrite2
, 2))
561 return (HANDLE
) _get_osfhandle(fd
);