Win32: unify environment case-sensitivity
[git/dscho.git] / compat / winansi.c
blob9f95954390741b74557ffedaf2006ab37ee2a3de
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 Functions to be wrapped:
13 #undef isatty
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;
24 static WORD attr;
25 static int negative;
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;
31 #ifdef __MINGW32__
32 typedef struct _CONSOLE_FONT_INFOEX {
33 ULONG cbSize;
34 DWORD nFont;
35 COORD dwFontSize;
36 UINT FontFamily;
37 UINT FontWeight;
38 WCHAR FaceName[LF_FACESIZE];
39 } CONSOLE_FONT_INFOEX, *PCONSOLE_FONT_INFOEX;
40 #endif
42 typedef BOOL (WINAPI *PGETCURRENTCONSOLEFONTEX)(HANDLE, BOOL,
43 PCONSOLE_FONT_INFOEX);
45 static void warn_if_raster_font(void)
47 DWORD fontFamily = 0;
48 PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx;
50 /* don't bother if output was ascii only */
51 if (!non_ascii_used)
52 return;
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;
63 } else {
64 /* pre-Vista: check default console font in registry */
65 HKEY hkey;
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);
71 RegCloseKey(hkey);
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;
87 HANDLE hcon;
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)
94 return 0;
96 /* check if its a device (i.e. console, printer, serial port) */
97 if (GetFileType(hcon) != FILE_TYPE_CHAR)
98 return 0;
100 /* check if its a handle to a console output screen buffer */
101 if (!GetConsoleScreenBufferInfo(hcon, &sbi))
102 return 0;
104 /* initialize attributes */
105 if (!initialized) {
106 attr = plain_attr = sbi.wAttributes;
107 negative = 0;
108 initialized = 1;
111 return 1;
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 */
129 if (wlen != len)
130 non_ascii_used = 1;
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;
139 if (negative) {
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 */
167 if (!console)
168 return;
170 GetConsoleScreenBufferInfo(console, &sbi);
171 FillConsoleOutputCharacterA(console, ' ',
172 sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
173 &dummy);
176 static void set_attr(char func, const int *params, int paramlen)
178 int i;
179 switch (func) {
180 case 'm':
181 for (i = 0; i < paramlen; i++) {
182 switch (params[i]) {
183 case 0: /* reset */
184 attr = plain_attr;
185 negative = 0;
186 break;
187 case 1: /* bold */
188 attr |= FOREGROUND_INTENSITY;
189 break;
190 case 2: /* faint */
191 case 22: /* normal */
192 attr &= ~FOREGROUND_INTENSITY;
193 break;
194 case 3: /* italic */
195 /* Unsupported */
196 break;
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; */
202 break;
203 case 24: /* no underline */
204 /* attr &= ~COMMON_LVB_UNDERSCORE; */
205 break;
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;
211 break;
212 case 25: /* no blink */
213 attr &= ~BACKGROUND_INTENSITY;
214 break;
215 case 7: /* negative */
216 negative = 1;
217 break;
218 case 27: /* positive */
219 negative = 0;
220 break;
221 case 8: /* conceal */
222 case 28: /* reveal */
223 /* Unsupported */
224 break;
225 case 30: /* Black */
226 attr &= ~FOREGROUND_ALL;
227 break;
228 case 31: /* Red */
229 attr &= ~FOREGROUND_ALL;
230 attr |= FOREGROUND_RED;
231 break;
232 case 32: /* Green */
233 attr &= ~FOREGROUND_ALL;
234 attr |= FOREGROUND_GREEN;
235 break;
236 case 33: /* Yellow */
237 attr &= ~FOREGROUND_ALL;
238 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
239 break;
240 case 34: /* Blue */
241 attr &= ~FOREGROUND_ALL;
242 attr |= FOREGROUND_BLUE;
243 break;
244 case 35: /* Magenta */
245 attr &= ~FOREGROUND_ALL;
246 attr |= FOREGROUND_RED | FOREGROUND_BLUE;
247 break;
248 case 36: /* Cyan */
249 attr &= ~FOREGROUND_ALL;
250 attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
251 break;
252 case 37: /* White */
253 attr |= FOREGROUND_RED |
254 FOREGROUND_GREEN |
255 FOREGROUND_BLUE;
256 break;
257 case 38: /* Unknown */
258 break;
259 case 39: /* reset */
260 attr &= ~FOREGROUND_ALL;
261 attr |= (plain_attr & FOREGROUND_ALL);
262 break;
263 case 40: /* Black */
264 attr &= ~BACKGROUND_ALL;
265 break;
266 case 41: /* Red */
267 attr &= ~BACKGROUND_ALL;
268 attr |= BACKGROUND_RED;
269 break;
270 case 42: /* Green */
271 attr &= ~BACKGROUND_ALL;
272 attr |= BACKGROUND_GREEN;
273 break;
274 case 43: /* Yellow */
275 attr &= ~BACKGROUND_ALL;
276 attr |= BACKGROUND_RED | BACKGROUND_GREEN;
277 break;
278 case 44: /* Blue */
279 attr &= ~BACKGROUND_ALL;
280 attr |= BACKGROUND_BLUE;
281 break;
282 case 45: /* Magenta */
283 attr &= ~BACKGROUND_ALL;
284 attr |= BACKGROUND_RED | BACKGROUND_BLUE;
285 break;
286 case 46: /* Cyan */
287 attr &= ~BACKGROUND_ALL;
288 attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
289 break;
290 case 47: /* White */
291 attr |= BACKGROUND_RED |
292 BACKGROUND_GREEN |
293 BACKGROUND_BLUE;
294 break;
295 case 48: /* Unknown */
296 break;
297 case 49: /* reset */
298 attr &= ~BACKGROUND_ALL;
299 attr |= (plain_attr & BACKGROUND_ALL);
300 break;
301 default:
302 /* Unsupported code */
303 break;
306 set_console_attr();
307 break;
308 case 'K':
309 erase_in_line();
310 break;
311 default:
312 /* Unsupported code */
313 break;
317 enum {
318 TEXT = 0, ESCAPE = 033, BRACKET = '['
321 static DWORD WINAPI console_thread(LPVOID unused)
323 unsigned char buffer[BUFFER_SIZE];
324 DWORD bytes;
325 int start, end = 0, c, parampos = 0, state = TEXT;
326 int params[MAX_PARAMS];
328 while (1) {
329 /* read next chunk of bytes from the pipe */
330 if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
331 NULL)) {
332 /* exit if pipe has been closed or disconnected */
333 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
334 GetLastError() == ERROR_BROKEN_PIPE)
335 break;
336 /* ignore other errors */
337 continue;
340 /* scan the bytes and handle ANSI control codes */
341 bytes += end;
342 start = end = 0;
343 while (end < bytes) {
344 c = buffer[end++];
345 switch (state) {
346 case TEXT:
347 if (c == ESCAPE) {
348 /* print text seen so far */
349 if (end - 1 > start)
350 write_console(buffer + start,
351 end - 1 - start);
353 /* then start parsing escape sequence */
354 start = end - 1;
355 memset(params, 0, sizeof(params));
356 parampos = 0;
357 state = ESCAPE;
359 break;
361 case ESCAPE:
362 /* continue if "\033[", otherwise bail out */
363 state = (c == BRACKET) ? BRACKET : TEXT;
364 break;
366 case BRACKET:
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
374 * bounds
376 parampos++;
377 if (parampos >= MAX_PARAMS)
378 state = TEXT;
379 } else {
381 * end of escape sequence, change
382 * console attributes
384 set_attr(c, params, parampos + 1);
385 start = end;
386 state = TEXT;
388 break;
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)
397 end--;
398 else if (end - 1 > start &&
399 buffer[end - 2] >= 0xe0)
400 end -= 2;
401 else if (end - 2 > start &&
402 buffer[end - 3] >= 0xf0)
403 end -= 3;
406 /* print remaining complete UTF-8 sequences */
407 if (end > start)
408 write_console(buffer + start, end - start);
410 /* move remaining bytes to the front */
411 if (end < bytes)
412 memmove(buffer, buffer + end, bytes - end);
413 end = bytes - end;
414 } else {
415 /* all data has been consumed, mark buffer empty */
416 end = 0;
420 /* check if the console font supports unicode */
421 warn_if_raster_font();
423 CloseHandle(hread);
424 return 0;
427 static void winansi_exit(void)
429 /* flush all streams */
430 _flushall();
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);
444 CloseHandle(hwrite);
445 CloseHandle(hthread);
448 static void die_lasterr(const char *fmt, ...)
450 va_list params;
451 va_start(params, fmt);
452 errno = err_win_to_posix(GetLastError());
453 die_errno(fmt, params);
454 va_end(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);
463 return hresult;
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;
489 char name[32];
491 /* check if either stdout or stderr is a console output screen buffer */
492 con1 = is_console(1);
493 con2 = is_console(2);
494 if (!con1 && !con2)
495 return;
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);
519 if (hwrite_fd == -1)
520 die_errno("_open_osfhandle(%li) failed", (long) hwrite);
522 /* redirect stdout / stderr to the pipe */
523 if (con1)
524 hwrite1 = redirect_console(stdout, &hconsole1, hwrite_fd);
525 if (con2)
526 hwrite2 = redirect_console(stderr, &hconsole2, hwrite_fd);
528 /* close pipe file descriptor (also closes the duped hwrite) */
529 close(hwrite_fd);
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))
543 return 1;
544 else if (fd == 2 && is_same_handle(hwrite2, 2))
545 return 1;
546 else
547 return isatty(fd);
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))
557 return hconsole1;
558 else if (fd == 2 && is_same_handle(hwrite2, 2))
559 return hconsole2;
560 else
561 return (HANDLE) _get_osfhandle(fd);