French translation: copy -> copie.
[git/dscho.git] / compat / winansi.c
blob040ef5adcaeca237134b582556615ffeb3b8d56f
1 /*
2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
3 */
5 #undef NOGDI
6 #include "../git-compat-util.h"
7 #include <wingdi.h>
8 #include <winreg.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;
19 static WORD attr;
20 static int negative;
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;
26 #ifdef __MINGW32__
27 typedef struct _CONSOLE_FONT_INFOEX {
28 ULONG cbSize;
29 DWORD nFont;
30 COORD dwFontSize;
31 UINT FontFamily;
32 UINT FontWeight;
33 WCHAR FaceName[LF_FACESIZE];
34 } CONSOLE_FONT_INFOEX, *PCONSOLE_FONT_INFOEX;
35 #endif
37 typedef BOOL (WINAPI *PGETCURRENTCONSOLEFONTEX)(HANDLE, BOOL,
38 PCONSOLE_FONT_INFOEX);
40 static void warn_if_raster_font(void)
42 DWORD fontFamily = 0;
43 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx;
45 /* don't bother if output was ascii only */
46 if (!non_ascii_used)
47 return;
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;
58 } else {
59 /* pre-Vista: check default console font in registry */
60 HKEY hkey;
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);
66 RegCloseKey(hkey);
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;
82 HANDLE hcon;
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)
89 return 0;
91 /* check if its a device (i.e. console, printer, serial port) */
92 if (GetFileType(hcon) != FILE_TYPE_CHAR)
93 return 0;
95 /* check if its a handle to a console output screen buffer */
96 if (!GetConsoleScreenBufferInfo(hcon, &sbi))
97 return 0;
99 /* initialize attributes */
100 if (!initialized) {
101 console = hcon;
102 attr = plain_attr = sbi.wAttributes;
103 negative = 0;
104 initialized = 1;
107 return 1;
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 */
125 if (wlen != len)
126 non_ascii_used = 1;
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;
135 if (negative) {
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 */
163 if (!console)
164 return;
166 GetConsoleScreenBufferInfo(console, &sbi);
167 FillConsoleOutputCharacterA(console, ' ',
168 sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
169 &dummy);
172 static void set_attr(char func, const int *params, int paramlen)
174 int i;
175 switch (func) {
176 case 'm':
177 for (i = 0; i < paramlen; i++) {
178 switch (params[i]) {
179 case 0: /* reset */
180 attr = plain_attr;
181 negative = 0;
182 break;
183 case 1: /* bold */
184 attr |= FOREGROUND_INTENSITY;
185 break;
186 case 2: /* faint */
187 case 22: /* normal */
188 attr &= ~FOREGROUND_INTENSITY;
189 break;
190 case 3: /* italic */
191 /* Unsupported */
192 break;
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; */
198 break;
199 case 24: /* no underline */
200 /* attr &= ~COMMON_LVB_UNDERSCORE; */
201 break;
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;
207 break;
208 case 25: /* no blink */
209 attr &= ~BACKGROUND_INTENSITY;
210 break;
211 case 7: /* negative */
212 negative = 1;
213 break;
214 case 27: /* positive */
215 negative = 0;
216 break;
217 case 8: /* conceal */
218 case 28: /* reveal */
219 /* Unsupported */
220 break;
221 case 30: /* Black */
222 attr &= ~FOREGROUND_ALL;
223 break;
224 case 31: /* Red */
225 attr &= ~FOREGROUND_ALL;
226 attr |= FOREGROUND_RED;
227 break;
228 case 32: /* Green */
229 attr &= ~FOREGROUND_ALL;
230 attr |= FOREGROUND_GREEN;
231 break;
232 case 33: /* Yellow */
233 attr &= ~FOREGROUND_ALL;
234 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
235 break;
236 case 34: /* Blue */
237 attr &= ~FOREGROUND_ALL;
238 attr |= FOREGROUND_BLUE;
239 break;
240 case 35: /* Magenta */
241 attr &= ~FOREGROUND_ALL;
242 attr |= FOREGROUND_RED | FOREGROUND_BLUE;
243 break;
244 case 36: /* Cyan */
245 attr &= ~FOREGROUND_ALL;
246 attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
247 break;
248 case 37: /* White */
249 attr |= FOREGROUND_RED |
250 FOREGROUND_GREEN |
251 FOREGROUND_BLUE;
252 break;
253 case 38: /* Unknown */
254 break;
255 case 39: /* reset */
256 attr &= ~FOREGROUND_ALL;
257 attr |= (plain_attr & FOREGROUND_ALL);
258 break;
259 case 40: /* Black */
260 attr &= ~BACKGROUND_ALL;
261 break;
262 case 41: /* Red */
263 attr &= ~BACKGROUND_ALL;
264 attr |= BACKGROUND_RED;
265 break;
266 case 42: /* Green */
267 attr &= ~BACKGROUND_ALL;
268 attr |= BACKGROUND_GREEN;
269 break;
270 case 43: /* Yellow */
271 attr &= ~BACKGROUND_ALL;
272 attr |= BACKGROUND_RED | BACKGROUND_GREEN;
273 break;
274 case 44: /* Blue */
275 attr &= ~BACKGROUND_ALL;
276 attr |= BACKGROUND_BLUE;
277 break;
278 case 45: /* Magenta */
279 attr &= ~BACKGROUND_ALL;
280 attr |= BACKGROUND_RED | BACKGROUND_BLUE;
281 break;
282 case 46: /* Cyan */
283 attr &= ~BACKGROUND_ALL;
284 attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
285 break;
286 case 47: /* White */
287 attr |= BACKGROUND_RED |
288 BACKGROUND_GREEN |
289 BACKGROUND_BLUE;
290 break;
291 case 48: /* Unknown */
292 break;
293 case 49: /* reset */
294 attr &= ~BACKGROUND_ALL;
295 attr |= (plain_attr & BACKGROUND_ALL);
296 break;
297 default:
298 /* Unsupported code */
299 break;
302 set_console_attr();
303 break;
304 case 'K':
305 erase_in_line();
306 break;
307 default:
308 /* Unsupported code */
309 break;
313 enum {
314 TEXT = 0, ESCAPE = 033, BRACKET = '['
317 static DWORD WINAPI console_thread(LPVOID unused)
319 unsigned char buffer[BUFFER_SIZE];
320 DWORD bytes;
321 int start, end = 0, c, parampos = 0, state = TEXT;
322 int params[MAX_PARAMS];
324 while (1) {
325 /* read next chunk of bytes from the pipe */
326 if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
327 NULL)) {
328 /* exit if pipe has been closed or disconnected */
329 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
330 GetLastError() == ERROR_BROKEN_PIPE)
331 break;
332 /* ignore other errors */
333 continue;
336 /* scan the bytes and handle ANSI control codes */
337 bytes += end;
338 start = end = 0;
339 while (end < bytes) {
340 c = buffer[end++];
341 switch (state) {
342 case TEXT:
343 if (c == ESCAPE) {
344 /* print text seen so far */
345 if (end - 1 > start)
346 write_console(buffer + start,
347 end - 1 - start);
349 /* then start parsing escape sequence */
350 start = end - 1;
351 memset(params, 0, sizeof(params));
352 parampos = 0;
353 state = ESCAPE;
355 break;
357 case ESCAPE:
358 /* continue if "\033[", otherwise bail out */
359 state = (c == BRACKET) ? BRACKET : TEXT;
360 break;
362 case BRACKET:
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
370 * bounds
372 parampos++;
373 if (parampos >= MAX_PARAMS)
374 state = TEXT;
375 } else {
377 * end of escape sequence, change
378 * console attributes
380 set_attr(c, params, parampos + 1);
381 start = end;
382 state = TEXT;
384 break;
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)
393 end--;
394 else if (end - 1 > start &&
395 buffer[end - 2] >= 0xe0)
396 end -= 2;
397 else if (end - 2 > start &&
398 buffer[end - 3] >= 0xf0)
399 end -= 3;
402 /* print remaining complete UTF-8 sequences */
403 if (end > start)
404 write_console(buffer + start, end - start);
406 /* move remaining bytes to the front */
407 if (end < bytes)
408 memmove(buffer, buffer + end, bytes - end);
409 end = bytes - end;
410 } else {
411 /* all data has been consumed, mark buffer empty */
412 end = 0;
416 /* check if the console font supports unicode */
417 warn_if_raster_font();
419 CloseHandle(hread);
420 return 0;
423 static void winansi_exit(void)
425 /* flush all streams */
426 _flushall();
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);
440 CloseHandle(hwrite);
441 CloseHandle(hthread);
444 static void die_lasterr(const char *fmt, ...)
446 va_list params;
447 va_start(params, fmt);
448 errno = err_win_to_posix(GetLastError());
449 die_errno(fmt, params);
450 va_end(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);
459 return hresult;
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
472 * isatty(1).
474 typedef struct {
475 HANDLE osfhnd;
476 char osflags;
477 } ioinfo;
479 extern __declspec(dllimport) ioinfo *__pioinfo[];
481 static size_t sizeof_ioinfo = 0;
483 #define IOINFO_L2E 5
484 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
486 #define FDEV 0x40
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()
496 int istty, wastty;
497 /* don't init twice */
498 if (sizeof_ioinfo)
499 return sizeof_ioinfo >= 256;
501 sizeof_ioinfo = sizeof(ioinfo);
502 wastty = isatty(1);
503 while (sizeof_ioinfo < 256) {
504 /* toggle FDEV flag, check isatty, then toggle back */
505 _pioinfo(1)->osflags ^= FDEV;
506 istty = isatty(1);
507 _pioinfo(1)->osflags ^= FDEV;
508 /* return if we found the correct size */
509 if (istty != wastty)
510 return 0;
511 sizeof_ioinfo += sizeof(void*);
513 error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
514 return 1;
517 static HANDLE swap_osfhnd(int fd, HANDLE new_handle)
519 ioinfo *pioinfo;
520 HANDLE old_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;
530 return old_handle;
533 void winansi_init(void)
535 int con1, con2;
536 char name[32];
538 /* check if either stdout or stderr is a console output screen buffer */
539 con1 = is_console(1);
540 con2 = is_console(2);
541 if (!con1 && !con2)
542 return;
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 */
565 if (con1)
566 hconsole1 = swap_osfhnd(1, hwrite1 = duplicate_handle(hwrite));
567 if (con2)
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))
583 return hconsole1;
584 else if (fd == 2 && is_same_handle(hwrite2, 2))
585 return hconsole2;
586 else
587 return (HANDLE) _get_osfhandle(fd);