Merge branch 'jk/parseopt-usage-msg-opt'
[git] / compat / winansi.c
1 /*
2  * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
3  */
4
5 #undef NOGDI
6 #include "../git-compat-util.h"
7 #include <wingdi.h>
8 #include <winreg.h>
9
10 /* In this file, we actually want to use Windows' own isatty(). */
11 #undef isatty
12
13 /*
14  ANSI codes used by git: m, K
15
16  This file is git-specific. Therefore, this file does not attempt
17  to implement any codes that are not used by git.
18 */
19
20 static HANDLE console;
21 static WORD plain_attr;
22 static WORD attr;
23 static int negative;
24 static int non_ascii_used = 0;
25 static HANDLE hthread, hread, hwrite;
26 static HANDLE hconsole1, hconsole2;
27
28 #ifdef __MINGW32__
29 #if !defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 5
30 typedef struct _CONSOLE_FONT_INFOEX {
31         ULONG cbSize;
32         DWORD nFont;
33         COORD dwFontSize;
34         UINT FontFamily;
35         UINT FontWeight;
36         WCHAR FaceName[LF_FACESIZE];
37 } CONSOLE_FONT_INFOEX, *PCONSOLE_FONT_INFOEX;
38 #endif
39 #endif
40
41 typedef BOOL (WINAPI *PGETCURRENTCONSOLEFONTEX)(HANDLE, BOOL,
42                 PCONSOLE_FONT_INFOEX);
43
44 static void warn_if_raster_font(void)
45 {
46         DWORD fontFamily = 0;
47         PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx;
48
49         /* don't bother if output was ascii only */
50         if (!non_ascii_used)
51                 return;
52
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;
62         } else {
63                 /* pre-Vista: check default console font in registry */
64                 HKEY hkey;
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);
70                         RegCloseKey(hkey);
71                 }
72         }
73
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";
79                 DWORD dummy;
80                 WriteConsoleW(console, msg, wcslen(msg), &dummy, NULL);
81         }
82 }
83
84 static int is_console(int fd)
85 {
86         CONSOLE_SCREEN_BUFFER_INFO sbi;
87         HANDLE hcon;
88
89         static int initialized = 0;
90
91         /* get OS handle of the file descriptor */
92         hcon = (HANDLE) _get_osfhandle(fd);
93         if (hcon == INVALID_HANDLE_VALUE)
94                 return 0;
95
96         /* check if its a device (i.e. console, printer, serial port) */
97         if (GetFileType(hcon) != FILE_TYPE_CHAR)
98                 return 0;
99
100         /* check if its a handle to a console output screen buffer */
101         if (!GetConsoleScreenBufferInfo(hcon, &sbi))
102                 return 0;
103
104         /* initialize attributes */
105         if (!initialized) {
106                 console = hcon;
107                 attr = plain_attr = sbi.wAttributes;
108                 negative = 0;
109                 initialized = 1;
110         }
111
112         return 1;
113 }
114
115 #define BUFFER_SIZE 4096
116 #define MAX_PARAMS 16
117
118 static void write_console(unsigned char *str, size_t len)
119 {
120         /* only called from console_thread, so a static buffer will do */
121         static wchar_t wbuf[2 * BUFFER_SIZE + 1];
122         DWORD dummy;
123
124         /* convert utf-8 to utf-16 */
125         int wlen = xutftowcsn(wbuf, (char*) str, ARRAY_SIZE(wbuf), len);
126
127         /* write directly to console */
128         WriteConsoleW(console, wbuf, wlen, &dummy, NULL);
129
130         /* remember if non-ascii characters are printed */
131         if (wlen != len)
132                 non_ascii_used = 1;
133 }
134
135 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
136 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
137
138 static void set_console_attr(void)
139 {
140         WORD attributes = attr;
141         if (negative) {
142                 attributes &= ~FOREGROUND_ALL;
143                 attributes &= ~BACKGROUND_ALL;
144
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;
153
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;
160         }
161         SetConsoleTextAttribute(console, attributes);
162 }
163
164 static void erase_in_line(void)
165 {
166         CONSOLE_SCREEN_BUFFER_INFO sbi;
167         DWORD dummy; /* Needed for Windows 7 (or Vista) regression */
168
169         if (!console)
170                 return;
171
172         GetConsoleScreenBufferInfo(console, &sbi);
173         FillConsoleOutputCharacterA(console, ' ',
174                 sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
175                 &dummy);
176 }
177
178 static void set_attr(char func, const int *params, int paramlen)
179 {
180         int i;
181         switch (func) {
182         case 'm':
183                 for (i = 0; i < paramlen; i++) {
184                         switch (params[i]) {
185                         case 0: /* reset */
186                                 attr = plain_attr;
187                                 negative = 0;
188                                 break;
189                         case 1: /* bold */
190                                 attr |= FOREGROUND_INTENSITY;
191                                 break;
192                         case 2:  /* faint */
193                         case 22: /* normal */
194                                 attr &= ~FOREGROUND_INTENSITY;
195                                 break;
196                         case 3:  /* italic */
197                                 /* Unsupported */
198                                 break;
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; */
204                                 break;
205                         case 24: /* no underline */
206                                 /* attr &= ~COMMON_LVB_UNDERSCORE; */
207                                 break;
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;
213                                 break;
214                         case 25: /* no blink */
215                                 attr &= ~BACKGROUND_INTENSITY;
216                                 break;
217                         case 7:  /* negative */
218                                 negative = 1;
219                                 break;
220                         case 27: /* positive */
221                                 negative = 0;
222                                 break;
223                         case 8:  /* conceal */
224                         case 28: /* reveal */
225                                 /* Unsupported */
226                                 break;
227                         case 30: /* Black */
228                                 attr &= ~FOREGROUND_ALL;
229                                 break;
230                         case 31: /* Red */
231                                 attr &= ~FOREGROUND_ALL;
232                                 attr |= FOREGROUND_RED;
233                                 break;
234                         case 32: /* Green */
235                                 attr &= ~FOREGROUND_ALL;
236                                 attr |= FOREGROUND_GREEN;
237                                 break;
238                         case 33: /* Yellow */
239                                 attr &= ~FOREGROUND_ALL;
240                                 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
241                                 break;
242                         case 34: /* Blue */
243                                 attr &= ~FOREGROUND_ALL;
244                                 attr |= FOREGROUND_BLUE;
245                                 break;
246                         case 35: /* Magenta */
247                                 attr &= ~FOREGROUND_ALL;
248                                 attr |= FOREGROUND_RED | FOREGROUND_BLUE;
249                                 break;
250                         case 36: /* Cyan */
251                                 attr &= ~FOREGROUND_ALL;
252                                 attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
253                                 break;
254                         case 37: /* White */
255                                 attr |= FOREGROUND_RED |
256                                         FOREGROUND_GREEN |
257                                         FOREGROUND_BLUE;
258                                 break;
259                         case 38: /* Unknown */
260                                 break;
261                         case 39: /* reset */
262                                 attr &= ~FOREGROUND_ALL;
263                                 attr |= (plain_attr & FOREGROUND_ALL);
264                                 break;
265                         case 40: /* Black */
266                                 attr &= ~BACKGROUND_ALL;
267                                 break;
268                         case 41: /* Red */
269                                 attr &= ~BACKGROUND_ALL;
270                                 attr |= BACKGROUND_RED;
271                                 break;
272                         case 42: /* Green */
273                                 attr &= ~BACKGROUND_ALL;
274                                 attr |= BACKGROUND_GREEN;
275                                 break;
276                         case 43: /* Yellow */
277                                 attr &= ~BACKGROUND_ALL;
278                                 attr |= BACKGROUND_RED | BACKGROUND_GREEN;
279                                 break;
280                         case 44: /* Blue */
281                                 attr &= ~BACKGROUND_ALL;
282                                 attr |= BACKGROUND_BLUE;
283                                 break;
284                         case 45: /* Magenta */
285                                 attr &= ~BACKGROUND_ALL;
286                                 attr |= BACKGROUND_RED | BACKGROUND_BLUE;
287                                 break;
288                         case 46: /* Cyan */
289                                 attr &= ~BACKGROUND_ALL;
290                                 attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
291                                 break;
292                         case 47: /* White */
293                                 attr |= BACKGROUND_RED |
294                                         BACKGROUND_GREEN |
295                                         BACKGROUND_BLUE;
296                                 break;
297                         case 48: /* Unknown */
298                                 break;
299                         case 49: /* reset */
300                                 attr &= ~BACKGROUND_ALL;
301                                 attr |= (plain_attr & BACKGROUND_ALL);
302                                 break;
303                         default:
304                                 /* Unsupported code */
305                                 break;
306                         }
307                 }
308                 set_console_attr();
309                 break;
310         case 'K':
311                 erase_in_line();
312                 break;
313         default:
314                 /* Unsupported code */
315                 break;
316         }
317 }
318
319 enum {
320         TEXT = 0, ESCAPE = 033, BRACKET = '['
321 };
322
323 static DWORD WINAPI console_thread(LPVOID unused)
324 {
325         unsigned char buffer[BUFFER_SIZE];
326         DWORD bytes;
327         int start, end = 0, c, parampos = 0, state = TEXT;
328         int params[MAX_PARAMS];
329
330         while (1) {
331                 /* read next chunk of bytes from the pipe */
332                 if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
333                                 NULL)) {
334                         /* exit if pipe has been closed or disconnected */
335                         if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
336                                         GetLastError() == ERROR_BROKEN_PIPE)
337                                 break;
338                         /* ignore other errors */
339                         continue;
340                 }
341
342                 /* scan the bytes and handle ANSI control codes */
343                 bytes += end;
344                 start = end = 0;
345                 while (end < bytes) {
346                         c = buffer[end++];
347                         switch (state) {
348                         case TEXT:
349                                 if (c == ESCAPE) {
350                                         /* print text seen so far */
351                                         if (end - 1 > start)
352                                                 write_console(buffer + start,
353                                                         end - 1 - start);
354
355                                         /* then start parsing escape sequence */
356                                         start = end - 1;
357                                         memset(params, 0, sizeof(params));
358                                         parampos = 0;
359                                         state = ESCAPE;
360                                 }
361                                 break;
362
363                         case ESCAPE:
364                                 /* continue if "\033[", otherwise bail out */
365                                 state = (c == BRACKET) ? BRACKET : TEXT;
366                                 break;
367
368                         case BRACKET:
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 == ';') {
374                                         /*
375                                          * next parameter, bail out if out of
376                                          * bounds
377                                          */
378                                         parampos++;
379                                         if (parampos >= MAX_PARAMS)
380                                                 state = TEXT;
381                                 } else {
382                                         /*
383                                          * end of escape sequence, change
384                                          * console attributes
385                                          */
386                                         set_attr(c, params, parampos + 1);
387                                         start = end;
388                                         state = TEXT;
389                                 }
390                                 break;
391                         }
392                 }
393
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)
399                                         end--;
400                                 else if (end - 1 > start &&
401                                                 buffer[end - 2] >= 0xe0)
402                                         end -= 2;
403                                 else if (end - 2 > start &&
404                                                 buffer[end - 3] >= 0xf0)
405                                         end -= 3;
406                         }
407
408                         /* print remaining complete UTF-8 sequences */
409                         if (end > start)
410                                 write_console(buffer + start, end - start);
411
412                         /* move remaining bytes to the front */
413                         if (end < bytes)
414                                 memmove(buffer, buffer + end, bytes - end);
415                         end = bytes - end;
416                 } else {
417                         /* all data has been consumed, mark buffer empty */
418                         end = 0;
419                 }
420         }
421
422         /* check if the console font supports unicode */
423         warn_if_raster_font();
424
425         CloseHandle(hread);
426         return 0;
427 }
428
429 static void winansi_exit(void)
430 {
431         /* flush all streams */
432         _flushall();
433
434         /* signal console thread to exit */
435         FlushFileBuffers(hwrite);
436         DisconnectNamedPipe(hwrite);
437
438         /* wait for console thread to copy remaining data */
439         WaitForSingleObject(hthread, INFINITE);
440
441         /* cleanup handles... */
442         CloseHandle(hwrite);
443         CloseHandle(hthread);
444 }
445
446 static void die_lasterr(const char *fmt, ...)
447 {
448         va_list params;
449         va_start(params, fmt);
450         errno = err_win_to_posix(GetLastError());
451         die_errno(fmt, params);
452         va_end(params);
453 }
454
455 static HANDLE duplicate_handle(HANDLE hnd)
456 {
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);
462         return hresult;
463 }
464
465
466 /*
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).
470  *
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
475  * isatty(1).
476  */
477 typedef struct {
478         HANDLE osfhnd;
479         char osflags;
480 } ioinfo;
481
482 extern __declspec(dllimport) ioinfo *__pioinfo[];
483
484 static size_t sizeof_ioinfo = 0;
485
486 #define IOINFO_L2E 5
487 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
488
489 #define FPIPE 0x08
490 #define FDEV  0x40
491
492 static inline ioinfo* _pioinfo(int fd)
493 {
494         return (ioinfo*)((char*)__pioinfo[fd >> IOINFO_L2E] +
495                         (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
496 }
497
498 static int init_sizeof_ioinfo(void)
499 {
500         int istty, wastty;
501         /* don't init twice */
502         if (sizeof_ioinfo)
503                 return sizeof_ioinfo >= 256;
504
505         sizeof_ioinfo = sizeof(ioinfo);
506         wastty = isatty(1);
507         while (sizeof_ioinfo < 256) {
508                 /* toggle FDEV flag, check isatty, then toggle back */
509                 _pioinfo(1)->osflags ^= FDEV;
510                 istty = isatty(1);
511                 _pioinfo(1)->osflags ^= FDEV;
512                 /* return if we found the correct size */
513                 if (istty != wastty)
514                         return 0;
515                 sizeof_ioinfo += sizeof(void*);
516         }
517         error("Tweaking file descriptors doesn't work with this MSVCRT.dll");
518         return 1;
519 }
520
521 static HANDLE swap_osfhnd(int fd, HANDLE new_handle)
522 {
523         ioinfo *pioinfo;
524         HANDLE old_handle;
525
526         /* init ioinfo size if we haven't done so */
527         if (init_sizeof_ioinfo())
528                 return INVALID_HANDLE_VALUE;
529
530         /* get ioinfo pointer and change the handles */
531         pioinfo = _pioinfo(fd);
532         old_handle = pioinfo->osfhnd;
533         pioinfo->osfhnd = new_handle;
534         return old_handle;
535 }
536
537 #ifdef DETECT_MSYS_TTY
538
539 #include <winternl.h>
540 #include <ntstatus.h>
541
542 static void detect_msys_tty(int fd)
543 {
544         ULONG result;
545         BYTE buffer[1024];
546         POBJECT_NAME_INFORMATION nameinfo = (POBJECT_NAME_INFORMATION) buffer;
547         PWSTR name;
548
549         /* check if fd is a pipe */
550         HANDLE h = (HANDLE) _get_osfhandle(fd);
551         if (GetFileType(h) != FILE_TYPE_PIPE)
552                 return;
553
554         /* get pipe name */
555         if (!NT_SUCCESS(NtQueryObject(h, ObjectNameInformation,
556                         buffer, sizeof(buffer) - 2, &result)))
557                 return;
558         name = nameinfo->Name.Buffer;
559         name[nameinfo->Name.Length] = 0;
560
561         /* check if this could be a MSYS2 pty pipe ('msys-XXXX-ptyN-XX') */
562         if (!wcsstr(name, L"msys-") || !wcsstr(name, L"-pty"))
563                 return;
564
565         /* init ioinfo size if we haven't done so */
566         if (init_sizeof_ioinfo())
567                 return;
568
569         /* set FDEV flag, reset FPIPE flag */
570         _pioinfo(fd)->osflags &= ~FPIPE;
571         _pioinfo(fd)->osflags |= FDEV;
572 }
573
574 #endif
575
576 int winansi_isatty(int fd)
577 {
578         int res = isatty(fd);
579
580         if (res) {
581                 /*
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
586                  *
587                  * https://msdn.microsoft.com/en-us/library/f4s0ddew.aspx
588                  */
589                 HANDLE handle = (HANDLE)_get_osfhandle(fd);
590                 if (fd == STDIN_FILENO) {
591                         DWORD dummy;
592
593                         if (!GetConsoleMode(handle, &dummy))
594                                 res = 0;
595                 } else if (fd == STDOUT_FILENO || fd == STDERR_FILENO) {
596                         CONSOLE_SCREEN_BUFFER_INFO dummy;
597
598                         if (!GetConsoleScreenBufferInfo(handle, &dummy))
599                                 res = 0;
600                 }
601         }
602
603         return res;
604 }
605
606 void winansi_init(void)
607 {
608         int con1, con2;
609         char name[32];
610
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 */
617                 detect_msys_tty(0);
618                 detect_msys_tty(1);
619                 detect_msys_tty(2);
620 #endif
621                 return;
622         }
623
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");
630
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");
634
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");
639
640         /* schedule cleanup routine */
641         if (atexit(winansi_exit))
642                 die_errno("atexit(winansi_exit) failed");
643
644         /* redirect stdout / stderr to the pipe */
645         if (con1)
646                 hconsole1 = swap_osfhnd(1, duplicate_handle(hwrite));
647         if (con2)
648                 hconsole2 = swap_osfhnd(2, duplicate_handle(hwrite));
649 }
650
651 /*
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.
654  */
655 HANDLE winansi_get_osfhandle(int fd)
656 {
657         HANDLE hnd = (HANDLE) _get_osfhandle(fd);
658         if (isatty(fd) && GetFileType(hnd) == FILE_TYPE_PIPE) {
659                 if (fd == 1 && hconsole1)
660                         return hconsole1;
661                 else if (fd == 2 && hconsole2)
662                         return hconsole2;
663         }
664         return hnd;
665 }